coze-bridge 0.2.0 → 0.2.1-alpha.10

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 +100 -100
  2. package/package.json +2 -2
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 mg=Object.create;var va=Object.defineProperty;var wg=Object.getOwnPropertyDescriptor;var _g=Object.getOwnPropertyNames;var yg=Object.getPrototypeOf,Eg=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 Qe=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Sa=(t,e)=>{for(var r in e)va(t,r,{get:e[r],enumerable:!0})},bg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _g(e))!Eg.call(t,o)&&o!==r&&va(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)):{},bg(e||!t||!t.__esModule?va(r,"default",{value:t,enumerable:!0}):r,t));function $e(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 ml}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 Ia(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[l,u,f]=c.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>r}function cs(t,e,r,i){let o;try{o=Ig(t)}catch{return}for(let c of o){let l=Ia(c,e);if(l&&kg(l,r,i))try{Ag(ml(t,c))}catch{}}}var Qr,Aa=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(ml(this.dir,sr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
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&&cs(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 Cg}from"node:fs";import{join as Rg}from"node:path";function _l(t){let e=t.retentionDays??Og,r=t.clock??(()=>Pn(new Date));ls={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();cs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])cs(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 yl(t){ka=t}function El(t){return or[ka]<=or[t]}function bl(t,e){let r=or[t];return r===void 0?!0:r>=or[e]}function us(t){wl={...t}}function vl(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)),l=e(o%60);return`${Pn(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:vl(new Date),level:e,module:r,msg:i,...o})}
11
- `;Cg(t,{recursive:!0}),Tg(Rg(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 ds(t,e,r,i,o){if(or[t]<or[ka])return;let c=`${JSON.stringify({ts:vl(new Date),level:t,module:e,msg:r,...wl,...i})}
12
- `;if(ls){let l=Ng(o,i),u=l?Lg(ls,l):ls.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Dg.write(c):Pg.write(c)}function H(t,e){return{debug:(r,i)=>ds("debug",t,r,i,e),info:(r,i)=>ds("info",t,r,i,e),warn:(r,i)=>ds("warn",t,r,i,e),error:(r,i)=>ds("error",t,r,i,e),child:r=>H(`${t}.${r}`,e),forAgent:r=>H(t,r)}}var or,ka,Pg,Dg,wl,Og,ls,ne=Qe(()=>{"use strict";ir();Aa();or={debug:10,info:20,warn:30,error:40},ka=(()=>{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,wl={},Og=$e("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ls=null});var k,je=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 kl={};Sa(kl,{ACP_WRAPPER_NPM_PACKAGES:()=>ti,_resetAcpInstallerForTests:()=>Gg,_setBinaryPathCacheForTests:()=>Hg,buildAcpSpawn:()=>ni,ensureAcpInstalled:()=>ar,getAcpBinaryPath:()=>fs,pickWhichLine:()=>Ra,probeAcpVersion:()=>Ug,resolveAcpCommand:()=>Al});import{readFileSync as Sl}from"node:fs";import{createRequire as Mg}from"node:module";import{dirname as Bg,resolve as Fg}from"node:path";function Ra(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=Il.resolve(`${t.npmPackage}/package.json`),r=Bg(e),i=JSON.parse(Sl(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=Ca[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),Ta.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Ta.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=Ca[t];if(e)try{let r=Il.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Sl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Ta.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function fs(t){return ei.get(t)}function Al(t,e){if(e)return e;let r=fs(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=Al(t);return{command:process.execPath,args:[i,...r]}}function Gg(){ei.clear()}function Hg(t,e){ei.set(t,e)}var Ta,Ca,ti,Il,ei,sn=Qe(()=>{"use strict";je();ne();Ta=H("agents.acp-installer"),Ca={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ti=Object.values(Ca).filter(t=>t!==void 0).map(t=>t.npmPackage),Il=Mg(import.meta.url),ei=new Map});import{chmod as jg,mkdir as Wg,readFile as Kg,rename as $g,rm as Vg,writeFile as Zg}from"node:fs/promises";import{dirname as Yg}from"node:path";async function cr(t){try{let e=await Kg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function on(t,e,r){await Wg(Yg(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 $g(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 Jg}from"node:fs";import{homedir as Xg}from"node:os";import{sep as Qg,join as Ae,resolve as Pl}from"node:path";function ee(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=ee()){let r=Ae(e.agentsRoot,t);return{root:r,config:Ae(r,"config.json"),workspace:Ae(r,"workspace"),logs:Ae(r,"logs")}}function hs(t=ee()){try{return Jg(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ri(t,e){let r=await Rl.realpath(Pl(t)).catch(()=>null);if(!r)return!1;let i=await Rl.realpath(Pl(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 Oe=Qe(()=>{"use strict"});var ps={};Sa(ps,{AGENT_CONFIG_FILE_MODE:()=>xs,enforceAgentConfigMode:()=>nm,loadAgentConfig:()=>ke,persistAgentSessions:()=>ii,persistAgentSkills:()=>si,saveAgentConfig:()=>Be});import{chmod as em,stat as tm}from"node:fs/promises";function ke(t,e){return cr(Ve(t,e).config)}function Be(t,e){return dr(Ve(t.agentId,e).config,t,{mode:xs})}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!==xs&&(await em(r,xs),Dl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Dl.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 Be(i,r))}async function si(t,e,r){let i=await ke(t,r);i&&(i.skills=e,await Be(i,r))}var Dl,xs,cn=Qe(()=>{"use strict";an();ne();Oe();Dl=H("agent-config"),xs=384});var Oa=ae((KI,Nl)=>{Nl.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 ms=ae(Bl=>{var Ml={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(Ml))Bl[t]=cm(Ml[t])});var Hl=ae((VI,Gl)=>{var dm=ue("fs"),Le=ue("path"),Fl=Oa(),lm=ms(),um=typeof process=="object"&&process.platform==="win32",zl=t=>typeof t=="object"&&t!==null,Ul=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=Le.sep,this.fs=dm,zl(t)&&zl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Gl.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 lm.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=Le.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,f){if(l&&f.isDirectory())return o(!1);var x=Le.dirname(t);c.fs.exists(x,function(g){g||c.makeDir(x),c.fs.open(t,"w",438,function(m,S){m?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,b){c.fs.write(b,e,0,e.length,0,function(){c.fs.close(b,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,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 f=Le.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&l.push(Le.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(l=l.concat(r(f,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=Le.join(t,u),r.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Le.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(g,m){if(g)return e(g);i=i.concat(m),--l||e(null,i)}):--l||e(null,i))})})})};be.prototype.getAttributes=function(){};be.prototype.setAttributes=function(){};be.crc32update=function(t,e){return Ul[(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 Fl.STORED:return"STORED ("+t+")";case Fl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};be.canonical=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.join(".",e)};be.zipnamefix=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.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=Le.resolve(Le.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Le.normalize(Le.join(t,r.slice(i,o).join(Le.sep)));if(c.indexOf(t)===0)return c}return Le.normalize(Le.join(t,Le.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=um;be.crcTable=Ul});var jl=ae((ZI,ql)=>{var fm=ue("path");ql.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 Kl=ae((YI,Wl)=>{Wl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var fr=ae((JI,ur)=>{ur.exports=Hl();ur.exports.Constants=Oa();ur.exports.Errors=ms();ur.exports.FileAttr=jl();ur.exports.decoder=Kl()});var Vl=ae((XI,$l)=>{var dn=fr(),z=dn.Constants;$l.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,l=0,u=0,f=0,x=0,g=0,m=0,S=0,_=0,b=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,P=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 P(o>>>8)},get crc(){return c},set crc(y){c=A(y)},get compressedSize(){return l},set compressedSize(y){l=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 g},set commentLength(y){g=y},get diskNumStart(){return m},set diskNumStart(y){m=A(y)},get inAttr(){return S},set inAttr(y){S=A(y)},get attr(){return _},set attr(y){_=A(y)},get fileAttr(){return(_||0)>>16&4095},get offset(){return b},set offset(y){b=A(y)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+f+x+g},get realDataOffset(){return b+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(y){var C=y.slice(b,b+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 D=b+z.LOCHDR+I.fnameLen,B=D+I.extraLen;return y.slice(D,B)},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),l=y.readUInt32LE(z.CENSIZ),u=y.readUInt32LE(z.CENLEN),f=y.readUInt16LE(z.CENNAM),x=y.readUInt16LE(z.CENEXT),g=y.readUInt16LE(z.CENCOM),m=y.readUInt16LE(z.CENDSK),S=y.readUInt16LE(z.CENATT),_=y.readUInt32LE(z.CENATX),b=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(l,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+g);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(l,z.CENSIZ),y.writeUInt32LE(u,z.CENLEN),y.writeUInt16LE(f,z.CENNAM),y.writeUInt16LE(x,z.CENEXT),y.writeUInt16LE(g,z.CENCOM),y.writeUInt16LE(m,z.CENDSK),y.writeUInt16LE(S,z.CENATT),y.writeUInt32LE(_,z.CENATX),y.writeUInt32LE(b,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(l),size:y(u),fileNameLength:y(f),extraLength:y(x),commentLength:y(g),diskNumStart:m,inAttr:S,attr:_,offset:b,centralHeaderSize:y(z.CENHDR+f+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Yl=ae((QI,Zl)=>{var hr=fr(),_e=hr.Constants;Zl.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(l,u){let f=l.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 Na=ae(La=>{La.EntryHeader=Vl();La.MainHeader=Yl()});var Xl=ae((t2,Jl)=>{Jl.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),f=0;u.fill(0);for(var x=0;x<c.length;x++){var g=c[x];g.copy(u,f),f+=g.length}i&&i(u)}),o.end(t)}}}});var eu=ae((n2,Ql)=>{var hm=+(process.versions?process.versions.node:"").split(".")[0]||0;Ql.exports=function(t,e){var r=ue("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),l=[],u=0;c.on("data",function(f){l.push(f),u+=f.length}),c.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var g=0;g<l.length;g++){var m=l[g];m.copy(f,x),x+=m.length}o&&o(f)}),c.end(t)}}}});var su=ae((r2,iu)=>{"use strict";var{randomFillSync:tu}=ue("crypto"),xm=ms(),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}),ru=(t,e)=>Math.imul(t,e)>>>0,nu=(t,e)=>pm[(t^e)&255]^t>>>8,oi=()=>typeof tu=="function"?tu(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 ws={genSalt:oi};function _s(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])}_s.prototype.updateKeys=function(t){let e=this.keys;return e[0]=nu(e[0],t),e[1]+=e[0]&255,e[1]=ru(e[1],134775813)+1,e[2]=nu(e[2],e[1]>>>24),t};_s.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return ru(t,t^1)>>8&255};function gm(t){let e=new _s(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 _s(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 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?ws.genSalt=function(){return t.slice(0,12)}:t==="node"?ws.genSalt=oi.node:ws.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=ws.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)}iu.exports={decrypt:wm,encrypt:ym,_salter:_m}});var ou=ae(ys=>{ys.Deflater=Xl();ys.Inflater=eu();ys.ZipCrypto=su()});var Ba=ae((s2,au)=>{var ce=fr(),Em=Na(),ve=ce.Constants,Ma=ou();au.exports=function(t,e){var r=new Em.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,l=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let g=t,m=typeof g.decoder=="object"?g.decoder:ce.decoder;x=m.hasOwnProperty("efs")?m.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function _(y){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(y)!==r.localHeader.crc)return!1}else{let C={},D=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(D)==ve.LOCSIG||e.readUInt32LE(D)==ve.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==ve.EXTSIG)C.crc=e.readUInt32LE(D+ve.EXTCRC),C.compressedSize=e.readUInt32LE(D+ve.EXTSIZ),C.size=e.readUInt32LE(D+ve.EXTLEN);else if(e.readUInt16LE(D+12)===19280)C.crc=e.readUInt32LE(D+ve.EXTCRC-4),C.compressedSize=e.readUInt32LE(D+ve.EXTSIZ-4),C.size=e.readUInt32LE(D+ve.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(C.compressedSize!==r.compressedSize||C.size!==r.size||C.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(y)!==C.crc)return!1}return!0}function b(y,C,D){if(typeof C>"u"&&typeof y=="string"&&(D=y,y=void 0),c)return y&&C&&C(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var B=S();if(B.length===0)return y&&C&&C(B),B;if(r.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw ce.Errors.INVALID_PASS_PARAM();B=Ma.ZipCrypto.decrypt(B,r,D)}var M=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(B.copy(M),_(M))return y&&C&&C(M),M;throw y&&C&&C(M,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var Y=new Ma.Inflater(B,r.size);if(y)Y.inflateAsync(function(V){V.copy(V,0),C&&(_(V)?C(V):C(V,ce.Errors.BAD_CRC()))});else{if(Y.inflate(M).copy(M,0),!_(M))throw ce.Errors.BAD_CRC(`"${m.decode(i)}"`);return M}break;default:throw y&&C&&C(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(y,C){if((!l||!l.length)&&Buffer.isBuffer(e))return y&&C&&C(S()),S();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),y&&C&&C(D),D;default:case ce.Constants.DEFLATED:var B=new Ma.Deflater(l);if(y)B.deflateAsync(function(Y){D=Buffer.alloc(Y.length),r.compressedSize=Y.length,Y.copy(D),C&&C(D)});else{var M=B.deflate();return r.compressedSize=M.length,M}B=null;break}}else if(y&&C)C(Buffer.alloc(0));else return Buffer.alloc(0)}function A(y,C){return ce.readBigUInt64LE(y,C)}function T(y){try{for(var C=0,D,B,M;C+4<y.length;)D=y.readUInt16LE(C),C+=2,B=y.readUInt16LE(C),C+=2,M=y.slice(C,C+B),C+=B,ve.ID_ZIP64===D&&P(M)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(y){var C,D,B,M;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&&(D=A(y,ve.EF_ZIP64_SCOMP),r.compressedSize===ve.EF_ZIP64_OR_32&&(r.compressedSize=D)),y.length>=ve.EF_ZIP64_DSN&&(B=A(y,ve.EF_ZIP64_RHO),r.offset===ve.EF_ZIP64_OR_32&&(r.offset=B)),y.length>=ve.EF_ZIP64_DSN+4&&(M=y.readUInt32LE(ve.EF_ZIP64_DSN),r.diskNumStart===ve.EF_ZIP64_OR_16&&(r.diskNumStart=M))}return{get entryName(){return m.decode(i)},get rawEntryName(){return i},set entryName(y){i=ce.toBuffer(y,m.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 m.decode(o)},set comment(y){if(o=ce.toBuffer(y,m.encode),r.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var y=m.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){l=ce.toBuffer(y,ce.decoder.encode),!c&&l.length?(r.size=l.length,r.method=ce.Constants.DEFLATED,r.crc=ce.crc32(y),r.changed=!0):r.method=ce.Constants.STORED},getData:function(y){return r.changed?l:b(!1,null,y)},getDataAsync:function(y,C){r.changed?y(l):b(!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=ce.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(),D=Buffer.alloc(C.length+i.length+r.extraLocalLength);return C.copy(D,y),y+=C.length,i.copy(D,y),y+=i.length,f.copy(D,y),y+=f.length,D},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(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var lu=ae((o2,du)=>{var cu=Ba(),bm=Na(),We=fr();du.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new bm.MainHeader,l=!1,u=null;let f=new Set,x=e,{noSort:g,decoder:m}=x;t?b(x.readEntries):l=!0;function S(){let A=new Set;for(let T of Object.keys(i)){let P=T.split("/");if(P.pop(),!!P.length)for(let y=0;y<P.length;y++){let C=P.slice(0,y+1).join("/")+"/";A.add(C)}}for(let T of A)if(!(T in i)){let P=new cu(x);P.entryName=T,P.attr=16,P.temporary=!0,r.push(P),i[P.entryName]=P,f.add(P)}}function _(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/We.Constants.CENHDR)throw We.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,T=0;T<r.length;T++){var P=A,y=new cu(x,t);y.header=t.slice(P,P+=We.Constants.CENHDR),y.entryName=t.slice(P,P+=y.header.fileNameLength),y.header.extraLength&&(y.extra=t.slice(P,P+=y.header.extraLength)),y.header.commentLength&&(y.comment=t.slice(P,P+y.header.commentLength)),A+=y.header.centralHeaderSize,r[T]=y,i[y.entryName]=y}f.clear(),S()}function b(A){var T=t.length-We.Constants.ENDHDR,P=Math.max(0,T-65535),y=P,C=t.length,D=-1,B=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),T;T>=y;T--)if(t[T]===80){if(t.readUInt32LE(T)===We.Constants.ENDSIG){D=T,B=T,C=T+We.Constants.ENDHDR,y=T-We.Constants.END64HDR;continue}if(t.readUInt32LE(T)===We.Constants.END64SIG){y=P;continue}if(t.readUInt32LE(T)===We.Constants.ZIP64SIG){D=T,C=T+We.readBigUInt64LE(t,T+We.Constants.ZIP64SIZE)+We.Constants.ZIP64LEAD;break}}if(D==-1)throw We.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(D,C)),c.commentLength&&(o=t.slice(B+We.Constants.ENDHDR)),A&&_()}function I(){r.length>1&&!g&&r.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return l||_(),r.filter(A=>!f.has(A))},get comment(){return m.decode(o)},set comment(A){o=We.toBuffer(A,m.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||_(),i[A]||null},setEntry:function(A){l||_(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,T=!0){l||_();let P=i[A];this.getEntryChildren(P,T).map(C=>C.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||_();let T=i[A],P=r.indexOf(T);P>=0&&(r.splice(P,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,T=!0){if(l||_(),typeof A=="object")if(A.isDirectory&&T){let P=[],y=A.entryName;for(let C of r)C.entryName.startsWith(y)&&P.push(C);return P}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(){l||_(),I();let A=[],T=[],P=0,y=0;c.size=0,c.offset=0;let C=0;for(let M of this.entries){let Y=M.getCompressedData();M.header.offset=y;let V=M.packLocalHeader(),re=V.length+Y.length;y+=re,A.push(V),A.push(Y);let X=M.packCentralHeader();T.push(X),c.size+=X.length,P+=re+X.length,C++}P+=c.mainHeaderSize,c.offset=y,c.totalEntries=C,y=0;let D=Buffer.alloc(P);for(let M of A)M.copy(D,y),y+=M.length;for(let M of T)M.copy(D,y),y+=M.length;let B=c.toBinary();return o&&o.copy(B,We.Constants.ENDHDR),B.copy(D,y),t=D,l=!1,D},toAsyncBuffer:function(A,T,P,y){try{l||_(),I();let C=[],D=[],B=0,M=0,Y=0;c.size=0,c.offset=0;let V=function(re){if(re.length>0){let X=re.shift(),se=X.entryName+X.extra.toString();P&&P(se),X.getCompressedDataAsync(function(oe){y&&y(se),X.header.offset=M;let R=X.packLocalHeader(),G=R.length+oe.length;M+=G,C.push(R),C.push(oe);let W=X.packCentralHeader();D.push(W),c.size+=W.length,B+=G+W.length,Y++,V(re)})}else{B+=c.mainHeaderSize,c.offset=M,c.totalEntries=Y,M=0;let X=Buffer.alloc(B);C.forEach(function(oe){oe.copy(X,M),M+=oe.length}),D.forEach(function(oe){oe.copy(X,M),M+=oe.length});let se=c.toBinary();o&&o.copy(se,We.Constants.ENDHDR),se.copy(X,M),t=X,l=!1,A(X)}};V(Array.from(this.entries))}catch(C){T(C)}}}}});var hu=ae((a2,fu)=>{var Ee=fr(),ye=ue("path"),vm=Ba(),Sm=lu(),Dn=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),uu=(...t)=>Ee.findLast(t,e=>typeof e=="string"),Im=(...t)=>Ee.findLast(t,e=>typeof e=="function"),Am={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};fu.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=Ee.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Ee(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ee.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Ee.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw Ee.Errors.INVALID_FILENAME();let c=new Sm(r,i),{canonical:l,sanitize:u,zipnamefix:f}=Ee;function x(_){if(_&&c){var b;if(typeof _=="string"&&(b=c.getEntry(ye.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(b=c.getEntry(_.entryName)),b)return b}return null}function g(_){let{join:b,normalize:I,sep:A}=ye.posix;return b(ye.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function m(_){return _ instanceof RegExp?(function(b){return function(I){return b.test(I)}})(_):typeof _!="function"?()=>!0:_}let S=(_,b)=>{let I=b.slice(-1);return I=I===o.sep?o.sep:"",ye.relative(_,b)+I};return{readFile:function(_,b){var I=x(_);return I&&I.getData(b)||null},childCount:function(_){let b=x(_);if(b)return c.getChildCount(b)},readFileAsync:function(_,b){var I=x(_);I?I.getDataAsync(b):b(null,"getEntry failed for:"+_)},readAsText:function(_,b){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(b||"utf8")}return""},readAsTextAsync:function(_,b,I){var A=x(_);A?A.getDataAsync(function(T,P){if(P){b(T,P);return}T&&T.length?b(T.toString(I||"utf8")):b("")}):b("")},deleteFile:function(_,b=!0){var I=x(_);I&&c.deleteFile(I.entryName,b)},deleteEntry:function(_){var b=x(_);b&&c.deleteEntry(b.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,b){var I=x(_);I&&(I.comment=b)},getZipEntryComment:function(_){var b=x(_);return b&&b.comment||""},updateFile:function(_,b){var I=x(_);I&&I.setData(b)},addLocalFile:function(_,b,I,A){if(o.fs.existsSync(_)){b=b?g(b):"";let T=ye.win32.basename(ye.win32.normalize(_));b+=I||T;let P=o.fs.statSync(_),y=P.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);P.isDirectory()&&(b+=o.sep),this.addFile(b,y,A,P)}else throw Ee.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,b){_=typeof _=="object"?_:{localPath:_};let I=ye.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:P}=_,y=this;o.fs.stat(I,function(C,D){if(C)return b(C,!1);T=T?g(T):"";let B=ye.win32.basename(ye.win32.normalize(I));if(T+=P||B,D.isFile())o.fs.readFile(I,function(M,Y){return M?b(M,!1):(y.addFile(T,Y,A,D),setImmediate(b,void 0,!0))});else if(D.isDirectory())return T+=o.sep,y.addFile(T,Buffer.alloc(0),A,D),setImmediate(b,void 0,!0)})},addLocalFolder:function(_,b,I){if(I=m(I),b=b?g(b):"",_=ye.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),T=this;if(A.length)for(let P of A){let y=ye.join(b,S(_,P));I(y)&&T.addLocalFile(P,ye.dirname(y))}}else throw Ee.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,b,I,A){A=m(A),I=I?g(I):"",_=ye.normalize(_);var T=this;o.fs.open(_,"r",function(P){if(P&&P.code==="ENOENT")b(void 0,Ee.Errors.FILE_NOT_FOUND(_));else if(P)b(void 0,P);else{var y=o.findFiles(_),C=-1,D=function(){if(C+=1,C<y.length){var B=y[C],M=S(_,B).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?o.fs.stat(B,function(Y,V){Y&&b(void 0,Y),V.isFile()?o.fs.readFile(B,function(re,X){re?b(void 0,re):(T.addFile(I+M,X,"",V),D())}):(T.addFile(I+M+"/",Buffer.alloc(0),"",V),D())}):process.nextTick(()=>{D()})}else b(!0,void 0)};D()}})},addLocalFolderAsync2:function(_,b){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=ye.resolve(g(_.localPath));let{zipPath:A,filter:T,namefix:P}=_;T instanceof RegExp?T=(function(D){return function(B){return D.test(B)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?g(A):"",P=="latin1"&&(P=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=D=>D);let y=D=>ye.join(A,P(S(localPath,D))),C=D=>ye.win32.basename(ye.win32.normalize(P(D)));o.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?b(void 0,Ee.Errors.FILE_NOT_FOUND(localPath)):D?b(void 0,D):o.findFilesAsync(localPath,function(B,M){if(B)return b(B);M=M.filter(Y=>T(y(Y))),M.length||b(void 0,!1),setImmediate(M.reverse().reduce(function(Y,V){return function(re,X){if(re||X===!1)return setImmediate(Y,re,!1);I.addLocalFileAsync({localPath:V,zipPath:ye.dirname(y(V)),zipName:C(V)},Y)}},b))})})},addLocalFolderPromise:function(_,b){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},b),(T,P)=>{T&&A(T),P&&I(this)})})},addFile:function(_,b,I,A){_=f(_);let T=x(_),P=T!=null;P||(T=new vm(i),T.entryName=_),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 D=T.isDirectory?16384:32768;return y?D|=4095&A.mode:typeof A=="number"?D|=4095&A:D|=T.isDirectory?493:420,C=(C|D<<16)>>>0,T.attr=C,T.setData(b),P||c.setEntry(T),T},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,b,I,A,T,P){A=Dn(!1,A),T=Dn(!1,T),I=Dn(!0,I),P=uu(T,P);var y=x(_);if(!y)throw Ee.Errors.NO_ENTRY();var C=l(y.entryName),D=u(b,P&&!y.isDirectory?P:I?C:ye.basename(C));if(y.isDirectory){var B=c.getEntryChildren(y);return B.forEach(function(V){if(V.isDirectory)return;var re=V.getData();if(!re)throw Ee.Errors.CANT_EXTRACT_FILE();var X=l(V.entryName),se=u(b,I?X:ye.basename(X));let oe=T?V.header.fileAttr:void 0;o.writeFileTo(se,re,A,oe)}),!0}var M=y.getData(c.password);if(!M)throw Ee.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(D)&&!A)throw Ee.Errors.CANT_OVERRIDE();let Y=T?_.header.fileAttr:void 0;return o.writeFileTo(D,M,A,Y),!0},test:function(_){if(!c)return!1;for(var b in c.entries)try{if(b.isDirectory)continue;var I=c.entries[b].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,b,I,A){if(I=Dn(!1,I),A=uu(I,A),b=Dn(!1,b),!c)throw Ee.Errors.NO_ZIP();c.entries.forEach(function(T){var P=u(_,l(T.entryName));if(T.isDirectory){o.makeDir(P);return}var y=T.getData(A);if(!y)throw Ee.Errors.CANT_EXTRACT_FILE();let C=I?T.header.fileAttr:void 0;o.writeFileTo(P,y,b,C);try{o.fs.utimesSync(P,T.header.time,T.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,b,I,A){if(A=Im(b,I,A),I=Dn(!1,I),b=Dn(!1,b),!A)return new Promise((D,B)=>{this.extractAllToAsync(_,b,I,function(M){M?B(M):D(this)})});if(!c){A(Ee.Errors.NO_ZIP());return}_=ye.resolve(_);let T=D=>u(_,ye.normalize(l(D.entryName))),P=(D,B)=>new Error(D+': "'+B+'"'),y=[],C=[];c.entries.forEach(D=>{D.isDirectory?y.push(D):C.push(D)});for(let D of y){let B=T(D),M=I?D.header.fileAttr:void 0;try{o.makeDir(B),M&&o.fs.chmodSync(B,M),o.fs.utimesSync(B,D.header.time,D.header.time)}catch{A(P("Unable to create folder",B))}}C.reverse().reduce(function(D,B){return function(M){if(M)D(M);else{let Y=ye.normalize(l(B.entryName)),V=u(_,Y);B.getDataAsync(function(re,X){if(X)D(X);else if(!re)D(Ee.Errors.CANT_EXTRACT_FILE());else{let se=I?B.header.fileAttr:void 0;o.writeFileToAsync(V,re,b,se,function(oe){oe||D(P("Unable to write file",V)),o.fs.utimes(V,B.header.time,B.header.time,function(R){R?D(P("Unable to set times",V)):D()})})}})}}},A)()},writeZip:function(_,b){if(arguments.length===1&&typeof _=="function"&&(b=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof b=="function"&&b(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,b){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},b);return new Promise((T,P)=>{!_&&i.filename&&(_=i.filename),_||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(y=>{let C=D=>D?T(D):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,y,I,A,C)},P)})},toBufferPromise:function(){return new Promise((_,b)=>{c.toAsyncBuffer(_,b)})},toBuffer:function(_,b,I,A){return typeof _=="function"?(c.toAsyncBuffer(_,b,I,A),null):c.compressToBuffer()}}}});import{execFile as D_,spawn as O_,spawnSync as IA}from"node:child_process";import{promisify as L_}from"node:util";function M_(t){if(process.platform!=="win32")return!1;if(Of.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Of,"").toLowerCase();return N_.has(r)}function Lf(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,Lf(t,r))}function Nf(t,e=[],r={}){return B_(t,e,Lf(t,r))}var N_,Of,B_,$t=Qe(()=>{"use strict";N_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Of=/\.(cmd|bat|ps1)$/i;B_=L_(D_)});var Zt=ae((fR,_h)=>{"use strict";var mh=["nodebuffer","arraybuffer","fragments"],wh=typeof Blob<"u";wh&&mh.push("blob");_h.exports={BINARY_TYPES:mh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:wh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var $i=ae((hR,ko)=>{"use strict";var{EMPTY_BUFFER:gb}=Zt(),hd=Buffer[Symbol.species];function mb(t,e){if(t.length===0)return gb;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 hd(r.buffer,r.byteOffset,i):r}function yh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Eh(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function wb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function xd(t){if(xd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new hd(t):ArrayBuffer.isView(t)?e=new hd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),xd.readOnly=!1),e}ko.exports={concat:mb,mask:yh,toArrayBuffer:wb,toBuffer:xd,unmask:Eh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ue("bufferutil");ko.exports.mask=function(e,r,i,o,c){c<48?yh(e,r,i,o,c):t.mask(e,r,i,o,c)},ko.exports.unmask=function(e,r){e.length<32?Eh(e,r):t.unmask(e,r)}}catch{}});var Sh=ae((xR,vh)=>{"use strict";var bh=Symbol("kDone"),pd=Symbol("kRun"),gd=class{constructor(e){this[bh]=()=>{this.pending--,this[pd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[pd]()}[pd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[bh])}}};vh.exports=gd});var zr=ae((pR,Th)=>{"use strict";var Vi=ue("zlib"),Ih=$i(),_b=Sh(),{kStatusCode:Ah}=Zt(),yb=Buffer[Symbol.species],Eb=Buffer.from([0,0,255,255]),Co=Symbol("permessage-deflate"),Yt=Symbol("total-length"),Br=Symbol("callback"),kn=Symbol("buffers"),Fr=Symbol("error"),To,md=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,!To){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;To=new _b(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){To.add(o=>{this._decompress(e,r,(c,l)=>{o(),i(c,l)})})}compress(e,r,i){To.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"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Vi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[Co]=this,this._inflate[Yt]=0,this._inflate[kn]=[],this._inflate.on("error",vb),this._inflate.on("data",kh)}this._inflate[Br]=i,this._inflate.write(e),r&&this._inflate.write(Eb),this._inflate.flush(()=>{let c=this._inflate[Fr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=Ih.concat(this._inflate[kn],this._inflate[Yt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Yt]=0,this._inflate[kn]=[],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"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Vi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[Yt]=0,this._deflate[kn]=[],this._deflate.on("data",bb)}this._deflate[Br]=i,this._deflate.write(e),this._deflate.flush(Vi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Ih.concat(this._deflate[kn],this._deflate[Yt]);r&&(c=new yb(c.buffer,c.byteOffset,c.length-4)),this._deflate[Br]=null,this._deflate[Yt]=0,this._deflate[kn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Th.exports=md;function bb(t){this[kn].push(t),this[Yt]+=t.length}function kh(t){if(this[Yt]+=t.length,this[Co]._maxPayload<1||this[Yt]<=this[Co]._maxPayload){this[kn].push(t);return}this[Fr]=new RangeError("Max payload size exceeded"),this[Fr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Fr][Ah]=1009,this.removeListener("data",kh),this.reset()}function vb(t){if(this[Co]._inflate=null,this[Fr]){this[Br](this[Fr]);return}t[Ah]=1007,this[Br](t)}});var Ur=ae((gR,Ro)=>{"use strict";var{isUtf8:Ch}=ue("buffer"),{hasBlob:Sb}=Zt(),Ib=[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 Ab(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function wd(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 kb(t){return Sb&&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:kb,isValidStatusCode:Ab,isValidUTF8:wd,tokenChars:Ib};if(Ch)Ro.exports.isValidUTF8=function(t){return t.length<24?wd(t):Ch(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ue("utf-8-validate");Ro.exports.isValidUTF8=function(e){return e.length<32?wd(e):t(e)}}catch{}});var vd=ae((mR,Mh)=>{"use strict";var{Writable:Tb}=ue("stream"),Rh=zr(),{BINARY_TYPES:Cb,EMPTY_BUFFER:Ph,kStatusCode:Rb,kWebSocket:Pb}=Zt(),{concat:_d,toArrayBuffer:Db,unmask:Ob}=$i(),{isValidStatusCode:Lb,isValidUTF8:Dh}=Ur(),Po=Buffer[Symbol.species],ut=0,Oh=1,Lh=2,Nh=3,yd=4,Ed=5,Do=6,bd=class extends Tb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Cb[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[Pb]=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 Po(i.buffer,i.byteOffset+e,i.length-e),new Po(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 Po(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 Oh:this.getPayloadLength16(e);break;case Lh:this.getPayloadLength64(e);break;case Nh:this.getMask();break;case yd:this.getData(e);break;case Ed:case Do: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=Oh:this._payloadLength===127?this._state=Lh: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=Nh:this._state=yd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=yd}getData(e){let r=Ph;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&&Ob(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Ed,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 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=_d(i,r):this._binaryType==="arraybuffer"?o=Db(_d(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=ut):(this._state=Do,setImmediate(()=>{this.emit("message",o,!0),this._state=ut,this.startLoop(e)}))}else{let o=_d(i,r);if(!this._skipUTF8Validation&&!Dh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Ed||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=ut):(this._state=Do,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,Ph),this.end();else{let i=e.readUInt16BE(0);if(!Lb(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Po(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Dh(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=Do,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[Rb]=o,l}};Mh.exports=bd});var Ad=ae((_R,zh)=>{"use strict";var{Duplex:wR}=ue("stream"),{randomFillSync:Nb}=ue("crypto"),{types:{isUint8Array:Mb}}=ue("util"),Bh=zr(),{EMPTY_BUFFER:Bb,kWebSocket:Fb,NOOP:zb}=Zt(),{isBlob:Gr,isValidStatusCode:Ub}=Ur(),{mask:Fh,toBuffer:Vn}=$i(),ft=Symbol("kByteLength"),Gb=Buffer.alloc(4),Oo=8*1024,Zn,Hr=Oo,bt=0,Hb=1,qb=2,Sd=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=bt,this.onerror=zb,this[Fb]=void 0}static frame(e,r){let i,o=!1,c=2,l=!1;r.mask&&(i=r.maskBuffer||Gb,r.generateMask?r.generateMask(i):(Hr===Oo&&(Zn===void 0&&(Zn=Buffer.alloc(Oo)),Nb(Zn,0,Oo),Hr=0),i[0]=Zn[Hr++],i[1]=Zn[Hr++],i[2]=Zn[Hr++],i[3]=Zn[Hr++]),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 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],l?[x,e]:o?(Fh(e,i,x,c,u),[x]):(Fh(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=Bb;else{if(typeof e!="number"||!Ub(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(Mb(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!==bt?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):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 l={[ft]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Gr(e)?this._state!==bt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==bt?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):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 l={[ft]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Gr(e)?this._state!==bt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==bt?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,r,i){let o=this._extensions[Bh.extensionName],c=r.binary?2:1,l=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,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 x={[ft]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:f,rsv1:l};Gr(e)?this._state!==bt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==bt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[ft],this._state=qb,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Id,this,u,o);return}this._bufferedBytes-=i[ft];let l=Vn(c);r?this.dispatch(l,r,i,o):(this._state=bt,this.sendFrame(t.frame(l,i),o),this.dequeue())}).catch(c=>{process.nextTick(jb,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[Bh.extensionName];this._bufferedBytes+=i[ft],this._state=Hb,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Id(this,f,o);return}this._bufferedBytes-=i[ft],this._state=bt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===bt&&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)}};zh.exports=Sd;function Id(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 jb(t,e,r){Id(t,e,r),t.onerror(e)}});var Vh=ae((yR,$h)=>{"use strict";var{kForOnEventAttribute:Zi,kListener:kd}=Zt(),Uh=Symbol("kCode"),Gh=Symbol("kData"),Hh=Symbol("kError"),qh=Symbol("kMessage"),jh=Symbol("kReason"),qr=Symbol("kTarget"),Wh=Symbol("kType"),Kh=Symbol("kWasClean"),Jt=class{constructor(e){this[qr]=null,this[Wh]=e}get target(){return this[qr]}get type(){return this[Wh]}};Object.defineProperty(Jt.prototype,"target",{enumerable:!0});Object.defineProperty(Jt.prototype,"type",{enumerable:!0});var Yn=class extends Jt{constructor(e,r={}){super(e),this[Uh]=r.code===void 0?0:r.code,this[jh]=r.reason===void 0?"":r.reason,this[Kh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Uh]}get reason(){return this[jh]}get wasClean(){return this[Kh]}};Object.defineProperty(Yn.prototype,"code",{enumerable:!0});Object.defineProperty(Yn.prototype,"reason",{enumerable:!0});Object.defineProperty(Yn.prototype,"wasClean",{enumerable:!0});var jr=class extends Jt{constructor(e,r={}){super(e),this[Hh]=r.error===void 0?null:r.error,this[qh]=r.message===void 0?"":r.message}get error(){return this[Hh]}get message(){return this[qh]}};Object.defineProperty(jr.prototype,"error",{enumerable:!0});Object.defineProperty(jr.prototype,"message",{enumerable:!0});var Yi=class extends Jt{constructor(e,r={}){super(e),this[Gh]=r.data===void 0?null:r.data}get data(){return this[Gh]}};Object.defineProperty(Yi.prototype,"data",{enumerable:!0});var Wb={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Zi]&&o[kd]===e&&!o[Zi])return;let i;if(t==="message")i=function(c,l){let u=new Yi("message",{data:l?c:c.toString()});u[qr]=this,Lo(e,this,u)};else if(t==="close")i=function(c,l){let u=new Yn("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[qr]=this,Lo(e,this,u)};else if(t==="error")i=function(c){let l=new jr("error",{error:c,message:c.message});l[qr]=this,Lo(e,this,l)};else if(t==="open")i=function(){let c=new Jt("open");c[qr]=this,Lo(e,this,c)};else return;i[Zi]=!!r[Zi],i[kd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[kd]===e&&!r[Zi]){this.removeListener(t,r);break}}};$h.exports={CloseEvent:Yn,ErrorEvent:jr,Event:Jt,EventTarget:Wb,MessageEvent:Yi};function Lo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var No=ae((ER,Zh)=>{"use strict";var{tokenChars:Ji}=Ur();function Nt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Kb(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,l,u,f=-1,x=-1,g=-1,m=0;for(;m<t.length;m++)if(x=t.charCodeAt(m),l===void 0)if(g===-1&&Ji[x]===1)f===-1&&(f=m);else if(m!==0&&(x===32||x===9))g===-1&&f!==-1&&(g=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let _=t.slice(f,g);x===44?(Nt(e,_,r),r=Object.create(null)):l=_,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(u===void 0)if(g===-1&&Ji[x]===1)f===-1&&(f=m);else if(x===32||x===9)g===-1&&f!==-1&&(g=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m),Nt(r,t.slice(f,g),!0),x===44&&(Nt(e,l,r),r=Object.create(null),l=void 0),f=g=-1}else if(x===61&&f!==-1&&g===-1)u=t.slice(f,m),f=g=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(o){if(Ji[x]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);f===-1?f=m:i||(i=!0),o=!1}else if(c)if(Ji[x]===1)f===-1&&(f=m);else if(x===34&&f!==-1)c=!1,g=m;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(x===34&&t.charCodeAt(m-1)===61)c=!0;else if(g===-1&&Ji[x]===1)f===-1&&(f=m);else if(f!==-1&&(x===32||x===9))g===-1&&(g=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let _=t.slice(f,g);i&&(_=_.replace(/\\/g,""),i=!1),Nt(r,u,_),x===44&&(Nt(e,l,r),r=Object.create(null),l=void 0),u=void 0,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(f===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=m);let S=t.slice(f,g);return l===void 0?Nt(e,S,r):(u===void 0?Nt(r,S,!0):i?Nt(r,u,S.replace(/\\/g,"")):Nt(r,u,S),Nt(e,l,r)),e}function $b(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(", ")}Zh.exports={format:$b,parse:Kb}});var zo=ae((SR,ax)=>{"use strict";var Vb=ue("events"),Zb=ue("https"),Yb=ue("http"),Xh=ue("net"),Jb=ue("tls"),{randomBytes:Xb,createHash:Qb}=ue("crypto"),{Duplex:bR,Readable:vR}=ue("stream"),{URL:Td}=ue("url"),Tn=zr(),ev=vd(),tv=Ad(),{isBlob:nv}=Ur(),{BINARY_TYPES:Yh,CLOSE_TIMEOUT:rv,EMPTY_BUFFER:Mo,GUID:iv,kForOnEventAttribute:Cd,kListener:sv,kStatusCode:ov,kWebSocket:He,NOOP:Qh}=Zt(),{EventTarget:{addEventListener:av,removeEventListener:cv}}=Vh(),{format:dv,parse:lv}=No(),{toBuffer:uv}=$i(),ex=Symbol("kAborted"),Rd=[8,13],Xt=["CONNECTING","OPEN","CLOSING","CLOSED"],fv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends Vb{constructor(e,r,i){super(),this._binaryType=Yh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Mo,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]),tx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yh.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[He]=this,c[He]=this,e[He]=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=Ev,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",ix),e.on("data",Fo),e.on("end",sx),e.on("error",ox),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){ot(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())}),rx(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){Pd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Mo,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){Pd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Mo,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){Pd(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||Mo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ot(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[Cd])return e[sv];return null},set(e){for(let r of this.listeners(t))if(r[Cd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Cd]:!0})}})});me.prototype.addEventListener=av;me.prototype.removeEventListener=cv;ax.exports=me;function tx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:rv,protocolVersion:Rd[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,!Rd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Rd.join(", ")})`);let c;if(e instanceof Td)c=e;else try{c=new Td(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:",f;if(c.protocol!=="ws:"&&!l&&!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;Bo(t,I);return}let x=l?443:80,g=Xb(16).toString("base64"),m=l?Zb.request:Yb.request,S=new Set,_;if(o.createConnection=o.createConnection||(l?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":g,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Tn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=dv({[Tn.extensionName]:_.offer()})),r.length){for(let I of r){if(typeof I!="string"||!fv.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.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 b;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,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&&!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")),b=t._req=m(o),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=m(o);o.timeout&&b.on("timeout",()=>{ot(t,b,"Opening handshake has timed out")}),b.on("error",I=>{b===null||b[ex]||(b=t._req=null,Bo(t,I))}),b.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){ot(t,b,"Maximum redirects exceeded");return}b.abort();let P;try{P=new Td(A,e)}catch{let C=new SyntaxError(`Invalid URL: ${A}`);Bo(t,C);return}tx(t,P,r,i)}else t.emit("unexpected-response",b,I)||ot(t,b,`Unexpected server response: ${I.statusCode}`)}),b.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==me.CONNECTING)return;b=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){ot(t,A,"Invalid Upgrade header");return}let y=Qb("sha1").update(g+iv).digest("base64");if(I.headers["sec-websocket-accept"]!==y){ot(t,A,"Invalid Sec-WebSocket-Accept header");return}let C=I.headers["sec-websocket-protocol"],D;if(C!==void 0?S.size?S.has(C)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":S.size&&(D="Server sent no subprotocol"),D){ot(t,A,D);return}C&&(t._protocol=C);let B=I.headers["sec-websocket-extensions"];if(B!==void 0){if(!_){ot(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=lv(B)}catch{ot(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Y=Object.keys(M);if(Y.length!==1||Y[0]!==Tn.extensionName){ot(t,A,"Server indicated an extension that was not requested");return}try{_.accept(M[Tn.extensionName])}catch{ot(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Tn.extensionName]=_}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(b,t):b.end()}function Bo(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function hv(t){return t.path=t.socketPath,Xh.connect(t)}function xv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Xh.isIP(t.host)?"":t.host),Jb.connect(t)}function ot(t,e,r){t._readyState=me.CLOSING;let i=new Error(r);Error.captureStackTrace(i,ot),e.setHeader?(e[ex]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Bo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Pd(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[He];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[He]!==void 0&&(r._socket.removeListener("data",Fo),process.nextTick(nx,r._socket),t===1005?r.close():r.close(t,e))}function gv(){let t=this[He];t.isPaused||t._socket.resume()}function mv(t){let e=this[He];e._socket[He]!==void 0&&(e._socket.removeListener("data",Fo),process.nextTick(nx,e._socket),e.close(t[ov])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Jh(){this[He].emitClose()}function wv(t,e){this[He].emit("message",t,e)}function _v(t){let e=this[He];e._autoPong&&e.pong(t,!this._isServer,Qh),e.emit("ping",t)}function yv(t){this[He].emit("pong",t)}function nx(t){t.resume()}function Ev(t){let e=this[He];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,rx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function rx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ix(){let t=this[He];if(this.removeListener("close",ix),this.removeListener("data",Fo),this.removeListener("end",sx),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[He]=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 Fo(t){this[He]._receiver.write(t)||this.pause()}function sx(){let t=this[He];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function ox(){let t=this[He];this.removeListener("error",ox),this.on("error",Qh),t&&(t._readyState=me.CLOSING,this.destroy())}});var ux=ae((AR,lx)=>{"use strict";var IR=zo(),{Duplex:bv}=ue("stream");function cx(t){t.emit("close")}function vv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function dx(t){this.removeListener("error",dx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Sv(t,e){let r=!0,i=new bv({...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(cx,i);return}let l=!1;t.once("error",function(f){l=!0,c(f)}),t.once("close",function(){l||c(o),process.nextTick(cx,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",vv),i.on("error",dx),i}lx.exports=Sv});var Dd=ae((kR,fx)=>{"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 l=t.charCodeAt(o);if(i===-1&&Iv[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}fx.exports={parse:Av}});var yx=ae((CR,_x)=>{"use strict";var kv=ue("events"),Uo=ue("http"),{Duplex:TR}=ue("stream"),{createHash:Tv}=ue("crypto"),hx=No(),Jn=zr(),Cv=Dd(),Rv=zo(),{CLOSE_TIMEOUT:Pv,GUID:Dv,kWebSocket:Ov}=Zt(),Lv=/^[+/0-9A-Za-z]{22}==$/,xx=0,px=1,mx=2,Od=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:Rv,...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=Uo.createServer((i,o)=>{let c=Uo.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,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===mx){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!==px)if(this._state=px,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",gx);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Xn(this,e,r,405,"Invalid HTTP method");return}if(l===void 0||l.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=Cv.parse(f)}catch{Xn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&g!==void 0){let S=new Jn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=hx.parse(g);_[Jn.extensionName]&&(S.accept(_[Jn.extensionName]),m[Jn.extensionName]=S)}catch{Xn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={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(S,(_,b,I,A)=>{if(!_)return Qi(r,b||401,I,A);this.completeUpgrade(m,c,x,e,r,i,o)});return}if(!this.options.verifyClient(S))return Qi(r,401)}this.completeUpgrade(m,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,l,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>xx)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")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;m&&(x.push(`Sec-WebSocket-Protocol: ${m}`),g._protocol=m)}if(e[Jn.extensionName]){let m=e[Jn.extensionName].params,S=hx.format({[Jn.extensionName]:[m]});x.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
8
+ var yg=Object.create;var Ia=Object.defineProperty;var bg=Object.getOwnPropertyDescriptor;var Eg=Object.getOwnPropertyNames;var vg=Object.getPrototypeOf,Sg=Object.prototype.hasOwnProperty;var he=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var rt=(t,e)=>()=>(t&&(e=t(t=0)),e);var de=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Aa=(t,e)=>{for(var n in e)Ia(t,n,{get:e[n],enumerable:!0})},Ig=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Eg(e))!Sg.call(t,s)&&s!==n&&Ia(t,s,{get:()=>e[s],enumerable:!(i=bg(e,s))||i.enumerable});return t};var Ht=(t,e,n)=>(n=t!=null?yg(vg(t)):{},Ig(e||!t||!t.__esModule?Ia(n,"default",{value:t,enumerable:!0}):n,t));function Ze(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ar=rt(()=>{"use strict"});import{createWriteStream as Ag,mkdirSync as Tg,readdirSync as kg,unlinkSync as Cg}from"node:fs";import{join as bl}from"node:path";function Ln(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function cr(t,e){return`${t}-${e}.log`}function Ta(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Dg(t,e,n){let i=c=>{let[d,u,h]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>n}function us(t,e,n,i){let s;try{s=kg(t)}catch{return}for(let c of s){let d=Ta(c,e);if(d&&Dg(d,n,i))try{Cg(bl(t,c))}catch{}}}var ri,ka=rt(()=>{"use strict";ri=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Ln(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let n=this.clock();n!==this.currentDate&&this.rotate(n),this.stream?.write(e)}rotate(e){this.stream?.end();try{Tg(this.dir,{recursive:!0});let n=Ag(bl(this.dir,cr(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
+ `)),this.stream=n}catch(n){process.stderr.write(`[log-sink] rotate failed: ${String(n)}
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&us(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 Rg,mkdirSync as Pg}from"node:fs";import{join as Og}from"node:path";function vl(t){let e=t.retentionDays??Mg,n=t.clock??(()=>Ln(new Date));hs={bridgeSink:new ri(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:s=>new ri(t.agentLogsDir(s),"agent",{retentionDays:e,clock:n})};let i=n();us(t.bridgeLogsDir,"bridge",i,e);for(let s of t.listAgentIds?.()??[])us(t.agentLogsDir(s),"agent",i,e)}function Bg(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Sl(t){Ca=t}function Il(t){return dr[Ca]<=dr[t]}function Al(t,e){let n=dr[t];return n===void 0?!0:n>=dr[e]}function xs(t){El={...t}}function Tl(t){let e=(u,h=2)=>String(u).padStart(h,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",s=Math.abs(n),c=e(Math.floor(s/60)),d=e(s%60);return`${Ln(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function ut(t,e,n,i,s){try{let c=`${JSON.stringify({ts:Tl(new Date),level:e,module:n,msg:i,...s})}
11
+ `;Pg(t,{recursive:!0}),Rg(Og(t,cr("bridge",Ln(new Date))),c)}catch{}}function Fg(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function fs(t,e,n,i,s){if(dr[t]<dr[Ca])return;let c=`${JSON.stringify({ts:Tl(new Date),level:t,module:e,msg:n,...El,...i})}
12
+ `;if(hs){let d=Fg(s,i),u=d?Bg(hs,d):hs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Ng.write(c):Lg.write(c)}function q(t,e){return{debug:(n,i)=>fs("debug",t,n,i,e),info:(n,i)=>fs("info",t,n,i,e),warn:(n,i)=>fs("warn",t,n,i,e),error:(n,i)=>fs("error",t,n,i,e),child:n=>q(`${t}.${n}`,e),forAgent:n=>q(t,n)}}var dr,Ca,Lg,Ng,El,Mg,hs,ee=rt(()=>{"use strict";ar();ka();dr={debug:10,info:20,warn:30,error:40},Ca=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Lg=process.stdout,Ng=process.stderr,El={},Mg=Ze("COZE_BRIDGE_LOG_RETENTION_DAYS",30),hs=null});var T,$e=rt(()=>{"use strict";T=class extends Error{code;retriable;cause;constructor(e,n,i){super(n),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Rl={};Aa(Rl,{ACP_WRAPPER_NPM_PACKAGES:()=>ps,_resetAcpInstallerForTests:()=>jg,_setBinaryPathCacheForTests:()=>Wg,buildAcpSpawn:()=>si,ensureAcpInstalled:()=>lr,getAcpBinaryPath:()=>gs,pickWhichLine:()=>Pa,probeAcpVersion:()=>Hg,resolveAcpCommand:()=>Dl});import{readFileSync as kl}from"node:fs";import{createRequire as zg}from"node:module";import{dirname as Ug,resolve as Gg}from"node:path";function Pa(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 n=i=>e.find(s=>s.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function qg(t){let e=Cl.resolve(`${t.npmPackage}/package.json`),n=Ug(e),i=JSON.parse(kl(e,"utf8")),s=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!s)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return Gg(n,s)}async function lr(t,e){let n=Ra[t];if(!n)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ii.get(t);if(i)return i;try{let s=qg(n);return ii.set(t,s),Da.info("acp wrapper resolved",{framework:t,binary:n.binary,path:s}),s}catch(s){throw Da.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(s)}),new T("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${n.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:s})}}async function Hg(t){let e=Ra[t];if(e)try{let n=Cl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(kl(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Da.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function gs(t){return ii.get(t)}function Dl(t,e){if(e)return e;let n=gs(t);if(!n)throw new T("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return n}function si(t,e,n){if(e)return{command:e,args:[...n]};let i=Dl(t);return{command:process.execPath,args:[i,...n]}}function jg(){ii.clear()}function Wg(t,e){ii.set(t,e)}var Da,Ra,ps,Cl,ii,cn=rt(()=>{"use strict";$e();ee();Da=q("agents.acp-installer"),Ra={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},ps=Object.values(Ra).filter(t=>t!==void 0).map(t=>t.npmPackage),Cl=zg(import.meta.url),ii=new Map});import{chmod as $g,mkdir as Vg,readFile as Jg,rename as Zg,rm as Yg,writeFile as Xg}from"node:fs/promises";import{dirname as Qg}from"node:path";async function ur(t){try{let e=await Jg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function dn(t,e,n){await Vg(Qg(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Xg(i,e,{encoding:"utf8",mode:n?.mode}),await Zg(i,t),n?.mode!==void 0&&await $g(t,n.mode)}catch(s){throw await Yg(i,{force:!0}).catch(()=>{}),s}}async function fr(t,e,n){await dn(t,`${JSON.stringify(e,null,2)}
14
+ `,n)}var ln=rt(()=>{"use strict"});import{promises as Ll,readdirSync as em}from"node:fs";import{homedir as tm}from"node:os";import{sep as nm,join as De,resolve as Nl}from"node:path";function X(t){let e=t??tm(),n=De(e,".coze"),i=De(n,"bridge"),s=De(i,"lib"),c=De(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:s,libEntry:De(s,"index.js"),binDir:De(i,"bin"),pidFile:De(i,"bridge.pid"),portFile:De(i,"bridge.port"),tokenFile:De(i,"bridge.token"),patTokenFile:De(i,"pat-token"),agentEnvFile:De(i,"agent-env.json"),logFile:De(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:De(c,"daemon-stdio.log"),installLock:De(i,"install.lock"),configFile:De(i,"config.json"),agentsRoot:De(n,"agents")}}function Ye(t,e=X()){let n=De(e.agentsRoot,t);return{root:n,config:De(n,"config.json"),workspace:De(n,"workspace"),logs:De(n,"logs")}}function ms(t=X()){try{return em(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function oi(t,e){let n=await Ll.realpath(Nl(t)).catch(()=>null);if(!n)return!1;let i=await Ll.realpath(Nl(e)).catch(()=>null);if(!i)return!1;let s=process.platform==="win32"?n.toLowerCase():n,c=process.platform==="win32"?i.toLowerCase():i;return s===c||s.startsWith(c+nm)}var Be=rt(()=>{"use strict"});var _s={};Aa(_s,{AGENT_CONFIG_FILE_MODE:()=>ws,enforceAgentConfigMode:()=>sm,loadAgentConfig:()=>Re,persistAgentSessions:()=>ai,persistAgentSkills:()=>ci,saveAgentConfig:()=>Ue});import{chmod as rm,stat as im}from"node:fs/promises";function Re(t,e){return ur(Ye(t,e).config)}function Ue(t,e){return fr(Ye(t.agentId,e).config,t,{mode:ws})}async function sm(t,e){if(process.platform==="win32")return;let n=Ye(t,e).config;try{let i=await im(n);if(!i.isFile())return;let s=i.mode&511;s!==ws&&(await rm(n,ws),Ml.warn("agent config mode auto-corrected to 0600",{path:n,from:s.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Ml.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function ai(t,e,n){let i=await Re(t,n);i&&(i.sessions=Object.fromEntries(e),await Ue(i,n))}async function ci(t,e,n){let i=await Re(t,n);i&&(i.skills=e,await Ue(i,n))}var Ml,ws,un=rt(()=>{"use strict";ln();ee();Be();Ml=q("agent-config"),ws=384});var Na=de(($2,zl)=>{zl.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 bs=de(Gl=>{var Ul={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 um(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(n,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Ul))Gl[t]=um(Ul[t])});var Kl=de((J2,Wl)=>{var fm=he("fs"),Fe=he("path"),ql=Na(),hm=bs(),xm=typeof process=="object"&&process.platform==="win32",Hl=t=>typeof t=="object"&&t!==null,jl=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Ae(t){this.sep=Fe.sep,this.fs=fm,Hl(t)&&Hl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Wl.exports=Ae;Ae.prototype.makeDir=function(t){let e=this;function n(i){let s=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){s+=e.sep+c;var d;try{d=e.fs.statSync(s)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw u}if(d&&d.isFile())throw hm.FILE_IN_THE_WAY(`"${s}"`)}})}n(t)};Ae.prototype.writeFileTo=function(t,e,n,i){let s=this;if(s.fs.existsSync(t)){if(!n)return!1;var c=s.fs.statSync(t);if(c.isDirectory())return!1}var d=Fe.dirname(t);s.fs.existsSync(d)||s.makeDir(d);var u;try{u=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),u=s.fs.openSync(t,"w",438)}if(u)try{s.fs.writeSync(u,e,0,e.length,0)}finally{s.fs.closeSync(u)}return s.fs.chmodSync(t,i||438),!0};Ae.prototype.writeFileToAsync=function(t,e,n,i,s){typeof i=="function"&&(s=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!n)return s(!1);c.fs.stat(t,function(u,h){if(d&&h.isDirectory())return s(!1);var x=Fe.dirname(t);c.fs.exists(x,function(m){m||c.makeDir(x),c.fs.open(t,"w",438,function(_,S){_?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,v){c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){s(!0)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,function(){c.fs.chmod(t,i||438,function(){s(!0)})})}):c.fs.chmod(t,i||438,function(){s(!0)})})})})})};Ae.prototype.findFiles=function(t){let e=this;function n(i,s,c){typeof s=="boolean"&&(c=s,s=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let h=Fe.join(i,u),x=e.fs.statSync(h);(!s||s.test(h))&&d.push(Fe.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(n(h,s,c)))}),d}return n(t,void 0,!0)};Ae.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(s,c){if(s)return e(s);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Fe.join(t,u),n.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Fe.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(m,_){if(m)return e(m);i=i.concat(_),--d||e(null,i)}):--d||e(null,i))})})})};Ae.prototype.getAttributes=function(){};Ae.prototype.setAttributes=function(){};Ae.crc32update=function(t,e){return jl[(t^e)&255]^t>>>8};Ae.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Ae.crc32update(n,t[i++]);return~n>>>0};Ae.methodToString=function(t){switch(t){case ql.STORED:return"STORED ("+t+")";case ql.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ae.canonical=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.join(".",e)};Ae.zipnamefix=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.posix.join(".",e)};Ae.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let i=n-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ae.sanitize=function(t,e){t=Fe.resolve(Fe.normalize(t));for(var n=e.split("/"),i=0,s=n.length;i<s;i++){var c=Fe.normalize(Fe.join(t,n.slice(i,s).join(Fe.sep)));if(c.indexOf(t)===0)return c}return Fe.normalize(Fe.join(t,Fe.basename(e)))};Ae.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Ae.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Ae.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)};Ae.fromDate2DOS=function(t){let e=0,n=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),n=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|n};Ae.isWin=xm;Ae.crcTable=jl});var Vl=de((Z2,$l)=>{var pm=he("path");$l.exports=function(t,{fs:e}){var n=t||"",i=c(),s=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(s=e.statSync(n),i.directory=s.isDirectory(),i.mtime=s.mtime,i.atime=s.atime,i.executable=(73&s.mode)!==0,i.readonly=(128&s.mode)===0,i.hidden=pm.basename(n)[0]==="."):console.warn("Invalid path: "+n),{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:n,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 Zl=de((Y2,Jl)=>{Jl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=de((X2,xr)=>{xr.exports=Kl();xr.exports.Constants=Na();xr.exports.Errors=bs();xr.exports.FileAttr=Vl();xr.exports.decoder=Zl()});var Xl=de((Q2,Yl)=>{var fn=pr(),z=fn.Constants;Yl.exports=function(){var t=20,e=10,n=0,i=0,s=0,c=0,d=0,u=0,h=0,x=0,m=0,_=0,S=0,y=0,v=0;t|=fn.isWin?2560:768,n|=z.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,k=b=>Math.max(0,b)&65535,P=b=>Math.max(0,b)&255;return s=fn.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return n},set flags(b){n=b},get flags_efs(){return(n&z.FLG_EFS)>0},set flags_efs(b){b?n|=z.FLG_EFS:n&=~z.FLG_EFS},get flags_desc(){return(n&z.FLG_DESC)>0},set flags_desc(b){b?n|=z.FLG_DESC:n&=~z.FLG_DESC},get method(){return i},set method(b){switch(b){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=b},get time(){return fn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=fn.fromDate2DOS(b)},get timeval(){return s},set timeval(b){s=A(b)},get timeHighByte(){return P(s>>>8)},get crc(){return c},set crc(b){c=A(b)},get compressedSize(){return d},set compressedSize(b){d=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return h},set fileNameLength(b){h=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return m},set commentLength(b){m=b},get diskNumStart(){return _},set diskNumStart(b){_=A(b)},get inAttr(){return S},set inAttr(b){S=A(b)},get attr(){return y},set attr(b){y=A(b)},get fileAttr(){return(y||0)>>16&4095},get offset(){return v},set offset(b){v=A(b)},get encrypted(){return(n&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+x+m},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var D=b.slice(v,v+z.LOCHDR);if(D.readUInt32LE(0)!==z.LOCSIG)throw fn.Errors.INVALID_LOC();I.version=D.readUInt16LE(z.LOCVER),I.flags=D.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=D.readUInt16LE(z.LOCHOW),I.time=D.readUInt32LE(z.LOCTIM),I.crc=D.readUInt32LE(z.LOCCRC),I.compressedSize=D.readUInt32LE(z.LOCSIZ),I.size=D.readUInt32LE(z.LOCLEN),I.fnameLen=D.readUInt16LE(z.LOCNAM),I.extraLen=D.readUInt16LE(z.LOCEXT);let O=v+z.LOCHDR+I.fnameLen,F=O+I.extraLen;return b.slice(O,F)},loadFromBinary:function(b){if(b.length!==z.CENHDR||b.readUInt32LE(0)!==z.CENSIG)throw fn.Errors.INVALID_CEN();t=b.readUInt16LE(z.CENVEM),e=b.readUInt16LE(z.CENVER),n=b.readUInt16LE(z.CENFLG),i=b.readUInt16LE(z.CENHOW),s=b.readUInt32LE(z.CENTIM),c=b.readUInt32LE(z.CENCRC),d=b.readUInt32LE(z.CENSIZ),u=b.readUInt32LE(z.CENLEN),h=b.readUInt16LE(z.CENNAM),x=b.readUInt16LE(z.CENEXT),m=b.readUInt16LE(z.CENCOM),_=b.readUInt16LE(z.CENDSK),S=b.readUInt16LE(z.CENATT),y=b.readUInt32LE(z.CENATX),v=b.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(z.LOCHDR);return b.writeUInt32LE(z.LOCSIG,0),b.writeUInt16LE(e,z.LOCVER),b.writeUInt16LE(n,z.LOCFLG),b.writeUInt16LE(i,z.LOCHOW),b.writeUInt32LE(s,z.LOCTIM),b.writeUInt32LE(c,z.LOCCRC),b.writeUInt32LE(d,z.LOCSIZ),b.writeUInt32LE(u,z.LOCLEN),b.writeUInt16LE(h,z.LOCNAM),b.writeUInt16LE(I.extraLen,z.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(z.CENHDR+h+x+m);return b.writeUInt32LE(z.CENSIG,0),b.writeUInt16LE(t,z.CENVEM),b.writeUInt16LE(e,z.CENVER),b.writeUInt16LE(n,z.CENFLG),b.writeUInt16LE(i,z.CENHOW),b.writeUInt32LE(s,z.CENTIM),b.writeUInt32LE(c,z.CENCRC),b.writeUInt32LE(d,z.CENSIZ),b.writeUInt32LE(u,z.CENLEN),b.writeUInt16LE(h,z.CENNAM),b.writeUInt16LE(x,z.CENEXT),b.writeUInt16LE(m,z.CENCOM),b.writeUInt16LE(_,z.CENDSK),b.writeUInt16LE(S,z.CENATT),b.writeUInt32LE(y,z.CENATX),b.writeUInt32LE(v,z.CENOFF),b},toJSON:function(){let b=function(D){return D+" bytes"};return{made:t,version:e,flags:n,method:fn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(m),diskNumStart:_,inAttr:S,attr:y,offset:v,centralHeaderSize:b(z.CENHDR+h+x+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var eu=de((eI,Ql)=>{var gr=pr(),ve=gr.Constants;Ql.exports=function(){var t=0,e=0,n=0,i=0,s=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 n},set size(c){n=c},get offset(){return i},set offset(c){i=c},get commentLength(){return s},set commentLength(c){s=c},get mainHeaderSize(){return ve.ENDHDR+s},loadFromBinary:function(c){if((c.length!==ve.ENDHDR||c.readUInt32LE(0)!==ve.ENDSIG)&&(c.length<ve.ZIP64HDR||c.readUInt32LE(0)!==ve.ZIP64SIG))throw gr.Errors.INVALID_END();c.readUInt32LE(0)===ve.ENDSIG?(t=c.readUInt16LE(ve.ENDSUB),e=c.readUInt16LE(ve.ENDTOT),n=c.readUInt32LE(ve.ENDSIZ),i=c.readUInt32LE(ve.ENDOFF),s=c.readUInt16LE(ve.ENDCOM)):(t=gr.readBigUInt64LE(c,ve.ZIP64SUB),e=gr.readBigUInt64LE(c,ve.ZIP64TOT),n=gr.readBigUInt64LE(c,ve.ZIP64SIZE),i=gr.readBigUInt64LE(c,ve.ZIP64OFF),s=0)},toBinary:function(){var c=Buffer.alloc(ve.ENDHDR+s);return c.writeUInt32LE(ve.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,ve.ENDSUB),c.writeUInt16LE(e,ve.ENDTOT),c.writeUInt32LE(n,ve.ENDSIZ),c.writeUInt32LE(i,ve.ENDOFF),c.writeUInt16LE(s,ve.ENDCOM),c.fill(" ",ve.ENDHDR),c},toJSON:function(){let c=function(d,u){let h=d.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:c(i,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ba=de(Ma=>{Ma.EntryHeader=Xl();Ma.MainHeader=eu()});var nu=de((nI,tu)=>{tu.exports=function(t){var e=he("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var s=e.createDeflateRaw(n),c=[],d=0;s.on("data",function(u){c.push(u),d+=u.length}),s.on("end",function(){var u=Buffer.alloc(d),h=0;u.fill(0);for(var x=0;x<c.length;x++){var m=c[x];m.copy(u,h),h+=m.length}i&&i(u)}),s.end(t)}}}});var iu=de((rI,ru)=>{var gm=+(process.versions?process.versions.node:"").split(".")[0]||0;ru.exports=function(t,e){var n=he("zlib");let i=gm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(s){var c=n.createInflateRaw(i),d=[],u=0;c.on("data",function(h){d.push(h),u+=h.length}),c.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var m=0;m<d.length;m++){var _=d[m];_.copy(h,x),x+=_.length}s&&s(h)}),c.end(t)}}}});var du=de((iI,cu)=>{"use strict";var{randomFillSync:su}=he("crypto"),mm=bs(),wm=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),au=(t,e)=>Math.imul(t,e)>>>0,ou=(t,e)=>wm[(t^e)&255]^t>>>8,di=()=>typeof su=="function"?su(Buffer.alloc(12)):di.node();di.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let n=0;n<e;n++)t[n]=Math.random()*256&255;return t};var Es={genSalt:di};function vs(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let n=0;n<e.length;n++)this.updateKeys(e[n])}vs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=ou(e[0],t),e[1]+=e[0]&255,e[1]=au(e[1],134775813)+1,e[2]=ou(e[2],e[1]>>>24),t};vs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return au(t,t^1)>>8&255};function _m(t){let e=new vs(t);return function(n){let i=Buffer.alloc(n.length),s=0;for(let c of n)i[s++]=e.updateKeys(c^e.next());return i}}function ym(t){let e=new vs(t);return function(n,i,s=0){i||(i=Buffer.alloc(n.length));for(let c of n){let d=e.next();i[s++]=c^d,e.updateKeys(c)}return i}}function bm(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=_m(n),s=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==c)throw mm.WRONG_PASSWORD();return i(t.slice(12))}function Em(t){Buffer.isBuffer(t)&&t.length>=12?Es.genSalt=function(){return t.slice(0,12)}:t==="node"?Es.genSalt=di.node:Es.genSalt=di}function vm(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=ym(n),c=Es.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return s(c,d),s(t,d,12)}cu.exports={decrypt:bm,encrypt:vm,_salter:Em}});var lu=de(Ss=>{Ss.Deflater=nu();Ss.Inflater=iu();Ss.ZipCrypto=du()});var za=de((oI,uu)=>{var le=pr(),Sm=Ba(),Te=le.Constants,Fa=lu();uu.exports=function(t,e){var n=new Sm.EntryHeader,i=Buffer.alloc(0),s=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let m=t,_=typeof m.decoder=="object"?m.decoder:le.decoder;x=_.hasOwnProperty("efs")?_.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function y(b){if(!n.flags_desc&&!n.localHeader.flags_desc){if(le.crc32(b)!==n.localHeader.crc)return!1}else{let D={},O=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(O)==Te.LOCSIG||e.readUInt32LE(O)==Te.CENSIG)throw le.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Te.EXTSIG)D.crc=e.readUInt32LE(O+Te.EXTCRC),D.compressedSize=e.readUInt32LE(O+Te.EXTSIZ),D.size=e.readUInt32LE(O+Te.EXTLEN);else if(e.readUInt16LE(O+12)===19280)D.crc=e.readUInt32LE(O+Te.EXTCRC-4),D.compressedSize=e.readUInt32LE(O+Te.EXTSIZ-4),D.size=e.readUInt32LE(O+Te.EXTLEN-4);else throw le.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==n.compressedSize||D.size!==n.size||D.crc!==n.crc)throw le.Errors.DESCRIPTOR_FAULTY();if(le.crc32(b)!==D.crc)return!1}return!0}function v(b,D,O){if(typeof D>"u"&&typeof b=="string"&&(O=b,b=void 0),c)return b&&D&&D(Buffer.alloc(0),le.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return b&&D&&D(F),F;if(n.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw le.Errors.INVALID_PASS_PARAM();F=Fa.ZipCrypto.decrypt(F,n,O)}var B=Buffer.alloc(n.size);switch(n.method){case le.Constants.STORED:if(F.copy(B),y(B))return b&&D&&D(B),B;throw b&&D&&D(B,le.Errors.BAD_CRC()),le.Errors.BAD_CRC();case le.Constants.DEFLATED:var V=new Fa.Inflater(F,n.size);if(b)V.inflateAsync(function(K){K.copy(K,0),D&&(y(K)?D(K):D(K,le.Errors.BAD_CRC()))});else{if(V.inflate(B).copy(B,0),!y(B))throw le.Errors.BAD_CRC(`"${_.decode(i)}"`);return B}break;default:throw b&&D&&D(Buffer.alloc(0),le.Errors.UNKNOWN_METHOD()),le.Errors.UNKNOWN_METHOD()}}function I(b,D){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&D&&D(S()),S();if(d.length&&!c){var O;switch(n.method){case le.Constants.STORED:return n.compressedSize=n.size,O=Buffer.alloc(d.length),d.copy(O),b&&D&&D(O),O;default:case le.Constants.DEFLATED:var F=new Fa.Deflater(d);if(b)F.deflateAsync(function(V){O=Buffer.alloc(V.length),n.compressedSize=V.length,V.copy(O),D&&D(O)});else{var B=F.deflate();return n.compressedSize=B.length,B}F=null;break}}else if(b&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,D){return le.readBigUInt64LE(b,D)}function k(b){try{for(var D=0,O,F,B;D+4<b.length;)O=b.readUInt16LE(D),D+=2,F=b.readUInt16LE(D),D+=2,B=b.slice(D,D+F),D+=F,Te.ID_ZIP64===O&&P(B)}catch{throw le.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(b){var D,O,F,B;b.length>=Te.EF_ZIP64_SCOMP&&(D=A(b,Te.EF_ZIP64_SUNCOMP),n.size===Te.EF_ZIP64_OR_32&&(n.size=D)),b.length>=Te.EF_ZIP64_RHO&&(O=A(b,Te.EF_ZIP64_SCOMP),n.compressedSize===Te.EF_ZIP64_OR_32&&(n.compressedSize=O)),b.length>=Te.EF_ZIP64_DSN&&(F=A(b,Te.EF_ZIP64_RHO),n.offset===Te.EF_ZIP64_OR_32&&(n.offset=F)),b.length>=Te.EF_ZIP64_DSN+4&&(B=b.readUInt32LE(Te.EF_ZIP64_DSN),n.diskNumStart===Te.EF_ZIP64_OR_16&&(n.diskNumStart=B))}return{get entryName(){return _.decode(i)},get rawEntryName(){return i},set entryName(b){i=le.toBuffer(b,_.encode);var D=i[i.length-1];c=D===47||D===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,n.extraLength=b.length,k(b)},get comment(){return _.decode(s)},set comment(b){if(s=le.toBuffer(b,_.encode),n.commentLength=s.length,s.length>65535)throw le.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){d=le.toBuffer(b,le.decoder.encode),!c&&d.length?(n.size=d.length,n.method=le.Constants.DEFLATED,n.crc=le.crc32(b),n.changed=!0):n.method=le.Constants.STORED},getData:function(b){return n.changed?d:v(!1,null,b)},getDataAsync:function(b,D){n.changed?b(d):v(!0,b,D)},set attr(b){n.attr=b},get attr(){return n.attr},set header(b){n.loadFromBinary(b)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var b=n.centralHeaderToBinary(),D=le.Constants.CENHDR;return i.copy(b,D),D+=i.length,u.copy(b,D),D+=n.extraLength,s.copy(b,D),b},packLocalHeader:function(){let b=0;n.flags_efs=this.efs,n.extraLocalLength=h.length;let D=n.localHeaderToBinary(),O=Buffer.alloc(D.length+i.length+n.extraLocalLength);return D.copy(O,b),b+=D.length,i.copy(O,b),b+=i.length,h.copy(O,b),b+=h.length,O},toJSON:function(){let b=function(D){return"<"+(D&&D.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:b(e),data:b(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var xu=de((aI,hu)=>{var fu=za(),Im=Ba(),Ve=pr();hu.exports=function(t,e){var n=[],i={},s=Buffer.alloc(0),c=new Im.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:m,decoder:_}=x;t?v(x.readEntries):d=!0;function S(){let A=new Set;for(let k of Object.keys(i)){let P=k.split("/");if(P.pop(),!!P.length)for(let b=0;b<P.length;b++){let D=P.slice(0,b+1).join("/")+"/";A.add(D)}}for(let k of A)if(!(k in i)){let P=new fu(x);P.entryName=k,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,h.add(P)}}function y(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/Ve.Constants.CENHDR)throw Ve.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(c.diskEntries);for(var A=c.offset,k=0;k<n.length;k++){var P=A,b=new fu(x,t);b.header=t.slice(P,P+=Ve.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,n[k]=b,i[b.entryName]=b}h.clear(),S()}function v(A){var k=t.length-Ve.Constants.ENDHDR,P=Math.max(0,k-65535),b=P,D=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),k;k>=b;k--)if(t[k]===80){if(t.readUInt32LE(k)===Ve.Constants.ENDSIG){O=k,F=k,D=k+Ve.Constants.ENDHDR,b=k-Ve.Constants.END64HDR;continue}if(t.readUInt32LE(k)===Ve.Constants.END64SIG){b=P;continue}if(t.readUInt32LE(k)===Ve.Constants.ZIP64SIG){O=k,D=k+Ve.readBigUInt64LE(t,k+Ve.Constants.ZIP64SIZE)+Ve.Constants.ZIP64LEAD;break}}if(O==-1)throw Ve.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,D)),c.commentLength&&(s=t.slice(F+Ve.Constants.ENDHDR)),A&&y()}function I(){n.length>1&&!m&&n.sort((A,k)=>A.entryName.toLowerCase().localeCompare(k.entryName.toLowerCase()))}return{get entries(){return d||y(),n.filter(A=>!h.has(A))},get comment(){return _.decode(s)},set comment(A){s=Ve.toBuffer(A,_.encode),c.commentLength=s.length},getEntryCount:function(){return d?n.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||y(),i[A]||null},setEntry:function(A){d||y(),n.push(A),i[A.entryName]=A,c.totalEntries=n.length},deleteFile:function(A,k=!0){d||y();let P=i[A];this.getEntryChildren(P,k).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let k=i[A],P=n.indexOf(k);P>=0&&(n.splice(P,1),delete i[A],c.totalEntries=n.length)},getEntryChildren:function(A,k=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&k){let P=[],b=A.entryName;for(let D of n)D.entryName.startsWith(b)&&P.push(D);return P}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let k=this.getEntryChildren(A);return k.includes(A)?k.length-1:k.length}return 0},compressToBuffer:function(){d||y(),I();let A=[],k=[],P=0,b=0;c.size=0,c.offset=0;let D=0;for(let B of this.entries){let V=B.getCompressedData();B.header.offset=b;let K=B.packLocalHeader(),te=K.length+V.length;b+=te,A.push(K),A.push(V);let Z=B.packCentralHeader();k.push(Z),c.size+=Z.length,P+=te+Z.length,D++}P+=c.mainHeaderSize,c.offset=b,c.totalEntries=D,b=0;let O=Buffer.alloc(P);for(let B of A)B.copy(O,b),b+=B.length;for(let B of k)B.copy(O,b),b+=B.length;let F=c.toBinary();return s&&s.copy(F,Ve.Constants.ENDHDR),F.copy(O,b),t=O,d=!1,O},toAsyncBuffer:function(A,k,P,b){try{d||y(),I();let D=[],O=[],F=0,B=0,V=0;c.size=0,c.offset=0;let K=function(te){if(te.length>0){let Z=te.shift(),ae=Z.entryName+Z.extra.toString();P&&P(ae),Z.getCompressedDataAsync(function(ce){b&&b(ae),Z.header.offset=B;let R=Z.packLocalHeader(),U=R.length+ce.length;B+=U,D.push(R),D.push(ce);let j=Z.packCentralHeader();O.push(j),c.size+=j.length,F+=U+j.length,V++,K(te)})}else{F+=c.mainHeaderSize,c.offset=B,c.totalEntries=V,B=0;let Z=Buffer.alloc(F);D.forEach(function(ce){ce.copy(Z,B),B+=ce.length}),O.forEach(function(ce){ce.copy(Z,B),B+=ce.length});let ae=c.toBinary();s&&s.copy(ae,Ve.Constants.ENDHDR),ae.copy(Z,B),t=Z,d=!1,A(Z)}};K(Array.from(this.entries))}catch(D){k(D)}}}}});var mu=de((cI,gu)=>{var Ie=pr(),Se=he("path"),Am=za(),Tm=xu(),Nn=(...t)=>Ie.findLast(t,e=>typeof e=="boolean"),pu=(...t)=>Ie.findLast(t,e=>typeof e=="string"),km=(...t)=>Ie.findLast(t,e=>typeof e=="function"),Cm={noSort:!1,readEntries:!1,method:Ie.Constants.NONE,fs:null};gu.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),Cm);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)&&(n=t,i.method=Ie.Constants.BUFFER,t=void 0)),Object.assign(i,e);let s=new Ie(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ie.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))i.method=Ie.Constants.FILE,i.filename=t,n=s.fs.readFileSync(t);else throw Ie.Errors.INVALID_FILENAME();let c=new Tm(n,i),{canonical:d,sanitize:u,zipnamefix:h}=Ie;function x(y){if(y&&c){var v;if(typeof y=="string"&&(v=c.getEntry(Se.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(v=c.getEntry(y.entryName)),v)return v}return null}function m(y){let{join:v,normalize:I,sep:A}=Se.posix;return v(Se.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function _(y){return y instanceof RegExp?(function(v){return function(I){return v.test(I)}})(y):typeof y!="function"?()=>!0:y}let S=(y,v)=>{let I=v.slice(-1);return I=I===s.sep?s.sep:"",Se.relative(y,v)+I};return{readFile:function(y,v){var I=x(y);return I&&I.getData(v)||null},childCount:function(y){let v=x(y);if(v)return c.getChildCount(v)},readFileAsync:function(y,v){var I=x(y);I?I.getDataAsync(v):v(null,"getEntry failed for:"+y)},readAsText:function(y,v){var I=x(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(y,v,I){var A=x(y);A?A.getDataAsync(function(k,P){if(P){v(k,P);return}k&&k.length?v(k.toString(I||"utf8")):v("")}):v("")},deleteFile:function(y,v=!0){var I=x(y);I&&c.deleteFile(I.entryName,v)},deleteEntry:function(y){var v=x(y);v&&c.deleteEntry(v.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,v){var I=x(y);I&&(I.comment=v)},getZipEntryComment:function(y){var v=x(y);return v&&v.comment||""},updateFile:function(y,v){var I=x(y);I&&I.setData(v)},addLocalFile:function(y,v,I,A){if(s.fs.existsSync(y)){v=v?m(v):"";let k=Se.win32.basename(Se.win32.normalize(y));v+=I||k;let P=s.fs.statSync(y),b=P.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);P.isDirectory()&&(v+=s.sep),this.addFile(v,b,A,P)}else throw Ie.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,v){y=typeof y=="object"?y:{localPath:y};let I=Se.resolve(y.localPath),{comment:A}=y,{zipPath:k,zipName:P}=y,b=this;s.fs.stat(I,function(D,O){if(D)return v(D,!1);k=k?m(k):"";let F=Se.win32.basename(Se.win32.normalize(I));if(k+=P||F,O.isFile())s.fs.readFile(I,function(B,V){return B?v(B,!1):(b.addFile(k,V,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return k+=s.sep,b.addFile(k,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(y,v,I){if(I=_(I),v=v?m(v):"",y=Se.normalize(y),s.fs.existsSync(y)){let A=s.findFiles(y),k=this;if(A.length)for(let P of A){let b=Se.join(v,S(y,P));I(b)&&k.addLocalFile(P,Se.dirname(b))}}else throw Ie.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,v,I,A){A=_(A),I=I?m(I):"",y=Se.normalize(y);var k=this;s.fs.open(y,"r",function(P){if(P&&P.code==="ENOENT")v(void 0,Ie.Errors.FILE_NOT_FOUND(y));else if(P)v(void 0,P);else{var b=s.findFiles(y),D=-1,O=function(){if(D+=1,D<b.length){var F=b[D],B=S(y,F).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(B)?s.fs.stat(F,function(V,K){V&&v(void 0,V),K.isFile()?s.fs.readFile(F,function(te,Z){te?v(void 0,te):(k.addFile(I+B,Z,"",K),O())}):(k.addFile(I+B+"/",Buffer.alloc(0),"",K),O())}):process.nextTick(()=>{O()})}else v(!0,void 0)};O()}})},addLocalFolderAsync2:function(y,v){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=Se.resolve(m(y.localPath));let{zipPath:A,filter:k,namefix:P}=y;k instanceof RegExp?k=(function(O){return function(F){return O.test(F)}})(k):typeof k!="function"&&(k=function(){return!0}),A=A?m(A):"",P=="latin1"&&(P=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=O=>O);let b=O=>Se.join(A,P(S(localPath,O))),D=O=>Se.win32.basename(Se.win32.normalize(P(O)));s.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?v(void 0,Ie.Errors.FILE_NOT_FOUND(localPath)):O?v(void 0,O):s.findFilesAsync(localPath,function(F,B){if(F)return v(F);B=B.filter(V=>k(b(V))),B.length||v(void 0,!1),setImmediate(B.reverse().reduce(function(V,K){return function(te,Z){if(te||Z===!1)return setImmediate(V,te,!1);I.addLocalFileAsync({localPath:K,zipPath:Se.dirname(b(K)),zipName:D(K)},V)}},v))})})},addLocalFolderPromise:function(y,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},v),(k,P)=>{k&&A(k),P&&I(this)})})},addFile:function(y,v,I,A){y=h(y);let k=x(y),P=k!=null;P||(k=new Am(i),k.entryName=y),k.comment=I||"";let b=typeof A=="object"&&A instanceof s.fs.Stats;b&&(k.header.time=A.mtime);var D=k.isDirectory?16:0;let O=k.isDirectory?16384:32768;return b?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=k.isDirectory?493:420,D=(D|O<<16)>>>0,k.attr=D,k.setData(v),P||c.setEntry(k),k},getEntries:function(y){return c.password=y,c?c.entries:[]},getEntry:function(y){return x(y)},getEntryCount:function(){return c.getEntryCount()},forEach:function(y){return c.forEach(y)},extractEntryTo:function(y,v,I,A,k,P){A=Nn(!1,A),k=Nn(!1,k),I=Nn(!0,I),P=pu(k,P);var b=x(y);if(!b)throw Ie.Errors.NO_ENTRY();var D=d(b.entryName),O=u(v,P&&!b.isDirectory?P:I?D:Se.basename(D));if(b.isDirectory){var F=c.getEntryChildren(b);return F.forEach(function(K){if(K.isDirectory)return;var te=K.getData();if(!te)throw Ie.Errors.CANT_EXTRACT_FILE();var Z=d(K.entryName),ae=u(v,I?Z:Se.basename(Z));let ce=k?K.header.fileAttr:void 0;s.writeFileTo(ae,te,A,ce)}),!0}var B=b.getData(c.password);if(!B)throw Ie.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(O)&&!A)throw Ie.Errors.CANT_OVERRIDE();let V=k?y.header.fileAttr:void 0;return s.writeFileTo(O,B,A,V),!0},test:function(y){if(!c)return!1;for(var v in c.entries)try{if(v.isDirectory)continue;var I=c.entries[v].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,v,I,A){if(I=Nn(!1,I),A=pu(I,A),v=Nn(!1,v),!c)throw Ie.Errors.NO_ZIP();c.entries.forEach(function(k){var P=u(y,d(k.entryName));if(k.isDirectory){s.makeDir(P);return}var b=k.getData(A);if(!b)throw Ie.Errors.CANT_EXTRACT_FILE();let D=I?k.header.fileAttr:void 0;s.writeFileTo(P,b,v,D);try{s.fs.utimesSync(P,k.header.time,k.header.time)}catch{throw Ie.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,v,I,A){if(A=km(v,I,A),I=Nn(!1,I),v=Nn(!1,v),!A)return new Promise((O,F)=>{this.extractAllToAsync(y,v,I,function(B){B?F(B):O(this)})});if(!c){A(Ie.Errors.NO_ZIP());return}y=Se.resolve(y);let k=O=>u(y,Se.normalize(d(O.entryName))),P=(O,F)=>new Error(O+': "'+F+'"'),b=[],D=[];c.entries.forEach(O=>{O.isDirectory?b.push(O):D.push(O)});for(let O of b){let F=k(O),B=I?O.header.fileAttr:void 0;try{s.makeDir(F),B&&s.fs.chmodSync(F,B),s.fs.utimesSync(F,O.header.time,O.header.time)}catch{A(P("Unable to create folder",F))}}D.reverse().reduce(function(O,F){return function(B){if(B)O(B);else{let V=Se.normalize(d(F.entryName)),K=u(y,V);F.getDataAsync(function(te,Z){if(Z)O(Z);else if(!te)O(Ie.Errors.CANT_EXTRACT_FILE());else{let ae=I?F.header.fileAttr:void 0;s.writeFileToAsync(K,te,v,ae,function(ce){ce||O(P("Unable to write file",K)),s.fs.utimes(K,F.header.time,F.header.time,function(R){R?O(P("Unable to set times",K)):O()})})}})}}},A)()},writeZip:function(y,v){if(arguments.length===1&&typeof y=="function"&&(v=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=s.writeFileTo(y,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((k,P)=>{!y&&i.filename&&(y=i.filename),y||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let D=O=>O?k(O):P("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(y,b,I,A,D)},P)})},toBufferPromise:function(){return new Promise((y,v)=>{c.toAsyncBuffer(y,v)})},toBuffer:function(y,v,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,v,I,A),null):c.compressToBuffer()}}}});import{execFile as N_,spawn as M_,spawnSync as AA}from"node:child_process";import{promisify as B_}from"node:util";function z_(t){if(process.platform!=="win32")return!1;if(Bf.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(Bf,"").toLowerCase();return F_.has(n)}function Ff(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return z_(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function st(t,e=[],n={}){return M_(t,e,Ff(t,n))}function zf(t,e=[],n={}){return U_(t,e,Ff(t,n))}var F_,Bf,U_,Zt=rt(()=>{"use strict";F_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Bf=/\.(cmd|bat|ps1)$/i;U_=B_(N_)});var Xt=de((aD,yh)=>{"use strict";var wh=["nodebuffer","arraybuffer","fragments"],_h=typeof Blob<"u";_h&&wh.push("blob");yh.exports={BINARY_TYPES:wh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:_h,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Zi=de((cD,Ro)=>{"use strict";var{EMPTY_BUFFER:pE}=Xt(),gd=Buffer[Symbol.species];function gE(t,e){if(t.length===0)return pE;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let s=0;s<t.length;s++){let c=t[s];n.set(c,i),i+=c.length}return i<e?new gd(n.buffer,n.byteOffset,i):n}function bh(t,e,n,i,s){for(let c=0;c<s;c++)n[i+c]=t[c]^e[c&3]}function Eh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function mE(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function md(t){if(md.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new gd(t):ArrayBuffer.isView(t)?e=new gd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),md.readOnly=!1),e}Ro.exports={concat:gE,mask:bh,toArrayBuffer:mE,toBuffer:md,unmask:Eh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=he("bufferutil");Ro.exports.mask=function(e,n,i,s,c){c<48?bh(e,n,i,s,c):t.mask(e,n,i,s,c)},Ro.exports.unmask=function(e,n){e.length<32?Eh(e,n):t.unmask(e,n)}}catch{}});var Ih=de((dD,Sh)=>{"use strict";var vh=Symbol("kDone"),wd=Symbol("kRun"),_d=class{constructor(e){this[vh]=()=>{this.pending--,this[wd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[wd]()}[wd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[vh])}}};Sh.exports=_d});var qr=de((lD,Ch)=>{"use strict";var Yi=he("zlib"),Ah=Zi(),wE=Ih(),{kStatusCode:Th}=Xt(),_E=Buffer[Symbol.species],yE=Buffer.from([0,0,255,255]),Oo=Symbol("permessage-deflate"),Qt=Symbol("total-length"),Ur=Symbol("callback"),Dn=Symbol("buffers"),Gr=Symbol("error"),Po,yd=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,!Po){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Po=new wE(n)}}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[Ur];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let s=n[i];if(s.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(s=s[0],i==="client_max_window_bits"){if(s!==!0){let c=+s;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let c=+s;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=s})}),e}decompress(e,n,i){Po.add(s=>{this._decompress(e,n,(c,d)=>{s(),i(c,d)})})}compress(e,n,i){Po.add(s=>{this._compress(e,n,(c,d)=>{s(),i(c,d)})})}_decompress(e,n,i){let s=this._isServer?"client":"server";if(!this._inflate){let c=`${s}_max_window_bits`,d=typeof this.params[c]!="number"?Yi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Yi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Oo]=this,this._inflate[Qt]=0,this._inflate[Dn]=[],this._inflate.on("error",EE),this._inflate.on("data",kh)}this._inflate[Ur]=i,this._inflate.write(e),n&&this._inflate.write(yE),this._inflate.flush(()=>{let c=this._inflate[Gr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Ah.concat(this._inflate[Dn],this._inflate[Qt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Qt]=0,this._inflate[Dn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let s=this._isServer?"server":"client";if(!this._deflate){let c=`${s}_max_window_bits`,d=typeof this.params[c]!="number"?Yi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Yi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Qt]=0,this._deflate[Dn]=[],this._deflate.on("data",bE)}this._deflate[Ur]=i,this._deflate.write(e),this._deflate.flush(Yi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Ah.concat(this._deflate[Dn],this._deflate[Qt]);n&&(c=new _E(c.buffer,c.byteOffset,c.length-4)),this._deflate[Ur]=null,this._deflate[Qt]=0,this._deflate[Dn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Ch.exports=yd;function bE(t){this[Dn].push(t),this[Qt]+=t.length}function kh(t){if(this[Qt]+=t.length,this[Oo]._maxPayload<1||this[Qt]<=this[Oo]._maxPayload){this[Dn].push(t);return}this[Gr]=new RangeError("Max payload size exceeded"),this[Gr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Gr][Th]=1009,this.removeListener("data",kh),this.reset()}function EE(t){if(this[Oo]._inflate=null,this[Gr]){this[Ur](this[Gr]);return}t[Th]=1007,this[Ur](t)}});var Hr=de((uD,Lo)=>{"use strict";var{isUtf8:Dh}=he("buffer"),{hasBlob:vE}=Xt(),SE=[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 IE(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function bd(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function AE(t){return vE&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Lo.exports={isBlob:AE,isValidStatusCode:IE,isValidUTF8:bd,tokenChars:SE};if(Dh)Lo.exports.isValidUTF8=function(t){return t.length<24?bd(t):Dh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=he("utf-8-validate");Lo.exports.isValidUTF8=function(e){return e.length<32?bd(e):t(e)}}catch{}});var Ad=de((fD,Bh)=>{"use strict";var{Writable:TE}=he("stream"),Rh=qr(),{BINARY_TYPES:kE,EMPTY_BUFFER:Ph,kStatusCode:CE,kWebSocket:DE}=Xt(),{concat:Ed,toArrayBuffer:RE,unmask:PE}=Zi(),{isValidStatusCode:OE,isValidUTF8:Oh}=Hr(),No=Buffer[Symbol.species],pt=0,Lh=1,Nh=2,Mh=3,vd=4,Sd=5,Mo=6,Id=class extends TE{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||kE[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[DE]=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=pt}_write(e,n,i){if(this._opcode===8&&this._state==pt)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 No(i.buffer,i.byteOffset+e,i.length-e),new No(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],s=n.length-e;e>=i.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),s),this._buffers[0]=new No(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case pt:this.getInfo(e);break;case Lh:this.getPayloadLength16(e);break;case Nh:this.getPayloadLength64(e);break;case Mh:this.getMask();break;case vd:this.getData(e);break;case Sd:case Mo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let i=(n[0]&64)===64;if(i&&!this._extensions[Rh.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Lh:this._payloadLength===127?this._state=Nh: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 n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=i*Math.pow(2,32)+n.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 n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Mh:this._state=vd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vd}getData(e){let n=Ph;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&PE(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Sd,this.decompress(n,e);return}if(n.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(n)}this.dataMessage(e)}decompress(e,n){this._extensions[Rh.extensionName].decompress(e,this._fin,(s,c)=>{if(s)return n(s);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");n(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");n(d);return}this._fragments.push(c)}this.dataMessage(n),this._state===pt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=pt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ed(i,n):this._binaryType==="arraybuffer"?s=RE(Ed(i,n)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=pt):(this._state=Mo,setImmediate(()=>{this.emit("message",s,!0),this._state=pt,this.startLoop(e)}))}else{let s=Ed(i,n);if(!this._skipUTF8Validation&&!Oh(s)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Sd||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=pt):(this._state=Mo,setImmediate(()=>{this.emit("message",s,!1),this._state=pt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ph),this.end();else{let i=e.readUInt16BE(0);if(!OE(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(c);return}let s=new No(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Oh(s)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(c);return}this._loop=!1,this.emit("conclude",i,s),this.end()}this._state=pt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=pt):(this._state=Mo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=pt,this.startLoop(n)}))}createError(e,n,i,s,c){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=c,d[CE]=s,d}};Bh.exports=Id});var Cd=de((xD,Uh)=>{"use strict";var{Duplex:hD}=he("stream"),{randomFillSync:LE}=he("crypto"),{types:{isUint8Array:NE}}=he("util"),Fh=qr(),{EMPTY_BUFFER:ME,kWebSocket:BE,NOOP:FE}=Xt(),{isBlob:jr,isValidStatusCode:zE}=Hr(),{mask:zh,toBuffer:Yn}=Zi(),gt=Symbol("kByteLength"),UE=Buffer.alloc(4),Bo=8*1024,Xn,Wr=Bo,It=0,GE=1,qE=2,Td=class t{constructor(e,n,i){this._extensions=n||{},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=It,this.onerror=FE,this[BE]=void 0}static frame(e,n){let i,s=!1,c=2,d=!1;n.mask&&(i=n.maskBuffer||UE,n.generateMask?n.generateMask(i):(Wr===Bo&&(Xn===void 0&&(Xn=Buffer.alloc(Bo)),LE(Xn,0,Bo),Wr=0),i[0]=Xn[Wr++],i[1]=Xn[Wr++],i[2]=Xn[Wr++],i[3]=Xn[Wr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!n.mask||d)&&n[gt]!==void 0?u=n[gt]:(e=Buffer.from(e),u=e.length):(u=e.length,s=n.mask&&n.readOnly&&!d);let h=u;u>=65536?(c+=8,h=127):u>125&&(c+=2,h=126);let x=Buffer.allocUnsafe(s?u+c:c);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.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]:s?(zh(e,i,x,c,u),[x]):(zh(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,s){let c;if(e===void 0)c=ME;else{if(typeof e!="number"||!zE(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);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 n=="string")c.write(n,2);else if(NE(n))c.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[gt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==It?this.enqueue([this.dispatch,c,!1,d,s]):this.sendFrame(t.frame(c,d),s)}ping(e,n,i){let s,c;if(typeof e=="string"?(s=Buffer.byteLength(e),c=!1):jr(e)?(s=e.size,c=!1):(e=Yn(e),s=e.length,c=Yn.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[gt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};jr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let s,c;if(typeof e=="string"?(s=Buffer.byteLength(e),c=!1):jr(e)?(s=e.size,c=!1):(e=Yn(e),s=e.length,c=Yn.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[gt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};jr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let s=this._extensions[Fh.extensionName],c=n.binary?2:1,d=n.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):jr(e)?(u=e.size,h=!1):(e=Yn(e),u=e.length,h=Yn.readOnly),this._firstFragment?(this._firstFragment=!1,d&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=s._threshold),this._compress=d):(d=!1,c=0),n.fin&&(this._firstFragment=!0);let x={[gt]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:d};jr(e)?this._state!==It?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==It?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,s){this._bufferedBytes+=i[gt],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(kd,this,u,s);return}this._bufferedBytes-=i[gt];let d=Yn(c);n?this.dispatch(d,n,i,s):(this._state=It,this.sendFrame(t.frame(d,i),s),this.dequeue())}).catch(c=>{process.nextTick(HE,this,c,s)})}dispatch(e,n,i,s){if(!n){this.sendFrame(t.frame(e,i),s);return}let c=this._extensions[Fh.extensionName];this._bufferedBytes+=i[gt],this._state=GE,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");kd(this,h,s);return}this._bufferedBytes-=i[gt],this._state=It,i.readOnly=!1,this.sendFrame(t.frame(u,i),s),this.dequeue()})}dequeue(){for(;this._state===It&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][gt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][gt],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Uh.exports=Td;function kd(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let s=t._queue[i],c=s[s.length-1];typeof c=="function"&&c(e)}}function HE(t,e,n){kd(t,e,n),t.onerror(e)}});var Jh=de((pD,Vh)=>{"use strict";var{kForOnEventAttribute:Xi,kListener:Dd}=Xt(),Gh=Symbol("kCode"),qh=Symbol("kData"),Hh=Symbol("kError"),jh=Symbol("kMessage"),Wh=Symbol("kReason"),Kr=Symbol("kTarget"),Kh=Symbol("kType"),$h=Symbol("kWasClean"),en=class{constructor(e){this[Kr]=null,this[Kh]=e}get target(){return this[Kr]}get type(){return this[Kh]}};Object.defineProperty(en.prototype,"target",{enumerable:!0});Object.defineProperty(en.prototype,"type",{enumerable:!0});var Qn=class extends en{constructor(e,n={}){super(e),this[Gh]=n.code===void 0?0:n.code,this[Wh]=n.reason===void 0?"":n.reason,this[$h]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Gh]}get reason(){return this[Wh]}get wasClean(){return this[$h]}};Object.defineProperty(Qn.prototype,"code",{enumerable:!0});Object.defineProperty(Qn.prototype,"reason",{enumerable:!0});Object.defineProperty(Qn.prototype,"wasClean",{enumerable:!0});var $r=class extends en{constructor(e,n={}){super(e),this[Hh]=n.error===void 0?null:n.error,this[jh]=n.message===void 0?"":n.message}get error(){return this[Hh]}get message(){return this[jh]}};Object.defineProperty($r.prototype,"error",{enumerable:!0});Object.defineProperty($r.prototype,"message",{enumerable:!0});var Qi=class extends en{constructor(e,n={}){super(e),this[qh]=n.data===void 0?null:n.data}get data(){return this[qh]}};Object.defineProperty(Qi.prototype,"data",{enumerable:!0});var jE={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Xi]&&s[Dd]===e&&!s[Xi])return;let i;if(t==="message")i=function(c,d){let u=new Qi("message",{data:d?c:c.toString()});u[Kr]=this,Fo(e,this,u)};else if(t==="close")i=function(c,d){let u=new Qn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Kr]=this,Fo(e,this,u)};else if(t==="error")i=function(c){let d=new $r("error",{error:c,message:c.message});d[Kr]=this,Fo(e,this,d)};else if(t==="open")i=function(){let c=new en("open");c[Kr]=this,Fo(e,this,c)};else return;i[Xi]=!!n[Xi],i[Dd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Dd]===e&&!n[Xi]){this.removeListener(t,n);break}}};Vh.exports={CloseEvent:Qn,ErrorEvent:$r,Event:en,EventTarget:jE,MessageEvent:Qi};function Fo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var zo=de((gD,Zh)=>{"use strict";var{tokenChars:es}=Hr();function Bt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function WE(t){let e=Object.create(null),n=Object.create(null),i=!1,s=!1,c=!1,d,u,h=-1,x=-1,m=-1,_=0;for(;_<t.length;_++)if(x=t.charCodeAt(_),d===void 0)if(m===-1&&es[x]===1)h===-1&&(h=_);else if(_!==0&&(x===32||x===9))m===-1&&h!==-1&&(m=_);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_);let y=t.slice(h,m);x===44?(Bt(e,y,n),n=Object.create(null)):d=y,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(u===void 0)if(m===-1&&es[x]===1)h===-1&&(h=_);else if(x===32||x===9)m===-1&&h!==-1&&(m=_);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_),Bt(n,t.slice(h,m),!0),x===44&&(Bt(e,d,n),n=Object.create(null),d=void 0),h=m=-1}else if(x===61&&h!==-1&&m===-1)u=t.slice(h,_),h=m=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(s){if(es[x]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);h===-1?h=_:i||(i=!0),s=!1}else if(c)if(es[x]===1)h===-1&&(h=_);else if(x===34&&h!==-1)c=!1,m=_;else if(x===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(x===34&&t.charCodeAt(_-1)===61)c=!0;else if(m===-1&&es[x]===1)h===-1&&(h=_);else if(h!==-1&&(x===32||x===9))m===-1&&(m=_);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_);let y=t.slice(h,m);i&&(y=y.replace(/\\/g,""),i=!1),Bt(n,u,y),x===44&&(Bt(e,d,n),n=Object.create(null),d=void 0),u=void 0,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=_);let S=t.slice(h,m);return d===void 0?Bt(e,S,n):(u===void 0?Bt(n,S,!0):i?Bt(n,u,S.replace(/\\/g,"")):Bt(n,u,S),Bt(e,d,n)),e}function KE(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(s=>{let c=i[s];return Array.isArray(c)||(c=[c]),c.map(d=>d===!0?s:`${s}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Zh.exports={format:KE,parse:WE}});var Ho=de((_D,cx)=>{"use strict";var $E=he("events"),VE=he("https"),JE=he("http"),Qh=he("net"),ZE=he("tls"),{randomBytes:YE,createHash:XE}=he("crypto"),{Duplex:mD,Readable:wD}=he("stream"),{URL:Rd}=he("url"),Rn=qr(),QE=Ad(),ev=Cd(),{isBlob:tv}=Hr(),{BINARY_TYPES:Yh,CLOSE_TIMEOUT:nv,EMPTY_BUFFER:Uo,GUID:rv,kForOnEventAttribute:Pd,kListener:iv,kStatusCode:sv,kWebSocket:We,NOOP:ex}=Xt(),{EventTarget:{addEventListener:ov,removeEventListener:av}}=Jh(),{format:cv,parse:dv}=zo(),{toBuffer:lv}=Zi(),tx=Symbol("kAborted"),Od=[8,13],tn=["CONNECTING","OPEN","CLOSING","CLOSED"],uv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,be=class t extends $E{constructor(e,n,i){super(),this._binaryType=Yh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Uo,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,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),nx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yh.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,n,i){let s=new QE({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 ev(e,this._extensions,i.generateMask);this._receiver=s,this._sender=c,this._socket=e,s[We]=this,c[We]=this,e[We]=this,s.on("conclude",xv),s.on("drain",pv),s.on("error",gv),s.on("message",mv),s.on("ping",wv),s.on("pong",_v),c.onerror=yv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",sx),e.on("data",qo),e.on("end",ox),e.on("error",ax),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[Rn.extensionName]&&this._extensions[Rn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(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,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ix(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ld(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Uo,n,i)}pong(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ld(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Uo,n,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ld(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Rn.extensionName]||(s.compress=!1),this._sender.send(e||Uo,s,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(be,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(be.prototype,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(be,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(be.prototype,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(be,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(be.prototype,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(be,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});Object.defineProperty(be.prototype,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(be.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(be.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Pd])return e[iv];return null},set(e){for(let n of this.listeners(t))if(n[Pd]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Pd]:!0})}})});be.prototype.addEventListener=ov;be.prototype.removeEventListener=av;cx.exports=be;function nx(t,e,n,i){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:nv,protocolVersion:Od[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=s.autoPong,t._closeTimeout=s.closeTimeout,!Od.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Od.join(", ")})`);let c;if(e instanceof Rd)c=e;else try{c=new Rd(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:",h;if(c.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?h="The URL's pathname is empty":c.hash&&(h="The URL contains a fragment identifier"),h){let I=new SyntaxError(h);if(t._redirects===0)throw I;Go(t,I);return}let x=d?443:80,m=YE(16).toString("base64"),_=d?VE.request:JE.request,S=new Set,y;if(s.createConnection=s.createConnection||(d?hv:fv),s.defaultPort=s.defaultPort||x,s.port=c.port||x,s.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},s.path=c.pathname+c.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(y=new Rn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=cv({[Rn.extensionName]:y.offer()})),n.length){for(let I of n){if(typeof I!="string"||!uv.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(c.username||c.password)&&(s.auth=`${c.username}:${c.password}`),u){let I=s.path.split(":");s.socketPath=I[0],s.path=I[1]}let v;if(s.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?s.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,k]of Object.entries(I))i.headers[A.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete s.headers.authorization,delete s.headers.cookie,I||delete s.headers.host,s.auth=void 0)}s.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),v=t._req=_(s),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=_(s);s.timeout&&v.on("timeout",()=>{dt(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[tx]||(v=t._req=null,Go(t,I))}),v.on("response",I=>{let A=I.headers.location,k=I.statusCode;if(A&&s.followRedirects&&k>=300&&k<400){if(++t._redirects>s.maxRedirects){dt(t,v,"Maximum redirects exceeded");return}v.abort();let P;try{P=new Rd(A,e)}catch{let D=new SyntaxError(`Invalid URL: ${A}`);Go(t,D);return}nx(t,P,n,i)}else t.emit("unexpected-response",v,I)||dt(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,k)=>{if(t.emit("upgrade",I),t.readyState!==be.CONNECTING)return;v=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){dt(t,A,"Invalid Upgrade header");return}let b=XE("sha1").update(m+rv).digest("base64");if(I.headers["sec-websocket-accept"]!==b){dt(t,A,"Invalid Sec-WebSocket-Accept header");return}let D=I.headers["sec-websocket-protocol"],O;if(D!==void 0?S.size?S.has(D)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":S.size&&(O="Server sent no subprotocol"),O){dt(t,A,O);return}D&&(t._protocol=D);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!y){dt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=dv(F)}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(B);if(V.length!==1||V[0]!==Rn.extensionName){dt(t,A,"Server indicated an extension that was not requested");return}try{y.accept(B[Rn.extensionName])}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Rn.extensionName]=y}t.setSocket(A,k,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(v,t):v.end()}function Go(t,e){t._readyState=be.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function fv(t){return t.path=t.socketPath,Qh.connect(t)}function hv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Qh.isIP(t.host)?"":t.host),ZE.connect(t)}function dt(t,e,n){t._readyState=be.CLOSING;let i=new Error(n);Error.captureStackTrace(i,dt),e.setHeader?(e[tx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Go,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ld(t,e,n){if(e){let i=tv(e)?e.size:lv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${tn[t.readyState]})`);process.nextTick(n,i)}}function xv(t,e){let n=this[We];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[We]!==void 0&&(n._socket.removeListener("data",qo),process.nextTick(rx,n._socket),t===1005?n.close():n.close(t,e))}function pv(){let t=this[We];t.isPaused||t._socket.resume()}function gv(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",qo),process.nextTick(rx,e._socket),e.close(t[sv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Xh(){this[We].emitClose()}function mv(t,e){this[We].emit("message",t,e)}function wv(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,ex),e.emit("ping",t)}function _v(t){this[We].emit("pong",t)}function rx(t){t.resume()}function yv(t){let e=this[We];e.readyState!==be.CLOSED&&(e.readyState===be.OPEN&&(e._readyState=be.CLOSING,ix(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ix(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function sx(){let t=this[We];if(this.removeListener("close",sx),this.removeListener("data",qo),this.removeListener("end",ox),t._readyState=be.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[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Xh),t._receiver.on("finish",Xh))}function qo(t){this[We]._receiver.write(t)||this.pause()}function ox(){let t=this[We];t._readyState=be.CLOSING,t._receiver.end(),this.end()}function ax(){let t=this[We];this.removeListener("error",ax),this.on("error",ex),t&&(t._readyState=be.CLOSING,this.destroy())}});var fx=de((bD,ux)=>{"use strict";var yD=Ho(),{Duplex:bv}=he("stream");function dx(t){t.emit("close")}function Ev(){!this.destroyed&&this._writableState.finished&&this.destroy()}function lx(t){this.removeListener("error",lx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function vv(t,e){let n=!0,i=new bv({...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||(n=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,c){if(t.readyState===t.CLOSED){c(s),process.nextTick(dx,i);return}let d=!1;t.once("error",function(h){d=!0,c(h)}),t.once("close",function(){d||c(s),process.nextTick(dx,i)}),n&&t.terminate()},i._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(s,c,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(s,c,d)});return}t.send(s,d)},i.on("end",Ev),i.on("error",lx),i}ux.exports=vv});var Nd=de((ED,hx)=>{"use strict";var{tokenChars:Sv}=Hr();function Iv(t){let e=new Set,n=-1,i=-1,s=0;for(s;s<t.length;s++){let d=t.charCodeAt(s);if(i===-1&&Sv[d]===1)n===-1&&(n=s);else if(s!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=s);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);i===-1&&(i=s);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(n,s);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}hx.exports={parse:Iv}});var bx=de((SD,yx)=>{"use strict";var Av=he("events"),jo=he("http"),{Duplex:vD}=he("stream"),{createHash:Tv}=he("crypto"),xx=zo(),er=qr(),kv=Nd(),Cv=Ho(),{CLOSE_TIMEOUT:Dv,GUID:Rv,kWebSocket:Pv}=Xt(),Ov=/^[+/0-9A-Za-z]{22}==$/,px=0,gx=1,_x=2,Md=class extends Av{constructor(e,n){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:Dv,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=jo.createServer((i,s)=>{let c=jo.STATUS_CODES[426];s.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),s.end(c)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=Lv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,c,d)=>{this.handleUpgrade(s,c,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=px}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===_x){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ts,this);return}if(e&&this.once("close",e),this._state!==gx)if(this._state=gx,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(ts,this):process.nextTick(ts,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ts(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,s){n.on("error",mx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){tr(this,e,n,400,"Invalid Upgrade header");return}if(c===void 0||!Ov.test(c)){tr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){tr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ns(n,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=kv.parse(h)}catch{tr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&m!==void 0){let S=new er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=xx.parse(m);y[er.extensionName]&&(S.accept(y[er.extensionName]),_[er.extensionName]=S)}catch{tr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={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(S,(y,v,I,A)=>{if(!y)return ns(n,v||401,I,A);this.completeUpgrade(_,c,x,e,n,i,s)});return}if(!this.options.verifyClient(S))return ns(n,401)}this.completeUpgrade(_,c,x,e,n,i,s)}completeUpgrade(e,n,i,s,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[Pv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>px)return ns(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Tv("sha1").update(n+Rv).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let _=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;_&&(x.push(`Sec-WebSocket-Protocol: ${_}`),m._protocol=_)}if(e[er.extensionName]){let _=e[er.extensionName].params,S=xx.format({[er.extensionName]:[_]});x.push(`Sec-WebSocket-Extensions: ${S}`),m._extensions=e}this.emit("headers",x,s),c.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",gx),g.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(g),g.on("close",()=>{this.clients.delete(g),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Xi,this)})),u(g,o)}};_x.exports=Od;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=mx,t.emit("close")}function gx(){this.destroy()}function Qi(t,e,r,i){r=r||Uo.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} ${Uo.STATUS_CODES[e]}\r
17
- `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
16
+ `)),c.removeListener("error",mx),m.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(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ts,this)})),u(m,s)}};yx.exports=Md;function Lv(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function ts(t){t._state=_x,t.emit("close")}function mx(){this.destroy()}function ns(t,e,n,i){n=n||jo.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${jo.STATUS_CODES[e]}\r
17
+ `+Object.keys(i).map(s=>`${s}: ${i[s]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+r)}function Xn(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let l=new Error(o);Error.captureStackTrace(l,Xn),t.emit("wsClientError",l,r,e)}else Qi(r,i,o,c)}});var Ox=ae(Me=>{"use strict";var N=j;(function(t,e){let r=j,i=t();for(;;)try{if(parseInt(r(629))/1*(-parseInt(r(225))/2)+parseInt(r(1565))/3+parseInt(r(621))/4*(parseInt(r(1447))/5)+-parseInt(r(822))/6+parseInt(r(459))/7*(-parseInt(r(241))/8)+parseInt(r(1460))/9+parseInt(r(1354))/10*(parseInt(r(1232))/11)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(jo,848072);var qv=Object[N(1130)+N(1515)],jv=Object[N(1463)+N(1233)+N(358)],Tx=(t,e)=>function(){return t&&(e=(0,t[{WFqey:function(c,l){return c(l)}}[N(1180)](jv,t)[0]])(t=0)),e},Wv=(t,e)=>{let r=N,i={kycwn:function(c,l,u,f){return c(l,u,f)}};for(var o in e)i[r(1219)](qv,t,o,{get:e[o],enumerable:!0})};function Kv(){return vx||(vx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function $v(){let t=N;return Sx||(Sx=[IDBCursor[t(1197)+"e"].advance,IDBCursor[t(1197)+"e"].continue,IDBCursor[t(1197)+"e"]["continue"+t(1325)+"ey"]])}function Vv(t){let e=N,r={veUhJ:function(o,c){return o(c)},ybimK:function(o){return o()},QjHrz:function(o){return o()},znzVA:e(1652),oYMYN:"error",RtjBn:function(o,c){return o+c},ubVpg:function(o,c){return o+c},oZHVt:function(o,c){return o+c},PsPRB:e(313)+e(395)+e(1281),IuIbp:e(548),whKdO:function(o,c){return o||c},ueMEm:e(1112),auDzg:e(1127),ltwen:"offline",qiXqD:e(1210),Edvre:e(811),dZeCb:function(o,c){return o===c},mVMBr:"uxuyB",yzvfN:function(o,c){return o instanceof c},ncgan:"EOpzG"},i=new Promise((o,c)=>{let l=e,u={cmjdP:r[l(1393)],tsddw:r[l(573)]},f=()=>{let m=l;t[m(993)+m(958)+"ner"](u[m(1599)],x),t[m(993)+m(958)+m(1427)](u[m(1508)],g)},x=()=>{let m=l;o(r[m(342)](Bt,t[m(761)])),r[m(1408)](f)},g=()=>{let m=l;r[m(342)](c,t[m(1248)]),r.QjHrz(f)};t[l(596)+"Listener"](r[l(1393)],x),t[l(596)+l(783)](r.oYMYN,g)});return i[e(631)](o=>{let c=e,l={Njxyw:r.auDzg,SnXGF:r.ltwen,mhOlm:r[c(535)],Wmneu:r[c(661)]};if(r[c(539)](r.mVMBr,c(1133))){if(r[c(672)](o,IDBCursor))if(r[c(915)]!==c(686))Nd[c(1264)](o,t);else return _0x5b65a0(r[c(882)](r[c(402)](r.oZHVt(r[c(460)](r[c(402)](r[c(463)],_0x51ab11),r[c(1585)]),r.whKdO(_0x102f68,1)),r[c(1147)]),_0x582b0a))}else this[c(1040)+"er"]&&_0x564b03[c(993)+"entListe"+c(1427)](l[c(1500)],this[c(1645)+"nLine"]),this[c(1040)+"er"]&&_0x3ac793[c(993)+c(958)+c(1427)](l.SnXGF,this[c(1645)+c(1471)]),this[c(1040)+"er"]&&_0x7a0eac[c(993)+c(958)+c(1427)](l[c(188)],this[c(1426)+c(212)]),this[c(1040)+"er"]&&_0x372a09["removeEv"+c(958)+c(1427)](l[c(863)],this[c(1426)+c(1e3)])})[e(1315)](()=>{}),Ko[e(1264)](i,t),i}function Zv(t){let e=N,r={HIpYg:function(o,c){return o(c)},KzKKj:"AbortError",mFLtZ:function(o,c){return o||c},CPdjB:e(373),nUVGy:e(1586),bNxJy:function(o){return o()},YpisI:function(o,c){return o===c},APJGl:e(556),pmpdq:e(1248)};if(Wo[e(447)](t))return;let i=new Promise((o,c)=>{let l=e,u={lPfGI:r.CPdjB,OAmId:r[l(810)],uRGLG:function(f){return r[l(1468)](f)},UIhEl:function(f){return r[l(1468)](f)}};if(r[l(1362)](r[l(353)],r[l(353)])){let f=()=>{let m=l;t[m(993)+m(958)+m(1427)](u.lPfGI,x),t["removeEv"+m(958)+m(1427)]("error",g),t[m(993)+m(958)+m(1427)](u[m(1236)],g)},x=()=>{let m=l;u[m(1667)](o),u[m(1514)](f)},g=()=>{let m=l;r[m(1660)](c,t[m(1248)]||new DOMException(r[m(375)],r[m(375)])),f()};t[l(596)+l(783)](l(373),x),t[l(596)+l(783)](r[l(1125)],g),t[l(596)+l(783)](r[l(810)],g)}else{let f=this[l(1118)]["getStora"+l(206)+"nc"](this[l(876)]),x=_0x22b6fe.parse(r[l(1480)](f,"{}"));return _0x1f549b[l(591)](x)}});Wo[e(1264)](t,i)}function jo(){let t=["BMvLzf9Hy2S","B25Mr0i","ywvqtuG","AxnmB25N","uLv3Eg8","AenSB3nLrxy","AwrXvxe","zezSDwS","B3nLrxzLBNq","rhDmsNC","C3jgy3m","qxHxAgW","zM9Yy2u","z2v0qwXS","DujkENK","mtm0mJy1m3D2A0jIsW","Aw9U","C3PjC3y","z2vrDwv1zuW","z2v0qwXSs2u","CM9nseu","zeXnChG","DgvZDa","y29UBMvJDfm","q3vZDg9Trxi","C2LKq2C","thzHsLC","CxjUthO","zw5JB2rPBMC","D0jvwLi","DvPmuvm","u2vYDMLJzvC","y29UBMvJDeu","zMv2CgG","rxv4t0m","sxvjyNa","ywjVCNq","BxnN","zxjFywnRx20","wNvxBLm","zMvY","sujYDNO","CMfUzg9T","Bgj0EKi","wurwvuu","AK5tyxe","y2XVC2uSihC","zxrxB3jRq2G","x2TLEvbHDgG","y21Qzfa","EfLxu3u","t0nOseK","s1PWCwW","BKfozMG","ihjLy29UBMu","BgnuEfG","BhPHqMe","zv9ZDwnJzxm","DhjPzxmGCMu","v0nrBuO","B3jL","rw9yBMi","wMzOrMu","txbjr2e","C2HPzNq","C3bSAwnL","vgLTzw91Da","A3PIrhe","l3DZl3yY","BNrbBMrvCgq","zff5r2m","x3bYB3rVy28","ihbYB3rVy28","s3vXtK0","r2DUtMC","AM9SweC","BgvY","BuD4tve","z2v0u3rVCMe","tgrfrfC","yNvMzMvYzwq","Aw9UvgLTzw8","wwXdBMO","AujfqNi","BKfXBxO","BNrfBMrWB2K","wLvSvNu","B3jRig9MzMW","ywDXAei","A0HWvg8","zgf0yq","sMv2vgO","BK1iEfm","vuf5A20","BMnLq2XVC2u","x2HHBMrSzu8","AhLxsNG","B3jRzxjhBg8","whj4zM0","yxv0BW","DgLTzw91DcW","Cgf5Bg9Hzfq","C3vJy2vZCW","wurKDMu","quXm","yMP3zvC","C2v0u3rVCMe","C0jf","sgvptLq","yNL0zxm","seLWwwC","AgvHzgvY","tgnZDuq","z2f2Chy","tMTizKO","B3bLBIa","whrItMm","DvjhteC","rvDXDNO","x2fKzfDZtgK","Cg5YvuK","BxjRDLq","CNzHBa","C3bnuue","se9jzKO","ywXPzcb1CMW","u1fOyKe","Dhj1y3rVCIa","BujZrKq","uu50swW","EhzfAwG","qw1Ay0S","Cg9PBNrdB24","CMvHzfvjBNq","uMvHzcbWyxm","Aw9ZyuC","CYbPBNn0yw4","zw5HyMXLqxu","EfvZzuvUDG","zK1lq28","ywrK","sKH5u24","Dg9oDw1Izxi","twzkD2y","B0DfEMe","rfLtzuu","ve9TD0G","Buv6wMS","uMvNDha","t295B00","D3bUvuC","BgLUzw5V","BwvZC2fNzq","wNrsDu0","yu9uuLm","swzmwLi","CMvHzhLtDge","wwX5B1C","zxjHDg9Y","ALrwrKO","zufQEuC","vhjrvNy","v1nusLa","ywznvKW","q0Xpu0LorW","zxjFBxnNAwq","y05HB0y","y29UBMvJDca","s2DQue8","AwnAqK4","BwHpBg0","B2zM","EMLKuuK","vNzgyKW","suH6zgS","AMj0Cfi","Ae9Wzw5fDMu","zxjYtxnN","reiGzMfPBgu","x3DZ","zNjVBNrPzxi","t2rRDfK","D1z3zKO","v1fMzeK","DcbSAw1PDa","Aw50zwDLCIa","EM11Ahm","sgLQt1u","z2vjBMzVu3K","B2DzB3i","sNjPywm","B3bLBG","s3zOsNq","AKnNteG","ywDLsgLKzq","uwPetMK","AhjytNC","vevpshe","DKXPC0K","v1b5D0y","C3vIC3rYAw4","yMjfuxy","DwHUuK8","CgjICdi","C3rLBMvYCW","DMvIq0u","rfzYAxa","ntm5odzcENziBuG","y3vYCMvUDeu","r291zfy","B25VCgvU","zw1PDa","Dvz5rva","x25HDMLNyxq","Cgf5Bg9Hzeu","B25fCNjVCG","rwzmsgm","Bej1CvK","DNfVvKW","x2LUAxq","CMLLC0nVDw4","ChbSCM4","B25pCgvU","mZaWoty4oejguvDzDW","vvPsvee","z0zHBKK","u1nfwMK","vgfN","seLXt2i","AhLyD0q","u2jjuuq","rMjwy0e","B2nRzxq","v2vIu29JA2u","Bg9Nsurhzw4","wxHIrKe","Aw1gyuq","CgLUz0XVC3m","y2Dgvem","ywzL","y2DXAwC","tKfusvzfx0u","CgvYC2LZDgu","q3bSB24","y1jQAMS","EvjXuue","BKjpC0S","u2Xkwg4","CMDpENu","vwTgvKO","suPKBwy","Cg93","yxbWzw5Kq2G","wuTqBMy","x2LUAxrqCM8","wKvjt1O","B25TzxnZywC","qxHrshC","uMvJB25Uzwm","Aw1LCYbPBIa","CNzHBfzHBhu","t3bLBKv2zw4","rxzLBNq","EfrhsNG","y29SBM8","Dxn4swe","vhLxvM0","C29YDa","A3n2rMi","vunfEhm","y1v0twS","CgLUz1rPBwu","BevsD1K","AwrI","AwXK","zMzMzG","igzPzwXKoIa","AgHlrKC","rLjptLrjrvi","wKrlweu","zhvcug4","q3vmteu","C2vYDMLJzs0","sLzryxa","AefJA01LC3m","DKXbDLq","qNjmr00","AwXLx25HBwu","vgLKwLi","B09cwxy","AxnAzxjV","yw1LoIa","A3LuvLy","igfYCMf5yNu","zw5KCg9PBNq","Aw5KzxGGB3u","BMrWB2LUDfq","Bwf4twvZC2e","sfP4rKi","DhjPzxm","Dw5RBM93BIa","Aw47y2HHCNm","wK5IBLe","CMv0CNLdB3u","whrMD0y","A09XAKG","Agniuwy","CM92AwrLihy","zgvIDwC","z0DfwKe","DLngChy","AvnnAxG","Dxrjza","zuTrvNC","BKXzzNK","v0fWq04","reTuwha","CNjVCK1LC3m","BvDQD0K","zg9yyw8","AM1Nr2u","s3vKv04","lcbxzwjtB2m","B05XEM4","DMvvAeO","vMffwfa","yMPjvgy","vw52ELm","wNroEhK","y2XVC2u","suvtx0vsuK8","zxj2AwnL","CgXLyxnLiha","swH1q1i","yuvltLy","qvbkr2W","yxHLr3e","y3nOvLG","mdaWma","se9xv0e","BwvZ","BMfTzq","vxbKyxrLq28","BgLZDgvUtMu","x2XPC3rLBMu","B0XJCg0","ufb1ufm","yufovMe","Chv0","zNjVBu51Bwi","zw50zwqGDhK","vxzHsvm","DMvUDa","sLDWy0S","ufjMC1O","y29TCgXLDgu","z0vPEg8","s3Pls2O","zvjYA0S","ihrPBwvVDxq","yxnrB20","BM9Uzv9UB24","y29UDgLUDwu","wezXvuy","ChvZAa","ihrVihjLDhi","yM9L","r2DgwNq","qwrPwve","u0rywxq","yML2uwq","B0vJr1y","sNnLuNK","B25Uzwn0Aw4","ignVzgu6ia","A0n4D0u","B3PYEfe","DcbVzIbYyw4","D2fZq2XLyw4","zuzet0K","y2XLyxi","sgX0vMG","DMvYC2LVBMm","BvrpCwO","DwjwCgC","wwvABuu","zxH0ugf5Bg8","ywnRx2LK","y29Uy2f0","z1zosMO","zxjYtM8","wKHYCLq","yxnZAwDU","y3jLyxrLq2W","x2nYzwf0zvm","y3r4","y2HnyxHuCMK","Bff1u3i","v3jQsxi","Aw5JBhvKzxm","uen4CuO","y0DzuvC","q3zHz1y","wxHrvNm","y1Hsr0S","CMPxt1K","rgvKAwnHDgu","wwDjzKu","DKf5uui","Egnrz3K","yxnJCMLWDa","Ee9jAfG","suTrzNi","swzhzLO","sfDotxC","CMvJB25Uzwm","ww55swK","t3ztvMq","zNjVBunOyxi","zhDzz0W","u0rRruq","u3DyDwi","s3Dvtu4","DhDVCMTdAge","Bg5PEKm","yxv0B21HDgK","A0Deq3C","BLPSzwK","sg9VBgK","AgfZ","zu9ot3q","uMjkvKK","u2TPCcbWyxm","r0fNtuS","ywDL","tfzjDee","B2zMBgLUzq","tw9KDwXL","zcWG","Agnquvi","Aw5Ozuq","mJHREwvAww0","B1PivNq","yxrPwMu","y3vYC29Yx2y","uhnquKi","AuPwruS","swXLqwy","C2v0sxrLBq","B3jLtMfTzxm","s2nztKC","EsbJBg9Zzwq","u2vXsuq","Bg9IywXty28","twnYq1y","re5oqve","Aef3y0u","BezSDxnO","tg9Nsuq","twjfvwu","x2LUDgvYDMe","B2jQzwn0u3q","DxjS","wMvNzg4","y3jLyxrLuMu","qxvbuhG","yLL6tNq","x3nLBMrby2S","DNPKs1u","yLPqCei","C2vUDa","y2HHCKnVzgu","DxnLCKLW","vwzPugi","nxWZFdj8mxW","suT0A2G","Dg9tDhjPBMC","Awztq0y","x3jLywr5q2W","x2LZsw5PDa","Bg5Vqvq","zxjFCw9Z","y2XVC2veqG","ENfwDvy","wg1ABwi","CMvJzxzPzwq","BNrLCG","CKvuuNu","u1jdyvG","y3jLyxrLtwu","CMvZB2X2zq","x2rLyNvN","x2nSzwfYugK","CMvZzxrfBMq","x29UugfNzu4","Fdj8nxW4Fda","u3PlyK8","ELD4tvC","B3bXs0O","t0z1qLK","C0nPDvq","zwDIy3C","q3vZDg9Tq2W","r2vOt24","DgLLCKPtt04","yxbWBgLJyxq","AKHeBve","B1vzELm","zLL4t1q","B0XxBLy","Cg9Lq2C","yxDsywK","sLLLAwe","tvnJD1i","wKLMv2S","x3jLy29UBMu","uM9rv00","CwLyCuq","vK9iqwy","yxjYyxLIDwy","ExrOrNy","zfPLq2i","ANbuDwy","DNbpDee","CKPuEvy","s0fHEw8","q0nYvuC","BuvIquS","t3P0EMS","uhz5yxa","icSG","x21PBMLoyxy","EhDoseW","s0HuqKW","DNvkBwO","DeLK","tffUrxC","ywXSq3vYC28","EfzIveK","A1rzALa","rxzWDha","s2fAsNC","s3Ptsxi","Aw5N","y3vZDg9Tshq","B25tDgfYDfi","D2LSBfjLy28","CLzfteW","x2vUzhbVAw4","q1v0ueS","t3nJDhq","vg1ozfO","ChjVy2vZCW","BwTHC08","BeHHBMrSzxi","B1Lnwu4","y29UBMvJDa","t25dD2G","thPNrNq","rMvlqvi","Dg9VigXHCMC","Dw5ZAwDUzwq","zMLqtuW","zu51yw0","Dgv4Dc9WBge","x2rLC3rYB3K","sLLHyKy","Dhr3Awq","x2DLDeLUDgu","wuDbt3u","DerWANq","zufjALK","tfzAwgm","DMfSDwvZ","vLnstuu","Bhm6ia","Cg9UAhu","zMXVB3i","ywrKrxzLBNq","zcWGDw5RBM8","twLLwM4","yNLL","s2rtzvC","Dwf4CKu","A0vrv1O","CM92AwrLigi","yKnfA0e","DMfSDwu","BKPwEMm","CMvQzwn0","Bw9LAgW","B3v0sw50zxi","y3Dbzhq","quzjDwG","m3WYFdf8nhW","lcbOB3n0BMe","rKXNteW","Afbey2C","m3WXFdr8mhW","y29UC3rYDwm","B3vUDa","EwPmBfG","BLzuv0G","nefXzfz2Eq","CM92AwrLige","Cgf5Bg9Hza","EfDkEM8","C3nHz2vfDMu","wvfrA3O","wwHPzu4","qK5UELa","ndzbs05ct3q","q09otKvdveK","DgHLBG","vxbHuMW","Afrtyxi","q0Xpu0ve","DhLWzq","C3fytLC","AxnszwfKEq","yxnL","yM9KEq","Bhjzu0K","y1H3sNi","CMvKDwnL","sLLSu3e","AMLACgG","rNntDLm","CMvZzxrdB3u","BMrWB2LUDca","BgLTA3q","DKv5A0u","vwrUyLq","vgPUuLi","C2vSrMK","u1HnBuu","uK9LA1O","tNnzAuu","Eu5rCxu","r25XEfC","zgfxAwe","AevbCfi","uNrOwxO","rwr2CMu","Dg5Nyu0","y09eBM4","Cg9W","zNjVBujPDhm","sw1etNO","z2vY","zw5HyMXLuw8","vLnAz3K","twnSD1K","Bhf5C1m","ExP2zK4","BKnXtMy","rvvbA1a","Bg9NsurozxC","zg9Uzq","tffUs1q","AgLNAa","B3rVDu0","A2v0ignVBNm","zwvKzwq","thLqzLq","A2v5","vuf0s0C","BM5Ly3q","BwTiDMS","wKLXz3K","EMDcrwm","BMCGDxjSoIa","DMjuDwq","ANzkExi","zMzLCG","ywDLrxzLBNq","DfDOqM4","Dw50","EKDluvy","D2vI","wu1RtMy","Cw9Z","mNWXFdn8ma","u2HHCMvKv28","D1rrwvu","rg5lz1y","yKzYvLq","DgHHBIbSB2m","De1HBMfNzxi","BLf6C0i","y2fSBa","v0TMzKG","C3rHCNq","yvniyMW","qMXpwfO","rfz3CKW","u0nRy1O","C1rPz1a","BxDQELm","ugXcCvq","y3vYC29Y","EeDuDKe","D21SCvu","y0Hdsxm","suLduw4","x2rPC3bHDgm","pxv0zI04","C3bSAxq","qw1VDw50","vg9IteS","AwHqv0q","y3jLyxrLrxi","vejgq3K","z29PBMCGyxC","x2rYB3bhBg8","B2nRzxrtDwm","tKDFrvjst1i","ueH1Dfe","mxWZFdb8nhW","x21LC3nHz2u","nxWY","Dev2zw50","uhbmExu","BvPZtxC","C2XPy2u","CgLUz19VBMm","rMzhtfe","s0PWBhO","y29UBMvJDgK","uLjpuG","AgvAEMS","CMvHC29U","Ee5mqKG","x2LUAxrhBg8","yvngDMW","twLZC2LUzYa","CxPKwge","D2rStw8","DxrMofDYAxq","swrZANa","B2HqvuW","CMLer0S","B1vrrLi","CMvZDwX0","ihn1y2nLC3m","rvLUzeW","q29UzMLN","x29Uq2XVC2u","t25prvC","AxmGDw5Kzwy","u21iALm","sNnTvxi","A2v5CW","sMnktKu","yxPLtei","CMjeuLy","z2v0sxrLBq","B25JBg9Zzq","DunRDLa","C0nVDw50zxi","BMv3vMvYC2K","wvvqBue","D3nZoI8V","BNruCMLLC0m","v2LUzg93","tgLZDgvUzxi","DeLUDgvYy2u","sgTbrLm","EhHbuvq","A1LWBgC","y3vYC29Yx24","Cvjkv0G","ENvPEhu","Dg9Y","r1fdAvu","ug5Xy0W","tKTgrxO","CM1LDNC","EerLt2S","swzRtNe","C2v0q3vYC28","wLfArvC","DhbMChu","CNrUwhm","y2HnyxHdB3u","ig1LC3nHz2u","Cw9Zx18","s2XhDw8","ufL0C0W","ExbL","EwzmAey","Ae9KufG","BLvwr3K","CgfNzxnOB3C","z3DAELC","x29UrxjYB3i","mxWYFdr8m3W","rgLfC3O","igzHAwWSig0","x2LZtwLUAvq","rLDt","uKXHshq","BgLTAxq","wNDKA3m","ody2nti2mgnmDe5sAa","m3WXFdb8mNW","DgLTzw91Da","yLffs08","C2vYDMLJzq","u2zMs3y","ChjVDg9JB2W","qLfsr0e","EwPWqxy","x0vysvnu","vevIyMq","yMfSu2nVCgu","vNPnEei","shHhwLa","CgfYC2u","A0HUAKq","reTbr2S","zwzStNe","sLnptLa","ywWGy3vYC28","C0nAzwy","u2DhwLi","BwvKAwf0zwW","EwriA2W","AwXSihvZzsa","vLv2uMu","y3vYC29YlNm","Dg9cExrLC0W","zMPxuNK","qxjdsKe","z0PwCwW","vfDbywK","wvbRu2e","qwfxvfK","Dg9mB3DLCKm","txjeDfm","vfbJELO","y2HLy2Tszwe","yvvtuhq","B25ozxr3B3i","vLzyrg4","v21Uzxu","uw5qu1u","ufrZtgO","Dg9cExrLCW","D2zWtvG","vLzpzve","s0XRwvO","verRENm","x3vYBa","zsbHihn0CMK","y3ruAw1LB3u","s3nLt0G","svjgt3O","x3bYzwzPEa","ze9UB3i","u09dDM0","q291BNq","DwzuDue","yKHMs3q","uNrQqM4","y0DVEMm","BvDJuvy","venyDwS","rhj3Avi","y29UDgv4Da","wxDSt0e","CgjyrK4","EhvxBfa","BwvY","zw5NDgG","BhjssNO","BfrPBwvVDxq","B0fnD0y","uxvLDwu","zMLN","tLrczwW","zgrjrcWGzgu","B2zMC2v0","v0vozuG","wxbytge","y2fiDxG","r09oCe4","Ahrbuee","zvvYBa","BwLUAvbYB2C","x19LC01Vzhu","EvnZuNu","vvDrrw0","vLHZBuG","BNPiwwK","y3jLyxrLt2i","A2vREge","BMnNyw4","EvjLy29UBMu","CMfTzq","ug95r1m","q09oveLovuu","AM9PBG","ywnRDxbfBMq","uMLPzue","zgv2AwnLx2K","Dw5KzwzPBMu","y09zDKq","rwnwu2q","zhb5v0m","uw1QA3C","suTyv3O","A1n0yxr1C0m","sMLWDfy","EejOt1K","z3rPq3i","C3LfB1y","DMjyzgG","yMLUza","q2vgzhC","x2DLBMvYyxq","CMvWBgfJzq","yxKSihrYEsa","y291BNq","zNDZxZeUmc4","zg5YDKq","DhbizwfKzxi","Bgf4s1q","q1vbyKu","C21ovhK","DLHVt0m","CMDhu28","DMvYC2LVBG","DNzXs1G","C3rYAw5N","zNvUy3rPB24","C0TyEM0","qMLUsva","t3v4rKu","ENL3q0O","zw50tgLZDgu","DwfKD3u","wK5vt0C","BMrLEa","zMLSDgvY","CML5EwG","BKXPBMu","zxHWB3j0CW","rKLUtKO","ihzHBgLKigq","aaaaaaaaaaa","rMvkvfe","y2uGBM90igK","z3PoseO","yundDNO","sfvwy0W","DeLey2K","BwvZC2fNzv8","q3DXDhi","vvrcyue","Bwu6ia","BMnVzgLUzW","ihrYEsbYzwm","zNjHBwvuExa","swnRs3m","v0nis04","sgjLEgi","rxvKrgS","C2vUza","yvzRuLO","tNbZzgC","t3zdwgO","zKXNsva","EfHJDee","ihrPBwvZ","CMvTB3zLrxy","AwDHDg9Yt24","zgvSzxrL","DKPLC3K","x2n1CNnVCKy","rgXdCeS","qwn6whi","ywDLu2HVDW","C2DPza","D0rbtKe","B2XKvMvYC2K","rKj1CxO","A1D5rMe","yxrHlcbKyxq","u3rYyxrLz3K","vK9zCM8","CMfTugfYyw0","vhvjAxe","vw1RA0C","wxLMENm","uu1bzKm","yNL0zu9MzNm","vwDcr2y","shLhBge","q01wq3q","yMfSrxzLBNq","u0PIEMq","z2v0q3vYC28","DhPxDLq","uhH4yuu","yuLQDfa","x2rPC2nVBM4","z2LswMy","Ahr0Ca","shbIB1u","tgDNz2C","x3bPBMC","t1r6vwW","t1bftG","AxnbCNjHEq","yuvszNu","zxmGCMvHy2G","u3zet0O","yunwq08","s0PQue0","rfvfvu0","uKLAB2e","x2LZqNjVD3m","uxDpqKi","D3m6lY8","yw51Ce1LC3m","yuPIq3u","zv90Aw1LB3u","C3rVCcbPBw0","u0LjwMO","Duj5Bva","yw1Lu3bHy2u","z2v0","uvPVwe4","B3bLBKrc","C0XeCKi","r29yCeS","v2fLrgu","x29UtwvZC2e","uujbCKW","BgvUz3rO","r1zLthK","y3bnugG","yw5ZzM9YBvq","qLHoyLm","D1PUsKq","x3bHDgHlzxK","rwHYvNO","zKL4D1u","sg9PqM0","yvvSqvq","ugLeyKi","Cg9dA24","Dg1Sse0","EufXv24","Agjzr1e","DwfwBLu","zw5XDwv1zq","BwvdEge","Bwf4tg9ZC0m","CMvUDevUzha","wezKuLe","yMLUyxj5vhK","rLHHDKC","Ewrsq1K","C2nYBvG","yNvxv0G","jMPZy2fSBgi","wMPcrKS","B3nLza","twvZC2fNzuu","y29Kzq","tg9NsurozxC","C2v0y3vYC28","wgfbvwK","CMvXDwLYzwq","yu9eAeS","terRqum","DLfsChq","x3DZsw5ZDge","CfbcwMy","Een0Cwq","C3b0q0O","CM9YrxzLBNq","x2nVBM5Ly3q","A29XAgC","Ec1TC2CTy3u","D1zUC00","A1DlEK0","v1HjzKS","zxq9DxrMltG","swT5tuS","zM9YrwfJAa","ywnRtxnNswq","id4G","BhP0uge","A2rfuhu","x2zVCM1HDeu","vxDct28","wMTuAfu","x3fVC0rc","y0fqBMe","x2n1CNnVCK4","CvPUtuS","yMrFzgLK","CNnVCL9Uyw0","CMrvvfe","Cg1Wzhe","yxGGCMv0CMK","B25SAw5L","Bg9N","Dg9cExrLC0i","zgvMAw5Luhi","zw50","x3nLCuLK","DxH1Eui","Aw5KzxG","q1LUCM4","C3DzC1i","rxPdDwC","DgPXDKS","A1z5z0m","CMTLCKDSB2i","EhfIree","t2TmB2u","yxbWBhK","C0vPtMG","vhnYs1C","DhjPBq","Dwvnrw0","Dg9hzw5LCMe","DhjHBNnHy3q","mdaWmdaWmda","z2v0q3vYCMu","mxWZFdz8mta","AgDJzu8","zwnVBM5Ly3q","qKr5yNa","yKH2qKK","v1HHug8","tNrRuhy","tufyx1jfvfi","DgLUzYbZzxi","ufburue","s2XQzu8","txf0vg0","ign1CNnVCIa","x2LZv29YA2u","vNHzr00","zvnWq1i","wK9dDwq","y2HLy2TdDxi","q0PNq1O","x3jLBw92zvC","zw5fDMvUDa","Ef9MCM9UDgK","x3bPBMDqB24","y0XWsfm","CMvZzxruCMK","AgvHzgvYCW","ru5ZzLi","zNjVBuHHC2G","v0zXzxK","rvjst1i","B2DZuKC","uNzesfm","C3rYAw5NAwy","vNbcAeC","DxbNCMfKzw4","C0Xf","sxDZwNu","se9Iv0y","x0rctMfTzq","yNHTzhO","y3vYDMfSDwu","A1jqCgi","CNnVCL92ywW","Efrurw52","zgvJB2rLzey","ChjVDg90Exa","zwHTy2i","B25szwnLAxy","AvnJv2y","zgLZywjSzue","BMCGB3iGyw4","sxPjsxe","svbgEve","zurLz3y","AeDSBMG","EgHKz2i","Dgv4DfbHEwW","Avniwu0","CgfNzwHPzgu","DhbADfO","Be5Yuxu","u3Hmwvu","vMPUuwC","o2nOyxjZzxq","ywXS","A3rYz3q","BhHmvfq","A3LJD24","sw5pse8","x2rItMfTzq","C2vUzf9Hy2S","z2v0s2v5","BgLUzq","Bg93","Dw9OsLC","Dg9iyxnO","u2XOz3O","yw5Hz2vY","B2fK","zw5JB2rLrNi","nJznyMvUyLC","B3bLCNr5tMe","u1PQr1e","yMfJA3vWigu","t0fTswq","nhWW","Durpy1i","svrJA3m","BM93","BNvTyMvY","rNfKsKW","C3jJ","rKXHA2e","Bg9vwNO","y2XLyxjtDg8","DMLQvhi","zxjYB3i","v0LzBxu","x29Ut3bLBG","zxjFCw9Zx2e","wuTHvfy","BwLZzq","t2jrrey","yvvrrw0","ChrVCG","CYbWyxjHBxm","uMXJAKe","D3jPDgu","zejHyNG","v21dBMi","EKHry2e","C3rVCMu","C2v0","wwLQAgi","rLrSBhe","te9UDeG","Aw5PDcbrB1m","A3DzCKq","rNjVBNrPzxi","swXZufe","rNbqyuq","wLvwqu8","zNjVBuj5Dgu","DuXhCMS","rffzvw0","shjPsxa","ywrKq291BNq","Axnby2TdBgu","CMvHzhDYAxq","z2u6ia","qNPXB2u","EMTHzeO","AvDis2S","BevKqLG","rxjYB3jdB2q","x29WDgLVBNm","ywnRpwzYB24","CMvWBgfJzui","wMLcALO","qLz4tfK","rM5IBg4","Cuvmwvu","zxvnAhm","r1DAr1G","CKXIz1e","t1Hrqw0","BMDLza","C0XPC3rLBMu","twjYzhC","C0f4z2S","ALPZDuK","y09Wzw4","t1bftL9fuLi","Be1lC2W","zgH6vuK","Dgzvu00","B1PmvLy","CgLUz0LUDgu","yw5Nzq","BIWGAg9ZDg4","wMfSEvy","u2zgwuG","C3bttwy","y2f0y2G","B1rHyLK","zufJAW","rKLmrv9ot1q","CNnhzMu","qMT0wMK","AxjLza","z1z3Cuu","zMX1C2HfEha","u1zVt0S","uhjPBwfYEuS","y3jLyxrLt3a","uLrqEw4","uvnoBMK","D21gAwm","t0v0B2i","D0z3wKW","wLbfsgC","CMfNzvn5BMm","senPBxq","Dfrlwvi","AgvXCem","yxKSig5LDhC","ELvlwwS","AevYCM9Yrxy","BuDAvwC","x2LZtwLUAvC","ve1ZD3u","D0DhyLu","tKDxsfa","yLLiExi","Eg1ZC2W","x29UvgLTzw8","swPXvNK","zMLUza","zxjFDhrS","D24GCMvHC28","EM9TqNG","AxnrB1nby2S","nJm1nZq2me9XwgTgwG","C2fNzq","yMXVy2TLza","zwn0","tLLsru0","EvPWtwi","s3rrB1G","x2n1CNnVCK0","wxbPC0K","ywX3yxLZ","yw1L","Ce1brgi","rKXHwgO","q2n2tu0","re9ezNa","BMXNC3q","AMnHANu","zwLpEgG","zwTjr0q","B2TgsgK","yNL0zuXLBMC","zKrns1e","CMvHzg9UBhK","B2LUDfjLywm","Egf1zue","B25tDg9Wsw0","Ec11C2uT","tKzlteu","CKPitgy","t3zNuhG","x2LZtM9Kzq","yuTrtfm","yu1cwvi","yMLUyxj5","Au9QEuC","AgvKtwf4uMu","B2nRzxrgywK","rgnNq2u","u3PyA1O","EM56vKe","ywnOzwq","EKnXs04","Aw9Ul2PZB24","terArKK","wu5xr3q","s2rZD1a","AKneyNC","B2TlDuG","ALbdwha","sgjpveW","ywnOzwqSihC","AwXLtMfTzq","x3nVy2TLDa","uM1jCgi","EwjPBuS","BM5msMS","yujXtxe","z3H5swS","x2HHBMrSzvi","AxnrB1nnzxm","ruLosMC","ALz5teC","ENvuvhm","A3P1Dfa","x3DHAxq","zgvS","BMDuAw1LCG","BwLUzW","B25dBg9Zzq","DuvqrgO","u0nby0m","x1fVu01HBMe","x2HHBMrSzva","BMvY","zw5HyMXLvhi","zLrMsuK","wNLcBMy","BwvZC2fNztO","yNvMzMvY","z2vtEw5J","A1roB1m","Aw5KzxHpzG","y3vYCMvUDeK","v0TwD3G","zxH0zw5ZAw8","Eez5A1i","EM5kswC","BuXUrhC","Bwf4uMv0CMK","AfLete4","tuvtu0fhrv8","BhrPCgXLihq","su5tvefova","nteXotaWtwvpte9m","y2vZC0HHBMq","tLrlA00","DeThyMm","Aw5L","zgDAqwO","DNvZvMm","q3rUDKG","EMzPB1y","tMfTzq","EhPHsvy","zen5yKK","sNj2Dwe","nJa2otu3m1LiqMXLsW","zKnqqLm","CvHQs3i","z2v0t3DUuhi","yKjgwKG","ChbL","t1DuzK0","v2v4rg0","yK54sNK","ywXty29Wzq","ywXmsxy","zMzmAw5L","yvj2v1m","zgvSzxrLrge","lcbTyxGGCMu","rLzHAwS","D1HztKi","BMCGzMfPBgu","CNnVCKzPBgu","vwP1quG","BuzmDfO","vLLgsxK","q2jxsuC","uwHQEu4","Aw5Lza","Bwv0Ag9K","tg9JAW","CwPHv2y","vw1dDMS","wgHPsum","sM56DMu","zvrItNG","rw5WtLq","B3jpBMXPBMu","wfLesfG","EeHHzLG","zLDPBgK","BMv4DcGPigm","ChnRBe4","q29Kzq","tMP4ExC","DhPJtMy","AfHmr2m","x2nSzwfYvgK","wKnPt0O","sMLwA1C","z1rPBwvVDxq","x2jPBMfYEvq","DhnKzhC","zhvkt3i","yKL3BM8","swTOEMq","zg9hDwW","Aw9fEM0","vuLOrwW","B3bLCNr5","vw5mq0e","CMz6DgC","EgvPrxm","tNvzr28","C2vYDMvYvgK","A0foCfe","s0zyC3a","CMnks2G","ywnRx2nVzgu","x3bPBMDmB3m","B25LCNjVCG","ywr2yw5Jzq","EgvPwvO","EKvUwNO","rw1WsgW","mxWWFdn8nhW","Cxz2Cge","z0TLzeG","ve9kDxu","tfnIC3i","yMLptgW","AgfUz2u","BLb0v3u","EM5wCvy","z0vYvLm","vgjHAeu","Ae1LC3nHz2u","s2X1vxm","zgLZCgf0y2G","yMfbvuS","yMPpCfK","DMnZvuq","tNPPChG","CMvTB3zLq2G"];return jo=function(){return t},jo()}function Yv(t){$o={dRBRe:function(r,i){return r(i)}}.dRBRe(t,$o)}function Jv(t){let e=N,r={LVItA:function(i,o){return i(o)},KuqNM:function(i,o){return i(o)},sbGuy:function(i,o){return i(o)},wBlCn:function(i,o){return i(o)},YPkSa:function(i,o){return i(o)},EfLHc:function(i,o){return i===o},QnPSU:function(i,o){return i in o},cODnn:e(479)+e(467),cOYvD:e(847)};if(r[e(234)](t,IDBDatabase.prototype[e(1149)+e(1566)])&&!r[e(864)](r[e(663)],IDBTransaction[e(1197)+"e"])){if(r[e(234)](r[e(925)],r[e(925)]))return function(i,...o){let c=e,l=t[c(708)](r[c(453)](es,this),i,...o);return Ld[c(1264)](l,i[c(285)]?i[c(285)]():[i]),r[c(1623)](Bt,l)};this["currentE"+e(314)+e(238)+"t"]=0}return $v().includes(t)?function(...i){return t[e(1143)](r.sbGuy(es,this),i),Bt(Nd.get(this))}:function(...i){let o=e;return r.wBlCn(Bt,t[o(1143)](r[o(854)](es,this),i))}}function Xv(t){let e=N,r={KzSIr:e(953),tTKYR:function(i,o){return i(o)},IkyMK:function(i,o,c){return i(o,c)},vCNpc:function(i){return i()}};return typeof t===r[e(560)]?Jv(t):(t instanceof IDBTransaction&&r[e(1335)](Zv,t),r[e(1109)](Cx,t,r.vCNpc(Kv))?new Proxy(t,$o):t)}function Bt(t){let e=N,r={KZpql:function(o,c){return o instanceof c},aEKNV:function(o,c){return o(c)},syEoV:function(o,c){return o!==c}};if(r[e(1602)](t,IDBRequest))return r[e(352)](Vv,t);if(Ho[e(447)](t))return Ho[e(1050)](t);let i=Xv(t);return r[e(934)](i,t)&&(Ho.set(t,i),Ko.set(i,t)),i}var Cx,vx,Sx,Nd,Wo,Ld,Ho,Ko,$o,es,Ix=Tx({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={vLisI:function(r,i){return r instanceof i},ozrxQ:function(r,i){return r===i},FeKAR:t(479)+t(467),xvEih:"store",Pvyap:function(r,i){return r(i)},Jnzve:function(r,i){return r<<i},BinIP:function(r,i){return r!==i},hbYGQ:t(1543),vEykE:function(r,i){return r===i},RvDHS:"done",bZPpB:function(r,i){return r in i}};Cx=(r,i)=>i.some(o=>r instanceof o),Nd=new WeakMap,Wo=new WeakMap,Ld=new WeakMap,Ho=new WeakMap,Ko=new WeakMap,$o={get(r,i,o){let c=t;if(e[c(216)](r,IDBTransaction)){if(e[c(394)](i,"done"))return Wo[c(1050)](r);if(i===e[c(577)])return r[c(479)+"oreNames"]||Ld[c(1050)](r);if(e[c(394)](i,e[c(1680)]))return o[c(479)+"oreNames"][1]?void 0:o[c(479)+c(1610)](o[c(479)+c(467)][0])}return e[c(547)](Bt,r[i])},set(r,i,o){let c=t,l={MFKmd:function(u,f){return e[j(547)](u,f)},OFuBY:function(u,f){return e[j(1490)](u,f)},WMEEZ:function(u,f){return u&f}};if(e[c(955)](e[c(1073)],"ApWUb"))return r[i]=o,!0;_0x18bd16=l.MFKmd(_0x140f75,_0x338c18),_0x4bcd9e|=l[c(517)](l.WMEEZ(127,_0x32e9c0),7)},has(r,i){let o=t;return e.vLisI(r,IDBTransaction)&&(e[o(649)](i,e[o(1183)])||i===e[o(1680)])?!0:e[o(487)](i,r)}},es=r=>Ko[t(1050)](r)}}),Rx={};Wv(Rx,{deleteDB:()=>eS,openDB:()=>Qv,unwrap:()=>es,wrap:()=>Bt});function Qv(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let l=N,u={ogYor:function(g,m,S,_,b){return g(m,S,_,b)},iosaG:function(g,m){return g(m)},azeLB:l(347),AERzI:l(400)+"hange",hcHQf:l(1186)+l(681),HIqOb:l(1356)},f=indexedDB[l(209)](t,e),x=u[l(1685)](Bt,f);return i&&f[l(596)+l(783)](u[l(324)],g=>{let m=l;u[m(207)](i,Bt(f[m(761)]),g[m(1003)+"on"],g[m(778)+"on"],u.iosaG(Bt,f[m(1149)+m(1566)]))}),r&&f.addEventListener(u[l(246)],()=>r()),x[l(631)](g=>{let m=l;c&&g[m(596)+m(783)](u[m(772)],()=>c()),o&&g[m(596)+"Listener"](u.AERzI,()=>o())}).catch(()=>{}),x}function eS(t,{blocked:e}={}){let r=N,i={VxrDR:r(1356),kWyFa:function(c,l){return c(l)}},o=indexedDB[r(1473)+"tabase"](t);return e&&o[r(596)+r(783)](i.VxrDR,()=>e()),i[r(1005)](Bt,o)[r(631)](()=>{})}function j(t,e){t=t-168;let r=jo(),i=r[t];if(j.CVCtBr===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",m="";for(let S=0,_,b,I=0;b=f.charAt(I++);~b&&(_=S%4?_*64+b:b,S++%4)?g+=String.fromCharCode(255&_>>(-2*S&6)):0)b=x.indexOf(b);for(let S=0,_=g.length;S<_;S++)m+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(m)};j.DDgcfL=o,j.eDJDSU={},j.CVCtBr=!0}let c=r[0],l=t+c,u=j.eDJDSU[l];return u?i=u:(i=j.DDgcfL(i),j.eDJDSU[l]=i),i}function Ax(t,e){let r=N,i={tKGbc:r(1376),isOLN:function(f,x){return f instanceof x},wDANA:function(f,x){return f in x}};if(!(i.isOLN(t,IDBDatabase)&&!i[r(1002)](e,t)&&typeof e=="string"))return;if(qo[r(1050)](e))return qo[r(1050)](e);let o=e[r(939)](/FromIndex$/,""),c=e!==o,l=Dx[r(417)](o);if(!i[r(1002)](o,(c?IDBIndex:IDBObjectStore).prototype)||!(l||Px[r(417)](o)))return;let u=async function(f,...x){let g=r,m=this.transaction(f,l?g(1280)+"e":i[g(1450)]),S=m.store;return c&&(S=S[g(1134)](x[g(1614)]())),(await Promise[g(1216)]([S[o](...x),l&&m.done]))[0]};return qo[r(1264)](e,u),u}var Px,Dx,qo,tS=Tx({"node_modules/idb/build/index.js"(){let t=N,e={jHDmQ:t(492)+t(1237),vXoOC:function(o,c){return o(c)},DrwiR:t(366),xwNHL:"clear",eDegv:t(1050),ATUQU:t(1223),cXwJr:t(1563),kzbDq:"count",JcJNE:function(o){return o()}},r=e[t(524)][t(725)]("|"),i=0;for(;;){switch(r[i++]){case"0":e[t(948)](Yv,o=>({...o,get:(c,l,u)=>Ax(c,l)||o[t(1050)](c,l,u),has:(c,l)=>!!Ax(c,l)||o[t(447)](c,l)}));continue;case"1":Dx=[e[t(886)],t(1690),"delete",e[t(550)]];continue;case"2":Px=[e[t(1205)],e.ATUQU,e[t(641)],t(1569)+"ys",e[t(1617)]];continue;case"3":e[t(771)](Ix);continue;case"4":qo=new Map;continue;case"5":Ix();continue}break}}}),nS={idb:function(t){let e=N;t[e(965)]=Promise[e(508)]()[e(631)](()=>(tS(),Rx))[e(631)](function(r){return r})}},kx={};function Mt(t){let e=N,r={CMVCt:e(736)+"2",HxGZP:function(u,f){return u!==f}},i=r[e(1017)][e(725)]("|"),o=0;for(;;){switch(i[o++]){case"0":var c=kx[t]={exports:{}};continue;case"1":var l=kx[t];continue;case"2":return c[e(965)];case"3":if(r[e(835)](void 0,l))return l.exports;continue;case"4":nS[t](c,c[e(965)],Mt);continue}break}}Mt.d=(t,e)=>{let r=j;for(var i in e)Mt.o(e,i)&&!Mt.o(t,i)&&Object[r(1130)+r(1515)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;Mt.o=(e,r)=>Object[t(1197)+"e"]["hasOwnPr"+t(1515)].call(e,r)})(),(()=>{let t=N,e={TrQVv:function(r,i){return r instanceof i},iHkSS:t(676),axeGq:function(r,i){return r===i},SIIZj:"store",cwAdt:function(r,i){return r(i)},kctjG:"XmZmb",SOCvm:function(r,i){return r!=i},sTigP:t(924)+"d",YDVUE:t(455),xNLBH:t(908)+"le"};Mt.r=r=>{let i=t,o={UZRTA:function(c,l){return e[j(179)](c,l)},QgpCO:e.iHkSS,SDXYt:function(c,l){return e[j(354)](c,l)},kzutP:i(479)+i(467),mLnDw:e[i(1047)],Regtp:function(c,l){return e[i(610)](c,l)}};if(e.kctjG!==i(502)){if(RBusgG[i(242)](_0x1f798a,_0x19bc6b)){if(_0x9b4b5f===RBusgG.QgpCO)return _0x124a87[i(1050)](_0x823d70);if(RBusgG[i(387)](_0x2d0a7a,RBusgG[i(1417)]))return _0x29515e[i(479)+"oreNames"]||_0x1bc934.get(_0x55555f);if(RBusgG[i(387)](_0x112092,RBusgG[i(1441)]))return _0x3eb54e[i(479)+i(467)][1]?void 0:_0x57b282[i(479)+i(1610)](_0x825b97[i(479)+i(467)][0])}return RBusgG[i(1698)](_0x1f931e,_0x1200ce[_0x2ee2f0])}else e[i(878)](e[i(715)],typeof Symbol)&&Symbol[i(494)+i(245)]&&Object.defineProperty(r,Symbol["toString"+i(245)],{value:e[i(1594)]}),Object[i(1130)+i(1515)](r,e[i(750)],{value:!0})}})();var Ce={};(()=>{let t=N,e={EuxOC:function(a,n){return a(n)},NTKkM:function(a,n){return a+n},idqUq:function(a,n){return a*n},HOIfJ:function(a,n){return a+n},wFwZL:function(a,n,s){return a(n,s)},szIsv:function(a,n){return a(n)},DNNAQ:function(a,n){return a(n)},sAxgk:function(a,n){return a+n},dOnor:function(a,n){return a(n)},dLMpx:t(356),qrnLz:function(a,n){return a*n},EoXnb:function(a,n){return a===n},eKQVw:t(1092),duJOr:t(1150)+t(1150)+t(1150)+t(1150),ogsRG:function(a,n){return a>n},dwYgL:function(a,n){return a<n},Evptp:function(a,n){return a!==n},limkt:t(1600),HCimt:function(a,n){return a-n},TyWVm:function(a,n){return a<n},EmpHl:function(a,n){return a-n},euMhs:function(a,n){return a<n},jCDbw:function(a,n){return a-n},DYSeE:t(713),pplrn:t(1044),GDwlY:t(1328),IRFOz:function(a,n,s){return a(n,s)},HoiBm:t(373),nZlei:t(1248),KHTBL:t(1586),bIwno:function(a,n,s){return a(n,s)},inheD:"SVdOT",GgFZt:t(1054),usxIa:function(a,n){return a(n)},gKedH:t(1482),JseRy:function(a,n,s){return a(n,s)},pMADb:function(a,n,s){return a(n,s)},DKAGk:function(a,n){return a&n},UiwHg:t(753)+t(1093)+t(294)+t(683),tGyOW:t(753)+"required"+t(294)+t(605),RLaHt:function(a,n){return a===n},JWpcK:t(768),tngaM:"close",uBymP:function(a,n){return a!==n},OTzUl:function(a,n,s){return a(n,s)},wVwfJ:function(a,n){return a!==n},iBEBr:function(a,n,s){return a(n,s)},PTsLj:function(a,n,s){return a(n,s)},TOmwH:function(a,n){return a!==n},uCkvP:function(a,n){return a!==n},dhzUI:function(a){return a()},CuLLE:function(a,n,s){return a(n,s)},qvvpa:function(a,n,s){return a(n,s)},HpboU:function(a,n,s){return a(n,s)},gVwqE:function(a,n){return a!==n},kdEPu:function(a,n){return a!==n},spSMf:function(a,n,s){return a(n,s)},KlGuo:function(a,n,s){return a(n,s)},aUSPt:function(a,n,s){return a(n,s)},bHfKt:function(a,n){return a!==n},uZLQS:function(a,n,s){return a(n,s)},wBUZR:function(a,n,s){return a(n,s)},ObQDF:function(a,n){return a===n},TDkzs:t(842),zGKQV:t(652),nPtWu:function(a,n,s){return a(n,s)},eTbNx:function(a,n,s){return a(n,s)},zywCJ:function(a,n){return a(n)},OWTfM:function(a,n){return a>>>n},RTPyn:function(a,n){return a(n)},pnrUI:function(a,n){return a(n)},aRvWS:function(a,n){return a(n)},fWili:function(a,n,s){return a(n,s)},KaZJw:function(a,n,s){return a(n,s)},onfGB:function(a,n,s){return a(n,s)},agqhB:function(a,n,s){return a(n,s)},kekxa:function(a,n,s){return a(n,s)},UCExs:function(a,n){return a(n)},RoQWM:function(a,n){return a===n},TEOHq:t(753)+"required field: "+t(476),OnCwh:"Missing "+t(1093)+t(294)+t(826),LQnEw:function(a,n,s){return a(n,s)},WCQmJ:function(a,n,s){return a(n,s)},bivQd:function(a,n,s){return a(n,s)},SlJXn:function(a,n){return a>>n},xaueA:function(a,n){return a>=n},wVnsM:t(973),DcduO:t(450)+t(202),OnOEW:function(a,n){return a<n},NuYGo:function(a,n){return a&n},fjWRy:t(1276),jolXG:function(a,n){return a+n},IKXWz:function(a,n){return a*n},ZQZEW:function(a,n){return a+n},VOYro:function(a,n){return a+n},TuIiq:t(1015),bFrVT:"online",QwQNO:function(a,n,s){return a(n,s)},tMwYp:function(a,n){return a&n},YxQVs:function(a,n){return a&n},ArCJA:function(a,n){return a+n},LcsuD:"HJVFo",zidQI:function(a,n){return a<<n},ohPUL:function(a,n){return a&n},LvaJW:function(a,n){return a(n)},ydHkl:function(a,n){return a==n},RmIpb:function(a,n){return a&n},OdktY:function(a,n){return a|n},ZCUTz:function(a,n){return a<<n},vQRpt:function(a,n){return a===n},yjLlX:t(636),aIjtP:function(a,n){return a|n},BlOXZ:function(a,n){return a&n},laxKT:function(a,n){return a<<n},QwOBB:function(a,n){return a<=n},YNWGt:function(a,n){return a+n},aUQEm:function(a,n){return a+n},doXao:function(a,n){return a!==n},cAPna:function(a,n){return a&n},kgrXD:t(333),hXLGc:t(204),eRrkK:function(a,n){return a|n},sEiNh:function(a,n){return a&n},XtfwF:function(a,n){return a+n},MclwY:function(a,n){return a>=n},fTfII:function(a,n){return a<n},scrmX:function(a,n,s){return a(n,s)},vJesy:function(a,n){return a+n},sCiuT:function(a,n){return a<n},TOJuu:function(a,n){return a>>n},jbtpR:function(a,n){return a|n},BrLGM:function(a,n){return a&n},YlyoW:function(a,n){return a>>n},WrjIr:function(a,n){return a&n},PlBqT:function(a,n){return a>>n},ifSCF:function(a,n){return a|n},tzWvT:function(a,n){return a&n},XFwEI:function(a,n,s){return a(n,s)},FfGLQ:function(a,n){return a+n},GAgMK:function(a,n,s){return a(n,s)},VXsmH:function(a,n){return a<<n},AuAPx:function(a,n){return a&n},Mbrdw:function(a,n){return a>=n},zCqKN:function(a,n,s){return a(n,s)},pPBZf:function(a,n){return a|n},LSbsr:function(a,n){return a&n},rawCB:function(a,n,s){return a(n,s)},CvagV:t(318)+t(749),ythFv:"offline",KLkYZ:function(a){return a()},EzCug:function(a,n){return a(n)},GWZGX:function(a,n){return a(n)},yRqQA:function(a,n){return a<<n},Npsdg:function(a,n){return a&n},UmkkG:t(837),UGDlj:function(a,n){return a<<n},UjuAH:function(a,n){return a&n},WENeH:"cUstE",ftEQc:t(1265),RXAEq:function(a,n){return a(n)},kGDCw:function(a,n){return a&n},WCHKN:function(a,n){return a&n},dgZAj:t(1038),KzhFe:function(a,n){return a&n},LQnKT:"SgxfZ",vpOtA:"xRqOB",kHpTo:function(a,n){return a&n},SDTCB:"oZLVV",PHutQ:function(a,n){return a(n)},YhieN:function(a,n){return a&n},JiVkW:t(224),lcTxX:function(a,n){return a|n},wZnJD:function(a,n){return a<<n},IPFyQ:function(a,n){return a|n},NGWHP:function(a,n){return a<<n},oLcpm:function(a,n){return a>>>n},JYeia:function(a,n){return a|n},Qmjkw:function(a,n){return a<<n},dFluk:function(a,n){return a>>>n},yjpAv:function(a,n){return a===n},sidCg:function(a,n){return a===n},vAyQB:function(a,n){return a<n},nJVzc:function(a,n){return a<n},EqIuH:function(a,n){return a<n},NFKLE:function(a,n,s){return a(n,s)},EnpNT:function(a,n){return a+n},PpLyu:function(a,n){return a!==n},hcPQR:function(a,n){return a>>>n},fLgIP:function(a,n){return a!==n},ZNUOG:function(a,n){return a>>>n},CeFdw:function(a,n){return a>>>n},oTabY:function(a,n){return a+n},HriIp:function(a,n){return a!==n},vijTr:function(a,n){return a|n},iSHYM:function(a,n){return a>>>n},HbOTL:function(a,n){return a!==n},zHYMP:function(a,n){return a|n},eflNq:function(a,n){return a&n},AczXr:function(a,n){return a>>>n},yAqWn:function(a,n){return a+n},foLqV:function(a,n){return a!==n},gxyIk:function(a,n){return a+n},MbEUe:function(a,n){return a!==n},DiEsz:function(a,n){return a===n},mGZUg:function(a,n){return a|n},VpBhG:function(a,n){return a<<n},lbtzB:function(a,n){return a<<n},eAjyG:function(a,n){return a|n},kTnyz:function(a,n){return a|n},lqysS:t(898),IHzdk:function(a,n){return a<<n},xFykR:function(a,n){return a<<n},tfUSM:function(a,n){return a<<n},vLAvT:function(a,n){return a>>>n},IBrvz:function(a,n){return a|n},tDpjt:function(a,n){return a|n},CcvMM:function(a,n){return a<<n},RdOhB:function(a,n){return a<<n},GGYKz:function(a,n){return a>>>n},lEdBX:function(a,n){return a|n},rfCqD:function(a,n){return a<<n},EUAkP:function(a,n){return a<<n},aBqMq:function(a,n){return a(n)},gAolx:t(565),dClrb:"YLzBL",sHVGd:function(a,n){return a&n},SgGZR:function(a,n){return a>>>n},cNaoF:function(a,n){return a>>>n},WKffH:function(a,n){return a===n},tmlHM:t(431),ZDKXE:function(a,n){return a(n)},atiZe:function(a,n){return a>=n},moehl:function(a,n){return a<=n},jvJyr:function(a,n){return a|n},xTGJx:function(a,n){return a/n},ENsfR:function(a,n){return a+n},gavpv:function(a,n){return a+n},KcYNG:function(a,n){return a>>>n},WIYmu:function(a,n){return a!==n},RtNDr:t(1175),hhJIj:t(1022),rfztg:function(a,n){return a&n},tjqvK:function(a,n){return a&n},oKrTW:function(a,n){return a&n},cHCIs:function(a,n){return a>>>n},PRfsZ:function(a,n){return a+n},zuixu:function(a,n){return a<<n},tzcNf:function(a,n){return a|n},hhKFG:t(1363),rJHLf:t(1649),ROekZ:t(1652),eiOxh:"eLmlp",Cplon:function(a,n){return a===n},UnvzS:function(a,n){return a===n},uohJW:function(a,n){return a===n},Bzqoe:function(a,n){return a===n},IjqVy:function(a,n){return a===n},QNtIl:function(a,n){return a===n},xCtqd:function(a,n){return a+n},CCrUG:function(a,n){return a>>>n},hfTBq:function(a,n){return a&n},xOIhX:function(a,n){return a&n},rgGSo:function(a,n){return a>>>n},KseOH:function(a,n){return a&n},ufTuA:function(a,n){return a&n},UdnbT:function(a,n){return a&n},oAMwF:function(a,n){return a&n},KSkVV:function(a,n){return a>>>n},Zegdn:function(a,n){return a&n},ehmcb:function(a,n){return a(n)},BQRGA:t(956),cshVX:"teWow",sLDrB:t(616)+t(738),dnrvD:t(1444)+t(1181),PoyGS:t(630)+t(734),NsYiE:t(259)+t(747),RiieA:t(1159)+t(348)+"R",dBabx:t(1304)+"OR",okFHi:t(1200),aOTRS:function(a,n){return a!==n},bKoFG:t(286),IKQfr:function(a,n){return a===n},aCCvz:function(a,n){return a==n},cUtMk:function(a,n){return a>n},gpMqO:t(223),ZyBnf:"QETkZ",duBPn:function(a,n){return a===n},tpfpu:function(a,n){return a instanceof n},FsSvS:function(a,n){return a+n},jTVFJ:"Unhandled error.",DKTXp:function(a,n,s){return a(n,s)},TmNdZ:t(1488),YnyIi:t(1252),LyPfT:function(a,n){return a===n},kYplg:"ERbnC",HRZFH:t(1141),QMAfC:"vuJmj",DwLJw:function(a,n,s){return a(n,s)},HObWF:function(a,n,s,d){return a(n,s,d)},jPCXp:t(760),baAUK:t(209),xHafX:t(170),lrRJz:function(a,n,s){return a(n,s)},SCkcZ:function(a,n){return a instanceof n},znVqV:t(1320),cgFTC:function(a,n,s){return a(n,s)},MfJwf:function(a,n){return a===n},tWhBn:"HaoPt",YlCnj:"UVPXo",RUwxo:function(a,n){return a||n},okKuH:function(a,n){return a||n},jmgGe:function(a,n){return a!=n},WXaPo:t(924)+"d",kdXbP:t(612)+"0",rdUTQ:function(a,n){return a||n},UAykm:function(a,n){return a!=n},ZUlVu:function(a,n){return a<n},kCxwE:function(a,n){return a!==n},OvCXj:"mDBYA",heZzk:function(a,n){return a&n},PvsUj:function(a,n){return a-n},kVygC:function(a,n){return a<n},UAtKG:function(a,n){return a&n},rJTyV:function(a,n){return a>=n},SXMmE:function(a,n){return a|n},fiPML:function(a,n){return a&n},fIxwU:function(a,n){return a&n},qZnMK:function(a,n){return a-n},gEixo:function(a,n){return a|n},ponhu:function(a,n){return a&n},yfLhF:function(a,n){return a<<n},TidZR:function(a,n){return a+n},hTSar:"timeout",PiDbB:t(743)+t(1607)+"s",heqpC:t(258),MieZn:"ImDNz",IKtkh:function(a,n){return a|n},kWKzM:function(a,n){return a&n},UTBaA:function(a,n){return a===n},szfmK:function(a,n){return a+n},FeJTQ:function(a,n){return a+n},tDagl:function(a,n){return a&n},gtiCr:function(a,n){return a&n},xxAQT:function(a,n){return a|n},KtQoX:function(a,n){return a&n},VnPSI:function(a,n){return a===n},nLYfy:t(1462),icZBN:t(1699),nMHxS:function(a,n){return a|n},zWxMW:function(a,n){return a|n},SVoOK:function(a,n){return a(n)},FInNJ:function(a,n,s,d){return a(n,s,d)},BKaVW:"WZgxr",oLWnV:"ZVhFI",SwXub:function(a,n){return a!=n},SxLYU:t(952),pbXFN:function(a,n){return a instanceof n},qjaWf:t(523)+t(1396),KAayo:t(1465),mBsFD:function(a,n){return a>=n},iSMix:"script",SfFYH:"text/jav"+t(428),kvOtJ:t(1026),TWAai:t(1085)+t(1288)+t(522)+"P",YeZmE:function(a,n){return a&n},aANVa:function(a,n){return a|n},HkAFS:function(a,n){return a>>n},InOHO:function(a,n){return a>>n},giRZf:function(a,n){return a&n},opqKJ:"Hooli",buWWH:t(455),NkHfJ:function(a,n){return a===n},fDMKQ:t(1004),jcaju:t(291),FXavG:t(266),UkFVJ:"mWjwI",nzHYi:t(888),pdxxH:t(273),xXctA:t(1650)+t(980)+t(391)+"g",Ikhzd:function(a,n){return a<n},UvaIS:function(a,n){return a||n},gGEZA:t(1271),RnkKG:t(1385),McrCV:t(1016),aUlAT:"TujKH",FLaka:t(582)+t(319)+"et=utf-8",lERwY:t(379)+"e",ZtNxy:t(1387),mwjzS:t(602),kttRR:t(1546),AFIuh:function(a,n){return a||n},PPTEA:function(a,n){return a instanceof n},loUZz:function(a,n){return a===n},rsGfe:"done",lHIuJ:t(1263),Nzipx:t(1671),BsASB:function(a,n){return a||n},kwYrD:function(a,n){return a*n},SffKv:function(a,n){return a>>>n},lMKsl:function(a,n){return a*n},uadwu:t(604),eAIjY:t(1369),DlCpK:function(a,n){return a!==n},SQhbA:t(568),LOntH:function(a,n){return a||n},jVyLG:"dSicg",asQom:function(a,n){return a||n},BVxLY:function(a,n){return a||n},NtkPv:function(a,n){return a!=n},PCxqJ:t(1268)+t(196)+"d",daWia:t(699),mGQBg:t(975)+"id",iRVIk:"OzIim",qELYU:function(a,n,s,d,h){return a(n,s,d,h)},EudDk:function(a,n){return a!==n},EYndL:"BEpyy",gVNJj:t(525),ZiBjZ:function(a,n){return a<<n},VaEXP:t(1641),OkLoe:t(1173)+t(499),ToPTe:t(1173)+"er_is_ack",FLaXj:t(1173)+t(1588)+t(1001),hyWJx:function(a,n,s,d){return a(n,s,d)},OTDsn:t(1550),TEbbd:"is_ack",fqwZK:function(a,n){return a&&n},WAnoi:function(a,n){return a===n},gErVS:"WmcNi",CYnrn:"wYqsQ",OvSVd:t(405),wpnUG:t(1524),aCVCO:"received",vbXdh:t(615),ZOCud:t(484),dDfok:function(a,n){return a(n)},zEnZz:function(a,n){return a(n)},sTTLC:function(a,n){return a instanceof n},xGTvA:function(a,n){return a instanceof n},yZpMb:function(a,n){return a instanceof n},YgIfE:t(523)+"ion/json"+t(1215)+"=utf-8",gFanI:function(a,n){return a!==n},bjITf:t(1498),fCPBS:function(a){return a()},XbkEG:"PWoML",yNQqu:function(a,n){return a<n},swYsR:function(a,n){return a>n},BbwUV:function(a,n){return a(n)},iWHKk:function(a,n){return a&n},cGYQW:function(a,n){return a||n},pBRfD:function(a,n){return a+n},rtnXs:function(a,n){return a>n},xeiEs:function(a,n){return a>n},nPnDb:function(a,n){return a!==n},kqJOb:"eJoPE",zUKYk:t(932),Cwqtr:function(a,n){return a+n},BblhV:"index ou"+t(395)+t(1281),IhuCR:t(548),cRjjk:" > ",gzNHJ:function(a,n){return a!==n},EMIVL:t(1368),uLGrk:t(703),ZMuxc:function(a,n){return a>n},RIZoa:t(203)+t(578)+"e",ZjBFK:function(a,n){return a&n},rLbgQ:function(a,n){return a+n},SCAcC:function(a,n){return a+n},DaGBl:function(a,n){return a+n},uBJzy:function(a,n){return a===n},KgjPO:"rsmLa",xuWlP:function(a,n,s){return a(n,s)},YxbFA:"1|0|2|3|4",IwsZu:function(a,n){return a<n},uaVnU:function(a,n){return a+n},alLIv:function(a,n,s,d){return a(n,s,d)},aSFvl:function(a,n){return a|n},nANfh:function(a,n){return a|n},GehOn:function(a,n){return a<<n},VGRia:function(a,n){return a+n},FQEQO:function(a,n){return a<<n},ioEzm:function(a,n){return a<<n},KdswP:function(a,n){return a<<n},VSRME:function(a,n){return a&n},AdiYQ:function(a,n){return a>>>n},eQzWB:function(a,n){return a+n},Yyfzs:function(a,n){return a&n},zgBEc:function(a,n){return a>>>n},roMHE:function(a,n){return a!==n},aVkRZ:"LOfHE",HOWWA:t(465),nAqmz:function(a,n){return a>>>n},qcmgO:function(a,n){return a<n},ihPWD:function(a,n){return a&n},VYFIy:function(a,n){return a<n},SbIQD:function(a,n){return a>>>n},eFDOI:function(a,n){return a&n},EcVSd:function(a,n){return a|n},vusVc:function(a,n){return a>>>n},biOLl:function(a,n){return a|n},QgKXS:function(a,n){return a<<n},sptCJ:function(a,n){return a!==n},ZCiOJ:t(812),znJIg:function(a,n,s,d){return a(n,s,d)},wsDpj:function(a,n){return a(n)},PPuPS:t(1152)+t(513)+"|4|7|9",rETRu:function(a,n,s,d){return a(n,s,d)},jZsuI:function(a,n,s,d){return a(n,s,d)},UWQEm:t(359),mWcQV:function(a,n){return a(n)},PieWM:function(a,n){return a(n)},rbDRV:t(462)+t(305),oEcGV:function(a,n){return a<n},CUAbE:function(a,n,s){return a(n,s)},sKXzm:function(a,n,s){return a(n,s)},bHvBI:function(a,n){return a+n},lzaBa:function(a,n,s){return a(n,s)},NIzpX:function(a,n){return a===n},SMZsP:t(268),xcQgy:t(1583),Zwdks:t(1318)+t(831),uVyEP:function(a,n,s){return a(n,s)},kRPpb:t(788)+"ame",YpXLa:t(555)+"rValues",VVXDn:t(1654),CtnvH:function(a,n,s,d){return a(n,s,d)},srFcs:t(1446),AmZcK:t(919),MrDtS:function(a,n,s,d){return a(n,s,d)},KdSeW:"setdb",bYHyr:t(727),oGEza:t(173),uaxrE:t(1091)+"r",JYabF:function(a,n){return a||n},doGul:function(a,n){return a!==n},wmFic:t(1691),bVQck:function(a,n){return a+n},NKFEz:function(a,n){return a+n},YQdEp:function(a,n){return a&n},nsiyY:function(a,n){return a<<n},ZHJRc:function(a,n){return a<<n},KwUMN:function(a,n){return a>=n},hOdPX:function(a,n){return a<=n},oOBYv:function(a,n){return a(n)},xzvPr:function(a,n,s,d){return a(n,s,d)},hYDLN:t(1089),CYKet:t(1173)+t(183),xzaIV:function(a,n,s){return a(n,s)},YPVTn:t(1173)+t(1350),tpZtZ:"x-msg-qos",jCgLH:function(a,n,s){return a(n,s)},GVeLy:t(1104)+t(1123)+"e",ZPEHg:function(a,n){return a(n)},SSEZi:function(a,n,s){return a(n,s)},Jrvua:t(1104)+t(1194)+"ue",XFqUF:function(a,n){return a>n},qGYlC:function(a){return a()},HZxFB:t(883),tLWuj:function(a){return a()},MScwR:function(a){return a()},hyXwD:function(a){return a()},wGGbU:function(a,n,s){return a(n,s)},vbTud:function(a){return a()},QhjyN:function(a,n){return a(n)},xDeOk:function(a,n){return a===n},KJplz:t(486),lNrQu:t(953),YGAOu:function(a,n){return a(n)},UwBOo:function(a,n){return a instanceof n},caHux:function(a,n){return a!==n},fMKCo:function(a){return a()},WPywF:function(a,n){return a<n},QjDNi:function(a,n){return a===n},FVaik:"Lgggg",GgnNg:function(a,n,s){return a(n,s)},SjQYL:function(a){return a()},kyTVV:"vsWaw",UfiPb:function(a,n,s){return a(n,s)},FqdJL:function(a,n,s){return a(n,s)},XhiIC:function(a,n){return a===n},OChHI:function(a,n,s,d){return a(n,s,d)},LDZFI:t(599),VjnQg:function(a,n){return a(n)},aZRKR:t(537)+t(1590),ktrgt:t(221),IoglQ:t(350)+t(325)+t(1675),VxYGM:t(350)+"rovide w"+t(1257)+t(340)+t(680)+t(1677)+t(767)+t(1484),bQEKO:t(1046)+"ediately"+t(1604)+"ct",ZtRuM:t(1210),BDybp:t(811),XFdRQ:function(a,n){return a|n},poCkn:function(a,n){return a||n},tIDci:t(1057),Hpfcp:t(1292),vvqKX:t(341),hEApR:function(a,n){return a!==n},rjWOY:"https:",ITcks:t(780),Cmpoi:t(1042),UpaRl:t(1122),AxQHw:t(585),ZkThU:function(a,n){return a||n},iOjyG:t(697),koqhg:t(942)+"0",zWwYZ:function(a,n){return a(n)},RQvAf:function(a){return a()},ydRCY:function(a,n,s){return a(n,s)},xhdgb:function(a,n){return a===n},YKPnf:t(1170),kOqjH:t(1055),nssLV:"reconnect",lnoAT:t(710),GONpN:function(a,n){return a>n},HijOU:function(a,n,s){return a(n,s)},EhrVz:t(208),xeMeL:function(a,n){return a(n)},wmlqU:t(210),LfmYo:function(a,n){return a>n},vSFpv:function(a,n){return a>>n},EWqvz:function(a,n){return a>>n},JsmUr:t(180),bxmdz:t(1258),LdEDW:"ping_once_timeout",ZalyV:t(731)+t(940)+t(433)+t(1160)+"ver",YDdve:function(a,n){return a!==n},gJVql:function(a,n,s){return a(n,s)},KJjPM:function(a,n){return a!==n},ekIGD:t(1261),KljeO:function(a,n){return a(n)},nCqNf:function(a,n){return a===n},ZuWnS:t(1222),JYlSq:t(1531)+"2",rcJKh:function(a,n){return a+n},eNuam:function(a,n){return a|n},lxLTT:t(1386),hrXNw:t(264),bBFZH:function(a,n,s){return a(n,s)},OvgPx:function(a,n,s){return a(n,s)},acskC:t(1228),QqeMg:"ack",htAPA:t(757),ZHrrT:t(660),TjnRR:"lrYSI",MpIGa:function(a,n){return a===n},Hbexb:t(741),IICQn:"6|4|5|7|"+t(700),nnLJk:t(1596)+t(1686)+t(970)+"nitialized",FTllq:function(a,n){return a===n},lpiso:function(a,n){return a===n},mkasO:t(1596)+"s alread"+t(469),TCXuk:t(823)+"4",LDkAC:t(350)+t(622)+t(967)+t(1006)+"a must b"+t(872)+t(1202)+t(311)+t(692),LzgFt:function(a,n){return a==n},svJNI:t(1241),YUPmA:function(a,n){return a!=n},SRCaX:function(a,n){return a instanceof n},wXYNB:function(a,n){return a===n},NYREM:function(a,n){return a!==n},TPczZ:t(399),poeCg:t(488),nMWFB:function(a,n){return a<n},hTFGn:t(1075),ZNbnQ:t(1458),kTNoS:function(a,n){return a!==n},sFWMM:"manual r"+t(1154)+t(561),UnLCA:function(a,n){return a&n},qzdXa:function(a,n){return a&n},mzoyf:t(536),otouM:t(1655),kGpoX:t(968),cXRGK:function(a,n){return a===n},XtbNc:t(782),rwbZi:function(a,n){return a===n},kTYjP:"Object",xVzWJ:function(a,n){return a===n},dQyGc:t(424)+"dWorkerG"+t(471)+"pe",qdbOG:function(a,n){return a!=n},Xrxfm:function(a,n){return a!=n},OYETA:function(a,n){return a==n},kANpQ:function(a,n){return a!=n},lBuqY:t(1581)+t(1647)+t(833),Xjtnm:function(a,n){return a!=n},eONOt:function(a,n){return a===n},SzXkZ:"__x_msg_"+t(804)};Mt.r(Ce),Mt.d(Ce,{FWS:()=>xg,CustomErrorEvent:()=>tl,createCloseEvent:()=>xt,ReconnectEvent:()=>el,createErrorEvent:()=>at,decodedFrame:()=>en,createOpenEvent:()=>al,CustomCloseEvent:()=>nl,createReconnectEvent:()=>ua,FrontierMessageEvent:()=>il,encodeFrame:()=>Ft,createMessageEvent:()=>ol,OpenEvent:()=>sl,ErrorCode:()=>nn,Event:()=>tr,MessageEvent:()=>rl});let r="";function i(a=""){let n=t,s="02",d=""+Date[n(1240)](),h=r||(r=e.EuxOC(f,a)),w=Math.random()[n(494)](16)[n(742)](-6);return e[n(1449)](e[n(1449)](s,d)+h,w)}function o(){let a=t;return e[a(1449)](e[a(1556)](1e4,Date[a(1240)]()),Math[a(595)](e[a(1556)](1e4,Math[a(1592)]())))}function c(a){let n=t;return e.HOIfJ(e[n(1584)](Array,8)[n(920)]("0"),e[n(1331)](parseInt,a,10)[n(494)](2)).slice(-8)}function l(a){let n=t;return(e[n(1567)](Array,4)[n(920)]("0")+parseInt(a,2)[n(494)](16))[n(742)](-4)}function u(a){let n=t,s=a.split(/\./).map(w=>c(w)),d=[];return d[0]=e[n(473)](l,e.sAxgk(s[0],s[1])),d[1]=e[n(877)](l,s[2]+s[3]),["0000",e.dLMpx,e[n(1571)],e[n(1571)],e[n(1571)],n(293),d[0],d[1]][n(920)]("")}function f(a){let n=t,s={nQzsB:function(d,h){return e.sAxgk(d,h)},BNnzP:function(d,h){return e[j(1577)](d,h)}};if(e[n(1611)](e[n(331)],e[n(331)])){let d=/(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(1572)](a),h=/(([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 d?e.EuxOC(u,a):h?e[n(877)](x,a):e[n(1509)]}else return rbIFdy[n(707)](1e4*_0x330af6[n(1240)](),_0x345072[n(595)](rbIFdy[n(628)](1e4,_0x5e58ea.random())))}function x(a){let n=t,s="",d=[],h=0,w=0,E=!0,v=e[n(1571)];if(e[n(1182)](a[n(1435)]("::"),-1)){let p=a[n(725)]("::");for(let O=0;e[n(437)](O,p[n(1058)]);O++){let F=p[O];if(F[n(1435)](":")>0){let K=F[n(725)](":");E&&(h=K.length),w+=K[n(1058)];for(let U=0;e[n(437)](U,K[n(1058)]);U++)if(e[n(558)](4,K[U][n(1058)])){if(e[n(648)]!=="xYWSu")return this[n(197)]?this[n(197)].protocol:"";{let Z=v[n(218)+"g"](0,e[n(1334)](4,K[U][n(1058)])),De=Z[n(406)](K[U]);d[n(382)](De)}}else d.push(K[U]);E=!1}else{if(e.Evptp(4,F.length)){let K=v.substring(0,e[n(1334)](4,F[n(1058)])),U=K.concat(F);d[n(382)](U)}else d[n(382)](F);E&&(h+=1),w+=1,E=!1}}let L="";for(let O=0;e[n(284)](O,e[n(1530)](8,w));O++)L=L[n(406)](v);for(let O=0;e[n(1294)](O,d[n(1058)]);O++)e.EoXnb(O,h)&&(s=s[n(406)](L)),s=s[n(406)](d[O]);return s}{let p=a[n(725)](":");for(let L=0;L<p[n(1058)];L++){let O=p[L];if(p[L][n(1058)]!==4){let F=v[n(218)+"g"](0,e[n(1400)](4,p[L][n(1058)])),K=F[n(406)](O);s=s.concat(K)}else s=s.concat(O)}return s}}function g(a,n){let s=t;if(e[s(1695)]===e[s(239)])return 0;{let d=a[s(683)];if(e[s(558)](void 0,d))if(e.GDwlY===s(1595)){let w=this[s(1118)][s(1628)+s(206)+"nc"](this._prefix),E=_0x51d4ad[s(836)](w||"{}");return _0x43121f[s(770)](E)}else pe(n,10),e[s(1331)](G,n,d);let h=a[s(605)];e[s(558)](void 0,h)&&(e.IRFOz(pe,n,18),e[s(875)](G,n,h))}}function m(a){let n=t,s={uDOcR:e.nZlei,VVOeQ:function(d,h,w){return e[j(1510)](d,h,w)}};if(e[n(558)](e[n(458)],e[n(385)])){let d={};e:for(;!e[n(283)](V,a);)if(e.EoXnb(n(1482),e[n(1533)])){let h=xe(a);switch(h>>>3){case 0:break e;case 1:d[n(683)]=e[n(390)](R,a,e.usxIa(xe,a));break;case 2:d[n(605)]=R(a,xe(a));break;default:e[n(1365)](T,a,e[n(838)](7,h))}}else this[n(229)](s[n(1238)],s[n(868)](_0x3dc7d3,s[n(1238)],{message:this[n(1115)+n(335)+n(452)](_0x504356)}));if(e.EoXnb(void 0,d[n(683)]))throw new Error(e.UiwHg);if(e[n(1611)](void 0,d[n(605)]))throw new Error(e.tGyOW);return d}else _0xf0d27f[n(993)+n(958)+n(1427)](LYhytT[n(1067)],_0x32d9b5),_0x40653e["removeEv"+n(958)+n(1427)](LYhytT[n(445)],_0xe929fb),_0x43df4[n(993)+n(958)+n(1427)](LYhytT[n(551)],_0x2d097a)}function S(a){let n=t;if(e[n(819)](e.JWpcK,e[n(371)])){let s=C();return _(a,s),e[n(877)](M,s)}else return _0x380894||(_0x2437df=[_0x3ce9c4.prototype[n(1527)],_0x319cfa[n(1197)+"e"][n(380)],_0x4b7bc4.prototype.continuePrimaryKey])}function _(a,n){let s=t,d={IVaci:e.tngaM},h=a[s(470)];e[s(1048)](void 0,h)&&(e.OTzUl(pe,n,8),e[s(875)](ht,n,h));let w=a[s(476)];e[s(1048)](void 0,w)&&(pe(n,16),ht(n,w));let E=a.service;e[s(200)](void 0,E)&&(e.iBEBr(pe,n,24),e[s(865)](ht,n,e[s(877)](P,E)));let v=a[s(1485)];e[s(1696)](void 0,v)&&(e.iBEBr(pe,n,32),ht(n,e.DNNAQ(P,v)));let p=a[s(1177)];if(e[s(776)](void 0,p))for(let zt of p){e.iBEBr(pe,n,42);let St=e[s(1306)](C);e[s(299)](g,zt,St),e[s(1532)](pe,n,St.limit),e.HpboU(W,n,St),e[s(473)](D,St)}let L=a[s(232)+s(979)];L!==void 0&&(e.HpboU(pe,n,50),e[s(390)](G,n,L));let O=a[s(1651)+s(807)];e[s(1322)](void 0,O)&&(pe(n,58),G(n,O));let F=a.payload;e[s(1114)](void 0,F)&&(e.spSMf(pe,n,66),e.KlGuo(pe,n,F[s(1058)]),e[s(860)](oe,n,F));let K=a[s(1090)];e[s(881)](void 0,K)&&(e[s(805)](pe,n,74),e[s(1580)](G,n,K));let U=a[s(1520)+s(1421)];e[s(1114)](void 0,U)&&(e.PTsLj(pe,n,82),e.wBUZR(G,n,U));let Z=a.msgID;e.uBymP(void 0,Z)&&(e[s(1254)](e[s(870)],e[s(696)])?(_0x2dc52e&&_0x168d30[s(596)+s(783)](ySqWhb.IVaci,()=>_0x487941()),_0x227426&&_0x288c26["addEvent"+s(783)](s(400)+s(1537),()=>_0x1123e0())):(e[s(1538)](pe,n,90),e.HpboU(G,n,Z)));let De=a[s(981)+"e"];e.gVwqE(void 0,De)&&(e[s(1491)](pe,n,96),ht(n,P(De)))}function b(a){return e[t(473)](I,B(a))}function I(a){let n=t,s={};e:for(;!V(a);){let d=e[n(957)](xe,a);switch(e[n(1466)](d,3)){case 0:break e;case 1:s.SeqID=e[n(299)](vt,a,!0);break;case 2:s[n(476)]=vt(a,!0);break;case 3:s[n(826)]=e[n(1327)](xe,a);break;case 4:s[n(1485)]=e.pnrUI(xe,a);break;case 5:{let h=e[n(1472)](A,a);(s[n(1177)]||(s[n(1177)]=[]))[n(382)](e[n(1584)](m,a)),a[n(820)]=h;break}case 6:s["payloadE"+n(979)]=e[n(1496)](R,a,e[n(1472)](xe,a));break;case 7:s.payloadType=e.KaZJw(R,a,xe(a));break;case 8:s[n(623)]=e[n(1551)](se,a,xe(a));break;case 9:s[n(1090)]=e[n(1638)](R,a,e[n(1670)](xe,a));break;case 10:s[n(1520)+n(1421)]=e[n(914)](R,a,e[n(1567)](xe,a));break;case 11:s.msgID=e[n(1496)](R,a,e[n(287)](xe,a));break;case 12:s[n(981)+"e"]=e[n(957)](xe,a);break;default:e[n(875)](T,a,e.DKAGk(7,d))}}if(e[n(534)](void 0,s.SeqID))throw new Error(n(753)+n(1093)+n(294)+n(470));if(e[n(534)](void 0,s[n(476)]))throw new Error(e[n(215)]);if(e.RoQWM(void 0,s[n(826)]))throw new Error(e[n(575)]);if(e[n(534)](void 0,s[n(1485)]))throw new Error(n(753)+n(1093)+n(294)+n(1485));return s}function A(a){let n=t,s=e[n(877)](xe,a),d=a.limit;return a[n(820)]=e[n(1449)](a[n(900)],s),d}function T(a,n){let s=t;switch(n){case 0:for(;128&te(a););break;case 2:e[s(554)](Y,a,e.szIsv(xe,a));break;case 5:e[s(1609)](Y,a,4);break;case 1:e[s(388)](Y,a,8);break;default:throw new Error("Unimplem"+s(368)+"pe: "+n)}}function P(a){let n=t;return a|=0,{low:a,high:e[n(265)](a,31),unsigned:e[n(1378)](a,0)}}let y=[];function C(){let a=t,n=y[a(664)]();return n?(n[a(900)]=n[a(820)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(a){y[t(382)](a)}function B(a){return{bytes:a,offset:0,limit:a[t(1058)]}}function M(a){let n=t,s=a.bytes,d=a[n(820)];return s.length===d?s:s.subarray(0,d)}function Y(a,n){let s=t;if(s(973)!==e[s(1105)])return _0x496d85?this[s(849)+"E"]():this[s(1129)+"E"]();if(e.ogsRG(e.HOIfJ(a.offset,n),a[s(820)]))throw new Error(e.DcduO);a[s(900)]+=n}function V(a){let n=t;return e[n(1378)](a[n(900)],a[n(820)])}function re(a,n){let s=t,d={VzMxB:function(h,w){return e[j(766)](h,w)},mTOqj:function(h,w){return h<w},SDkED:function(h,w){return e[j(1519)](h,w)},fYxOT:function(h,w){return e[j(1674)](h,w)}};if(e[s(534)](s(1547),e[s(850)]))_0x3f38b7=_0x58e9a6.charCodeAt(_0x55110b),d[s(834)](_0x36dff9,128)?_0x2adc93+=1:d[s(401)](_0x4282bf,2048)?_0x1fdbfa+=2:(64512&_0x71eac)===55296&&d[s(438)](64512,_0x4e5320[s(489)+"At"](d[s(526)](_0xc76214,1)))===56320?(++_0x5c2f35,_0x139610+=4):_0x48747e+=3;else{let h=a.bytes,w=a[s(900)],E=a.limit,v=e[s(1625)](w,n);if(e.ogsRG(v,h[s(1058)])){let p=new Uint8Array(e[s(929)](2,v));p[s(1264)](h),a[s(1659)]=p}return a[s(900)]=v,e[s(1182)](v,E)&&(a[s(820)]=v),w}}function X(a,n){let s=t,d=a[s(900)];if(e[s(1182)](e[s(799)](d,n),a[s(820)]))throw new Error(s(1684)+"t limit");return a[s(900)]+=n,d}function se(a,n){let s=t,d=e[s(1609)](X,a,n);return a[s(1659)].subarray(d,e.VOYro(d,n))}function oe(a,n){let s=t;if(e[s(558)](s(1015),e[s(1010)]))this[s(497)]=!0,this._connect();else{let d=e[s(388)](re,a,n[s(1058)]);a[s(1659)][s(1264)](n,d)}}function R(a,n){let s=t,d=e.QwQNO(X,a,n),h=String["fromChar"+s(1499)],w=a.bytes,E="\uFFFD",v="";for(let p=0;p<n;p++){let L=w[p+d],O,F,K,U;if(e.RLaHt(e.tMwYp(128,L),0))v+=e[s(957)](h,L);else if(e[s(1254)](e[s(421)](224,L),192))if(e[s(1378)](p+1,n))v+=E;else if(O=w[e[s(851)](p,d)+1],(192&O)!==128)v+=E;else if(e[s(1254)](e[s(1662)],e[s(1662)]))U=e[s(190)](e.ohPUL(31,L),6)|e.DKAGk(63,O),U<128?v+=E:(v+=e[s(1576)](h,U),p++);else return this[s(226)+s(314)+s(238)+"t"]++,this[s(1151)+"ntEndpoint"]();else e[s(845)](e[s(1407)](240,L),224)?e[s(1378)](e[s(851)](p,2),n)?v+=E:(O=w[e[s(1449)](p,d)+1],F=w[e.sAxgk(p+d,2)],e.RmIpb(e.OdktY(O,e.ZCUTz(F,8)),49344)!==32896?v+=E:e[s(1096)](s(636),e[s(619)])?(U=e[s(1023)](e[s(712)](15,L)<<12|e.laxKT(e[s(838)](63,O),6),63&F),e[s(437)](U,2048)||U>=55296&&e.QwOBB(U,57343)?v+=E:(v+=e[s(877)](h,U),p+=2)):_0x140f06.persisted&&(this[s(231)+s(1493)]()&&(!this._ws||this[s(197)].readyState!==this[s(1031)]||e[s(776)](this[s(197)][s(174)+"te"],this[s(630)+"NG"]))&&this[s(1645)+s(964)](),this[s(1040)+"er"]&&_0x1ec47["addEvent"+s(783)](e.bFrVT,this[s(1645)+s(964)]),this[s(1040)+"er"]&&_0x35898a.addEventListener(s(454),this["_handleO"+s(1471)]))):e[s(845)](e[s(1519)](248,L),240)?e[s(1301)](p,3)>=n?v+=E:(O=w[e.ArCJA(e[s(1301)](p,d),1)],F=w[e.YNWGt(e[s(1008)](p,d),2)],K=w[e[s(1255)](p+d,3)],e[s(337)](e[s(1119)](e[s(199)](O|e[s(190)](F,8),K<<16),12632256),8421504)?v+=E:e[s(558)](e.kgrXD,e[s(1502)])?(U=e[s(199)](e[s(1023)](e[s(376)](e[s(421)](7,L)<<18,e[s(945)](e[s(758)](63,O),12)),e[s(190)](e[s(838)](63,F),6)),e.sEiNh(63,K)),U<65536||U>1114111?v+=E:(U-=65536,v+=h(e[s(322)](e[s(265)](U,10),55296),e.YNWGt(e[s(1144)](1023,U),56320)),p+=3)):(_0x59705e(_0xa4bb9f,16),_0x271d57(_0x8c04e4,_0x164fe7))):v+=E}return v}function G(a,n){let s=t,d=n[s(1058)],h=0;for(let v=0;e[s(284)](v,d);v++){let p=n[s(489)+"At"](v);e[s(670)](p,55296)&&p<=56319&&v+1<d&&(p=e[s(1530)](e[s(799)](p<<10,n[s(489)+"At"](++v)),56613888)),h+=e[s(1429)](p,128)?1:p<2048?2:e[s(284)](p,65536)?3:4}pe(a,h);let w=e[s(1083)](re,a,h),E=a[s(1659)];for(let v=0;e[s(1294)](v,d);v++){let p=n[s(489)+"At"](v);e[s(1378)](p,55296)&&e[s(1041)](p,56319)&&e[s(1294)](e[s(996)](v,1),d)&&(p=e[s(1674)](p<<10,n.charCodeAt(++v))-56613888),e[s(518)](p,128)?E[w++]=p:(p<2048?E[w++]=e[s(1144)](e[s(1534)](p,6),31)|192:(p<65536?E[w++]=e[s(1023)](e[s(838)](e[s(1534)](p,12),15),224):(E[w++]=e.jbtpR(e[s(304)](e[s(175)](p,18),7),240),E[w++]=e[s(193)](e[s(416)](e[s(175)](p,12),63),128)),E[w++]=e.eRrkK(e[s(717)](p,6)&63,128)),E[w++]=e[s(495)](e[s(1021)](63,p),128))}}function W(a,n){let s=t,d=e.XFwEI(re,a,n[s(820)]),h=a[s(1659)],w=n.bytes;for(let E=0,v=n[s(820)];e[s(437)](E,v);E++)h[e[s(744)](E,d)]=w[E]}function te(a){let n=t;return a.bytes[e[n(1314)](X,a,1)]}function Xe(a,n){let s=e.GAgMK(re,a,1);a.bytes[s]=n}function xe(a){let n=t,s=0,d=0,h;do h=e.LvaJW(te,a),s<32&&(d|=e.VXsmH(127&h,s)),s+=7;while(e[n(483)](128,h));return d}function pe(a,n){let s=t;for(n>>>=0;e[s(1300)](n,128);)e[s(1395)](Xe,a,e[s(1098)](e[s(1535)](127,n),128)),n>>>=7;e.rawCB(Xe,a,n)}function vt(a,n){let s=t,d=0,h=0,w=0,E;if(E=e[s(1137)](te,a),d=e[s(838)](127,E),e.BlOXZ(128,E)&&(E=e[s(1295)](te,a),d|=e.yRqQA(e[s(988)](127,E),7),128&E))if(e[s(1011)]===e[s(1011)]){if(E=te(a),d|=e.UGDlj(e[s(1535)](127,E),14),e[s(1479)](128,E))if(e[s(881)](e[s(901)],e.ftEQc)){if(E=e.RXAEq(te,a),d|=e[s(444)](127,E)<<21,e[s(983)](128,E))if(e[s(1611)](s(1038),e[s(1452)])){if(E=e[s(1137)](te,a),h=e[s(304)](127,E),e[s(988)](128,E)&&(E=e.pnrUI(te,a),h|=e.KzhFe(127,E)<<7,e[s(483)](128,E))){if(e[s(819)](e[s(677)],e[s(541)]))_0x432415[s(639)][s(1549)+s(292)](_0x3199bd),_0xd34e8b["frontier"+s(840)]=void 0,e[s(283)](_0x1eb20d,_0x2e413a&&_0x5d1c3d[s(1587)]||e[s(420)]);else if(E=te(a),h|=e[s(911)](e.kHpTo(127,E),14),128&E)if(e[s(819)](e.SDTCB,s(1308))){if(E=e[s(735)](te,a),h|=e[s(190)](e[s(627)](127,E),21),128&E){if(e[s(1505)]==="tDUlX")return _0x494561.log(_0x193efc),!1;E=te(a),w=127&E,e.UjuAH(128,E)&&(E=te(a),w|=(127&E)<<7)}}else return new _0x52e3ef(_0x4caa70,{data:_0x3eed2d})}}else this[s(231)+s(1493)]()&&(!this[s(197)]||e[s(1322)](this[s(197)][s(174)+"te"],this.OPEN)||e[s(776)](this[s(197)][s(174)+"te"],this[s(630)+"NG"]))&&this[s(1645)+"nLine"](),this[s(1040)+"er"]&&_0x32227d[s(596)+s(783)](e[s(704)],this["_handleO"+s(964)]),this._isBrowser&&_0x1930fc[s(596)+s(783)](e[s(538)],this[s(1645)+s(1471)])}else{this[s(510)+"ngTimer"](),this[s(1174)+s(1506)+"Id"]=_0x248179(this[s(1029)][s(936)](this),this._options["pingInte"+s(1672)]);return}}else{let v=this[s(566)+s(706)]?.[s(1151)+s(1635)+"nt"]();this[s(509)]("open "+v),e[s(869)](_0x3e4a8f)}return{low:e.lcTxX(d,e[s(1063)](h,28)),high:e[s(1204)](h>>>4,e[s(1344)](w,24)),unsigned:n}}function ht(a,n){let s=t,d=n[s(1225)]>>>0,h=e.oLcpm(e[s(530)](e[s(363)](n[s(1225)],28),e[s(928)](n[s(678)],4)),0),w=e[s(1557)](n[s(678)],24),E=e[s(830)](0,w)?e[s(1575)](0,h)?e[s(518)](d,16384)?d<128?1:2:e.vAyQB(d,2097152)?3:4:e[s(426)](h,16384)?e[s(606)](h,128)?5:6:e.EqIuH(h,2097152)?7:8:w<128?9:10,v=e[s(1381)](re,a,E),p=a[s(1659)];switch(E){case 10:p[v+9]=e[s(1119)](e[s(1557)](w,7),1);case 9:p[e[s(1492)](v,8)]=E!==9?e[s(1023)](128,w):e.KzhFe(127,w);case 8:p[e[s(1674)](v,7)]=e[s(740)](8,E)?e[s(193)](h>>>21,128):e[s(838)](e[s(457)](h,21),127);case 7:p[e.ZQZEW(v,6)]=e[s(990)](7,E)?e.ifSCF(e[s(960)](h,14),128):e[s(983)](e[s(937)](h,14),127);case 6:p[e[s(1316)](v,5)]=e[s(1277)](6,E)?e[s(1247)](e[s(1209)](h,7),128):e[s(421)](e[s(457)](h,7),127);case 5:p[v+4]=e[s(1403)](5,E)?128|h:127&h;case 4:p[e.NTKkM(v,3)]=e[s(1322)](4,E)?e.zHYMP(e[s(1557)](d,21),128):e[s(839)](e[s(999)](d,21),127);case 3:p[e.yAqWn(v,2)]=e.foLqV(3,E)?d>>>14|128:e.sEiNh(e[s(1209)](d,14),127);case 2:p[e[s(1411)](v,1)]=e[s(477)](2,E)?d>>>7|128:d>>>7&127;case 1:p[v]=e[s(881)](1,E)?128|d:e[s(1407)](127,d)}}function en(a){return e[t(957)](b,a)}function Ft(a){return e[t(1576)](S,a)}let tn=65536,Yr=e.kGpoX,we=e[t(1577)](tn,tn),Ie=we*we,er=e[t(281)](Ie,2),Pe=String[t(1197)+"e"][t(489)+"At"];class fe{constructor(n,s,d){let h=t;this[h(1553)]=!0,this[h(1225)]=e.IPFyQ(0,n),this[h(678)]=0|s,this[h(579)]=!!d}static[t(1553)](n){let s=t;return n&&e[s(815)](!0,n[s(1553)])}static fromBits(n,s,d){return new fe(n,s,d)}static fromBytes(n,s,d){let h=t;return d?fe.fromBytesLE(n,s):fe[h(1274)+h(1657)](n,s)}static[t(1274)+t(1187)](n,s){let d=t;return new fe(e[d(1340)](n[0]|e[d(1185)](n[1],8)|e[d(1593)](n[2],16),e[d(263)](n[3],24)),e[d(193)](e[d(178)](e.kTnyz(n[4],n[5]<<8),n[6]<<16),e[d(1344)](n[7],24)),s)}static[t(1274)+"sBE"](n,s){let d=t;if(e[d(1277)](e[d(671)],e[d(671)]))_0x4cf0cc[d(639)][d(1549)+d(292)](_0x1a0e3a);else return new fe(e[d(530)](e[d(376)](e[d(1023)](e[d(1185)](n[4],24),e[d(192)](n[5],16)),e[d(1439)](n[6],8)),n[7]),e[d(1340)](e.zidQI(n[0],24)|e[d(1344)](n[1],16)|e[d(1307)](n[2],8),n[3]),s)}static[t(1179)](n){let s=t;return e[s(819)](n,Yr)?Qd:new fe(e[s(303)](e[s(1591)](e[s(588)](Pe[s(708)](n,0),e.xFykR(Pe[s(708)](n,1),8)),e[s(1367)](Pe[s(708)](n,2),16))|e.RdOhB(Pe[s(708)](n,3),24),0),e.GGYKz(e[s(1591)](e[s(1285)](Pe[s(708)](n,4),e.rfCqD(Pe[s(708)](n,5),8))|e[s(674)](Pe[s(708)](n,6),16),e[s(945)](Pe[s(708)](n,7),24)),0),!0)}[t(1227)](){let n=t,s={CUtPK:function(d,h){return d+h},HHyqV:function(d,h){return e[j(1410)](d,h)},BXNbS:function(d,h,w){return d(h,w)}};return e.gAolx===e.dClrb?EyjtCK[n(567)](EyjtCK.HHyqV(_0x454899,8)[n(920)]("0"),EyjtCK[n(1062)](_0x2ddb2c,_0x43635a,10)[n(494)](2))[n(742)](-8):String[n(436)+"Code"](e.sHVGd(255,this.low),e.ohPUL(e[n(843)](this[n(1225)],8),255),this[n(1225)]>>>16&255,e.oLcpm(this.low,24),e.LSbsr(255,this[n(678)]),e[n(1209)](this[n(678)],8)&255,e.WrjIr(e.SgGZR(this.high,16),255),e[n(184)](this[n(678)],24))}static fromNumber(n,s=!0){let d=t;if(e[d(709)](e[d(1071)],e[d(1071)])){if(e[d(297)](isNaN,n))return s?Ap:Qd;if(s){if(e[d(461)](n,Ie))return Tp}else{if(e[d(608)](n,-er))return Cp;if(n+1>=er)return kp}return fe[d(665)](e[d(691)](n%we,0),e[d(281)](n,we)|0,s)}else return this[d(1406)][d(174)+"te"]}[t(1692)](){let n=t;return this[n(579)]?e[n(1178)](e[n(929)](e.hcPQR(this.high,0),we),e.CeFdw(this.low,0)):e[n(1663)](this[n(678)]*we,e[n(468)](this[n(1225)],0))}[t(308)](){let n=t;if(e[n(1249)](e.RtNDr,e.hhJIj))return e[n(1096)](0,this[n(678)])&&e[n(819)](0,this[n(1225)]);_0x387fe1(_0x3f4dcb,50),e[n(451)](_0x457ab9,_0x2a06e6,_0x4191cc)}[t(1690)](n){let s=t;fe[s(1553)](n)||(n=fe.fromNumber(n));let d=this[s(678)]>>>16,h=e[s(1517)](65535,this.high),w=e[s(303)](this[s(1225)],16),E=e[s(1138)](65535,this[s(1225)]),v=n[s(678)]>>>16,p=e.oKrTW(65535,n.high),L=e[s(721)](n[s(1225)],16),O=e[s(1144)](65535,n.low),F=0,K=0,U=0,Z=0;return Z+=E+O,U+=e[s(1557)](Z,16),Z&=65535,U+=e[s(1492)](w,L),K+=e[s(363)](U,16),U&=65535,K+=e[s(322)](h,p),F+=e[s(184)](K,16),K&=65535,F+=e[s(372)](d,v),F&=65535,fe.fromBits(e[s(790)](U,16)|Z,e[s(1501)](F<<16,K),this[s(579)])}equals(n){let s=t,d={HWNMw:function(h,w){return e.sidCg(h,w)},YMkNf:e[s(295)],IzIIq:e[s(1382)],Hslwe:e[s(654)],QZoXN:function(h,w,E){return h(w,E)}};if(e[s(1371)]!=="lZOBM")return fe.isLong(n)||(n=fe[s(367)+"er"](n)),e.uBymP(this.unsigned,n[s(579)])&&e[s(261)](e.oLcpm(this.high,31),1)&&e.UnvzS(e[s(303)](n[s(678)],31),1)?!1:e[s(1226)](this[s(678)],n[s(678)])&&e[s(1282)](this.low,n.low);{let{pingInterval:h,pingFrequency:w}=this[s(1287)];if((d[s(432)]("hi",_0x22b06f.data)&&d[s(432)](d[s(698)],w)||d[s(432)](d[s(1203)],w))&&(this[s(510)+"ngTimer"](),this[s(229)](s(743)+s(1607)+"s",d.Hslwe),this[s(1174)+s(1506)+"Id"]=d[s(1051)](_0x5919b5,this[s(1029)][s(936)](this),h)),_0x13a7d5[s(1640)]==="hi")return;try{_0x200275(this,_0x330cf0,[_0x12f562,_0x3851ee,_0x1d1bd3,_0x14d971,_0x1855f7,_0x1f3dae])}catch(E){let v=d[s(1051)](_0x582e31,"error",{message:E[s(170)],code:_0x5afdf2[s(1444)+"ERROR"],error:E});this["_dispatc"+s(1339)+s(1131)](v)}}}addOne(){let n=t;return e[n(1348)](-1,this[n(1225)])&&e.yjpAv(-1,this[n(678)])?fe[n(665)](0,0,this[n(579)]):e[n(1679)](-1,this[n(1225)])?fe[n(665)](0,e[n(996)](this[n(678)],1),this[n(579)]):fe.fromBits(e[n(1099)](this.low,1),this.high,this[n(579)])}[t(866)](n){let s=t;return n?this[s(849)+"E"]():this[s(1129)+"E"]()}toBytesLE(){let n=t,s=this[n(678)],d=this[n(1225)];return[e[n(444)](255,d),e[n(758)](e[n(1466)](d,8),255),e[n(544)](d,16)&255,d>>>24,e.hfTBq(255,s),e[n(544)](s,8)&255,e[n(429)](e[n(949)](s,16),255),e[n(937)](s,24)]}[t(1129)+"E"](){let n=t,s=this[n(678)],d=this.low;return[e[n(303)](s,24),e[n(874)](e[n(468)](s,16),255),e[n(880)](s>>>8,255),e.BrLGM(255,s),d>>>24,e[n(650)](e.CCrUG(d,16),255),e.oAMwF(e.KSkVV(d,8),255),e[n(481)](255,d)]}}let Qd=new fe(0,0,!1),Ap=new fe(0,0,!0),kp=fe.fromBits(-1,2147483647,!1),Tp=fe[t(665)](-1,-1,!0),Cp=fe.fromBits(0,-2147483648,!1);var nn=(function(a){let n=t;if(e[n(829)]===e[n(355)])return e[n(1072)](e[n(1198)](_0x1ce025,4).join("0"),e[n(1579)](_0x3cea19,_0x1d6760,2).toString(16))[n(742)](-4);{let s=e[n(1053)][n(725)]("|"),d=0;for(;;){switch(s[d++]){case"0":a[a[n(1444)+n(1181)]=5004]=e[n(943)];continue;case"1":a[a[e[n(918)]]=5002]=e[n(918)];continue;case"2":return a;case"3":a[a[e[n(655)]]=5001]=n(259)+"RROR";continue;case"4":a[a[n(1159)+n(348)+"R"]=5003]=e[n(922)];continue;case"5":a[a[e[n(1260)]]=5005]=e[n(1260)];continue}break}}})({});class tr{constructor(n){this.type=n,this.target=null}}class el extends tr{constructor(n,s){let d=t;super(n),this.message=s&&s[d(170)]||null}}class tl extends tr{constructor(n,s){let d=t;if(e[d(1679)](e[d(1373)],d(1200)))super(n),this[d(1248)]=s&&s.error||null,this.colno=s&&s[d(282)]||0,this.filename=s&&s.filename||"",this.lineno=s&&s[d(169)]||0,this[d(170)]=s&&s[d(170)]||"",this[d(1089)]=s&&s[d(1089)]||5001;else{let{type:h}=_0x284837;this[d(229)](h,_0x2a724a)}}}class nl extends tr{constructor(n,s){let d=t;super(n),this.code=s&&s[d(1089)]||0,this[d(749)]=s&&s[d(749)]||"",this[d(396)]=s&&s.wasClean||!1,this[d(564)+d(685)]=s&&s["willReco"+d(685)]||!1}}class rl extends tr{constructor(n,s){let d=t;super(n),this[d(1640)]=s&&s[d(1640)]||null}}class il extends rl{constructor(n,s){let d=t;super(n),this[d(1640)]=s&&s[d(1640)]||null,this[d(170)]=s&&s[d(170)]||null}}class sl extends tr{constructor(n,s){let d=t;super(n),this.data=s&&s[d(1640)]||null}}function at(a,{message:n,code:s,error:d}){return new tl(a,{message:n,code:s,error:d})}function xt(a,{code:n,reason:s,wasClean:d,willReconnect:h}){return new nl(a,{code:n,reason:s,wasClean:d,willReconnect:h})}function ol(a,{data:n,message:s}){return new il(a,{data:n,message:s})}function al(a,{data:n}){return new sl(a,{data:n})}function ua(a,{message:n}){return new el(a,{message:n})}class cl{constructor(n,s){let d=t;e.aOTRS(e.bKoFG,d(286))?_0x539a00.d=(h,w)=>{let E=d;for(var v in w)_0x473c7d.o(w,v)&&!_0x4de97f.o(h,v)&&_0x1a4a9f[E(1130)+E(1515)](h,v,{enumerable:!0,get:w[v]})}:(this[d(312)+"s"]=n,this[d(1442)+"es"]=s,this[d(1436)+"ndex"]=0,this[d(226)+"ndpointT"+d(238)+"t"]=0)}["resetEndpointCon"+t(897)](){let n=t;this[n(1436)+n(961)]=0,this[n(226)+n(314)+n(238)+"t"]=0}[t(1176)+"es"](){let n=t;this[n(226)+n(314)+n(238)+"t"]=0}[t(1151)+t(1635)+"nt"](){let n=t;return this[n(312)+"s"][this["currentI"+n(961)]]}[t(1151)+t(1635)+t(781)+t(618)](){return this[t(226)+"ndpointTriesCount"]}["checkRea"+t(414)+"es"](){let n=t;return!!(e[n(1378)](this["currentI"+n(961)],this[n(312)+"s"][n(1058)])||this[n(1436)+n(961)]===e.jCDbw(this[n(312)+"s"][n(1058)],1)&&e[n(430)](this["currentEndpointT"+n(238)+"t"],this[n(1442)+"es"]))}["checkCur"+t(1078)+t(1377)+"hedMaxRe"+t(317)](){let n=t;return e.aCCvz(this["currentI"+n(961)],this[n(312)+"s"].length)?!0:e[n(288)](this[n(226)+n(314)+n(238)+"t"],this[n(1442)+"es"])}[t(1289)+t(921)+"pointAnd"+t(360)+t(695)](){let n=t;if(e[n(200)](e.gpMqO,e[n(1430)]))return this[n(226)+"ndpointT"+n(238)+"t"]=1,this[n(1436)+n(961)]++,this[n(312)+"s"][this["currentI"+n(961)]];_0x43cd2c[n(1128)](_0x548871)}[t(1151)+t(1635)+t(1619)+"ateCount"](){let n=t;return this[n(226)+n(314)+n(238)+"t"]++,this.getCurrentEndpoint()}}let nr=(e[t(779)](e[t(1157)],typeof globalThis)&&e[t(422)](e[t(1666)],globalThis.constructor[t(359)])||e.YUPmA(e[t(1157)],typeof window)&&e.rwbZi(e[t(1666)],window[t(617)+t(791)][t(359)]))&&e[t(1157)]!=typeof document,Rn=e[t(1158)](e.WXaPo,typeof globalThis)&&(e.NkHfJ(e[t(557)],globalThis[t(617)+t(791)][t(359)])||e.xVzWJ(e[t(1620)],globalThis[t(617)+"tor"][t(359)]))&&e.qdbOG(e.WXaPo,typeof tt),Jr=(e[t(1648)](e[t(1157)],typeof globalThis)&&e.kTYjP===globalThis["construc"+t(791)][t(359)]||e.OYETA(e.WXaPo,typeof globalThis)||e.WXaPo!=typeof globalThis&&!!globalThis.WeixinJSBridge)&&e[t(1158)](e[t(1157)],typeof wx),Xr=e.kANpQ(e[t(1157)],typeof globalThis)&&(e[t(430)](e.dQyGc,globalThis[t(617)+"tor"][t(359)])||t(701)+t(1140)+t(1469)===globalThis["construc"+t(791)][t(359)]||e[t(345)](e[t(235)],globalThis["construc"+t(791)][t(359)]))&&e.YUPmA(t(924)+"d",typeof self),Rp=e.Xjtnm("undefined",typeof globalThis)&&e[t(448)](e[t(557)],globalThis[t(617)+"tor"][t(359)])&&e[t(1521)](e[t(1157)],typeof global)&&e[t(557)]===global[t(617)+t(791)].name&&e[t(1648)](t(924)+"d",typeof process)&&!!process[t(950)];class fa{constructor(){let n=t;this[n(362)+"rs"]={}}[t(229)](n,...s){let d=t,h=this[d(362)+"rs"][n];if(h)h[d(742)]()[d(1110)](w=>w.fn[d(1143)](w[d(413)],s));else if(e[d(298)](d(1248),n)&&!this[d(1526)]){let w=s[d(1058)]&&s[0];if(e[d(800)](w,Error))throw w;let E=new Error(e[d(645)](e[d(177)],w?e[d(1411)](e.NTKkM(" (",w[d(170)]),")"):""));throw E[d(887)]=w,w}return this}off(n,s){let d=t;if(n===void 0)this[d(362)+"rs"]={};else if(e[d(298)](void 0,s))this[d(362)+"rs"][n]=null;else{let h=this[d(362)+"rs"][n];if(h)for(let w=0;e.nJVzc(w,h[d(1058)]);)e[d(261)](h[w].fn,s)?h[d(1615)](w,1):++w}return this}on(n,s,d){let h=t;return(this[h(362)+"rs"][n]||(this[h(362)+"rs"][n]=[]))[h(382)]({fn:s,ctx:d||this}),this}}class Pp extends fa{["_formatE"+t(335)+t(452)](n){let s=t,d={IfkNq:e.nZlei,GWqVD:function(h,w,E){return e[j(334)](h,w,E)},PnqcL:function(h,w){return e[j(1411)](h,w)}};if(e[s(569)]!==e[s(434)])return n[s(195)]||n[s(408)]?(s(1431)+" "+(n[s(195)]||"")+s(392)+(n[s(408)]||""))[s(1146)]():JSON[s(1184)+"y"](n);{let h=_0x5ecec8[s(1432)][s(742)](_0x8bbb52[s(1014)+"et"],d[s(793)](_0x191586[s(1374)+"th"],_0x1e29b8.byteOffset));this._socket&&this[s(1406)][s(986)]({data:h,fail:w=>{let E=s;this.emit(d.IfkNq,d.GWqVD(_0x42de9d,d[E(797)],{message:this[E(1115)+"rrorMess"+E(452)](w)}))}})}}constructor(n,s,d){let h=t;if(e[h(682)](e[h(787)],e.HRZFH)){let w=_0x3b5b2a[h(170)][h(623)];w&&_0xbb7c47[h(798)+"rs"](w)}else super(),this[h(1406)]=null,Jr&&wx[h(1573)+"ocket"]&&(this[h(1406)]=wx[h(1573)+"ocket"]({url:n,protocols:s,header:d,fail:this[h(412)+"ocketFai"+h(572)][h(936)](this),success:this[h(412)+h(733)+"cessHand"+h(1626)][h(936)](this)})),Rn&&tt[h(1573)+"ocket"]&&(this[h(1406)]=tt[h(1573)+h(250)]({url:n,protocols:s,header:d,fail:this[h(412)+"ocketFai"+h(572)][h(936)](this),success:this[h(412)+"ocketSuc"+h(1448)+h(1626)][h(936)](this)}))}[t(412)+t(733)+t(1448)+t(1626)](){let n=t;n(552)!==e[n(1013)]?(this["_cursorN"+n(1049)]=_0x36102c,this[n(997)+n(1405)]=_0x39a65c,this[n(737)+n(1007)]=_0x38daea,this._qosDB=e[n(1030)](_0x552c15,this[n(1120)+"ameSpace"],"cursor_n"+n(1364))):Promise[n(508)]().then(()=>{let s=n;this[s(1669)+s(222)]()})}[t(412)+t(1390)+t(572)](n){let s=t,d={rmevw:function(h,w,E){return e[j(1559)](h,w,E)},Oztzk:e.nZlei,ZUVAO:e[s(662)],YQQkz:"1|2|3|0|4",zomBx:function(h,w,E,v){return h(w,E,v)},EINJg:function(h,w){return h+w},nVTWH:function(h,w,E,v){return e[s(1189)](h,w,E,v)}};if(e[s(1402)]===e[s(1402)])Promise.resolve()[s(631)](()=>{let h=s,w=d[h(795)](at,d[h(546)],{message:this[h(1115)+h(335)+"age"](n)});this[h(229)](d[h(546)],w);let E=d[h(795)](xt,h(347),{reason:this["_formatE"+h(335)+"age"](n)});this[h(229)](d[h(1273)],E)});else{let h=d[s(626)][s(725)]("|"),w=0;for(;;){switch(h[w++]){case"0":if(_0x595305[s(1259)])return _0x2bbd7b[s(1259)](_0x1ff093,_0x43c5c6)+_0x3019b8;continue;case"1":if(!_0x2ffea9)return _0x5576e8;continue;case"2":if(_0x131bbd.length<40)return d[s(1352)](_0x4707e0,_0x2be843,_0x4b9e38,_0x3d7a30)+_0x3cc7d7;continue;case"3":if(_0x40fa58[s(756)+"e"])return _0xd8e5f7[s(756)+"e"](_0x5bab01,_0x205051)+_0x215a4f;continue;case"4":return d[s(1414)](d[s(620)](_0x5e85bc,_0x399b84,_0x4fedd8,_0x40cff4),_0x2eb6b6)}break}}}[t(1669)+t(222)](){let n=t,s={lQuSr:e[n(1495)],yMfHI:function(d,h,w){return d(h,w)}};this[n(1406)][n(240)](d=>{let h=n;this.emit(e[h(1545)],al(e.baAUK,{...d,data:d[h(195)]||""}))}),this._socket[n(1422)](d=>{let h=n;this[h(229)](e[h(662)],e[h(388)](xt,e.tngaM,{...d}))}),this[n(1406)].onMessage(d=>{let h=n;this[h(229)](s[h(415)],s.yMfHI(ol,s[h(415)],{...d}))}),this[n(1406)][n(233)](d=>{let h=n;this.emit(h(1248),at(h(1248),{...d,message:d[h(195)]||""}))})}[t(986)](n){let s=t,d={meCxa:s(1248),iJVEK:function(h,w,E){return e[s(1491)](h,w,E)}};if(e[s(714)](n,Uint8Array)){let h=n[s(1432)][s(742)](n[s(1014)+"et"],e.FsSvS(n[s(1374)+"th"],n[s(1014)+"et"]));this[s(1406)]&&this[s(1406)][s(986)]({data:h,fail:w=>{let E=s;this[E(229)](d[E(1076)],d[E(464)](at,d[E(1076)],{message:this[E(1115)+"rrorMess"+E(452)](w)}))}})}else this._socket&&this[s(1406)][s(986)]({data:n,fail:h=>{let w=s;this[w(229)](w(1248),e.lrRJz(at,e.nZlei,{message:this[w(1115)+"rrorMess"+w(452)](h)}))}})}[t(347)](n,s){let d=t;this[d(1406)]&&this[d(1406)].close({code:n,reason:s})}["addEvent"+t(783)](n,s){this.on(n,s)}[t(993)+t(958)+t(1427)](n,s){let d=t;e[d(1539)]!=="BktZi"?(_0x2a373d[d(1208)+d(1230)]="",_0x27ca08.log(_0x1ffcdf)):this[d(189)](n,s)}get[t(174)+"te"](){let n=t;return this._socket[n(174)+"te"]}get[t(1080)+"pe"](){let n=t;return this[n(1406)][n(1080)+"pe"]}set[t(1080)+"pe"](n){}get[t(480)](){let n=t;if(e[n(1693)](e[n(694)],e[n(1632)])){if(this[n(566)+"tManager"]?.[n(859)+n(414)+"es"]()){let d=this[n(566)+n(706)]?.[n(1151)+n(1635)+"nt"]();this[n(723)+n(1555)+n(1131)](e[n(554)](_0x18cd33,e[n(662)],{code:1006,reason:n(185)+d+(n(377)+", max retries reached"),wasClean:!0}))}else{let d=this[n(1287)][n(433)+n(784)+n(1256)](_0x34bb8e,_0x1dea7b);this[n(723)+n(1555)+n(1131)](e[n(256)](_0x14601b,e[n(662)],{code:_0x2e9603,reason:_0x5ec123,wasClean:!0,willReconnect:d})),d&&this[n(1102)]()}return}else return this[n(1406)][n(480)]}get[t(828)](){let n=t;return this._socket[n(828)]}get extensions(){return this[t(1406)].extensions}get["buffered"+t(726)](){return 0}}function Dp(a,n){let s=t;if(n)return new n(a.url,a[s(828)]);if(e[s(1554)](Jr,Rn))return new Pp(a[s(480)],a.protocol,a[s(1177)]);if(e[s(1401)](nr,Xr)&&e[s(338)](e[s(1157)],typeof WebSocket)&&WebSocket)return new WebSocket(a.url,a[s(828)+"s"])}function Op(a){let n=t,s=e.kdXbP[n(725)]("|"),d=0;for(;;){switch(s[d++]){case"0":return!1;case"1":if(Rn&&tt[n(1573)+"ocket"])return!0;continue;case"2":if(Jr&&wx[n(1573)+n(250)])return!0;continue;case"3":if(a)return!0;continue;case"4":if(e[n(1124)](nr,Xr)&&e[n(1643)]("undefined",typeof WebSocket)&&WebSocket)return!0;continue}break}}function dl(a,n,s){let d=-1;async function h(w){let E=j;return w<=d?Promise[E(607)](new Error(E(1497)+"alled mu"+E(1445)+E(277)+E(570))):(d=w,w===s[E(1058)]?Promise[E(508)]():s[w].bind(a)(n,h[E(936)](null,w+1)))}e.dOnor(h,0)}function ll(a){let n=t,s=0,d=0;for(let h=0;e[n(1636)](h,a.length);++h)if(e[n(393)](e[n(989)],e[n(989)])){if(this[n(510)+"ngTimer"](),this["_clearTi"+n(891)](),this[n(1171)+n(1299)+"rs"](),this[n(1097)+n(1644)](1e3,_0x3326a7),this[n(1102)+n(1486)]=!1,_0xce267e&&this[n(231)+n(1493)]()&&!this["_readyCl"+n(1087)]){if(this[n(566)+n(706)]?.["checkRea"+n(414)+"es"]()){let E=this[n(566)+n(706)]?.["getCurre"+n(1635)+"nt"]();this[n(723)+n(1555)+n(1131)](_0x42eabc(n(347),{code:1006,reason:n(185)+E+(n(377)+n(1474)+n(1608)+"ached"),wasClean:!0}))}else{let E=this[n(1287)]["reconnectInterce"+n(1256)](_0x24e1d5,_0x1e6922);this[n(723)+n(1555)+n(1131)](e.NFKLE(_0x1ea94c,e.tngaM,{code:_0x57c063,reason:_0x52f4a1,wasClean:!0,willReconnect:E})),E&&this[n(1102)]()}return}this[n(231)+"orOnline"]()||this[n(496)+n(1087)]?this[n(723)+n(1555)+n(1131)](e[n(865)](_0x2a4575,e[n(662)],{code:_0x34283e,reason:n(599)})):this[n(723)+n(1555)+"ent"](_0x4e236e(e[n(662)],{code:1006,reason:n(731)+"ay, netw"+n(1637)+"ine"})),this[n(197)]=null,this[n(566)+n(706)]?.[n(511)+n(1682)+n(897)](),this[n(1525)+"sCounter"]?.["resetCou"+n(504)]()}else d=a[n(489)+"At"](h),e[n(606)](d,128)?s+=1:e[n(766)](d,2048)?s+=2:e[n(1348)](e[n(988)](64512,d),55296)&&e[n(1254)](e[n(748)](64512,a.charCodeAt(h+1)),56320)?(++h,s+=4):s+=3;return s}function ul(a,n,s){let d=t;if(e.PvsUj(s,n)<1)return"";let h="";for(let w=n;w<s;){let E=a[w++];if(E<=127)h+=String[d(436)+d(1499)](E);else if(e[d(670)](E,192)&&e[d(1139)](E,224))h+=String["fromChar"+d(1499)](e.zuixu(e[d(684)](31,E),6)|e[d(684)](63,a[w++]));else if(e[d(542)](E,224)&&E<240)h+=String["fromChar"+d(1499)](e[d(178)](e[d(653)](e.RdOhB(e[d(580)](15,E),12),e[d(190)](63&a[w++],6)),e[d(1066)](63,a[w++])));else if(E>=240){let v=e[d(1121)](e[d(374)](e[d(1247)](e.zHYMP(e[d(1063)](7&E,18),e[d(594)](63,a[w++])<<12),e[d(808)](e[d(1479)](63,a[w++]),6)),e[d(988)](63,a[w++])),65536);h+=String[d(436)+d(1499)](e.TidZR(55296,e[d(717)](v,10))),h+=String[d(436)+d(1499)](56320+e.xOIhX(1023,v))}}return h}function ha(a,n,s){let d=t,h=s,w,E;for(let v=0;e[d(1294)](v,a.length);++v)e[d(1336)]==="GtrqF"?(this[d(1525)+"sCounter"]?.addCount(),this[d(229)](d(743)+d(1045)+"t",e[d(633)]),this._pingLossCounter?.["checkRea"+d(802)+"nt"]()?this["_handleR"+d(1154)]():this[d(1029)]()):(w=a[d(489)+"At"](v),e[d(1636)](w,128)?n[s++]=w:e[d(437)](w,2048)?e.ObQDF(e[d(598)],d(666))?(n[s++]=e[d(493)](e.YlyoW(w,6),192),n[s++]=e[d(1106)](63,w)|128):(_0x58054a(e[d(654)]),this[d(189)](e.PiDbB,_0x22ee4a),this[d(189)](d(743)+d(1045)+"t",_0x57a23b)):(64512&w)===55296&&e[d(977)](64512&(E=a[d(489)+"At"](e.szfmK(v,1))),56320)?(w=e[d(969)](65536+(e.tDagl(1023,w)<<10),e[d(933)](1023,E)),++v,n[s++]=w>>18|240,n[s++]=e[d(1340)](w>>12&63,128),n[s++]=e[d(786)](e[d(1360)](e[d(717)](w,6),63),128),n[s++]=e[d(839)](63,w)|128):e.VnPSI(e[d(332)],e[d(187)])?(this["_message"+d(896)].push(_0x3032de),this[d(509)]("enqueue",_0x4644d5)):(n[s++]=e.YlyoW(w,12)|224,n[s++]=e[d(1642)](e.ponhu(w>>6,63),128),n[s++]=e[d(515)](63&w,128)));return s-h}async function fl(a){let n=t;if(e[n(972)](n(952),typeof a)){let s=new Uint8Array(e[n(1324)](ll,a));return e[n(966)](ha,a,s,0),s}return e[n(714)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[n(1432)],a[n(1014)+"et"],a[n(1374)+"th"])}function Lp(a){let n=t;try{return e[n(1693)](e.BKaVW,e[n(527)])?this[n(226)+n(314)+"riesCount"]:e[n(439)](e.SxLYU,typeof a)&&(e[n(714)](a,ArrayBuffer)||a[n(1432)]&&e[n(889)](a[n(1432)],ArrayBuffer))||e[n(439)](e.SxLYU,typeof a)?"":(JSON[n(836)](a),e[n(1487)])}catch{return e[n(845)](e[n(1213)],typeof a)?n(582)+n(319)+"et=utf-8":""}}let Np=(a,n)=>{let s=t;switch(a){case s(384):case e[s(543)]:return{[s(1380)+a]:1,"x-tt-env":n};default:return{}}};class Mp{constructor(n){let s=t;this["maxLossC"+s(618)]=n,this[s(941)]=0}[t(1278)](){let n=t;this[n(941)]++}[t(859)+t(802)+"nt"](){let n=t;return e[n(1678)](this[n(941)],this["maxLossC"+n(618)])}["resetCou"+t(504)](n=0){let s=t;this[s(1077)+s(618)]=n,this[s(941)]=0}}async function Bp(a){let n=t;if(e[n(1282)](n(446),e[n(516)]))return new Promise(s=>{let d=n;if(!nr)return e.LvaJW(s,e[d(420)]);try{let h=document.createElement(e[d(329)]);window["frontier"+d(840)]=w=>{let E=d;document[E(639)][E(1549)+E(292)](h),window[E(198)+"JSONP"]=void 0,s(w&&w[E(1587)]||E(318)+E(749))},h[d(635)]=e[d(1313)],h[d(1243)]=a.replace(/^ws/,e.kvOtJ)+e[d(853)];try{document[d(639)][d(270)+"ild"](h)}catch{document.body[d(1549)+d(292)](h)}}catch{window["frontier"+d(840)]=void 0,e.UCExs(s,e[d(420)])}});e[n(284)](_0x57de2d,65536)?_0x3e111a[_0x4615e2++]=e.IKtkh(e[n(403)](_0x98b964>>12,15),224):(_0x525ae9[_0x2cd375++]=e.aANVa(e[n(1639)](e[n(785)](_0xa4bb1c,18),7),240),_0x363ed2[_0x7c4005++]=e[n(588)](e[n(1220)](_0x4ca5c5,12)&63,128)),_0x6ee2f2[_0x186da0++]=e[n(1605)](e[n(1025)](e.InOHO(_0x1e70f8,6),63),128)}function rn(a,n,s){let d=t;return!!a?.[d(1349)](h=>h.key===n&&h[d(605)]===s)}function rr(a,n){let s=t;return a?.find(d=>d[s(683)]===n)?.value}let xa=null;async function Fp(){let a=t,n={DcgCe:e[a(1157)],IgWBc:e[a(1084)],LVZXc:"__esModule"};if(e[a(1664)](e[a(1375)],e.fDMKQ))return xa||(xa=Promise[a(508)]()[a(631)](Mt[a(936)](Mt,e[a(1370)]))),xa;SHNQVE[a(1391)]!=typeof _0x58e958&&_0x1f0c4a["toString"+a(245)]&&_0x35edf3[a(1130)+a(1515)](_0x3f2784,_0x26e956[a(494)+a(245)],{value:SHNQVE.IgWBc}),_0x43e959[a(1130)+a(1515)](_0x520b10,SHNQVE[a(590)],{value:!0})}class zp extends fa{constructor(n,s){let d=t;super(),this[d(1221)]=n,this[d(1598)]=s,this[d(1118)]=void 0,this[d(272)+d(1253)]=null}async openDB(){await this[t(237)]()}async _init(){let n=t,s={SZjGQ:function(d,h){return e[j(972)](d,h)}};if(e[n(1081)]===e[n(1081)]){if(this._qosDB)return;if(this[n(272)+"mise"])return this[n(272)+n(1253)];try{if(e[n(267)]!==n(336))this[n(997)+"ileName"]=_0x53c6e9;else{let d=this[n(1221)],h=this[n(1598)];this._initPromise=(async()=>{let w=n,{openDB:E}=await e[w(869)](Fp);this[w(1118)]=await E(w(198)+"_"+d,1,{upgrade(v){v[w(913)+"jectStore"](d,{keyPath:h})}})})(),await this[n(272)+n(1253)]}}catch(d){if(e.VnPSI(n(888),e[n(912)]))console[n(1128)](d);else return null}finally{this[n(272)+n(1253)]=null}}else return VOCPNv[n(1234)](this[n(1436)+"ndex"],this[n(312)+"s"][n(1058)])?!0:this[n(226)+n(314)+n(238)+"t"]>this[n(1442)+"es"]}async[t(1050)](n){let s=t;try{return await this[s(237)](),this[s(1118)]?.[s(1050)](this[s(1221)],n)}catch(d){console[s(1128)](d)}}async set(n,s){let d=t;return await this[d(237)](),this[d(1118)]?.[d(366)](this._dbName,n)}async[t(1419)](n){let s=t;try{if(e.pdxxH==="pnDdG")_0x2c565e.log(_0x1afa9d);else return await this[s(237)](),this[s(1118)]?.[s(995)](this[s(1221)],n)}catch(d){console[s(1128)](d)}}async[t(398)](){let n=t;try{return await this[n(237)](),this[n(1118)]?.[n(398)](this[n(1221)])}catch(s){console[n(1128)](s)}}async keys(){let n=t;return await this._init(),this[n(1118)]?.[n(1569)+"ys"](this[n(1221)])}async[t(1563)](){let n=t;return await this[n(237)](),this[n(1118)]?.[n(1563)](this._dbName)}async[t(500)](){let n=t,s={jiZph:function(d,h){return e[j(1511)](d,h)},vqoVL:function(d,h){return d(h)},wYPFn:function(d,h){return d>h},frksL:function(d,h){return e[j(322)](d,h)},wTQYU:function(d,h){return d|h},cpMPh:function(d,h){return e[j(369)](d,h)},BSpjr:function(d,h){return d>>>h}};try{if(e[n(327)]===e.RnkKG){let d=s[n(1060)](_0x79bd41,8192),h=s.BSpjr(d,1),w=null,E=d;return function(v){let p=n;if(s[p(644)](v,1)||v>h)return s[p(236)](_0x37804d,v);s.wYPFn(E+v,d)&&(w=s.vqoVL(_0x10a977,d),E=0);let L=_0x2bd8bd[p(708)](w,E,E+=v);return 7&E&&(E=s.frksL(s[p(702)](7,E),1)),L}}else this._qosDB?.[n(347)](),this[n(1118)]=void 0}catch(d){if(e[n(830)](e[n(472)],e[n(1068)])){let h=this[n(566)+n(706)]?.["getCurre"+n(1635)+"nt"]();this[n(509)](n(185)+h+" timeout"),this._disconnect(1001,e[n(991)],!0)}else console.log(d)}}get[t(637)](){let n=t;try{return!!this[n(1118)]}catch(s){return console[n(1128)](s),!1}}}class Up{constructor(n,s){let d=t,h={zqVuV:function(w,E){return e[j(714)](w,E)},hGlnh:e[d(1244)],wfpMX:e[d(1487)],mGxMQ:e[d(1213)],AxWhl:e[d(290)],afMVL:e[d(346)]};if(e[d(716)]!==e.kttRR)this[d(1190)]=n,this[d(1064)]=s,this[d(1118)]=localStorage;else{let w=h[d(501)](this[d(1287)]["payloadE"+d(979)],_0x53ed06)?{force:!!this[d(1287)][d(232)+d(979)][d(1562)],encoding:this[d(1287)]["payloadE"+d(979)][d(1578)]?this[d(1287)][d(232)+"ncoding"].encoding[d(939)](/\s/g,"")[d(856)+d(638)]():""}:{force:!1,encoding:this[d(1287)][d(232)+d(979)]?this._options[d(232)+d(979)][d(939)](/\s/g,"")["toLowerC"+d(638)]():""},E=_0x15de5e[d(232)+d(979)]?_0x25d185.payloadEncoding[d(939)](/\s/g,"")[d(856)+"ase"]():"",v=this[d(1287)][d(1651)+"ype"]instanceof _0x172102?{force:!!this[d(1287)]["payloadT"+d(807)][d(1562)],type:this[d(1287)][d(1651)+"ype"][d(635)]?this[d(1287)][d(1651)+d(807)][d(635)][d(939)](/\s/g,"")[d(856)+"ase"]():""}:{force:!1,type:this[d(1287)]["payloadT"+d(807)]?this._options[d(1651)+"ype"][d(939)](/\s/g,"").toLowerCase():""},p=_0x1a763f[d(1651)+d(807)]?_0x426a6d[d(1651)+d(807)][d(939)](/\s/g,"")[d(856)+"ase"]():"",L=v[d(1562)]?v.type:p||v.type,O=w[d(1562)]?w[d(1578)]:E||w[d(1578)],F=[h[d(1206)],h[d(867)],d(523)+d(1396)+d(1215)+d(724),h[d(1627)]],K=[h[d(1561)],h[d(181)]];this[d(1287)][d(1428)+d(1061)+"extPayload"]&&F[d(417)](L)&&(!O||K[d(417)](O))?_0x22d1ea[d(1208)+d(1230)]=_0x4dd080(_0xe75824[d(623)],0,_0x4394c8.payload[d(1374)+"th"]):_0xc3ca89["textPayl"+d(1230)]=""}}async[t(1052)](){}get[t(876)](){let n=t;return n(198)+"_"+this[n(1190)]}async[t(1050)](n){let s=t,d=this[s(1118)][s(774)](this[s(876)]);return JSON[s(836)](e[s(611)](d,"{}"))[n]}async[t(1264)](n,s){let d=t,h={XYDHX:function(w,E){return e[j(1161)](w,E)},imFaD:function(w,E){return e[j(1245)](w,E)},AaWTY:e[d(1319)],SqZWP:e.lHIuJ,FbVcA:function(w,E){return w in E}};if(e[d(1548)]===e[d(1548)]){let w=this._qosDB[d(774)](this[d(876)]),E=JSON[d(836)](e[d(1124)](w,"{}"));return E[s||n[this[d(1064)]]]=n,this[d(1118)][d(466)](this[d(876)],JSON[d(1184)+"y"](E)),s||n[this[d(1064)]]}else return HyJyao[d(1494)](_0xd11dd8,_0x472562)&&(HyJyao[d(254)](_0x2746cf,HyJyao[d(855)])||_0x4c9449===HyJyao.SqZWP)?!0:HyJyao[d(249)](_0x13b242,_0x3463d0)}async[t(1419)](n){let s=t,d=this[s(1118)][s(774)](this[s(876)]),h=JSON[s(836)](d||"{}");return h[n]=void 0,this[s(1118)].setItem(this[s(876)],JSON[s(1184)+"y"](h))}async[t(398)](){let n=t;return this._qosDB[n(398)]()}async keys(){let n=t,s=this[n(1118)][n(774)](this[n(876)]),d=JSON[n(836)](e.BsASB(s,"{}"));return Object[n(770)](d)}async[t(1563)](){let n=t,s=this[n(1118)][n(774)](this._prefix),d=JSON.parse(e[n(611)](s,"{}"));return Object.values(d)}[t(500)](){let n=t;return e[n(959)]===e[n(589)]?this[n(579)]?e[n(1269)](e[n(827)](this.high,0),_0x5ba917)+e[n(843)](this[n(1225)],0):e[n(1305)](this[n(678)],_0x32543e)+(this[n(1225)]>>>0):Promise[n(508)]()}get[t(637)](){return!!this[t(1118)]}}class Gp{constructor(n,s){let d=t;this[d(1190)]=n,this[d(1064)]=s,this[d(1118)]=Rn?tt:Jr?wx:null}async openDB(){}get[t(876)](){let n=t;return n(198)+"_"+this[n(1190)]}async get(n){let s=t;if(e[s(998)](e[s(1676)],e[s(1676)]))return this[s(197)]?this[s(197)].readyState:this[s(1287)][s(443)+s(1303)]?this[s(630)+"NG"]:this[s(634)];{let d=this[s(1118)][s(1628)+s(1433)](this[s(876)]);return JSON[s(836)](d||"{}")[n]}}async[t(1264)](n,s){let d=t,h=this[d(1118)][d(1628)+d(1433)](this[d(876)]),w=JSON[d(836)](e.AFIuh(h,"{}"));return w[s||n[this._pathKey]]=n,this._qosDB[d(1656)+d(1433)](this[d(876)],JSON[d(1184)+"y"](w)),s||n[this[d(1064)]]}async[t(1419)](n){let s=t,d=this[s(1118)][s(1628)+"geSync"](this[s(876)]),h=JSON.parse(e[s(1267)](d,"{}"));return h[n]=void 0,this[s(1118)][s(1656)+s(1433)](this[s(876)],JSON.stringify(h))}async clear(){let n=t,s={riyyh:e.nZlei};if(e.jVyLG===e[n(1415)])return this[n(1118)][n(1246)+n(1333)]();{let d=_0x438fb8(s[n(963)],{message:_0x5c5b33[n(170)],code:_0x587acf[n(1304)+"OR"],error:_0x3b7d12});this[n(723)+"hErrorEvent"](d)}}async[t(770)](){let n=t,s=this[n(1118)][n(1628)+"geInfoSync"](this[n(876)]),d=JSON[n(836)](s||"{}");return Object.keys(d)}async getAll(){let n=t,s=this[n(1118)][n(1628)+n(206)+"nc"](this[n(876)]),d=JSON[n(836)](s||"{}");return Object[n(591)](d)}closeDB(){return Promise.resolve()}get[t(637)](){return!!this[t(1118)]}}function hl(a,n){let s=t;if(e[s(378)](Rn,Rn))return new Gp(a,n);if(e[s(1291)](nr,Xr)&&e[s(1158)](e[s(1157)],typeof indexedDB))return new zp(a,n);if((nr||Xr)&&e.WXaPo!=typeof localStorage)return new Up(a,n);throw new Error(e[s(418)])}class Hp{constructor(){let n=t;this[n(478)+n(894)+"Id"]=null,this[n(478)+"l"]=36e5,this._qosDB=hl(e[n(658)],e.mGQBg)}async[t(478)+"lFlush"](){let n=t;e[n(1567)](clearInterval,this[n(478)+"lTimeoutId"]),this[n(478)+n(894)+"Id"]=setInterval(()=>{let s=n;this[s(1323)+s(1321)]()},this[n(478)+"l"])}async openDB(){let n=t;await this[n(1118)][n(1052)]()[n(631)](()=>{let s=n;this[s(478)+s(475)]()})}async["flushExp"+t(1321)](){let n=t;(await this[n(1118)]?.[n(1563)]()||[])[n(962)](({timestamp:h})=>h<Date[n(1240)]()).forEach(h=>{let w=n;this[w(1118)]?.[w(1419)](h[w(975)+"id"])})}async[t(1419)](n){let s=t;if(e[s(709)](e.iRVIk,s(711)))for(var d in _0x53dc2f)_0x5721fb.o(_0x3b0bb3,d)&&!_0x50ce29.o(_0x5a1898,d)&&_0x12b85d[s(1130)+"operty"](_0x700b00,d,{enumerable:!0,get:_0x1ac16f[d]});else return this._qosDB?.[s(1419)](n)}async[t(1264)](n,s){let d=t;return this[d(1118)]?.[d(1264)]({message_id:n,timestamp:s})}async[t(1050)](n){let s=t;if(e[s(985)](e[s(763)],e[s(407)]))return this._qosDB?.[s(1050)](n);LYhytT[s(1293)](_0x5a6d6e,LYhytT[s(1472)](_0x43f3be,_0x29cb50[s(761)]),_0x444f1b[s(1003)+"on"],_0x1eb779.newVersion,LYhytT[s(1137)](_0x149903,_0x423bf3["transact"+s(1566)]))}async[t(500)](){let n=t,s={qRJWH:function(d,h){return e[j(1290)](d,h)},zkadJ:function(d,h){return e[j(895)](d,h)},iCuuR:function(d,h){return e.OnOEW(d,h)},FLgLL:function(d,h){return e[j(1324)](d,h)}};e.VaEXP!==e[n(343)]?(_0x1c6902=faNoqO[n(789)](faNoqO[n(1283)](31,_0x5f57f6),6)|63&_0x353538,faNoqO.iCuuR(_0x55f6bf,128)?_0x3f1e7c+=_0x1f71ad:(_0x439d50+=faNoqO[n(614)](_0x235b30,_0x21a8a1),_0x162f0f++)):(clearInterval(this["_interva"+n(894)+"Id"]),await this[n(1118)]?.closeDB())}get[t(637)](){let n=t;return this[n(1118)]?.[n(637)]}}function pa(a){let n=t,s=!!this[n(1287)][n(668)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let d=e[n(1189)](rn,a[n(170)][n(1177)],e[n(1142)],"2"),h=d&&e[n(966)](rn,a.message[n(1177)],n(1173)+n(1251)+"ck","1"),w=d&&rn(a[n(170)][n(1177)],e.ToPTe,"1"),E=w?e[n(1381)](rr,a[n(170)][n(1177)],e[n(1366)])?.[n(725)](",")[n(962)](Boolean)||[]:[];return{enabled:s,isQoSMessage:d,isQoSAck:h,isAckCleanupMessage:w,ackMsgIds:E}}async function xl(){let a=t;return this["_QoSMana"+a(667)]||(this[a(1425)+"ger"]=new Hp),this[a(1425)+a(667)].isReady||await this[a(1425)+"ger"][a(1052)](),this[a(1425)+a(667)]}async function qp(a,n){let s=t,d={xeiYZ:function(p,L){return p(L)},GoudV:function(p,L){return p<L},AsBDz:function(p,L){return p<<L},zuTTs:function(p,L){return p&L}},{enableAutoAck:h}=this[s(1287)],w=e[s(1646)](rn,a[s(170)][s(1177)],e.OTDsn,"1"),E=e.HObWF(rn,a[s(170)][s(1177)],e[s(832)],"1"),v=pa[s(708)](this,a);if(e.fqwZK(h,w))if(e.WAnoi(e[s(1540)],e[s(1135)]))_0x1e0c10=VtMAmi[s(1528)](_0x4026d6,_0x1a5d91),VtMAmi[s(227)](_0x5570ed,32)&&(_0x20fc60|=VtMAmi.AsBDz(VtMAmi[s(1416)](127,_0x563c83),_0x52d5e7)),_0x1cdcaa+=7;else{let{SeqID:p,LogID:L,service:O,LogIDNew:F,method:K}=a[s(170)];this[s(485)]({SeqID:p,LogID:L,LogIDNew:F,service:O,method:K,headers:[{key:e[s(832)],value:"1"},{key:e[s(435)],value:e[s(1401)](F,"")},{key:e.wpnUG,value:"0"}]})}E&&!v[s(1353)]&&this["_dispatchAckMess"+s(693)](a),e[s(869)](n)}async function jp(a,n){let s=t;this[s(509)](e[s(1036)],a[s(170)]),e[s(869)](n)}async function Wp(a,n){let s=t;if(e[s(935)]!==e[s(1168)]){let d=e.dDfok(en,await e[s(1529)](fl,a[s(1640)]));try{if(e.sTTLC(d[s(623)],Uint8Array)){let h=e[s(719)](this[s(1287)][s(232)+"ncoding"],Object)?{force:!!this[s(1287)][s(232)+s(979)][s(1562)],encoding:this[s(1287)]["payloadE"+s(979)].encoding?this[s(1287)][s(232)+s(979)][s(1578)][s(939)](/\s/g,"")[s(856)+s(638)]():""}:{force:!1,encoding:this[s(1287)][s(232)+"ncoding"]?this[s(1287)][s(232)+"ncoding"][s(939)](/\s/g,"")[s(856)+"ase"]():""},w=d[s(232)+s(979)]?d[s(232)+s(979)][s(939)](/\s/g,"")[s(856)+s(638)]():"",E=e[s(1359)](this[s(1287)][s(1651)+"ype"],Object)?{force:!!this[s(1287)][s(1651)+s(807)].force,type:this[s(1287)][s(1651)+s(807)][s(635)]?this[s(1287)][s(1651)+s(807)].type.replace(/\s/g,"")[s(856)+s(638)]():""}:{force:!1,type:this[s(1287)]["payloadT"+s(807)]?this[s(1287)][s(1651)+s(807)].replace(/\s/g,"")[s(856)+s(638)]():""},v=d.payloadType?d[s(1651)+s(807)][s(939)](/\s/g,"")["toLowerC"+s(638)]():"",p=E.force?E[s(635)]:v||E[s(635)],L=h.force?h[s(1578)]:w||h[s(1578)],O=[s(582)+s(319)+s(1108),e[s(1487)],e[s(425)],s(952)],F=[e[s(290)],e[s(346)]];this[s(1287)][s(1428)+"ansformT"+s(404)+"ad"]&&O.includes(p)&&(!L||F[s(417)](L))?d[s(1208)+s(1230)]=e[s(1646)](ul,d.payload,0,d[s(623)][s(1374)+"th"]):d[s(1208)+s(1230)]=""}else d["textPayl"+s(1230)]=""}catch(h){e.gFanI(e[s(344)],"znaWw")?(d[s(1208)+s(1230)]="",console[s(1128)](h)):(_0x283ca8=_0xdd46f8(_0x4b1dd),_0x3e5461=0)}a[s(170)]=d,e[s(1461)](n)}else this[s(1507)+s(807)]=_0x16e430,this._ws&&(this[s(197)][s(1080)+"pe"]=_0x3c2f65)}function Kp(a,n,s){let d=t,h={SJbzd:function(L,O){return e[j(172)](L,O)},PYtsL:e.XbkEG,dpyWC:function(L,O){return e[j(656)](L,O)},uhnRO:function(L,O){return e[j(1136)](L,O)},SzKbO:function(L,O){return e[j(1663)](L,O)},TsrKW:function(L,O){return e.BbwUV(L,O)},euvhh:function(L,O){return e[j(1284)](L,O)},GnqxW:function(L,O){return e[j(969)](L,O)},lnizC:function(L,O){return e[j(193)](L,O)}},w=e[d(419)](s,8192),E=e.cNaoF(w,1),v=null,p=w;return function(L){let O=d;if(h[O(1019)](h.PYtsL,h[O(806)]))this.on(_0x4b8bb3,_0x4406d4);else{if(h[O(927)](L,1)||h[O(220)](L,E))return a(L);h[O(220)](h[O(514)](p,L),w)&&(v=h[O(1145)](a,w),p=0);let F=n[O(708)](v,p,p+=L);return h.euvhh(7,p)&&(p=h[O(657)](h[O(442)](7,p),1)),F}}}let $p=4294967295;function Vp(a,n,s){let d=t;if(e.nPnDb(e.kqJOb,e[d(1338)]))return RangeError(e.HOIfJ(e[d(976)](e.BblhV+a+e[d(351)]+(n||1),e[d(262)]),s));{let h=_0x53c17c.bytes,w=_0x3568ab[d(900)],E=_0x2994c2[d(820)],v=e.pBRfD(w,_0x417d9b);if(e[d(801)](v,h.length)){let p=new _0x2da999(e.qrnLz(2,v));p[d(1264)](h),_0x43b293[d(1659)]=p}return _0xb52985[d(900)]=v,e[d(1518)](v,E)&&(_0x16bcb9[d(820)]=v),w}}function Zp(a,n,s){let d=t;if(e.gzNHJ(e.EMIVL,e[d(1275)])){if(e.ZMuxc(s,$p))throw new Error(e[d(1039)]);let h=3;for(;h>=0;){let w=e[d(1086)](255,s);e[d(1646)](ma,w,a,e[d(1296)](n,h)),s>>>=8,h--}return e[d(1424)](n,4)}else _0x15fae4=d(780),_0x8786e2=_0x178908[d(939)](/(^http)((?:[s]*:\/\/))/,""),_0x4cdaee=/(^ws)((?:[s]*:\/\/))/[d(1572)](_0x4b4b22)?_0x153ee7:""+_0x4c2d08+_0x2ed4e5}function Yp(a,n){let s=t,d={zHQca:s(291)},h=0,w=n,E=e.DaGBl(n,4);for(;w<E;)if(e[s(1564)](e[s(186)],e[s(186)])){let{value:v,offset:p}=e[s(890)](ga,a,w);w=p,h=e[s(190)](h,8)>>>0,h+=v}else return _0x319216||(_0x199fed=_0x5b8fa9[s(508)]()[s(631)](_0xf8b832[s(936)](_0x3d665e,VkSFCq[s(1262)]))),_0x3ebcf1;return{value:h,offset:E}}function Jp(a,n,s){let d=t,h=e[d(253)].split("|"),w=0;for(;;){switch(h[w++]){case"0":if(e[d(1188)](a.length,40))return e[d(1074)](e[d(1470)](ha,a,n,s),s);continue;case"1":if(!a)return s;continue;case"2":if(n[d(756)+"e"])return n[d(756)+"e"](a,s)+s;continue;case"3":if(n[d(1259)])return e[d(969)](n.write(a,s),s);continue;case"4":return e[d(851)](e.HObWF(ha,a,n,s),s)}break}}function Xp(a,n){let s=t,d=new fe(e[s(752)](e[s(1603)](e[s(521)](a[n+4],24)|e.Qmjkw(a[e.VGRia(n,5)],16),a[e[s(1674)](n,6)]<<8),a[n+7]),e[s(1098)](e.FQEQO(a[e[s(372)](n,0)],24)|e[s(1513)](a[n+1],16)|e[s(1399)](a[n+2],8),a[e[s(1398)](n,3)]),!0);return n+=8,{value:d,offset:n+8}}function Qp(a,n,s){let d=t,h=a[d(1225)],w=a[d(678)];return n[s]=e[d(827)](w,24),n[s+1]=e[d(592)](e[d(960)](w,16),255),n[e[d(372)](s,2)]=e[d(580)](e[d(386)](w,8),255),n[s+3]=e[d(1519)](255,w),n[e.eQzWB(s,4)]=e[d(544)](h,24),n[s+5]=e[d(1012)](h>>>16,255),n[e.yAqWn(s,6)]=e[d(684)](e[d(688)](h,8),255),n[s+7]=e.UjuAH(255,h),s+=8,s}function ga(a,n){let s=t;return a.readUInt8?{value:a[s(1683)+"8"](n),offset:n+1}:{value:255&a[n],offset:e[s(996)](n,1)}}function ma(a,n,s){let d=t;return n.writeUint8?n.writeUint8(a,s):n[s]=e[d(429)](255,a),e[d(306)](s,1)}let eg=function(a){let n=t;return e[n(1570)](e[n(987)],e[n(357)])?new Uint8Array(a):this[n(197)]?this[n(197)][n(1080)+"pe"]:this[n(1507)+n(807)]},tg=e[t(779)](e[t(1157)],typeof Buffer)?Buffer["allocUns"+t(257)]:e[t(1314)](Kp,eg,Uint8Array[t(1197)+"e"].subarray),ng=16,wa=32;function rg(a){let n=t,s=0,d={};for(let h=0;h<a[n(1058)];h++)d[a[h][n(788)+n(1364)]]=e.wsDpj(ll,a[h][n(788)+"ame"]),s+=14+d[a[h][n(788)+n(1364)]];return[s,d]}function pl(a,n,s){let d=t,h={wdlMo:e[d(364)],WQfdI:function(L,O,F,K){return e[d(505)](L,O,F,K)},eXVHr:d(848)+d(349),hgceO:d(826),WKVwx:function(L,O,F,K){return e[d(1302)](L,O,F,K)},xHuzb:e[d(910)],JVQap:function(L,O,F,K){return L(O,F,K)},GQCiU:d(1661)},[w,E]=e[d(884)](rg,a),v=e.PieWM(tg,w),p=0;return a[d(1110)](L=>{let O=d,F=h[O(755)].split("|"),K=0;for(;;){switch(F[K++]){case"0":p=h[O(201)](Jp,L.cursor_name,v,p);continue;case"1":console[O(1128)](h.eXVHr,L,L[O(826)]);continue;case"2":console.log(h[O(1153)],p);continue;case"3":p=h[O(1437)](ma,0,v,p);continue;case"4":console[O(1128)](h.xHuzb,p);continue;case"5":p=h[O(301)](ma,E[L[O(788)+O(1364)]],v,p);continue;case"6":console[O(1128)](h[O(792)],p);continue;case"7":p=Qp(fe[O(367)+"er"](L[O(718)]||n),v,p);continue;case"8":console[O(1128)](O(300)+O(359),p);continue;case"9":console[O(1128)](O(1192),p);continue;case"10":p=h[O(1437)](Zp,v,p,L[O(826)]||0);continue}break}}),{frameType:wa,headers:[{key:e[d(773)],value:s}],payload:v}}function ig(a){let n=t,s=0,d=[];for(;e[n(389)](s,a[n(1374)+"th"]);){let{offset:h}=e[n(946)](ga,a,s);s=h;let w={cursor_name:"",cursor:0,service:0},{value:E,offset:v}=e[n(954)](Yp,a,s);w.service=E,s=v;let{value:p,offset:L}=ga(a,s);s=L,w[n(788)+n(1364)]=e[n(1646)](ul,a,s,e[n(1156)](s,p)),s+=p;let{value:O,offset:F}=e[n(1606)](Xp,a,s);w.cursor=O.toNumber(),s=F,d[n(382)](w)}return d}function sg(){let a=t,n={aODhK:function(s,d,h){return e[j(1491)](s,d,h)}};if(e.NIzpX(e.SMZsP,e[a(427)])){let s=this[a(566)+"tManager"]?.[a(1151)+a(1635)+"nt"](),d=this[a(1287)]["reconnec"+a(784)+a(1256)](_0x47dbce[a(1089)],_0x21ff3f.reason);this["_dispatc"+a(1555)+a(1131)](n[a(1094)](_0x344511,a(347),{code:1006,reason:_0x19501f[a(749)]||"connecti"+a(1477)+a(597)+a(1351)+a(1311)+a(309)+s,willReconnect:d})),d&&this[a(1102)]();return}else return{frameType:wa,headers:[{key:e[a(773)],value:e[a(821)]}],payload:void 0}}class og{constructor(n,s,d){let h=t;this[h(1120)+h(1049)]=n,this[h(997)+h(1405)]=s,this[h(737)+"Strategy"]=d,this[h(1118)]=e[h(230)](hl,this[h(1120)+"ameSpace"],e[h(1193)])}async[t(1052)](){let n=t;await this[n(1118)][n(1052)]()}async getCursors(){let n=t;if(!this[n(1118)][n(637)])return;let s=this[n(737)+n(1007)],d=await this[n(1118)][n(1563)]();switch(console[n(1128)](e[n(902)],d),s){case e[n(862)]:return d&&d.length?e[n(1454)](pl,d,0,this[n(997)+n(1405)]):void 0;case e[n(1560)]:return;case e[n(1681)]:return d&&d[n(1058)]?e[n(857)](pl,d,0,this[n(997)+n(1405)]):e[n(1306)](sg)}}async[t(1264)](n,s,d){let h=t;return console[h(1128)](e[h(600)],n,s,d),this[h(1118)].set({cursor_name:n,cursor:s,service:d})}async[t(798)+"rs"](n){let s=t;if(e[s(1696)](e[s(1345)],e[s(1694)])){let d=ig(n);for(let h of d)console[s(1128)](e[s(601)],d),await this[s(1118)].set(h)}else this[s(817)+"T"]?_0x370df1[s(861)+s(930)+s(1537)](({isConnected:d})=>{let h=s;this[h(549)+h(994)+h(1224)]=d,d?this["_handleO"+h(964)]():this[h(1645)+h(1471)]()}):this[s(1341)+"X"]&&_0x134ad5[s(861)+s(930)+s(1537)](({isConnected:d})=>{let h=s;this[h(549)+"igatorOn"+h(1224)]=d,d?this[h(1645)+h(964)]():this[h(1645)+h(1471)]()})}async[t(1050)](n){let s=t;return(await this[s(1118)][s(1050)](n))?.[s(718)]}async closeDB(){let n=t;await this[n(1118)][n(500)]()}["updateCu"+t(1478)+t(1456)](n){let s=t;this["_cursorF"+s(1405)]=n}get isReady(){let n=t;return this[n(1118)][n(637)]}}let ag=e[t(1392)];async function gl(a){let n=t,s={RbJVI:function(v,p,L,O,F){return e[j(1293)](v,p,L,O,F)},lHcrP:function(v,p){return v(p)}};if(!this[n(1287)].enableQoS)return null;let{aID:d,fpID:h,messageStrategy:w}=this[n(1287)],E=e[n(584)](a,ag);try{return this._cursorManager?e[n(1512)]("JHySn",e[n(1329)])?_0xf2e80f[n(596)+n(783)](n(1186)+"eeded",v=>{let p=n;LVpvik[p(449)](_0x15e4f8,_0x35aca8(_0x156f26[p(761)]),v.oldVersion,v.newVersion,LVpvik.lHcrP(_0x5e50ee,_0x3928b3[p(1149)+p(1566)]))}):a&&this[n(1361)+n(1229)]["updateCu"+n(1478)+n(1456)](a):this["_cursorM"+n(1229)]=new og(h+"_"+d+"_"+E,E,w),this[n(1361)+n(1229)][n(637)]||await this[n(1361)+n(1229)].openDB(),this[n(1361)+"anager"]}catch{return null}}async function cg(a,n){let s=t,d={SvDOJ:function(U,Z){return e.bVQck(U,Z)},ZIfWk:function(U,Z){return e[j(794)](U,Z)},HrAoY:function(U,Z){return e.gVwqE(U,Z)},aERfu:function(U,Z){return e.YQdEp(U,Z)},mEzZk:function(U,Z){return U|Z},uEPDj:function(U,Z){return e.nsiyY(U,Z)},spMQA:function(U,Z){return e.ZHJRc(U,Z)},JrKzl:function(U,Z){return U&Z},tNSxt:function(U,Z){return U<Z},TbahE:function(U,Z){return e[j(440)](U,Z)},lztPa:function(U,Z){return e[j(809)](U,Z)},IckKs:function(U,Z){return e[j(307)](U,Z)}},h=e.xzvPr(rn,a[s(170)].headers,e[s(1443)],"-1"),w=e.alLIv(rn,a[s(170)].headers,e.TEbbd,"1"),E=e[s(256)](rr,a[s(170)][s(1177)],e.CYKet),v=e[s(957)](Number,e[s(1457)](rr,a[s(170)][s(1177)],e.YPVTn))||0,p=pa[s(708)](this,a),L=rn(a[s(170)][s(1177)],e[s(1211)],"2"),O=e[s(211)](rr,a[s(170)].headers,e[s(1059)]),F=e[s(1332)](Number,e[s(244)](rr,a[s(170)][s(1177)],e[s(1459)]));if(p[s(1353)])return e.dhzUI(n);let K=p[s(1413)+s(1355)]?await xl.call(this):null;if(e[s(381)](a[s(170)].service,0)&&w&&!h||a[s(170)][s(826)]>0){if(E&&p[s(1413)+s(1355)]&&K)return!!!await K[s(1050)](E)&&(this[s(723)+"hMessage"+s(280)](a),await K[s(1264)](E,Date[s(1240)]()+v)),e.qGYlC(n);if(L)if(e.HZxFB!==e[s(316)])_0x29f712=_0x5a7f89[_0x6ad2a6+_0x436daf+1],_0x4f9a81=_0x4a9fe3[wUPpeV[s(1035)](wUPpeV[s(532)](_0x4cd23c,_0x189f01),2)],wUPpeV.HrAoY(wUPpeV[s(1033)](wUPpeV[s(1697)](_0x18e5c7,wUPpeV[s(1423)](_0x2eae2e,8)),49344),32896)?_0x6887f4+=_0x2e63ac:(_0x58abb2=wUPpeV[s(1697)](wUPpeV[s(1697)](wUPpeV[s(1673)](wUPpeV[s(1033)](15,_0xe7d721),12),wUPpeV[s(1423)](wUPpeV.JrKzl(63,_0x3f74b2),6)),wUPpeV.JrKzl(63,_0x463dad)),wUPpeV.tNSxt(_0x2a99a1,2048)||wUPpeV[s(1541)](_0x35b3ba,55296)&&wUPpeV[s(1113)](_0x3ca2bf,57343)?_0x3b0ba6+=_0x4e2772:(_0x114750+=wUPpeV[s(982)](_0x89cb2e,_0x20e7ea),_0x308fca+=2));else{let U=await gl.call(this);if(!U)return this[s(723)+s(1542)+s(280)](a),e.tLWuj(n);let Z=await U.get(O)??-1;if(Z<F)this[s(723)+"hMessage"+s(280)](a),U[s(1264)](O,F,a.message[s(826)]);else throw new Error(s(503)+s(803)+s(1164)+F+(" larger "+s(705)+s(841)+"r ")+Z);return e.KLkYZ(n)}return this[s(723)+s(1542)+"Event"](a),e.fCPBS(n)}}async function dg(a,n){let s=t,d=pa.call(this,a);if(!d[s(1413)+s(1355)])return e.MScwR(n);let h=await xl.call(this);if(d[s(1279)+s(1043)+s(452)]&&d[s(1111)+"s"][s(1058)])for(let w of d[s(1111)+"s"])await h.del(w);n()}async function lg(a,n){let s=t,d=a.message[s(981)+"e"]===ng,h=e.IjqVy(a[s(170)].frameType,wa);if(!d&&!h)return e[s(247)](n);let w=e[s(1343)](rr,a.message.headers,"cursor_f"+s(305));if(!w)return e[s(690)](n);let E=await gl.call(this,w);if(!E)return e[s(531)](n);if(d){let v=await E[s(1020)+"rs"](),p={frameType:v?.[s(981)+"e"],SeqID:fe[s(367)+"er"](this._seqId++),LogID:fe[s(367)+"er"](this[s(1287)][s(252)+s(176)]()),service:9e3,method:5,headers:v?.[s(1177)],payload:v?.payload},L=e[s(1483)](S,p);this[s(197)]&&this._ws[s(174)+"te"]&&this[s(197)][s(986)](L)}if(h){let v=a[s(170)].payload;v&&E[s(798)+"rs"](v)}}let ug=async function(a,n){let s=t;if(e[s(796)](e[s(745)],s(486)))this[s(497)]=!1,e[s(1576)](clearTimeout,this[s(1102)+s(1631)+s(330)]),e[s(1306)](n);else return s(198)+"_"+this[s(1190)]},fg=async function(a,n){let s=t,d={ySsRu:function(E,v){return E===v},hAwcE:e.lNrQu,MqtTm:function(E,v){return e[j(587)](E,v)},zfioV:function(E,v){return e[j(1116)](E,v)},NCqaQ:function(E){return E()}};if(!this._ws||e[s(903)](this._ws[s(174)+"te"],this[s(1031)]))return e[s(1689)](n);let{pingInterval:h}=this[s(1287)];this[s(566)+s(706)]?.[s(511)+s(1682)+s(897)]();for(let E=0;e[s(217)](E,this["_message"+s(896)][s(1058)]);E++){let v=this[s(737)+s(896)][E];if(e[s(977)](this[s(197)].readyState,this[s(1031)])&&v!==null)if(e[s(213)](s(1028),e[s(1475)]))this._ws&&this[s(197)][s(986)](v),this[s(737)+s(896)][E]=null;else return dAPKTZ[s(909)](typeof _0xd2360d,dAPKTZ[s(474)])?dAPKTZ[s(1163)](_0x220054,_0x5f1cc0):(dAPKTZ[s(1455)](_0x41fddb,_0x297ccb)&&dAPKTZ[s(1163)](_0x6d6243,_0x4294d3),_0x153bbb(_0x1f4c88,dAPKTZ.NCqaQ(_0x195394))?new _0x1d8f12(_0x3a51fb,_0x36b850):_0x5a4518);else break}this[s(737)+"Queue"]=this["_message"+s(896)][s(962)](E=>!!E),this["_pingPon"+s(1506)+"Id"]=e[s(1624)](setTimeout,()=>this[s(1029)](),h),this["_dispatc"+s(194)+"nt"](a),this._isBrowser&&this._ws&&(this._ws[s(1080)+"pe"]=this[s(1507)+s(807)]);let w=this[s(566)+s(706)]?.[s(1151)+s(1635)+"nt"]();this[s(509)](s(1665)+w+s(762)),e.SjQYL(n)},hg=async function(a,n){let s=t,d=this[s(566)+s(706)]?.[s(1151)+"ntEndpoint"]();this[s(509)](s(1665)+d),n()};class xg extends fa{constructor(n){let s=t,d={xmssl:function(v,p,L){return v(p,L)},ZfhFe:e.nZlei,jPMfR:function(v,p){return e[j(709)](v,p)},JiptV:function(v,p,L){return v(p,L)},aePMH:e[s(662)],jpTuf:function(v,p){return e[s(1114)](v,p)},iEFQq:e[s(1397)],SDDCl:function(v,p){return e[s(1214)](v,p)},smNTy:function(v,p,L){return e[s(1027)](v,p,L)},awRai:function(v,p,L){return e[s(1580)](v,p,L)}};super(),this[s(549)+"igatorOn"+s(1224)]=!0,this[s(1040)+"er"]=nr,this[s(1384)]=Rp,this._isMiniTT=Rn,this[s(1341)+"X"]=Jr,this[s(1165)+"r"]=Xr,this[s(737)+s(896)]=[],this[s(566)+s(706)]=null,this[s(496)+"osed"]=!1,this[s(1507)+"ype"]=e.aZRKR,this[s(1102)+"Lock"]=!1,this[s(1102)+s(1631)+s(330)]=null,this[s(533)+s(873)+"tId"]=null,this[s(1174)+s(1506)+"Id"]=null,this[s(1132)]=0,this[s(497)]=!1,this[s(871)]="",this[s(1425)+"ger"]=null,this[s(1361)+s(1229)]=null,this[s(1525)+s(777)]=null,this[s(1621)+"ls"]=e[s(1217)],this.CLOSED=3,this.CONNECTING=0,this[s(1031)]=1,this[s(182)]=2,this._onOpen=v=>{let p=s,L={WXIfK:e[p(445)],KudWN:function(O,F,K){return e[p(554)](O,F,K)}};try{dl(this,v,[ug,fg,hg])}catch(O){if(p(669)!==e[p(310)]){let F=e[p(491)](at,p(1248),{message:O[p(170)],code:nn[p(1304)+"OR"],error:O});this[p(723)+p(1339)+p(1131)](F)}else this[p(229)](YYsKjX[p(1107)],YYsKjX[p(339)](_0x3107bf,"error",{message:this[p(1115)+p(335)+p(452)](_0x2e4fc7)}))}},this[s(1056)+"ge"]=async v=>{let p=s,{pingInterval:L,pingFrequency:O}=this[p(1287)];if((e[p(709)]("hi",v.data)&&e[p(295)]===O||e[p(1382)]===O)&&(this[p(510)+p(1420)](),this[p(229)](e[p(1069)],e[p(654)]),this[p(1174)+p(1506)+"Id"]=e[p(1242)](setTimeout,this[p(1029)][p(936)](this),L)),!e[p(1489)]("hi",v[p(1640)]))try{e[p(1601)](dl,this,v,[Wp,qp,dg,lg,cg,jp])}catch(F){let K=e[p(1606)](at,p(1248),{message:F[p(170)],code:nn[p(1444)+p(1181)],error:F});this["_dispatc"+p(1339)+p(1131)](K)}},this[s(813)]=v=>{let p=s,L=this[p(566)+"tManager"]?.[p(859)+p(414)+"es"](),O=this[p(566)+p(706)]?.getCurrentEndpoint();if(L&&!v[p(170)]){let F=p(185)+O+(p(816)+p(1126)+p(1034)+"ed");this[p(723)+"hErrorEv"+p(1131)](d[p(1346)](at,d.ZfhFe,{message:F,code:nn[p(1159)+p(348)+"R"],error:v}));return}this[p(197)]&&d.jPMfR(this[p(197)][p(174)+"te"],this[p(1031)])&&this[p(1024)+"ect"](),this[p(723)+"hErrorEv"+p(1131)](d[p(931)](at,d[p(1612)],{message:v[p(170)],code:nn[p(259)+p(747)],error:v}))},this._onClose=async v=>{let p=s;this[p(1503)+p(891)](),this[p(510)+"ngTimer"](),this[p(1171)+p(1299)+"rs"](),this[p(197)]=null,this[p(1102)+p(1486)]=!1;let L=this[p(566)+p(706)]?.[p(859)+"chMaxTries"]();if(!L&&this[p(231)+p(1493)]()&&!this[p(496)+p(1087)]){let O=this[p(566)+p(706)]?.[p(1151)+"ntEndpoint"](),F=this[p(1287)][p(433)+"tInterce"+p(1256)](v.code,v[p(749)]);this[p(723)+p(1555)+"ent"](xt(d[p(1552)],{code:1006,reason:v[p(749)]||p(746)+p(1477)+p(597)+p(1351)+p(1311)+p(309)+O,willReconnect:F})),F&&this[p(1102)]();return}if(d[p(540)](1e3,v.code)&&this[p(496)+p(1087)]){this[p(723)+"hCloseEvent"](d[p(1346)](xt,d[p(1552)],{code:1e3,reason:d.iEFQq})),this["_endpoin"+p(706)]?.[p(511)+p(1682)+p(897)](),this[p(1525)+p(777)]?.[p(646)+"nter"]();return}if(d[p(540)](1e3,v[p(1089)])&&L){let O=this[p(566)+p(706)]?.[p(1151)+p(1635)+"nt"](),F=v[p(749)];F||(F=await d.SDDCl(Bp,this._url)),F="connecti"+p(1477)+p(456)+F+(p(613)+p(978))+O+(", max re"+p(1608)+p(1394)),this["_dispatc"+p(1555)+p(1131)](xt(d[p(1552)],{code:v.code,reason:F}));let K=p(185)+O+(p(816)+p(1126)+"es reached");this[p(723)+p(1339)+p(1131)](d[p(947)](at,d.ZfhFe,{message:K,code:nn[p(1159)+p(348)+"R"]})),this[p(566)+p(706)]?.["resetEnd"+p(1682)+"fig"](),this[p(1525)+p(777)]?.[p(646)+p(504)]();return}if(d[p(540)](1e3,v.code)&&!v[p(749)]){let O=this[p(566)+p(706)]?.getCurrentEndpoint();this["_dispatchCloseEv"+p(1131)](d[p(529)](xt,d[p(1552)],{code:v[p(1089)],reason:"connecti"+p(1477)+p(597)+"wn reaso"+p(1311)+p(309)+O})),this[p(566)+p(706)]?.[p(511)+p(1682)+"fig"](),this["_pingLos"+p(777)]?.[p(646)+p(504)]();return}this[p(723)+"hCloseEvent"](v),this["_endpoin"+p(706)]?.[p(511)+p(1682)+"fig"](),this[p(1525)+"sCounter"]?.[p(646)+"nter"]()},this[s(775)]=null,this[s(1526)]=null,this[s(274)+"e"]=null,this[s(228)]=null,this[s(563)+s(1154)]=null,this[s(1199)+s(1317)]=null,this[s(1379)+s(844)+s(916)+"ct"]=null,this[s(1645)+s(964)]=this["_handleO"+s(964)][s(936)](this),this[s(1645)+s(1471)]=this[s(1645)+s(1471)][s(936)](this),this[s(1426)+s(212)]=this["_handleP"+s(212)][s(936)](this),this[s(1426)+s(1e3)]=this[s(1426)+s(1e3)][s(936)](this),this[s(1287)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(281)](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.rJHLf,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1681)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:w}=n,E=Array[s(1032)](h)?h:e[s(845)](e[s(1213)],typeof h)?[h]:[];if(!E||e[s(1348)](0,E.length))throw new Error(e.IoglQ);if(!Op(w))throw new Error(e[s(1166)]);Object[s(410)](this._options,n),this._endpointManager=new cl(E,this[s(1287)][s(1442)+"es"]),this[s(1525)+s(777)]=new Mp(this[s(1287)]["pingLoss"+s(879)]),this[s(1287)][s(443)+s(1303)]&&(this._isInit=!0,this[s(1102)]()),this[s(1287)][s(361)+"tworkCha"+s(1298)]&&(this[s(817)+"T"]||this._isMiniWX?this[s(512)+"etWorkCh"+s(1310)]():this[s(1040)+"er"]&&this["_initGlo"+s(1018)+"Listener"]())}[t(1645)+"nLine"](){let n=t;this[n(1287)][n(1201)+"utoReconnect"]||this._readyClosed||this["_handleR"+n(1154)]()}[t(1645)+t(1471)](){let n=t;this[n(583)+n(251)+"t"]();let s=ua(n(433)+"t",{message:e[n(825)]});this[n(1379)+"mediatel"+n(916)+"ct"]&&this[n(1379)+n(844)+n(916)+"ct"](s)}[t(751)+t(1018)+t(783)](){let n=t;this[n(1040)+"er"]&&window.addEventListener(e.bFrVT,this[n(1645)+"nLine"]),this[n(1040)+"er"]&&window["addEvent"+n(783)](e[n(538)],this[n(1645)+"ffLine"]),this._isBrowser&&window[n(596)+n(783)](e.ZtRuM,this[n(1426)+n(212)]),this._isBrowser&&window[n(596)+n(783)](e[n(1155)],this["_handleP"+n(1e3)])}["_dropGlo"+t(1018)+t(783)](){let n=t;this._isBrowser&&window["removeEv"+n(958)+n(1427)](e.bFrVT,this[n(1645)+n(964)]),this[n(1040)+"er"]&&window["removeEv"+n(958)+"ner"](e[n(538)],this["_handleO"+n(1471)]),this[n(1040)+"er"]&&window["removeEventListe"+n(1427)](e.ZtRuM,this[n(1426)+"ageHide"]),this._isBrowser&&window[n(993)+n(958)+n(1427)](n(811),this[n(1426)+n(1e3)])}[t(1426)+t(212)](n){let s=t;if(e[s(1226)](e[s(974)],e.Hpfcp))this[s(1553)]=!0,this[s(1225)]=e[s(1079)](0,_0x2e4d95),this[s(678)]=e[s(1536)](0,_0x2fa9fb),this[s(579)]=!!_0x4061d4;else{if(!n.persisted)if(e[s(951)]!==s(341)){let d=this[s(1118)][s(774)](this[s(876)]),h=_0x1ca1ef[s(836)](e[s(1070)](d,"{}"));return h[_0xc96dd5]=void 0,this._qosDB.setItem(this[s(876)],_0x506532[s(1184)+"y"](h))}else this._isBrowser&&window["removeEventListe"+s(1427)](e[s(171)],this[s(1426)+s(212)]),this._isBrowser&&window[s(993)+s(958)+s(1427)](e[s(1155)],this[s(1426)+s(1e3)]),this[s(347)]();this._isBrowser&&window[s(993)+s(958)+"ner"](e[s(704)],this[s(1645)+s(964)]),this._isBrowser&&window["removeEv"+s(958)+s(1427)](e[s(538)],this["_handleO"+s(1471)])}}["_handleP"+t(1e3)](n){let s=t;n[s(260)+"d"]&&(this[s(231)+s(1493)]()&&(!this[s(197)]||this[s(197)][s(174)+"te"]!==this[s(1031)]||e[s(659)](this[s(197)][s(174)+"te"],this[s(630)+"NG"]))&&this[s(1645)+s(964)](),this[s(1040)+"er"]&&window["addEvent"+s(783)](s(1127),this[s(1645)+s(964)]),this[s(1040)+"er"]&&window[s(596)+s(783)](e[s(538)],this[s(1645)+s(1471)]))}async[t(938)+t(906)](n){let s=t,{fpID:d,deviceID:h,bddID:w,ttwID:E,accessKey:v,aID:p,customParams:L={},enableAutoAck:O,enableQoS:F,QoSLevel:K,env:U}=this[s(1287)],Z,De,zt;this[s(1040)+"er"]||this[s(1341)+"X"]||this[s(817)+"T"]?(Z=location&&e[s(972)](e[s(423)],location[s(828)])?e[s(1239)]:e.Cmpoi,De=n[s(939)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),zt=/^wss(.*:\/\/)/.test(n)?n:""+Z+De):(Z="wss://",De=n[s(939)](/(^http)((?:[s]*:\/\/))/,""),zt=/(^ws)((?:[s]*:\/\/))/[s(1572)](De)?De:""+Z+De);let St=w?e[s(632)]:E?e[s(275)]:s(923)+"d",as=w||E||h;if(e[s(1117)](!as,!St))throw new Error("please p"+s(603)+s(899)+"viceID or ttwID");let _a=e[s(1212)]==typeof L?await e[s(1306)](L):L,pg=U?e[s(334)](Np,U[s(1688)],U[s(1195)]):{},ya=Object[s(410)]({device_platform:e[s(1388)],version_code:e[s(1103)],access_key:v,fpid:d,aid:p,[St]:as,xsack:O?1:0,xaack:O?1:0,xsqos:F?1:0,qos_level:F?K:void 0,qos_sdk_version:2,...pg},_a),gg=Object.keys(ya)[s(642)]((Ea,ba)=>ya[ba]!==void 0?""+Ea+(Ea?"&":"?")+ba+"="+ya[ba]:Ea,"");return zt+s(1618)+gg}async[t(1102)](){let n=t,s={HeONT:function(d,h){return e.zWwYZ(d,h)},mEbAK:function(d){return e.RQvAf(d)}};if(!(this[n(1102)+"Lock"]||this[n(496)+n(1087)])){this[n(1102)+n(1486)]=!0;try{let d=this[n(566)+n(706)]?.[n(1169)+n(1078)+"ointReac"+n(1389)+n(317)](),{timeoutInterval:h}=this[n(1287)];if(d){let E=this[n(566)+"tManager"]?.[n(1151)+n(1635)+"nt"](),v=this[n(566)+"tManager"]?.[n(1289)+n(921)+"pointAndUpdateCo"+n(695)](),p=this[n(566)+n(706)]?.[n(1151)+n(1635)+n(781)+"ount"]();if(v){let L=n(185)+E+(" timeout"+n(1474)+"tries re"+n(1404)+n(846)+n(1235)+n(647))+v+(n(383)+"y"),O=e[n(1082)](at,e[n(445)],{message:L,code:nn[n(1159)+n(348)+"R"]});this[n(509)](L),this["_dispatc"+n(1339)+"ent"](O),this[n(871)]=await this._generateUrl(v),this[n(509)](n(185)+v+" "+p+n(992)),this[n(1171)+n(1299)+"rs"]()}else{let L="connect "+E+(n(377)+n(1474)+n(1608)+"ached");this[n(509)](L),this[n(723)+n(1339)+n(1131)](e[n(1082)](at,e[n(445)],{message:L,code:nn[n(1159)+"IES_ERROR"]}));return}}else if(e[n(1207)](e.YKPnf,e[n(271)])){let E=this[n(566)+"tManager"]?.[n(1151)+n(1635)+"ntAndUpdateCount"](),v=this[n(566)+n(706)]?.[n(1151)+n(1635)+n(781)+n(618)]();this[n(871)]=await this[n(938)+n(906)](E||""),this[n(509)](n(185)+E+" "+v+n(992)),this[n(1171)+n(1299)+"rs"]()}else _0x47cc92(qTSVqW[n(1658)](_0x318fd0,_0x4bf9b2[n(761)])),qTSVqW[n(545)](_0x56790c);if(this[n(497)])this._isInit=!1;else if(e.kOqjH===e[n(323)]){let E=e.uVyEP(ua,e.nssLV,{message:e[n(498)]});this[n(563)+n(1154)]&&this["onStartR"+n(1154)](E)}else{if(!this._ws)return;this[n(197)][n(596)+n(783)](e.baAUK,this[n(1250)]),this[n(197)][n(596)+n(783)](e[n(662)],this[n(765)]),this._ws[n(596)+"Listener"]("message",this[n(1056)+"ge"]),this[n(197)]["addEvent"+n(783)](e.nZlei,this[n(813)])}let w=this[n(566)+n(706)]?.[n(1151)+n(1635)+n(781)+n(618)]()||0;e[n(904)](w,1)&&await this[n(1418)](w-1),this[n(509)](n(746)+n(689)+this[n(871)]+(n(1622)+n(593))+this[n(1621)+"ls"]),this[n(197)]=Dp({url:this[n(871)],protocols:[this._protocols],headers:this._options[n(907)+n(1009)+"s"][n(562)+n(944)]},this._options.ws),(this._isBrowser||this[n(1165)+"r"])&&this._ws&&(this[n(197)][n(1080)+"pe"]=this[n(1507)+n(807)]),this[n(1669)+n(222)](),this["_connect"+n(1631)+n(330)]=e[n(205)](setTimeout,this[n(1347)+"ut"][n(936)](this),h)}catch(d){throw this["_connect"+n(1486)]=!1,d}}}["_clearTi"+t(891)](){let n=t;e.DlCpK(n(208),e[n(1065)])?this[n(197)]&&this._ws[n(347)](_0x13f0eb,_0x9d3c74):(clearTimeout(this[n(1102)+n(1631)+n(330)]),this[n(1102)+n(1631)+n(330)]=null)}[t(510)+t(1420)](){let n=t;e[n(1576)](clearTimeout,this[n(1174)+n(1506)+"Id"]),e.xeMeL(clearTimeout,this["_reconnectTimeou"+n(553)]),this[n(1174)+n(1506)+"Id"]=null,this[n(533)+"ctTimeou"+n(553)]=null}[t(509)](...n){let s=t;this._options[s(326)]&&console[s(1128)].apply(console,[s(296)+">",...n])}[t(586)+t(278)+"e"](n){let s=t;if(e[s(720)]===e[s(720)]){let{initReconnectInterval:d,maxReconnectInterval:h,reconnectIntervalGrowFactor:w}=this[s(1287)],E=d*Math[s(269)](w,n-1);return e.LfmYo(E,h)?h:E}else this[s(1190)]=_0x17733e,this[s(1064)]=_0x3c91aa,this._qosDB=_0x40b4d6}[t(1029)](){let n=t,s={WexDm:function(d,h){return e.xxAQT(d,h)},TBFCy:function(d,h){return e[j(328)](d,h)},TMswu:function(d,h){return e[j(429)](d,h)},cSDIv:function(d,h){return e[j(1668)](d,h)}};if(e[n(769)]===e[n(769)]){if(this[n(197)]&&this[n(197)][n(174)+"te"]===this[n(630)+"NG"]){this[n(510)+n(1420)](),this[n(1174)+n(1506)+"Id"]=e[n(559)](setTimeout,this[n(1029)][n(936)](this),this[n(1287)][n(1309)+n(1672)]);return}if(!this[n(197)]||e[n(243)](this[n(197)][n(174)+"te"],this[n(1031)]))return void this[n(1412)+"econnect"]();this[n(197)]&&this[n(197)][n(986)]("hi"),this[n(533)+n(873)+"tId"]=e.agqhB(setTimeout,this[n(1412)+n(1154)+n(1616)].bind(this),this[n(1287)][n(289)+n(609)+"val"])}else _0x5a20a4[_0x4cd049++]=XcTFer.WexDm(XcTFer[n(730)](_0xb1c9c7,12),224),_0x4e3f6f[_0xa3be0++]=XcTFer[n(1467)](XcTFer[n(1342)](XcTFer.cSDIv(_0xffad6d,6),63),128),_0x41f06e[_0x175935++]=XcTFer.WexDm(XcTFer[n(1342)](63,_0x114a37),128)}["_handleR"+t(1154)+t(1616)](){let n=t;if(e[n(1226)](n(1258),e[n(1191)]))this[n(1525)+"sCounter"]?.[n(1278)](),this.emit(e[n(1629)],e[n(633)]),this[n(1525)+"sCounter"]?.[n(859)+n(802)+"nt"]()?this[n(1412)+"econnect"]():this[n(1029)]();else return this._qosDB?.[n(1264)]({message_id:_0x22b58c,timestamp:_0x503658})}["_navigat"+t(1493)](){let n=t;return this._isMiniTT||this[n(1341)+"X"]?this[n(549)+n(994)+n(1224)]:(this._isBrowser||this._isWorker)&&this[n(1287)]["listenNe"+n(441)+"nged"]?navigator.onLine:!0}[t(1412)+"econnect"](){let n=t;!this[n(231)+"orOnline"]()||this["_readyCl"+n(1087)]||(this["_endpoin"+n(706)]?.[n(511)+n(1682)+n(897)](),this[n(1525)+n(777)]?.[n(646)+n(504)](),this._ws?this[n(1024)+n(1357)](1001,e[n(1312)],!0):this[n(1102)]())}[t(512)+t(1597)+"ange"](){let n=t;this[n(817)+"T"]?tt[n(861)+"kStatusChange"](({isConnected:s})=>{let d=n;this[d(549)+d(994)+d(1224)]=s,s?this["_handleO"+d(964)]():this[d(1645)+d(1471)]()}):this[n(1341)+"X"]&&wx[n(861)+n(930)+n(1537)](({isConnected:s})=>{let d=n;this["_miniNavigatorOn"+d(1224)]=s,s?this[d(1645)+"nLine"]():this[d(1645)+"ffLine"]()})}[t(1418)](n){return new Promise(s=>{let d=j;e.UfiPb(setTimeout,s,this["_getInte"+d(278)+"e"](n))})}_disconnect(n=1e3,s="",d=!1){let h=t;this._ws&&this[h(583)+h(251)+"t"](n,s,d)}[t(1347)+"ut"](){let n=t,s=this["_endpoin"+n(706)]?.[n(1151)+n(1635)+"nt"]();this[n(509)](n(185)+s+n(377)),this._disconnect(1001,n(1650)+n(980)+n(391)+"g",!0)}_sendAck(n){let s=t;if(e[s(1037)](e[s(1372)],e[s(1372)])){let d=_0x16a716[s(683)];e[s(1322)](void 0,d)&&(e[s(893)](_0x17e2e5,_0x370441,10),e[s(559)](_0x5e130b,_0x2197b9,d));let h=_0x393755[s(605)];e[s(1653)](void 0,h)&&(e[s(852)](_0x4a2a42,_0x53ed21,18),_0x4216cc(_0x495247,h))}else{let d=e[s(1162)](Ft,n);this._ws&&e[s(673)](this[s(197)][s(174)+"te"],this[s(1031)])&&(this[s(197)]&&this[s(197)][s(986)](d),this._debug(e[s(1589)],n))}}["_removeW"+t(1299)+"rs"](){let n=t,s=e[n(643)][n(725)]("|"),d=0;for(;;){switch(s[d++]){case"0":this[n(197)][n(993)+n(958)+n(1427)]("open",this[n(1250)]);continue;case"1":if(!this[n(197)])return;continue;case"2":this[n(197)]["removeEv"+n(958)+n(1427)](e.nZlei,this._onError);continue;case"3":this._ws[n(993)+"entListe"+n(1427)](e[n(662)],this[n(765)]);continue;case"4":this[n(197)]["removeEv"+n(958)+"ner"](n(170),this[n(1056)+"ge"]);continue}break}}[t(1669)+t(222)](){let n=t,s=(n(814)+"0").split("|"),d=0;for(;;){switch(s[d++]){case"0":this[n(197)][n(596)+"Listener"](e[n(445)],this._onError);continue;case"1":if(!this[n(197)])return;continue;case"2":this._ws[n(596)+n(783)](e[n(1545)],this._onOpen);continue;case"3":this._ws[n(596)+n(783)](e[n(1495)],this[n(1056)+"ge"]);continue;case"4":this[n(197)][n(596)+n(783)](e.tngaM,this[n(765)]);continue}break}}[t(1097)+t(1644)](n=1e3,s=""){let d=t;try{this[d(197)]&&this[d(197)].close(n,s)}catch{}}[t(583)+t(251)+"t"](n=1e3,s="",d=!1){let h=t;if(e.YDdve(e[h(1218)],e[h(214)])){if(this[h(510)+h(1420)](),this[h(1503)+"mer"](),this[h(1171)+h(1299)+"rs"](),this[h(1097)+h(1644)](1e3,s),this._connectLock=!1,d&&this[h(231)+"orOnline"]()&&!this["_readyCl"+h(1087)]){if(this[h(566)+"tManager"]?.[h(859)+"chMaxTries"]()){let E=this[h(566)+h(706)]?.[h(1151)+h(1635)+"nt"]();this["_dispatchCloseEv"+h(1131)](xt(h(347),{code:1006,reason:h(185)+E+(h(377)+h(1474)+"tries re"+h(1394)),wasClean:!0}))}else{let E=this._options.reconnectInterceptor(n,s);this["_dispatc"+h(1555)+h(1131)](e[h(1464)](xt,e[h(662)],{code:n,reason:s,wasClean:!0,willReconnect:E})),E&&this[h(1102)]()}return}this[h(231)+h(1493)]()||this["_readyCl"+h(1087)]?this[h(723)+h(1555)+h(1131)](e[h(1383)](xt,e[h(662)],{code:n,reason:e[h(1397)]})):this[h(723)+h(1555)+h(1131)](xt(e[h(662)],{code:1006,reason:"going aw"+h(1337)+h(1637)+h(1451)})),this._ws=null,this["_endpoin"+h(706)]?.[h(511)+h(1682)+h(897)](),this["_pingLos"+h(777)]?.resetCounter()}else{if(_0x35099a<1||e[h(904)](_0x485b0c,_0x48adb8))return e.dDfok(_0x2f2e2b,_0x21897a);_0x221850+_0x276255>_0x2bc0f2&&(_0x3f1099=e[h(1576)](_0x5e74d6,_0x7ac8b0),_0x5762d2=0);let w=_0x21b33c.call(_0x2a0a5f,_0x27cd4e,_0x209adc+=_0x4e0ce0);return 7&_0x19ddc3&&(_0x2c40a7=e[h(1523)](e[h(581)](7,_0x158f0b),1)),w}}[t(723)+"hOpenEvent"](n){let s=t;this.emit(e[s(1545)],n),this.onopen&&this[s(228)](n)}[t(723)+"hMessageEvent"](n){let s=t;if(s(191)!==e.acskC)this.emit(e[s(1495)],n),this[s(274)+"e"]&&this[s(274)+"e"](n);else{let{SeqID:d,LogID:h,service:w,LogIDNew:E,method:v}=_0x336635[s(170)];this[s(485)]({SeqID:d,LogID:h,LogIDNew:E,service:w,method:v,headers:[{key:e.TEbbd,value:"1"},{key:"ack_id",value:E||""},{key:e[s(168)],value:"0"}]})}}[t(723)+t(302)+"ageEvent"](n){let s=t;this[s(229)](e.QqeMg,n),this["onReceiv"+s(1317)]&&this["onReceiv"+s(1317)](n)}[t(723)+t(1339)+t(1131)](n){let s=t;this[s(229)](s(1248),n),this[s(1526)]&&this[s(1526)](n)}["_dispatchCloseEv"+t(1131)](n){let s=t;this[s(229)](e.tngaM,n),this[s(775)]&&this[s(775)](n)}get binaryType(){let n=t;return this[n(197)]?this[n(197)][n(1080)+"pe"]:this[n(1507)+n(807)]}set[t(1080)+"pe"](n){let s=t;this["_binaryT"+s(807)]=n,this._ws&&(this[s(197)][s(1080)+"pe"]=n)}get[t(321)+"nt"](){let n=t;return this[n(566)+n(706)]?.["getCurre"+n(1635)+n(781)+n(618)]()||0}get[t(1630)+t(726)](){let n=t;return this[n(737)+n(896)][n(642)]((d,h)=>(d+=h&&h[n(1374)+"th"]||0,d),0)+(this[n(197)]?this._ws[n(1630)+n(726)]:0)}get[t(1438)+"ns"](){let n=t;return this[n(197)]?this._ws[n(1438)+"ns"]:""}get protocol(){let n=t;if(e[n(998)](e[n(905)],e[n(409)]))return this[n(197)]?this[n(197)].protocol:"";e[n(852)](_0x59bedc,_0x9ae4aa,74),e[n(1633)](_0x1e2f5b,_0x2f2ade,_0x3573b5)}get[t(174)+"te"](){let n=t;if(e[n(200)](e[n(651)],n(640)))_0x5c1a5a[n(1128)](_0x44f023);else return this[n(197)]?this[n(197)][n(174)+"te"]:this[n(1287)][n(443)+n(1303)]?this.CONNECTING:this[n(634)]}get[t(480)](){let n=t;return this[n(197)]?this[n(197)][n(480)]:this[n(871)]}[t(347)](n=1e3,s){let d=t;if(e[d(1613)](e[d(984)],e[d(984)])){let h=e[d(722)][d(725)]("|"),w=0;for(;;){switch(h[w++]){case"0":this[d(583)+d(251)+"t"](n,s);continue;case"1":if(!this[d(197)])return void this[d(509)](e[d(1409)]);continue;case"2":this[d(1425)+d(667)]?.[d(500)]();continue;case"3":if(e[d(1266)](this._ws.readyState,this[d(634)])||e.lpiso(this._ws[d(174)+"te"],this[d(182)]))return void this[d(509)](e[d(571)]);continue;case"4":this[d(1503)+d(891)]();continue;case"5":this[d(510)+"ngTimer"]();continue;case"6":this[d(496)+d(1087)]=!0;continue;case"7":this[d(732)+d(1018)+d(783)]();continue}break}}else _0x3bfb70[d(1264)](_0x3e8eb5,_0x4141cf),_0x171b1f.set(_0x496d1f,_0x5e55b4)}async[t(986)](n,s){let d=t,h={egbcw:e[d(885)]};if(e[d(972)](null,n))throw new Error(e[d(1095)]);e[d(576)](e.svJNI,typeof n)&&(n=JSON[d(1184)+"y"](n)),e[d(779)](e[d(1213)],typeof n)&&!(n instanceof ArrayBuffer)&&!(n[d(1432)]&&n[d(1432)]instanceof ArrayBuffer)&&(n=JSON[d(1184)+"y"](n));let w=await e[d(307)](fl,n),E=Lp(n),{method:v=0,service:p=this._options[d(826)],logID:L=this[d(1287)][d(252)+d(176)](),headers:O=this[d(1287)][d(1177)],payloadEncoding:F=this[d(1287)][d(232)+d(979)],payloadType:K=this[d(1287)][d(1651)+d(807)],logIDNew:U=this._options[d(675)+"Config"][d(1687)+d(1148)+"teLogIDNew"]?e[d(1567)](i,this[d(1287)][d(675)+d(764)][d(490)]):""}=s||{};if(!p)throw new Error(d(350)+d(622)+" valid s"+d(349));let Z={SeqID:fe.fromNumber(this[d(1132)]++),LogID:fe[d(367)+"er"](L),service:p,method:v,headers:O,payloadEncoding:e[d(506)](F,Object)?F[d(1578)]?F[d(1578)]:"":F,payloadType:e[d(714)](K,Object)?K[d(635)]?K.type:E:K||E,payload:w,LogIDNew:U},De=e[d(1198)](Ft,Z);if(this[d(197)]&&e[d(1476)](this[d(197)][d(174)+"te"],this.OPEN))if(e[d(1358)](d(399),e[d(858)])){let as=h[d(519)].split("|"),_a=0;for(;;){switch(as[_a++]){case"0":var zt=_0x491d63[_0x3df837]={exports:{}};continue;case"1":if(St!==void 0)return St[d(965)];continue;case"2":_0x129dee[_0x17e23b](zt,zt[d(965)],_0x58792b);continue;case"3":var St=_0x2883cd[_0x28568c];continue;case"4":return zt[d(965)]}break}}else this[d(197)]&&this[d(197)][d(986)](De),this._debug(e[d(528)],Z);else e.nMWFB(this[d(737)+d(896)][d(1058)],this[d(1287)][d(315)+d(1568)+d(892)])?(this["_message"+d(896)].push(De),this[d(509)](e.hTFGn,Z)):e[d(1570)](d(624),e[d(320)])?(this[d(737)+"Queue"].shift(),this[d(737)+d(896)][d(382)](De)):_0xfdc67b.log(_0x1db475);return{seqID:this[d(1132)],logID:L,logIDNew:U}}async reconnect(n){let s=t,{url:d}=n||{},h=Array.isArray(d)?d:e[s(1213)]==typeof d?[d]:[];n&&Object[s(410)](this[s(1287)],n),h&&h[s(1058)]?this[s(566)+s(706)]=new cl(h,this[s(1287)][s(1442)+"es"]):this[s(566)+s(706)]?.[s(511)+s(1682)+s(897)](),this[s(1525)+s(777)]?.[s(646)+s(504)](this[s(1287)][s(255)+s(879)]),this[s(496)+s(1087)]=!1,this[s(197)]&&e[s(1434)](this._ws[s(174)+"te"],this.CLOSED)?this[s(1024)+s(1357)](1e3,e.sFWMM,!0):(this._isInit=!0,this._connect())}async[t(574)](){let n=t;!this[n(1102)+n(1486)]&&(this["_endpoin"+n(706)]?.[n(511)+n(1682)+n(897)](),this[n(1525)+"sCounter"]?.[n(646)+n(504)](),this[n(496)+n(1087)]=!1,this[n(497)]=!0,this[n(1102)]())}[t(596)+t(783)](n,s){this.on(n,s)}[t(1544)+t(280)](n){let s=t,d={ErdLR:function(h,w){return e[j(1516)](h,w)},KFXsp:function(h,w){return h>>>w},OEtob:function(h,w){return e.tjqvK(h,w)},riDGK:function(h,w){return e[j(754)](h,w)},OXQAm:function(h,w){return e[j(688)](h,w)}};if(e[s(971)](e.mzoyf,e[s(679)])){let{type:h}=n;this[s(229)](h,n)}else{let h=this[s(678)],w=this[s(1225)];return[255&w,uPCiof.ErdLR(uPCiof.KFXsp(w,8),255),uPCiof.OEtob(uPCiof[s(1522)](w,16),255),uPCiof.KFXsp(w,24),uPCiof[s(1330)](255,h),uPCiof[s(759)](h>>>8,255),uPCiof.ErdLR(uPCiof[s(1297)](h,16),255),h>>>24]}}[t(993)+t(958)+t(1427)](n,s){this[t(189)](n,s)}pingOnce(){return new Promise((n,s)=>{let d=j,h={FpPaD:d(1652),bbEQv:d(743)+d(1607)+"s",ZIqgy:e.LdEDW,eSpCR:function(v,p){return e[d(1670)](v,p)}};this[d(510)+d(1420)](),this[d(1174)+d(1506)+"Id"]=e[d(451)](setTimeout,this[d(1029)][d(936)](this),this[d(1287)][d(1309)+d(1672)]);let w=()=>{let v=d;n(h[v(1272)]),this[v(189)](h[v(219)],w),this[v(189)](h.ZIqgy,E)},E=()=>{let v=d;h[v(1167)](s,v(824)),this[v(189)](v(743)+v(1607)+"s",w),this[v(189)](h[v(687)],E)};this.on("ping_onc"+d(1607)+"s",w),this.on(e[d(1629)],E),this[d(1029)]()})}}})(),Me[N(520)+N(1558)]=Ce[N(520)+N(1558)],Me["CustomEr"+N(1101)]=Ce["CustomEr"+N(1101)],Me[N(1286)+"e"]=Ce[N(1286)+"e"],Me[N(280)]=Ce.Event,Me[N(818)]=Ce[N(818)],Me[N(1270)+N(1088)+"vent"]=Ce[N(1270)+"MessageE"+N(370)],Me[N(1088)+"vent"]=Ce.MessageEvent,Me.OpenEvent=Ce[N(279)+"t"],Me[N(276)+N(739)]=Ce[N(276)+N(739)],Me[N(411)+"oseEvent"]=Ce[N(411)+N(1558)],Me[N(729)+N(1101)]=Ce["createEr"+N(1101)],Me[N(507)+"ssageEvent"]=Ce["createMe"+N(625)+"nt"],Me[N(1326)+N(1172)]=Ce[N(1326)+N(1172)],Me[N(482)+N(1582)+N(370)]=Ce["createRe"+N(1582)+N(370)],Me[N(1196)+N(917)]=Ce[N(1196)+N(917)],Me[N(1231)+"ame"]=Ce[N(1231)+N(1364)];for(Go in Ce)[N(520)+"oseEvent",N(1574)+"rorEvent",N(1286)+"e",N(280),"FWS",N(1270)+N(1088)+N(370),"MessageE"+N(370),"OpenEvent","Reconnec"+N(739),N(411)+"oseEvent",N(729)+N(1101),N(507)+N(625)+"nt",N(1326)+N(1172),N(482)+N(1582)+N(370),N(1196)+N(917),"encodeFrame"][N(1435)](Go)===-1&&(Me[Go]=Ce[Go]);var Go;Object[N(1130)+N(1515)](Me,N(908)+"le",{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 CS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Ud(t=ee()){return vS(t.libEntry)?t.libEntry:kS(new URL("../index.ts",import.meta.url))}async function Wx(t={}){let e=t.paths??ee(),r=t.entryOverride??Ud(e),i=CS(e,process.env.COZE_BRIDGE_LOG_MODE);await IS(AS(i),{recursive:!0});let o=SS(i,"a"),l=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=nt(process.execPath,l,{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,Xo=Qe(()=>{"use strict";$t();ne();Oe();TS=H("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 C1(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Vr(r)}</key>
21
- <string>${Vr(i)}</string>`).join(`
20
+ `+n)}function tr(t,e,n,i,s,c){if(t.listenerCount("wsClientError")){let d=new Error(s);Error.captureStackTrace(d,tr),t.emit("wsClientError",d,n,e)}else ns(n,i,s,c)}});var Lx=de(oe=>{"use strict";var M=G;(function(t,e){let n=G,i=t();for(;;)try{if(-parseInt(n(1768))/1*(parseInt(n(410))/2)+parseInt(n(1405))/3*(parseInt(n(1126))/4)+-parseInt(n(1433))/5+-parseInt(n(1280))/6*(-parseInt(n(1124))/7)+-parseInt(n(692))/8*(parseInt(n(1422))/9)+parseInt(n(1784))/10+parseInt(n(801))/11===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Vo,102953);var qv=Object[M(1641)+"operty"],Hv=Object[M(1125)+M(1323)+M(864)],Cx=(t,e)=>function(){return t&&(e=(0,t[{qUvMl:function(c,d){return c(d)}}[M(1102)](Hv,t)[0]])(t=0)),e},jv=(t,e)=>{for(var n in e)qv(t,n,{get:e[n],enumerable:!0})};function Wv(){return Sx||(Sx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Kv(){let t=M;return Ix||(Ix=[IDBCursor[t(1042)+"e"][t(813)],IDBCursor[t(1042)+"e"].continue,IDBCursor.prototype.continuePrimaryKey])}function $v(t){let e=M,n={TZbfT:e(1653),eUAdM:e(730),oLELu:function(s,c){return s(c)},mQNar:"success",HuKwb:e(1055),PZaLZ:function(s,c){return s(c)},WhBpJ:function(s){return s()},MENdL:function(s,c){return s!==c},XARMl:e(1259),rQras:"ZALnQ",hWPxl:function(s,c){return s instanceof c}},i=new Promise((s,c)=>{let d=e,u={LHMom:n.mQNar,CyHnS:n.HuKwb,ylnLn:function(_,S){return n.PZaLZ(_,S)},dTjhV:function(_){return n.WhBpJ(_)}},h=()=>{let _=G;t[_(1363)+_(1016)+"ner"](u[_(784)],x),t["removeEventListe"+_(1552)](u[_(1005)],m)},x=()=>{s(u[G(591)](zt,t.result)),u.dTjhV(h)},m=()=>{let _=G;if(n[_(1553)]===n[_(1174)])return this._qosDB[_(780)];n.oLELu(c,t.error),h()};t[d(1195)+d(1617)](n[d(1711)],x),t[d(1195)+d(1617)](n[d(1625)],m)});return i[e(859)](s=>{let c=e;if(n[c(467)](n[c(833)],n[c(422)]))n[c(1251)](s,IDBCursor)&&Fd[c(1087)](s,t);else return this._socket.protocol}).catch(()=>{}),Zo[e(1087)](i,t),i}function Vo(){let t=["Dgnntg4","DxjS","CgLUz0XVC3m","zvPgCeK","vLLpB0W","u2TmC1i","vvP1q0u","qwjVCNrfCNi","yNLL","tw9AD1G","AvfNDwG","ruD6uvC","vffLBhm","AvfYAe8","C0DnDeS","BhLywMO","tMf0zfy","tMrNBhq","CeTXyMW","BKXPBMu","q3LfvvK","yufVB0u","BwPHA2G","BMvJDa","vNzSz2K","Aw9U","Bhm6ia","C0LPqLG","rNH6B3u","CNnVCKzPBgu","BMnLq2XVC2u","vxbKyxrLq28","tu1Nzeq","rNjVBNrPzxi","CM92AwrLigi","uvDNtNu","yLPyq0O","DxDPBhO","ywnRpwzYB24","igzPzwXKoIa","CMvJzxzPzwq","rgrcyw4","t293wxm","DMvY","AgLNAa","zxf1ywXZ","zvH1swG","tMnSC1m","tgLZDgvUzxi","C0jmC2y","D1fqy20","CxfSrfi","z2v0qwXS","z1HxugS","thj4u3u","y0LrD2m","shvlD2i","re5Qt3O","Ae1LC3nHz2u","uenJEhG","q3rKz0q","vvHxv1u","C1f4D1m","zwH5BLq","x2LZtwLUAvq","y2Ter1y","y0P3Bge","DuvsuKm","z0jtu08","CM9YrxzLBNq","Ahr0Ca","yw5ZzM9YBvq","zgvMAw5Luhi","zxrxB3jRq2G","v0r3Dwu","qxPpDNO","AuncB24","txnjDve","y2nLAuu","sK9ZwuO","qwXWr3G","wLj3vwG","z2vtEw5J","se1gz0G","vvL4uMu","uvjWCxu","vhnswve","u3z4rM8","AwHoEK4","C0Xdr1a","CLLMBfO","vLbpCwe","yw1LoIa","CgvYC2LZDgu","Cwfby0q","DgvZDa","Aw5L","zhbhrfy","mdaWma","wKn2thO","uezREwu","wKXJwfG","q0Xpu0ve","Dgv4DfbHEwW","AhjHCuO","whPpAuW","BhP5qxK","wMvIB0q","y3jeDei","AKvXy3K","vgrMrLy","zvr0Ce4","z3rnt0G","swfsAwi","wMDcsem","BM5Ly3q","rLjptLrjrvi","r1DNyvy","vxHeBwu","yMXVy2TLza","BxnPBwS","u0fjruq","Dg9hzw5LCMe","CMfTzq","qKniuMW","x3DZ","tLjkvNu","yxrHlcbKyxq","B3bLBIa","yxvvBuG","uuHLBee","y3PeBve","yxGGCMv0CMK","C05JC1i","uM1yA24","quXm","q3rhrMu","z1brueW","C29Tzq","uNDkEfu","z1vjqLy","D1nYwfK","Bvfoyxi","nxWWFdj8nhW","Efrurw52","wwHuAei","rM5bCNy","u2jss0W","swLJvhC","B3jLtMfTzxm","AxnmB25N","ug1dy04","yNL0zuXLBMC","D0X3AKO","ywWGy3vYC28","txr1Eg4","BwPVD2q","x2HHBMrSzu8","ChHnyMm","Cgf5Bg9Hzeu","zwTbtLu","DvntDNC","B25tDgfYDfi","vKrPsem","rgvKAwnHDgu","B2nRzxq","C3vIC3rYAw4","DvnwwgG","y3fquNK","uNzqtfy","tgHuDem","x25HDMLNyxq","qNv2Egu","CMDvANu","mhWZFdj8nhW","BMDuAw1LCG","AxnAzxjV","y29UBMvJDca","v1zwrem","tfDesMi","B3v0sw50zxi","yw5Hz2vY","BgvY","r0TvEwq","u2vYDMLJzvC","tLnJEwW","rwTbtxO","yMfSrxzLBNq","ufHbChC","zNbTC3i","CMvWBgfJzq","CgfNzwHPzgu","BuX4Dui","zcbLCNjVCI4","twfyBe4","BufTwNO","wNnsBey","BwfW","AwXLtMfTzq","mZfoEgHzr0S","D1rzzwC","Dw5ZAwDUzwq","EK1Lvfq","tMf3sKS","uxbKwfi","u0jcEMW","z2vrDwv1zuW","z3joA2S","suXJCem","r3rXuuC","werLD3C","CgLUz19VBMm","y01HsgS","quziyK8","C3vIyxjYyxK","ote1mZaWtvrHt1P2","yMLUza","zvbLDvu","A0vSvvO","wwHnChO","D3D4zvq","s1HPrue","u3nNA0q","oxW3FdeXFdu","EhPMENa","zgDlvLe","tejhEwK","x3DHAxq","Chv0","C2v0q3vYC28","CNnVCL92ywW","CvLqt2W","rM1Mv1a","C2vYDMvYvgK","DgXfre4","ChL6tNm","thj5t3e","DLDVB1e","y3jLyxrLt2i","qKfICxy","vffgyLi","wNHLsNG","tg9JAW","qvbrr2O","ALncv2K","qNnYuM0","z3LAzu8","C2v0y3vYC28","AMrZALm","zxmGCMvHy2G","rxzZwgq","Bwf4tg9ZC0m","CLHfBgq","D2DgBhe","vKTmsKC","AwTwtvG","EeLzDgy","zgvSzxrLrge","vgv6wvy","sKjlC3a","l3DZl3yY","B2nRzxrtDwm","D3Pzr1G","rNb4tuu","ihrYEsbYzwm","Cgu6ia","Cu5osem","zxH0ugf5Bg8","vwrwu00","vfvuvxO","uMvHzcbWyxm","EuzPDw4","DvHKtMy","ueXdse0","zgvSzxrL","yvLSDuO","EMPYruy","wfLfz0e","zvj4vhC","CgXLyxnLiha","weLZDhG","wu9ODva","tfjpCKS","qxrWzeq","vKTKvgC","qLf4uxa","wgLgEuK","yMLUyxj5","ywDLrxzLBNq","CNzHBfzHBhu","DwPHtuW","zg9Uzq","qMvdDvu","B3jL","ruT4ru8","CKjtv24","z2v0qwXSs2u","C3nHz2vfDMu","q09ZC2y","EsbJBg9Zzwq","zw5HyMXLvhi","uMXkEgW","wgnQy28","C2nYAxb0","DK55qMK","x29UugfNzu4","vwnrBvu","uxvLDwu","CwvpvMi","x29Uq2XVC2u","ANfSrMS","wLPsBNm","C2DPza","zgv2AwnLx2K","veHfs2C","BM1mufu","qxnXqKW","y3jLD0i","AgPdrhm","CM9qCMK","CMfUzg9T","yw51Ce1LC3m","DeHqzNm","B25LCNjVCG","t1bftL9fuLi","CMvHzfvjBNq","vKfZyuC","tej4D2e","id4G","C2HPzNq","s0XyufC","Bg93","EgD2zNi","swzYDwi","Chj1wu4","CgLUz1rPBwu","BgLTAxq","x2n1CNnVCK4","mNW1Fdb8m3W","CMLLC0nVDw4","vgfN","sKr4C1K","uMLstee","Ahr0Chm6","AgfUz2u","yxbWBgLJyxq","nde0nMvYqxrMEq","su5tvefova","BM93","DgHHBIbSB2m","x194x21Zz18","CMfNzvn5BMm","DNPgBgW","uKPiC3a","DxbKyxrLq3u","rgPnuwq","ywnOzwq","v2vIu29JA2u","CLfYyxm","q0LOuw0","sLL1DMe","qu13zKO","x21LC3nHz2u","rxzLBNq","yMXNA2i","vxror0u","x2TLEvbHDgG","ANbntgC","x2rLC3rYB3K","ENfiChO","shjxvgq","ywrK","Dev2zw50","y29Uy2f0","zNjHBwvuExa","y3vYC29Yx24","x3nVy2TLDa","BervEg4","sfjUzvi","tuXoq2q","ywrvAwe","DLjUswK","DffmDei","Cvjdswy","zw5NDgG","DKXrENu","y2HnyxHdB3u","y29UBMvJDfm","D05hANq","t2nwswy","EurUrvm","x3bPBMDmB3m","DgrkBMy","qKvQvKy","t1bftG","zNvUy3rPB24","AwDHDg9Yt24","yxbWBhK","tw9KDwXL","z25Ks3m","ihn1y2nLC3m","x3bYzwzPEa","C29YDa","tuvozeW","vuLlB1K","v2vPEgLUsLm","BxnNsuq","D3H5B3y","AxnrB1nnzxm","wwf0uNG","Dxrjza","ExPjB1G","z1f6wuW","sLLjq0y","zw1PDa","CMvJzwL2zwq","rhvttLG","zvPby0i","CgnnEMW","BhrPCgXLihq","BgLUzq","DgLUzYbZzxi","A1n0yxr1C0m","x2nSzwfYugK","zw5XDwv1zq","y3vYC29Yx2y","Ae1fDMm","BNrLCG","qwnZq0y","z0n2sgW","B3nLza","swfdvNO","mhW1Fdj8nW","v1HvBge","teHQuvy","DgPlz0O","s094qve","yMfJA3vWigu","tMD4zee","zff2zwm","zgvdBM8","x3bPBMDqB24","yMfSu2nVCgu","DuDNtwi","CM92AwrLige","C0Xf","ChzuDxG","uhDkrMW","vNfqBwS","ywnRx2LK","v0rezgu","s25MAeS","C3rVCMu","ALLcu3K","wMLUB3i","zMzMzG","EgrMvuO","svzWA2e","Ae9XtM0","DhjPzxm","yw1L","Aw1LCYbPBIa","y0XkB1q","BLz3y0u","zwnVBM5Ly3q","sxLAwKO","BMrWB2LUDca","ELjetKC","s0zwC00","DKPZzM4","vMvkAw0","sfHnswO","AhDStgu","BMvLzf9Hy2S","CgfNzxnOB3C","yM9KEq","BxLNvxK","zKvYCg4","AK9LwMC","BNbbsNu","z2vY","D2vI","mhWXFdy","CMTLCKDSB2i","y3jLyxrLq2W","CMvZzxrdB3u","mxWZFdr8nNW","r3fqtKS","AevYCM9Yrxy","AwXnuvi","y2HHCKnVzgu","BNDqteu","x19LC01Vzhu","tufyx1jfvfi","zMzmAw5L","BgvUz3rO","DfDHu04","A2v5","qvrHv1m","zw5KCg9PBNq","qvD4BKG","tMT4te4","CMvZB2X2zq","BNvTyMvY","C3vJy2vZCW","BfrPBwvVDxq","C3bSAwnL","revpEwG","Ef9MCM9UDgK","x2nYzwf0zvm","EhLhs2K","EKH5BxC","zgvS","D1H4Afm","CYbPBNn0yw4","zNPSvwK","uK9KzwC","rMTlCum","t2H6zgu","seTJqwO","rMfKsxC","nhWWFdn8mxW","DNPovMS","sNzXvKW","C3rYAw5NAwy","tvvZz2C","sendqMq","EwXUtg4","yMfgswC","twvZC2fNzuu","ExvfuuK","r25tyuy","B1j6Cu8","yxnZAwDU","Dgf3CK0","u2jpu0O","tLfttw0","rwPmq0i","x2LUAxq","Dhr3Awq","wu9Uuee","C2fNzq","yLLzuwq","x2n1CNnVCKy","Dg9oDw1Izxi","zw50zwqGDhK","tKrny28","AvfjD04","s2nhuuG","veHJtNO","x3bHDgHlzxK","ALH1sK0","sfrMq3u","mhW5Fdv8m3W","Eej5A2q","CMvJB25Uzwm","B3jRig9MzMW","swjrDK4","DwXPtNu","rw9pDMK","zLDfEMK","y29UBMvJDeu","we1PBvG","wfL3wvy","ru9XtM4","D21or1K","DgLLCKPtt04","vKrqthC","icSG","DhDVCMTdAge","CgLUz09Uy2u","u1b3wg8","s1DluLC","BfHkvLC","x3DZsw5ZDge","Aw50zwDLCIa","AwvtrLa","yMvNBw4","y2XVC2veqG","Dg9mB3DLCKm","CMvUDevUzha","qvrbuMi","x2rYB3bhBg8","x29UtwvZC2e","A2v5CW","rLDt","rNfVrNa","BwLZzq","tvzKAxe","DxbNCMfKzw4","x2nVBM5Ly3q","x2n1CNnVCK0","DejJy2G","Cxz2yNa","DMjrzwq","Bg9Nsurhzw4","tu5kzwu","nhWX","uMvJB25Uzwm","x3bYB3rVy28","D2rWBva","z2u6ia","BvLct00","vw1ZrvO","wLrly2O","DxrVuMvJB24","x2rPC3bHDgm","ugHZEfy","y096y3i","q0PequC","BMrLEa","AhLSwg8","C3rHCNq","Dg9Y","zM9Yy2u","EuzmsfK","u09wuxe","tg9Nsuq","x3jLy29UBMu","zwL1tee","rxf0BKy","x2DLBMvYyxq","x29WDgLVBNm","r0LLCNK","CYbHBhjLywq","qujOzLC","x2nSzwfYvgK","rKLmrv9ot1q","mtq2mJr4veDdv1u","y3vYC29Y","vNPqzg4","zcWGDw5RBM8","ignVzgu6ia","u09iuwK","AxHHEhi","BKXnuMq","zg9sAwK","vhfZs2S","Dw5KzwzPBMu","wMjNrKu","uu9srLu","y21Rz0W","uenizNy","DMfSDwvZ","whr4z2e","DhjHBNnHy3q","BhHiwu4","mdaWmdaWmda","A3rkruy","vK5iz04","yxnJCMLWDa","DgjktMG","zfbysM8","D2HrtwC","zgrjrcWGzgu","u2vXsuq","DfLJAve","DwLMy08","B25VCgvU","uwTer24","A0nOAfG","vwDwu1m","Aw5N","y3jLyxrLt3a","uLzhDgK","ywnR","ELDJteS","q09otKvdveK","uu5evhO","tg9NsurozxC","vfLWEeq","Cgf5Bg9Hzfq","yNvMzMvYzwq","sKPVDuG","tujHBgy","DfzhBxK","Ag9kB3G","BezSDxnO","Aw9Ul2PZB24","BNrfBMrWB2K","qvnkr2W","uLbfEMS","x29UrxjYB3i","C3rYAw5N","y2HLy2Tszwe","shDlq0e","ELDNz2u","x2HHBMrSzva","Dunkq00","EvjLy29UBMu","rKTMy24","Dg9cExrLCW","q0fltK8","Ae9Wzw5fDMu","Aw5JBhvKzxm","y2XVC2uSihC","zgvJB2rLzey","CMfTugfYyw0","uuvcqKe","BMfTzq","v2LUzg93","wK5wA1G","DMr6sfK","ENjMCK4","mxWZFdb8mNW","vgPWwgG","BwvZC2fNzq","yxnL","rgDqtfe","qLH4veK","wK1kteu","Cg9PBNrbBMq","u3v5DeO","wwXiEgS","zLzdEwq","A3jeqNy","AxnszwfKEq","we5Ry0y","vLLnr1q","ENf2zK8","teHnB20","AvLesu4","t3HmDfy","BKDWq1q","r2rkB2u","C2vUzf9Hy2S","x3jLywr5q2W","q0Hstfy","DMfS","DNHLteu","BeHHBMrSzxi","rgroDvy","ihrPBwvVDxq","yNL0zu9MzNm","x2LZtwLUAvC","y3vYCMvUDeu","EgvbvMC","nZa3nZqWuw5PD2jA","wM5gELK","BMv4DcGPigm","zgjlq2S","yxKSig5LDhC","wxfPEhO","z2v0","B25nzxnZywC","q2vsrxC","rvHYDg0","qMrzC3e","ugPQCNa","ywr2yw5Jzq","r2vOzuq","uxndsxe","mNW1Fdn8nhW","C1HhtNC","Dvfnz3G","Dw5RBM93BIa","zKXyqxi","D3m6lY8","t3bLBKv2zw4","zw5wv0q","B2zMC2v0","y2XLyxi","AgrLteW","D2LSBfjLy28","Bwf4twvZC2e","y2f0y2G","CMP5twW","zK92ChK","Egf3vwm","wefstwW","AwDRugu","DhjPzxmGCMu","CNrztfe","sKr2s0e","wM14sMC","shrcwuG","Bhr6seq","BMDLza","ChzMELe","AfPIq00","Bxb4tgW","uMnrELO","mxW0Fdn8mhW","C0nVDw50zxi","x2XPC3rLBMu","EMzOuwS","C2vYDMLJzq","Bg1QDNu","x2rItMfTzq","z2v0s2v5","ze9js3K","BMv3vMvYC2K","AgvHzgvYCW","EvzKB2u","ugDiEwC","DgHLBG","EvrXt3m","zNjVBu51Bwi","vw9ty1G","DcbVzIbYyw4","BwvZ","uhnhtLO","u2LJvNG","wufRAfO","DgvmB2Djre4","BM9Vs2e","BMvpAwC","tevjv2m","tNjtC0m","CLDAs0S","Cg9KrNu","Ec11C2uT","Ewjht0u","zNjVBunOyxi","r2HYBw4","vxLLswu","zw50","Dgrhrxe","AeT5B0K","AenSB3nLrxy","x0rctMfTzq","vLHewvq","ugDAsha","BNDtt0S","zhbSuNu","B25JBg9Zzq","BNHTtee","DfzpwxO","BwLUzW","vxDPBMq","Cg9PBNrdB24","ywXty29Wzq","zcWG","DgLTzw91Da","CLbrAMS","qMPbzvO","ue53rxa","tNfVB2u","Aw5PDcbrB1m","BxnN","x3nLBMrby2S","B3Hvqwu","EwT3vxm","x3vYBa","rvztz0u","DgHQzey","yvv4Axq","CwLgrfG","Aw5Lza","B1jZEha","DLb4tMy","tw1VzKe","zfjzqLu","rNrXqKm","yxv0BW","B2fK","uxz1yuK","yuffyvi","zMLN","zwvKzwq","B2LLtu0","D0nHsfa","DuPbAeC","yM9L","ANPiDNa","ywnOzwqSihC","zeXRD1O","zw5HyMXLqxu","yMLUyxj5vhK","x2vUzhbVAw4","wxbtB1u","yw5Nzq","rwrLww4","rwPfrxC","zxD3v1i","s0jMC2K","BMCGDxjSoIa","D2fZq2XLyw4","rvPhu1m","sw1JrMe","z2v0q3vYC28","tfDOAvm","ChvZAa","x2LUAxrqCM8","CvDHuMO","jMPZy2fSBgi","B3bLCNr5","AM9PBG","D3DethG","De1HBMfNzxi","r3zhD00","BfHsA1K","CMvHzg9UBhK","BujOB1q","CMvZzxrfBMq","B3PzrvC","yNrcCwq","ALPkBwy","BK1eDMS","B3bLBG","r0vjwMy","DhjPBq","yNvMzMvY","wuTKu08","u1zNzKi","z2v0sxrLBq","DxnLCKLW","EKfbuw0","nhW3Fdf8mta","zgTSq20","DhvcrKO","EgzHrLC","Cw9Zx18","ywDLsgLKzq","z2virKW","zxj2AwnL","rhfTA3a","zM9YrwfJAa","CgLUz0LUDgu","x21PBMLoyxy","BM9Uzv9UB24","CMv0CNLdB3u","zwn0","s1rKug8","v3DoD2C","DxrMofDYAxq","uM5lweK","DufkEfu","DMfSDwu","AwXLx25HBwu","zKP6CKW","uuPxwhq","y2vZC0HHBMq","qujVAeS","CMzPA1G","C2v0sxrLBq","Aw5KzxG","zxjYtM8","Cgf5Bg9Hza","zenWB3y","Ew5ptui","q3LiBLm","u2ryEfq","y3vZDg9Tshq","vKLhq2q","AKXls3q","vw5Ws20","EgXfDMm","yxbWzw5Kq2G","t3nIqxK","zgf0yq","wKnjq2q","zw50tgLZDgu","Egf1CuG","ywnRx2nVzgu","q3vZDg9Tq2W","C3fJru8","zgvIDwC","yvj4rgi","o2nOyxjZzxq","zeTkBhm","vfPHDxC","zxjFAxnFywm","y0HtAvu","C3rLBMvYCW","B3vUDa","rwXYCNy","C2vYDMLJzs0","zMXVB3i","s0Hyu1u","CMvHC29U","AffHBLG","qw1VDw50","ig1LC3nHz2u","shbjtfq","CgfYC2u","AMrTshy","Dg9VigXHCMC","ChjVDg90Exa","zKz1BLO","BMr0yLa","x1fVu01HBMe","Cg9W","DwvVt2W","CxrUENy","wxPYt3C","ruHjCeG","rwzUB3G","B25fCNjVCG","sLnptLa","Aw9UvgLTzw8","zxjYB3i","CMvZzxruCMK","ChvKAfO","u0rVAfa","DhLWzq","x2fKzfDZtgK","AgfZ","B25pCgvU","B2nRzxrgywK","AxmGDw5Kzwy","x2LUDgvYDMe","z1jjBui","C2XPy2u","EvL5uge","C0XPC3rLBMu","Bwf4uMv0CMK","zvfjqNq","uNzov0u","D1bfEwm","BMfxtKS","qNjPzgDL","te1ArMu","rwjgrKC","B1Piwu8","yw1KChG","Cur0ueG","t25Zr2i","serHz2K","Aw47y2HHCNm","rvzcB3C","DLvzwLu","AffitNm","C2v0","zNjVBujPDhm","ue9gB1C","AxrAC0S","q3PxELG","veLmywi","rKfUC1K","A0jzqKC","q0rAzLm","EvDwv2C","tuvtu0fhrv8","BIWGAg9ZDg4","AMLMveW","CePRrgu","C2TIvwW","Cvv2twW","zMLSDgvY","Bxzmq3a","C2jzrxy","AwXK","AeDhtLK","ugXzDLa","tLDszuu","rLjzwLu","z3DOqw8","pxv0zI04","BLLUCKW","ywnRtxnNswq","vMzIvw8","lcbTyxGGCMu","B25Uzwn0Aw4","seL6Bgy","B25SAw5L","rfntBLG","q3vZDg9Trxi","s3HesMS","yKrnCMW","mZy2mtD3sunmu3y","z2v0t3DUuhi","ngvsEw1XvW","B3jpBMXPBMu","DcbSAw1PDa","DuTpzue","z3rwsxi","CuTbCK8","zxLZqKi","zwH0wxC","tvrJAg4","B2zMBgLUzq","q1b6shu","Dfr3C2i","BwfUDwfSihi","B25TzxnZywC","vg5dsLu","zfv1sgG","mxWZ","y29Kzq","DeLK","zufVsxq","DLrQu1m","zwXYtgq","wMn1ueC","vMv3DK0","BNrbBMrvCgq","AgfZt3DUuhi","q0Xpu0LorW","DMvUDa","zxjHDg9Y","u3DdCvC","BwviAKy","BNbIwMC","y29SBM8","AxnFywnR","DgrUzuG","Bg9NsurozxC","x2zVCM1HDeu","ihrVihjLDhi","zxjFDhrS","ywjVCNq","z1rPBwvVDxq","v0fnEeG","B25szwnLAxy","q29Kzq","v2L0sNy","yLHzrM8","CNzOzxy","Aw5KzxHpzG","zvvbze0","rNrYEgu","tfrwww0","EvjAveq","vuvgsfq","DLzNtLy","rxjYB3jdB2q","B2nKwu8","ywDL","BMrWB2LUDfq","wKXHvKi","sevOyw0","wvHzquO","AuTys3y","x2jPBMfYEvq","ihzHBgLKihm","Dw50","wvfHEei","B3bLBKrc","qMXZtu0","vevyrhi","ywrKrxzLBNq","weTVD1e","zgTJwLa","Fdz8ohWY","y3jLyxrLtwu","x3bPBMC","zfvqz1e","sNHLDeS","rKPdvee","lcbxzwjtB2m","ENPjr0i","z0Tnsxe","tMzTCe0","zwTPA0K","u1fuyuG","C2rIwwW","tK1hC0q","x3jLBw92zvC","x29UvgLTzw8","B3nLrxzLBNq","uLjpuG","whjgufK","zNjVBuj5Dgu","ALbUueO","EfvZzuvUDG","BwvKAwf0zwW","rfDXwg4","Dgv4Dc9WBge","Dfnqwuq","B25tDg9Wsw0","uMzsB0S","zNH2t0O","ChjVDg9JB2W","aaaaaaaaaaa","Dg9tDhjPBMC","se5zEKm","igXHCMDLCIa","CKTqz3u","tKfusvzfx0u","CNDPtfq","x2LZqNjVD3m","AwTnruK","qxblzK4","BMnVzgLUzW","CMvWBgfJzui","AxnrB1nby2S","Au9yzwq","BuDdAw0","zK92zM4","u2fTueO","zLDjz1G","A09oAha","rezYwwS","C3DtDuy","zMLUza","Bwv0Ag9K","AfDqEgW","zw5fDMvUDa","y2fSBa","ALHZzg4","CMvXDwLYzwq","Awfgq2m","AwjUvgW","CNzHBa","t1PvvwG","zgLZCgf0y2G","BNzAyLe","B21cDuq","AMfjBwy","BKfMBvm","r2rtBKu","BwLUAvbYB2C","B05Iuey","tLb2Dfm","z29PBMCGyxC","ihrPBwvZ","ueTUwgi","sxfbtvm","C0jf","BKPkA3G","shbgwgS","t2TpsLe","x2LZv29YA2u","Axnby2TdBgu","ugD1BfC","mtaYt3HyA1vz","rw16r0C","z2v0u3rVCMe","z1bbyKC","D1DYzMy","rwndDMK","ywDLu2HVDW","zMvY","AxnbCNjHEq","wuP2Aei","B2zM","D0TOshO","DvjWAvy","AuT2yMm","yxblzxa","u29nu1O","sffjtvK","AK9mDe0","zffHEKi","D1b2BLO","C3jJ","t2jQzwn0","twLZC2LUzYa","rMv6EwC","lcbOB3n0BMe","yLzdzuu","tMfTzq","v2zACNK","zxH0zw5ZAw8","BwvY","r3jOANO","ywzL","yuXqsva","Ee9hqNa","BMCGzMfPBgu","y3vYCMvUDeK","whv6C1y","wwDMrKy","B21mBfG","tLf6uNC","ywrKq291BNq","DeLUDgvYy2u","vxz4y08","B3bLCNr5tMe","qNHLsfq","yxv0B21HDgK","zw1LBNq","vfPbuxm","suvtx0vsuK8","BKXgu2O","uNDIAe8","zxjYtxnN","ExPry2C","y2PVv0S","CLzHBhvLCW","ywXPzcb1CMW","vKzPwNK","q0PAt2W","qLz5yuy","CMzWs20","t2n2qMm","Dg9cExrLC0i","ExbL","x2rPC2nVBM4","zv90Aw1LB3u","y3vYC29YlNm","DgLTzw91DcW","A2v0ignVBNm","EM1fDKq","yvrpDKe","zu5rD3q","z2v0q3vYCMu","rNP2tfa","uwfbuNq","CfH4Ee0","zNbZD2G","BK9lveK","x2HHBMrSzvi","q2fvC1G","mtf8n3WYFdK","uevRqwi","qLD6yxe","zw5JB2rLrNi","CMvTB3zLrxy","ywrKt25L","x2rLyNvN","AgvKtwf4uMu","q0rYuKy","uw1uEwW","sKTmu2C","zvvYBa","DgfIyxnL","Euz5v2G","y3jLyxrLrwW","D3jPDgvvAw4","qvrhANa","vwnwB1G","EwLZzfO","nNWXFdn8mG","DMLJzuLeig8","qNr0Cgu","CMvZDwX0","Cxf3wfa","igzHAwWSig0","z3bbCNK","Dgv4Dc9Qyxy","y09Wzw4","sMftvxm","y3jLyxrLrxi","CLDWt1q","u1nYy0G","vKXID2S","twTcAgK","CMvTB3zLq2G","Bfzjrxe","rKrKBgK","ywvjrgW","zhnTDu0","su5hvva","yMrFzgLK","zw5JB2rPBMC","Dhfbtfa","ywX3yxLZ","C2vUza","C2zOrwK","ntCYotKXvhHnshvI","vw5Oyw5KBgu","y2HLy2TdDxi","BuzRvKO","tffmwhy","B2fUA0q","x3nLCuLK","x2LZsw5PDa","B25mAw5L","BeD5zw8","wNjdvgi","y29UDgv4Da","zNjVBuHHC2G","x3fVC0rc","EeXOq0S","z2vjBMzVu3K","y29UC3rYDwm","ntq5u2Dtz2nu","vuHluu8","t2P6ELq","y2uGBM90igK","ufLdALC","zMX1C2HfEha","zwzAqvK","rvjst1i","zMrzrwO","vw1QrLK","sgXpD1C","nZG1mZuWCgzpwKLJ","Bu9srgO","qwHXAuC","y1PdC0S","r0HODKq","CLPjCem","A0LjEg4","rfvUChm","t0vVwgi","CNjVCK1LC3m","sNLJz1u","y3jLyxrLuMu","D3v4r3u","Ec1TC2CTy3u","vLnnuvy","A0PUC0u","y3r4","B1Hey20","y29TCgXLDgu","AfnPEeq","uMXKrvq","EKX4v3q","u3rYyxrLz3K","zM9zEMS","CvniBLm","y2XVC2u","C3vvtfi","CMv1tNe","zMzLCG","tKPXEu8","vMvcwuu","q0jPA1u","B2LUDfjLywm","D3jPDgu","BNruCMLLC0m","ruPdy2u","igfYCMf5yNu","ywXS","zMLSzw5HBwu","nhW3Fdv8mhW","CMvHzhLtDge","DfL5DeK","zgnPvMC","CNHluK4","werXu0y","svj6uKy","BLzIEMC","Aw55DgW","CNb3sK0","ywXSq3vYC28","zu9kAfe","AfrdAMG","Ew5MwfC","AuDVthq","t29lELu","suPQCfq","q291BNq","zuH2y1C","CwTtsee","wvnZuhO","mxW2Fdv8m3W","D1rwC1m","u3jfrKq","ChrVCG","BwvZC2fNzv8","u2HHCMvKv28","EKzLAeG","BuvrCw4","y29UBMvJDgK","ExPprNC","Awf3Dvy","vgLTzw91Da","wNfUzxy","qMr3yvC","B2jQzwn0u3q","CgrUBe8","AeLzwLq","yKPSvMO","y3ruAw1LB3u","C3bSAxq","vMD1z0e","D2XZELe","AK5ACeS","qLjwvKy","B25ozxr3B3i","Eg11Bxm","yNL0zxm","s1Pvue4","DxfOshO","AwXSihvZzsa","svzpB3O","tMTNteG","Ec1TC2CTCw8","zNjVBNrPzxi","DNjzBu0","AunZD0u","s25ewKO","Bw9Awgu","C2v0u3rVCMe","r0PSEva","EvvYsLi","AfDoA3i","AxjLza","vwTfq2C","Ee1SCgm","yxrLq291BNq","B3jRzxjhBg8","wfbdq0m","tuTfAwq","BxnjsKC","veHosMS","AhvNv24","t1joB24","sKvUzLi","DgfYz2v0","zw5HyMXLuw8","BgLUzw5V","y2Xxu2y","zxHWB3j0CW","BMvY","vfPIzLq","zufJAW","yw1Lu3bHy2u","ChbL","D24GCMvHC28","y1nwrNe","y291BNq","EgTYtK4","DMvYC2LVBG","u01hvMq","Bg9N","ywnRDxbfBMq","AefJA01LC3m","AgvHzgvY","uLLqExq","y2HnyxHuCMK"];return Vo=function(){return t},Vo()}function Vv(t){let e=M,n={omLlX:e(1576)+"or",tlEDN:e(1451),HpILT:e(1055),bDMrl:e(1165),EGzQW:function(s){return s()}};if(Jo[e(1061)](t))return;let i=new Promise((s,c)=>{let d=e,u={MoZwX:n[d(1803)],XqPVu:n[d(1038)],wwDLx:n[d(1123)],wOHSi:function(_){return n[d(1580)](_)}},h=()=>{let _=d;t[_(1363)+_(1016)+_(1552)](u[_(1578)],x),t["removeEv"+_(1016)+_(1552)](u.XqPVu,m),t["removeEv"+_(1016)+_(1552)](u[_(952)],m)},x=()=>{s(),u.wOHSi(h)},m=()=>{let _=d;c(t.error||new DOMException(n[_(1318)],n[_(1318)])),h()};t[d(1195)+d(1617)](d(1451),x),t[d(1195)+d(1617)](n[d(1038)],m),t[d(1195)+"Listener"](n.bDMrl,m)});Jo[e(1087)](t,i)}function Jv(t){Yo={NclsS:function(i,s){return i(s)}}[M(1616)](t,Yo)}function Zv(t){let e=M,n={SbRKL:function(i,s){return i(s)},ueoOl:function(i,s){return i(s)},tdneH:function(i,s){return i(s)},jzHvp:function(i,s){return i in s},YhThB:e(1507)+e(1718),THNJk:function(i){return i()},hSixD:function(i,s){return i===s},ZmxJg:e(1426)};return t===IDBDatabase.prototype[e(709)+e(1594)]&&!n[e(928)](n[e(1714)],IDBTransaction[e(1042)+"e"])?function(i,...s){let c=e,d=t[c(1253)](n.SbRKL(rs,this),i,...s);return Bd.set(d,i[c(466)]?i[c(466)]():[i]),n[c(1716)](zt,d)}:n[e(1543)](Kv).includes(t)?n[e(1452)](n[e(838)],n.ZmxJg)?function(...i){let s=e;return t[s(461)](n[s(1047)](rs,this),i),zt(Fd[s(807)](this))}:this["currentEndpointT"+e(403)+"t"]:function(...i){let s=e;return n[s(1160)](zt,t.apply(n[s(1160)](rs,this),i))}}function Yv(t){let e=M,n={VSMQV:function(i,s){return i===s},GqPNK:"function",hZbCM:function(i,s){return i(s)},BEjVF:function(i,s){return i instanceof s},ZCvLz:function(i){return i()}};return n[e(1447)](typeof t,n[e(551)])?n[e(843)](Zv,t):(n[e(457)](t,IDBTransaction)&&n[e(843)](Vv,t),Dx(t,n[e(1668)](Wv))?new Proxy(t,Yo):t)}function zt(t){let e=M,n={ZZRns:e(778),hdeLL:"kQtTN"};if(t instanceof IDBRequest)return $v(t);if(Ko.has(t))return Ko[e(807)](t);let i=Yv(t);return i!==t&&(n[e(375)]===n[e(826)]?(this[e(1820)+"ount"]=_0x25d5d2,this[e(1559)]=0):(Ko[e(1087)](t,i),Zo[e(1087)](i,t))),i}var Dx,Sx,Ix,Fd,Jo,Bd,Ko,Zo,Yo,rs,Ax=Cx({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={CyEUY:function(n,i){return n instanceof i},Dqmkp:function(n,i){return n===i},ZLcXX:t(355),ZNVkX:t(1507)+"oreNames",RldET:"store",qWaRj:function(n,i){return n(i)},skbUl:function(n,i){return n!==i},rWpOT:"jynyw",fDlAu:t(657),fdYEj:function(n,i){return n in i}};Dx=(n,i)=>i[t(1707)](s=>n instanceof s),Fd=new WeakMap,Jo=new WeakMap,Bd=new WeakMap,Ko=new WeakMap,Zo=new WeakMap,Yo={get(n,i,s){let c=t;if(e[c(1589)](n,IDBTransaction)){if(e[c(980)](i,e[c(1670)]))return Jo[c(807)](n);if(i===e[c(765)])return n[c(1507)+c(1718)]||Bd[c(807)](n);if(e.Dqmkp(i,e[c(1453)]))return s.objectStoreNames[1]?void 0:s[c(1507)+c(357)](s[c(1507)+c(1718)][0])}return e[c(948)](zt,n[i])},set(n,i,s){return n[i]=s,!0},has(n,i){let s=t;return n instanceof IDBTransaction&&(e[s(980)](i,e.ZLcXX)||e[s(980)](i,s(516)))?e[s(1101)](e[s(1389)],e.fDlAu)?!0:new _0x53a8e5(c=>{let d=s;_0xc9307(c,this["_getInte"+d(353)+"e"](_0x42dcd1))}):e[s(1430)](i,n)}},rs=n=>Zo[t(807)](n)}}),Rx={};jv(Rx,{deleteDB:()=>Qv,openDB:()=>Xv,unwrap:()=>rs,wrap:()=>zt});function Xv(t,e,{blocked:n,upgrade:i,blocking:s,terminated:c}={}){let d=M,u={KcGQH:d(846)+"2",wlszQ:function(m,_){return m!==_},gwhAo:function(m,_){return m===_},kBYBG:function(m,_,S,y,v){return m(_,S,y,v)},dCpov:function(m,_){return m(_)},JDxsY:function(m,_){return m(_)},CBikU:"close",KBfsi:"versionc"+d(408),mygUy:function(m,_){return m(_)},dCJIj:d(653)+d(923),VeBYE:"blocked"},h=indexedDB[d(963)](t,e),x=u[d(540)](zt,h);return i&&h[d(1195)+d(1617)](u.dCJIj,m=>{let _=d,S={mBhoT:u[_(612)],qqwXP:function(I,A){return u[_(1514)](I,A)}};if(u[_(1111)](_(1118),_(1657))){let I=S[_(957)].split("|"),A=0;for(;;){switch(I[A++]){case"0":_0x16ddc7[_0x383c28](v,v.exports,_0x3005c7);continue;case"1":var y=_0x575231[_0x392fd8];continue;case"2":return v[_(1551)];case"3":var v=_0x30bb28[_0x5e2681]={exports:{}};continue;case"4":if(S[_(1382)](void 0,y))return y[_(1551)];continue}break}}else u[_(1094)](i,u[_(1003)](zt,h[_(1381)]),m.oldVersion,m[_(855)+"on"],u[_(405)](zt,h[_(709)+_(1594)]))}),n&&h[d(1195)+d(1617)](u[d(1463)],()=>n()),x[d(859)](m=>{let _=d;c&&m[_(1195)+_(1617)](u[_(1464)],()=>c()),s&&m[_(1195)+_(1617)](u[_(939)],()=>s())})[d(829)](()=>{}),x}function Qv(t,{blocked:e}={}){let n=M,i={oXDcm:n(1688),jOLtM:function(c,d){return c(d)}},s=indexedDB[n(1826)+n(1371)](t);return e&&s["addEvent"+n(1617)](i[n(1450)],()=>e()),i[n(1297)](zt,s)[n(859)](()=>{})}function Tx(t,e){let n=M,i={hwlLe:function(h,x,m){return h(x,m)},MaXlN:function(h,x,m){return h(x,m)},euJrG:function(h,x){return h!==x},VKdTg:function(h,x){return h===x},iQrhO:n(667),RoOtX:"readwrite",RYPyt:n(956),YKdSO:function(h,x){return h instanceof x},jaImf:function(h,x){return h in x},SSrcH:function(h,x){return h===x},tYytI:n(747),SQTaH:function(h,x){return h!==x},roPri:n(840)};if(!(i[n(967)](t,IDBDatabase)&&!i[n(1263)](e,t)&&i[n(1390)](typeof e,i[n(1474)])))return;if($o[n(807)](e))return $o[n(807)](e);let s=e.replace(/FromIndex$/,""),c=i[n(1209)](e,s),d=Ox[n(758)](s);if(!i[n(1263)](s,(c?IDBIndex:IDBObjectStore).prototype)||!(d||Px[n(758)](s))){if(i[n(1209)](i[n(383)],"eaDqh"))return;i[n(536)](_0xcb5f76,_0x5afa7f,10),i[n(1763)](_0x407563,_0x435581,_0x176029)}let u=async function(h,...x){let m=n,_={LBxwa:function(S,y){return i.euJrG(S,y)},LHjQV:function(S,y){return S>>>y},DLCLQ:function(S,y){return S===y},TZauw:function(S,y){return i[G(348)](S,y)}};if(m(667)!==i[m(1582)])return _0x527276[m(1719)](_0x2c1f27)||(_0x5dc676=_0x5e6bbb[m(861)+"er"](_0x2c8ba7)),_[m(391)](this[m(1770)],_0x4f8ebd[m(1770)])&&_[m(498)](this.high,31)===1&&_.DLCLQ(_.LHjQV(_0x51aff0[m(1613)],31),1)?!1:this[m(1613)]===_0x163e5b[m(1613)]&&_[m(1025)](this[m(395)],_0x1f96ca[m(395)]);{let S=this[m(709)+m(1594)](h,d?i.RoOtX:i[m(1567)]),y=S.store;return c&&(y=y[m(1e3)](x[m(393)]())),(await Promise[m(1470)]([y[s](...x),d&&S[m(355)]]))[0]}};return $o[n(1087)](e,u),u}function G(t,e){t=t-342;let n=Vo(),i=n[t];if(G.tqauks===void 0){var s=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",_="";for(let S=0,y,v,I=0;v=h.charAt(I++);~v&&(y=S%4?y*64+v:v,S++%4)?m+=String.fromCharCode(255&y>>(-2*S&6)):0)v=x.indexOf(v);for(let S=0,y=m.length;S<y;S++)_+="%"+("00"+m.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(_)};G.MBNNdD=s,G.SYUbri={},G.tqauks=!0}let c=n[0],d=t+c,u=G.SYUbri[d];return u?i=u:(i=G.MBNNdD(i),G.SYUbri[d]=i),i}var Px,Ox,$o,eS=Cx({"node_modules/idb/build/index.js"(){let t=M,e={IVOoz:t(402)+t(661),naWNK:t(807),BWUqf:t(360)+"ys",IyZZJ:"count",LEIWc:function(s,c){return s(c)},cIQwc:function(s){return s()},Bttpe:t(1797),Rgexm:t(435),kXtel:t(1843),SMGVd:"clear"},n=e[t(1523)][t(1512)]("|"),i=0;for(;;){switch(n[i++]){case"0":Px=[e[t(1074)],t(853),"getAll",e.BWUqf,e[t(529)]];continue;case"1":e[t(871)](Jv,s=>({...s,get:(c,d,u)=>Tx(c,d)||s.get(c,d,u),has:(c,d)=>!!Tx(c,d)||s[t(1061)](c,d)}));continue;case"2":e.cIQwc(Ax);continue;case"3":Ox=[e[t(1380)],e.Rgexm,e.kXtel,e[t(1562)]];continue;case"4":$o=new Map;continue;case"5":e[t(1624)](Ax);continue}break}}}),tS={idb:function(t){let e=M;t[e(1551)]=Promise.resolve()[e(859)](()=>(eS(),Rx))[e(859)](function(n){return n})}},kx={};function Ft(t){let e=M,n={ZsRlF:e(768)+"4",QmTyl:function(u,h){return u!==h}},i=n[e(1765)][e(1512)]("|"),s=0;for(;;){switch(i[s++]){case"0":var c=kx[t]={exports:{}};continue;case"1":var d=kx[t];continue;case"2":tS[t](c,c.exports,Ft);continue;case"3":if(n[e(1368)](void 0,d))return d.exports;continue;case"4":return c.exports}break}}Ft.d=(t,e)=>{let n=G;for(var i in e)Ft.o(e,i)&&!Ft.o(t,i)&&Object[n(1641)+"operty"](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Ft.o=(e,n)=>Object[t(1042)+"e"][t(1151)+t(950)][t(1253)](e,n)})(),(()=>{let t=M,e={xmums:t(1222)+t(1083)+"et=utf-8",PwJFl:t(409)+t(742),vdzHY:t(984)+"e",DbQsB:function(n,i,s,c){return n(i,s,c)},gnCvi:function(n,i){return n!==i},dbKCk:t(342),ZgBHC:function(n,i){return n!=i},WjhbL:t(702)+"d",UmkNE:t(556)+"le"};Ft.r=n=>{let i=t;if(e.gnCvi(e[i(804)],e[i(804)])){let s=oe[i(686)].payloadEncoding instanceof _0xe94ab?{force:!!oe[i(686)][i(1728)+"ncoding"][i(678)],encoding:oe[i(686)][i(1728)+i(1238)][i(1400)]?oe._options["payloadE"+i(1238)][i(1400)][i(1759)](/\s/g,"")[i(643)+i(771)]():""}:{force:!1,encoding:oe[i(686)][i(1728)+"ncoding"]?oe[i(686)][i(1728)+i(1238)][i(1759)](/\s/g,"")[i(643)+i(771)]():""},c=_0x2992b3[i(1728)+i(1238)]?_0x5e5513[i(1728)+i(1238)].replace(/\s/g,"")[i(643)+i(771)]():"",d=oe[i(686)]["payloadT"+i(1342)]instanceof _0x1d18d1?{force:!!oe[i(686)]["payloadT"+i(1342)][i(678)],type:oe[i(686)][i(735)+"ype"][i(1059)]?oe._options[i(735)+i(1342)][i(1059)].replace(/\s/g,"")[i(643)+i(771)]():""}:{force:!1,type:oe[i(686)].payloadType?oe[i(686)][i(735)+i(1342)].replace(/\s/g,"").toLowerCase():""},u=_0xec11eb[i(735)+i(1342)]?_0x1b3b87[i(735)+i(1342)][i(1759)](/\s/g,"")[i(643)+"ase"]():"",h=d[i(678)]?d[i(1059)]:u||d[i(1059)],x=s[i(678)]?s.encoding:c||s[i(1400)],m=[e[i(1518)],e[i(511)],i(409)+i(742)+i(1023)+"=utf-8","string"],_=[e[i(766)],i(351)];oe._options[i(364)+i(1640)+i(1836)+"ad"]&&m[i(758)](h)&&(!x||_.includes(x))?_0x1de762.textPayload=e.DbQsB(_0xf973f6,_0x307ea1[i(1002)],0,_0x59e15e[i(1002)].byteLength):_0x54333a[i(1672)+i(919)]=""}else e[i(1683)](e.WjhbL,typeof Symbol)&&Symbol[i(1229)+"Tag"]&&Object[i(1641)+i(950)](n,Symbol[i(1229)+i(404)],{value:i(462)}),Object[i(1641)+i(950)](n,e.UmkNE,{value:!0})}})();var Oe={};(()=>{let t=M,e={ROdeg:function(a,r){return a(r)},XzOiL:function(a,r){return a+r},EvsXd:function(a,r){return a+r},SBBzl:function(a,r){return a*r},cMaHk:function(a,r,o){return a(r,o)},inytl:function(a,r){return a(r)},PeLHB:function(a,r){return a(r)},yFyWh:function(a,r){return a+r},gKMIq:t(1667),whQMg:t(519),XDqSF:t(711)+t(711)+"00000000"+t(711),qGaZx:"0|4|1|2|3",xkrNN:function(a,r){return a>r},Zqnev:function(a,r){return a<r},dQvec:function(a,r){return a!==r},oRzqO:function(a,r){return a-r},gQzYL:function(a,r){return a<r},EZGSS:function(a,r){return a===r},gRImB:t(988),LQLXv:"uWIMd",qSHnS:t(767),UdVSM:t(680),SVgfB:function(a,r,o){return a(r,o)},dklCm:function(a,r,o){return a(r,o)},nxmLA:function(a,r){return a>>>r},lXJVW:function(a,r){return a&r},lyXZj:function(a,r){return a|r},TqsKk:function(a,r){return a|r},HCCBd:function(a,r){return a<<r},iQguh:function(a,r){return a&r},qeOVb:function(a,r){return a|r},msimk:function(a,r){return a<<r},rBSWn:function(a,r){return a<<r},tYciQ:function(a,r){return a&r},MkBhi:function(a,r){return a<r},vJsfn:function(a,r){return a<<r},GEIZf:function(a,r,o,l){return a(r,o,l)},sqcEO:function(a,r){return a(r)},oODMH:t(1109),Ghrmn:t(1757),nVbzg:function(a,r){return a(r)},ndtbP:function(a,r){return a>>>r},VAsaG:function(a,r,o){return a(r,o)},nGpCT:function(a,r){return a(r)},QvuaI:function(a,r,o){return a(r,o)},RuvHe:t(1302)+t(1255)+t(1608)+"key",NJqyO:function(a,r){return a===r},bVCeE:t(1302)+t(1255)+t(1608)+t(992),VYMGT:function(a){return a()},omBuD:function(a,r,o){return a(r,o)},HEham:"xGUZw",vNyBi:function(a,r){return a!==r},rPQjk:function(a,r,o){return a(r,o)},DEOyh:function(a,r,o){return a(r,o)},dOIKy:function(a,r,o){return a(r,o)},IbQvN:function(a,r){return a!==r},HNYzC:function(a,r,o){return a(r,o)},BdYsq:function(a,r){return a(r)},TngGS:function(a,r){return a!==r},qDtPH:function(a,r){return a(r)},HKcAj:function(a,r){return a!==r},YJvhB:function(a,r,o){return a(r,o)},BxeHT:function(a,r,o){return a(r,o)},CHRLV:function(a,r,o){return a(r,o)},zMeTT:function(a,r,o){return a(r,o)},XMimX:function(a,r){return a!==r},YgfFF:function(a,r,o){return a(r,o)},wXxhS:function(a,r,o){return a(r,o)},MVdiq:function(a,r){return a!==r},DWqXn:function(a,r,o){return a(r,o)},gPAbG:function(a,r){return a!==r},foYzk:function(a,r){return a(r)},zLxWt:function(a,r){return a===r},WfZry:function(a,r){return a(r)},tHPfs:function(a,r){return a>>>r},Ohzde:function(a,r){return a(r)},ImcFa:function(a,r){return a(r)},jdmHv:function(a,r){return a(r)},cSVFq:function(a,r,o){return a(r,o)},CJDAG:function(a,r,o){return a(r,o)},LTVYm:t(1302)+t(1255)+t(1608)+t(719),YSsPz:function(a,r){return a===r},kChhX:t(1302)+"required"+t(1608)+t(681),pJkDe:t(1302)+t(1255)+t(1608)+t(850),Vvlgi:t(1302)+t(1255)+" field: method",jPnPJ:function(a,r){return a+r},qNNHC:function(a,r){return a(r)},OowYs:function(a,r,o){return a(r,o)},NkgLH:function(a,r){return a(r)},UQzFv:function(a,r,o){return a(r,o)},AWxnH:"Unimplem"+t(609)+t(1834),iawuV:function(a,r){return a>=r},ZLaVB:function(a,r,o){return a(r,o)},EJCce:function(a,r){return a&r},gPQPL:function(a,r){return a!==r},ePeuU:"JYICF",mpxLl:function(a,r){return a>>r},LMZFe:"Skip pas"+t(1128),sfhEi:function(a,r,o){return a(r,o)},HtBYH:t(1443),kONhp:function(a,r){return a*r},Ndglt:function(a,r){return a>r},NMGsD:function(a,r){return a>r},zzIGB:function(a,r){return a+r},ZRwUh:t(1839)+t(1128),HpFXk:function(a,r){return a+r},WXUla:"4|2|1|3|"+t(1792)+"|0|10|6|8",kIIxn:function(a,r){return a|r},vbQed:function(a,r){return a<r},DFrYk:function(a,r){return a<r},quAcU:function(a,r){return a>r},OjzzT:function(a,r){return a|r},BdwaW:t(518),fpswh:function(a,r,o){return a(r,o)},rfikX:function(a,r){return a<r},JaSUs:function(a,r){return a+r},zFehH:function(a,r){return a&r},DBEOL:function(a,r){return a===r},XiFyI:function(a,r){return a+r},wgFlq:function(a,r){return a+r},ekANU:function(a,r){return a&r},ikVMX:function(a,r){return a&r},pyzNs:function(a,r){return a+r},UHKQO:function(a,r){return a&r},zjrEF:function(a,r){return a&r},HDagi:function(a,r){return a<<r},sNcsR:function(a,r){return a<r},TEXDr:function(a,r){return a<=r},elrLd:t(732),VKLJG:t(987),VNHgN:function(a,r){return a==r},gBSSO:function(a,r){return a&r},Uwind:function(a,r){return a>=r},YatRx:function(a,r){return a+r},CeREw:function(a,r){return a+r},nVwcE:function(a,r){return a+r},podFu:function(a,r){return a!==r},oieMM:function(a,r){return a|r},yuEQI:function(a,r){return a<<r},RvPLV:function(a,r){return a<<r},FKfcn:function(a,r){return a|r},AzOvz:function(a,r){return a|r},thjdF:function(a,r){return a|r},NgxdA:function(a,r){return a<<r},WAMxH:function(a,r){return a&r},fJzrL:function(a,r,o){return a(r,o)},aYluJ:function(a,r){return a+r},iCswE:function(a,r){return a+r},HQIMY:function(a,r){return a<r},ZcuPG:function(a,r){return a<r},WPbcT:function(a,r,o){return a(r,o)},BjAeZ:function(a,r){return a<r},mEQqn:function(a,r){return a-r},ZCICd:function(a,r){return a<r},iYDIN:function(a,r){return a&r},uCJCM:function(a,r){return a|r},uwilz:function(a,r){return a>>r},qkSHA:function(a,r){return a&r},jSBWi:function(a,r){return a>>r},NPvtS:function(a,r){return a|r},PXDxZ:function(a,r,o){return a(r,o)},RwJxU:t(356),eZFpI:t(1809),McAuP:function(a,r,o){return a(r,o)},tdJnf:function(a,r){return a===r},JDvKA:"AoBDk",FtqBC:function(a,r,o){return a(r,o)},RmXkn:function(a,r){return a&r},VPOqa:function(a,r){return a<<r},MsmXi:function(a,r){return a<<r},tQLtB:function(a,r){return a(r)},eQIBt:function(a,r){return a&r},PCHfv:function(a,r){return a(r)},bJlVj:function(a,r){return a(r)},PsGNZ:function(a,r){return a<<r},gtVIr:function(a,r){return a&r},gtMOH:function(a,r){return a<<r},hMEvc:function(a,r){return a&r},dciVg:function(a,r){return a&r},uRvZW:function(a,r){return a>>>r},OoKzU:function(a,r){return a===r},bYYQd:function(a,r){return a===r},CtdgD:function(a,r,o){return a(r,o)},eoJqx:function(a,r){return a>>>r},dUPgQ:function(a,r){return a+r},EcCvi:function(a,r){return a&r},pcMzl:function(a,r){return a|r},vWooQ:function(a,r){return a>>>r},GHhvD:function(a,r){return a!==r},cceiE:function(a,r){return a|r},neOig:function(a,r){return a>>>r},YXYAJ:function(a,r){return a&r},AsqBL:function(a,r){return a>>>r},CJZOl:function(a,r){return a+r},Buvxe:function(a,r){return a>>>r},eHvcW:function(a,r){return a!==r},tVOYz:function(a,r){return a|r},TezYV:function(a,r){return a+r},oRsxp:function(a,r){return a!==r},aTOvA:function(a,r){return a|r},OEoXb:function(a,r){return a&r},XANMz:function(a,r){return a>>>r},ZxeJx:function(a,r){return a>>>r},lmjvu:function(a,r){return a!==r},efZAY:function(a,r){return a&r},tVGmy:function(a,r){return a(r)},fOvpy:function(a,r){return a(r)},UxDme:function(a,r){return a|r},gndKs:function(a,r){return a|r},sKsgg:t(960),qmHoS:"service",npbZg:t(1031)+t(763),CgoAl:t(763),xMlpc:"curvalue",NDMco:"MzLFA",xzfzp:t(1226),AcsCF:function(a,r){return a(r)},WJdte:t(885),xlEvc:function(a,r){return a<<r},crDtB:function(a,r){return a<<r},PLCHM:function(a,r){return a>r},PEkAb:t(1358),FaWNP:t(1715),qiFDX:function(a,r){return a|r},DTLsb:function(a,r){return a<<r},CnDsm:function(a,r){return a<<r},YnlBr:function(a,r){return a|r},PFkye:function(a,r){return a>>>r},IicTw:function(a,r){return a|r},oxUAe:function(a,r){return a<<r},pXxxM:function(a,r){return a<<r},GtqQG:function(a,r){return a&r},nGogU:function(a,r){return a&r},nRson:function(a,r){return a&r},amdpx:function(a,r){return a>>>r},FgDwN:function(a,r){return a>>>r},ktJEF:function(a,r){return a>=r},vLQzu:function(a,r){return a+r},jZJmf:function(a,r){return a|r},GzLCr:function(a,r){return a%r},JJouH:function(a,r){return a/r},uXdNf:function(a,r){return a+r},yVdoe:function(a,r){return a*r},UIKoY:function(a,r){return a>>>r},meHjF:function(a,r){return a+r},USgET:function(a,r){return a*r},DdBan:function(a,r){return a>>>r},WHpMC:function(a,r,o){return a(r,o)},yzQcg:function(a,r,o){return a(r,o)},XIstx:function(a,r){return a!==r},yTqOs:"bMJeq",qTsxy:function(a,r){return a===r},fpmsr:t(672),xIYtf:function(a,r){return a&r},WDwue:function(a,r){return a>>>r},xOGBp:function(a,r){return a&r},ikMEI:function(a,r){return a>>>r},JOsYJ:function(a,r){return a&r},adUia:function(a,r){return a+r},sLCGP:function(a,r){return a+r},AlpGx:function(a,r){return a|r},QJWXt:function(a,r){return a<<r},HrWTd:function(a,r){return a===r},dgKVQ:function(a,r){return a===r},vPxNf:function(a,r){return a===r},PhsxV:function(a,r){return a+r},JxetK:function(a,r){return a>>>r},wSrXY:function(a,r){return a>>>r},UXWWU:function(a,r){return a>>>r},mYBOM:function(a,r){return a&r},dKJls:function(a,r){return a&r},pvTux:function(a,r){return a>>>r},aLPIP:function(a,r){return a>>>r},VkLtT:function(a,r){return a&r},SOHQi:t(1233)+"RROR",HXMIj:t(731)+"NG_ERROR",jdsjS:t(557)+t(1328)+"R",YpSoU:t(1097)+t(1429),QORFU:t(388)+"OR",iCBon:t(1291),NkxLN:"KsAXY",enVWD:function(a,r){return a>r},AhqiG:function(a,r){return a+r},nwPLE:t(945),nooKa:t(1458),mVlLI:function(a,r){return a===r},eIVJo:t(522),Xcjco:function(a,r){return a||r},eNQwt:function(a,r){return a===r},HlOwW:t(507),UEFHT:function(a,r){return a===r},nOKTI:function(a,r){return a-r},zRDNG:function(a,r){return a===r},SsgkD:t(1055),hylXo:function(a,r){return a instanceof r},LhTtC:t(1406)+t(1762),KOxAQ:function(a,r){return a+r},UcVoX:function(a,r){return a+r},rpwJM:function(a,r){return a===r},EHIpH:function(a,r){return a<r},SbOSJ:t(759)+t(578)+t(1425)+"nitialized",GdSnE:function(a,r){return a!==r},BlsMM:"FsQVZ",WYwtk:t(1544),qRCIf:function(a,r){return a>r},SkLsR:t(963),DSSnX:function(a,r){return a&r},KldAs:function(a,r){return a>>>r},GJlyP:function(a,r){return a&r},xgvfr:t(770),xawUc:t(441),xfaFW:t(710),zfhQk:function(a,r,o){return a(r,o)},EkAMz:function(a,r){return a<r},qgsZf:function(a,r){return a&r},OcvBc:function(a,r,o){return a(r,o)},yFLHY:"reconnect",wzYGX:"stop immediately reconnect",rwiLT:t(381),apKep:function(a,r){return a||r},nvZbQ:t(702)+"d",DNjOz:"1|2|0|3|4",APQGj:function(a,r){return a||r},awpDm:function(a,r){return a!=r},pruYN:function(a,r){return a>r},iOXed:t(639)+t(1041)+"e",nIFbz:t(803)+"alled mu"+t(483)+t(525)+"process",UkPZP:function(a,r){return a===r},RJHsp:function(a,r){return a+r},hoJox:"rtYLQ",suULR:function(a,r){return a<r},sdbYl:function(a,r){return a===r},BAbqv:function(a,r){return a&r},ozYEW:function(a,r){return a===r},vzFll:function(a,r){return a&r},Iqaxl:function(a,r){return a<r},EbFFG:function(a,r){return a<=r},VzPdn:function(a,r){return a|r},MMgdD:function(a,r){return a&r},gCvHl:function(a,r){return a&r},tWaSN:function(a,r){return a>=r},KLXPW:function(a,r){return a|r},nJJkx:function(a,r){return a&r},yzIoX:function(a,r){return a&r},rxKRN:function(a,r){return a<<r},vTjSS:function(a,r){return a&r},OSRkD:function(a,r){return a>>r},FRYZU:function(a,r){return a<r},LrxSu:function(a,r){return a&r},nnySG:function(a,r){return a===r},MsIuQ:function(a,r){return a&r},GVsCo:function(a,r){return a|r},wPvnZ:function(a,r){return a&r},Fxzou:function(a,r){return a+r},FmfWP:function(a,r){return a|r},UkECg:function(a,r){return a>>r},MPXAA:function(a,r){return a&r},YOhuP:function(a,r){return a-r},dVHxb:function(a,r){return a(r)},uifcO:function(a,r,o,l){return a(r,o,l)},FJCTA:function(a,r){return a+r},MhuTb:t(1081),mGumF:t(990),fLXAr:"PiUWz",mAmZz:t(1181),HwKCA:t(747),vRnIi:function(a,r){return a instanceof r},KxDJk:function(a,r){return a!=r},gXWPk:"applicat"+t(742),THEKg:function(a,r){return a==r},hQHNs:t(1222)+t(1083)+"et=utf-8",bXYFo:t(1556),jNZpK:function(a,r){return a>=r},VewvM:function(a,r,o){return a(r,o)},IPlID:function(a,r,o){return a(r,o)},XDeww:t(601),mvLCp:function(a,r){return a===r},BQkze:t(991),fErpn:function(a,r){return a(r)},eXuIh:t(367),MKdNt:t(1385)+t(714),mFkVJ:function(a,r){return a+r},MLNCd:t(819)+t(1034),UoScX:"idb",VLbwk:t(1208),GKUyd:function(a){return a()},gpAry:function(a,r,o,l){return a(r,o,l)},EjEEw:function(a,r){return a>=r},ybGOE:"zfrFH",DUnps:"gBFdr",yWVWg:function(a,r){return a>=r},KBzQs:t(684),sIiBX:function(a,r){return a(r)},FAnsY:function(a,r){return a&r},iKXKv:function(a,r){return a+r},xBykd:function(a,r){return a||r},afjLp:function(a,r){return a>>>r},cLJoT:function(a,r){return a===r},BVyaF:t(1545),hGGNY:t(499),eAoIt:function(a,r){return a||r},XYwYV:function(a,r){return a||r},KZUPN:function(a,r){return a||r},ArZmM:function(a,r){return a||r},wTYeg:t(1136),xeAVg:function(a,r){return a(r)},bBBiq:function(a,r){return a===r},npAJu:t(1573),BXxTI:function(a,r){return a||r},BCHRl:function(a,r){return a!=r},fZwwP:t(902)+"DB failed",BQxQp:function(a,r,o){return a(r,o)},sXGNw:"qos",rWZKK:"message_id",FtDVJ:"x_frontier_qos",rXEld:function(a,r,o,l){return a(r,o,l)},GeheD:t(572)+"er_ack_m"+t(376),dUuHh:function(a,r,o,l){return a(r,o,l)},uSVXh:t(537),zmEvD:function(a,r){return a&&r},RcQzZ:t(1159),NRJVu:t(513),jXsdn:function(a,r){return a||r},SAIED:t(1018),EVSgE:function(a,r){return a(r)},sbYEv:function(a,r){return a(r)},ZbgFE:function(a,r){return a instanceof r},UZuCE:t(409)+t(742)+t(1023)+t(1112),oNbPF:t(984)+"e",blgkb:t(351),uJAhG:function(a,r){return a>r},WVVDC:function(a,r){return a(r)},UvxcO:function(a,r){return a+r},qaAcD:function(a,r){return a>>>r},raOsG:t(1550),SvxFo:t(1245),PgHyg:function(a,r){return a(r)},jEqcy:function(a,r){return a+r},CDZfS:function(a,r){return a+r},JwLwS:t(632),mGCim:t(392),UqYvW:function(a,r){return a+r},GWgaV:function(a,r){return a+r},JBKsp:function(a,r,o){return a(r,o)},nLFSj:function(a,r){return a>>>r},JeCPA:"2|3|4|1|0",MTchn:function(a,r){return a+r},wmNGY:function(a,r,o,l){return a(r,o,l)},kCEoZ:function(a,r){return a+r},vxeLE:function(a,r){return a|r},VDPLw:function(a,r){return a+r},ABhfW:function(a,r){return a<<r},TQels:function(a,r){return a+r},AMwfJ:function(a,r){return a<<r},wuxGu:function(a,r){return a+r},Ifrub:function(a,r){return a|r},WitJv:function(a,r){return a<<r},jYBSy:function(a,r){return a+r},AjMcr:function(a,r){return a+r},MKEid:function(a,r){return a>>>r},igkPe:function(a,r){return a&r},LROrK:function(a,r){return a&r},OxbOe:function(a,r){return a+r},tawrM:function(a,r){return a>>>r},PCcxx:function(a,r){return a&r},HHFiy:function(a,r){return a>>>r},yDnES:function(a,r){return a+r},KnDZJ:function(a,r){return a&r},MqRDo:function(a,r){return a&r},NrSsC:t(1493)+t(1359)+"|10|4|0|8",SPwXo:function(a,r,o,l){return a(r,o,l)},sGMtK:function(a,r){return a&r},ZMJLE:function(a,r){return a<r},lVIEq:function(a,r){return a|r},hIYZT:function(a,r){return a<r},iKvbc:function(a,r){return a<r},RvNWE:function(a,r){return a|r},ehynT:function(a,r){return a<r},oankD:function(a,r){return a-r},ZeboD:function(a,r){return a<r},TrvOT:t(616),krDBv:function(a,r){return a(r)},QaARt:function(a,r){return a+r},LQVqa:t(617)+t(972)+t(1198),PGRrF:t(1345)+"ervice",BsrRm:function(a,r,o,l){return a(r,o,l)},SoMSZ:"cursor_f"+t(993),qtnzv:function(a,r){return a<r},OcVIf:function(a,r,o,l){return a(r,o,l)},ewwWR:t(691)+"_EXIST",tTwsb:t(1685)+">",AlymX:function(a,r){return a===r},NQSMm:t(1225),oVOvV:"cursor_n"+t(524),XrFPY:t(1482)+t(1334),pxMbc:t(1704),fsFWd:"CONTINUE",CYTiD:function(a,r,o,l){return a(r,o,l)},lzyAy:function(a){return a()},hQanX:"setdb",nLMRd:function(a,r){return a instanceof r},wNGjt:t(355),XKowQ:function(a,r){return a===r},YQaxB:"store",puzUg:function(a,r){return a in r},Ehqfx:function(a,r){return a===r},ibnTl:"ZlPSv",QsCIq:t(1816)+"r",YOnPA:function(a,r){return a(r)},zqvfO:function(a,r){return a===r},COssf:t(1730),ATGjp:function(a,r){return a||r},bZXCJ:t(1303),IVpka:t(1207),MBalf:function(a,r,o,l){return a(r,o,l)},zqHpz:"code",OxLtV:function(a,r){return a(r)},wGNyo:function(a,r,o){return a(r,o)},grNkk:t(572)+t(1164),LPAlw:t(1525)+"s",EOqNn:function(a,r,o){return a(r,o)},doRii:"x-msg-cursor_name",jifTL:function(a,r){return a(r)},fbEKd:function(a,r,o){return a(r,o)},DvWGq:t(1446)+t(1799)+"ue",JvqVL:t(866),PgulW:function(a){return a()},FqoFp:function(a){return a()},aAEaR:function(a,r){return a===r},tqALP:function(a){return a()},yyNYE:function(a,r){return a!==r},xauqH:function(a,r){return a===r},nAfmS:t(1635),GIery:function(a,r,o){return a(r,o)},rZIpC:function(a){return a()},LkrJb:function(a){return a()},xgPcZ:"mLxuB",VqPmk:function(a,r){return a===r},tbJNh:t(1402),PmCcN:function(a,r){return a===r},nMDvk:t(918),FpxME:t(1780)+"e_success",uRpiV:t(568),dPXJo:function(a,r,o){return a(r,o)},Xtxga:function(a,r,o){return a(r,o)},vUYZU:function(a,r){return a+r},gUIBV:function(a,r){return a&r},wLwjJ:function(a,r){return a>>r},swSuF:"pbbp2",yRZTD:t(343)+"rovide v"+t(1335),BWzaq:function(a,r){return a(r)},RlJxl:t(343)+"rovide ws params"+t(1204)+t(1347)+"tructor "+t(1064)+t(912),xLhCK:function(a,r){return a+r},MUsgg:function(a,r){return a+r},JKLSg:function(a,r){return a<<r},ZcizB:function(a,r){return a>r},VtIib:function(a,r){return a!==r},Yqixz:t(750),YhMpz:function(a,r,o){return a(r,o)},mORDj:"online",NScyl:t(1760),pKqbl:t(538),fFunZ:"offline",YAkhZ:function(a,r){return a&r},NawJK:function(a,r){return a>>r},EmzGG:function(a,r){return a|r},yYyPa:function(a,r){return a&r},jOeZg:function(a,r){return a===r},eOJhQ:t(480),eZAcB:function(a,r){return a==r},GSMTv:t(407),FkKqC:t(821),TdfFV:t(1399),iQIwN:t(377)+"d",eTtpN:t(343)+t(1603)+t(718)+t(1379)+"r ttwID",GdJoe:t(459),sBLsf:t(545),LBGyi:"fws_1.0.0",Elrrv:t(925),CtGFe:function(a,r,o){return a(r,o)},jqlFk:function(a,r,o){return a(r,o)},moZXe:t(676),EdeYn:function(a,r){return a-r},RwbhO:function(a,r,o){return a(r,o)},rKPgu:function(a,r){return a===r},ILcpC:t(429),Efnox:function(a,r){return a(r)},DjMQd:function(a,r){return a(r)},VsUmi:function(a,r){return a*r},PMgjQ:function(a,r){return a-r},aRxDb:function(a,r){return a>r},TUTUz:function(a,r){return a!==r},aAooE:t(897),KnfhK:function(a,r,o){return a(r,o)},POFoW:function(a,r){return a(r)},FmKUh:function(a,r){return a===r},CzWzX:t(789),zbSEx:"ViSIi",cmkgL:"VqCwH",ZwVuG:t(1743)+"1",AtpdD:function(a,r){return a+r},dLkwZ:function(a,r){return a<<r},gwmcC:"HuRVH",hkptd:t(1398),rjyMl:t(1577),ATaWS:t(1269)+t(805)+t(620)+t(1665),fFwVb:t(729),QEBBA:t(698),qYPOl:t(1472)+t(1378),zHymw:t(759)+"s alread"+t(363),UgVSS:function(a,r){return a==r},qqlDR:t(343)+t(508)+" valid d"+t(1696)+"a must be a string or an"+t(1469)+t(1461),AFHbO:t(567),ykwUs:function(a,r){return a instanceof r},baFIg:function(a,r){return a instanceof r},uQMgx:function(a,r){return a(r)},msIJG:"please p"+t(508)+t(1189)+t(979),qKArO:function(a,r){return a instanceof r},DivVG:function(a,r){return a<r},YzrOw:t(488),rYflZ:function(a,r){return a==r},iaFCc:t(1138)+"econnect"+t(726),uaajb:t(1780)+t(1344)+"t",RSiXB:function(a,r){return a<r},pPgoZ:function(a,r){return a===r},rgUju:function(a,r){return a(r)},nYnrL:t(1228),DgPLQ:function(a,r){return a*r},JYuva:function(a,r){return a*r},lXRkY:function(a,r){return a!=r},UmjFY:t(764),ujaML:function(a,r){return a!=r},eqxIp:function(a,r){return a===r},iGoLt:function(a,r){return a!=r},QRpqu:t(1301),ryvwr:t(1733)+"dWorkerGlobalScope",tclOt:function(a,r){return a!=r},IQcHu:function(a,r){return a==r},pudhZ:function(a,r){return a!=r},GnSaF:function(a,r){return a===r},MmofA:t(1498)+t(547)+t(895),otdqw:function(a,r){return a!=r},deCno:function(a,r){return a!=r},kElUZ:t(414)+t(976)};Ft.r(Oe),Ft.d(Oe,{FWS:()=>wg,CustomErrorEvent:()=>sl,createCloseEvent:()=>wt,ReconnectEvent:()=>il,createErrorEvent:()=>lt,decodedFrame:()=>rn,createOpenEvent:()=>ul,CustomCloseEvent:()=>ol,createReconnectEvent:()=>xa,FrontierMessageEvent:()=>cl,encodeFrame:()=>Gt,createMessageEvent:()=>ll,OpenEvent:()=>dl,ErrorCode:()=>on,Event:()=>ir,MessageEvent:()=>al});let n="";function i(a=""){let r=t,o="02",l=""+Date.now(),f=n||(n=e[r(580)](h,a)),p=Math.random()[r(1229)](16)[r(1067)](-6);return e[r(1674)](e.EvsXd(e[r(1819)](o,l),f),p)}function s(){let a=t;return e.XzOiL(1e4*Date[a(412)](),Math[a(1032)](e[a(1774)](1e4,Math[a(384)]())))}function c(a){let r=t;return e[r(1674)](Array(8)[r(951)]("0"),parseInt(a,10).toString(2))[r(1067)](-8)}function d(a){let r=t;return e[r(1819)](e[r(580)](Array,4)[r(951)]("0"),e.cMaHk(parseInt,a,2)[r(1229)](16)).slice(-4)}function u(a){let r=t,o=a.split(/\./)[r(1766)](p=>c(p)),l=[];return l[0]=e[r(1480)](d,e[r(1674)](o[0],o[1])),l[1]=e.PeLHB(d,e[r(1372)](o[2],o[3])),[e[r(1206)],e[r(1206)],e[r(1206)],e[r(1206)],e[r(1206)],e[r(717)],l[0],l[1]][r(951)]("")}function h(a){let r=t,o=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(1664)](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 o?u(a):l?e[r(580)](x,a):e[r(1477)]}function x(a){let r=t,o="",l=[],f=0,p=0,w=!0,E=e[r(1206)];if(a[r(1173)]("::")>-1){let g=a.split("::");for(let L=0;L<g[r(559)];L++){let N=g[L];if(e[r(1560)](N.indexOf(":"),0)){let $=N.split(":");w&&(f=$[r(559)]),p+=$.length;for(let se=0;e[r(1505)](se,$[r(559)]);se++)if(e[r(503)](4,$[se][r(559)])){let re=E.substring(0,e.oRzqO(4,$[se].length)),ie=re[r(437)]($[se]);l[r(946)](ie)}else l[r(946)]($[se]);w=!1}else{if(N[r(559)]!==4){let $=E[r(1735)+"g"](0,4-N.length),se=$.concat(N);l[r(946)](se)}else l[r(946)](N);w&&(f+=1),p+=1,w=!1}}let C="";for(let L=0;e[r(1505)](L,e[r(596)](8,p));L++)C=C[r(437)](E);for(let L=0;e.gQzYL(L,l[r(559)]);L++)e[r(942)](L,f)&&(o=o[r(437)](C)),o=o[r(437)](l[L]);return o}if(e[r(1066)]!==e[r(1409)]){let g=a[r(1512)](":");for(let C=0;e[r(1505)](C,g[r(559)]);C++){let L=g[C];if(e[r(503)](4,g[C][r(559)]))if(e[r(942)](e[r(1457)],e[r(1837)]))this["currentE"+r(1183)+r(403)+"t"]=0;else{let N=E[r(1735)+"g"](0,e[r(596)](4,g[C][r(559)])),$=N[r(437)](L);o=o[r(437)]($)}else o=o[r(437)](L)}return o}else if(!this[r(654)+r(1811)]){let g=e.qGaZx[r(1512)]("|"),C=0;for(;;){switch(g[C++]){case"0":this[r(933)+r(953)]?.[r(958)+"pointConfig"]();continue;case"1":this[r(790)+r(494)]=!1;continue;case"2":this[r(1412)]=!0;continue;case"3":this[r(654)]();continue;case"4":this._pingLossCounter?.["resetCou"+r(491)]();continue}break}}}function m(a,r){let o=t,l=a[o(561)];e.dQvec(void 0,l)&&(e[o(968)](we,r,10),e[o(968)](U,r,l));let f=a[o(992)];e[o(503)](void 0,f)&&(e[o(973)](we,r,18),e.dklCm(U,r,f))}function _(a){let r=t,o={};e:for(;!e[r(1020)](K,a);)if(e[r(503)](e.oODMH,e[r(878)])){let l=e[r(1479)](me,a);switch(e[r(1044)](l,3)){case 0:break e;case 1:o.key=e.VAsaG(R,a,e[r(787)](me,a));break;case 2:o[r(992)]=e.cMaHk(R,a,me(a));break;default:e[r(920)](k,a,7&l)}}else{if(_0x5a3a4d=e.nxmLA(e.lXJVW(127,_0xbfff9e[_0xa3f7b]),0),e[r(476)](_0x18ae07[_0x53c5b8++],128))return{value:_0x243136?_0x214521:e.lyXZj(0,_0x45b615),offset:_0x2fad3b};if(_0x511567=e[r(890)](e[r(701)](_0x3610f4,e.HCCBd(e[r(1579)](127,_0x4d42b6[_0x4e8d75]),7)),0),e.Zqnev(_0x53f52a[_0x3b973b++],128))return{value:_0x1b8bb7?_0x1c1651:e.qeOVb(0,_0x133fad),offset:_0x1d0a9};if(_0x5138b6=e[r(890)](e.qeOVb(_0x2c3b65,e.msimk(127&_0x115b91[_0x341cbe],14)),0),e[r(1505)](_0x4f572b[_0x37cfe7++],128))return{value:_0x5a96c5?_0x2a7014:e[r(701)](0,_0x5153cd),offset:_0x25377c};if(_0x22a7d3=e[r(890)](_0x5c1b28|e[r(359)](e.tYciQ(127,_0x50e530[_0x4d0749]),21),0),e[r(1392)](_0x2b9844[_0x153d82++],128))return{value:_0x555579?_0x285348:e.qeOVb(0,_0x586995),offset:_0x9dc4f5};if(_0x524000=e[r(890)](_0x1afe29|e.vJsfn(15&_0x5c9614[_0x3d589d],28),0),e.Zqnev(_0xb66408[_0x2848fe++],128))return{value:_0x564129?_0x3d15f6:0|_0x355f73,offset:_0x2094b6};if(e[r(1560)](_0xba96a7+=5,_0x202872.length))throw _0x59cfc9=_0x54c503[r(559)],e.GEIZf(_0x4a47c7,_0x12b1b5,10,_0xf7e199[r(559)]);return{value:_0x2d2d4b?_0x199391:0|_0x12684e,offset:_0x2ff4f9}}if(e[r(942)](void 0,o[r(561)]))throw new Error(e.RuvHe);if(e.NJqyO(void 0,o.value))throw new Error(e[r(1305)]);return o}function S(a){let r=t,o=e[r(782)](D);return e[r(920)](y,a,o),B(o)}function y(a,r){let o=t,l={jXuJM:function(f,p,w){return e[G(1262)](f,p,w)},vVgNV:"close"};if(e.NJqyO(e[o(1185)],e.HEham)){let f=a.SeqID;e[o(368)](void 0,f)&&(e[o(898)](we,r,8),e[o(571)](mt,r,f));let p=a[o(681)];p!==void 0&&(we(r,16),e[o(854)](mt,r,p));let w=a[o(850)];e[o(503)](void 0,w)&&(we(r,24),e[o(973)](mt,r,e[o(1479)](P,w)));let E=a[o(1250)];e[o(621)](void 0,E)&&(e[o(1262)](we,r,32),e[o(1230)](mt,r,e[o(811)](P,E)));let g=a[o(856)];if(e.TngGS(void 0,g))for(let Me of g){e.dOIKy(we,r,42);let pe=D();e[o(854)](m,Me,pe),we(r,pe[o(400)]),e[o(968)](j,r,pe),e[o(1080)](O,pe)}let C=a[o(1728)+o(1238)];e[o(583)](void 0,C)&&(e[o(1289)](we,r,50),e[o(1324)](U,r,C));let L=a.payloadType;L!==void 0&&(e[o(920)](we,r,58),e.rPQjk(U,r,L));let N=a[o(1002)];e[o(368)](void 0,N)&&(e[o(571)](we,r,66),e[o(791)](we,r,N[o(559)]),e[o(1771)](ce,r,N));let $=a[o(733)];e[o(626)](void 0,$)&&(e[o(1317)](we,r,74),e[o(577)](U,r,$));let se=a[o(1802)+"ming"];se!==void 0&&(e[o(577)](we,r,82),e[o(1771)](U,r,se));let re=a[o(470)];e.MVdiq(void 0,re)&&(we(r,90),e[o(1221)](U,r,re));let ie=a[o(438)+"e"];e.gPAbG(void 0,ie)&&(e.cMaHk(we,r,96),e[o(1221)](mt,r,e[o(1456)](P,ie)))}else{let f=this[o(933)+o(953)]?.[o(1351)+"ntEndpoint"]();this[o(670)+"hCloseEv"+o(880)](l[o(615)](_0x5b53ae,l[o(1179)],{code:1006,reason:"connect "+f+(o(796)+o(1116)+o(835)+"ached"),wasClean:!0}))}}function v(a){return e[t(787)](I,F(a))}function I(a){let r=t,o={hraqJ:function(l,f){return l(f)}};if(e[r(1454)](r(1604),r(1789)))return _0x4c69a7(_0x1ca128[r(461)](XtnNVc[r(1673)](_0x24d1c4,this),_0x17e13c));{let l={};e:for(;!K(a);){let f=e.WfZry(me,a);switch(e.tHPfs(f,3)){case 0:break e;case 1:l[r(719)]=e[r(390)](At,a,!0);break;case 2:l[r(681)]=e[r(854)](At,a,!0);break;case 3:l[r(850)]=e.inytl(me,a);break;case 4:l[r(1250)]=e[r(1307)](me,a);break;case 5:{let p=e[r(582)](A,a);(l[r(856)]||(l[r(856)]=[]))[r(946)](e[r(943)](_,a)),a[r(400)]=p;break}case 6:l[r(1728)+"ncoding"]=e[r(1781)](R,a,e[r(943)](me,a));break;case 7:l["payloadT"+r(1342)]=e.DEOyh(R,a,e.sqcEO(me,a));break;case 8:l[r(1002)]=e[r(1324)](ae,a,e[r(1040)](me,a));break;case 9:l[r(733)]=e[r(1558)](R,a,e[r(1307)](me,a));break;case 10:l[r(1802)+r(892)]=e.CJDAG(R,a,e.sqcEO(me,a));break;case 11:l.msgID=e[r(898)](R,a,e.nVbzg(me,a));break;case 12:l.frameType=me(a);break;default:e.DWqXn(k,a,e[r(637)](7,f))}}if(e[r(1454)](void 0,l[r(719)]))throw new Error(e[r(1176)]);if(e.YSsPz(void 0,l.LogID))throw new Error(e[r(724)]);if(e[r(1454)](void 0,l[r(850)]))throw new Error(e[r(1100)]);if(e.zLxWt(void 0,l[r(1250)]))throw new Error(e[r(1593)]);return l}}function A(a){let r=t,o=me(a),l=a.limit;return a[r(400)]=e[r(1218)](a[r(824)],o),l}function k(a,r){let o=t;switch(r){case 0:for(;128&e[o(1835)](Q,a););break;case 2:e.OowYs(V,a,e[o(1524)](me,a));break;case 5:V(a,4);break;case 1:e.UQzFv(V,a,8);break;default:throw new Error(e[o(1218)](e[o(564)],r))}}function P(a){let r=t;if(e.gPQPL(e[r(1786)],r(477))){for(_0x538465>>>=0;e.iawuV(_0x1ff3e4,128);)e[r(1184)](_0x5d9cd6,_0x41b5cb,e[r(701)](e[r(1468)](127,_0x4d522c),128)),_0x57f100>>>=7;e[r(1324)](_0x4559be,_0xe78171,_0x3a057f)}else return a|=0,{low:a,high:e[r(844)](a,31),unsigned:a>=0}}let b=[];function D(){let a=t,r=b[a(1046)]();return r?(r[a(824)]=r.limit=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){b[t(946)](a)}function F(a){return{bytes:a,offset:0,limit:a.length}}function B(a){let r=t,o=a[r(1519)],l=a[r(400)];return o[r(559)]===l?o:o[r(1783)](0,l)}function V(a,r){let o=t;if(e[o(1560)](e[o(1819)](a[o(824)],r),a[o(400)]))throw new Error(e[o(1076)]);a.offset+=r}function K(a){let r=t;return e[r(1503)](a[r(824)],a.limit)}function te(a,r){let o=t,l=a[o(1519)],f=a.offset,p=a.limit,w=e.EvsXd(f,r);if(e[o(1560)](w,l[o(559)]))if(e.TngGS(o(1396),e[o(839)])){let E=new Uint8Array(e[o(1246)](2,w));E[o(1087)](l),a[o(1519)]=E}else e[o(791)](_0x26fa4d,_0x1ff5dc,18),e[o(1404)](_0x4159d2,_0xd3a124,_0x55d86a);return a.offset=w,e[o(1586)](w,p)&&(a[o(400)]=w),f}function Z(a,r){let o=t,l=a.offset;if(e[o(1211)](e[o(1205)](l,r),a.limit))throw new Error(e.ZRwUh);return a[o(824)]+=r,l}function ae(a,r){let o=t,l=e[o(898)](Z,a,r);return a[o(1519)][o(1783)](l,e[o(1275)](l,r))}function ce(a,r){let o=t,l=e[o(1221)](te,a,r[o(559)]);a.bytes[o(1087)](r,l)}function R(a,r){let o=t,l={xlAGQ:e[o(497)],PlYvP:function(f,p){return e[o(386)](f,p)},SDohP:function(f,p){return e[o(1439)](f,p)},IRzRF:function(f,p){return e[o(1044)](f,p)},vrYmM:function(f,p){return e[o(720)](f,p)},tcMLn:function(f,p){return e.vbQed(f,p)},wdpmP:function(f,p){return e[o(372)](f,p)},uliNu:function(f,p){return e.ndtbP(f,p)},hTCjh:function(f,p){return e[o(1247)](f,p)},XNkcF:function(f,p){return e[o(1439)](f,p)},XuzsV:function(f,p){return e.quAcU(f,p)},HMFgH:function(f,p,w,E){return e[o(964)](f,p,w,E)},jpMLg:function(f,p){return e[o(1424)](f,p)},NatdV:function(f,p){return e[o(590)](f,p)},dsmuM:function(f,p){return e.lXJVW(f,p)},btFwu:function(f,p){return e[o(1247)](f,p)},ZrCTb:function(f,p){return f|p},ZnFzY:function(f,p){return f|p}};if(e.YSsPz(e[o(1506)],"miJoI")){if(this._options["disableA"+o(669)+o(1592)]||this[o(790)+"osed"])return;this["_handleR"+o(528)]()}else{let f=e[o(1355)](Z,a,r),p=String[o(877)+o(1169)],w=a[o(1519)],E="\uFFFD",g="";for(let C=0;e[o(998)](C,r);C++){let L=w[e.JaSUs(C,f)],N,$,se,re;if(e[o(1499)](128,L)===0)g+=e[o(1480)](p,L);else if(e.DBEOL(224&L,192))e[o(1503)](e[o(350)](C,1),r)?g+=E:(N=w[e.wgFlq(e.XzOiL(C,f),1)],(192&N)!==128?g+=E:(re=e[o(701)](e[o(1689)](e[o(1729)](31,L),6),63&N),e[o(1392)](re,128)?g+=E:(g+=p(re),C++)));else if(e[o(1824)](240,L)==224)if(e[o(1804)](C,2)>=r)g+=E;else if(N=w[e[o(1205)](e.pyzNs(C,f),1)],$=w[e[o(1822)](C+f,2)],e[o(1423)](e[o(372)](N,$<<8),49344)!==32896)g+=E;else if(re=e[o(1439)](e[o(372)](e[o(1845)](15,L)<<12,e[o(1082)](e[o(1824)](63,N),6)),63&$),e[o(1702)](re,2048)||e.iawuV(re,55296)&&e.TEXDr(re,57343))g+=E;else if(e[o(1462)](e[o(1147)],e[o(1823)])){let ie=4294967295;return function(Me,pe,qt=!0){let _e=o,Ea=l.xlAGQ[_e(1512)]("|"),ni=0;for(;;){switch(Ea[ni++]){case"0":ie=l[_e(1108)](l[_e(1058)](ie,(15&Me[pe])<<28),0);continue;case"1":ie=l[_e(1478)](l.SDohP(ie,l.vrYmM(127,Me[pe])<<7),0);continue;case"2":if(l[_e(1569)](Me[pe++],128))return{value:qt?ie:l[_e(664)](0,ie),offset:pe};continue;case"3":if(l[_e(1569)](Me[pe++],128))return{value:qt?ie:0|ie,offset:pe};continue;case"4":ie=l[_e(622)](l[_e(1527)](127,Me[pe]),0);continue;case"5":if(l[_e(1484)](Me[pe++],128))return{value:qt?ie:l.XNkcF(0,ie),offset:pe};continue;case"6":if(l[_e(1316)](pe+=5,Me[_e(559)]))throw pe=Me[_e(559)],l[_e(1652)](_0x190b17,pe,10,Me[_e(559)]);continue;case"7":if(Me[pe++]<128)return{value:qt?ie:l[_e(781)](0,ie),offset:pe};continue;case"8":return{value:qt?ie:l[_e(431)](0,ie),offset:pe};case"9":ie=l[_e(1478)](l[_e(431)](ie,l[_e(1585)](l[_e(1397)](127,Me[pe]),14)),0);continue;case"10":if(l.btFwu(Me[pe++],128))return{value:qt?ie:l[_e(1415)](0,ie),offset:pe};continue;case"11":ie=l[_e(802)](ie,l.vrYmM(127,Me[pe])<<21)>>>0;continue}break}}}else g+=e.BdYsq(p,re),C+=2;else e[o(713)](e.gBSSO(248,L),240)?e[o(893)](e[o(473)](C,3),r)?g+=E:(N=w[e[o(809)](C,f)+1],$=w[e[o(1387)](e[o(527)](C,f),2)],se=w[e[o(809)](C,f)+3],e[o(874)]((e.oieMM(N,e[o(594)]($,8))|e[o(1738)](se,16))&12632256,8421504)?g+=E:(re=e[o(754)](e[o(1644)](e[o(909)]((7&L)<<18,e[o(502)](e.WAMxH(63,N),12)),e[o(502)](e.iQguh(63,$),6)),63&se),e[o(1702)](re,65536)||re>1114111?g+=E:(re-=65536,g+=e[o(994)](p,e[o(1844)](e.mpxLl(re,10),55296),e[o(1528)](e.gBSSO(1023,re),56320)),C+=3))):g+=E}return g}}function U(a,r){let o=t,l=r.length,f=0;for(let E=0;e[o(998)](E,l);E++){let g=r.charCodeAt(E);e[o(893)](g,55296)&&g<=56319&&e[o(1296)](e[o(1218)](E,1),l)&&(g=e[o(1528)](e.vJsfn(g,10),r[o(554)+"At"](++E))-56613888),f+=e[o(658)](g,128)?1:e[o(1148)](g,2048)?2:e[o(1296)](g,65536)?3:4}e.WPbcT(we,a,f);let p=e[o(1289)](te,a,f),w=a[o(1519)];for(let E=0;e[o(476)](E,l);E++){let g=r[o(554)+"At"](E);g>=55296&&e.TEXDr(g,56319)&&e[o(899)](e.HpFXk(E,1),l)&&(g=e[o(1500)](e.pyzNs(g<<10,r[o(554)+"At"](++E)),56613888)),e[o(1015)](g,128)?w[p++]=g:(e[o(658)](g,2048)?w[p++]=e.OjzzT(e[o(785)](e[o(844)](g,6),31),192):(e[o(1702)](g,65536)?w[p++]=e[o(752)](e.iQguh(e.uwilz(g,12),15),224):(w[p++]=e[o(1439)](e[o(1729)](e[o(844)](g,18),7),240),w[p++]=e.OjzzT(e[o(1491)](g>>12,63),128)),w[p++]=e[o(909)](e[o(1499)](e[o(1813)](g,6),63),128)),w[p++]=e[o(1268)](63&g,128))}}function j(a,r){let o=t,l=e.PXDxZ(te,a,r.limit),f=a[o(1519)],p=r.bytes;for(let w=0,E=r[o(400)];e[o(1148)](w,E);w++)f[e[o(1674)](w,l)]=p[w]}function Q(a){let r=t,o={ABohK:function(l,f){return e[G(1040)](l,f)},xyGKi:function(l,f){return e[G(1674)](l,f)}};if(e[r(1706)](e[r(1708)],e[r(1572)]))return a[r(1519)][e.McAuP(Z,a,1)];{let f=""+_0x4c3ed2[r(412)](),p=_0x43470c||(_0x28f212=gfdOhS[r(997)](_0x3a3754,_0x532976)),w=_0x27999d[r(384)]()[r(1229)](16)[r(1067)](-6);return gfdOhS[r(574)](gfdOhS[r(574)]("02",f)+p,w)}}function nt(a,r){let o=t,l={dpGDV:function(f,p,w){return e[G(1611)](f,p,w)},XYEgA:o(439)+"ame"};if(e[o(456)](e[o(837)],e[o(837)])){let f=e[o(917)](te,a,1);a[o(1519)][f]=r}else this[o(401)+o(1555)]=_0x52c0d8,this[o(607)+o(1767)]=_0x51b88c,this[o(426)+o(1455)]=_0x13186c,this[o(1418)]=l[o(1666)](_0x1b2650,this[o(401)+"ameSpace"],l[o(1846)])}function me(a){let r=t,o=0,l=0,f;do f=Q(a),e.DFrYk(o,32)&&(l|=e.vJsfn(e.RmXkn(127,f),o)),o+=7;while(e[r(1637)](128,f));return l}function we(a,r){let o=t;for(r>>>=0;e.iawuV(r,128);)e[o(917)](nt,a,e[o(924)](e[o(1729)](127,r),128)),r>>>=7;e[o(994)](nt,a,r)}function At(a,r){let o=t,l=0,f=0,p=0,w;return w=Q(a),l=e[o(1703)](127,w),e.ekANU(128,w)&&(w=e[o(1480)](Q,a),l|=e[o(1660)](127&w,7),128&w&&(w=e[o(1479)](Q,a),l|=e.MsmXi(127&w,14),e.lXJVW(128,w)&&(w=e[o(446)](Q,a),l|=e[o(1071)](127,w)<<21,128&w&&(w=e[o(706)](Q,a),f=e[o(1637)](127,w),e[o(1468)](128,w)&&(w=e[o(1835)](Q,a),f|=e[o(1738)](127&w,7),e[o(1703)](128,w)&&(w=e.bJlVj(Q,a),f|=e.PsGNZ(e[o(1167)](127,w),14),e[o(1130)](128,w)&&(w=e.WfZry(Q,a),f|=e[o(1681)](e[o(490)](127,w),21),e[o(1475)](128,w)&&(w=e[o(1510)](Q,a),p=e.gBSSO(127,w),128&w&&(w=Q(a),p|=e[o(1738)](e.hMEvc(127,w),7)))))))))),{low:e.FKfcn(l,f<<28),high:e[o(924)](f>>>4,p<<24),unsigned:r}}function mt(a,r){let o=t,l=e.nxmLA(r[o(395)],0),f=e[o(1644)](e.ndtbP(r[o(395)],28),r[o(1613)]<<4)>>>0,p=e.uRvZW(r[o(1613)],24),w=e[o(1487)](0,p)?e[o(606)](0,f)?l<16384?e[o(1296)](l,128)?1:2:e.vbQed(l,2097152)?3:4:f<16384?e.ZCICd(f,128)?5:6:f<2097152?7:8:e.ZCICd(p,128)?9:10,E=e[o(1629)](te,a,w),g=a[o(1519)];switch(w){case 10:g[e.XiFyI(E,9)]=e[o(1130)](e.eoJqx(p,7),1);case 9:g[e[o(1201)](E,8)]=e.TngGS(9,w)?e[o(1424)](128,p):e[o(1285)](127,p);case 8:g[e.iCswE(E,7)]=e[o(368)](8,w)?e[o(482)](e[o(1806)](f,21),128):f>>>21&127;case 7:g[E+6]=e[o(1437)](7,w)?e[o(1647)](e[o(870)](f,14),128):e[o(1186)](e.AsqBL(f,14),127);case 6:g[e.CJZOl(E,5)]=w!==6?e.thjdF(e[o(386)](f,7),128):e[o(1741)](f,7)&127;case 5:g[E+4]=e[o(1490)](5,w)?e.tVOYz(128,f):e.EJCce(127,f);case 4:g[e[o(527)](E,3)]=e[o(626)](4,w)?e[o(1424)](e[o(1044)](l,21),128):e[o(637)](e[o(380)](l,21),127);case 3:g[e[o(1827)](E,2)]=e[o(913)](3,w)?e[o(1349)](l>>>14,128):e[o(1441)](e.XANMz(l,14),127);case 2:g[e[o(527)](E,1)]=e[o(368)](2,w)?e[o(1810)](l,7)|128:l>>>7&127;case 1:g[E]=e[o(851)](1,w)?128|l:e.efZAY(127,l)}}function rn(a){return e[t(739)](v,a)}function Gt(a){return e[t(831)](S,a)}let sn=65536,Qr=e[t(1113)],Ee=e[t(772)](sn,sn),Ce=e[t(424)](Ee,Ee),rr=Ce/2,Ne=String[t(1042)+"e"][t(554)+"At"];class xe{constructor(r,o,l){let f=t;this[f(1719)]=!0,this[f(395)]=e[f(1687)](0,r),this[f(1613)]=e.gndKs(0,o),this.unsigned=!!l}static[t(1719)](r){let o=t;return r&&e[o(1492)](!0,r[o(1719)])}static[t(1088)](r,o,l){let f=t;if(e[f(1283)](e.sKsgg,f(1276)))return new xe(r,o,l);{let p=_0x39a558.substring(0,e.mEQqn(4,_0x1d1f07[_0x546af9].length)),w=p[f(437)](_0x184664);_0x151263=_0x182e7e.concat(w)}}static fromBytes(r,o,l){let f=t,p={SDBPw:f(1345)+f(979),TnCJU:function(w,E,g,C){return w(E,g,C)},JEHRF:function(w,E,g,C){return w(E,g,C)},pvfzQ:e.qmHoS,fOvfn:function(w,E,g,C){return e[f(964)](w,E,g,C)},eMqpn:e[f(1157)],tBcch:e.CgoAl,yisdZ:e[f(1537)],JEnfR:function(w,E){return e[f(1479)](w,E)}};if(e.tdJnf(e[f(610)],e[f(1793)])){let[w,E]=p[f(1546)](_0xf85039,_0x352c24),g=_0x5c6050(w),C=0;return _0x4303c9[f(981)](L=>{let N=f;_0x3b0daf[N(1563)](p.SDBPw,L,L.service),C=p[N(1140)](_0x518f10,0,g,C),_0x5e0f52[N(1563)](N(1566),C),C=p.JEHRF(_0x48b1c8,g,C,L[N(850)]||0),_0x34c61b[N(1563)](p[N(842)],C),C=p[N(1243)](_0x3a939d,E[L[N(439)+"ame"]],g,C),_0x5e0db9[N(1563)](p.eMqpn,C),C=_0xe8612d(L[N(439)+"ame"],g,C),_0x2563de[N(1563)](p[N(656)],C),C=p[N(1140)](_0x2f3dc6,_0x11c1d2[N(861)+"er"](L.cursor||_0x3d5deb),g,C),_0x9498bd[N(1563)](p[N(1377)],C)}),{frameType:_0x1d9e1a,headers:[{key:f(489)+f(993),value:_0x27549e}],payload:g}}else return l?xe[f(1217)+f(509)](r,o):xe["fromByte"+f(1273)](r,o)}static fromBytesLE(r,o){let l=t;if(e[l(1492)](e.WJdte,"VXDYT"))return new xe(e[l(1647)](e.thjdF(r[0]|r[1]<<8,e.VPOqa(r[2],16)),e[l(1011)](r[3],24)),e.thjdF(r[4]|e[l(1677)](r[5],8)|e[l(1681)](r[6],16),e[l(1677)](r[7],24)),o);e[l(492)](_0xb75c51,this[l(1065)+l(569)+"Id"]),this["_interva"+l(569)+"Id"]=e[l(1355)](_0x5b0b8a,()=>{this[l(1427)+"ired"]()},this._interval)}static[t(1217)+t(1273)](r,o){let l=t;if(e.lmjvu(e[l(1360)],e.FaWNP))return new xe(e.tVOYz(e.qiFDX(e[l(1424)](r[4]<<24,e.DTLsb(r[5],16)),r[6]<<8),r[7]),e[l(924)](e[l(752)](e[l(865)](r[0],24)|e.xlEvc(r[1],16),e.CnDsm(r[2],8)),r[3]),o);if(e[l(1842)](_0x11d4b3[l(824)]+_0x1945c5,_0x29a012[l(400)]))throw new _0x206702(e.LMZFe);_0xf7a442[l(824)]+=_0x2ee697}static[t(1417)](r){let o=t;return e[o(456)](r,Qr)?rl:new xe(e[o(386)](e.YnlBr(Ne[o(1253)](r,0),e[o(1082)](Ne.call(r,1),8))|Ne[o(1253)](r,2)<<16|e.MsmXi(Ne.call(r,3),24),0),e[o(1669)](e[o(1717)](e[o(924)](Ne.call(r,4),e.oxUAe(Ne[o(1253)](r,5),8)),e[o(1354)](Ne[o(1253)](r,6),16))|Ne[o(1253)](r,7)<<24,0),!0)}toHash(){let r=t;return String.fromCharCode(e[r(1130)](255,this[r(395)]),e[r(1778)](e[r(1669)](this[r(395)],8),255),e.nGogU(this[r(395)]>>>16,255),e[r(1810)](this[r(395)],24),e.nRson(255,this.high),e.GtqQG(this[r(1613)]>>>8,255),e[r(1285)](e.amdpx(this[r(1613)],16),255),e.FgDwN(this[r(1613)],24))}static fromNumber(r,o=!0){let l=t;if(e[l(787)](isNaN,r))return o?Dp:rl;if(o){if(r>=Ce)return Pp}else{if(e[l(1194)](r,-rr))return Op;if(e[l(712)](e[l(449)](r,1),rr))return Rp}return xe[l(1088)](e[l(961)](e.GzLCr(r,Ee),0),e[l(482)](e[l(737)](r,Ee),0),o)}toNumber(){let r=t;return this[r(1770)]?e[r(1841)](e[r(857)](e.neOig(this.high,0),Ee),e[r(468)](this[r(395)],0)):e[r(1156)](e.USgET(this[r(1613)],Ee),e.DdBan(this[r(395)],0))}[t(1745)](){let r=t;if(e[r(344)](e[r(860)],r(645)))return e.qTsxy(0,this.high)&&e[r(1492)](0,this.low);e.WHpMC(_0x55c317,_0x5b8d1c,24),e[r(1332)](_0x826c7a,_0x52ed3e,e.PeLHB(_0x5818be,_0x5aea13))}[t(435)](r){let o=t;if(e[o(851)](e[o(1758)],e[o(1758)]))this[o(848)+"rs"]={};else{xe.isLong(r)||(r=xe[o(861)+"er"](r));let l=e.uRvZW(this.high,16),f=e[o(1825)](65535,this.high),p=e[o(1643)](this.low,16),w=e[o(1313)](65535,this.low),E=e[o(1669)](r[o(1613)],16),g=65535&r[o(1613)],C=e[o(1236)](r.low,16),L=e[o(1648)](65535,r[o(395)]),N=0,$=0,se=0,re=0;return re+=e[o(444)](w,L),se+=e[o(1610)](re,16),re&=65535,se+=e[o(1658)](p,C),$+=e.neOig(se,16),se&=65535,$+=f+g,N+=$>>>16,$&=65535,N+=e[o(1844)](l,E),N&=65535,xe.fromBits(e[o(1649)](se<<16,re),e[o(1584)](e.QJWXt(N,16),$),this[o(1770)])}}[t(1614)](r){let o=t;return xe.isLong(r)||(r=xe.fromNumber(r)),this[o(1770)]!==r[o(1770)]&&e[o(1462)](this.high>>>31,1)&&e[o(1462)](r.high>>>31,1)?!1:e[o(942)](this[o(1613)],r[o(1613)])&&e.HrWTd(this[o(395)],r[o(395)])}[t(1364)](){let r=t;return e[r(1794)](-1,this[r(395)])&&e[r(914)](-1,this[r(1613)])?xe[r(1088)](0,0,this.unsigned):this[r(395)]===-1?xe[r(1088)](0,this[r(1613)]+1,this.unsigned):xe[r(1088)](e[r(671)](this[r(395)],1),this[r(1613)],this[r(1770)])}[t(755)](r){return r?this.toBytesLE():this[t(1341)+"E"]()}toBytesLE(){let r=t,o=this[r(1613)],l=this[r(395)];return[e[r(1579)](255,l),e[r(1579)](e[r(1202)](l,8),255),e[r(1845)](e[r(1710)](l,16),255),e.JxetK(l,24),255&o,e.eQIBt(e[r(890)](o,8),255),o>>>16&255,o>>>24]}[t(1341)+"E"](){let r=t,o=this.high,l=this[r(395)];return[e[r(1741)](o,24),e[r(1491)](o>>>16,255),e[r(1630)](o,8)&255,e[r(666)](255,o),l>>>24,e[r(1024)](e[r(510)](l,16),255),e[r(1312)](l,8)&255,e.VkLtT(255,l)]}}let rl=new xe(0,0,!1),Dp=new xe(0,0,!0),Rp=xe[t(1088)](-1,2147483647,!1),Pp=xe[t(1088)](-1,-1,!0),Op=xe.fromBits(0,-2147483648,!1);var on=(function(a){let r=t;return a[a[e[r(697)]]=5001]=e.SOHQi,a[a[e[r(535)]]=5002]=e[r(535)],a[a[e[r(1817)]]=5003]=e[r(1817)],a[a[e[r(934)]]=5004]=r(1097)+r(1429),a[a[e[r(704)]]=5005]=e.QORFU,a})({});class ir{constructor(r){let o=t;if(e[o(583)](e[o(1645)],e[o(565)]))this[o(1059)]=r,this[o(1547)]=null;else return 0}}class il extends ir{constructor(r,o){let l=t;super(r),this[l(770)]=o&&o[l(770)]||null}}class sl extends ir{constructor(r,o){let l=t,f=(l(816)+l(546))[l(1512)]("|"),p=0;for(;;){switch(f[p++]){case"0":this.lineno=o&&o[l(1549)]||0;continue;case"1":this.message=o&&o.message||"";continue;case"2":super(r);continue;case"3":this[l(1158)]=o&&o[l(1158)]||0;continue;case"4":this[l(1471)]=o&&o.filename||"";continue;case"5":this[l(1055)]=o&&o[l(1055)]||null;continue;case"6":this.code=o&&o[l(1143)]||5001;continue}break}}}class ol extends ir{constructor(r,o){let l=t,f=(l(585)+"2")[l(1512)]("|"),p=0;for(;;){switch(f[p++]){case"0":this[l(1143)]=o&&o[l(1143)]||0;continue;case"1":this[l(941)]=o&&o[l(941)]||!1;continue;case"2":this[l(827)+l(1684)]=o&&o[l(827)+l(1684)]||!1;continue;case"3":this.reason=o&&o[l(1034)]||"";continue;case"4":super(r);continue}break}}}class al extends ir{constructor(r,o){let l=t;super(r),this.data=o&&o[l(1014)]||null}}class cl extends al{constructor(r,o){let l=t;if(e[l(1492)](e[l(555)],e[l(555)]))super(r),this.data=o&&o[l(1014)]||null,this[l(770)]=o&&o[l(770)]||null;else{let f=_0x3ca88f[l(824)];if(e[l(823)](e[l(1435)](f,_0x25394f),_0x203124[l(400)]))throw new _0x2e873c(e[l(1650)]);return _0x1e3527[l(824)]+=_0x46e86d,f}}}class dl extends ir{constructor(r,o){let l=t;super(r),this[l(1014)]=o&&o[l(1014)]||null}}function lt(a,{message:r,code:o,error:l}){return new sl(a,{message:r,code:o,error:l})}function wt(a,{code:r,reason:o,wasClean:l,willReconnect:f}){return new ol(a,{code:r,reason:o,wasClean:l,willReconnect:f})}function ll(a,{data:r,message:o}){return new cl(a,{data:r,message:o})}function ul(a,{data:r}){return new dl(a,{data:r})}function xa(a,{message:r}){let o=t,l={VFcag:function(f,p,w){return e[G(791)](f,p,w)},QkDGn:"error",czDmQ:function(f,p,w){return e[G(1355)](f,p,w)},HRneR:e.nooKa};if(e.mVlLI(e.eIVJo,o(1725))){let f=l.VFcag(_0x555a21,l[o(723)],{message:this["_formatE"+o(1442)+o(1182)](_0x163c98)});this[o(478)](o(1055),f);let p=l[o(1700)](_0x571013,l.HRneR,{reason:this[o(1162)+o(1442)+o(1182)](_0x455363)});this[o(478)](l[o(442)],p)}else return new il(a,{message:r})}class fl{constructor(r,o){let l=t;this.endpoints=r,this.maxRetries=o,this[l(1315)+"ndex"]=0,this[l(799)+l(1183)+l(403)+"t"]=0}[t(958)+t(894)+t(922)](){let r=t;this[r(1315)+r(674)]=0,this[r(799)+"ndpointTriesCount"]=0}[t(1056)+"es"](){let r=t;this[r(799)+r(1183)+"riesCount"]=0}[t(1351)+t(743)+"nt"](){let r=t;if(e[r(1350)](e[r(1432)],e[r(1432)]))return this[r(563)+"s"][this[r(1315)+r(674)]];{let o=this._qosDB[r(1282)+r(1651)](this._prefix),l=_0x46ffcf[r(1039)](e[r(366)](o,"{}"));return l[_0x4ad3bc]=void 0,this[r(1418)][r(1531)+r(1651)](this._prefix,_0x70dde2.stringify(l))}}[t(1351)+t(743)+"ntTriesC"+t(1029)](){let r=t;return this[r(799)+r(1183)+"riesCount"]}[t(748)+"chMaxTries"](){let r=t;return!!(this[r(1315)+r(674)]>=this.endpoints[r(559)]||e[r(1178)](this[r(1315)+"ndex"],e[r(1356)](this[r(563)+"s"][r(559)],1))&&e[r(531)](this[r(799)+r(1183)+r(403)+"t"],this.maxRetries))}[t(1407)+t(644)+t(1465)+t(1366)+"tries"](){let r=t;return e.VNHgN(this.currentIndex,this[r(563)+"s"][r(559)])?!0:e[r(1842)](this[r(799)+"ndpointTriesCount"],this[r(1070)+"es"])}[t(1239)+t(1564)+t(775)+t(1600)+t(1190)](){let r=t;return this[r(799)+r(1183)+r(403)+"t"]=1,this["currentI"+r(674)]++,this.endpoints[this[r(1315)+r(674)]]}[t(1351)+t(743)+t(1150)+t(1538)](){let r=t;return this[r(799)+"ndpointT"+r(403)+"t"]++,this.getCurrentEndpoint()}}let sr=(e[t(955)](e.nvZbQ,typeof globalThis)&&e[t(526)](e[t(1431)],globalThis[t(1421)+t(677)][t(763)])||e[t(354)](e.nvZbQ,typeof window)&&e.eqxIp(e[t(1431)],window[t(1421)+t(677)][t(763)]))&&e[t(1486)](e[t(1261)],typeof document),On=t(702)+"d"!=typeof globalThis&&(e.QRpqu===globalThis[t(1421)+"tor"][t(763)]||e[t(1454)](e.ryvwr,globalThis[t(1421)+t(677)][t(763)]))&&e[t(1261)]!=typeof tt,ei=(e.tclOt(e.nvZbQ,typeof globalThis)&&e.UkPZP(t(1301),globalThis[t(1421)+t(677)][t(763)])||e.IQcHu(t(702)+"d",typeof globalThis)||e[t(1057)](e[t(1261)],typeof globalThis)&&!!globalThis[t(469)+t(1075)])&&e[t(1693)](t(702)+"d",typeof wx),ti=e[t(955)](t(702)+"d",typeof globalThis)&&(e[t(595)](e.ryvwr,globalThis[t(1421)+t(677)].name)||e[t(915)]===globalThis[t(1421)+"tor"][t(763)]||e.nnySG(t(1753)+t(1539)+t(506),globalThis[t(1421)+t(677)][t(763)]))&&e.otdqw(t(702)+"d",typeof self),Lp=e.KxDJk(t(702)+"d",typeof globalThis)&&e[t(1654)]===globalThis[t(1421)+t(677)].name&&e[t(504)](e[t(1261)],typeof global)&&e.eNQwt(t(1301),global[t(1421)+t(677)][t(763)])&&e[t(1122)](e[t(1261)],typeof process)&&!!process[t(1561)];class pa{constructor(){let r=t;this[r(848)+"rs"]={}}[t(478)](r,...o){let l=t,f=this._listeners[r];if(f)f[l(1067)]().forEach(p=>p.fn[l(461)](p[l(1449)],o));else if(e[l(1492)](e[l(1791)],r)&&!this[l(387)]){let p=o[l(559)]&&o[0];if(e.hylXo(p,Error))throw p;let w=new Error(e[l(1739)]+(p?e[l(500)](e[l(1376)](" (",p.message),")"):""));throw w[l(1416)]=p,p}return this}[t(1290)](r,o){let l=t;if(r===void 0)this[l(848)+"rs"]={};else if(e[l(1481)](void 0,o))this[l(848)+"rs"][r]=null;else{let f=this[l(848)+"rs"][r];if(f)for(let p=0;e[l(1050)](p,f[l(559)]);)e[l(1492)](f[p].fn,o)?f[l(570)](p,1):++p}return this}on(r,o,l){let f=t;if(e[f(1265)](e[f(1193)],e.WYwtk))return(this[f(848)+"rs"][r]||(this[f(848)+"rs"][r]=[]))[f(946)]({fn:o,ctx:l||this}),this;{let p=(f(550)+f(496))[f(1512)]("|"),w=0;for(;;){switch(p[w++]){case"0":this[f(1045)+f(544)]?.[f(642)]();continue;case"1":this[f(790)+f(494)]=!0;continue;case"2":if(e[f(456)](this._ws[f(1473)+"te"],this[f(1671)])||e.OoKzU(this[f(1694)][f(1473)+"te"],this[f(1152)]))return void this[f(1365)](f(759)+f(688)+f(363));continue;case"3":this["_clearTi"+f(1309)]();continue;case"4":this._clearPingTimer();continue;case"5":if(!this[f(1694)])return void this[f(1365)](e[f(599)]);continue;case"6":this["_dropGlo"+f(1756)+"Listener"]();continue;case"7":this[f(432)+f(421)+"t"](_0xc39fe9,_0x4c694a);continue}break}}}}class Np extends pa{[t(1162)+"rrorMess"+t(1182)](r){let o=t;return r.errMsg||r.errNo?("message: "+(r[o(1331)]||"")+o(696)+(r[o(1001)]||""))[o(965)]():JSON.stringify(r)}constructor(r,o,l){let f=t;super(),this[f(440)]=null,ei&&wx[f(451)+f(1734)]&&(this[f(440)]=wx[f(451)+f(1734)]({url:r,protocols:o,header:l,fail:this["_createS"+f(1063)+f(794)][f(1785)](this),success:this["_createSocketSuc"+f(996)+"ler"][f(1785)](this)})),On&&tt[f(451)+f(1734)]&&(this[f(440)]=tt[f(451)+f(1734)]({url:r,protocols:o,header:l,fail:this[f(573)+f(1063)+f(794)][f(1785)](this),success:this[f(573)+f(1830)+f(996)+f(1751)][f(1785)](this)}))}[t(573)+t(1830)+t(996)+t(1751)](){let r=t;Promise[r(566)]()[r(859)](()=>{this[r(1060)+"steners"]()})}[t(573)+"ocketFai"+t(794)](r){let o=t;Promise[o(566)]()[o(859)](()=>{let l=o,f=lt(e[l(1791)],{message:this[l(1162)+l(1442)+l(1182)](r)});this.emit(e[l(1791)],f);let p=e.DEOyh(wt,e[l(869)],{reason:this[l(1162)+l(1442)+l(1182)](r)});this[l(478)](e[l(869)],p)})}["_addWsLi"+t(1028)](){let r=t,o={pSpgb:function(l,f){return e[G(671)](l,f)},cZCsK:function(l,f){return e[G(1560)](l,f)},CDrRF:function(l,f){return e[G(1774)](l,f)},yzOFw:function(l,f){return e[G(447)](l,f)},lGyeo:e[r(1574)],tSPYD:function(l,f,p){return e.QvuaI(l,f,p)},dplRu:function(l,f,p){return l(f,p)},EXrtm:function(l,f){return e[r(1079)](l,f)},FzvLP:function(l,f){return l>>>f},Mtuxn:function(l,f){return e[r(1120)](l,f)},hKyoI:function(l,f){return l&f},FDdli:function(l,f){return e.KldAs(l,f)},BUpvu:function(l,f){return e[r(1532)](l,f)},VDiHC:function(l,f){return e[r(1454)](l,f)},TsRYQ:r(745),KWKRW:e[r(396)],KHXSU:e.SsgkD,aUxit:function(l,f,p){return l(f,p)}};if(e[r(832)]===e[r(975)]){let l=_0x46f498[r(1519)],f=_0x4a11a0[r(824)],p=_0x41211d[r(400)],w=BaFYyT.pSpgb(f,_0x54c56e);if(BaFYyT[r(1436)](w,l[r(559)])){let E=new _0x5d20da(BaFYyT[r(1367)](2,w));E[r(1087)](l),_0x392509.bytes=E}return _0x47dd5f[r(824)]=w,BaFYyT[r(1502)](w,p)&&(_0x3e583a[r(400)]=w),f}else this[r(440)][r(1062)](l=>{let f=r;this[f(478)](o[f(1414)],o[f(1223)](ul,f(963),{...l,data:l[f(1331)]||""}))}),this[r(440)].onClose(l=>{let f=r;this.emit(f(1458),o[f(888)](wt,f(1458),{...l}))}),this[r(440)][r(808)+"e"](l=>{let f=r;if(o[f(1732)](o.TsRYQ,o[f(1655)]))this[f(478)](o.KWKRW,o.tSPYD(ll,o[f(636)],{...l}));else{let p=this[f(1613)],w=this.low;return[BaFYyT.EXrtm(p,24),BaFYyT[f(1352)](p,16)&255,BaFYyT[f(1724)](p>>>8,255),255&p,BaFYyT[f(810)](w,24),BaFYyT[f(882)](w>>>16,255),BaFYyT[f(882)](BaFYyT[f(1395)](w,8),255),BaFYyT.BUpvu(255,w)]}}),this[r(440)][r(1052)](l=>{let f=r;this[f(478)](o[f(1033)],o[f(910)](lt,o[f(1033)],{...l,message:l[f(1331)]||""}))})}send(r){let o=t,l={mjakh:"culVg",gyZeO:e.SsgkD,XDmUe:function(f,p,w){return e[G(849)](f,p,w)},kDEeQ:function(f,p){return e[G(1755)](f,p)},Nqooe:function(f,p){return e[G(658)](f,p)},CIhQm:function(f,p){return e.qgsZf(f,p)},ApKfN:function(f,p){return e[G(1156)](f,p)},SyDaj:function(f,p){return f!==p},EVBow:o(495),RVGti:function(f,p,w){return e[o(1340)](f,p,w)}};if(e[o(675)](r,Uint8Array)){let f=r.buffer[o(1067)](r[o(797)+"et"],e[o(527)](r[o(1721)+"th"],r.byteOffset));this[o(440)]&&this[o(440)][o(1403)]({data:f,fail:p=>{let w=o;if(l[w(1591)]!==w(1495))this.emit(l.gyZeO,l.XDmUe(lt,w(1055),{message:this[w(1162)+w(1442)+w(1182)](p)}));else return this[w(1694)]?this[w(1694)][w(1473)+"te"]:this[w(686)].automaticOpen?this.CONNECTING:this[w(1671)]}})}else this[o(440)]&&this[o(440)][o(1403)]({data:r,fail:f=>{let p=o,w={YXHUx:function(E,g){return l.kDEeQ(E,g)},UnpKm:function(E,g){return l.kDEeQ(E,g)},wTVsS:function(E,g){return l[G(901)](E,g)},pdnlO:function(E,g){return E===g},Pjjrp:function(E,g){return l[G(423)](E,g)},aVWKw:function(E,g){return l[G(423)](E,g)},eysBB:function(E,g){return l[G(1237)](E,g)}};if(l.SyDaj(l[p(1084)],l[p(1084)])){let E=0,g=0;for(let C=0;w.YXHUx(C,_0xadbfaa[p(559)]);++C)g=_0x5c24e4[p(554)+"At"](C),w[p(1010)](g,128)?E+=1:w[p(1494)](g,2048)?E+=2:w[p(1508)](w[p(812)](64512,g),55296)&&w[p(1508)](w.aVWKw(64512,_0x25230e[p(554)+"At"](w[p(1132)](C,1))),56320)?(++C,E+=4):E+=3;return E}else this[p(478)](p(1055),l[p(728)](lt,l[p(1815)],{message:this[p(1162)+p(1442)+p(1182)](f)}))}})}close(r,o){let l=t;this[l(440)]&&this[l(440)][l(1458)]({code:r,reason:o})}[t(1195)+t(1617)](r,o){this.on(r,o)}[t(1363)+t(1016)+t(1552)](r,o){let l=t,f={PKnXb:function(p,w,E){return e.rPQjk(p,w,E)},PNwEp:e[l(679)],gJCNH:e[l(1831)]};if(e[l(1234)]!==e.rwiLT){this[l(432)+l(421)+"t"]();let p=f[l(1271)](_0x4ee25b,f[l(900)],{message:f.gJCNH});this[l(1224)+l(1220)+l(753)+"ct"]&&this[l(1224)+l(1220)+l(753)+"ct"](p)}else this[l(1290)](r,o)}get[t(1473)+"te"](){let r=t;return this[r(440)][r(1473)+"te"]}get binaryType(){return this[t(440)].binaryType}set[t(932)+"pe"](r){}get[t(1570)](){return this[t(440)].url}get[t(1227)](){let r=t;return this[r(440)][r(1227)]}get[t(1308)+"ns"](){let r=t;return this[r(440)][r(1308)+"ns"]}get["buffered"+t(1036)](){return 0}}function Mp(a,r){let o=t;if(r)return new r(a[o(1570)],a[o(1227)]);if(ei||On)return new Np(a[o(1570)],a[o(1227)],a[o(856)]);if(e[o(1294)](sr,ti)&&e[o(1261)]!=typeof WebSocket&&WebSocket)return new WebSocket(a[o(1570)],a[o(1227)+"s"])}function Bp(a){let r=t,o=e[r(1626)].split("|"),l=0;for(;;){switch(o[l++]){case"0":if(On&&tt[r(451)+r(1734)])return!0;continue;case"1":if(a)return!0;continue;case"2":if(ei&&wx[r(451)+r(1734)])return!0;continue;case"3":if(e[r(1812)](sr,ti)&&e.awpDm(e[r(1261)],typeof WebSocket)&&WebSocket)return!0;continue;case"4":return!1}break}}function hl(a,r,o){let l=t,f={BRVVF:e.nIFbz,kJnsE:function(p,w){return e.UkPZP(p,w)},begmn:function(p,w){return e.RJHsp(p,w)}};if(e[l(740)]===l(836)){let p=-1;async function w(E){let g=l;return E<=p?Promise.reject(new Error(f[g(1516)])):(p=E,f[g(1448)](E,o[g(559)])?Promise[g(566)]():o[E][g(1785)](a)(r,w[g(1785)](null,f[g(641)](E,1))))}w(0)}else{if(e[l(398)](_0x2a35f9,_0xb3a68b))throw new _0x102f41(e.iOXed);let p=3;for(;p>=0;){let w=255&_0x5d49fc;_0x3d22b5(w,_0x2ad45d,e[l(1372)](_0x49418b,p)),_0x41ab99>>>=8,p--}return _0x437cda+4}}function xl(a){let r=t,o=0,l=0;for(let f=0;e[r(1459)](f,a.length);++f)l=a[r(554)+"At"](f),e[r(1702)](l,128)?o+=1:l<2048?o+=2:e[r(1210)](e[r(1808)](64512,l),55296)&&e[r(959)](e[r(416)](64512,a[r(554)+"At"](e.aYluJ(f,1))),56320)?(++f,o+=4):o+=3;return o}function pl(a,r,o){let l=t;if(e[l(1500)](o,r)<1)return"";let f="";for(let p=r;e.Iqaxl(p,o);){let w=a[p++];if(e[l(1077)](w,127))f+=String["fromChar"+l(1169)](w);else if(e[l(712)](w,192)&&e[l(1505)](w,224))f+=String[l(877)+l(1169)](e[l(694)](e[l(995)](e[l(1601)](31,w),6),e[l(493)](63,a[p++])));else if(w>=224&&e[l(1296)](w,240))f+=String[l(877)+"Code"](e[l(372)](e[l(594)](15&w,12)|e[l(1689)](e.gtVIr(63,a[p++]),6),e[l(1428)](63,a[p++])));else if(e[l(560)](w,240)){let E=e[l(1356)](e[l(394)](e[l(1274)](7,w)<<18|e[l(475)](63,a[p++])<<12,e[l(1476)](e[l(1146)](63,a[p++]),6))|63&a[p++],65536);f+=String[l(877)+l(1169)](55296+e.OSRkD(E,10)),f+=String["fromChar"+l(1169)](e[l(1674)](56320,e.GtqQG(1023,E)))}}return f}function ga(a,r,o){let l=t,f=o,p,w;for(let E=0;e[l(1247)](E,a[l(559)]);++E)if(p=a[l(554)+"At"](E),e[l(1110)](p,128))r[o++]=p;else if(e[l(899)](p,2048))r[o++]=e[l(1606)](p,6)|192,r[o++]=63&p|128;else if(e[l(1623)](64512,p)===55296&&e.nnySG(64512&(w=a.charCodeAt(E+1)),56320)){let g=(l(1712)+l(1142)).split("|"),C=0;for(;;){switch(g[C++]){case"0":++E;continue;case"1":r[o++]=e[l(961)](e[l(1646)](p>>6,63),128);continue;case"2":r[o++]=e.GVsCo(p>>18,240);continue;case"3":r[o++]=e.aTOvA(e[l(1299)](63,p),128);continue;case"4":r[o++]=e[l(372)](e[l(1606)](p,12)&63,128);continue;case"5":p=e[l(1597)](e[l(417)](65536,(1023&p)<<10),e[l(1499)](1023,w));continue}break}}else r[o++]=e[l(1801)](e[l(844)](p,12),224),r[o++]=e[l(463)](e[l(1536)](p,6)&63,128),r[o++]=e.MPXAA(63,p)|128;return e[l(345)](o,f)}async function gl(a){let r=t;if(e[r(713)]("string",typeof a)){let o=new Uint8Array(e.dVHxb(xl,a));return e[r(721)](ga,a,o,0),o}return a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a[r(966)],a[r(797)+"et"],a[r(1721)+"th"])}function Fp(a){let r=t;if(e[r(434)](e.MhuTb,e.mGumF)){let o=e[r(673)](_0x234891,_0x4ea3e9,1);_0x518459[r(1519)][o]=_0x56421e}else try{return e[r(820)]===e[r(1764)]?e[r(1203)](e[r(1774)](1e4,_0x228b94[r(412)]()),_0x50832a[r(1032)](e[r(857)](1e4,_0x277cd2.random()))):e.awpDm(e[r(749)],typeof a)&&(a instanceof ArrayBuffer||a[r(966)]&&e[r(445)](a.buffer,ArrayBuffer))||e[r(1122)](r(747),typeof a)?"":(JSON[r(1039)](a),e[r(1622)])}catch{return e[r(378)](e[r(749)],typeof a)?e[r(1086)]:""}}let zp=(a,r)=>{let o=t;switch(a){case o(927):case e[o(1171)]:return{[o(875)+a]:1,"x-tt-env":r};default:return{}}};class Up{constructor(r){let o=t;this[o(1820)+o(1029)]=r,this[o(1559)]=0}[t(1320)](){this.count++}[t(748)+"chMaxCount"](){let r=t;return e.jNZpK(this[r(1559)],this[r(1820)+r(1029)])}[t(549)+t(491)](r=0){let o=t,l={aOTqr:function(f,p,w){return e[G(1149)](f,p,w)},reuNq:function(f,p,w){return e.IPlID(f,p,w)},BSGXU:function(f,p,w){return e[G(1771)](f,p,w)}};e[o(1265)](e[o(1779)],e[o(1779)])?(vmmzCM.aOTqr(_0x1fb57d,_0x2f7321,66),vmmzCM[o(1460)](_0x4026a3,_0x14e519,_0x66ce4c.length),vmmzCM.BSGXU(_0x4450f8,_0x4d74c5,_0x57b803)):(this["maxLossC"+o(1029)]=r,this[o(1559)]=0)}}async function Gp(a){return new Promise(r=>{let o=G,l={KXiEA:function(f,p,w){return e[G(920)](f,p,w)},ynfXW:e[o(869)]};if(e[o(1104)](e.BQkze,"pylpX")){let f={QHelA:o(1055),oZHYO:function(p,w,E){let g=o;return qgXOrJ[g(1790)](p,w,E)},xdfUJ:qgXOrJ[o(1485)]};_0x23feeb[o(566)]()[o(859)](()=>{let p=o,w=_0x32da92(f[p(1699)],{message:this[p(1162)+p(1442)+p(1182)](_0x4d945e)});this[p(478)](f[p(1699)],w);let E=f[p(1078)](_0xd952c7,f[p(520)],{reason:this[p(1162)+p(1442)+p(1182)](_0x363abb)});this[p(478)](f[p(520)],E)})}else{if(!sr)return e[o(541)](r,o(819)+o(1034));try{let f=document[o(1373)+o(1326)](e[o(1615)]);window[o(1526)+o(1053)]=p=>{let w=o;document[w(539)].removeChild(f),window[w(1526)+w(1053)]=void 0,r(p&&p[w(903)]||w(819)+"reason")},f[o(1059)]=e.MKdNt,f[o(1300)]=e[o(1408)](a[o(1759)](/^ws/,o(1639)),o(949)+o(1607)+o(630)+"P");try{document.body[o(1012)+o(1106)](f)}catch{document[o(539)][o(1393)+o(1106)](f)}}catch{window["frontier"+o(1053)]=void 0,e.fOvpy(r,e.MLNCd)}}})}function an(a,r,o){let l=t;return!!a?.[l(1249)](f=>f[l(561)]===r&&f[l(992)]===o)}function or(a,r){let o=t;return a?.find(l=>l[o(561)]===r)?.value}let ma=null;async function qp(){let a=t;return ma||(ma=Promise[a(566)]().then(Ft[a(1785)](Ft,e[a(862)]))),ma}class Hp extends pa{constructor(r,o){let l=t;super(),this[l(852)]=r,this[l(430)]=o,this._qosDB=void 0,this[l(947)+"mise"]=null}async[t(1192)](){await this[t(602)]()}async[t(602)](){let r=t,o={vzNVk:function(l,f){return l===f},nmLPU:e[r(1391)],auUmH:function(l){return e[r(1752)](l)},iEcGW:function(l,f,p,w){return e[r(1384)](l,f,p,w)}};if(!this._qosDB){if(this._initPromise)return this[r(947)+"mise"];try{let l=this[r(852)],f=this._keyPath;this[r(947)+r(651)]=(async()=>{let p=r,{openDB:w}=await o[p(1698)](qp);this[p(1418)]=await o.iEcGW(w,p(1526)+"_"+l,1,{upgrade(E){let g=p;o[g(586)](o[g(379)],g(471))?this[g(1694)]&&this._ws[g(1458)](_0x6b22c0,_0x1e6a1a):E[g(1807)+"jectStore"](l,{keyPath:f})}})})(),await this[r(947)+"mise"]}catch(l){console[r(1563)](l)}finally{this[r(947)+r(651)]=null}}}async[t(807)](r){let o=t;try{return await this[o(602)](),this[o(1418)]?.get(this[o(852)],r)}catch(l){console.log(l)}}async set(r,o){let l=t,f={uqhHz:function(p,w){return e[G(937)](p,w)}};return l(1197)!==l(1272)?(await this[l(602)](),this[l(1418)]?.[l(1797)](this[l(852)],r)):(_0x2fb934|=0,{low:_0x21f19d,high:_0x1a7df7>>31,unsigned:lqwzxg[l(1521)](_0x1b13e1,0)})}async[t(576)](r){let o=t;try{return await this[o(602)](),this[o(1418)]?.delete(this._dbName,r)}catch(l){console[o(1563)](l)}}async clear(){let r=t,o={nwSOK:function(l,f){return e[G(1104)](l,f)}};if(e[r(626)](r(1540),e[r(876)]))try{if(e.MVdiq(e[r(1440)],e.DUnps)){let l=_0x1c5243[r(1519)],f=_0x3a3eb6.limit;return ugXySk[r(887)](l[r(559)],f)?l:l[r(1783)](0,f)}else return await this[r(602)](),this._qosDB?.[r(825)](this[r(852)])}catch(l){console[r(1563)](l)}else{let l=this[r(1418)][r(969)](this._prefix),f=_0x39ea8a.parse(e[r(366)](l,"{}"));return f[_0x63fe1d]=void 0,this[r(1418)][r(999)](this._prefix,_0x578515[r(588)+"y"](f))}}async[t(648)](){let r=t;return await this[r(602)](),this._qosDB?.[r(360)+"ys"](this._dbName)}async getAll(){let r=t;return await this[r(602)](),this[r(1418)]?.[r(1621)](this[r(852)])}async[t(642)](){let r=t;try{this._qosDB?.[r(1458)](),this[r(1418)]=void 0}catch(o){console[r(1563)](o)}}get isReady(){let r=t;try{return e.KBzQs!==r(1004)?!!this[r(1418)]:!!(e[r(1096)](this["currentI"+r(674)],this[r(563)+"s"].length)||e.nnySG(this["currentI"+r(674)],this.endpoints[r(559)]-1)&&this[r(799)+"ndpointT"+r(403)+"t"]===this[r(1070)+"es"])}catch(o){return console[r(1563)](o),!1}}}class jp{constructor(r,o){let l=t;this[l(884)]=r,this[l(614)]=o,this[l(1418)]=localStorage}async openDB(){}get _prefix(){let r=t;return r(1526)+"_"+this[r(884)]}async get(r){let o=t;if(e[o(526)](e[o(1338)],e[o(1107)])){let l={dRYBU:function(g,C){return e[o(1148)](g,C)},jLKKt:function(g,C){return g>C},DdNuV:function(g,C){return e[o(1596)](g,C)},TZAQs:function(g,C){return e[o(1842)](g,C)},RiRLA:function(g,C){return e[o(1480)](g,C)},ubXsB:function(g,C){return e[o(1093)](g,C)},hjCDs:function(g,C){return e[o(1187)](g,C)},geHFL:function(g,C){return g|C}},f=e[o(618)](_0x21295d,8192),p=e.afjLp(f,1),w=null,E=f;return function(g){let C=o;if(l[C(916)](g,1)||l[C(1009)](g,p))return l[C(795)](_0x5b84dd,g);l[C(1327)](E+g,f)&&(w=l[C(406)](_0x38a5fb,f),E=0);let L=_0x671af0[C(1253)](w,E,E+=g);return l.ubXsB(7,E)&&(E=l[C(382)](l[C(978)](7,E),1)),L}}else{let l=this[o(1418)][o(969)](this[o(465)]);return JSON[o(1039)](e[o(366)](l,"{}"))[r]}}async[t(1087)](r,o){let l=t,f=this[l(1418)][l(969)](this[l(465)]),p=JSON.parse(f||"{}");return p[o||r[this[l(614)]]]=r,this[l(1418)][l(999)](this[l(465)],JSON[l(588)+"y"](p)),o||r[this[l(614)]]}async[t(576)](r){let o=t,l=this._qosDB[o(969)](this[o(465)]),f=JSON[o(1039)](e[o(1294)](l,"{}"));return f[r]=void 0,this[o(1418)][o(999)](this[o(465)],JSON[o(588)+"y"](f))}async[t(825)](){let r=t;return this._qosDB[r(825)]()}async[t(648)](){let r=t,o=this[r(1418)][r(969)](this[r(465)]),l=JSON.parse(e[r(1145)](o,"{}"));return Object[r(648)](l)}async[t(1621)](){let r=t,o=this._qosDB[r(969)](this[r(465)]),l=JSON[r(1039)](o||"{}");return Object[r(707)](l)}closeDB(){return Promise[t(566)]()}get[t(780)](){return!!this[t(1418)]}}class Wp{constructor(r,o){let l=t;this[l(884)]=r,this[l(614)]=o,this._qosDB=On?tt:ei?wx:null}async[t(1192)](){}get[t(465)](){return t(1526)+"_"+this._DBName}async[t(807)](r){let o=t,l=this[o(1418)][o(1282)+o(1651)](this[o(465)]);return JSON[o(1039)](e[o(627)](l,"{}"))[r]}async[t(1087)](r,o){let l=t,f=this[l(1418)][l(1282)+l(1651)](this[l(465)]),p=JSON.parse(e[l(1145)](f,"{}"));return p[o||r[this._pathKey]]=r,this._qosDB[l(1531)+l(1651)](this._prefix,JSON[l(588)+"y"](p)),o||r[this[l(614)]]}async[t(576)](r){let o=t,l=this._qosDB[o(1282)+o(1651)](this[o(465)]),f=JSON[o(1039)](e[o(1294)](l,"{}"));return f[r]=void 0,this[o(1418)][o(1531)+o(1651)](this[o(465)],JSON[o(588)+"y"](f))}async clear(){let r=t;return this[r(1418)]["clearSto"+r(415)]()}async[t(648)](){let r=t,o=this._qosDB[r(1282)+r(1420)+"nc"](this[r(465)]),l=JSON.parse(e[r(1520)](o,"{}"));return Object[r(648)](l)}async getAll(){let r=t,o=this[r(1418)][r(1282)+r(1420)+"nc"](this[r(465)]),l=JSON[r(1039)](e.ArZmM(o,"{}"));return Object[r(707)](l)}closeDB(){return Promise[t(566)]()}get[t(780)](){let r=t,o={wPEyc:function(l,f,p){return l(f,p)},QpdXR:function(l,f){return l+f}};if(r(1136)!==e[r(1769)]){let l=wvAFqi[r(1073)](_0x3d872d,_0x349452,_0x1ee6b7[r(400)]),f=_0x3e0efa.bytes,p=_0x561b37[r(1519)];for(let w=0,E=_0x3e2df9[r(400)];w<E;w++)f[wvAFqi[r(1773)](w,l)]=p[w]}else return!!this[r(1418)]}}function ml(a,r){let o=t;if(e.bBBiq(e[o(543)],e[o(543)])){if(e[o(773)](On,On))return new Wp(a,r);if(e.xBykd(sr,ti)&&e[o(1693)](e[o(1261)],typeof indexedDB))return new Hp(a,r);if((sr||ti)&&e[o(1261)]!=typeof localStorage)return new jp(a,r);throw new Error(e.fZwwP)}else _0x38401f+=e[o(800)](_0xbedc34,_0x187594),_0x11fcc8+=2}class Kp{constructor(){let r=t;this[r(1065)+r(569)+"Id"]=null,this._interval=36e5,this[r(1418)]=e[r(349)](ml,e[r(817)],e[r(873)])}async[t(1065)+t(741)](){let r=t;e[r(1596)](clearInterval,this[r(1065)+r(569)+"Id"]),this._intervalTimeoutId=setInterval(()=>{this.flushExpired()},this[r(1065)+"l"])}async[t(1192)](){let r=t;await this[r(1418)][r(1192)]()[r(859)](()=>{let o=r;this[o(1065)+o(741)]()})}async[t(1427)+t(1535)](){let r=t;(await this._qosDB?.[r(1621)]()||[])[r(1103)](({timestamp:f})=>f<Date[r(412)]())[r(981)](f=>{let p=r;this._qosDB?.[p(576)](f[p(1497)+"id"])})}async del(r){return this._qosDB?.del(r)}async[t(1087)](r,o){let l=t;return this[l(1418)]?.[l(1087)]({message_id:r,timestamp:o})}async get(r){let o=t;return this[o(1418)]?.[o(807)](r)}async[t(642)](){let r=t;clearInterval(this[r(1065)+"lTimeoutId"]),await this[r(1418)]?.closeDB()}get[t(780)](){let r=t;return this._qosDB?.[r(780)]}}function wa(a){let r=t,o=!!this[r(686)][r(1548)+"S"];if(!o)return{enabled:o,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(1384)](an,a[r(770)][r(856)],e.FtDVJ,"2"),f=l&&e[r(1821)](an,a[r(770)][r(856)],"x_frontier_qos_ack","1"),p=l&&e.gpAry(an,a[r(770)][r(856)],r(572)+r(1026)+"k","1"),w=p?e[r(1324)](or,a[r(770)][r(856)],e[r(814)])?.split(",")[r(1103)](Boolean)||[]:[];return{enabled:o,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:p,ackMsgIds:w}}async function wl(){let a=t;return this[a(1045)+"ger"]||(this[a(1045)+a(544)]=new Kp),this[a(1045)+a(544)][a(780)]||await this._QoSManager.openDB(),this["_QoSMana"+a(544)]}async function $p(a,r){let o=t,{enableAutoAck:l}=this[o(686)],f=e[o(1141)](an,a[o(770)][o(856)],e[o(1736)],"1"),p=e.dUuHh(an,a[o(770)][o(856)],"is_ack","1"),w=wa[o(1253)](this,a);if(e[o(1348)](l,f)){let{SeqID:E,LogID:g,service:C,LogIDNew:L,method:N}=a[o(770)];this[o(904)]({SeqID:E,LogID:g,LogIDNew:L,service:C,method:N,headers:[{key:e[o(845)],value:"1"},{key:e[o(1695)],value:e[o(1254)](L,"")},{key:e[o(1690)],value:"0"}]})}p&&!w[o(1240)]&&this[o(670)+o(1565)+"ageEvent"](a),e[o(1752)](r)}async function Vp(a,r){let o=t;this[o(1365)](o(479),a[o(770)]),e.GKUyd(r)}async function Jp(a,r){let o=t,l=e[o(908)](rn,await e[o(1105)](gl,a[o(1014)]));try{if(e[o(445)](l[o(1002)],Uint8Array)){let f=e[o(703)](this[o(686)]["payloadE"+o(1238)],Object)?{force:!!this[o(686)][o(1728)+"ncoding"][o(678)],encoding:this[o(686)][o(1728)+o(1238)][o(1400)]?this[o(686)]["payloadE"+o(1238)][o(1400)][o(1759)](/\s/g,"")[o(643)+"ase"]():""}:{force:!1,encoding:this[o(686)]["payloadE"+o(1238)]?this[o(686)].payloadEncoding[o(1759)](/\s/g,"")["toLowerC"+o(771)]():""},p=l[o(1728)+o(1238)]?l["payloadE"+o(1238)][o(1759)](/\s/g,"")[o(643)+o(771)]():"",w=e[o(703)](this[o(686)].payloadType,Object)?{force:!!this[o(686)].payloadType.force,type:this[o(686)]["payloadT"+o(1342)][o(1059)]?this[o(686)][o(735)+o(1342)][o(1059)][o(1759)](/\s/g,"")[o(643)+o(771)]():""}:{force:!1,type:this._options[o(735)+o(1342)]?this[o(686)][o(735)+o(1342)][o(1759)](/\s/g,"")[o(643)+o(771)]():""},E=l[o(735)+o(1342)]?l[o(735)+o(1342)].replace(/\s/g,"")[o(643)+"ase"]():"",g=w.force?w[o(1059)]:E||w.type,C=f.force?f.encoding:p||f[o(1400)],L=[e[o(1086)],e[o(1622)],e[o(1575)],e[o(749)]],N=[e[o(1267)],e[o(428)]];this._options[o(364)+o(1640)+"extPayload"]&&L[o(758)](g)&&(!C||N[o(758)](C))?l[o(1672)+"oad"]=e[o(1384)](pl,l[o(1002)],0,l[o(1002)][o(1721)+"th"]):l[o(1672)+"oad"]=""}else l[o(1672)+o(919)]=""}catch(f){l["textPayl"+o(919)]="",console[o(1563)](f)}a.message=l,r()}function Zp(a,r,o){let l=t,f=e[l(1145)](o,8192),p=e[l(1663)](f,1),w=null,E=f;return function(g){let C=l;if(g<1||e[C(926)](g,p))return a(g);e[C(527)](E,g)>f&&(w=e[C(1747)](a,f),E=0);let L=r[C(1253)](w,E,E+=g);return 7&E&&(E=e[C(1322)](e[C(891)](7,E),1)),L}}let Yp=4294967295;function Xp(a,r,o){let l=t;return e[l(531)](e.raOsG,e[l(1656)])?_0x34bc85[l(1507)+l(1718)][1]?void 0:_0x50e39d[l(1507)+l(357)](_0x46c6c1["objectSt"+l(1718)][0]):e[l(858)](RangeError,e[l(1678)](e[l(1095)](e[l(1205)]("index ou"+l(863)+l(665),a),e.JwLwS)+e.BXxTI(r,1),e[l(1242)])+o)}function Qp(a,r,o){let l=t;if(e[l(1586)](o,Yp))throw new Error(e[l(1241)]);let f=3;for(;e[l(1515)](f,0);){let p=e.VkLtT(255,o);e[l(1384)](ya,p,a,e.UqYvW(r,f)),o>>>=8,f--}return e[l(1686)](r,4)}function eg(a,r){let o=t,l=0,f=r,p=e[o(1156)](r,4);for(;f<p;){let{value:w,offset:E}=e[o(1828)](_a,a,f);f=E,l=e[o(1329)](e[o(1354)](l,8),0),l+=w}return{value:l,offset:p}}function tg(a,r,o){let l=t,f=e.JeCPA[l(1512)]("|"),p=0;for(;;){switch(f[p++]){case"0":return e[l(449)](ga(a,r,o),o);case"1":if(r[l(1466)])return e[l(809)](r[l(1466)](a,o),o);continue;case"2":if(!a)return o;continue;case"3":if(e[l(899)](a.length,40))return e[l(1134)](e[l(629)](ga,a,r,o),o);continue;case"4":if(r[l(989)+"e"])return e.kCEoZ(r.utf8Write(a,o),o);continue}break}}function ng(a,r){let o=t,l=new xe(e[o(911)](e[o(463)](e[o(793)](e.yuEQI(a[e[o(631)](r,4)],24),e[o(689)](a[e[o(1581)](r,5)],16)),e[o(425)](a[e.wuxGu(r,6)],8)),a[e[o(1408)](r,7)]),e[o(909)](e[o(397)](e[o(502)](a[r+0],24)|e[o(905)](a[e.TezYV(r,1)],16),e[o(1170)](a[e[o(517)](r,2)],8)),a[e[o(1658)](r,3)]),!0);return r+=8,{value:l,offset:e.AjMcr(r,8)}}function rg(a,r,o){let l=t,f=a[l(395)],p=a[l(1613)];return r[o]=p>>>24,r[o+1]=e[l(1541)](p,16)&255,r[o+2]=e[l(834)](e[l(1202)](p,8),255),r[e[l(1201)](o,3)]=e[l(346)](255,p),r[e.OxbOe(o,4)]=e[l(598)](f,24),r[e[l(1156)](o,5)]=e[l(1628)](f>>>16,255),r[e[l(1337)](o,6)]=e[l(1299)](e.HHFiy(f,8),255),r[e[l(1445)](o,7)]=255&f,o+=8,o}function _a(a,r){let o=t;return a[o(389)+"8"]?{value:a.readUInt8(r),offset:e[o(454)](r,1)}:{value:e[o(1529)](255,a[r]),offset:e[o(1822)](r,1)}}function ya(a,r,o){let l=t;return r.writeUint8?r[l(1374)+"t8"](a,o):r[o]=e.MqRDo(255,a),o+1}let ig=function(a){return new Uint8Array(a)},sg=e[t(1261)]!=typeof Buffer?Buffer["allocUns"+t(1311)]:e[t(917)](Zp,ig,Uint8Array[t(1042)+"e"][t(1783)]);(()=>{let a=t,r={SwCqW:e[a(872)],IaRib:function(l,f){return l>f},VgugA:function(l,f,p,w){return e[a(635)](l,f,p,w)},THcNz:function(l,f){return l>>>f},yFiun:function(l,f){return e[a(1583)](l,f)},puZLQ:function(l,f){return e[a(774)](l,f)},TYpxD:function(l,f){return e[a(1394)](l,f)},fzlUi:function(l,f){return l<<f},yUrJR:function(l,f){return e[a(1509)](l,f)},GvGwM:function(l,f){return l|f},IbLTr:function(l,f){return e[a(1293)](l,f)},RrBSb:function(l,f){return e[a(1072)](l,f)},TILab:function(l,f){return e[a(1632)](l,f)},AYBAR:function(l,f){return e[a(533)](l,f)}},o=4294967295;return function(l,f,p=!0){let w=a,E=r[w(1155)][w(1512)]("|"),g=0;for(;;){switch(E[g++]){case"0":if(r[w(1682)](f+=5,l.length))throw f=l.length,r[w(1513)](Xp,f,10,l[w(559)]);continue;case"1":o=r[w(613)](r[w(1840)](127,l[f]),0);continue;case"2":o=(o|r[w(1840)](127,l[f])<<21)>>>0;continue;case"3":if(r.puZLQ(l[f++],128))return{value:p?o:0|o,offset:f};continue;case"4":if(l[f++]<128)return{value:p?o:r[w(734)](0,o),offset:f};continue;case"5":o=(o|r[w(579)](r[w(1840)](127,l[f]),7))>>>0;continue;case"6":if(r[w(1533)](l[f++],128))return{value:p?o:r[w(954)](0,o),offset:f};continue;case"7":if(r.IbLTr(l[f++],128))return{value:p?o:0|o,offset:f};continue;case"8":return{value:p?o:r.RrBSb(0,o),offset:f};case"9":if(r[w(1092)](l[f++],128))return{value:p?o:r.GvGwM(0,o),offset:f};continue;case"10":o=(o|r.AYBAR(15&l[f],28))>>>0;continue;case"11":o=r[w(613)](r.TYpxD(o,r[w(579)](127&l[f],14)),0);continue}break}}})();let og=16,ba=32;function ag(a){let r=t,o={VfbUo:function(p,w){return p<w},MFtQx:function(p,w){return e[G(1283)](p,w)},Ftrxe:function(p,w){return e[G(1410)](p,w)}},l=0,f={};for(let p=0;e[r(1676)](p,a[r(559)]);p++)if(e[r(1265)]("euYcN",e.TrvOT))f[a[p][r(439)+r(524)]]=e[r(779)](xl,a[p]["cursor_n"+r(524)]),l+=e[r(1353)](14,f[a[p]["cursor_n"+r(524)]]);else{let w=_0x210703[r(1512)](":");_0x61917a&&(_0x361190=w[r(559)]),_0x2d8f4f+=w[r(559)];for(let E=0;DpCzhy[r(1115)](E,w[r(559)]);E++)if(DpCzhy.MFtQx(4,w[E][r(559)])){let g=_0x43732e.substring(0,DpCzhy[r(1175)](4,w[E][r(559)])),C=g[r(437)](w[E]);_0x409263[r(946)](C)}else _0x52bf05[r(946)](w[E]);_0x1d1f64=!1}return[l,f]}function _l(a,r,o){let l=t,[f,p]=e.WVVDC(ag,a),w=sg(f),E=0;return a[l(981)](g=>{let C=l,L=e.LQVqa[C(1512)]("|"),N=0;for(;;){switch(L[N++]){case"0":console[C(1563)](e.PGRrF,g,g.service);continue;case"1":console[C(1563)](e.npbZg,E);continue;case"2":console[C(1563)](e.xMlpc,E);continue;case"3":E=e[C(1814)](Qp,w,E,g[C(850)]||0);continue;case"4":console.log(e.qmHoS,E);continue;case"5":console[C(1563)](C(1566),E);continue;case"6":console.log(C(763),E);continue;case"7":E=ya(p[g[C(439)+C(524)]],w,E);continue;case"8":E=e[C(1384)](rg,xe[C(861)+"er"](g[C(693)]||r),w,E);continue;case"9":E=ya(0,w,E);continue;case"10":E=tg(g[C(439)+C(524)],w,E);continue}break}}),{frameType:ba,headers:[{key:e.SoMSZ,value:o}],payload:w}}function cg(a){let r=t,o=0,l=[];for(;e[r(1048)](o,a.byteLength);){let{offset:f}=e[r(1317)](_a,a,o);o=f;let p={cursor_name:"",cursor:0,service:0},{value:w,offset:E}=e.zMeTT(eg,a,o);p[r(850)]=w,o=E;let{value:g,offset:C}=e.HNYzC(_a,a,o);o=C,p[r(439)+r(524)]=e[r(453)](pl,a,o,o+g),o+=g;let{value:L,offset:N}=ng(a,o);p[r(693)]=L[r(608)](),o=N,l[r(946)](p)}return l}function dg(){let a=t;return{frameType:ba,headers:[{key:e.SoMSZ,value:e[a(938)]}],payload:void 0}}class lg{constructor(r,o,l){let f=t;e.AlymX(e[f(600)],e[f(600)])?(this[f(401)+"ameSpace"]=r,this[f(607)+f(1767)]=o,this[f(426)+f(1455)]=l,this[f(1418)]=ml(this[f(401)+"ameSpace"],e.oVOvV)):this[f(686)][f(1021)]&&_0x481c62[f(1563)][f(461)](_0x4b7bc1,[e.tTwsb,..._0x498ac2])}async[t(1192)](){let r=t;await this[r(1418)][r(1192)]()}async[t(944)+"rs"](){let r=t;if(!this[r(1418)][r(780)])return;let o=this[r(426)+r(1455)],l=await this[r(1418)][r(1621)]();switch(console[r(1563)](e[r(1216)],l),o){case e[r(1727)]:return l&&l.length?e.BsrRm(_l,l,0,this[r(607)+"ileName"]):void 0;case r(411):return;case e.fsFWd:return l&&l[r(559)]?e.CYTiD(_l,l,0,this[r(607)+r(1767)]):e[r(1675)](dg)}}async set(r,o,l){let f=t;return console[f(1563)](e[f(1035)],r,o,l),this._qosDB[f(1087)]({cursor_name:r,cursor:o,service:l})}async[t(1798)+"rs"](r){let o=t;if(e.Ehqfx("CaQDW",e[o(1257)]))return KCTZtp[o(699)](_0x523a57,_0x1a0bb2)&&(_0x2a8314===KCTZtp[o(452)]||KCTZtp[o(1196)](_0x38b003,KCTZtp[o(1191)]))?!0:KCTZtp.puzUg(_0x4ea7e0,_0x63f1c7);{let l=e.Ohzde(cg,r);for(let f of l)console[o(1563)](e[o(815)],l),await this._qosDB[o(1087)](f)}}async[t(807)](r){let o=t;return(await this[o(1418)].get(r))?.[o(693)]}async[t(642)](){let r=t;e[r(783)](e[r(362)],e.COssf)?await this[r(1418)].closeDB():(_0x24cc8f[r(539)].removeChild(_0x1c8ee7),_0x3c4f59["frontier"+r(1053)]=void 0,e[r(604)](_0x3de2c4,_0x243f97&&_0x2fc4f7[r(903)]||e[r(443)]))}[t(418)+"rsorFile"+t(1306)](r){let o=t;this[o(607)+o(1767)]=r}get[t(780)](){return this._qosDB.isReady}}let ug=e[t(1787)];async function yl(a){let r=t,o={WDDde:function(E,g){return e.ROdeg(E,g)}};if(!this[r(686)].enableQoS)return null;let{aID:l,fpID:f,messageStrategy:p}=this[r(686)],w=e[r(1375)](a,ug);try{if(this[r(655)+"anager"]){if(e[r(914)](e[r(1605)],e[r(521)]))return xcsSmh[r(514)](_0x44b80a,_0x5d6760);a&&this[r(655)+r(1750)][r(418)+r(1598)+"Name"](a)}else this[r(655)+r(1750)]=new lg(f+"_"+l+"_"+w,w,p);return this["_cursorM"+r(1750)][r(780)]||await this[r(655)+"anager"].openDB(),this._cursorManager}catch{return null}}async function fg(a,r){let o=t,l=e[o(738)](an,a[o(770)][o(856)],e[o(433)],"-1"),f=an(a[o(770)][o(856)],e[o(845)],"1"),p=or(a.message[o(856)],o(572)+"er_msgid"),w=e[o(786)](Number,e.wGNyo(or,a[o(770)][o(856)],e[o(1776)]))||0,E=wa[o(1253)](this,a),g=e[o(629)](an,a.message[o(856)],e.LPAlw,"2"),C=e[o(628)](or,a.message.headers,e[o(700)]),L=e[o(1099)](Number,e.fbEKd(or,a.message[o(856)],e.DvWGq));if(E.isQoSAck)return e[o(1675)](r);let N=E["isQoSMes"+o(605)]?await wl[o(1253)](this):null;if(e[o(398)](a[o(770)][o(850)],0)&&f&&!l||e[o(1842)](a[o(770)][o(850)],0)){if(p&&E[o(472)+o(605)]&&N)if(e.tdJnf(e[o(587)],o(584)))try{return!!this[o(1418)]}catch($){return _0x284c88.log($),!1}else return!!!await N[o(807)](p)&&(this["_dispatc"+o(1627)+o(427)](a),await N[o(1087)](p,e[o(500)](Date[o(412)](),w))),e[o(1279)](r);if(g){let $=await yl[o(1253)](this);if(!$)return this[o(670)+o(1627)+o(427)](a),e[o(1752)](r);let se=await $[o(807)](C)??-1;if(se<L)this[o(670)+o(1627)+"Event"](a),$[o(1087)](C,L,a[o(770)][o(850)]);else throw new Error(o(1609)+o(1037)+" cursor "+L+(o(1231)+o(413)+o(1723)+"r ")+se);return e[o(1752)](r)}return this[o(670)+"hMessage"+o(427)](a),e[o(650)](r)}}async function hg(a,r){let o=t,l=wa[o(1253)](this,a);if(!l[o(472)+o(605)])return r();let f=await wl.call(this);if(l[o(1278)+o(385)+"age"]&&l.ackMsgIds[o(559)])for(let p of l[o(1114)+"s"])await f[o(576)](p);e[o(1752)](r)}async function xg(a,r){let o=t,l=e[o(921)](a[o(770)][o(438)+"e"],og),f=e.Ehqfx(a[o(770)][o(438)+"e"],ba);if(!l&&!f)return e[o(1401)](r);let p=e.dOIKy(or,a.message.headers,e[o(1295)]);if(!p)return e[o(1279)](r);let w=await yl[o(1253)](this,p);if(!w)return e[o(1675)](r);if(l){let E=await w[o(944)+"rs"](),g={frameType:E?.[o(438)+"e"],SeqID:xe.fromNumber(this[o(1411)]++),LogID:xe[o(861)+"er"](this[o(686)][o(659)+"erator"]()),service:9e3,method:5,headers:E?.[o(856)],payload:E?.[o(1002)]},C=S(g);this[o(1694)]&&this[o(1694)].readyState&&this[o(1694)].send(C)}if(f){let E=a.message[o(1002)];E&&w[o(1798)+"rs"](E)}}let pg=async function(a,r){let o=t;this[o(1412)]=!1,e[o(580)](clearTimeout,this["_connect"+o(1054)+o(474)]),e[o(782)](r)},gg=async function(a,r){let o=t;if(!this[o(1694)]||e.yyNYE(this[o(1694)][o(1473)+"te"],this[o(458)]))return e.FqoFp(r);let{pingInterval:l}=this._options;this["_endpoin"+o(953)]?.[o(958)+o(894)+o(922)]();for(let p=0;p<this[o(426)+o(371)].length;p++){let w=this[o(426)+o(371)][p];if(e[o(1017)](this[o(1694)][o(1473)+"te"],this[o(458)])&&w!==null)if(e[o(1264)]!=="xpFjv")this[o(1694)]&&this[o(1694)].send(w),this[o(426)+o(371)][p]=null;else return _0x3c5d4f;else break}this[o(426)+o(371)]=this[o(426)+o(371)].filter(p=>!!p),this[o(505)+o(1166)+"Id"]=e[o(687)](setTimeout,()=>this[o(1200)](),l),this[o(670)+o(757)+"nt"](a),this._isBrowser&&this[o(1694)]&&(this[o(1694)][o(932)+"pe"]=this[o(1188)+o(1342)]);let f=this[o(933)+o(953)]?.[o(1351)+o(743)+"nt"]();this[o(1365)](o(1697)+f+o(464)),e[o(1438)](r)},mg=async function(a,r){let o=t,l=this["_endpoin"+o(953)]?.[o(1351)+o(743)+"nt"]();this[o(1365)](o(1697)+l),e.LkrJb(r)};class wg extends pa{constructor(r){let o=t,l={hWNkr:function(E,g){return e[G(1085)](E,g)},PgZHp:function(E,g){return e[G(1819)](E,g)},eiuLA:function(E,g){return e[G(689)](E,g)},wQPcm:function(E,g){return e[G(1709)](E,g)},cHSiU:function(E,g){return e[G(1722)](E,g)},MNJee:function(E,g){return e[G(1801)](E,g)},qWAtI:function(E,g){return e[G(1583)](E,g)}};super(),this[o(983)+"igatorOnline"]=!0,this[o(1235)+"er"]=sr,this._isNode=Lp,this._isMiniTT=On,this[o(798)+"X"]=ei,this[o(1277)+"r"]=ti,this[o(426)+"Queue"]=[],this._endpointManager=null,this[o(790)+o(494)]=!1,this[o(1188)+"ype"]="arraybuf"+o(1287),this[o(654)+o(1811)]=!1,this[o(654)+o(1054)+o(474)]=null,this[o(682)+o(1511)+o(1144)]=null,this["_pingPon"+o(1166)+"Id"]=null,this[o(1411)]=0,this[o(1412)]=!1,this[o(907)]="",this[o(1045)+o(544)]=null,this[o(655)+o(1750)]=null,this[o(455)+o(847)]=null,this._protocols=e[o(1248)],this[o(1671)]=3,this[o(731)+"NG"]=0,this.OPEN=1,this[o(1152)]=2,this._onOpen=E=>{let g=o;try{e[g(1104)](g(1761),e.xgPcZ)?e[g(453)](hl,this,E,[pg,gg,mg]):(_0x7a6609=lOIovn[g(1534)](lOIovn[g(886)](65536,lOIovn[g(683)](1023&_0x16b437,10)),lOIovn[g(1619)](1023,_0x4924f0)),++_0x3333c3,_0x521ce8[_0x295c81++]=lOIovn.cHSiU(_0xfdc87f,18)|240,_0x433ec0[_0x5b545a++]=lOIovn[g(660)](lOIovn[g(1619)](lOIovn[g(1027)](_0x31ec80,12),63),128),_0x517544[_0x3eb998++]=lOIovn[g(660)](lOIovn.qWAtI(_0x5db143>>6,63),128),_0x465596[_0x210b3d++]=63&_0x42d696|128)}catch(C){let L=e[g(1149)](lt,e.SsgkD,{message:C[g(770)],code:on[g(388)+"OR"],error:C});this[g(670)+g(552)+g(880)](L)}},this[o(647)+"ge"]=async E=>{let g=o,{pingInterval:C,pingFrequency:L}=this[g(686)];if((e[g(783)]("hi",E[g(1014)])&&e[g(512)](e[g(715)],L)||e[g(1720)](e[g(962)],L))&&(this[g(487)+g(1744)](),this[g(478)](e[g(1832)],e.uRpiV),this[g(505)+g(1166)+"Id"]=setTimeout(this[g(1200)][g(1785)](this),C)),!e[g(1481)]("hi",E.data))try{e[g(453)](hl,this,E,[Jp,$p,hg,xg,fg,Vp])}catch(N){let $=lt(e[g(1791)],{message:N.message,code:on[g(1097)+"ERROR"],error:N});this[g(670)+g(552)+g(880)]($)}},this._onError=E=>{let g=o,C=this[g(933)+"tManager"]?.[g(748)+g(1568)+"es"](),L=this[g(933)+g(953)]?.[g(1351)+"ntEndpoint"]();if(C&&!E[g(770)]){let N=g(1746)+L+(g(1383)+g(1701)+g(1818)+"ed");this[g(670)+g(552)+g(880)](e.CtdgD(lt,g(1055),{message:N,code:on[g(557)+"IES_ERROR"],error:E}));return}this._ws&&e.rpwJM(this._ws.readyState,this[g(458)])&&this[g(1343)+g(986)](),this["_dispatc"+g(552)+g(880)](e[g(716)](lt,e.SsgkD,{message:E[g(770)],code:on[g(1233)+g(1215)],error:E}))},this[o(373)]=async E=>{let g=o;this[g(690)+g(1309)](),this["_clearPi"+g(1744)](),this[g(1212)+"sListeners"](),this[g(1694)]=null,this[g(654)+g(1811)]=!1;let C=this["_endpoin"+g(953)]?.["checkRea"+g(1568)+"es"]();if(!C&&this[g(1740)+g(1127)]()&&!this["_readyCl"+g(494)]){let L=this[g(933)+g(953)]?.[g(1351)+"ntEndpoint"](),N=this[g(686)][g(619)+g(1321)+g(1496)](E[g(1143)],E[g(1034)]);this["_dispatchCloseEv"+g(880)](wt(e.nooKa,{code:1006,reason:E[g(1034)]||"connecti"+g(1314)+"d, unkno"+g(1557)+g(1098)+g(1661)+L,willReconnect:N})),N&&this[g(654)]();return}if(e[g(874)](1e3,E[g(1143)])&&this[g(790)+"osed"]){this[g(670)+g(883)+g(880)](e.SVgfB(wt,e[g(869)],{code:1e3,reason:g(1577)})),this["_endpoin"+g(953)]?.[g(958)+"pointConfig"](),this["_pingLos"+g(847)]?.[g(549)+g(491)]();return}if(E.code!==1e3&&C){let L=this[g(933)+"tManager"]?.[g(1351)+g(743)+"nt"](),N=E[g(1034)];N||(N=await Gp(this[g(907)])),N=g(1501)+g(1314)+g(896)+N+(g(1304)+"me: ")+L+(g(1116)+"tries re"+g(420)),this["_dispatc"+g(883)+"ent"](wt(g(1458),{code:E[g(1143)],reason:N}));let $=g(1746)+L+(" fail, m"+g(1701)+g(1818)+"ed");this[g(670)+g(552)+"ent"](e[g(1221)](lt,e.SsgkD,{message:$,code:on["MAX_RETR"+g(1328)+"R"]})),this[g(933)+"tManager"]?.["resetEndpointCon"+g(922)](),this[g(455)+g(847)]?.[g(549)+g(491)]();return}if(e[g(652)](1e3,E.code)&&!E[g(1034)]){let L=this[g(933)+g(953)]?.[g(1351)+g(743)+"nt"]();this[g(670)+g(883)+g(880)](e[g(708)](wt,"close",{code:E[g(1143)],reason:g(1501)+"ng faile"+g(695)+"wn reaso"+g(1098)+g(1661)+L})),this[g(933)+g(953)]?.[g(958)+g(894)+g(922)](),this["_pingLos"+g(847)]?.[g(549)+"nter"]();return}this["_dispatc"+g(883)+"ent"](E),this["_endpoin"+g(953)]?.["resetEnd"+g(894)+g(922)](),this[g(455)+g(847)]?.[g(549)+g(491)]()},this.onclose=null,this[o(387)]=null,this[o(1139)+"e"]=null,this[o(722)]=null,this[o(1731)+o(528)]=null,this[o(1168)+o(1554)]=null,this[o(1224)+o(1220)+o(753)+"ct"]=null,this["_handleO"+o(1588)]=this[o(1726)+o(1588)][o(1785)](this),this[o(1726)+o(558)]=this[o(1726)+o(558)].bind(this),this[o(751)+"ageHide"]=this[o(751)+o(977)][o(1785)](this),this["_handleP"+o(1286)]=this[o(751)+"ageShow"].bind(this),this[o(686)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[o(737)](1,0),service:0,logIDGenerator:s,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[o(962)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e.fsFWd,env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:p}=r,w=Array.isArray(f)?f:e.THEKg(e[o(749)],typeof f)?[f]:[];if(!w||e.bYYQd(0,w[o(559)]))throw new Error(e[o(1177)]);if(!e[o(1361)](Bp,p))throw new Error(e[o(365)]);Object[o(597)](this._options,r),this[o(933)+o(953)]=new fl(w,this[o(686)].maxRetries),this[o(455)+"sCounter"]=new Up(this[o(686)][o(1571)+o(1489)]),this[o(686)][o(1325)+o(1386)]&&(this[o(1412)]=!0,this[o(654)]()),this[o(686)]["listenNe"+o(633)+"nged"]&&(this[o(1633)+"T"]||this[o(798)+"X"]?this[o(369)+"etWorkCh"+o(935)]():this[o(1235)+"er"]&&this["_initGlo"+o(1756)+o(1617)]())}[t(1726)+t(1588)](){let r=t;this[r(686)]["disableAutoRecon"+r(1592)]||this[r(790)+"osed"]||this["_handleR"+r(528)]()}[t(1726)+t(558)](){let r=t,o={UyeIe:function(l,f){return e[G(1419)](l,f)},tuBFJ:function(l,f){return e[G(589)](l,f)},IJjpT:function(l,f){return e[G(490)](l,f)},cqPRy:function(l,f){return l|f},rvhev:function(l,f){return l<<f},ckDGV:function(l,f){return e[G(1369)](l,f)},KFVsM:function(l,f){return l|f},LryOq:function(l,f){return l&f},YlHxk:function(l,f){return e[G(1824)](l,f)},CAKNO:function(l,f){return e[G(1681)](l,f)},itZsK:function(l,f){return e.MsIuQ(l,f)},frUVH:function(l,f){return e.hIYZT(l,f)},cjoWK:function(l,f){return e.ZcizB(l,f)},wWrff:function(l,f,p){return l(f,p)},OsbAy:function(l,f){return e[G(844)](l,f)},SuytJ:function(l,f){return l+f},fvlOI:function(l,f){return e[G(1130)](l,f)}};if(e.VtIib(e[r(806)],e[r(806)]))_0x3f4064=_0xe279a1[LstyDK[r(879)](LstyDK[r(879)](_0x1f6fed,_0x2d7dcd),1)],_0x5ae056=_0x52499e[LstyDK[r(879)](LstyDK.UyeIe(_0x1bc3fe,_0x489957),2)],_0xe02bf9=_0x1328d3[LstyDK[r(974)](_0x5973f8+_0x350e09,3)],LstyDK[r(1488)](LstyDK[r(1737)](_0x396867,LstyDK[r(1172)](_0x5bc533,8))|LstyDK.ckDGV(_0x3a0382,16),12632256)!==8421504?_0x39c1a9+=_0x51a90e:(_0x2b263d=LstyDK.cqPRy(LstyDK[r(532)](LstyDK[r(1634)](LstyDK[r(1805)](7,_0x2e19dd),18),LstyDK[r(1634)](LstyDK[r(777)](63,_0x1cf76e),12)),LstyDK[r(756)](LstyDK[r(1488)](63,_0x15d5cb),6))|LstyDK[r(1090)](63,_0x2d2d75),LstyDK.frUVH(_0x1febd1,65536)||LstyDK[r(1333)](_0x32aa59,1114111)?_0x53dc1e+=_0x2dedd6:(_0x5d22e1-=65536,_0x586226+=LstyDK[r(1284)](_0x5312f6,LstyDK[r(974)](LstyDK[r(1013)](_0x2385dc,10),55296),LstyDK[r(776)](LstyDK.fvlOI(1023,_0x4a3e56),56320)),_0x29263c+=3));else{this[r(432)+"WebSocket"]();let l=e[r(1788)](xa,e[r(679)],{message:e[r(1831)]});this["onStopIm"+r(1220)+r(753)+"ct"]&&this["onStopIm"+r(1220)+r(753)+"ct"](l)}}["_initGlobalEvent"+t(1617)](){let r=t;this[r(1235)+"er"]&&window["addEvent"+r(1617)](e[r(1434)],this[r(1726)+"nLine"]),this._isBrowser&&window[r(1195)+"Listener"](r(1135),this["_handleO"+r(558)]),this[r(1235)+"er"]&&window["addEvent"+r(1617)](e.NScyl,this[r(751)+"ageHide"]),this[r(1235)+"er"]&&window[r(1195)+r(1617)](e[r(1587)],this["_handleP"+r(1286)])}[t(646)+"balEventListener"](){let r=t;this._isBrowser&&window[r(1363)+r(1016)+r(1552)](e[r(1434)],this[r(1726)+r(1588)]),this._isBrowser&&window[r(1363)+"entListe"+r(1552)](e[r(1043)],this[r(1726)+r(558)]),this[r(1235)+"er"]&&window[r(1363)+"entListe"+r(1552)](e[r(1754)],this["_handleP"+r(977)]),this[r(1235)+"er"]&&window[r(1363)+r(1016)+r(1552)](e.pKqbl,this["_handleP"+r(1286)])}[t(751)+"ageHide"](r){let o=t;r[o(1662)+"d"]||(e[o(542)](o(1336),"VFiZy")?(this[o(1235)+"er"]&&window[o(1363)+o(1016)+o(1552)](e[o(1754)],this[o(751)+o(977)]),this[o(1235)+"er"]&&window[o(1363)+o(1016)+"ner"](e[o(1587)],this["_handleP"+o(1286)]),this[o(1458)]()):(e.EkAMz(_0x3cb39f,65536)?_0x651e66[_0x33bae5++]=e[o(1120)](e[o(1722)](_0x4f637f,12),15)|224:(_0x23d92c[_0x167423++]=e[o(867)](e[o(1813)](_0x4b5df9,18),7)|240,_0xed68ce[_0x14f3be++]=e[o(1801)](e.hMEvc(e[o(1772)](_0x57af67,12),63),128)),_0x2de361[_0x3287b8++]=e[o(1281)](e[o(1068)](_0x351cc1>>6,63),128))),this[o(1235)+"er"]&&window["removeEv"+o(1016)+"ner"](e[o(1434)],this["_handleO"+o(1588)]),this._isBrowser&&window["removeEv"+o(1016)+"ner"](o(1135),this[o(1726)+"ffLine"])}[t(751)+t(1286)](r){let o=t;if(e[o(1483)]!=="ZVWNW")r[o(1662)+"d"]&&(this[o(1740)+o(1127)]()&&(!this[o(1694)]||e[o(621)](this[o(1694)][o(1473)+"te"],this[o(458)])||e.MVdiq(this[o(1694)][o(1473)+"te"],this.CONNECTING))&&this["_handleO"+o(1588)](),this[o(1235)+"er"]&&window[o(1195)+o(1617)](o(1119),this[o(1726)+o(1588)]),this._isBrowser&&window[o(1195)+o(1617)](e[o(1043)],this["_handleO"+o(558)]));else return _0x1942e1&&(_0x36a95d=(0,_0x18a4e1[_0x5c281c(_0x56de5d)[0]])(_0x30d469=0)),_0x26028b}async[t(685)+"eUrl"](r){let o=t,{fpID:l,deviceID:f,bddID:p,ttwID:w,accessKey:E,aID:g,customParams:C={},enableAutoAck:L,enableQoS:N,QoSLevel:$,env:se}=this._options,re,ie,Me;this[o(1235)+"er"]||this._isMiniWX||this[o(1633)+"T"]?(re=location&&e[o(481)](e.GSMTv,location.protocol)?"wss://":e[o(581)],ie=r.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),Me=/^wss(.*:\/\/)/[o(1664)](r)?r:""+re+ie):(re="wss://",ie=r.replace(/(^http)((?:[s]*:\/\/))/,""),Me=/(^ws)((?:[s]*:\/\/))/[o(1664)](ie)?ie:""+re+ie);let pe=p?e[o(1679)]:w?o(603):e[o(611)],qt=p||w||f;if(!qt||!pe)throw new Error(e[o(1680)]);let _e=e[o(713)](e[o(788)],typeof C)?await C():C,Ea=se?e[o(673)](zp,se[o(1219)],se[o(1713)]):{},ni=Object[o(597)]({device_platform:e[o(1618)],version_code:e[o(1795)],access_key:E,fpid:l,aid:g,[pe]:qt,xsack:L?1:0,xaack:L?1:0,xsqos:N?1:0,qos_level:N?$:void 0,qos_sdk_version:2,...Ea},_e),_g=Object[o(648)](ni).reduce((va,Sa)=>ni[Sa]!==void 0?""+va+(va?"&":"?")+Sa+"="+ni[Sa]:va,"");return Me+o(1829)+_g}async[t(654)](){let r=t;if(!(this._connectLock||this[r(790)+"osed"])){this[r(654)+r(1811)]=!0;try{let o=this[r(933)+"tManager"]?.[r(1407)+r(644)+r(1465)+r(1366)+r(523)](),{timeoutInterval:l}=this[r(686)];if(o)if(e[r(942)](r(925),e[r(1030)])){let p=this[r(933)+r(953)]?.[r(1351)+r(743)+"nt"](),w=this[r(933)+r(953)]?.[r(1239)+r(1564)+"pointAnd"+r(1600)+r(1190)](),E=this[r(933)+"tManager"]?.[r(1351)+"ntEndpointTriesC"+r(1029)]();if(w){let g=r(1746)+p+(r(796)+", max retries re"+r(929)+r(1522)+r(501)+r(530))+w+(r(1163)+"y"),C=e[r(1705)](lt,e[r(1791)],{message:g,code:on[r(557)+r(1328)+"R"]});this._debug(g),this[r(670)+r(552)+r(880)](C),this[r(907)]=await this[r(685)+r(1370)](w),this._debug(r(1746)+w+" "+E+r(1270)),this[r(1212)+r(1069)+"rs"]()}else{let g="connect "+p+(r(796)+r(1116)+"tries reached");this[r(1365)](g),this[r(670)+r(552)+r(880)](lt(e[r(1791)],{message:g,code:on["MAX_RETR"+r(1328)+"R"]}));return}}else _0x3456ae=_0x49d6fd.concat(_0x5a2a1b),_0x47d8fb=_0x13e4c3.concat(_0x3de9d7[_0x4d7d3c]);else{let p=this[r(933)+r(953)]?.[r(1351)+r(743)+r(1150)+r(1538)](),w=this[r(933)+r(953)]?.[r(1351)+"ntEndpoi"+r(1467)+r(1029)]();this._url=await this[r(685)+r(1370)](e[r(1294)](p,"")),this[r(1365)](r(1746)+p+" "+w+r(1270)),this[r(1212)+r(1069)+"rs"]()}if(this._isInit)this._isInit=!1;else{let p=e[r(374)](xa,"reconnect",{message:e[r(1530)]});this["onStartR"+r(528)]&&this["onStartR"+r(528)](p)}let f=this[r(933)+r(953)]?.[r(1351)+r(743)+r(1467)+r(1029)]()||0;f>1&&await this[r(1796)](e[r(936)](f,1)),this[r(1365)](r(1501)+r(940)+this[r(907)]+(" protoco"+r(1595))+this[r(663)+"ls"]),this[r(1694)]=e[r(1705)](Mp,{url:this[r(907)],protocols:[this[r(663)+"ls"]],headers:this._options[r(1266)+r(761)+"s"][r(1007)+"tpHeader"]},this._options.ws),(this[r(1235)+"er"]||this[r(1277)+"r"])&&this._ws&&(this._ws[r(932)+"pe"]=this[r(1188)+r(1342)]),this[r(1060)+"steners"](),this[r(654)+r(1054)+"utId"]=e[r(1330)](setTimeout,this._onTimeout[r(1785)](this),l)}catch(o){throw this[r(654)+r(1811)]=!1,o}}}_clearTimer(){let r=t;e[r(1232)](e[r(1777)],e[r(1777)])?(e[r(1051)](clearTimeout,this["_connect"+r(1054)+r(474)]),this[r(654)+r(1054)+r(474)]=null):this[r(1290)](_0x3c2c58,_0x4f7343)}[t(487)+t(1744)](){let r=t;e[r(1099)](clearTimeout,this[r(505)+"gTimeoutId"]),e[r(419)](clearTimeout,this[r(682)+r(1511)+r(1144)]),this[r(505)+r(1166)+"Id"]=null,this[r(682)+r(1511)+"tId"]=null}[t(1365)](...r){let o=t;this._options.debug&&console.log[o(461)](console,[e[o(1137)],...r])}["_getInte"+t(353)+"e"](r){let o=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:p}=this[o(686)],w=e.VsUmi(l,Math.pow(p,e.PMgjQ(r,1)));return e[o(1022)](w,f)?f:w}[t(1200)](){let r=t;if(this[r(1694)]&&e[r(1210)](this._ws[r(1473)+"te"],this[r(731)+"NG"])){this["_clearPi"+r(1744)](),this[r(505)+r(1166)+"Id"]=setTimeout(this._ping[r(1785)](this),this[r(686)][r(982)+r(1258)]);return}if(!this._ws||e[r(1838)](this[r(1694)][r(1473)+"te"],this[r(458)]))return void this[r(1357)+r(528)]();this[r(1694)]&&this[r(1694)][r(1403)]("hi"),this["_reconne"+r(1511)+r(1144)]=setTimeout(this[r(1357)+r(528)+r(1504)].bind(this),this._options[r(399)+r(1749)+r(792)])}["_handleR"+t(528)+t(1504)](){let r=t;this[r(455)+"sCounter"]?.[r(1320)](),this[r(478)]("ping_onc"+r(1344)+"t",e[r(1590)]),this[r(455)+r(847)]?.[r(748)+r(450)+"nt"]()?this[r(1357)+r(528)]():this[r(1200)]()}[t(1740)+t(1127)](){let r=t;return this[r(1633)+"T"]||this._isMiniWX?this[r(983)+"igatorOn"+r(484)]:(this._isBrowser||this[r(1277)+"r"])&&this[r(686)]["listenNe"+r(633)+r(841)]?navigator[r(1413)]:!0}[t(1357)+t(528)](){let r=t;!this["_navigat"+r(1127)]()||this[r(790)+r(494)]||(this["_endpoin"+r(953)]?.[r(958)+r(894)+r(922)](),this["_pingLos"+r(847)]?.resetCounter(),this[r(1694)]?this[r(1343)+"ect"](1001,"going away, try "+r(619)+r(485)+r(1612),!0):this._connect())}[t(369)+t(1642)+t(935)](){let r=t;this[r(1633)+"T"]?tt[r(1517)+r(486)+"hange"](({isConnected:o})=>{let l=r;this[l(983)+"igatorOn"+l(484)]=o,o?this[l(1726)+"nLine"]():this[l(1726)+l(558)]()}):this[r(798)+"X"]&&wx[r(1517)+r(486)+r(408)](({isConnected:o})=>{let l=r;this[l(983)+l(460)+l(484)]=o,o?this["_handleO"+l(1588)]():this[l(1726)+"ffLine"]()})}[t(1796)](r){let o={AcxIr:function(l,f,p){return e[G(515)](l,f,p)}};return new Promise(l=>{let f=G;o.AcxIr(setTimeout,l,this["_getInte"+f(353)+"e"](r))})}[t(1343)+t(986)](r=1e3,o="",l=!1){let f=t;this[f(1694)]&&this[f(432)+f(421)+"t"](r,o,l)}[t(1213)+"ut"](){let r=t,o=this[r(933)+r(953)]?.["getCurre"+r(743)+"nt"]();this[r(1365)](r(1746)+o+r(796)),this["_disconn"+r(986)](1001,r(1346)+r(1833)+r(1117)+"g",!0)}[t(904)](r){let o=t,l=e[o(1089)](Gt,r);this[o(1694)]&&e.FmKUh(this._ws[o(1473)+"te"],this[o(458)])&&(this[o(1694)]&&this._ws[o(1403)](l),this._debug(e[o(1091)],r))}[t(1212)+t(1069)+"rs"](){let r=t;if(e.zbSEx===e[r(705)])this[r(1418)]?.close(),this[r(1418)]=void 0;else{let o=e.ZwVuG[r(1512)]("|"),l=0;for(;;){switch(o[l++]){case"0":if(!this._ws)return;continue;case"1":this[r(1694)]["removeEv"+r(1016)+r(1552)](e[r(1791)],this[r(746)]);continue;case"2":this[r(1694)][r(1363)+"entListe"+r(1552)](e[r(869)],this._onClose);continue;case"3":this._ws[r(1363)+r(1016)+r(1552)](e.SkLsR,this._onOpen);continue;case"4":this._ws[r(1363)+r(1016)+r(1552)]("message",this[r(647)+"ge"]);continue}break}}}[t(1060)+t(1028)](){let r=t;this[r(1694)]&&(this[r(1694)]["addEvent"+r(1617)](e[r(1574)],this._onOpen),this[r(1694)][r(1195)+r(1617)](e.nooKa,this[r(373)]),this[r(1694)][r(1195)+r(1617)](e[r(396)],this._onMessage),this._ws[r(1195)+r(1617)](e[r(1791)],this[r(746)]))}["_wsInsta"+t(1599)](r=1e3,o=""){let l=t;try{this[l(1694)]&&this._ws[l(1458)](r,o)}catch{}}["_destroy"+t(421)+"t"](r=1e3,o="",l=!1){let f=t,p={ZTKcj:function(w,E){return e.EbFFG(w,E)},zAAQm:function(w,E){return e.Zqnev(w,E)},ApGQm:function(w,E){return e[G(347)](w,E)},jbXMT:function(w,E){return e[G(1410)](w,E)},VDXyX:function(w,E){return e[G(930)](w,E)}};if(e.gwmcC===e.hkptd){let w=_0x6d9420.charCodeAt(_0x6ecc5f);w>=55296&&dFlMhG[f(668)](w,56319)&&dFlMhG.zAAQm(dFlMhG.ApGQm(_0x57958c,1),_0x1ec12a)&&(w=dFlMhG.jbXMT(dFlMhG.VDXyX(w,10)+_0x52c634[f(554)+"At"](++_0x1b9552),56613888)),_0xc0be71+=w<128?1:dFlMhG[f(971)](w,2048)?2:dFlMhG[f(971)](w,65536)?3:4}else{if(this[f(487)+f(1744)](),this[f(690)+"mer"](),this["_removeW"+f(1069)+"rs"](),this[f(638)+f(1599)](1e3,o),this[f(654)+"Lock"]=!1,l&&this[f(1740)+f(1127)]()&&!this["_readyCl"+f(494)]){if(this["_endpoin"+f(953)]?.["checkRea"+f(1568)+"es"]()){let E=this["_endpoin"+f(953)]?.[f(1351)+f(743)+"nt"]();this[f(670)+f(883)+"ent"](wt(f(1458),{code:1006,reason:f(1746)+E+(f(796)+f(1116)+"tries re"+f(420)),wasClean:!0}))}else{let E=this[f(686)][f(619)+f(1321)+f(1496)](r,o);this[f(670)+f(883)+f(880)](e[f(1558)](wt,e[f(869)],{code:r,reason:o,wasClean:!0,willReconnect:E})),E&&this[f(654)]()}return}this[f(1740)+f(1127)]()||this["_readyCl"+f(494)]?this["_dispatchCloseEv"+f(880)](wt(f(1458),{code:r,reason:e[f(830)]})):this[f(670)+f(883)+f(880)](e.SVgfB(wt,e.nooKa,{code:1006,reason:e[f(562)]})),this[f(1694)]=null,this["_endpoin"+f(953)]?.[f(958)+f(894)+f(922)](),this[f(455)+f(847)]?.[f(549)+f(491)]()}}[t(670)+"hOpenEvent"](r){let o=t;this[o(478)](e[o(1574)],r),this[o(722)]&&this[o(722)](r)}[t(670)+t(1627)+t(427)](r){let o=t;this.emit(e[o(396)],r),this[o(1139)+"e"]&&this[o(1139)+"e"](r)}[t(670)+t(1565)+t(352)](r){let o=t;this[o(478)](e.fFwVb,r),this[o(1168)+"eAck"]&&this[o(1168)+o(1554)](r)}[t(670)+t(552)+t(880)](r){let o=t;this[o(478)](e[o(1791)],r),this.onerror&&this.onerror(r)}[t(670)+"hCloseEvent"](r){let o=t;this[o(478)](e[o(869)],r),this[o(889)]&&this[o(889)](r)}get[t(932)+"pe"](){let r=t;return this[r(1694)]?this[r(1694)][r(932)+"pe"]:this[r(1188)+"ype"]}set[t(932)+"pe"](r){let o=t;this["_binaryT"+o(1342)]=r,this[o(1694)]&&(this[o(1694)].binaryType=r)}get[t(985)+"nt"](){let r=t;return this[r(933)+r(953)]?.[r(1351)+r(743)+r(1467)+r(1029)]()||0}get["buffered"+t(1036)](){let r=t;return this._messageQueue.reduce((l,f)=>(l+=f&&f[G(1721)+"th"]||0,l),0)+(this[r(1694)]?this[r(1694)][r(736)+r(1036)]:0)}get[t(1308)+"ns"](){let r=t;return this[r(1694)]?this[r(1694)][r(1308)+"ns"]:""}get protocol(){let r=t;return this[r(1694)]?this[r(1694)][r(1227)]:""}get[t(1473)+"te"](){let r=t;return this._ws?this._ws.readyState:this[r(686)]["automati"+r(1386)]?this[r(731)+"NG"]:this[r(1671)]}get[t(1570)](){let r=t;return this[r(1694)]?this[r(1694)][r(1570)]:this._url}close(r=1e3,o){let l=t,f={ehtYw:function(p,w){return e.vxeLE(p,w)},uODSC:function(p,w){return p&w},KEJnG:function(p,w){return e[G(1110)](p,w)},dQazB:function(p,w){return p>=w},NQzRw:function(p,w){return e[G(1077)](p,w)},Grhjz:function(p,w){return p(w)}};if(l(698)===e[l(762)]){let p=e[l(1800)][l(1512)]("|"),w=0;for(;;){switch(p[w++]){case"0":this[l(646)+l(1756)+l(1617)]();continue;case"1":if(!this[l(1694)])return void this[l(1365)](e[l(599)]);continue;case"2":this[l(432)+l(421)+"t"](r,o);continue;case"3":if(e[l(1487)](this._ws[l(1473)+"te"],this.CLOSED)||this[l(1694)][l(1473)+"te"]===this[l(1152)])return void this[l(1365)](e[l(575)]);continue;case"4":this["_readyCl"+l(494)]=!0;continue;case"5":this._clearPingTimer();continue;case"6":this[l(1045)+l(544)]?.[l(642)]();continue;case"7":this["_clearTi"+l(1309)]();continue}break}}else _0xb42d3f=CfFbbb[l(1133)](CfFbbb[l(1133)]((15&_0x511a60)<<12,CfFbbb.uODSC(63,_0x48d3a8)<<6),CfFbbb.uODSC(63,_0x5cfad2)),CfFbbb.KEJnG(_0x924095,2048)||CfFbbb[l(1298)](_0x166bd2,55296)&&CfFbbb[l(1319)](_0x45fe93,57343)?_0x4995b0+=_0x312afe:(_0x5e74ff+=CfFbbb[l(1310)](_0x2f3119,_0x81bd46),_0x178158+=2)}async[t(1403)](r,o){let l=t;if(e[l(725)](null,r))throw new Error(e[l(1620)]);e[l(378)](e[l(1782)],typeof r)&&(r=JSON[l(588)+"y"](r)),e[l(749)]!=typeof r&&!e[l(906)](r,ArrayBuffer)&&!(r[l(966)]&&e[l(592)](r[l(966)],ArrayBuffer))&&(r=JSON[l(588)+"y"](r));let f=await e.jifTL(gl,r),p=e[l(818)](Fp,r),{method:w=0,service:E=this[l(686)][l(850)],logID:g=this[l(686)][l(659)+l(1154)](),headers:C=this._options[l(856)],payloadEncoding:L=this._options[l(1728)+l(1238)],payloadType:N=this[l(686)][l(735)+"ype"],logIDNew:$=this[l(686)].logIDNewConfig[l(931)+l(1691)+l(868)+"ew"]?e[l(800)](i,this[l(686)][l(1161)+"Config"][l(970)]):""}=e[l(773)](o,{});if(!E)throw new Error(e[l(1542)]);let se={SeqID:xe[l(861)+"er"](this[l(1411)]++),LogID:xe.fromNumber(g),service:E,method:w,headers:C,payloadEncoding:e[l(592)](L,Object)?L.encoding?L.encoding:"":L,payloadType:e[l(1131)](N,Object)?N[l(1059)]?N[l(1059)]:p:N||p,payload:f,LogIDNew:$},re=Gt(se);return this[l(1694)]&&e[l(1492)](this[l(1694)][l(1473)+"te"],this[l(458)])?(this[l(1694)]&&this[l(1694)][l(1403)](re),this._debug("sent",se)):e.DivVG(this[l(426)+l(371)][l(559)],this[l(686)][l(828)+l(1775)+l(448)])?(this[l(426)+l(371)].push(re),this[l(1365)](e[l(1049)],se)):(this[l(426)+l(371)][l(393)](),this[l(426)+l(371)][l(946)](re)),{seqID:this[l(1411)],logID:g,logIDNew:$}}async reconnect(r){let o=t,{url:l}=e[o(627)](r,{}),f=Array[o(1288)](l)?l:e[o(1659)](e.HwKCA,typeof l)?[l]:[];r&&Object.assign(this._options,r),f&&f[o(559)]?this[o(933)+o(953)]=new fl(f,this._options[o(1070)+"es"]):this[o(933)+o(953)]?.[o(958)+o(894)+o(922)](),this[o(455)+"sCounter"]?.[o(549)+o(491)](this[o(686)][o(1571)+"Count"]),this[o(790)+o(494)]=!1,this[o(1694)]&&this._ws[o(1473)+"te"]!==this.CLOSED?this[o(1343)+"ect"](1e3,e[o(1256)],!0):(this[o(1412)]=!0,this._connect())}async connect(){let r=t;!this[r(654)+r(1811)]&&(this[r(933)+r(953)]?.[r(958)+"pointCon"+r(922)](),this[r(455)+r(847)]?.resetCounter(),this[r(790)+"osed"]=!1,this._isInit=!0,this[r(654)]())}[t(1195)+t(1617)](r,o){this.on(r,o)}[t(1260)+t(427)](r){let o=t,{type:l}=r;this[o(478)](l,r)}["removeEventListe"+t(1552)](r,o){this[t(1290)](r,o)}[t(634)](){let r=t,o={rfpKm:function(l,f){return e.RSiXB(l,f)},ilMQR:function(l,f){return e.yYyPa(l,f)},fWEzi:function(l,f){return e[G(752)](l,f)},uERRC:function(l,f){return e.pPgoZ(l,f)},VIGCd:r(1748),UcQmU:function(l,f){return e[r(1742)](l,f)},ieSFP:e[r(1292)],tdGEq:e[r(1832)],ASJGl:r(1780)+r(1344)+"t",uKOeA:e[r(1590)]};return new Promise((l,f)=>{let p=r;this[p(487)+p(1744)](),this["_pingPon"+p(1166)+"Id"]=e.YhMpz(setTimeout,this[p(1200)][p(1785)](this),this[p(686)][p(982)+p(1258)]);let w=()=>{let g=p,C={VeJim:function(L,N){return o[G(1339)](L,N)},TjpXh:function(L,N){return L|N},SamPJ:function(L,N){return o.ilMQR(L,N)},EKxEO:function(L,N){return L<N},SdXxT:function(L,N){return o[G(624)](L,N)},sQxwS:function(L,N){return L>>N},zSCur:function(L,N){return L&N},EoOvi:function(L,N){return o[G(553)](L,N)}};o[g(1636)](o[g(1008)],o[g(1008)])?(o[g(370)](l,o[g(640)]),this[g(1290)](o[g(881)],w),this[g(1290)](o[g(744)],E)):(oCFSPw[g(534)](_0x56c388,2048)?_0x447c54[_0x186426++]=oCFSPw[g(769)](oCFSPw[g(1244)](_0x3bd6e1>>6,31),192):(oCFSPw[g(358)](_0x28cadc,65536)?_0x5c3a34[_0xe049a7++]=oCFSPw[g(1006)](oCFSPw[g(1244)](oCFSPw[g(1631)](_0x44cca9,12),15),224):(_0x5a52e8[_0x4c8bbe++]=oCFSPw[g(1006)](oCFSPw[g(1244)](oCFSPw.sQxwS(_0x1f1625,18),7),240),_0x34e9d6[_0x23ab28++]=oCFSPw.SamPJ(_0x5b928>>12,63)|128),_0x284676[_0x234d77++]=oCFSPw.SdXxT(oCFSPw.zSCur(_0x1bf7cb>>6,63),128)),_0x527adc[_0xda113b++]=oCFSPw[g(1006)](oCFSPw[g(623)](63,_0x2939ed),128))},E=()=>{let g=p;f(o[g(1129)]),this.off(o[g(881)],w),this[g(1290)](o.ASJGl,E)};this.on(e[p(1832)],w),this.on(e.uaajb,E),this[p(1200)]()})}}})(),oe[M(1019)+M(1214)]=Oe[M(1019)+M(1214)],oe[M(1121)+M(1638)]=Oe[M(1121)+M(1638)],oe.ErrorCode=Oe[M(1180)+"e"],oe[M(427)]=Oe.Event,oe[M(649)]=Oe[M(649)],oe[M(1602)+M(593)+M(1153)]=Oe[M(1602)+M(593)+M(1153)],oe[M(593)+"vent"]=Oe[M(593)+"vent"],oe.OpenEvent=Oe[M(822)+"t"],oe[M(662)+"tEvent"]=Oe[M(662)+M(436)],oe[M(548)+M(1214)]=Oe[M(548)+M(1214)],oe[M(1388)+M(1638)]=Oe.createErrorEvent,oe[M(1199)+M(361)+"nt"]=Oe[M(1199)+M(361)+"nt"],oe[M(727)+M(1252)]=Oe[M(727)+"enEvent"],oe[M(1444)+M(625)+M(1153)]=Oe["createRe"+M(625)+"vent"],oe[M(760)+M(1692)]=Oe[M(760)+M(1692)],oe[M(1362)+M(524)]=Oe[M(1362)+M(524)];for(Wo in Oe)[M(1019)+M(1214),M(1121)+"rorEvent","ErrorCode","Event",M(649),"Frontier"+M(593)+M(1153),M(593)+M(1153),"OpenEvent",M(662)+M(436),"createCl"+M(1214),M(1388)+M(1638),M(1199)+M(361)+"nt",M(727)+"enEvent","createReconnectE"+M(1153),M(760)+M(1692),M(1362)+M(524)][M(1173)](Wo)===-1&&(oe[Wo]=Oe[Wo]);var Wo;Object["definePr"+M(950)](oe,"__esModule",{value:!0})});import{existsSync as ES,openSync as vS}from"node:fs";import{mkdir as SS}from"node:fs/promises";import{dirname as IS}from"node:path";import{fileURLToPath as AS}from"node:url";function kS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Hd(t=X()){return ES(t.libEntry)?t.libEntry:AS(new URL("../index.ts",import.meta.url))}async function Kx(t={}){let e=t.paths??X(),n=t.entryOverride??Hd(e),i=kS(e,process.env.COZE_BRIDGE_LOG_MODE);await SS(IS(i),{recursive:!0});let s=vS(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=st(process.execPath,d,{detached:!0,stdio:["ignore",s,s],env:{...process.env,[os]:"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:n}),{pid:u.pid,entry:n}}var TS,os,na=rt(()=>{"use strict";Zt();ee();Be();TS=q("spawn-daemon"),os="COZE_BRIDGE_DAEMON"});import{spawn as S1}from"node:child_process";import{mkdir as I1,unlink as A1,writeFile as T1}from"node:fs/promises";import{dirname as k1,join as C1}from"node:path";function Yr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function D1(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${Yr(n)}</key>
21
+ <string>${Yr(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function R1(t,e){return new Promise((r,i)=>{let o=v1(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 $r,ss,sa,Zd,up=Qe(()=>{"use strict";ne();$r=H("supervisor.launchd"),ss="ai.coze.bridge",sa=R1,Zd={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function R1(t,e){return new Promise((n,i)=>{let s=S1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";s.stderr?.on("data",d=>{c+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var Zr,ds,ca,Qd,xp=rt(()=>{"use strict";ee();Zr=q("supervisor.launchd"),ds="ai.coze.bridge",ca=R1,Qd={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>${ss}</string>
31
+ <string>${ds}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Vr(t.nodeBin)}</string>
35
- <string>${Vr(t.entry)}</string>
34
+ <string>${Yr(t.nodeBin)}</string>
35
+ <string>${Yr(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>${Vr(t.logFile)}</string>
45
+ <string>${Yr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Vr(t.logFile)}</string>${C1(t.env)}
47
+ <string>${Yr(t.logFile)}</string>${D1(t.env)}
48
48
  </dict>
49
49
  </plist>
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"),$r.info("plist written",{plistPath:i,activate:r}),!r)return;await sa("launchctl",["unload","-w",i]).catch(c=>$r.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await sa("launchctl",["load","-w",i]),$r.info("launchd job loaded",{label:ss});let o=process.getuid?.()??0;await sa("launchctl",["kickstart","-k",`gui/${o}/${ss}`]),$r.info("launchd job kickstarted",{label:ss,uid:o})},async uninstall(t){let e=this.configPath(t);await sa("launchctl",["unload","-w",e]).catch(r=>$r.warn("launchctl unload failed (ignored)",{err:String(r)})),await I1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),$r.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 fp}from"node:path";function aa(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 ca(t,e){return new Promise((r,i)=>{let o=P1(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 oa,Zr,M1,Yd,hp=Qe(()=>{"use strict";ne();oa=H("supervisor.systemd"),Zr="coze-bridge.service",M1="/etc/systemd/system";Yd={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return C1(t.homeDir,"Library","LaunchAgents",`${ds}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await I1(k1(i),{recursive:!0}),await T1(i,this.renderConfig(t),"utf8"),Zr.info("plist written",{plistPath:i,activate:n}),!n)return;await ca("launchctl",["unload","-w",i]).catch(c=>Zr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ca("launchctl",["load","-w",i]),Zr.info("launchd job loaded",{label:ds});let s=process.getuid?.()??0;await ca("launchctl",["kickstart","-k",`gui/${s}/${ds}`]),Zr.info("launchd job kickstarted",{label:ds,uid:s})},async uninstall(t){let e=this.configPath(t);await ca("launchctl",["unload","-w",e]).catch(n=>Zr.warn("launchctl unload failed (ignored)",{err:String(n)})),await A1(e).catch(n=>{if(n.code!=="ENOENT")throw n}),Zr.info("launchd job removed",{plistPath:e})}}});import{spawn as P1}from"node:child_process";import{mkdir as O1,unlink as L1,writeFile as N1}from"node:fs/promises";import{dirname as M1,join as pp}from"node:path";function la(t,e){return t.isRoot?e:["--user",...e]}function F1(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function ua(t,e){return new Promise((n,i)=>{let s=P1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";s.stderr?.on("data",d=>{c+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var da,Xr,B1,el,gp=rt(()=>{"use strict";ee();da=q("supervisor.systemd"),Xr="coze-bridge.service",B1="/etc/systemd/system";el={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
- ${B1(t.env)}
62
+ ${F1(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?fp(M1,Zr):fp(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"),oa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await ca("systemctl",aa(t,["daemon-reload"])),await ca("systemctl",aa(t,r?["enable","--now",Zr]:["enable",Zr])),oa.info("systemd unit enabled",{unitName:Zr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await ca("systemctl",aa(t,["disable","--now",Zr])).catch(r=>oa.warn("systemctl disable failed (ignored)",{err:String(r)})),await O1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await ca("systemctl",aa(t,["daemon-reload"])).catch(()=>{}),oa.info("systemd unit removed",{unitPath:e})}}});import{spawn as F1}from"node:child_process";import{join as z1}from"node:path";function xp(t,e){return new Promise((r,i)=>{let o=F1(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 Jd,da,Xd,pp=Qe(()=>{"use strict";ne();Jd=H("supervisor.taskscheduler"),da="CozeBridge",Xd={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?pp(B1,Xr):pp(t.homeDir,".config","systemd","user",Xr)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),s=t.isRoot?"system":"user";await O1(M1(i),{recursive:!0}),await N1(i,this.renderConfig(t),"utf8"),da.info("systemd unit written",{unitPath:i,mode:s,activate:n}),await ua("systemctl",la(t,["daemon-reload"])),await ua("systemctl",la(t,n?["enable","--now",Xr]:["enable",Xr])),da.info("systemd unit enabled",{unitName:Xr,mode:s,activate:n})},async uninstall(t){let e=this.configPath(t);await ua("systemctl",la(t,["disable","--now",Xr])).catch(n=>da.warn("systemctl disable failed (ignored)",{err:String(n)})),await L1(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await ua("systemctl",la(t,["daemon-reload"])).catch(()=>{}),da.info("systemd unit removed",{unitPath:e})}}});import{spawn as z1}from"node:child_process";import{join as U1}from"node:path";function mp(t,e){return new Promise((n,i)=>{let s=z1(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";s.stderr?.on("data",d=>{c+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var tl,fa,nl,wp=rt(()=>{"use strict";ee();tl=q("supervisor.taskscheduler"),fa="CozeBridge",nl={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,50 +86,50 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
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 xp("schtasks",["/Create","/SC","ONLOGON","/TN",da,"/TR",r,"/RU",t.userName,"/F"]),Jd.info("task scheduler entry created",{task:da,logFile:t.logFile})},async uninstall(t){await xp("schtasks",["/Delete","/TN",da,"/F"]).catch(e=>Jd.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Jd.info("task scheduler entry removed",{task:da})}}});var gp={};Sa(gp,{buildContext:()=>W1,getSupervisor:()=>H1,launchdSupervisor:()=>Zd,systemdSupervisor:()=>Yd,taskSchedulerSupervisor:()=>Xd});import{homedir as U1,userInfo as G1}from"node:os";function H1(t=process.platform){switch(t){case"darwin":return Zd;case"linux":return Yd;case"win32":return Xd;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=ee();return{nodeBin:process.execPath,entry:Ud(t),logFile:t.logFile,homeDir:U1(),userName:G1().username,isRoot:process.getuid?.()===0,env:j1()}}var q1,mp=Qe(()=>{"use strict";Oe();Xo();up();hp();pp();q1=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();sn();var Tl=H("acp-installer-warmup"),qg=["claude-code","codex"];async function Cl(t={}){let e=t.ensure??ar,i=(await Promise.allSettled(qg.map(async o=>{let c=await e(o);Tl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Tl.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();ne();import{readdir as sm}from"node:fs/promises";import{mkdir as Ol,readFile as rm,writeFile as Ll}from"node:fs/promises";import{join as Pa}from"node:path";var im={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function lr(t,e,r){await Ol(t,{recursive:!0});let i=im[e],o=Pa(t,i);return await Ll(o,r??"","utf8"),o}async function Da(t,e,r){let i=Pa(t,".claude");await Ol(i,{recursive:!0});let o=Pa(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 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 Ll(o,JSON.stringify(c,null,2),"utf8"),o}var Ye=H("agent-detail-sync"),om=6e4,am=5*6e4,gs=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){Ye.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Ye.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){Ye.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(l){Ye.warn("detail sync failed for agent, skipping",{agentId:o,err:String(l)})}}})),Ye.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){Ye.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Ye.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){Ye.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){Ye.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),g=x?Math.min(x.currentDelay*2,am):om;this.retryQueue.set(e,{dueAt:Date.now()+g,currentDelay:g});return}if(o.agentId&&o.agentId!==e){Ye.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"?(Ye.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Ye.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Ye.debug("detail sync: no diff",{agentId:e});return}await Be(i,this.opts.paths),Ye.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}),Ye.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await lr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Qc=Ut(hu(),1);import{createHash as H_}from"node:crypto";import{lstat as Kc,mkdir as $c,readFile as co,readdir as Jf,rm as Vc,stat as Vf,writeFile as Zc}from"node:fs/promises";import{dirname as q_,join as Ke,normalize as j_,relative as Xc,resolve as Yc,sep as Xf}from"node:path";import{Readable as Qf}from"node:stream";import{pipeline as e0}from"node:stream/promises";import Cm from"events";import et from"fs";import{EventEmitter as Pc}from"node:events";import Vu from"node:stream";import{StringDecoder as Rm}from"node:string_decoder";import Ju from"node:path";import br from"node:fs";import{dirname as qm,parse as jm}from"path";import{EventEmitter as Xm}from"events";import fc from"assert";import{Buffer as Hn}from"buffer";import*as wu from"zlib";import Qm from"zlib";import{posix as pr}from"node:path";import{basename as Aw}from"node:path";import Vs from"fs";import Ct from"fs";import Iu from"path";import{win32 as Fw}from"node:path";import Du from"path";import hf from"node:fs";import t_ from"node:assert";import{randomBytes as xf}from"node:crypto";import ie from"node:fs";import Ne from"node:path";import pf from"fs";import ro from"node:fs";import Si from"node:path";import st from"node:fs";import c_ from"node:fs/promises";import Js from"node:path";import{join as Af}from"node:path";import it from"node:fs";import Cf from"node:path";var km=Object.defineProperty,Tm=(t,e)=>{for(var r in e)km(t,r,{get:e[r],enumerable:!0})},xu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Pm=t=>!!t&&typeof t=="object"&&(t instanceof Wn||t instanceof Vu||Dm(t)||Om(t)),Dm=t=>!!t&&typeof t=="object"&&t instanceof Pc&&typeof t.pipe=="function"&&t.pipe!==Vu.Writable.prototype.pipe,Om=t=>!!t&&typeof t=="object"&&t instanceof Pc&&typeof t.write=="function"&&typeof t.end=="function",Gt=Symbol("EOF"),Ht=Symbol("maybeEmitEnd"),ln=Symbol("emittedEnd"),Es=Symbol("emittingEnd"),ai=Symbol("emittedError"),bs=Symbol("closed"),pu=Symbol("read"),vs=Symbol("flush"),gu=Symbol("flushChunk"),pt=Symbol("encoding"),xr=Symbol("decoder"),Fe=Symbol("flowing"),ci=Symbol("paused"),_r=Symbol("resume"),ze=Symbol("buffer"),Je=Symbol("pipes"),Ue=Symbol("bufferLength"),Fa=Symbol("bufferPush"),Ss=Symbol("bufferShift"),Ze=Symbol("objectMode"),Se=Symbol("destroyed"),za=Symbol("error"),Ua=Symbol("emitData"),mu=Symbol("emitEnd"),Ga=Symbol("emitEnd2"),At=Symbol("async"),Ha=Symbol("abort"),Is=Symbol("aborted"),di=Symbol("signal"),On=Symbol("dataListeners"),rt=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),Zu=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 Zu{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 Pc{[Fe]=!1;[ci]=!1;[Je]=[];[ze]=[];[Ze];[pt];[At];[xr];[Gt]=!1;[ln]=!1;[Es]=!1;[bs]=!1;[ai]=null;[Ue]=0;[Se]=!1;[di];[Is]=!1;[On]=0;[rt]=!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[pt]=null):Um(e)?(this[pt]=e.encoding,this[Ze]=!1):(this[Ze]=!1,this[pt]=null),this[At]=!!e.async,this[xr]=this[pt]?new Rm(this[pt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[ze]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Je]});let{signal:r}=e;r&&(this[di]=r,r.aborted?this[Ha]():r.addEventListener("abort",()=>this[Ha]()))}get bufferLength(){return this[Ue]}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[Ze]}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}[Ha](){this[Is]=!0,this.emit("abort",this[di]?.reason),this.destroy(this[di]?.reason)}get aborted(){return this[Is]}set aborted(t){}write(t,e,r){if(this[Is])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[At]?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[Fe]&&this[Ue]!==0&&this[vs](!0),this[Fe]?this.emit("data",t):this[Fa](t),this[Ue]!==0&&this.emit("readable"),r&&i(r),this[Fe]):t.length?(typeof t=="string"&&!(e===this[pt]&&!this[xr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[pt]&&(t=this[xr].write(t)),this[Fe]&&this[Ue]!==0&&this[vs](!0),this[Fe]?this.emit("data",t):this[Fa](t),this[Ue]!==0&&this.emit("readable"),r&&i(r),this[Fe]):(this[Ue]!==0&&this.emit("readable"),r&&i(r),this[Fe])}read(t){if(this[Se])return null;if(this[rt]=!1,this[Ue]===0||t===0||t&&t>this[Ue])return this[Ht](),null;this[Ze]&&(t=null),this[ze].length>1&&!this[Ze]&&(this[ze]=[this[pt]?this[ze].join(""):Buffer.concat(this[ze],this[Ue])]);let e=this[pu](t||null,this[ze][0]);return this[Ht](),e}[pu](t,e){if(this[Ze])this[Ss]();else{let r=e;t===r.length||t===null?this[Ss]():typeof r=="string"?(this[ze][0]=r.slice(t),e=r.slice(0,t),this[Ue]-=t):(this[ze][0]=r.subarray(t),e=r.subarray(0,t),this[Ue]-=t)}return this.emit("data",e),!this[ze].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[Fe]||!this[ci])&&this[Ht](),this}[_r](){this[Se]||(!this[On]&&!this[Je].length&&(this[rt]=!0),this[ci]=!1,this[Fe]=!0,this.emit("resume"),this[ze].length?this[vs]():this[Gt]?this[Ht]():this.emit("drain"))}resume(){return this[_r]()}pause(){this[Fe]=!1,this[ci]=!0,this[rt]=!1}get destroyed(){return this[Se]}get flowing(){return this[Fe]}get paused(){return this[ci]}[Fa](t){this[Ze]?this[Ue]+=1:this[Ue]+=t.length,this[ze].push(t)}[Ss](){return this[Ze]?this[Ue]-=1:this[Ue]-=this[ze][0].length,this[ze].shift()}[vs](t=!1){do;while(this[gu](this[Ss]())&&this[ze].length);!t&&!this[ze].length&&!this[Gt]&&this.emit("drain")}[gu](t){return this.emit("data",t),this[Fe]}pipe(t,e){if(this[Se])return t;this[rt]=!1;let r=this[ln];return e=e||{},t===xu.stdout||t===xu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Je].push(e.proxyErrors?new Fm(this,t,e):new Zu(this,t,e)),this[At]?li(()=>this[_r]()):this[_r]()),t}unpipe(t){let e=this[Je].find(r=>r.dest===t);e&&(this[Je].length===1?(this[Fe]&&this[On]===0&&(this[Fe]=!1),this[Je]=[]):this[Je].splice(this[Je].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[rt]=!1,this[On]++,!this[Je].length&&!this[Fe]&&this[_r]();else if(t==="readable"&&this[Ue]!==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[At]?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[rt]&&!this[Je].length&&(this[Fe]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[On]=0,!this[rt]&&!this[Je].length&&(this[Fe]=!1)),e}get emittedEnd(){return this[ln]}[Ht](){!this[Es]&&!this[ln]&&!this[Se]&&this[ze].length===0&&this[Gt]&&(this[Es]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[bs]&&this.emit("close"),this[Es]=!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[At]?(li(()=>this[Ua](r)),!0):this[Ua](r);if(t==="end")return this[mu]();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(za,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}[Ua](t){for(let r of this[Je])r.dest.write(t)===!1&&this.pause();let e=this[rt]?!1:super.emit("data",t);return this[Ht](),e}[mu](){return this[ln]?!1:(this[ln]=!0,this.readable=!1,this[At]?(li(()=>this[Ga]()),!0):this[Ga]())}[Ga](){if(this[xr]){let e=this[xr].end();if(e){for(let r of this[Je])r.dest.write(e);this[rt]||super.emit("data",e)}}for(let e of this[Je])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[pt]?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[rt]=!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",l),this.off("end",u),this.off(Se,f),e(),o(x)},l=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",l),this.off(Se,f),e(),i({done:!0,value:void 0})},f=()=>c(new Error("stream destroyed"));return new Promise((x,g)=>{o=g,i=x,this.once(Se,f),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[rt]=!1;let t=!1,e=()=>(this.pause(),this.off(za,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(za,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[rt]=!0,this[ze].length=0,this[Ue]=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"),_t=Symbol("_close"),ui=Symbol("_ended"),de=Symbol("_fd"),qa=Symbol("_finished"),Kt=Symbol("_flags"),ja=Symbol("_flush"),lc=Symbol("_handleChunk"),uc=Symbol("_makeBuf"),bi=Symbol("_mode"),As=Symbol("_needDrain"),Sr=Symbol("_onerror"),Ir=Symbol("_onopen"),Wa=Symbol("_onread"),yr=Symbol("_onwrite"),En=Symbol("_open"),wt=Symbol("_path"),pn=Symbol("_pos"),kt=Symbol("_queue"),Er=Symbol("_read"),Ka=Symbol("_readSize"),Wt=Symbol("_reading"),fi=Symbol("_remain"),$a=Symbol("_size"),Ms=Symbol("_write"),Ln=Symbol("_writing"),Bs=Symbol("_defaultFlag"),Gn=Symbol("_errored"),Dc=class extends Wn{[Gn]=!1;[de];[wt];[Ka];[Wt]=!1;[$a];[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[de]=typeof e.fd=="number"?e.fd:void 0,this[wt]=t,this[Ka]=e.readSize||16*1024*1024,this[Wt]=!1,this[$a]=typeof e.size=="number"?e.size:1/0,this[fi]=this[$a],this[yn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[de]=="number"?this[Er]():this[En]()}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")}[En](){et.open(this[wt],"r",(t,e)=>this[Ir](t,e))}[Ir](t,e){t?this[Sr](t):(this[de]=e,this.emit("open",e),this[Er]())}[uc](){return Buffer.allocUnsafe(Math.min(this[Ka],this[fi]))}[Er](){if(!this[Wt]){this[Wt]=!0;let t=this[uc]();if(t.length===0)return process.nextTick(()=>this[Wa](null,0,t));et.read(this[de],t,0,t.length,null,(e,r,i)=>this[Wa](e,r,i))}}[Wa](t,e,r){this[Wt]=!1,t?this[Sr](t):this[lc](e,r)&&this[Er]()}[_t](){if(this[yn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Sr](t){this[Wt]=!0,this[_t](),this.emit("error",t)}[lc](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[_t](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[de]=="number"&&this[Er](),!1;case"error":return this[Gn]?!1:(this[Gn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Hm=class extends Dc{[En](){let t=!0;try{this[Ir](null,et.openSync(this[wt],"r")),t=!1}finally{t&&this[_t]()}}[Er](){let t=!0;try{if(!this[Wt]){this[Wt]=!0;do{let e=this[uc](),r=e.length===0?0:et.readSync(this[de],e,0,e.length,null);if(!this[lc](r,e))break}while(!0);this[Wt]=!1}t=!1}finally{t&&this[_t]()}}[_t](){if(this[yn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.closeSync(t),this.emit("close")}}},Xs=class extends Cm{readable=!1;writable=!0;[Gn]=!1;[Ln]=!1;[ui]=!1;[kt]=[];[As]=!1;[wt];[bi];[yn];[de];[Bs];[Kt];[qa]=!1;[pn];constructor(t,e){e=e||{},super(e),this[wt]=t,this[de]=typeof e.fd=="number"?e.fd:void 0,this[bi]=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[Bs]=e.flags===void 0,this[Kt]=e.flags===void 0?r:e.flags,this[de]===void 0&&this[En]()}emit(t,...e){if(t==="error"){if(this[Gn])return!1;this[Gn]=!0}return super.emit(t,...e)}get fd(){return this[de]}get path(){return this[wt]}[Sr](t){this[_t](),this[Ln]=!0,this.emit("error",t)}[En](){et.open(this[wt],this[Kt],this[bi],(t,e)=>this[Ir](t,e))}[Ir](t,e){this[Bs]&&this[Kt]==="r+"&&t&&t.code==="ENOENT"?(this[Kt]="w",this[En]()):t?this[Sr](t):(this[de]=e,this.emit("open",e),this[Ln]||this[ja]())}end(t,e){return t&&this.write(t,e),this[ui]=!0,!this[Ln]&&!this[kt].length&&typeof this[de]=="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[de]===void 0||this[Ln]||this[kt].length?(this[kt].push(t),this[As]=!0,!1):(this[Ln]=!0,this[Ms](t),!0)}[Ms](t){et.write(this[de],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[kt].length?this[ja]():(this[Ln]=!1,this[ui]&&!this[qa]?(this[qa]=!0,this[_t](),this.emit("finish")):this[As]&&(this[As]=!1,this.emit("drain"))))}[ja](){if(this[kt].length===0)this[ui]&&this[yr](null,0);else if(this[kt].length===1)this[Ms](this[kt].pop());else{let t=this[kt];this[kt]=[],Gm(this[de],t,this[pn],(e,r)=>this[yr](e,r))}}[_t](){if(this[yn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Yu=class extends Xs{[En](){let t;if(this[Bs]&&this[Kt]==="r+")try{t=et.openSync(this[wt],this[Kt],this[bi])}catch(e){if(e?.code==="ENOENT")return this[Kt]="w",this[En]();throw e}else t=et.openSync(this[wt],this[Kt],this[bi]);this[Ir](null,t)}[_t](){if(this[yn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.closeSync(t),this.emit("close")}}[Ms](t){let e=!0;try{this[yr](null,et.writeSync(this[de],t,0,t.length,this[pn])),e=!1}finally{if(e)try{this[_t]()}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"]]),Km=t=>!!t.sync&&!!t.file,$m=t=>!t.sync&&!!t.file,Vm=t=>!!t.sync&&!t.file,Zm=t=>!t.sync&&!t.file,Ym=t=>!!t.file,Jm=t=>Wm.get(t)||t,Oc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=Jm(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=[],l,u)=>{Array.isArray(c)&&(l=c,c={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let f=Oc(c);if(o?.(f,l),Km(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,l)}else if($m(f)){let x=e(f,l);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,l)}else if(Zm(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,l)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),ew=Qm.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},ew)),tw=Hn.concat,_u=Object.getOwnPropertyDescriptor(Hn,"concat"),nw=t=>t,Va=_u?.writable===!0||_u?.set!==void 0?t=>{Hn.concat=t?nw:tw}:t=>{},qn=Symbol("_superWrite"),ks=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"}},Za=Symbol("flushFlag"),Lc=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 wu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new wu[e](t)}catch(r){throw new ks(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 ks(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return fc(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),{[Za]: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;fc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Va(!0);let l;try{let f=typeof t[Za]=="number"?t[Za]:this.#r;l=this.#t._processChunk(t,f),Va(!1)}catch(f){Va(!1),this.#o(new ks(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 ks(f,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let f=l[0];u=this[qn](Hn.from(f));for(let x=1;x<l.length;x++)u=this[qn](l[x])}else u=this[qn](Hn.from(l));return r&&r(),u}},Xu=class extends Lc{#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),fc(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 Xu{#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 Xu{constructor(t){super(t,"Unzip")}},Qu=class extends Lc{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)}},sw=class extends Qu{constructor(t){super(t,"BrotliCompress")}},ow=class extends Qu{constructor(t){super(t,"BrotliDecompress")}},ef=class extends Lc{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)}},aw=class extends ef{constructor(t){super(t,"ZstdCompress")}},cw=class extends ef{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]=tf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=nf(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]),l;i?l=tf(c):c===0?l=c:(i=!0,l=nf(c)),l!==0&&(r-=l*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},tf=t=>(255^t)&255,nf=t=>(255^t)+1&255,pw={};Tm(pw,{code:()=>Nc,isCode:()=>Fs,isName:()=>gw,name:()=>Qs,normalFsTypes:()=>rf});var Fs=t=>Qs.has(t),gw=t=>Nc.has(t),rf=new Set(["0","","1","2","3","4","5","6","7","D"]),Qs=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"]]),Nc=new Map(Array.from(Qs).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=rf.has(o),l=c?r:void 0,u=c?i:void 0;if(this.path=l?.path??Nn(t,e,100),this.mode=l?.mode??u?.mode??gn(t,e+100,8),this.uid=l?.uid??u?.uid??gn(t,e+108,8),this.gid=l?.gid??u?.gid??gn(t,e+116,8),this.size=l?.size??u?.size??gn(t,e+124,12),this.mtime=l?.mtime??u?.mtime??Ya(t,e+136,12),this.cksum=gn(t,e+148,12),u&&this.#n(u,!0),l&&this.#n(l),Fs(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=l?.uname??u?.uname??Nn(t,e+265,32),this.gname=l?.gname??u?.gname??Nn(t,e+297,32),this.devmaj=l?.devmaj??u?.devmaj??gn(t,e+329,8)??0,this.devmin=l?.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??Ya(t,e+476,12),this.ctime=r?.ctime??i?.ctime??Ya(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=Ja(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=Ja(t,e+476,12,this.atime)||this.needPax,this.needPax=Ja(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,mn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Qs.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Nc.get(t));if(Fs(e)||e==="Unsupported")this.#e=e;else if(Fs(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.*/,""),Ya=(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)),Ew={12:8589934591,8:2097151},mn=(t,e,r,i)=>i===void 0?!1:i>Ew[r]||i<0?(dw(i,t.subarray(e,e+r)),!0):(bw(t,e,r,i),!1),bw=(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",Ja=(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 sf{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),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 sf(kw(Tw(e),r),i)}},kw=(t,e)=>e?Object.assign({},e,t):t,Tw=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(Cw,Object.create(null)),Cw=(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},Rw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=Rw!=="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=Q(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?Q(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=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},eo=(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,hc=Buffer.from([31,139]),xc=Buffer.from([40,181,47,253]),Ow=Math.max(hc.length,xc.length),ct=Symbol("state"),Bn=Symbol("writeEntry"),qt=Symbol("readEntry"),Xa=Symbol("nextEntry"),yu=Symbol("processEntry"),Tt=Symbol("extendedHeader"),hi=Symbol("globalExtendedHeader"),un=Symbol("meta"),Eu=Symbol("emitMeta"),ge=Symbol("buffer"),jt=Symbol("queue"),fn=Symbol("ended"),Qa=Symbol("emittedEnd"),Fn=Symbol("emit"),Te=Symbol("unzip"),Ts=Symbol("consumeChunk"),Cs=Symbol("consumeChunkSub"),ec=Symbol("consumeBody"),bu=Symbol("consumeMeta"),vu=Symbol("consumeHeader"),xi=Symbol("consuming"),tc=Symbol("bufferConcat"),Rs=Symbol("maybeEnd"),gr=Symbol("writing"),hn=Symbol("aborted"),Ps=Symbol("onDone"),zn=Symbol("sawValidEntry"),Ds=Symbol("sawNullBlock"),Os=Symbol("sawEOF"),Su=Symbol("closeStream"),Lw=()=>!0,Ri=class extends Xm{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[jt]=[];[ge];[qt];[Bn];[ct]="begin";[un]="";[Tt];[hi];[fn]=!1;[Te];[hn]=!1;[zn];[Ds]=!1;[Os]=!1;[gr]=!1;[xi]=!1;[Qa]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ps,()=>{(this[ct]==="begin"||this[zn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ps,t.ondone):this.on(Ps,()=>{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[Su]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){eo(this,t,e,r)}[vu](t,e){this[zn]===void 0&&(this[zn]=!1);let r;try{r=new jn(t,e,this[Tt],this[hi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Ds]?(this[Os]=!0,this[ct]==="begin"&&(this[ct]="header"),this[Fn]("eof")):(this[Ds]=!0,this[Fn]("nullBlock"));else if(this[Ds]=!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[Tt],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[ct]="ignore",o.resume()):o.size>0&&(this[un]="",o.on("data",c=>this[un]+=c),this[ct]="meta"):(this[Tt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Fn]("ignoredEntry",o),this[ct]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ct]="body":(this[ct]="header",o.end()),this[qt]?this[jt].push(o):(this[jt].push(o),this[Xa]())))}}}[Su](){queueMicrotask(()=>this.emit("close"))}[yu](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[Xa]()),e=!1);return e}[Xa](){do;while(this[yu](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"))}}[ec](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[ct]="header",this[Bn]=void 0,r.end()),o.length}[bu](t,e){let r=this[Bn],i=this[ec](t,e);return!this[Bn]&&r&&this[Eu](r),i}[Fn](t,e,r){this[jt].length===0&&!this[qt]?this.emit(t,e,r):this[jt].push([t,e,r])}[Eu](t){switch(this[Fn]("meta",this[un]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Tt]=$s.parse(this[un],this[Tt],!1);break;case"GlobalExtendedHeader":this[hi]=$s.parse(this[un],this[hi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Tt]??Object.create(null);this[Tt]=e,e.path=this[un].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Tt]||Object.create(null);this[Tt]=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 l=0;this[Te]===void 0&&l<hc.length;l++)t[l]!==hc[l]&&(this[Te]=!1);let o=!1;if(this[Te]===!1&&this.zstd!==!1){o=!0;for(let l=0;l<xc.length;l++)if(t[l]!==xc[l]){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 l=this[fn];this[fn]=!1,this[Te]=this[Te]===void 0?new iw({}):o?new cw({}):new ow({}),this[Te].on("data",f=>this[Ts](f)),this[Te].on("error",f=>this.abort(f)),this[Te].on("end",()=>{this[fn]=!0,this[Ts]()}),this[gr]=!0;let u=!!this[Te][l?"end":"write"](t);return this[gr]=!1,r?.(),u}}this[gr]=!0,this[Te]?this[Te].write(t):this[Ts](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}[tc](t){t&&!this[hn]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[Rs](){if(this[fn]&&!this[Qa]&&!this[hn]&&!this[xi]){this[Qa]=!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](Ps)}}[Ts](t){if(this[xi]&&t)this[tc](t);else if(!t&&!this[ge])this[Rs]();else if(t){if(this[xi]=!0,this[ge]){this[tc](t);let e=this[ge];this[ge]=void 0,this[Cs](e)}else this[Cs](t);for(;this[ge]&&this[ge]?.length>=512&&!this[hn]&&!this[Os];){let e=this[ge];this[ge]=void 0,this[Cs](e)}this[xi]=!1}(!this[ge]||this[fn])&&this[Rs]()}[Cs](t){let e=0,r=t.length;for(;e+512<=r&&!this[hn]&&!this[Os];)switch(this[ct]){case"begin":case"header":this[vu](t,e),e+=512;break;case"ignore":case"body":e+=this[ec](t,e);break;case"meta":e+=this[bu](t,e);break;default:throw new Error("invalid state: "+this[ct])}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()},of=(t,e)=>{let r=new Map(e.map(c=>[vi(c),!0])),i=t.filter,o=(c,l="")=>{let u=l||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,l)=>i(c,l)&&o(vi(c)):c=>o(vi(c))},Mw=t=>{let e=new Ri(t),r=t.file,i;try{i=br.openSync(r,"r");let o=br.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let l=Buffer.allocUnsafe(o.size),u=br.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 f=br.readSync(i,u,0,c,l);if(f===0)break;l+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{br.closeSync(i)}catch{}}},Bw=(t,e)=>{let r=new Ri(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("end",c),br.stat(o,(u,f)=>{if(u)l(u);else{let x=new Dc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Ar=Pi(Mw,Bw,t=>new Ri(t),t=>new Ri(t),(t,e)=>{e?.length&&of(t,e),t.noResume||Nw(t)}),af=(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:Au}=Fw,Mc=t=>{let e="",r=Au(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=Au(t)}return[e,t]},to=["|","<",">","?",":"],Bc=to.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Uw=new Map(to.map((t,e)=>[t,Bc[e]])),Gw=new Map(Bc.map((t,e)=>[t,to[e]])),ku=t=>to.reduce((e,r)=>e.split(r).join(Uw.get(r)),t),Hw=t=>Bc.reduce((e,r)=>e.split(r).join(Gw.get(r)),t),cf=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),vi(e)+"/"+t):Q(t),qw=16*1024*1024,Tu=Symbol("process"),Cu=Symbol("file"),Ru=Symbol("directory"),pc=Symbol("symlink"),Pu=Symbol("hardlink"),pi=Symbol("header"),zs=Symbol("read"),gc=Symbol("lstat"),Us=Symbol("onlstat"),mc=Symbol("onread"),wc=Symbol("onreadlink"),_c=Symbol("openfile"),yc=Symbol("onopenfile"),wn=Symbol("close"),Zs=Symbol("mode"),Ec=Symbol("awaitDrain"),nc=Symbol("ondrain"),Rt=Symbol("prefix"),df=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=Oc(e);super(),this.path=Q(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=Q(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Q(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]=Mc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=Hw(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||Iu.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[Us](o):this[gc]()}warn(t,e,r={}){return eo(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[gc](){Ct.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Us](e)})}[Us](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Kw(t),this.emit("stat",t),this[Tu]()}[Tu](){switch(this.type){case"File":return this[Cu]();case"Directory":return this[Ru]();case"SymbolicLink":return this[pc]();default:return this.end()}}[Zs](t){return af(t,this.type==="Directory",this.portable)}[Rt](t){return cf(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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](this.linkpath):this.linkpath,mode:this[Zs](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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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()}[pc](){Ct.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[wc](e)})}[wc](t){this.linkpath=Q(t),this[pi](),this.end()}[Pu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Iu.relative(this.cwd,t)),this.stat.size=0,this[pi](),this.end()}[Cu](){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[Pu](e);this.linkCache.set(t,this.absolute)}if(this[pi](),this.stat.size===0)return this.end();this[_c]()}[_c](){Ct.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[yc](e)})}[yc](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[zs]()}[zs](){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,l)=>{if(c)return this[wn](()=>this.emit("error",c));this[mc](l)})}[wn](t=()=>{}){this.fd!==void 0&&Ct.close(this.fd,t)}[mc](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[nc]():this[Ec](()=>this[nc]())}[Ec](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)}[nc](){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[zs]()}},jw=class extends df{sync=!0;[gc](){this[Us](Ct.lstatSync(this.absolute))}[pc](){this[wc](Ct.readlinkSync(this.absolute))}[_c](){this[yc](Ct.openSync(this.absolute,"r"))}[zs](){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=Ct.readSync(e,r,i,o,c);this[mc](l),t=!1}finally{if(t)try{this[wn](()=>{})}catch{}}}[Ec](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 eo(this,t,e,r)}constructor(t,e={}){let r=Oc(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=Q(t.path),this.mode=t.mode!==void 0?this[Zs](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?Q(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[l,u]=Mc(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 jn({path:this[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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)}[Rt](t){return cf(t,this.prefix)}[Zs](t){return af(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}},Kw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",$w=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++)Yw(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 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=Vw(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 Vw(t,e,r){let i=e,o=e?e.next:t.head,c=new Fc(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 Fc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Yw(t,e){t.head=new Fc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Fc=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}},Ou=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Lu=Buffer.alloc(1024),Gs=Symbol("onStat"),gi=Symbol("ended"),gt=Symbol("queue"),mi=Symbol("pendingLinks"),xn=Symbol("current"),Un=Symbol("process"),wi=Symbol("processing"),Ls=Symbol("processJob"),mt=Symbol("jobs"),rc=Symbol("jobDone"),Hs=Symbol("addFSEntry"),Nu=Symbol("addTarEntry"),bc=Symbol("stat"),vc=Symbol("readdir"),qs=Symbol("onreaddir"),js=Symbol("pipe"),Mu=Symbol("entry"),ic=Symbol("entryOpt"),Ws=Symbol("writeEntryClass"),lf=Symbol("write"),sc=Symbol("ondrain"),no=class extends Wn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Ws];onWriteEntry;[gt];[mi]=new Map;[mt]=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=Q(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[Ws]=df,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[sc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[sc]);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 $w,this[mt]=0,this.jobs=Number(t.jobs)||4,this[wi]=!1,this[gi]=!1}[lf](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[Hs](t):this[Nu](t),this.flowing}[Nu](t){let e=Q(Du.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Ou(t.path,e);r.entry=new Ww(t,this[ic](r)),r.entry.on("end",()=>this[rc](r)),this[mt]+=1,this[gt].push(r)}this[Un]()}[Hs](t){let e=Q(Du.resolve(this.cwd,t));this[gt].push(new Ou(t,e)),this[Un]()}[bc](t){t.pending=!0,this[mt]+=1;let e=this.follow?"stat":"lstat";Vs[e](t.absolute,(r,i)=>{t.pending=!1,this[mt]-=1,r?this.emit("error",r):this[Gs](t,i)})}[Gs](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[Ls](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]()}[vc](t){t.pending=!0,this[mt]+=1,Vs.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[mt]-=1,e)return this.emit("error",e);this[qs](t,r)})}[qs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Un]()}[Un](){if(!this[wi]){this[wi]=!0;for(let t=this[gt].head;t&&this[mt]<this.jobs;t=t.next)if(this[Ls](t.value),t.value.ignore){let e=t.next;this[gt].removeNode(t),t.next=e}this[wi]=!1,this[gi]&&this[gt].length===0&&this[mt]===0&&(this.zip?this.zip.end(Lu):(super.write(Lu),super.end()))}}get[xn](){return this[gt]&&this[gt].head&&this[gt].head.value}[rc](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[mi].get(r);if(i){this[mi].delete(r);for(let o of i)o.pending=!1,this[Ls](o)}}this[Un]()}[Ls](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[js](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Gs](t,e):this[bc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[qs](t,e):this[vc](t),!t.readdir)return}if(t.entry=this[Mu](t),!t.entry){t.ignore=!0;return}t===this[xn]&&!t.piped&&this[js](t)}}}[ic](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}}[Mu](t){this[mt]+=1;try{return new this[Ws](t.path,this[ic](t)).on("end",()=>this[rc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[sc](){this[xn]&&this[xn].entry&&this[xn].entry.resume()}[js](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Hs](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={}){eo(this,t,e,r)}},zc=class extends no{sync=!0;constructor(t){super(t),this[Ws]=jw}pause(){}resume(){}[bc](t){let e=this.follow?"statSync":"lstatSync";this[Gs](t,Vs[e](t.absolute))}[vc](t){this[qs](t,Vs.readdirSync(t.absolute))}[js](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Hs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[lf](i)})}},Jw=(t,e)=>{let r=new zc(t),i=new Yu(t.file,{mode:t.mode||438});r.pipe(i),uf(r,e)},Xw=(t,e)=>{let r=new no(t),i=new Xs(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 ff(r,e).catch(c=>r.emit("error",c)),o},uf=(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()},ff=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 zc(t);return uf(r,e),r},e_=(t,e)=>{let r=new no(t);return ff(r,e).catch(i=>r.emit("error",i)),r},k2=Pi(Jw,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,gf=n_==="win32",{O_CREAT:mf,O_NOFOLLOW:Bu,O_TRUNC:wf,O_WRONLY:_f}=pf.constants,yf=Number(process.env.__FAKE_FS_O_FILENAME__)||pf.constants.UV_FS_O_FILEMAP||0,r_=gf&&!!yf,i_=512*1024,s_=yf|wf|mf|_f,Fu=!gf&&typeof Bu=="number"?Bu|wf|mf|_f:null,Ef=Fu!==null?()=>Fu:r_?t=>t<i_?s_:"w":()=>"w",Sc=(t,e,r)=>{try{return ro.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},Ys=(t,e,r,i)=>{ro.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 l=Si.resolve(t,e.name);Ys(l,r,i,o)});else{let c=Si.resolve(t,e.name);Ys(c,r,i,o)}},bf=(t,e,r,i)=>{ro.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 Ys(t,e,r,i);let l=c.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--l===0)return Ys(t,e,r,i)}};for(let x of c)o_(t,x,e,r,f)})},a_=(t,e,r,i)=>{e.isDirectory()&&vf(Si.resolve(t,e.name),r,i),Sc(Si.resolve(t,e.name),r,i)},vf=(t,e,r)=>{let i;try{i=ro.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Sc(t,e,r);throw c}for(let o of i)a_(t,o,e,r);return Sc(t,e,r)},Sf=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"}},io=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)=>{st.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Sf(t,r?.code||"ENOTDIR")),e(r)})},l_=(t,e,r)=>{t=Q(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,l=e.uid,u=e.gid,f=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),x=e.preserve,g=e.unlink,m=Q(e.cwd),S=(b,I)=>{b?r(b):I&&f?bf(I,l,u,A=>S(A)):c?st.chmod(t,o,r):r()};if(t===m)return d_(t,S);if(x)return c_.mkdir(t,{mode:o,recursive:!0}).then(b=>S(null,b??void 0),S);let _=Q(Js.relative(m,t)).split("/");Ic(m,_,o,g,m,void 0,S)},Ic=(t,e,r,i,o,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),f=Q(Js.resolve(t+"/"+u));st.mkdir(f,r,If(f,e,r,i,o,c,l))},If=(t,e,r,i,o,c,l)=>u=>{u?st.lstat(t,(f,x)=>{if(f)f.path=f.path&&Q(f.path),l(f);else if(x.isDirectory())Ic(t,e,r,i,o,c,l);else if(i)st.unlink(t,g=>{if(g)return l(g);st.mkdir(t,r,If(t,e,r,i,o,c,l))});else{if(x.isSymbolicLink())return l(new io(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,Ic(t,e,r,i,o,c,l))},u_=t=>{let e=!1,r;try{e=st.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Sf(t,r??"ENOTDIR")}},f_=(t,e)=>{t=Q(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),f=e.preserve,x=e.unlink,g=Q(e.cwd),m=b=>{b&&u&&vf(b,c,l),o&&st.chmodSync(t,i)};if(t===g)return u_(g),m();if(f)return m(st.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(Js.relative(g,t)).split("/"),_;for(let b=S.shift(),I=g;b&&(I+="/"+b);b=S.shift()){I=Q(Js.resolve(I));try{st.mkdirSync(I,i),_=_||I}catch{let A=st.lstatSync(I);if(A.isDirectory())continue;if(x){st.unlinkSync(I),st.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new io(I,I+"/"+S.join("/"))}}return m(_)},oc=Object.create(null),zu=1e4,mr=new Set,h_=t=>{mr.has(t)?mr.delete(t):oc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),mr.add(t);let e=oc[t],r=mr.size-zu;if(r>zu/10){for(let i of mr)if(mr.delete(i),delete oc[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=Af(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(Af(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 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 f of u)o.add(f)}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 f=l[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(),Uu=Symbol("onEntry"),Ac=Symbol("checkFs"),Gu=Symbol("checkFs2"),kc=Symbol("isReusable"),dt=Symbol("makeFs"),Tc=Symbol("file"),Cc=Symbol("directory"),Ks=Symbol("link"),Hu=Symbol("symlink"),qu=Symbol("hardlink"),Ei=Symbol("ensureNoSymlink"),ju=Symbol("unsupported"),Wu=Symbol("checkPath"),ac=Symbol("stripAbsolutePath"),_n=Symbol("mkdir"),Ge=Symbol("onError"),Ns=Symbol("pending"),Ku=Symbol("pend"),wr=Symbol("unpend"),cc=Symbol("ended"),dc=Symbol("maybeClose"),Rc=Symbol("skip"),Ii=Symbol("doChown"),Ai=Symbol("uid"),ki=Symbol("gid"),Ti=Symbol("checkedCwd"),__=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ci=__==="win32",y_=1024,E_=(t,e)=>{if(!Ci)return ie.unlink(t,e);let r=t+".DELETE."+xf(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},b_=t=>{if(!Ci)return ie.unlinkSync(t);let e=t+".DELETE."+xf(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},$u=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Uc=class extends Ri{[cc]=!1;[Ti]=!1;[Ns]=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[cc]=!0,this[dc]()},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||Ci,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Ne.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[Uu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[dc](){this[cc]&&this[Ns]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[ac](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Mc(r),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Ci&&/^[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=Ne.posix.dirname(t.path),f=Ne.posix.normalize(Ne.posix.join(u,l.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}[Wu](t){let e=Q(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=Q(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[ac](t,"path")||!this[ac](t,"linkpath"))return!1;if(t.absolute=Ne.isAbsolute(t.path)?Q(Ne.resolve(t.path)):Q(Ne.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:Q(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}=Ne.win32.parse(String(t.absolute));t.absolute=i+ku(String(t.absolute).slice(i.length));let{root:o}=Ne.win32.parse(t.path);t.path=o+ku(t.path.slice(o.length))}return!0}[Uu](t){if(!this[Wu](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[Ac](t);default:return this[ju](t)}}[Ge](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_(Q(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)}[Tc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new Xs(String(t.absolute),{flags:Ef(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[Ge](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[Ge](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,f=>{f?this[Ge](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,g=t.mtime;ie.futimes(f,x,g,m=>m?ie.utimes(u,x,g,S=>c(S&&m)):c())}if(typeof f=="number"&&this[Ii](t)){o++;let x=this[Ai](t),g=this[ki](t);typeof x=="number"&&typeof g=="number"&&ie.fchown(f,x,g,m=>m?ie.chown(u,x,g,S=>c(S&&m)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[Ge](u,t),e()}),t.pipe(l)),l.pipe(i)}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[_n](String(t.absolute),r,i=>{if(i){this[Ge](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[wr](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ii](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)),c)),c()})}[ju](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Hu](t,e){let r=Q(Ne.relative(this.cwd,Ne.resolve(Ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ei](t,this.cwd,r,()=>this[Ks](t,String(t.linkpath),"symlink",e),i=>{this[Ge](i,t),e()})}[qu](t,e){let r=Q(Ne.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Ei](t,this.cwd,i,()=>this[Ks](t,r,"link",e),o=>{this[Ge](o,t),e()})}[Ei](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let l=Ne.resolve(e,c);ie.lstat(l,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new io(l,Ne.resolve(l,r.join("/"))));this[Ei](t,l,r,i,o)})}[Ku](){this[Ns]++}[wr](){this[Ns]--,this[dc]()}[Rc](t){this[wr](),t.resume()}[kc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ci}[Ac](t){this[Ku]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Gu](t,r))}[Gu](t,e){let r=l=>{e(l)},i=()=>{this[_n](this.cwd,this.dmode,l=>{if(l){this[Ge](l,t),r();return}this[Ti]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let l=Q(Ne.dirname(String(t.absolute)));if(l!==this.cwd)return this[_n](l,this.dmode,u=>{if(u){this[Ge](u,t),r();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Rc](t),r();return}if(l||this[kc](t,u))return this[dt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[dt](g??null,t,r);return f?ie.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),f=>this[dt](f??null,t,r))}if(t.absolute===this.cwd)return this[dt](null,t,r);E_(String(t.absolute),f=>this[dt](f??null,t,r))})};this[Ti]?o():i()}[dt](t,e,r){if(t){this[Ge](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Tc](e,r);case"Link":return this[qu](e,r);case"SymbolicLink":return this[Hu](e,r);case"Directory":case"GNUDumpDir":return this[Cc](e,r)}}[Ks](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[Ge](o,t):(this[wr](),t.resume()),i()})}},_i=t=>{try{return[null,t()]}catch(e){return[e,null]}},kf=class extends Uc{sync=!0;[dt](t,e){return super[dt](t,e,()=>{})}[Ac](t){if(!this[Ti]){let o=this[_n](this.cwd,this.dmode);if(o)return this[Ge](o,t);this[Ti]=!0}if(t.absolute!==this.cwd){let o=Q(Ne.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[_n](o,this.dmode);if(c)return this[Ge](c,t)}}let[e,r]=_i(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Rc](t);if(e||this[kc](t,r))return this[dt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[l]=c?_i(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[dt](l,t)}let[o]=_i(()=>ie.rmdirSync(String(t.absolute)));this[dt](o,t)}let[i]=t.absolute===this.cwd?[]:_i(()=>b_(String(t.absolute)));this[dt](i,t)}[Tc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{ie.closeSync(o)}catch(f){u=f}(l||u)&&this[Ge](l||u,t),e()},o;try{o=ie.openSync(String(t.absolute),Ef(t.size),r)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[Ge](l,t)),t.pipe(c)),c.on("data",l=>{try{ie.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,f=t.mtime;try{ie.futimesSync(o,u,f)}catch(x){try{ie.utimesSync(String(t.absolute),u,f)}catch{l=x}}}if(this[Ii](t)){let u=this[Ai](t),f=this[ki](t);try{ie.fchownSync(o,Number(u),Number(f))}catch(x){try{ie.chownSync(String(t.absolute),Number(u),Number(f))}catch{l=l||x}}}i(l)})}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[_n](String(t.absolute),r);if(i){this[Ge](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ii](t))try{ie.chownSync(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)))}catch{}e(),t.resume()}[_n](t,e){try{return f_(Q(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}}[Ei](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let l of r){c=Ne.resolve(c,l);let[u,f]=_i(()=>ie.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new io(c,Ne.resolve(e,r.join("/"))))}i()}[Ks](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[Ge](c,t)}}},v_=t=>{let e=new kf(t),r=t.file,i=hf.statSync(r),o=t.maxReadSize||16*1024*1024;new Hm(r,{readSize:o,size:i.size}).pipe(e)},S_=(t,e)=>{let r=new Uc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("close",c),hf.stat(o,(u,f)=>{if(u)l(u);else{let x=new Dc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Tf=Pi(v_,S_,t=>new kf(t),t=>new Uc(t),(t,e)=>{e?.length&&of(t,e)}),I_=(t,e)=>{let r=new zc(t),i=!0,o,c;try{try{o=it.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=it.openSync(t.file,"w+");else throw f}let l=it.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<l.size;c+=512){for(let g=0,m=0;g<512;g+=m){if(m=it.readSync(o,u,g,u.length-g,c+g),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!m)break e}let f=new jn(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(c+x+512>l.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{it.closeSync(o)}catch{}}},A_=(t,e,r,i,o)=>{let c=new Yu(t.file,{fd:i,start:r});e.pipe(c),T_(e,o)},k_=(t,e)=>{e=Array.from(e);let r=new no(t),i=(o,c,l)=>{let u=(S,_)=>{S?it.close(o,b=>l(S)):l(null,_)},f=0;if(c===0)return u(null,0);let x=0,g=Buffer.alloc(512),m=(S,_)=>{if(S||_===void 0)return u(S);if(x+=_,x<512&&_)return it.read(o,g,x,g.length-x,f+x,m);if(f===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let b=new jn(g);if(!b.cksumValid)return u(null,f);let I=512*Math.ceil((b.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&b.mtime&&t.mtimeCache.set(String(b.path),b.mtime),x=0,it.read(o,g,0,512,f,m)};it.read(o,g,0,512,f,m)};return new Promise((o,c)=>{r.on("error",c);let l="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&l==="r+")return l="w+",it.open(t.file,l,u);if(f||!x)return c(f);it.fstat(x,(g,m)=>{if(g)return it.close(x,()=>c(g));i(x,m.size,(S,_)=>{if(S)return c(S);let b=new Xs(t.file,{fd:x,start:_});r.pipe(b),b.on("error",c),b.on("close",o),C_(r,e)})})};it.open(t.file,l,u)})},T_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Ar({file:Cf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},C_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Ar({file:Cf.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(!Ym(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")}),H2=Pi(yi.syncFile,yi.asyncFile,yi.syncNoFile,yi.asyncNoFile,(t,e=[])=>{yi.validate?.(t,e),R_(t)}),R_=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 lt={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 so(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Rf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function oo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Pf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Df(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Kn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}$t();je();ne();Oe();je();function kr(t,e){if(so(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 OA}from"node:fs";import{dirname as NA,join as MA}from"node:path";import{fileURLToPath as FA}from"node:url";var Dt="0.2.0";je();ne();var ao="1008033",Mf="1289";var Bf="pbbp2",Ff="https://www.coze.cn",zf="/api/coze_claw/resource/get_frontier_key",F_="https://www.coze.cn",z_="wss://frontier.coze.cn";function Cr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??F_}function Uf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??z_}function bn(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=H("handshake");async function Gc(t){let e=Cr(t.endpoint),r=t.timeoutMs??1e4,i=`${Tr(e)}${zf}?aid=${encodeURIComponent(ao)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...bn(t.ppeOverride)},c=new AbortController,l=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 b=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${b.slice(0,200)}`)}let g=await u.json();if(g.code!==void 0&&g.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${g.code} msg=${g.msg??"-"} logid=${f}`);let m=g.data??{},S=typeof m.access_key=="string"&&m.access_key||typeof m.accessKey=="string"&&m.accessKey||void 0,_=typeof m.device_id=="string"&&m.device_id||typeof m.deviceId=="string"&&m.deviceId||void 0;if(!S||!_){let b=JSON.stringify(g).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${b}`)}return Oi.info("handshake ok",{remoteDeviceId:_,logid:f,traceId:x}),{accessKey:S,deviceId:_}}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(l)}}var Hc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",yt="auto",Gf=15e4;function Hf(t){return{model:qc(t.model)??yt,...t.modelToken?{modelToken:t.modelToken}:{}}}function U_(t){return!t||t===yt}var G_=new Set(["auto","\u81EA\u52A8"]);function qc(t){let e=t?.trim();if(e)return G_.has(e.toLowerCase())?yt:e}function qf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Hc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||yt;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 jf(t,e,r){return t.modelToken?{baseUrl:`${Hc}/v1`,providerName:"coze",headers:{Authorization:`Bearer ${t.modelToken}`,...jc(e,r)}}:null}function Wf(t){if(!t.modelToken)return{};let e={model:t.model||yt,model_context_window:t.modelInfo?.contextWindow??Gf};return{CODEX_CONFIG:JSON.stringify(e)}}function jc(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 Kf(t,e,r){if(!t.modelToken)return{};let i=jc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,l])=>`${c}:${l}`).join(`
92
- `)}}function Wc(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||yt,o=jc(e,r),c=["text"];t.modelInfo?.capabilities?.image===!0&&c.push("image");let l={baseUrl:`${Hc}/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??Gf,maxTokens:8192,api:"openai-completions"}]};return Object.keys(o).length>0&&(l.headers=o),l}var he=H("agent-handlers"),Zf=5*1024*1024,W_=1,K_=6,$_=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}$/,Y_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function J_(t){let e=t?.trim();return e?Y_.test(e)||Z_.test(e)?e:(he.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=l=>{o||(o=!0,l?r(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",l=>c(l))})}var lo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Kn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ve(r).workspace,c=i?.skills??[],l=[],u=new Set;for(let f of c){let x=Ke(o,f.relPath,"SKILL.md");await Vf(x).then(m=>m.isFile()).catch(()=>!1)&&(l.push(ny(f)),u.add(f.relPath))}if(e.scanLocal){let f=i?.framework??"claude-code",x=await Q_(r,o,f);for(let g of x)u.has(g.relPath)||(u.add(g.relPath),l.push(g.skill))}return{skills:l}}async addSkills(e){e._meta;let r=Kn(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],l=new Map(c.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await uo({agentId:r,workspace:i.workspace,framework:i.framework,skill:f});fo(c,l,x),u.push(f)}return await si(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Kn(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 f=Ke(i.workspace,u.relPath);await Vc(f,{recursive:!0,force:!0}),he.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await si(r,l),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Kn(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");he.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",l=t0(e.skillName),u=Ke(ed(c),l),f=Ke(o,u),x=Ke(f,"SKILL.md");if(!await Vf(x).then(T=>T.isFile()).catch(()=>!1))throw new k("SKILL_NOT_FOUND",`skill not found locally: ${e.skillName} (${u})`);let m=new Qc.default;m.addLocalFolder(f,l);let S=m.toBuffer();if(S.length>Yf)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${S.length} bytes exceeds limit ${Yf}`);let _=await co(x,{encoding:"utf8"}).then(T=>r0(T).description).catch(()=>{}),b={};this.opts.publishSkillToMarketplace?b=await this.opts.publishSkillToMarketplace({zip:S,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,..._?{description:_}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):he.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let I=b.version??"v1.0",A=b.skillId??e.skillId??n0(r,u);if(i){let T=i.skills??[],P=T.find(y=>y.relPath===u);P?(P.version=I,P.skillId=A):T.push({skillId:A,skillName:e.skillName,relPath:u,version:I,installedAt:Date.now(),..._?{description:_}:{}}),await si(r,T)}return he.info("skill published",{agentId:r,skillName:e.skillName,relPath:u,zipBytes:S.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 l=c.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,he.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l});continue}let f=c.downstream;c.downstream=void 0,he.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l}),f.stop(r).catch(x=>he.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 he.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 he.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await lr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw he.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 Be(i),he.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=J_(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&V_.test(l)&&o.push("--env",l);let u=await X_(o);return he.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 Be(i),he.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}):(he.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",`${lt.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 l=Ve(r);return c==="cloud"?await Vc(l.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Be(i)),he.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=qc(e.model)??yt,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 Be(i),he.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return he.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=>he.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 f=o.sessions.get(l);f?.downstream&&(await f.downstream.stop(`switchModel: ${r}`).catch(()=>{}),f.downstream=void 0)}));return await Promise.all(c),he.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,lt.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${lt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,lt.RESET),await this.runDetailSync(e.agentId,lt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),he.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 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 Be(r)}async repairAgent(e){if(kr(e._meta,lt.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${lt.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${lt.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){he.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,lt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){he.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){he.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=Kn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(o,c),u=await Kc(l).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(l,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=xy(e.depth);return u.isDirectory()?{tree:await hy(o,l,c,f)}:{tree:[{name:py(c),path:o0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){kr(e._meta,"_agent/getFileContent");let r=Kn(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 Kc(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>Zf)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${Zf})`);let l=await co(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 ke(e).catch(()=>null))?.workspace??Ve(e).workspace}safeJoin(e,r){let i=Yc(e,r||"."),o=Xc(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${Xf}`))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 t0(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 ed(t){return t==="claude-code"?Ke(".claude","skills"):Ke(".agents","skills")}function n0(t,e){return(H_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function r0(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 l=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[l]=u)}return i}async function Q_(t,e,r){let i=ed(r),o=Ke(e,i),c=await Jf(o,{withFileTypes:!0}).catch(()=>null);if(!c)return[];let l=[];for(let u of c){if(!u.isDirectory())continue;let f=u.name,x=Ke(i,f),g=Ke(o,f,"SKILL.md"),m=await co(g,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let S=r0(m);l.push({relPath:x,skill:{skillId:n0(t,x),skillName:S.name||f,...S.description?{description:S.description}:{}}})}return l}var ey=3e4,ty=50*1024*1024,Yf=10*1024*1024,Rr=3e4;async function uo(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,l=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!l)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=t0(o.skillName),f=ed(i),x=Ke(f,u),g=Ke(r,x);if(await $c(g,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");Ni(S.length),await Zc(Ke(g,"SKILL.md"),S,"utf8")}else{let S=await iy(o.downloadUrl);oy(S)?await ly(S,g):ay(S)?await cy(S,g):await Zc(Ke(g,"SKILL.md"),S.toString("utf8"),"utf8")}let m={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 he.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:c?"content":"downloadUrl"}),m}function fo(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 i0(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=Dt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await Be(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],l=new Map(c.map((g,m)=>[g.skillId,m])),u=c.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Be(r,e),{status:"noop",count:0};let f=0,x=0;for(let g of u)try{await Vc(Ke(r.workspace,g.relPath),{recursive:!0,force:!0});let m=await uo({agentId:t,workspace:r.workspace,framework:r.framework,skill:ry(g)});fo(c,l,m),f+=1}catch(m){x+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(m)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await Be(r,e),he.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 co(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 Jc(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function cy(t,e){let r,i;try{r=new Qc.default(t),i=r.getEntries()}catch(l){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${l.message}`,{cause:l})}for(let l of i){let u=l.entryName;if(!u||Jc(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=l.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=Yc(e);for(let l of i){if(Jc(l.entryName))continue;let u=l.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=Yc(e,u),x=Xc(c,f);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await $c(f,{recursive:!0});continue}await $c(q_(f),{recursive:!0});let g;try{g=l.getData()}catch(m){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${m.message}`,{cause:m})}await Zc(f,g)}}function dy(t){let e;for(let r of t){let i=r.entryName;if(!i||Jc(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=Tf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Rr}ms)`))},Rr);try{await e0(Qf.from(t),r)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Rr}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 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(x=>x==="..")&&e.push(`tar entry contains '..': ${l}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Rr}ms)`))},Rr);try{await e0(Qf.from(t),r)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Rr}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 s0(t,e,r,i,{count:0})}async function s0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await Jf(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if($_.has(u.name)||u.isSymbolicLink())continue;if(o.count>=fy){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=Ke(e,u.name),x=j_(Ke(r,u.name)),g=null;try{g=await Kc(f)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let m={name:u.name,path:o0(Xc(t,f)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(m.children=await s0(t,f,x,i-1,o)),l.push(m)}return l.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),l}function xy(t){return!t||t<=0?W_:Math.min(t,K_)}function py(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function o0(t){return t.split(Xf).join("/")}ne();var vn=H("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 l of this.opts.core.agents.values()){let u=wy(l);if(!u)continue;let f={agentId:l.agentId,status:u};l.patToken&&(f.patToken=l.patToken),l.accountId&&(f.accountId=l.accountId),r.push(f)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Dt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(l){this.consecutiveFailures+=1,vn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let c=o?.authFailures;if(c&&c.length>0&&(vn.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){vn.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}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 od,rm as fE,stat as hE}from"node:fs/promises";import{homedir as xE}from"node:os";import{join as cd}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}}je();var ho=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 a0(t){return"method"in t&&"id"in t&&t.id!==void 0}function c0(t){return"method"in t&&!("id"in t)}function xo(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"?by(t):t}var Ey=[[/\/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 Ey)e=e.replace(r,i);return e}function by(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 d0(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 k(r,o,{retriable:e?.retriable??!1,cause:c})}function u0(t){return`${JSON.stringify(t)}
95
- `}var l0=10*1024*1024,po=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>l0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${l0} 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(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 h0={"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"},bk=Object.fromEntries(Object.entries(h0).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=h0[e]??Sy(e),o=vy[i]??[],c=[i,String(this.seq)];if(o.length>0){let l=o.map(f=>f0(r?.[f]??"")),u=Iy(l).join(":");u&&c.push(u)}else r&&Object.values(r).some(l=>l)&&c.push(Object.values(r).filter(Boolean).map(l=>f0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function Sy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function f0(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 td(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 nd(t){try{let e=JSON.parse(Ay(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function x0(t,e,r={},i=o=>o){return{...i({...t,...nd(e)}),...r}}$t();ir();je();ne();Oe();import{execFileSync as Ty,spawnSync as Cy}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"),Cy("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var rd=new Set;function p0(t){typeof t=="number"&&t>0&&rd.add(t)}function g0(t){typeof t=="number"&&rd.delete(t)}function m0(){for(let t of rd)Gi(t,"SIGKILL")}var Lr="coze-bridge-daemon";function w0(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 _0(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,l=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(f=>i(f));u+=l)await o(Math.min(l,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var Ry=[{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 y0(t,e){if(!e)return null;for(let r of Ry)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function E0(t,e){return y0(t,e)}function b0(t,e){return y0(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 v0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,g=r-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Nr(g,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: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 S0=$e("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Ny=200,My=40,By=$e("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Fy=$e("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),zy=$e("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Uy=$e("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Gy=$e("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Hy=$e("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),I0=500;function qy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=I0?t:`${e.slice(0,I0)}...<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 A0(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)?A0(e.command):void 0,cwd:e.cwd,cwdExists:A0(e.cwd),envKeys:e.envKeys}}function Ky(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 Ot=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new po({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=x0(process.env,this.opts.agentEnvFile??ee().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,p0(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,g0(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=Wy(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 k("AGENT_SPAWN_FAILED",Ky(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()));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,S0,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=S0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=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 g={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let m=this.now(),S={cfg:o,startedAt:m,lastActivityAt:m,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:m,expectedIntervalMs:Nr(0,!1,o),sessionId:u};g.promptTimeout=S;let _=()=>{let b={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=v0(b,S.cfg,I),T=P=>{S.armedAt=I,S.expectedIntervalMs=P,g.timer=setTimeout(_,P)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.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,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};g.timer=setTimeout(_,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(g.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,g);try{this.writeFrame(l)}catch(m){g.timer&&clearTimeout(g.timer),this.pending.delete(c),x(m)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(u0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(xo(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(c0(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(a0(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(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=d0(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=E0(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 $y(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 go=class extends Ot{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 $y(e)}};sn();import{mkdtempSync as Jy,rmSync as Xy}from"node:fs";import{tmpdir as Qy}from"node:os";import{join as eE}from"node:path";import{readFileSync as T0}from"node:fs";import{homedir as Vy}from"node:os";import{join as k0}from"node:path";function C0(t){let e=t.CODEX_HOME?.trim()||k0(t.HOME?.trim()||Vy(),".codex");return k0(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 Yy(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 l=/^\[([^\]]+)\]$/.exec(c);if(l){let x=(l[1]??"").trim(),g=r[x]??{};r[x]=g,i=g;continue}let u=c.indexOf("=");if(u<=0)continue;let f=c.slice(0,u).trim();f&&(i[f]=Yy(c.slice(u+1)))}return{root:e,tables:r}}function P0(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 D0(t){let e;try{e=T0(C0(t),"utf8")}catch{return null}return P0(R0(e))?.providerId??null}function O0(t){let e;try{e=T0(C0(t),"utf8")}catch{return null}let r=P0(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 mo=class t extends Ot{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),l=e.isolateCodexHome?Jy(eE(Qy(),"coze-bridge-codex-home-")):void 0,u=l?{...e.env??{},CODEX_HOME:l}: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=l}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=O0(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{}}};je();var tE=3e4,Mr=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}`}]},tE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var L0=["default","acceptEdits","plan","auto","bypassPermissions"],N0=["read-only","auto","full-access"];function In(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return L0.includes(e);case"codex":return N0.includes(e);case"openclaw":return!1}}function id(t){switch(t){case"claude-code":return L0.join("/");case"codex":return N0.join("/");case"openclaw":return""}}an();je();ne();Oe();function sd(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 wo=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"}$t();ne();import{constants as M0}from"node:fs";import{access as nE}from"node:fs/promises";import{delimiter as rE,join as iE}from"node:path";var Et=H("framework-detector"),B0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},sE=[".exe",".cmd",".bat",".ps1"],$n=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??nt,access:e.access??nE}}async detect(e){let r=B0[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(B0).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(rE).filter(Boolean),i=this.env.platform==="win32"?["",...sE]:[""];for(let o of r)for(let c of i){let l=iE(o,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?M0.F_OK:M0.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&&(aE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,l,u=f=>{c||(c=!0,l&&clearTimeout(l),i(f))};try{let f=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});l=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)}})}},oE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function aE(t){return t.replace(oE,"")}import{homedir as cE}from"node:os";import{join as dE}from"node:path";an();$t();ir();je();ne();async function U0(){let t=dE(cE(),".openclaw/openclaw.json");return(await cr(t))?.gateway?.auth?.token??""}var F0=H("openclaw.config"),lE=[0,5e3,5e3],uE=$e("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),z0="models.providers.",_o="agents.defaults.models",yo=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new An;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??lE,this.cliTimeoutMs=e.cliTimeoutMs??uE}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,F0.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(l)})}}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="",l=!1,u=x=>{l||(l=!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){F0.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",`${z0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${z0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${_o}[${e}]`,()=>this.runCli(["config","set",_o,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${_o}[${e}]`,`${_o}.${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=H("agent-manager"),dd="acceptEdits",q0="full-access",j0="read-only";function pE(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}var gE=(t,e,r,i,o,c,l,u,f,x)=>{switch(t){case"claude-code":{let g={...o?{...qf(o),...Kf(o,l,u)}:{},...f??{},IS_SANDBOX:"1"};return new go({cwd:r,env:g,agentId:i})}case"codex":{let g=q0;x!==void 0&&(In("codex",x)?g=x:le.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let m=o?null:D0(process.env),S={...o?Wf(o):{},INITIAL_AGENT_MODE:pE(g),...process.env.COZE_BRIDGE_CODEX_APP_SERVER_LOGS==="1"?{APP_SERVER_LOGS:cd(r,"..","logs","codex-app-server")}:{},...m?{MODEL_PROVIDER:m}:{},...f??{}},_=o?jf(o,l,u):null,b=_?{methodId:"gateway",_meta:{gateway:_}}:void 0,I=!!o,A=!I&&process.env.COZE_BRIDGE_CODEX_LOCAL_GATEWAY_AUTH==="1";return new mo({cwd:r,agentId:i,...Object.keys(S).length>0?{env:S}:{},...b?{authRequest:b}:{},...I?{isolateCodexHome:!0}:{},...A?{resolveLocalGatewayAuth:!0}:{}})}case"openclaw":return new Mr({command:e,cwd:r,agentId:i,...c?{sessionName:sd(c)}:{}})}};function ad(t){return t==="claude-code"||t==="codex"}function mE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(wE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return U1(t.homeDir,".coze","bridge","task.xml")},async install(t){let n=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await mp("schtasks",["/Create","/SC","ONLOGON","/TN",fa,"/TR",n,"/RU",t.userName,"/F"]),tl.info("task scheduler entry created",{task:fa,logFile:t.logFile})},async uninstall(t){await mp("schtasks",["/Delete","/TN",fa,"/F"]).catch(e=>tl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),tl.info("task scheduler entry removed",{task:fa})}}});var _p={};Aa(_p,{buildContext:()=>K1,getSupervisor:()=>H1,launchdSupervisor:()=>Qd,systemdSupervisor:()=>el,taskSchedulerSupervisor:()=>nl});import{homedir as G1,userInfo as q1}from"node:os";function H1(t=process.platform){switch(t){case"darwin":return Qd;case"linux":return el;case"win32":return nl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function W1(){let t={};for(let e of j1){let n=process.env[e];n&&(t[e]=n)}return t}function K1(){let t=X();return{nodeBin:process.execPath,entry:Hd(t),logFile:t.logFile,homeDir:G1(),userName:q1().username,isRoot:process.getuid?.()===0,env:W1()}}var j1,yp=rt(()=>{"use strict";Be();na();xp();gp();wp();j1=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ee();cn();var Pl=q("acp-installer-warmup"),Kg=["claude-code","codex"];async function Ol(t={}){let e=t.ensure??lr,i=(await Promise.allSettled(Kg.map(async s=>{let c=await e(s);Pl.info("acp wrapper warmup ok",{framework:s,path:c})}))).filter(s=>s.status==="rejected");i.length>0&&Pl.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(s=>s.reason instanceof Error?s.reason.message:String(s.reason))})}un();ee();import{readdir as cm}from"node:fs/promises";import{mkdir as Bl,readFile as om,writeFile as Fl}from"node:fs/promises";import{join as Oa}from"node:path";var am={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function hr(t,e,n){await Bl(t,{recursive:!0});let i=am[e],s=Oa(t,i);return await Fl(s,n??"","utf8"),s}async function La(t,e,n){let i=Oa(t,".claude");await Bl(i,{recursive:!0});let s=Oa(i,"settings.local.json"),c={};try{let u=await om(s,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(c=h)}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(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return c.permissions=d,await Fl(s,JSON.stringify(c,null,2),"utf8"),s}var Qe=q("agent-detail-sync"),dm=6e4,lm=5*6e4,ys=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await cm(n)}catch(s){Qe.info("agents dir not found, skip detail sync",{root:n,err:String(s)});return}Qe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async s=>{let c=await Re(s,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Qe.debug("detail sync: skip disconnected agent",{agentId:s});return}try{await this.syncOne(s,c)}catch(d){Qe.warn("detail sync failed for agent, skipping",{agentId:s,err:String(d)})}}})),Qe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,s]of this.retryQueue)e>=s.dueAt&&n.push(i);if(n.length!==0){Qe.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(s){Qe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(s)})}}}async syncOne(e,n){let i=n??await Re(e,this.opts.paths);if(!i){Qe.info("detail sync: agent config missing, skip",{agentId:e});return}let s;try{s=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(h){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),m=x?Math.min(x.currentDelay*2,lm):dm;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(s.agentId&&s.agentId!==e){Qe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:s.agentId});return}let c=!1,d=!1;s.agentName&&s.agentName!==i.agentName&&(i.agentName=s.agentName,c=!0),s.description!==void 0&&s.description!==i.description&&(i.description=s.description,c=!0),s.cozeIdentity&&s.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=s.cozeIdentity,c=!0,d=!0);let u=!1;if(s.deployType==="cloud"&&i.deployType!=="cloud"?(Qe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):s.deployType&&Qe.info("detail.deployType",{agentId:e,deployType:s.deployType}),!c){Qe.debug("detail sync: no diff",{agentId:e});return}await Ue(i,this.opts.paths),Qe.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}),Qe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await hr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var rd=Ht(mu(),1);import{createHash as j_}from"node:crypto";import{lstat as Zc,mkdir as Yc,readFile as ho,readdir as r0,rm as Xc,stat as e0,writeFile as Qc}from"node:fs/promises";import{dirname as W_,join as Je,normalize as K_,relative as nd,resolve as ed,sep as i0}from"node:path";import{Readable as s0}from"node:stream";import{pipeline as o0}from"node:stream/promises";import Pm from"events";import it from"fs";import{EventEmitter as Oc}from"node:events";import Xu from"node:stream";import{StringDecoder as Om}from"node:string_decoder";import tf from"node:path";import Ir from"node:fs";import{dirname as Km,parse as $m}from"path";import{EventEmitter as tw}from"events";import xc from"assert";import{Buffer as Wn}from"buffer";import*as Eu from"zlib";import nw from"zlib";import{posix as wr}from"node:path";import{basename as Cw}from"node:path";import Xs from"fs";import Dt from"fs";import Cu from"path";import{win32 as Gw}from"node:path";import Mu from"path";import mf from"node:fs";import i_ from"node:assert";import{randomBytes as wf}from"node:crypto";import ne from"node:fs";import ze from"node:path";import _f from"fs";import ao from"node:fs";import Ti from"node:path";import ct from"node:fs";import u_ from"node:fs/promises";import to from"node:path";import{join as Df}from"node:path";import at from"node:fs";import Of from"node:path";var Dm=Object.defineProperty,Rm=(t,e)=>{for(var n in e)Dm(t,n,{get:e[n],enumerable:!0})},wu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Lm=t=>!!t&&typeof t=="object"&&(t instanceof Vn||t instanceof Xu||Nm(t)||Mm(t)),Nm=t=>!!t&&typeof t=="object"&&t instanceof Oc&&typeof t.pipe=="function"&&t.pipe!==Xu.Writable.prototype.pipe,Mm=t=>!!t&&typeof t=="object"&&t instanceof Oc&&typeof t.write=="function"&&typeof t.end=="function",jt=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),hn=Symbol("emittedEnd"),Is=Symbol("emittingEnd"),li=Symbol("emittedError"),As=Symbol("closed"),_u=Symbol("read"),Ts=Symbol("flush"),yu=Symbol("flushChunk"),_t=Symbol("encoding"),mr=Symbol("decoder"),Ge=Symbol("flowing"),ui=Symbol("paused"),Er=Symbol("resume"),qe=Symbol("buffer"),et=Symbol("pipes"),He=Symbol("bufferLength"),Ua=Symbol("bufferPush"),ks=Symbol("bufferShift"),Xe=Symbol("objectMode"),ke=Symbol("destroyed"),Ga=Symbol("error"),qa=Symbol("emitData"),bu=Symbol("emitEnd"),Ha=Symbol("emitEnd2"),Tt=Symbol("async"),ja=Symbol("abort"),Cs=Symbol("aborted"),fi=Symbol("signal"),Mn=Symbol("dataListeners"),ot=Symbol("discarded"),hi=t=>Promise.resolve().then(t),Bm=t=>t(),Fm=t=>t==="end"||t==="finish"||t==="prefinish",zm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Um=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Qu=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Er](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Gm=class extends Qu{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,n){super(t,e,n),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},qm=t=>!!t.objectMode,Hm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Vn=class extends Oc{[Ge]=!1;[ui]=!1;[et]=[];[qe]=[];[Xe];[_t];[Tt];[mr];[jt]=!1;[hn]=!1;[Is]=!1;[As]=!1;[li]=null;[He]=0;[ke]=!1;[fi];[Cs]=!1;[Mn]=0;[ot]=!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");qm(e)?(this[Xe]=!0,this[_t]=null):Hm(e)?(this[_t]=e.encoding,this[Xe]=!1):(this[Xe]=!1,this[_t]=null),this[Tt]=!!e.async,this[mr]=this[_t]?new Om(this[_t]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[qe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:n}=e;n&&(this[fi]=n,n.aborted?this[ja]():n.addEventListener("abort",()=>this[ja]()))}get bufferLength(){return this[He]}get encoding(){return this[_t]}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[Xe]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Tt]}set async(t){this[Tt]=this[Tt]||!!t}[ja](){this[Cs]=!0,this.emit("abort",this[fi]?.reason),this.destroy(this[fi]?.reason)}get aborted(){return this[Cs]}set aborted(t){}write(t,e,n){if(this[Cs])return!1;if(this[jt])throw new Error("write after end");if(this[ke])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[Tt]?hi:Bm;if(!this[Xe]&&!Buffer.isBuffer(t)){if(Um(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(zm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Xe]?(this[Ge]&&this[He]!==0&&this[Ts](!0),this[Ge]?this.emit("data",t):this[Ua](t),this[He]!==0&&this.emit("readable"),n&&i(n),this[Ge]):t.length?(typeof t=="string"&&!(e===this[_t]&&!this[mr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[_t]&&(t=this[mr].write(t)),this[Ge]&&this[He]!==0&&this[Ts](!0),this[Ge]?this.emit("data",t):this[Ua](t),this[He]!==0&&this.emit("readable"),n&&i(n),this[Ge]):(this[He]!==0&&this.emit("readable"),n&&i(n),this[Ge])}read(t){if(this[ke])return null;if(this[ot]=!1,this[He]===0||t===0||t&&t>this[He])return this[Wt](),null;this[Xe]&&(t=null),this[qe].length>1&&!this[Xe]&&(this[qe]=[this[_t]?this[qe].join(""):Buffer.concat(this[qe],this[He])]);let e=this[_u](t||null,this[qe][0]);return this[Wt](),e}[_u](t,e){if(this[Xe])this[ks]();else{let n=e;t===n.length||t===null?this[ks]():typeof n=="string"?(this[qe][0]=n.slice(t),e=n.slice(0,t),this[He]-=t):(this[qe][0]=n.subarray(t),e=n.subarray(0,t),this[He]-=t)}return this.emit("data",e),!this[qe].length&&!this[jt]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[jt]=!0,this.writable=!1,(this[Ge]||!this[ui])&&this[Wt](),this}[Er](){this[ke]||(!this[Mn]&&!this[et].length&&(this[ot]=!0),this[ui]=!1,this[Ge]=!0,this.emit("resume"),this[qe].length?this[Ts]():this[jt]?this[Wt]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[Ge]=!1,this[ui]=!0,this[ot]=!1}get destroyed(){return this[ke]}get flowing(){return this[Ge]}get paused(){return this[ui]}[Ua](t){this[Xe]?this[He]+=1:this[He]+=t.length,this[qe].push(t)}[ks](){return this[Xe]?this[He]-=1:this[He]-=this[qe][0].length,this[qe].shift()}[Ts](t=!1){do;while(this[yu](this[ks]())&&this[qe].length);!t&&!this[qe].length&&!this[jt]&&this.emit("drain")}[yu](t){return this.emit("data",t),this[Ge]}pipe(t,e){if(this[ke])return t;this[ot]=!1;let n=this[hn];return e=e||{},t===wu.stdout||t===wu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[et].push(e.proxyErrors?new Gm(this,t,e):new Qu(this,t,e)),this[Tt]?hi(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[et].find(n=>n.dest===t);e&&(this[et].length===1?(this[Ge]&&this[Mn]===0&&(this[Ge]=!1),this[et]=[]):this[et].splice(this[et].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[ot]=!1,this[Mn]++,!this[et].length&&!this[Ge]&&this[Er]();else if(t==="readable"&&this[He]!==0)super.emit("readable");else if(Fm(t)&&this[hn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[li]){let i=e;this[Tt]?hi(()=>i.call(this,this[li])):i.call(this,this[li])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Mn]=this.listeners("data").length,this[Mn]===0&&!this[ot]&&!this[et].length&&(this[Ge]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Mn]=0,!this[ot]&&!this[et].length&&(this[Ge]=!1)),e}get emittedEnd(){return this[hn]}[Wt](){!this[Is]&&!this[hn]&&!this[ke]&&this[qe].length===0&&this[jt]&&(this[Is]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[As]&&this.emit("close"),this[Is]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==ke&&this[ke])return!1;if(t==="data")return!this[Xe]&&!n?!1:this[Tt]?(hi(()=>this[qa](n)),!0):this[qa](n);if(t==="end")return this[bu]();if(t==="close"){if(this[As]=!0,!this[hn]&&!this[ke])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(t==="error"){this[li]=n,super.emit(Ga,n);let s=!this[fi]||this.listeners("error").length?super.emit("error",n):!1;return this[Wt](),s}else if(t==="resume"){let s=super.emit("resume");return this[Wt](),s}else if(t==="finish"||t==="prefinish"){let s=super.emit(t);return this.removeAllListeners(t),s}let i=super.emit(t,...e);return this[Wt](),i}[qa](t){for(let n of this[et])n.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[Wt](),e}[bu](){return this[hn]?!1:(this[hn]=!0,this.readable=!1,this[Tt]?(hi(()=>this[Ha]()),!0):this[Ha]())}[Ha](){if(this[mr]){let e=this[mr].end();if(e){for(let n of this[et])n.dest.write(e);this[ot]||super.emit("data",e)}}for(let e of this[et])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Xe]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Xe]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Xe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[_t]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ke,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ot]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[jt])return e();let i,s,c=x=>{this.off("data",d),this.off("end",u),this.off(ke,h),e(),s(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(ke,h),this.pause(),i({value:x,done:!!this[jt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(ke,h),e(),i({done:!0,value:void 0})},h=()=>c(new Error("stream destroyed"));return new Promise((x,m)=>{s=m,i=x,this.once(ke,h),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[ot]=!1;let t=!1,e=()=>(this.pause(),this.off(Ga,e),this.off(ke,e),this.off("end",e),t=!0,{done:!0,value:void 0}),n=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Ga,e),this.once(ke,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[ke])return t?this.emit("error",t):this.emit(ke),this;this[ke]=!0,this[ot]=!0,this[qe].length=0,this[He]=0;let e=this;return typeof e.close=="function"&&!this[As]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return Lm}},jm=it.writev,vn=Symbol("_autoClose"),vt=Symbol("_close"),xi=Symbol("_ended"),ue=Symbol("_fd"),Wa=Symbol("_finished"),Jt=Symbol("_flags"),Ka=Symbol("_flush"),fc=Symbol("_handleChunk"),hc=Symbol("_makeBuf"),Ii=Symbol("_mode"),Ds=Symbol("_needDrain"),Tr=Symbol("_onerror"),kr=Symbol("_onopen"),$a=Symbol("_onread"),vr=Symbol("_onwrite"),Sn=Symbol("_open"),Et=Symbol("_path"),wn=Symbol("_pos"),kt=Symbol("_queue"),Sr=Symbol("_read"),Va=Symbol("_readSize"),Vt=Symbol("_reading"),pi=Symbol("_remain"),Ja=Symbol("_size"),Us=Symbol("_write"),Bn=Symbol("_writing"),Gs=Symbol("_defaultFlag"),jn=Symbol("_errored"),Lc=class extends Vn{[jn]=!1;[ue];[Et];[Va];[Vt]=!1;[Ja];[pi];[vn];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[jn]=!1,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[Et]=t,this[Va]=e.readSize||16*1024*1024,this[Vt]=!1,this[Ja]=typeof e.size=="number"?e.size:1/0,this[pi]=this[Ja],this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[ue]=="number"?this[Sr]():this[Sn]()}get fd(){return this[ue]}get path(){return this[Et]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Sn](){it.open(this[Et],"r",(t,e)=>this[kr](t,e))}[kr](t,e){t?this[Tr](t):(this[ue]=e,this.emit("open",e),this[Sr]())}[hc](){return Buffer.allocUnsafe(Math.min(this[Va],this[pi]))}[Sr](){if(!this[Vt]){this[Vt]=!0;let t=this[hc]();if(t.length===0)return process.nextTick(()=>this[$a](null,0,t));it.read(this[ue],t,0,t.length,null,(e,n,i)=>this[$a](e,n,i))}}[$a](t,e,n){this[Vt]=!1,t?this[Tr](t):this[fc](e,n)&&this[Sr]()}[vt](){if(this[vn]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Tr](t){this[Vt]=!0,this[vt](),this.emit("error",t)}[fc](t,e){let n=!1;return this[pi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[pi]<=0)&&(n=!1,this[vt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[ue]=="number"&&this[Sr](),!1;case"error":return this[jn]?!1:(this[jn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Wm=class extends Lc{[Sn](){let t=!0;try{this[kr](null,it.openSync(this[Et],"r")),t=!1}finally{t&&this[vt]()}}[Sr](){let t=!0;try{if(!this[Vt]){this[Vt]=!0;do{let e=this[hc](),n=e.length===0?0:it.readSync(this[ue],e,0,e.length,null);if(!this[fc](n,e))break}while(!0);this[Vt]=!1}t=!1}finally{t&&this[vt]()}}[vt](){if(this[vn]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,it.closeSync(t),this.emit("close")}}},no=class extends Pm{readable=!1;writable=!0;[jn]=!1;[Bn]=!1;[xi]=!1;[kt]=[];[Ds]=!1;[Et];[Ii];[vn];[ue];[Gs];[Jt];[Wa]=!1;[wn];constructor(t,e){e=e||{},super(e),this[Et]=t,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[Ii]=e.mode===void 0?438:e.mode,this[wn]=typeof e.start=="number"?e.start:void 0,this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[wn]!==void 0?"r+":"w";this[Gs]=e.flags===void 0,this[Jt]=e.flags===void 0?n:e.flags,this[ue]===void 0&&this[Sn]()}emit(t,...e){if(t==="error"){if(this[jn])return!1;this[jn]=!0}return super.emit(t,...e)}get fd(){return this[ue]}get path(){return this[Et]}[Tr](t){this[vt](),this[Bn]=!0,this.emit("error",t)}[Sn](){it.open(this[Et],this[Jt],this[Ii],(t,e)=>this[kr](t,e))}[kr](t,e){this[Gs]&&this[Jt]==="r+"&&t&&t.code==="ENOENT"?(this[Jt]="w",this[Sn]()):t?this[Tr](t):(this[ue]=e,this.emit("open",e),this[Bn]||this[Ka]())}end(t,e){return t&&this.write(t,e),this[xi]=!0,!this[Bn]&&!this[kt].length&&typeof this[ue]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[xi]?(this.emit("error",new Error("write() after end()")),!1):this[ue]===void 0||this[Bn]||this[kt].length?(this[kt].push(t),this[Ds]=!0,!1):(this[Bn]=!0,this[Us](t),!0)}[Us](t){it.write(this[ue],t,0,t.length,this[wn],(e,n)=>this[vr](e,n))}[vr](t,e){t?this[Tr](t):(this[wn]!==void 0&&typeof e=="number"&&(this[wn]+=e),this[kt].length?this[Ka]():(this[Bn]=!1,this[xi]&&!this[Wa]?(this[Wa]=!0,this[vt](),this.emit("finish")):this[Ds]&&(this[Ds]=!1,this.emit("drain"))))}[Ka](){if(this[kt].length===0)this[xi]&&this[vr](null,0);else if(this[kt].length===1)this[Us](this[kt].pop());else{let t=this[kt];this[kt]=[],jm(this[ue],t,this[wn],(e,n)=>this[vr](e,n))}}[vt](){if(this[vn]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},ef=class extends no{[Sn](){let t;if(this[Gs]&&this[Jt]==="r+")try{t=it.openSync(this[Et],this[Jt],this[Ii])}catch(e){if(e?.code==="ENOENT")return this[Jt]="w",this[Sn]();throw e}else t=it.openSync(this[Et],this[Jt],this[Ii]);this[kr](null,t)}[vt](){if(this[vn]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,it.closeSync(t),this.emit("close")}}[Us](t){let e=!0;try{this[vr](null,it.writeSync(this[ue],t,0,t.length,this[wn])),e=!1}finally{if(e)try{this[vt]()}catch{}}}},Vm=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"]]),Jm=t=>!!t.sync&&!!t.file,Zm=t=>!t.sync&&!!t.file,Ym=t=>!!t.sync&&!t.file,Xm=t=>!t.sync&&!t.file,Qm=t=>!!t.file,ew=t=>Vm.get(t)||t,Nc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let s=ew(n);e[s]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Li=(t,e,n,i,s)=>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 h=Nc(c);if(s?.(h,d),Jm(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(Zm(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(Ym(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(h,d)}else if(Xm(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:s}),rw=nw.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},rw)),iw=Wn.concat,vu=Object.getOwnPropertyDescriptor(Wn,"concat"),sw=t=>t,Za=vu?.writable===!0||vu?.set!==void 0?t=>{Wn.concat=t?sw:iw}:t=>{},Kn=Symbol("_superWrite"),Rs=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"}},Ya=Symbol("flushFlag"),Mc=class extends Vn{#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 Eu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Eu[e](t)}catch(n){throw new Rs(n,this.constructor)}this.#o=n=>{this.#e||(this.#e=!0,this.close(),this.emit("error",n))},this.#t?.on("error",n=>this.#o(new Rs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return xc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Wn.alloc(0),{[Ya]:t})))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(n)}get ended(){return this.#n}[Kn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Wn.from(t,e)),this.#e)return;xc(this.#t,"zlib binding closed");let i=this.#t._handle,s=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Za(!0);let d;try{let h=typeof t[Ya]=="number"?t[Ya]:this.#r;d=this.#t._processChunk(t,h),Za(!1)}catch(h){Za(!1),this.#o(new Rs(h,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=s,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",h=>this.#o(new Rs(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[Kn](Wn.from(h));for(let x=1;x<d.length;x++)u=this[Kn](d[x])}else u=this[Kn](Wn.from(d));return n&&n(),u}},nf=class extends Mc{#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),xc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,s)=>{typeof i=="function"&&(s=i,i=this.flushFlag),this.flush(i),s?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},ow=class extends nf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Kn](t){return this.#e?(this.#e=!1,t[9]=255,super[Kn](t)):super[Kn](t)}},aw=class extends nf{constructor(t){super(t,"Unzip")}},rf=class extends Mc{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)}},cw=class extends rf{constructor(t){super(t,"BrotliCompress")}},dw=class extends rf{constructor(t){super(t,"BrotliDecompress")}},sf=class extends Mc{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)}},lw=class extends sf{constructor(t){super(t,"ZstdCompress")}},uw=class extends sf{constructor(t){super(t,"ZstdDecompress")}},fw=(t,e)=>{if(Number.isSafeInteger(t))t<0?xw(t,e):hw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},hw=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},xw=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var s=t&255;t=Math.floor(t/256),n?e[i-1]=of(s):s===0?e[i-1]=0:(n=!0,e[i-1]=af(s))}},pw=t=>{let e=t[0],n=e===128?mw(t.subarray(1,t.length)):e===255?gw(t):null;if(n===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(n))throw Error("parsed number outside of javascript safe integer range");return n},gw=t=>{for(var e=t.length,n=0,i=!1,s=e-1;s>-1;s--){var c=Number(t[s]),d;i?d=of(c):c===0?d=c:(i=!0,d=af(c)),d!==0&&(n-=d*Math.pow(256,e-s-1))}return n},mw=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var s=Number(t[i]);s!==0&&(n+=s*Math.pow(256,e-i-1))}return n},of=t=>(255^t)&255,af=t=>(255^t)+1&255,ww={};Rm(ww,{code:()=>Bc,isCode:()=>qs,isName:()=>_w,name:()=>ro,normalFsTypes:()=>cf});var qs=t=>ro.has(t),_w=t=>Bc.has(t),cf=new Set(["0","","1","2","3","4","5","6","7","D"]),ro=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"]]),Bc=new Map(Array.from(ro).map(t=>[t[1],t[0]])),$n=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,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let s=Fn(t,e+156,1),c=cf.has(s),d=c?n:void 0,u=c?i:void 0;if(this.path=d?.path??Fn(t,e,100),this.mode=d?.mode??u?.mode??_n(t,e+100,8),this.uid=d?.uid??u?.uid??_n(t,e+108,8),this.gid=d?.gid??u?.gid??_n(t,e+116,8),this.size=d?.size??u?.size??_n(t,e+124,12),this.mtime=d?.mtime??u?.mtime??Xa(t,e+136,12),this.cksum=_n(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),qs(s)&&(this.#e=s||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Fn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Fn(t,e+265,32),this.gname=d?.gname??u?.gname??Fn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??_n(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??_n(t,e+337,8)??0,t[e+475]!==0){let x=Fn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Fn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??Xa(t,e+476,12),this.ctime=n?.ctime??i?.ctime??Xa(t,e+488,12)}let h=256;for(let x=e;x<e+148;x++)h+=t[x];for(let x=e+156;x<e+512;x++)h+=t[x];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e||n==="linkpath"&&e||n==="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 n=this.ctime||this.atime?130:155,i=yw(this.path||"",n),s=i[0],c=i[1];this.needPax=!!i[2],this.needPax=zn(t,e,100,s)||this.needPax,this.needPax=yn(t,e+100,8,this.mode)||this.needPax,this.needPax=yn(t,e+108,8,this.uid)||this.needPax,this.needPax=yn(t,e+116,8,this.gid)||this.needPax,this.needPax=yn(t,e+124,12,this.size)||this.needPax,this.needPax=Qa(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=zn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=zn(t,e+265,32,this.uname)||this.needPax,this.needPax=zn(t,e+297,32,this.gname)||this.needPax,this.needPax=yn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=yn(t,e+337,8,this.devmin)||this.needPax,this.needPax=zn(t,e+345,n,c)||this.needPax,t[e+475]!==0?this.needPax=zn(t,e+345,155,c)||this.needPax:(this.needPax=zn(t,e+345,130,c)||this.needPax,this.needPax=Qa(t,e+476,12,this.atime)||this.needPax,this.needPax=Qa(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,yn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:ro.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Bc.get(t));if(qs(e)||e==="Unsupported")this.#e=e;else if(qs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},yw=(t,e)=>{let n=t,i="",s,c=wr.parse(t).root||".";if(Buffer.byteLength(n)<100)s=[n,i,!1];else{i=wr.dirname(n),n=wr.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?s=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?s=[n.slice(0,99),i,!0]:(n=wr.join(wr.basename(i),n),i=wr.dirname(i));while(i!==c&&s===void 0);s||(s=[t.slice(0,99),"",!0])}return s},Fn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),Xa=(t,e,n)=>bw(_n(t,e,n)),bw=t=>t===void 0?void 0:new Date(t*1e3),_n=(t,e,n)=>Number(t[e])&128?pw(t.subarray(e,e+n)):vw(t,e,n),Ew=t=>isNaN(t)?void 0:t,vw=(t,e,n)=>Ew(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),Sw={12:8589934591,8:2097151},yn=(t,e,n,i)=>i===void 0?!1:i>Sw[n]||i<0?(fw(i,t.subarray(e,e+n)),!0):(Iw(t,e,n,i),!1),Iw=(t,e,n,i)=>t.write(Aw(i,n),e,n,"ascii"),Aw=(t,e)=>Tw(Math.floor(t).toString(8),e),Tw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Qa=(t,e,n,i)=>i===void 0?!1:yn(t,e,n,i.getTime()/1e3),kw=new Array(156).join("\0"),zn=(t,e,n,i)=>i===void 0?!1:(t.write(i+kw,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),Ys=class df{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!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=n,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 n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),s=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)s[c]=0;new $n({path:("PaxHeader/"+Cw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,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(s),s.write(e,512,n,"utf8");for(let c=n+512;c<s.length;c++)s[c]=0;return s}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 n=this[e],i=n instanceof Date?n.getTime()/1e3:n,s=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(s),d=Math.floor(Math.log(c)/Math.log(10))+1;return c+d>=Math.pow(10,d)&&(d+=1),d+c+s}static parse(e,n,i=!1){return new df(Dw(Rw(e),n),i)}},Dw=(t,e)=>e?Object.assign({},e,t):t,Rw=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(Pw,Object.create(null)),Pw=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),s=i.shift();if(!s)return t;let c=s.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},Ow=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Y=Ow!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Lw=class extends Vn{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,n){switch(super({}),this.pause(),this.extended=e,this.globalExtended=n,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),n&&this.#e(n,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let n=this.remain,i=this.blockRemain;return this.remain=Math.max(0,n-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:n>=e?super.write(t):super.write(t.subarray(0,n))}#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(([n,i])=>!(i==null||n==="path"&&e))))}},io=(t,e,n,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=n instanceof Error&&n.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(n instanceof Error&&(i=Object.assign(n,i),n=n.message),t.emit("warn",e,n,i)):n instanceof Error?t.emit("error",Object.assign(n,i)):t.emit("error",Object.assign(new Error(`${e}: ${n}`),i))},Nw=1024*1024,pc=Buffer.from([31,139]),gc=Buffer.from([40,181,47,253]),Mw=Math.max(pc.length,gc.length),ft=Symbol("state"),Un=Symbol("writeEntry"),Kt=Symbol("readEntry"),ec=Symbol("nextEntry"),Su=Symbol("processEntry"),Ct=Symbol("extendedHeader"),gi=Symbol("globalExtendedHeader"),xn=Symbol("meta"),Iu=Symbol("emitMeta"),ye=Symbol("buffer"),$t=Symbol("queue"),pn=Symbol("ended"),tc=Symbol("emittedEnd"),Gn=Symbol("emit"),Pe=Symbol("unzip"),Ps=Symbol("consumeChunk"),Os=Symbol("consumeChunkSub"),nc=Symbol("consumeBody"),Au=Symbol("consumeMeta"),Tu=Symbol("consumeHeader"),mi=Symbol("consuming"),rc=Symbol("bufferConcat"),Ls=Symbol("maybeEnd"),_r=Symbol("writing"),gn=Symbol("aborted"),Ns=Symbol("onDone"),qn=Symbol("sawValidEntry"),Ms=Symbol("sawNullBlock"),Bs=Symbol("sawEOF"),ku=Symbol("closeStream"),Bw=()=>!0,Oi=class extends tw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[$t]=[];[ye];[Kt];[Un];[ft]="begin";[xn]="";[Ct];[gi];[pn]=!1;[Pe];[gn]=!1;[qn];[Ms]=!1;[Bs]=!1;[_r]=!1;[mi]=!1;[tc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ns,()=>{(this[ft]==="begin"||this[qn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ns,t.ondone):this.on(Ns,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Nw,this.filter=typeof t.filter=="function"?t.filter:Bw;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 n=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:n?!0:void 0,this.on("end",()=>this[ku]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){io(this,t,e,n)}[Tu](t,e){this[qn]===void 0&&(this[qn]=!1);let n;try{n=new $n(t,e,this[Ct],this[gi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Ms]?(this[Bs]=!0,this[ft]==="begin"&&(this[ft]="header"),this[Gn]("eof")):(this[Ms]=!0,this[Gn]("nullBlock"));else if(this[Ms]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let s=this[Un]=new Lw(n,this[Ct],this[gi]);if(!this[qn])if(s.remain){let c=()=>{s.invalid||(this[qn]=!0)};s.on("end",c)}else this[qn]=!0;s.meta?s.size>this.maxMetaEntrySize?(s.ignore=!0,this[Gn]("ignoredEntry",s),this[ft]="ignore",s.resume()):s.size>0&&(this[xn]="",s.on("data",c=>this[xn]+=c),this[ft]="meta"):(this[Ct]=void 0,s.ignore=s.ignore||!this.filter(s.path,s),s.ignore?(this[Gn]("ignoredEntry",s),this[ft]=s.remain?"ignore":"header",s.resume()):(s.remain?this[ft]="body":(this[ft]="header",s.end()),this[Kt]?this[$t].push(s):(this[$t].push(s),this[ec]())))}}}[ku](){queueMicrotask(()=>this.emit("close"))}[Su](t){let e=!0;if(!t)this[Kt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Kt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ec]()),e=!1);return e}[ec](){do;while(this[Su](this[$t].shift()));if(this[$t].length===0){let t=this[Kt];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[nc](t,e){let n=this[Un];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,s=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(s),n.blockRemain||(this[ft]="header",this[Un]=void 0,n.end()),s.length}[Au](t,e){let n=this[Un],i=this[nc](t,e);return!this[Un]&&n&&this[Iu](n),i}[Gn](t,e,n){this[$t].length===0&&!this[Kt]?this.emit(t,e,n):this[$t].push([t,e,n])}[Iu](t){switch(this[Gn]("meta",this[xn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=Ys.parse(this[xn],this[Ct],!1);break;case"GlobalExtendedHeader":this[gi]=Ys.parse(this[xn],this[gi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[xn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[xn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[gn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[gn])return n?.(),!1;if((this[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[ye]&&(t=Buffer.concat([this[ye],t]),this[ye]=void 0),t.length<Mw)return this[ye]=t,n?.(),!0;for(let d=0;this[Pe]===void 0&&d<pc.length;d++)t[d]!==pc[d]&&(this[Pe]=!1);let s=!1;if(this[Pe]===!1&&this.zstd!==!1){s=!0;for(let d=0;d<gc.length;d++)if(t[d]!==gc[d]){s=!1;break}}let c=this.brotli===void 0&&!s;if(this[Pe]===!1&&c)if(t.length<512)if(this[pn])this.brotli=!0;else return this[ye]=t,n?.(),!0;else try{new $n(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Pe]===void 0||this[Pe]===!1&&(this.brotli||s)){let d=this[pn];this[pn]=!1,this[Pe]=this[Pe]===void 0?new aw({}):s?new uw({}):new dw({}),this[Pe].on("data",h=>this[Ps](h)),this[Pe].on("error",h=>this.abort(h)),this[Pe].on("end",()=>{this[pn]=!0,this[Ps]()}),this[_r]=!0;let u=!!this[Pe][d?"end":"write"](t);return this[_r]=!1,n?.(),u}}this[_r]=!0,this[Pe]?this[Pe].write(t):this[Ps](t),this[_r]=!1;let i=this[$t].length>0?!1:this[Kt]?this[Kt].flowing:!0;return!i&&this[$t].length===0&&this[Kt]?.once("drain",()=>this.emit("drain")),n?.(),i}[rc](t){t&&!this[gn]&&(this[ye]=this[ye]?Buffer.concat([this[ye],t]):t)}[Ls](){if(this[pn]&&!this[tc]&&!this[gn]&&!this[mi]){this[tc]=!0;let t=this[Un];if(t&&t.blockRemain){let e=this[ye]?this[ye].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ye]&&t.write(this[ye]),t.end()}this[Gn](Ns)}}[Ps](t){if(this[mi]&&t)this[rc](t);else if(!t&&!this[ye])this[Ls]();else if(t){if(this[mi]=!0,this[ye]){this[rc](t);let e=this[ye];this[ye]=void 0,this[Os](e)}else this[Os](t);for(;this[ye]&&this[ye]?.length>=512&&!this[gn]&&!this[Bs];){let e=this[ye];this[ye]=void 0,this[Os](e)}this[mi]=!1}(!this[ye]||this[pn])&&this[Ls]()}[Os](t){let e=0,n=t.length;for(;e+512<=n&&!this[gn]&&!this[Bs];)switch(this[ft]){case"begin":case"header":this[Tu](t,e),e+=512;break;case"ignore":case"body":e+=this[nc](t,e);break;case"meta":e+=this[Au](t,e);break;default:throw new Error("invalid state: "+this[ft])}e<n&&(this[ye]=this[ye]?Buffer.concat([t.subarray(e),this[ye]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[gn]||(this[Pe]?(t&&this[Pe].write(t),this[Pe].end()):(this[pn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ls]())),this}},Ai=t=>{let e=t.length-1,n=-1;for(;e>-1&&t.charAt(e)==="/";)n=e,e--;return n===-1?t:t.slice(0,n)},Fw=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},lf=(t,e)=>{let n=new Map(e.map(c=>[Ai(c),!0])),i=t.filter,s=(c,d="")=>{let u=d||$m(c).root||".",h;if(c===u)h=!1;else{let x=n.get(c);h=x!==void 0?x:s(Km(c),u)}return n.set(c,h),h};t.filter=i?(c,d)=>i(c,d)&&s(Ai(c)):c=>s(Ai(c))},zw=t=>{let e=new Oi(t),n=t.file,i;try{i=Ir.openSync(n,"r");let s=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(s.size<c){let d=Buffer.allocUnsafe(s.size),u=Ir.readSync(i,d,0,s.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(c);for(;d<s.size;){let h=Ir.readSync(i,u,0,c,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Ir.closeSync(i)}catch{}}},Uw=(t,e)=>{let n=new Oi(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("end",c),Ir.stat(s,(u,h)=>{if(u)d(u);else{let x=new Lc(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Cr=Li(zw,Uw,t=>new Oi(t),t=>new Oi(t),(t,e)=>{e?.length&&lf(t,e),t.noResume||Fw(t)}),uf=(t,e,n)=>(t&=4095,n&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:qw,parse:Du}=Gw,Fc=t=>{let e="",n=Du(t);for(;qw(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Du(t)}return[e,t]},so=["|","<",">","?",":"],zc=so.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Hw=new Map(so.map((t,e)=>[t,zc[e]])),jw=new Map(zc.map((t,e)=>[t,so[e]])),Ru=t=>so.reduce((e,n)=>e.split(n).join(Hw.get(n)),t),Ww=t=>zc.reduce((e,n)=>e.split(n).join(jw.get(n)),t),ff=(t,e)=>e?(t=Y(t).replace(/^\.(\/|$)/,""),Ai(e)+"/"+t):Y(t),Kw=16*1024*1024,Pu=Symbol("process"),Ou=Symbol("file"),Lu=Symbol("directory"),mc=Symbol("symlink"),Nu=Symbol("hardlink"),wi=Symbol("header"),Hs=Symbol("read"),wc=Symbol("lstat"),js=Symbol("onlstat"),_c=Symbol("onread"),yc=Symbol("onreadlink"),bc=Symbol("openfile"),Ec=Symbol("onopenfile"),bn=Symbol("close"),Qs=Symbol("mode"),vc=Symbol("awaitDrain"),ic=Symbol("ondrain"),Rt=Symbol("prefix"),hf=class extends Vn{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 n=Nc(e);super(),this.path=Y(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||Kw,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=Y(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?Y(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=Fc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=Ww(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Y(n.absolute||Cu.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 s=this.statCache.get(this.absolute);s?this[js](s):this[wc]()}warn(t,e,n={}){return io(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[wc](){Dt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[js](e)})}[js](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Jw(t),this.emit("stat",t),this[Pu]()}[Pu](){switch(this.type){case"File":return this[Ou]();case"Directory":return this[Lu]();case"SymbolicLink":return this[mc]();default:return this.end()}}[Qs](t){return uf(t,this.type==="Directory",this.portable)}[Rt](t){return ff(t,this.prefix)}[wi](){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 $n({path:this[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](this.linkpath):this.linkpath,mode:this[Qs](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 Ys({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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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)}[Lu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[wi](),this.end()}[mc](){Dt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[yc](e)})}[yc](t){this.linkpath=Y(t),this[wi](),this.end()}[Nu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Y(Cu.relative(this.cwd,t)),this.stat.size=0,this[wi](),this.end()}[Ou](){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[Nu](e);this.linkCache.set(t,this.absolute)}if(this[wi](),this.stat.size===0)return this.end();this[bc]()}[bc](){Dt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ec](e)})}[Ec](t){if(this.fd=t,this.#e)return this[bn]();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[Hs]()}[Hs](){let{fd:t,buf:e,offset:n,length:i,pos:s}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Dt.read(t,e,n,i,s,(c,d)=>{if(c)return this[bn](()=>this.emit("error",c));this[_c](d)})}[bn](t=()=>{}){this.fd!==void 0&&Dt.close(this.fd,t)}[_c](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[bn](()=>this.emit("error",n))}if(t>this.remain){let n=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[bn](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let n=t;n<this.length&&t<this.blockRemain;n++)this.buf[n+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[ic]():this[vc](()=>this[ic]())}[vc](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=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,n)}[ic](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[bn](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[Hs]()}},$w=class extends hf{sync=!0;[wc](){this[js](Dt.lstatSync(this.absolute))}[mc](){this[yc](Dt.readlinkSync(this.absolute))}[bc](){this[Ec](Dt.openSync(this.absolute,"r"))}[Hs](){let t=!0;try{let{fd:e,buf:n,offset:i,length:s,pos:c}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let d=Dt.readSync(e,n,i,s,c);this[_c](d),t=!1}finally{if(t)try{this[bn](()=>{})}catch{}}}[vc](t){t()}[bn](t=()=>{}){this.fd!==void 0&&Dt.closeSync(this.fd),t()}},Vw=class extends Vn{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,n={}){return io(this,t,e,n)}constructor(t,e={}){let n=Nc(e);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.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=n.prefix,this.path=Y(t.path),this.mode=t.mode!==void 0?this[Qs](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:n.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 n.onwarn=="function"&&this.on("warn",n.onwarn);let s=!1;if(!this.preservePaths){let[d,u]=Fc(this.path);d&&typeof u=="string"&&(this.path=u,s=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new $n({path:this[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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}),s&&this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute path`,{entry:this,path:s+this.path}),this.header.encode()&&!this.noPax&&super.write(new Ys({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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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)}[Rt](t){return ff(t,this.prefix)}[Qs](t){return uf(t,this.type==="Directory",this.portable)}write(t,e,n){typeof e=="function"&&(n=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,n)}end(t,e,n){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),n&&this.once("finish",n),t?super.end(t,n):super.end(n),this}},Jw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",Zw=class Ar{tail;head;length=0;static create(e=[]){return new Ar(e)}constructor(e=[]){for(let n of e)this.push(n)}*[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 n=e.next,i=e.prev;return n&&(n.prev=i),i&&(i.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.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 n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,i=e.length;n<i;n++)Xw(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)Qw(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,s=0;i;s++)e.call(n,i.value,s,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,s=this.length-1;i;s--)e.call(n,i.value,s,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Ar;for(let s=this.head;s;)i.push(e.call(n,s.value,this)),s=s.next;return i}mapReverse(e,n){n=n||this;var i=new Ar;for(let s=this.tail;s;)i.push(e.call(n,s.value,this)),s=s.prev;return i}reduce(e,n){let i,s=this.head;if(arguments.length>1)i=n;else if(this.head)s=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;s;c++)i=e(i,s.value,c),s=s.next;return i}reduceReverse(e,n){let i,s=this.tail;if(arguments.length>1)i=n;else if(this.tail)s=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;s;c--)i=e(i,s.value,c),s=s.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Ar;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.head,c=0;for(c=0;s&&c<e;c++)s=s.next;for(;s&&c<n;c++,s=s.next)i.push(s.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Ar;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.length,c=this.tail;for(;c&&s>n;s--)c=c.prev;for(;c&&s>e;s--,c=c.prev)i.push(c.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let s=this.head;for(let d=0;s&&d<e;d++)s=s.next;let c=[];for(let d=0;s&&d<n;d++)c.push(s.value),s=this.removeNode(s);s?s!==this.tail&&(s=s.prev):s=this.tail;for(let d of i)s=Yw(this,s,d);return c}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let s=i.prev;i.prev=i.next,i.next=s}return this.head=n,this.tail=e,this}};function Yw(t,e,n){let i=e,s=e?e.next:t.head,c=new Uc(n,i,s,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function Xw(t,e){t.tail=new Uc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Qw(t,e){t.head=new Uc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Uc=class{list;next;prev;value;constructor(t,e,n,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,n?(n.prev=this,this.next=n):this.next=void 0}},Bu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Fu=Buffer.alloc(1024),Ws=Symbol("onStat"),_i=Symbol("ended"),yt=Symbol("queue"),yi=Symbol("pendingLinks"),mn=Symbol("current"),Hn=Symbol("process"),bi=Symbol("processing"),Fs=Symbol("processJob"),bt=Symbol("jobs"),sc=Symbol("jobDone"),Ks=Symbol("addFSEntry"),zu=Symbol("addTarEntry"),Sc=Symbol("stat"),Ic=Symbol("readdir"),$s=Symbol("onreaddir"),Vs=Symbol("pipe"),Uu=Symbol("entry"),oc=Symbol("entryOpt"),Js=Symbol("writeEntryClass"),xf=Symbol("write"),ac=Symbol("ondrain"),oo=class extends Vn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Js];onWriteEntry;[yt];[yi]=new Map;[bt]=0;[bi]=!1;[_i]=!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[Js]=hf,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 ow(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new cw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new lw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[ac]()),this.on("resume",()=>e.resume())}else this.on("drain",this[ac]);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[yt]=new Zw,this[bt]=0,this.jobs=Number(t.jobs)||4,this[bi]=!1,this[_i]=!1}[xf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&this.add(t),this[_i]=!0,this[Hn](),n&&n(),this}write(t){if(this[_i])throw new Error("write after end");return typeof t=="string"?this[Ks](t):this[zu](t),this.flowing}[zu](t){let e=Y(Mu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new Bu(t.path,e);n.entry=new Vw(t,this[oc](n)),n.entry.on("end",()=>this[sc](n)),this[bt]+=1,this[yt].push(n)}this[Hn]()}[Ks](t){let e=Y(Mu.resolve(this.cwd,t));this[yt].push(new Bu(t,e)),this[Hn]()}[Sc](t){t.pending=!0,this[bt]+=1;let e=this.follow?"stat":"lstat";Xs[e](t.absolute,(n,i)=>{t.pending=!1,this[bt]-=1,n?this.emit("error",n):this[Ws](t,i)})}[Ws](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[mn])this[Fs](t);else{let n=`${e.dev}:${e.ino}`,i=this[yi].get(n);i?i.push(t):this[yi].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Hn]()}[Ic](t){t.pending=!0,this[bt]+=1,Xs.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[bt]-=1,e)return this.emit("error",e);this[$s](t,n)})}[$s](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Hn]()}[Hn](){if(!this[bi]){this[bi]=!0;for(let t=this[yt].head;t&&this[bt]<this.jobs;t=t.next)if(this[Fs](t.value),t.value.ignore){let e=t.next;this[yt].removeNode(t),t.next=e}this[bi]=!1,this[_i]&&this[yt].length===0&&this[bt]===0&&(this.zip?this.zip.end(Fu):(super.write(Fu),super.end()))}}get[mn](){return this[yt]&&this[yt].head&&this[yt].head.value}[sc](t){this[yt].shift(),this[bt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[yi].get(n);if(i){this[yi].delete(n);for(let s of i)s.pending=!1,this[Fs](s)}}this[Hn]()}[Fs](t){if(t.pending&&t.pendingLink&&t===this[mn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[mn]&&!t.piped&&this[Vs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Ws](t,e):this[Sc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[$s](t,e):this[Ic](t),!t.readdir)return}if(t.entry=this[Uu](t),!t.entry){t.ignore=!0;return}t===this[mn]&&!t.piped&&this[Vs](t)}}}[oc](t){return{onwarn:(e,n,i)=>this.warn(e,n,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}}[Uu](t){this[bt]+=1;try{return new this[Js](t.path,this[oc](t)).on("end",()=>this[sc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[ac](){this[mn]&&this[mn].entry&&this[mn].entry.resume()}[Vs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let s=t.path,c=s==="./"?"":s.replace(/\/*$/,"/");this[Ks](c+i)});let e=t.entry,n=this.zip;if(!e)throw new Error("cannot pipe without source");n?e.on("data",i=>{n.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,n={}){io(this,t,e,n)}},Gc=class extends oo{sync=!0;constructor(t){super(t),this[Js]=$w}pause(){}resume(){}[Sc](t){let e=this.follow?"statSync":"lstatSync";this[Ws](t,Xs[e](t.absolute))}[Ic](t){this[$s](t,Xs.readdirSync(t.absolute))}[Vs](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let s=t.path,c=s==="./"?"":s.replace(/\/*$/,"/");this[Ks](c+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[xf](i)})}},e_=(t,e)=>{let n=new Gc(t),i=new ef(t.file,{mode:t.mode||438});n.pipe(i),pf(n,e)},t_=(t,e)=>{let n=new oo(t),i=new no(t.file,{mode:t.mode||438});n.pipe(i);let s=new Promise((c,d)=>{i.on("error",d),i.on("close",c),n.on("error",d)});return gf(n,e).catch(c=>n.emit("error",c)),s},pf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Cr({file:tf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},gf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Cr({file:tf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},n_=(t,e)=>{let n=new Gc(t);return pf(n,e),n},r_=(t,e)=>{let n=new oo(t);return gf(n,e).catch(i=>n.emit("error",i)),n},kI=Li(e_,t_,n_,r_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),s_=process.env.__FAKE_PLATFORM__||process.platform,yf=s_==="win32",{O_CREAT:bf,O_NOFOLLOW:Gu,O_TRUNC:Ef,O_WRONLY:vf}=_f.constants,Sf=Number(process.env.__FAKE_FS_O_FILENAME__)||_f.constants.UV_FS_O_FILEMAP||0,o_=yf&&!!Sf,a_=512*1024,c_=Sf|Ef|bf|vf,qu=!yf&&typeof Gu=="number"?Gu|Ef|bf|vf:null,If=qu!==null?()=>qu:o_?t=>t<a_?c_:"w":()=>"w",Ac=(t,e,n)=>{try{return ao.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},eo=(t,e,n,i)=>{ao.lchown(t,e,n,s=>{i(s&&s?.code!=="ENOENT"?s:null)})},d_=(t,e,n,i,s)=>{if(e.isDirectory())Af(Ti.resolve(t,e.name),n,i,c=>{if(c)return s(c);let d=Ti.resolve(t,e.name);eo(d,n,i,s)});else{let c=Ti.resolve(t,e.name);eo(c,n,i,s)}},Af=(t,e,n,i)=>{ao.readdir(t,{withFileTypes:!0},(s,c)=>{if(s){if(s.code==="ENOENT")return i();if(s.code!=="ENOTDIR"&&s.code!=="ENOTSUP")return i(s)}if(s||!c.length)return eo(t,e,n,i);let d=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return eo(t,e,n,i)}};for(let x of c)d_(t,x,e,n,h)})},l_=(t,e,n,i)=>{e.isDirectory()&&Tf(Ti.resolve(t,e.name),n,i),Ac(Ti.resolve(t,e.name),n,i)},Tf=(t,e,n)=>{let i;try{i=ao.readdirSync(t,{withFileTypes:!0})}catch(s){let c=s;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Ac(t,e,n);throw c}for(let s of i)l_(t,s,e,n);return Ac(t,e,n)},kf=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"}},co=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"}},f_=(t,e)=>{ct.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new kf(t,n?.code||"ENOTDIR")),e(n)})},h_=(t,e,n)=>{t=Y(t);let i=e.umask??18,s=e.mode|448,c=(s&i)!==0,d=e.uid,u=e.gid,h=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,m=e.unlink,_=Y(e.cwd),S=(v,I)=>{v?n(v):I&&h?Af(I,d,u,A=>S(A)):c?ct.chmod(t,s,n):n()};if(t===_)return f_(t,S);if(x)return u_.mkdir(t,{mode:s,recursive:!0}).then(v=>S(null,v??void 0),S);let y=Y(to.relative(_,t)).split("/");Tc(_,y,s,m,_,void 0,S)},Tc=(t,e,n,i,s,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),h=Y(to.resolve(t+"/"+u));ct.mkdir(h,n,Cf(h,e,n,i,s,c,d))},Cf=(t,e,n,i,s,c,d)=>u=>{u?ct.lstat(t,(h,x)=>{if(h)h.path=h.path&&Y(h.path),d(h);else if(x.isDirectory())Tc(t,e,n,i,s,c,d);else if(i)ct.unlink(t,m=>{if(m)return d(m);ct.mkdir(t,n,Cf(t,e,n,i,s,c,d))});else{if(x.isSymbolicLink())return d(new co(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Tc(t,e,n,i,s,c,d))},x_=t=>{let e=!1,n;try{e=ct.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new kf(t,n??"ENOTDIR")}},p_=(t,e)=>{t=Y(t);let n=e.umask??18,i=e.mode|448,s=(i&n)!==0,c=e.uid,d=e.gid,u=typeof c=="number"&&typeof d=="number"&&(c!==e.processUid||d!==e.processGid),h=e.preserve,x=e.unlink,m=Y(e.cwd),_=v=>{v&&u&&Tf(v,c,d),s&&ct.chmodSync(t,i)};if(t===m)return x_(m),_();if(h)return _(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Y(to.relative(m,t)).split("/"),y;for(let v=S.shift(),I=m;v&&(I+="/"+v);v=S.shift()){I=Y(to.resolve(I));try{ct.mkdirSync(I,i),y=y||I}catch{let A=ct.lstatSync(I);if(A.isDirectory())continue;if(x){ct.unlinkSync(I),ct.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new co(I,I+"/"+S.join("/"))}}return _(y)},cc=Object.create(null),Hu=1e4,yr=new Set,g_=t=>{yr.has(t)?yr.delete(t):cc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=cc[t],n=yr.size-Hu;if(n>Hu/10){for(let i of yr)if(yr.delete(i),delete cc[i],--n<=0)break}return e},m_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,w_=m_==="win32",__=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Df(i,n)),e.push(n||"/"),e},[]),y_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=w_?["win32 parallelization disabled"]:t.map(i=>Ai(Df(g_(i))));let n=new Set(t.map(i=>__(i)).reduce((i,s)=>i.concat(s)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let s=this.#e.get(i);s?s.push(e):this.#e.set(i,[e])}for(let i of n){let s=this.#e.get(i);if(!s)this.#e.set(i,[new Set([e])]);else{let c=s.at(-1);c instanceof Set?c.add(e):s.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(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.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:n,dirs:i}=e,s=new Set;for(let c of n){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")s.add(u);else for(let h of u)s.add(h)}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 h=d[0];typeof h=="function"&&s.add(h)}else u.delete(t)}return this.#r.delete(t),s.forEach(c=>this.#i(c)),!0}},b_=()=>process.umask(),ju=Symbol("onEntry"),kc=Symbol("checkFs"),Wu=Symbol("checkFs2"),Cc=Symbol("isReusable"),ht=Symbol("makeFs"),Dc=Symbol("file"),Rc=Symbol("directory"),Zs=Symbol("link"),Ku=Symbol("symlink"),$u=Symbol("hardlink"),Si=Symbol("ensureNoSymlink"),Vu=Symbol("unsupported"),Ju=Symbol("checkPath"),dc=Symbol("stripAbsolutePath"),En=Symbol("mkdir"),je=Symbol("onError"),zs=Symbol("pending"),Zu=Symbol("pend"),br=Symbol("unpend"),lc=Symbol("ended"),uc=Symbol("maybeClose"),Pc=Symbol("skip"),ki=Symbol("doChown"),Ci=Symbol("uid"),Di=Symbol("gid"),Ri=Symbol("checkedCwd"),E_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Pi=E_==="win32",v_=1024,S_=(t,e)=>{if(!Pi)return ne.unlink(t,e);let n=t+".DELETE."+wf(16).toString("hex");ne.rename(t,n,i=>{if(i)return e(i);ne.unlink(n,e)})},I_=t=>{if(!Pi)return ne.unlinkSync(t);let e=t+".DELETE."+wf(16).toString("hex");ne.renameSync(t,e),ne.unlinkSync(e)},Yu=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,qc=class extends Oi{[lc]=!1;[Ri]=!1;[zs]=0;reservations=new y_;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[lc]=!0,this[uc]()},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:v_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Pi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Y(ze.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:b_():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[ju](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[uc](){this[lc]&&this[zs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[dc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[s,c]=Fc(n),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Pi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=ze.posix.dirname(t.path),h=ze.posix.normalize(ze.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return s&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute ${e}`,{entry:t,[e]:n})),!0}[Ju](t){let e=Y(t.path),n=e.split("/");if(this.strip){if(n.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}n.splice(0,this.strip),t.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[dc](t,"path")||!this[dc](t,"linkpath"))return!1;if(t.absolute=ze.isAbsolute(t.path)?Y(ze.resolve(t.path)):Y(ze.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}=ze.win32.parse(String(t.absolute));t.absolute=i+Ru(String(t.absolute).slice(i.length));let{root:s}=ze.win32.parse(t.path);t.path=s+Ru(t.path.slice(s.length))}return!0}[ju](t){if(!this[Ju](t))return t.resume();switch(i_.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[kc](t);default:return this[Vu](t)}}[je](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[br](),e.resume())}[En](t,e,n){h_(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},n)}[ki](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}[Ci](t){return Yu(this.uid,t.uid,this.processUid)}[Di](t){return Yu(this.gid,t.gid,this.processGid)}[Dc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new no(String(t.absolute),{flags:If(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&ne.close(i.fd,()=>{}),i.write=()=>!0,this[je](u,t),e()});let s=1,c=u=>{if(u){i.fd&&ne.close(i.fd,()=>{}),this[je](u,t),e();return}--s===0&&i.fd!==void 0&&ne.close(i.fd,h=>{h?this[je](h,t):this[br](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){s++;let x=t.atime||new Date,m=t.mtime;ne.futimes(h,x,m,_=>_?ne.utimes(u,x,m,S=>c(S&&_)):c())}if(typeof h=="number"&&this[ki](t)){s++;let x=this[Ci](t),m=this[Di](t);typeof x=="number"&&typeof m=="number"&&ne.fchown(h,x,m,_=>_?ne.chown(u,x,m,S=>c(S&&_)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[je](u,t),e()}),t.pipe(d)),d.pipe(i)}[Rc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[En](String(t.absolute),n,i=>{if(i){this[je](i,t),e();return}let s=1,c=()=>{--s===0&&(e(),this[br](),t.resume())};t.mtime&&!this.noMtime&&(s++,ne.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[ki](t)&&(s++,ne.chown(String(t.absolute),Number(this[Ci](t)),Number(this[Di](t)),c)),c()})}[Vu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ku](t,e){let n=Y(ze.relative(this.cwd,ze.resolve(ze.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Si](t,this.cwd,n,()=>this[Zs](t,String(t.linkpath),"symlink",e),i=>{this[je](i,t),e()})}[$u](t,e){let n=Y(ze.resolve(this.cwd,String(t.linkpath))),i=Y(String(t.linkpath)).split("/");this[Si](t,this.cwd,i,()=>this[Zs](t,n,"link",e),s=>{this[je](s,t),e()})}[Si](t,e,n,i,s){let c=n.shift();if(this.preservePaths||c===void 0)return i();let d=ze.resolve(e,c);ne.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return s(new co(d,ze.resolve(d,n.join("/"))));this[Si](t,d,n,i,s)})}[Zu](){this[zs]++}[br](){this[zs]--,this[uc]()}[Pc](t){this[br](),t.resume()}[Cc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Pi}[kc](t){this[Zu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[Wu](t,n))}[Wu](t,e){let n=d=>{e(d)},i=()=>{this[En](this.cwd,this.dmode,d=>{if(d){this[je](d,t),n();return}this[Ri]=!0,s()})},s=()=>{if(t.absolute!==this.cwd){let d=Y(ze.dirname(String(t.absolute)));if(d!==this.cwd)return this[En](d,this.dmode,u=>{if(u){this[je](u,t),n();return}c()})}c()},c=()=>{ne.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Pc](t),n();return}if(d||this[Cc](t,u))return this[ht](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=m=>this[ht](m??null,t,n);return h?ne.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ne.rmdir(String(t.absolute),h=>this[ht](h??null,t,n))}if(t.absolute===this.cwd)return this[ht](null,t,n);S_(String(t.absolute),h=>this[ht](h??null,t,n))})};this[Ri]?s():i()}[ht](t,e,n){if(t){this[je](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Dc](e,n);case"Link":return this[$u](e,n);case"SymbolicLink":return this[Ku](e,n);case"Directory":case"GNUDumpDir":return this[Rc](e,n)}}[Zs](t,e,n,i){ne[n](e,String(t.absolute),s=>{s?this[je](s,t):(this[br](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},Rf=class extends qc{sync=!0;[ht](t,e){return super[ht](t,e,()=>{})}[kc](t){if(!this[Ri]){let s=this[En](this.cwd,this.dmode);if(s)return this[je](s,t);this[Ri]=!0}if(t.absolute!==this.cwd){let s=Y(ze.dirname(String(t.absolute)));if(s!==this.cwd){let c=this[En](s,this.dmode);if(c)return this[je](c,t)}}let[e,n]=Ei(()=>ne.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Pc](t);if(e||this[Cc](t,n))return this[ht](null,t);if(n.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=c?Ei(()=>{ne.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ht](d,t)}let[s]=Ei(()=>ne.rmdirSync(String(t.absolute)));this[ht](s,t)}let[i]=t.absolute===this.cwd?[]:Ei(()=>I_(String(t.absolute)));this[ht](i,t)}[Dc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{ne.closeSync(s)}catch(h){u=h}(d||u)&&this[je](d||u,t),e()},s;try{s=ne.openSync(String(t.absolute),If(t.size),n)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[je](d,t)),t.pipe(c)),c.on("data",d=>{try{ne.writeSync(s,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,h=t.mtime;try{ne.futimesSync(s,u,h)}catch(x){try{ne.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[ki](t)){let u=this[Ci](t),h=this[Di](t);try{ne.fchownSync(s,Number(u),Number(h))}catch(x){try{ne.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[Rc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[En](String(t.absolute),n);if(i){this[je](i,t),e();return}if(t.mtime&&!this.noMtime)try{ne.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ki](t))try{ne.chownSync(String(t.absolute),Number(this[Ci](t)),Number(this[Di](t)))}catch{}e(),t.resume()}[En](t,e){try{return p_(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(n){return n}}[Si](t,e,n,i,s){if(this.preservePaths||n.length===0)return i();let c=e;for(let d of n){c=ze.resolve(c,d);let[u,h]=Ei(()=>ne.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return s(new co(c,ze.resolve(e,n.join("/"))))}i()}[Zs](t,e,n,i){let s=`${n}Sync`;try{ne[s](e,String(t.absolute)),i(),t.resume()}catch(c){return this[je](c,t)}}},A_=t=>{let e=new Rf(t),n=t.file,i=mf.statSync(n),s=t.maxReadSize||16*1024*1024;new Wm(n,{readSize:s,size:i.size}).pipe(e)},T_=(t,e)=>{let n=new qc(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("close",c),mf.stat(s,(u,h)=>{if(u)d(u);else{let x=new Lc(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Pf=Li(A_,T_,t=>new Rf(t),t=>new qc(t),(t,e)=>{e?.length&&lf(t,e)}),k_=(t,e)=>{let n=new Gc(t),i=!0,s,c;try{try{s=at.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")s=at.openSync(t.file,"w+");else throw h}let d=at.fstatSync(s),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let m=0,_=0;m<512;m+=_){if(_=at.readSync(s,u,m,u.length-m,c+m),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!_)break e}let h=new $n(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(c+x+512>d.size)break;c+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,C_(t,n,c,s,e)}finally{if(i)try{at.closeSync(s)}catch{}}},C_=(t,e,n,i,s)=>{let c=new ef(t.file,{fd:i,start:n});e.pipe(c),R_(e,s)},D_=(t,e)=>{e=Array.from(e);let n=new oo(t),i=(s,c,d)=>{let u=(S,y)=>{S?at.close(s,v=>d(S)):d(null,y)},h=0;if(c===0)return u(null,0);let x=0,m=Buffer.alloc(512),_=(S,y)=>{if(S||y===void 0)return u(S);if(x+=y,x<512&&y)return at.read(s,m,x,m.length-x,h+x,_);if(h===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let v=new $n(m);if(!v.cksumValid)return u(null,h);let I=512*Math.ceil((v.size??0)/512);if(h+I+512>c||(h+=I+512,h>=c))return u(null,h);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,at.read(s,m,0,512,h,_)};at.read(s,m,0,512,h,_)};return new Promise((s,c)=>{n.on("error",c);let d="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",at.open(t.file,d,u);if(h||!x)return c(h);at.fstat(x,(m,_)=>{if(m)return at.close(x,()=>c(m));i(x,_.size,(S,y)=>{if(S)return c(S);let v=new no(t.file,{fd:x,start:y});n.pipe(v),v.on("error",c),v.on("close",s),P_(n,e)})})};at.open(t.file,d,u)})},R_=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Cr({file:Of.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},P_=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Cr({file:Of.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},vi=Li(k_,D_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Qm(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")}),HI=Li(vi.syncFile,vi.asyncFile,vi.syncNoFile,vi.asyncNoFile,(t,e=[])=>{vi.validate?.(t,e),O_(t)}),O_=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(n,i)=>e(n,i)&&!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0)):(n,i)=>!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0))};un();var xt={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 lo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Lf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function uo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Nf(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function Mf(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function Jn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Zt();$e();ee();Be();$e();function Dr(t,e){if(lo(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ni(t){return t.startsWith("http://")||t.startsWith("https://")}function Rr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as LA}from"node:fs";import{dirname as MA,join as BA}from"node:path";import{fileURLToPath as zA}from"node:url";var Ot="0.2.1-alpha.10";$e();ee();var fo="1008033",Uf="1289";var Gf="pbbp2",qf="https://www.coze.cn",Hf="/api/coze_claw/resource/get_frontier_key",G_="https://www.coze.cn",q_="wss://frontier.coze.cn";function Pr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??G_}function jf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??q_}function In(t){let e={},n=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return n&&(e["x-tt-env"]=n),i&&(e["x-use-ppe"]=i),e}function Bi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Mi=q("handshake");async function Hc(t){let e=Pr(t.endpoint),n=t.timeoutMs??1e4,i=`${Rr(e)}${Hf}?aid=${encodeURIComponent(fo)}`,s={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...In(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),n);Mi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:s,signal:c.signal}),h=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let v=await u.text().catch(()=>"");throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${v.slice(0,200)}`)}let m=await u.json();if(m.code!==void 0&&m.code!==0)throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${m.code} msg=${m.msg??"-"} logid=${h}`);let _=m.data??{},S=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(!S||!y){let v=JSON.stringify(m).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${v}`)}return Mi.info("handshake ok",{remoteDeviceId:y,logid:h,traceId:x}),{accessKey:S,deviceId:y}}catch(u){if(u instanceof T)throw Mi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Mi.warn("handshake timeout",{base:e,timeoutMs:n}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let h=u.cause;throw Mi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:h?.code,syscall:h?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var Wc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Lt="auto",jc=15e4;function Kf(t){return{model:Kc(t.model)??Lt,...t.modelToken?{modelToken:t.modelToken}:{}}}function $f(t){return!t||t===Lt}var H_=new Set(["auto","\u81EA\u52A8"]);function Kc(t){let e=t?.trim();if(e)return H_.has(e.toLowerCase())?Lt:e}function Vf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Wc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Lt;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=n,e.ANTHROPIC_DEFAULT_OPUS_MODEL=n,e.ANTHROPIC_DEFAULT_SONNET_MODEL=n,e.CLAUDE_CODE_SUBAGENT_MODEL=n,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else $f(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Jf(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Lt}"`):$f(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="${Wc}/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 n=t.modelInfo?.contextWindow??jc;e.push("-c",`model_context_window=${n}`)}return e}function Zf(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function $c(t,e){let{ttEnv:n,usePpe:i}=Bi(t),s={};return n&&(s["x-tt-env"]=n),i&&(s["x-use-ppe"]=i),e&&(s["x-mock-scenario"]=e),s}function Yf(t,e,n){if(!t.modelToken)return{};let i=$c(e,n);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
92
+ `)}}function Vc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Jc(t){return t.model||Lt}function Wf(t,e,n){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:8192,api:"openai-completions"}}function Xf(t,e,n,i){if(!t.modelToken)return null;let s=Jc(t),c=$c(e,n),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[Wf(s,d,t.modelInfo?.contextWindow??jc)],h=new Set([s]);for(let m of i??[])!m||h.has(m)||(h.add(m),u.push(Wf(m,["text"],jc)));let x={baseUrl:`${Wc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(x.headers=c),x}function Qf(t,e,n){if(!t.modelToken)return[];let i=$c(e,n),s=[];for(let[c,d]of Object.entries(i))s.push("-c",`model_providers.coze.http_headers.${c}="${d}"`);return s}var ge=q("agent-handlers"),t0=5*1024*1024,$_=1,V_=6,J_=new Set(["node_modules",".git",".coze","dist","build",".next"]),Z_=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Y_=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,X_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Q_(t){let e=t?.trim();return e?X_.test(e)||Y_.test(e)?e:(ge.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function ey(t){return new Promise((e,n)=>{let i=st("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),s=!1,c=d=>{s||(s=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",d=>c(d))})}var xo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let n=Jn(e._meta),i=await this.loadAgentCfg(n),s=i?.workspace??Ye(n).workspace,c=i?.skills??[],d=[],u=new Set;for(let h of c){let x=Je(s,h.relPath,"SKILL.md");await e0(x).then(_=>_.isFile()).catch(()=>!1)&&(d.push(iy(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",x=await ty(n,s,h);for(let m of x)u.has(m.relPath)||(u.add(m.relPath),d.push(m.skill))}return{skills:d}}async addSkills(e){e._meta;let n=Jn(e._meta),i=await this.requireAgentCfg(n),s=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((h,x)=>[h.skillId,x])),u=[];for(let h of s){let x=await po({agentId:n,workspace:i.workspace,framework:i.framework,skill:h});go(c,d,x),u.push(h)}return await ci(n,c),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=Jn(e._meta),i=await this.requireAgentCfg(n),s=new Set(e.skillIds??[]),c=i.skills??[],d=[];for(let u of c){if(!s.has(u.skillId)){d.push(u);continue}let h=Je(i.workspace,u.relPath);await Xc(h,{recursive:!0,force:!0}),ge.info("skill removed",{agentId:n,skillId:u.skillId,relPath:u.relPath})}return await ci(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=Jn(e._meta);if(!e.skillName)throw new T("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");ge.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),s=i?.workspace??Ye(n).workspace,c=i?.framework??"claude-code",d=a0(e.skillName),u=Je(id(c),d),h=Je(s,u),x=Je(h,"SKILL.md");if(!await e0(x).then(k=>k.isFile()).catch(()=>!1))throw new T("SKILL_NOT_FOUND",`skill not found locally: ${e.skillName} (${u})`);let _=new rd.default;_.addLocalFolder(h,d);let S=_.toBuffer();if(S.length>n0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${S.length} bytes exceeds limit ${n0}`);let y=await ho(x,{encoding:"utf8"}).then(k=>d0(k).description).catch(()=>{}),v={};this.opts.publishSkillToMarketplace?v=await this.opts.publishSkillToMarketplace({zip:S,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...y?{description:y}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):ge.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let I=v.version??"v1.0",A=v.skillId??e.skillId??c0(n,u);if(i){let k=i.skills??[],P=k.find(b=>b.relPath===u);P?(P.version=I,P.skillId=A):k.push({skillId:A,skillName:e.skillName,relPath:u,version:I,installedAt:Date.now(),...y?{description:y}:{}}),await ci(n,k)}return ge.info("skill published",{agentId:n,skillName:e.skillName,relPath:u,zipBytes:S.length,skillId:A,version:I}),{ok:!0,skillId:A,version:I}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[s,c]of i.sessions){if(!c.downstream)continue;let d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,ge.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d});continue}let h=c.downstream;c.downstream=void 0,ge.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d}),h.stop(n).catch(x=>ge.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:s,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return ge.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await Re(n);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return ge.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await hr(i.workspace,i.framework,e.cozeIdentity)}catch(s){throw ge.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(s)}),new T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(s)}`,{cause:s})}return i.cozeIdentity=e.cozeIdentity,await Ue(i),ge.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:i.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async upgradeBridge(e){let n=e.agentId||e._meta?.cozeAgentId;if(!n)throw new T("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Re(n))throw new T("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=["-y"];e.registry&&Ni(e.registry)&&s.push(`--registry=${e.registry}`);let c=Q_(e.targetVersion);s.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&Z_.test(d)&&s.push("--env",d);let u=await ey(s);return ge.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let n=e.agentId;if(!n)throw new T("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Re(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ue(i),ge.info("agent disconnected",{agentId:n,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(n,e.reason??"disconnect"),{ok:!0}):(ge.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new T("IPC_BAD_REQUEST",`${xt.DELETE}: missing agentId`);let i=await Re(n),s=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??s??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let d=Ye(n);return c==="cloud"?await Xc(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ue(i)),ge.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Dr(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=Kc(e.model)??Lt,i=await Re(e.agentId);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ue(i),ge.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return ge.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=s.model;s.model=n,e.modelInfo&&s.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(s,c).catch(u=>ge.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)}));let d=[];for(let[u,h]of s.allSessionQueues())d.push(h.enqueue(async()=>{let x=s.sessions.get(u);x?.downstream&&(await x.downstream.stop(`switchModel: ${n}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(d),ge.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:d.length}),{ok:!0}}async resetAgent(e){if(Dr(e._meta,xt.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${xt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,xt.RESET),await this.runDetailSync(e.agentId,xt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),ge.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(n);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 s=new Map;for(let[c,d]of i.sessions)s.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await ai(e,s)}async clearPersistedAcpSessionIds(e){let n=await Re(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let s of Object.values(n.sessions))s.acpSessionId&&(s.acpSessionId=void 0,i=!0);i&&await Ue(n)}async repairAgent(e){if(Dr(e._meta,xt.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${xt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${xt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){ge.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,xt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){ge.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){ge.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(s)})}}async getFileTree(e){Dr(e._meta,"_agent/getFileTree");let n=e._meta,i=Jn(n),s=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(s,c),u=await Zc(d).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 oi(d,s))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=gy(e.depth);return u.isDirectory()?{tree:await py(s,d,c,h)}:{tree:[{name:my(c),path:f0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Dr(e._meta,"_agent/getFileContent");let n=Jn(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new T("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(i,e.filePath),c=await Zc(s).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 oi(s,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>t0)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${t0})`);let d=await ho(s);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 n=this.opts.agents.get(e);return n?n.workspace:(await Re(e).catch(()=>null))?.workspace??Ye(e).workspace}safeJoin(e,n){let i=ed(e,n||"."),s=nd(e,i);if(s.startsWith("..")||s===".."||s.startsWith(`..${i0}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return Re(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new T("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function a0(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 id(t){return t==="claude-code"?Je(".claude","skills"):Je(".agents","skills")}function c0(t,e){return(j_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function d0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
+ ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let s of n.split(`
94
+ `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(s);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 ty(t,e,n){let i=id(n),s=Je(e,i),c=await r0(s,{withFileTypes:!0}).catch(()=>null);if(!c)return[];let d=[];for(let u of c){if(!u.isDirectory())continue;let h=u.name,x=Je(i,h),m=Je(s,h,"SKILL.md"),_=await ho(m,{encoding:"utf8"}).catch(()=>null);if(_===null)continue;let S=d0(_);d.push({relPath:x,skill:{skillId:c0(t,x),skillName:S.name||h,...S.description?{description:S.description}:{}}})}return d}var ny=3e4,ry=50*1024*1024,n0=10*1024*1024,Or=3e4;async function po(t){let{agentId:e,workspace:n,framework:i,skill:s}=t;if(!s.skillName)throw new T("IPC_BAD_REQUEST","skill missing skillName");let c=typeof s.content=="string"&&s.content.length>0,d=typeof s.downloadUrl=="string"&&s.downloadUrl.length>0;if(!c&&!d)throw new T("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let u=a0(s.skillName),h=id(i),x=Je(h,u),m=Je(n,x);if(await Yc(m,{recursive:!0}),c){let S=Buffer.from(s.content,"utf8");Fi(S.length),await Qc(Je(m,"SKILL.md"),S,"utf8")}else{let S=await oy(s.downloadUrl);cy(S)?await fy(S,m):dy(S)?await ly(S,m):await Qc(Je(m,"SKILL.md"),S.toString("utf8"),"utf8")}let _={skillId:s.skillId,skillName:s.skillName,relPath:x,installedAt:Date.now(),...s.description?{description:s.description}:{},...s.icon?{icon:s.icon}:{},...s.version?{version:s.version}:{},...s.downloadUrl?{downloadUrl:s.downloadUrl}:{},...s.config?{config:s.config}:{},...s.builtin?{builtin:s.builtin}:{}};return ge.info("skill installed",{agentId:e,skillId:s.skillId,skillName:s.skillName,relPath:x,source:c?"content":"downloadUrl"}),_}function go(t,e,n){let i=e.get(n.skillId);if(i!==void 0){t[i]=n;return}e.set(n.skillId,t.length),t.push(n)}function iy(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 sy(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 l0(t,e){let n=await Re(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Ot,s=n.skillsRefreshedForVersion;if(s===i)return{status:"noop",count:0};if(!s)return n.skillsRefreshedForVersion=i,await Ue(n,e),{status:"seeded",count:0};let c=[...n.skills??[]],d=new Map(c.map((m,_)=>[m.skillId,_])),u=c.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Ue(n,e),{status:"noop",count:0};let h=0,x=0;for(let m of u)try{await Xc(Je(n.workspace,m.relPath),{recursive:!0,force:!0});let _=await po({agentId:t,workspace:n.workspace,framework:n.framework,skill:sy(m)});go(c,d,_),h+=1}catch(_){x+=1,ge.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(_)})}return n.skills=c,x===0&&(n.skillsRefreshedForVersion=i),await Ue(n,e),ge.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:s,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function oy(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Fi(e);let n=ay(t);return Fi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await ho(e);return Fi(n.length),n}if(Ni(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),ny);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 s=await i.arrayBuffer();return Fi(s.byteLength),Buffer.from(s)}finally{clearTimeout(n)}}throw new T("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Fi(t){if(t>ry)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function ay(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new T("IPC_BAD_REQUEST","bad data URL");let n=!!e[2],i=e[3]??"";return n?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function cy(t){return t.length>=2&&t[0]===31&&t[1]===139}function dy(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],n=t[3];return e===3&&n===4||e===5&&n===6}function td(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function ly(t,e){let n,i;try{n=new rd.default(t),i=n.getEntries()}catch(d){throw new T("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||td(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(x=>x===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let s=uy(i),c=ed(e);for(let d of i){if(td(d.entryName))continue;let u=d.entryName;if(s&&u.startsWith(s)&&(u=u.slice(s.length)),!u)continue;let h=ed(e,u),x=nd(c,h);if(x.startsWith("..")||x==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Yc(h,{recursive:!0});continue}await Yc(W_(h),{recursive:!0});let m;try{m=d.getData()}catch(_){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${_.message}`,{cause:_})}await Qc(h,m)}}function uy(t){let e;for(let n of t){let i=n.entryName;if(!i||td(i))continue;let s=i.indexOf("/");if(s<=0)return;let c=i.slice(0,s+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function fy(t,e){await hy(t);let n=Pf({cwd:e,strip:1}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await o0(s0.from(t),n)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(s)}}async function hy(t){let e=[],n=Cr({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,s=setTimeout(()=>{i=!0,n.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await o0(s0.from(t),n)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(s)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var xy=5e3;async function py(t,e,n,i){return u0(t,e,n,i,{count:0})}async function u0(t,e,n,i,s){if(i<=0)return[];let c;try{c=await r0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(J_.has(u.name)||u.isSymbolicLink())continue;if(s.count>=xy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=Je(e,u.name),x=K_(Je(n,u.name)),m=null;try{m=await Zc(h)}catch{continue}if(m.isSymbolicLink())continue;s.count++;let _={name:u.name,path:f0(nd(t,h)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(_.children=await u0(t,h,x,i-1,s)),d.push(_)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function gy(t){return!t||t<=0?$_:Math.min(t,V_)}function my(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function f0(t){return t.split(i0).join("/")}ee();var An=q("agent-health-reporter"),wy=1e4,_y=3,zi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??wy,this.livenessFailureThreshold=e.livenessFailureThreshold??_y}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()}),An.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),An.info("heartbeat stopped"))}async tick(){if(this.inFlight){An.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,An.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let d of this.opts.core.agents.values()){let u=yy(d);if(!u)continue;let h={agentId:d.agentId,status:u};d.patToken&&(h.patToken=d.patToken),d.accountId&&(h.accountId=d.accountId),n.push(h)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Ot,_meta:{cozeDeviceId:e}},s;try{s=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,An.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=s?.authFailures;if(c&&c.length>0&&(An.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){An.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){An.warn("onTickEnd hook failed",{err:String(n)})}}};function yy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}un();import{mkdir as ld,rm as ub,stat as fb}from"node:fs/promises";import{homedir as hb}from"node:os";import{join as G0}from"node:path";cn();import{existsSync as Oy}from"node:fs";import{release as Ly}from"node:os";import{basename as Ny,isAbsolute as My}from"node:path";function Ui(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Lr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Nr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Tn(t,e){return{jsonrpc:"2.0",id:t,error:e}}$e();var mo=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 h0(t){return"method"in t&&"id"in t&&t.id!==void 0}function x0(t){return"method"in t&&!("id"in t)}function wo(t){return!("method"in t)&&"id"in t}var by={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 Ey(t){if(t!=null)return t instanceof Error?{name:t.name,message:Gi(t.message)}:typeof t=="string"?Gi(t):typeof t=="object"?Sy(t):t}var vy=[[/\/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 Gi(t){let e=t;for(let[n,i]of vy)e=e.replace(n,i);return e}function Sy(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Gi(i):e[n]=i;return e}function qi(t){if(t instanceof T){let e=Ey(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(n.reason=e.reason),{code:by[t.code]??J.INTERNAL_ERROR,message:Gi(t.message),data:n}}return{code:J.INTERNAL_ERROR,message:Gi(t instanceof Error?t.message:String(t))}}function p0(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,s=i?e?.message:t.message,c=t.data;if(i&&e){let{message:d,...u}=e;c=u}return new T(n,s,{retriable:e?.retriable??!1,cause:c})}function m0(t){return`${JSON.stringify(t)}
95
+ `}var g0=10*1024*1024,_o=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>g0){let s=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${s} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${g0} bytes`)}),[]}let n=this.buffer.split(`
96
+ `);this.buffer=n.pop()??"";let i=[];for(let s of n){let c=s.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(n){return this.onError?.({line:e,error:n}),[]}}};var _0={"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"},vT=Object.fromEntries(Object.entries(_0).map(([t,e])=>[e,t])),Iy={"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:[]},Mr=class{seq=0;next(e,n){this.seq+=1;let i=_0[e]??Ay(e),s=Iy[i]??[],c=[i,String(this.seq)];if(s.length>0){let d=s.map(h=>w0(n?.[h]??"")),u=Ty(d).join(":");u&&c.push(u)}else n&&Object.values(n).some(d=>d)&&c.push(Object.values(n).filter(Boolean).map(d=>w0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function Ay(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function w0(t){return t.replace(/[:_\s]+/g,"-")}function Ty(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}ln();import{readFileSync as ky}from"node:fs";var Cy=384;async function sd(t,e=process.env){let n={};for(let[i,s]of Object.entries(e))typeof s=="string"&&(n[i]=s);await fr(t.agentEnvFile,n,{mode:Cy})}function od(t){try{let e=JSON.parse(ky(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function y0(t,e,n={},i=s=>s){return{...i({...t,...od(e)}),...n}}Zt();ar();$e();ee();Be();import{execFileSync as Dy,spawnSync as Ry}from"node:child_process";function Hi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function ji(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),Ry("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ad=new Set;function b0(t){typeof t=="number"&&t>0&&ad.add(t)}function E0(t){typeof t=="number"&&ad.delete(t)}function v0(){for(let t of ad)ji(t,"SIGKILL")}var Br="coze-bridge-daemon";function S0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let s=process.getuid?.()??0;return Dy("pgrep",["-U",String(s),"-f",Br],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
97
+ `).map(s=>Number.parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0&&s!==i)}async function I0(t,e){if(t.length===0)return;let n=e?.killFn??ji,i=e?.isAliveFn??Hi,s=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),c=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<c&&t.some(h=>i(h));u+=d)await s(Math.min(d,c-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var Py=[{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:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \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\/codex-acp|optional dependency was not installed/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|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 A0(t,e){if(!e)return null;for(let n of Py)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function T0(t,e){return A0(t,e)}function k0(t,e){return A0(t,e)}function Fr(t,e,n){return!e&&n.firstUpdateMs>0&&t<n.firstUpdateMs?Math.max(1,n.firstUpdateMs-t):t<n.phase2GateMs?Math.max(1,n.phase2GateMs-t):Math.max(1,n.livenessWindowMs)}function C0(t,e,n){let s=n-t.armedAt-t.expectedIntervalMs;if(s>e.suspendThresholdMs){let x=t.suspendedMs+s,m=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:s,rearmMs:Fr(m,t.firstFrameSeen,e)}}let c=n-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:Fr(c,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Fr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Fr(c,!1,e)}}var D0=Ze("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),By=200,Fy=40,zy=Ze("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Uy=Ze("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Gy=Ze("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),qy=Ze("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Hy=Ze("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),jy=Ze("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),R0=500;function Wy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=R0?t:`${e.slice(0,R0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Ky(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:n}=t;if(typeof n=="string")e.push(n);else if(n&&typeof n=="object")try{e.push(JSON.stringify(n))}catch{}return e.join(" ")}function P0(t){try{return Oy(t)}catch{return}}function $y(t,e){return{platform:process.platform,osRelease:Ly(),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 Vy(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Ny(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Nt=class{constructor(e){this.opts=e;this.log=q(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new _o({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Mr;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",n=y0(process.env,this.opts.agentEnvFile??X().agentEnvFile,this.opts.env,s=>this.sanitizeEnv(s)),i=st(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,b0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",s=>{try{for(let c of this.decoder.push(s))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",s=>{let c=s.trimEnd();this.stderrRing.push(c),this.stderrRing.length>By&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",s=>{this.log.warn("child stdin error",{err:String(s)})}),i.stdout?.on("error",s=>{this.log.warn("child stdout error",{err:String(s)})}),i.stderr?.on("error",s=>{this.log.warn("child stderr error",{err:String(s)})}),i.on("exit",(s,c)=>{this.stopped=!0,E0(i.pid),(s!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:s,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(s,c));for(let u of this.exitHandlers)u(s,c)}),i.on("error",s=>{let c=s,d=$y(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(s),diag:d}),this.failAllPending(new T("AGENT_SPAWN_FAILED",Vy(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 n=this.child,i=new Promise(c=>n.once("exit",()=>c()));ji(n.pid,"SIGTERM");let s=setTimeout(()=>{n.killed||ji(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(s)}}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,n){let i={firstUpdateMs:Hy,phase2GateMs:zy,livenessWindowMs:Uy,absoluteMaxMs:Gy,approvalMaxMs:jy,suspendThresholdMs:qy,...n};return this.call("session/prompt",e,D0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Lr("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,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Nr(e,n))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Tn(e,n))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,n,i=D0,s){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Ui(c,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let h=n.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let m={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(s){let _=this.now(),S={cfg:s,startedAt:_,lastActivityAt:_,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:_,expectedIntervalMs:Fr(0,!1,s),sessionId:u};m.promptTimeout=S;let y=()=>{let v={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=C0(v,S.cfg,I),k=P=>{S.armedAt=I,S.expectedIntervalMs=P,m.timer=setTimeout(y,P)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),k(A.rearmMs);return}if(A.action==="continue"){k(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,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(y,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(d)}catch(_){m.timer&&clearTimeout(m.timer),this.pending.delete(c),x(_)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(m0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(wo(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new T("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:Wy(e.result)}),n.resolve(e.result));return}if(x0(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let s=i.promptTimeout;s&&(s.firstFrameSeen=!0,s.lastActivityAt=this.now(),this.trackToolCall(s,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(s=>this.log.warn("update handler failed (async)",{err:String(s)}))}catch(s){this.log.warn("update handler threw sync, swallowed",{err:String(s)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(h0(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,s=i?.sessionUpdate;if(s!=="tool_call"&&s!=="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";s==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Tn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let n of this.agentRequestHandlers)try{await n(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(Tn(e.id,qi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=p0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=k0(this.framework,Ky(e));return i?new T(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):n}buildExitError(e,n){if(this.stopReason!==void 0)return new T("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(Fy).join(`
98
+ `),s=T0(this.framework,i);return s?new T(s.bridgeCode,s.message,{cause:{reason:s.reason,code:e,signal:n,stderrTail:i}}):new T("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Jy(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&(n.startsWith("CLAUDE")||n==="AI_AGENT"||n==="BAGGAGE"||(e[n]=i));return e}var yo=class extends Nt{framework="claude-code";constructor(e){let{command:n,args:i}=si("claude-code",e.command,e.args??[]),s={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s)}sanitizeEnv(e){return Jy(e)}};cn();import{mkdtempSync as Zy,rmSync as Yy}from"node:fs";import{tmpdir as Xy}from"node:os";import{join as Qy}from"node:path";var bo=class extends Nt{framework="codex";authMethodId;codexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:s,args:c}=si("codex",e.command,i),d=e.isolateCodexHome?Zy(Qy(Xy(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,h={command:s,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(h),this.authMethodId=e.authMethodId,this.codexHomeDir=d}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Yy(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};$e();var eb=3e4,zr=class extends Nt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let s={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s),this.agentId=e.agentId,this.sessionName=n,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}`}]},eb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var O0=["default","acceptEdits","plan","auto","bypassPermissions"],L0=["read-only","auto","full-access"];function kn(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 cd(t){switch(t){case"claude-code":return O0.join("/");case"codex":return L0.join("/");case"openclaw":return""}}ln();$e();ee();Be();function dd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}cn();var Cn=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((n,i)=>{this.slots.push({task:e,resolve:n,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 n=await e.task();e.resolve(n)}catch(n){e.reject(n)}}}finally{this.running=!1}}}};var Eo=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 n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new Cn,this.sessionQueues.set(e,n)),n}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let n=this.sessionQueues.get(e);return!!n&&!n.isDisposed}async dispose(e){this.status="stopped";let n=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(n);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let n=[];for(let[,i]of this.sessions)Wi(i),i.downstream&&(n.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(n),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Wi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Yt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Zt();ee();import{constants as N0}from"node:fs";import{access as tb}from"node:fs/promises";import{delimiter as nb,join as rb}from"node:path";var St=q("framework-detector"),M0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},ib=[".exe",".cmd",".bat",".ps1"],Zn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??st,access:e.access??tb}}async detect(e){let n=M0[e],i=await this.which(n);if(!i)return St.debug("framework binary not found",{framework:e,bin:n}),null;let s=e==="openclaw"?["--log-level","silent"]:[],[c,d]=await Promise.all([this.probeVersion(i,s),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)])),n={};for(let[i,s]of e)s&&(n[i]=s);return n}async which(e){let n=this.env.pathEnv.split(nb).filter(Boolean),i=this.env.platform==="win32"?["",...ib]:[""];for(let s of n)for(let c of i){let d=rb(s,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?N0.F_OK:N0.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return St.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return St.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return St.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let s=JSON.parse(i[0]);if(!Array.isArray(s))return St.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=s.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(St.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}:(St.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:s.length}),null)}catch(s){return St.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(s),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return St.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||St.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let s={reachable:i},c=n.stdout.match(/\{[\s\S]*\}/);if(c)try{let d=JSON.parse(c[0]);typeof d.gateway?.port=="number"&&(s.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(s.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(s.detail=d.rpc.error)}catch(d){St.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return s}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(ob(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let s="",c=!1,d,u=h=>{c||(c=!0,d&&clearTimeout(d),i(h))};try{let h=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{s+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:s}))}catch{u(null)}})}},sb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function ob(t){return t.replace(sb,"")}import{homedir as ab}from"node:os";import{join as cb}from"node:path";ln();Zt();ar();$e();ee();async function z0(){let t=cb(ab(),".openclaw/openclaw.json");return ur(t)}async function U0(){return(await z0())?.gateway?.auth?.token??""}var B0=q("openclaw.config"),db=[0,5e3,5e3],lb=Ze("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),F0="models.providers.",vo="agents.defaults.models",So=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new Cn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??db,this.cliTimeoutMs=e.cliTimeoutMs??lb}async withRetry(e,n){let i;for(let s=0;s<this.retryDelaysMs.length;s++){let c=this.retryDelaysMs[s]??0;c>0&&await new Promise(d=>setTimeout(d,c));try{return await n()}catch(d){i=d,B0.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(d)})}}throw new T("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let s=st(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=x=>{d||(d=!0,clearTimeout(h),x())};s.stderr?.on("data",x=>{c+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.unref(),s.on("error",x=>u(()=>i(x))),s.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let s=String(i);if(n.some(c=>s.includes(c)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",n])))}catch(i){B0.warn(`${e} failed (best-effort)`,{configPath:n,err:String(i)})}}ensureProvider(e,n){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${F0}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${F0}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${vo}[${e}]`,()=>this.runCli(["config","set",vo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${vo}[${e}]`,`${vo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await z0())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let s=`${e}/`,c=[];for(let d of Object.keys(i))d.startsWith(s)&&c.push(d.slice(s.length));return c}ensureAgent(e,n,i){let s=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&s.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(s,["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 fe=q("agent-manager"),fd="acceptEdits",j0="full-access",W0="read-only";function xb(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 pb=(t,e,n,i,s,c,d,u,h,x)=>{switch(t){case"claude-code":{let m={...s?{...Vf(s),...Yf(s,d,u)}:{},...h??{},IS_SANDBOX:"1"};return new yo({cwd:n,env:m,agentId:i})}case"codex":{let m=s?[...Jf(s),...Qf(s,d,u)]:[],_=j0;x!==void 0&&(kn("codex",x)?_=x:fe.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let S=[...m,...xb(_)],y={...s?Zf(s):{},...h??{}},v=!!s;return new bo({cwd:n,agentId:i,...S.length>0?{extraArgs:S}:{},...Object.keys(y).length>0?{env:y}:{},...v?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new zr({command:e,cwd:n,agentId:i,...c?{sessionName:dd(c)}:{}})}};function ud(t){return t==="claude-code"||t==="codex"}function gb(t){let e=[],n=Object.keys(t).sort();for(let i of n){let s=t[i];s!==void 0&&(mb(s)||e.push(`${i}=${s}`))}return e.length===0?"":`${e.join(`
99
99
  `)}
100
- `}function wE(t){if(t.includes(`
101
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var _E={path:"",version:"cloud-deployed"},G0="openclaw_gateway_unavailable",yE="openclaw_default_agent_missing";function H0(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 EE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},bE=6e4,Eo=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??gE,this.createTimeoutMs=e.createTimeoutMs??bE,this.detectorFactory=e.detectorFactory??(()=>new $n),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new yo({command:r})),this.openclawConfigDir=e.openclawConfigDir??cd(xE(),".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=>{le.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=cd(e,".env");if(await hE(r).then(c=>c.isFile()).catch(()=>!1)){le.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=mE({...process.env,...nd(this.paths.agentEnvFile)});await on(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 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=so(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")le.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>le.warn("dispose stale agent failed (ignored)",{err:String(T)})),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(T=>le.warn("dispose drifted agent failed (ignored)",{err:String(T)})),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 T=await ke(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Be(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){le.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 Be(T,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 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",g;x&&!r?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let m=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??m??u.workspace,_=new AbortController,b=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&ad(e.framework)&&await ar(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await od(u.root,{recursive:!0}),await od(S,{recursive:!0}),await od(u.logs,{recursive:!0}),T(),x||await lr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Da(S,"cloud"):await Da(S,"local",dd)),T();let P=i,y=Hf({model:e.model??P?.model}),C=Rf(e._meta)??P?.accountId,D=e.patToken??P?.patToken,B=f==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new wo({agentId:e.agentId,framework:e.framework,workspace:S,model:y.model??yt,deployType:f,...C?{accountId:C}:{},...D?{patToken:D}:{},...B?{modelInfo:B}:{}}),I.status="ok",P?.sessions){let V=f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,se]of Object.entries(P.sessions)){let oe={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?se.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:X,framework:e.framework,fallback:oe.permissionMode})):In(e.framework,se.permissionMode)?oe.permissionMode=se.permissionMode:le.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&le.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:f}),se.cozeGroupId&&(oe.cozeGroupId=se.cozeGroupId),I.sessions.set(X,oe)}let re=Object.keys(P.sessions).length;re>0&&le.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(I),A=!0;let M={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:y.model};f==="cloud"&&(M.deployType="cloud"),C&&(M.accountId=C),D&&(M.patToken=D),B&&(M.modelInfo=B),P?.skills&&(M.skills=P.skills),P?.agentName&&(M.agentName=P.agentName),P?.description&&(M.description=P.description),M.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Dt,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):le.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let Y=e.initialSkills??[];if(Y.length>0){let V=[...M.skills??[]],re=new Map(V.map((oe,R)=>[oe.skillId,R])),X=await Promise.allSettled(Y.map(oe=>uo({agentId:e.agentId,workspace:S,framework:e.framework,skill:oe}))),se=0;for(let[oe,R]of X.entries()){let G=Y[oe];G&&(R.status==="fulfilled"?(fo(V,re,R.value),se++):le.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:G.skillId,skillName:G.skillName,err:String(R.reason)}))}se>0&&(M.skills=V,le.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:Y.length}))}return await Be(M,this.paths),le.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(T){throw le.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 fE(u.root,{recursive:!0,force:!0}).catch(P=>le.warn("rm agent dir failed (ignored)",{err:String(P)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(b)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&ad(e.framework))u=_E;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);ad(e.framework)&&!fs(e.framework)&&(le.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 g=e.sessions.get(i),m=Vt(e)?g?.permissionMode??q0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,this.buildBinShimPathEnv(),m)}try{return await x.start(),await x.initialize(EE),x}catch(g){let m=x instanceof Ot?x.getStderrTail():[];throw m.length>0&&le.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof k?g.code:"unknown",recentStderr:m}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,g)}}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",H0(o),{cause:{reason:G0}})}catch(o){le.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};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 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:yE}})}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",H0(r),{cause:{reason:G0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:l,command:u}=e,f=sd(o);if(r.deployType==="local"){let S=await this.ensureOpenclawDefaultAgent();return new Mr({command:u,cwd:S.workspace,agentId:S.id,sessionName:f})}let x=await U0(),g=i?$f(i,c,l):null,m;if(g){let S=Wc(o),b=g.models[0]?.id??yt,I=`${S}/${b}`;if(!this.ensuredProviders.has(I)){let A=this.getOpenclawConfig();await A.ensureProvider(S,g),await A.addModelToAllowlist(I),this.ensuredProviders.add(I)}m=I}return new Mr({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:f,...x?{gatewayToken:x}:{},...m?{slashModelOnStart:m}:{}})}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=Wc(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 Z0}from"node:crypto";import{promises as CE}from"node:fs";import{basename as Y0}from"node:path";je();ne();import{promises as vE}from"node:fs";import{basename as SE}from"node:path";var W0=H("file-upload"),IE="/api/coze_claw/file/agent_upload",AE=6e4;async function K0(t,e={}){let i=`${Tr(Cr(e.handshakeBase))}${IE}`,o=e.timeoutMs??AE,c=await vE.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",...bn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);W0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let g=await fetch(i,{method:"POST",headers:u,body:l,signal:f.signal}),m=g.headers.get("x-tt-logid")??"";if(!g.ok){let b=await g.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${m}: ${b.slice(0,200)}`)}let S=await g.json();if(S.code!==void 0&&S.code!==0)throw new k("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${m}`);let _=S.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${m}: ${JSON.stringify(S).slice(0,200)}`);return W0.info("file upload ok",{uri:_,logid:m}),{uri:_}}catch(g){throw g instanceof k?g:g.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${SE(t.path)}`):new k("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}je();ne();import{extname as kE}from"node:path";var TE={".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=kE(t).toLowerCase();return TE[e]??"application/octet-stream"}Oe();var bo=H("agent-send"),V0=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 X0(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(g=>setTimeout(g,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function Q0(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 CE.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>V0)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${V0}`);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 l=t.name??Y0(t.path),u;try{u=await K0({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(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:Z0(),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 X0(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: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 eh(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??Y0(t.path),c={sessionUpdate:"group_file",messageId:Z0(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await X0(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 th(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}sn();$t();ne();var Lt=H("coze-cli-installer"),nh="@coze/cli@latest",RE="coze",rh="0.1.8",PE=5e3,DE=5e3,OE=9e4,ih=1e4,qi=null,vo=!1;async function ud(t,e={}){if(vo)return;if(qi)return qi;let r=e.exec??Nf;return qi=(async()=>{try{let i=await LE(RE,r),o=!1;if(i){let l=await NE(r);if(l===void 0)Lt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(th(l,rh))Lt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:rh}),o=!0;else{Lt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),vo=!0;return}}let c=o?"upgrade-only":"full";Lt.info("coze-cli install start",{package:nh,mode:c});try{await r("npm",["i","-g","--prefer-online",nh],{timeout:OE,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){vo=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:ih}),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:ih}),Lt.info("coze auth login ok")}catch(l){Lt.warn("coze auth login failed",{err:String(l)});return}vo=!0}finally{qi=null}})(),qi}async function LE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:PE});return Ra(i)}catch{return}}async function NE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:DE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}an();Oe();var ME=10*6e4;function sh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?ME:e}function So(t){return cr(t??ee().configFile)}function ji(t,e){return dr(e??ee().configFile,t)}import{randomBytes as nb}from"node:crypto";ir();je();ne();import{createReadStream as BE}from"node:fs";import{mkdir as FE,readFile as zE,realpath as UE,stat as GE,writeFile as HE}from"node:fs/promises";import{basename as qE,dirname as fd,isAbsolute as jE,join as WE,relative as KE,resolve as oh,sep as $E}from"node:path";import{createInterface as VE}from"node:readline";var ch=H("fs-rpc"),Wi=$e("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function dh(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 uh(t.path,e);return await FE(fd(i),{recursive:!0}),await HE(i,t.content,"utf8"),ch.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function lh(t,e){let r=await uh(t.path,e),i=await GE(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 ZE(r,t.line??1,t.limit);else{let l=await zE(r,"utf8");if(o){let u=l.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=l}return ch.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function ZE(t,e,r){let i=VE({input:BE(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 f of i)if(u>=o&&u<c&&l.push(f),u++,u>=c)break}finally{i.close()}return l.join(`
104
- `)}async function uh(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([ah(oh(e)),ah(oh(t))]),o=KE(r,i);if(YE(o,$E,jE(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function YE(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function ah(t){let e=[],r=t;for(;r!==fd(r);)try{let i=await UE(r);return e.length?WE(i,...e.reverse()):i}catch{e.push(qE(r)),r=fd(r)}return t}ne();var fh=H("prompt-multimodal"),hh=10*1024*1024,JE=15e3,XE=6;async function xh(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 QE(l))}}let o=Array.from({length:Math.min(XE,t.length)},()=>i());return await Promise.all(o),e}function ph(t){return t.some(e=>e.type==="image")}async function QE(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 tb(e.uri),o=e.mimeType||eb(i)||"application/octet-stream";return fh.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 fh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function eb(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function tb(t){let e=new AbortController,r=setTimeout(()=>e.abort(),JE);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>hh)throw new Error(`image too large: ${o.byteLength} bytes (max ${hh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}cn();je();ne();var $=H("core"),rb=3e4,ib=/^(boe|ppe)_[A-Za-z0-9_-]+$/,sb="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",ob="\u5BA1\u6279\u5DF2\u8D85\u65F6",ab=3e4,Io=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=sh(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(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.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),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){$.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)&&$.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)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:l}),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){$.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(l=>$.debug("send error response to upstream failed (ignored)",{err:String(l)}));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)){$.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(xo(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&&ib.test(i)?this.currentCozeEnv=i:i&&$.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}`):$.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}`):$.warn("drop unknown notification",{method:e.method})}catch(o){$.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,g=oo(r._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,sb,x,g)}}let l=Date.now(),u=!1;try{let f=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,f}finally{$.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}=Df(i);switch(r){case"session/new":{let c=cb();return $.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return $.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 k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Vt(e)?Pf(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: ${id(e.framework)}`);let f=await this.ensureRuntime(e,l);if(u!==void 0&&f.permissionMode===void 0&&(f.permissionMode=u,await this.persistSessionMapping(e)),f.replySeq=0,await this.ensureDownstream(e,l,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 S=f.permissionMode;f.permissionMode=u,await this.persistSessionMapping(e);try{await f.downstream.setSessionMode({sessionId:f.acpSessionId,modeId:u})}catch(_){throw f.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),_}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(f.acpSessionId,x):e.activeTriggers.delete(f.acpSessionId);let g=oo(i._meta);if(g?e.activeGroupIds.set(f.acpSessionId,g):e.activeGroupIds.delete(f.acpSessionId),g&&f.cozeGroupId!==g&&(f.cozeGroupId=g,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&ph(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let m=await xh(c.prompt);try{let S=await f.downstream.sessionPrompt({...c,sessionId:f.acpSessionId,prompt:m});return f.lastActiveAt=Date.now(),S}catch(S){if(S instanceof k&&S.code==="AGENT_APPROVAL_TIMEOUT"){let _=f.pendingPermission;_&&(_.downstream.respondAgentRequest(_.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(_.upstreamId),f.pendingPermission=void 0);let b=f.acpSessionId,I=b?e.activeTriggers.get(b):void 0,A=b?e.activeGroupIds.get(b):void 0;return $.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:l}),await this.synthesizePromptReply(e,f,l,ob,I,A)}throw S}finally{if(e.activeTriggers.delete(f.acpSessionId),e.activeGroupIds.delete(f.acpSessionId),f.pendingPermission=void 0,f.reloadAfterTurn){f.reloadAfterTurn=!1;let S=f.downstream;S&&(f.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:f.acpSessionId}),S.stop("reload-after-turn").catch(_=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(_)})))}else f.downstream?.isAlive()&&this.armIdleTimer(e,l,f)}}case"session/cancel":{let l=o.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(l);if(e.hasSessionQueue(l)){let f=e.getSessionQueue(l);f.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:f.size}),f.dispose(new k("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,f=oo(i._meta);if(!l)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: ${id(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(l)??await this.ensureRuntime(e,l);if(x.permissionMode===u)return{};let g=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(m){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),m}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:l,modeId:u});return{}}default:throw new k("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 $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};$.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,f=l.runtime.acpSessionId;u?.isAlive()&&f&&c.push({downstream:u,acpSessionId:f,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 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"?dd:j0),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(lt.GEN_MODEL_TOKEN,i,ab);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,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=o&&Date.now()-u<c)throw new k("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 f;try{f=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=l+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&($.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}),$.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let g=await f.sessionNew({cwd:e.workspace});i.acpSessionId=g.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 $.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){$.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)){$.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)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}$.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=>$.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(Pr("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(Pr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>$.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){$.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){$.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(ub(r)){$.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"&&Vt(e)){let g=l.currentModeId;In(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(m=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(m)}))):typeof g=="string"&&!In(e.framework,g)&&$.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:g})}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(g=>$.warn("forward update failed",{agentId:e.agentId,err:String(g)}))}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}$.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??{},l=await dh(c,o);r.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await lh(c,o);r.respondAgentRequest(i.id,l)}}catch(o){$.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 g=u?e.activeGroupIds.get(u):void 0;g&&(x.cozeGroupId=g);let m=u?this.reverseSessionId(e,u):void 0,S=m?e.sessions.get(m):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let _={...c,...m?{sessionId:m}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:m}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:m,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(b=>({optionId:b.optionId,kind:b.kind,name:b.name}))}),this.upstream.send(Bi(o,"session/request_permission",_)).catch(b=>{this.pendingUpstream.delete(o),$.error("forward permission request failed",{agentId:e.agentId,err:String(b)}),r.respondAgentRequestError(i.id,{code:J.INTERNAL_ERROR,message:`upstream send failed: ${String(b)}`})})}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?($.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"&&db(e.result,o),$.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 ho(e.error)):i.value.resolve(e.result);return}$.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 $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:l,key:c}}}sendRequest(e,r,i=rb){let o=this.upstreamIds.next(e);return new Promise((c,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),l(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:l,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)),l(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){$.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:Dt}}))}};function cb(){return nb(16).toString("hex")}function db(t,e){if(!t||typeof t!="object"){$.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){$.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"){$.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")&&$.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var lb=["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 ub(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 lb.some(c=>o.startsWith(c))}an();ne();Oe();import{randomBytes as fb}from"node:crypto";import{createServer as hb}from"node:http";var xb=1e6,gh=H("ipc"),Ao=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??ee()}async start(){this.token=fb(32).toString("hex");let e=hb((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(),gh.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}`){Ki(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Ki(r,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await pb(e)}catch(u){Ki(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);Ki(r,200,u??{ok:!0})}catch(u){gh.error("IPC handler failed",{key:o,err:String(u)}),Ki(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Ki(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function pb(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>xb)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(ux(),1),Bv=Ut(No(),1),Fv=Ut(zr(),1),zv=Ut(vd(),1),Uv=Ut(Ad(),1),Gv=Ut(Dd(),1),Ex=Ut(zo(),1),Hv=Ut(yx(),1);var bx=Ex.default;je();ne();var{FWS:iS}=Ox(),Re=H("upstream.frontier"),Nx="application/json",Mx="none",sS=15e3;function oS(t){class e extends bx{constructor(i){super(i,Bf,{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(El("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 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){Re.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Ff,...bn(this.opts.ppeOverride)},r=oS(e),i=Uf(this.opts.urlOverride),o={url:i,ws:r,fpID:Mf,aID:ao,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Nx,force:!0},payloadEncoding:{encoding:Mx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new iS(o),l=!1,u=null,f,x,g=new Promise((_,b)=>{f=_,x=b}),m=_=>{l||(l=!0,u&&(clearTimeout(u),u=null),_?x(_):f())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Re.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&m();for(let b of this.connectHandlers)Promise.resolve(b({initial:_})).catch(I=>Re.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=_=>{this.opened=!1,Re.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{Re.warn("frontier error",{code:_.code,msg:_.message}),m(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let S=this.opts.openTimeoutMs??sS;u=setTimeout(()=>{m(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await g}catch(_){try{c.close(1e3,"open failed")}catch(b){Re.warn("fws close during start failure threw (ignored)",{err:String(b)})}throw this.fws=null,this.opened=!1,_}}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 k("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 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;Bx(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:Nx,payloadEncoding:Mx})}catch(u){throw Re.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){Re.debug("drop non-adapter frontier frame",{service:r});return}let i=dS(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;Bx(c)||Re.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(l=>Re.warn("frontier frame handler threw",{err:String(l)}))}};function Bx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Fx=2e3;function aS(t){return t.length<=Fx?t:`${t.slice(0,Fx)}...<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}}je();ne();var Md=H("skill-publish"),lS="/api/marketplace/product/skill/publish_with_assets",uS=15e4;async function zx(t,e={}){let i=`${Tr(Cr(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 l={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...bn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);Md.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:{...l,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:l,body:c,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${_.slice(0,200)}`)}let m=await x.json();if(Md.info("skill publish response",{logid:g,httpStatus:x.status,code:m.code,msg:m.msg,dataSkillId:m.data?.skill_id??"",dataVersion:m.data?.version??""}),m.code!==void 0&&m.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${m.code} msg=${m.msg??"-"} logid=${g}`);let S={};return m.data?.skill_id!==void 0&&m.data.skill_id!==""&&(S.skillId=String(m.data.skill_id)),m.data?.version&&(S.version=m.data.version),Md.info("skill publish ok",{logid:g,skillId:S.skillId??"",version:S.version??""}),S}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)}}ne();var Bd=H("upstream.switchable"),Vo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Bd.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 Bd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Bd.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 Fd=H("upstream"),Wr=class{handler=null;async start(){Fd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Fd.info("NoopUpstream stopped",{reason:e})}async send(e){Fd.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();an();ne();Oe();import{promises as fS}from"node:fs";var Ux=H("pat-token-store");async function Zo(t=ee()){try{let r=(await fS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(Ux.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"&&Ux.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function ns(t,e=ee()){if(!t)throw new Error("writePatToken: empty patToken");await on(e.patTokenFile,t,{mode:384})}Oe();Oe();import{promises as Yo}from"node:fs";import{join as hS}from"node:path";function xS(t,e){return`#!/bin/sh
100
+ `}function mb(t){if(t.includes(`
101
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var wb={path:"",version:"cloud-deployed"},q0="openclaw_gateway_unavailable",_b="openclaw_default_agent_missing";function H0(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 yb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},bb=6e4,Io=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??pb,this.createTimeoutMs=e.createTimeoutMs??bb,this.detectorFactory=e.detectorFactory??(()=>new Zn),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new So({command:n})),this.openclawConfigDir=e.openclawConfigDir??G0(hb(),".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=>{fe.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=G0(e,".env");if(await fb(n).then(c=>c.isFile()).catch(()=>!1)){fe.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let s=gb({...process.env,...od(this.paths.agentEnvFile)});await dn(n,s,{mode:384}),fe.info("openclaw .env bootstrapped",{envFile:n,bytes:s.length}),await this.getOpenclawConfig().restartGateway(),fe.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){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 Re(e.agentId,this.paths).catch(()=>null),s=lo(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")fe.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(k=>fe.warn("dispose stale agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else if(s&&c.deployType!=="cloud")fe.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(k=>fe.warn("dispose drifted agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){fe.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let k=await Re(e.agentId,this.paths).catch(()=>null);k&&(k.patToken=e.patToken,await Ue(k,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){fe.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let k=await Re(e.agentId,this.paths).catch(()=>null);k&&(k.modelInfo=e.modelInfo,await Ue(k,this.paths))}return fe.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!s&&!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),h=s?"cloud":"local",x=e.framework==="openclaw"&&h==="local",m;x&&!n?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let _=m??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??_??u.workspace,y=new AbortController,v=setTimeout(()=>y.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{s&&ud(e.framework)&&await lr(e.framework,y.signal);let k=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await ld(u.root,{recursive:!0}),await ld(S,{recursive:!0}),await ld(u.logs,{recursive:!0}),k(),x||await hr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await La(S,"cloud"):await La(S,"local",fd)),k();let P=i,b=Kf({model:e.model??P?.model}),D=Lf(e._meta)??P?.accountId,O=e.patToken??P?.patToken,F=h==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new Eo({agentId:e.agentId,framework:e.framework,workspace:S,model:b.model??Lt,deployType:h,...D?{accountId:D}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",P?.sessions){let K=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Z,ae]of Object.entries(P.sessions)){let ce={acpSessionId:ae.acpSessionId,modelToken:ae.modelToken,tokenGeneratedAt:ae.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};K?ae.permissionMode===void 0?(ce.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",fe.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Z,framework:e.framework,fallback:ce.permissionMode})):kn(e.framework,ae.permissionMode)?ce.permissionMode=ae.permissionMode:fe.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Z,framework:e.framework,value:ae.permissionMode}):ae.permissionMode!==void 0&&fe.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Z,framework:e.framework,deployType:h}),ae.cozeGroupId&&(ce.cozeGroupId=ae.cozeGroupId),I.sessions.set(Z,ce)}let te=Object.keys(P.sessions).length;te>0&&fe.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:te})}this.registry.register(I),A=!0;let B={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:b.model};h==="cloud"&&(B.deployType="cloud"),D&&(B.accountId=D),O&&(B.patToken=O),F&&(B.modelInfo=F),P?.skills&&(B.skills=P.skills),P?.agentName&&(B.agentName=P.agentName),P?.description&&(B.description=P.description),B.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Ot,e.framework==="openclaw"&&h==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):fe.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let V=e.initialSkills??[];if(V.length>0){let K=[...B.skills??[]],te=new Map(K.map((ce,R)=>[ce.skillId,R])),Z=await Promise.allSettled(V.map(ce=>po({agentId:e.agentId,workspace:S,framework:e.framework,skill:ce}))),ae=0;for(let[ce,R]of Z.entries()){let U=V[ce];U&&(R.status==="fulfilled"?(go(K,te,R.value),ae++):fe.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(R.reason)}))}ae>0&&(B.skills=K,fe.info("initialSkills installed",{agentId:e.agentId,installed:ae,requested:V.length}))}return await Ue(B,this.paths),fe.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(k){throw fe.error("agent create failed, rolling back",{agentId:e.agentId,err:String(k)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await ub(u.root,{recursive:!0,force:!0}).catch(P=>fe.warn("rm agent dir failed (ignored)",{err:String(P)})),k instanceof T?k:new T("AGENT_SPAWN_FAILED",String(k),{cause:k})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,n,i,s,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&ud(e.framework))u=wb;else throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);ud(e.framework)&&!gs(e.framework)&&(fe.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await lr(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:i,cozeEnv:s,mockScenario:c,command:u.path});else{let m=e.sessions.get(i),_=Yt(e)?m?.permissionMode??j0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,s,c,this.buildBinShimPathEnv(),_)}try{return await x.start(),await x.initialize(yb),x}catch(m){let _=x instanceof Nt?x.getStderrTail():[];throw _.length>0&&fe.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof T?m.code:"unknown",recentStderr:_}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,m)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let s=await this.detectorFactory().probeOpenclawGateway(n);if(!s.reachable)return new T("AGENT_ENV_NOT_READY",H0(s),{cause:{reason:q0}})}catch(s){fe.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(s)})}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};fe.warn("openclaw default agent stale or missing, attempting lazy re-detect");let n=await this.detectorFactory().detect("openclaw");if(n?.defaultAgent?.id&&n.defaultAgent.workspace)return fe.info("openclaw lazy re-detect success",{agentId:n.defaultAgent.id,workspace:n.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=n,{id:n.defaultAgent.id,workspace:n.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:_b}})}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 n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new T("AGENT_ENV_NOT_READY",H0(n),{cause:{reason:q0}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:s,cozeEnv:c,mockScenario:d,command:u}=e,h=dd(s);if(n.deployType==="local"){let _=await this.ensureOpenclawDefaultAgent();return new zr({command:u,cwd:_.workspace,agentId:_.id,sessionName:h})}let x=await U0(),m;if(i?.modelToken){let _=Vc(s),S=Jc(i),y=`${_}/${S}`;if(!this.ensuredProviders.has(y)){let v=this.getOpenclawConfig(),I=await v.getAllowlistModelsForProvider(_),A=Xf(i,c,d,I);A&&(await v.ensureProvider(_,A),await v.addModelToAllowlist(y),this.ensuredProviders.add(y))}m=y}return new zr({command:u,cwd:n.workspace,agentId:n.agentId,sessionName:h,...x?{gatewayToken:x}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,s=n??e.model;for(let c of e.sessions.keys()){let d=Vc(c),u=`${d}/${s}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,fe.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,fe.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as Z0}from"node:crypto";import{promises as kb}from"node:fs";import{basename as Y0}from"node:path";$e();ee();import{promises as Eb}from"node:fs";import{basename as vb}from"node:path";var K0=q("file-upload"),Sb="/api/coze_claw/file/agent_upload",Ib=6e4;async function $0(t,e={}){let i=`${Rr(Pr(e.handshakeBase))}${Sb}`,s=e.timeoutMs??Ib,c=await Eb.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",...In(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),s);K0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),_=m.headers.get("x-tt-logid")??"";if(!m.ok){let v=await m.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${_}: ${v.slice(0,200)}`)}let S=await m.json();if(S.code!==void 0&&S.code!==0)throw new T("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${_}`);let y=S.data?.file?.file_url;if(!y)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${_}: ${JSON.stringify(S).slice(0,200)}`);return K0.info("file upload ok",{uri:y,logid:_}),{uri:y}}catch(m){throw m instanceof T?m:m.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${s}ms) for ${vb(t.path)}`):new T("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(x)}}$e();ee();import{extname as Ab}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 V0(t){let e=Ab(t).toLowerCase();return Tb[e]??"application/octet-stream"}Be();var Ao=q("agent-send"),J0=50*1024*1024;function X0(t,e,n){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 s=i.sessions.get(n);if(!s)throw new T("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:s}}async function Q0(t,e,n,i,s,c){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,n,i,s);return}catch(x){u=x,h<2&&(Ao.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(m=>setTimeout(m,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function eh(t,e){let{session:n,runtime:i}=X0(e.core,t.agentId,t.sessionId);if(!await oi(t.path,n.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let s=await kb.stat(t.path).catch(()=>null);if(!s||!s.isFile())throw new T("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(s.size>J0)throw new T("FILE_TOO_LARGE",`${s.size} bytes > limit ${J0}`);let c=await V0(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 d=t.name??Y0(t.path),u;try{u=await $0({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:s.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Ao.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:s.size,mime:c,code:x instanceof T?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:Z0(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:d,sizeBytes:s.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Q0(e,n,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Ao.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:s.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:s.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function th(t,e){let{session:n,runtime:i}=X0(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 s=t.name??Y0(t.path),c={sessionUpdate:"group_file",messageId:Z0(),content:{uri:t.path,name:s,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Q0(e,n,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Ao.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:s,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function nh(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),s=Math.max(n.length,i.length);for(let c=0;c<s;c++){let d=n[c]??0,u=i[c]??0;if(d<u)return!0;if(d>u)return!1}return!1}cn();Zt();ee();var Mt=q("coze-cli-installer"),rh="@coze/cli@latest",Cb="coze",ih="0.1.8",Db=5e3,Rb=5e3,Pb=9e4,sh=1e4,Ki=null,To=!1;async function xd(t,e={}){if(To)return;if(Ki)return Ki;let n=e.exec??zf;return Ki=(async()=>{try{let i=await Ob(Cb,n),s=!1;if(i){let d=await Lb(n);if(d===void 0)Mt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(nh(d,ih))Mt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:ih}),s=!0;else{Mt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),To=!0;return}}let c=s?"upgrade-only":"full";Mt.info("coze-cli install start",{package:rh,mode:c});try{await n("npm",["i","-g","--prefer-online",rh],{timeout:Pb,maxBuffer:10*1024*1024}),Mt.info("coze-cli install ok")}catch(d){Mt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(s){To=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:sh}),Mt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Mt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:sh}),Mt.info("coze auth login ok")}catch(d){Mt.warn("coze auth login failed",{err:String(d)});return}To=!0}finally{Ki=null}})(),Ki}async function Ob(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:Db});return Pa(i)}catch{return}}async function Lb(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:Rb});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}ln();Be();var Nb=10*6e4;function oh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Nb:e}function ko(t){return ur(t??X().configFile)}function $i(t,e){return fr(e??X().configFile,t)}import{randomBytes as tE}from"node:crypto";ar();$e();ee();import{createReadStream as Mb}from"node:fs";import{mkdir as Bb,readFile as Fb,realpath as zb,stat as Ub,writeFile as Gb}from"node:fs/promises";import{basename as qb,dirname as pd,isAbsolute as Hb,join as jb,relative as Wb,resolve as ah,sep as Kb}from"node:path";import{createInterface as $b}from"node:readline";var dh=q("fs-rpc"),Vi=Ze("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function lh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>Vi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${Vi} bytes`);let i=await fh(t.path,e);return await Bb(pd(i),{recursive:!0}),await Gb(i,t.content,"utf8"),dh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function uh(t,e){let n=await fh(t.path,e),i=await Ub(n),s=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Vi&&!s)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Vi} bytes`);let c;if(s&&i.size>Vi)c=await Vb(n,t.line??1,t.limit);else{let d=await Fb(n,"utf8");if(s){let u=d.split(`
102
+ `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;c=u.slice(h,x).join(`
103
+ `)}else c=d}return dh.info("fs/read_text_file ok",{path:n,size:c.length}),{content:c}}async function Vb(t,e,n){let i=$b({input:Mb(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),s=Math.max(0,e-1),c=typeof n=="number"?s+n:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let h of i)if(u>=s&&u<c&&d.push(h),u++,u>=c)break}finally{i.close()}return d.join(`
104
+ `)}async function fh(t,e){if(typeof t!="string"||t.length===0)throw new T("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([ch(ah(e)),ch(ah(t))]),s=Wb(n,i);if(Jb(s,Kb,Hb(s)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Jb(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function ch(t){let e=[],n=t;for(;n!==pd(n);)try{let i=await zb(n);return e.length?jb(i,...e.reverse()):i}catch{e.push(qb(n)),n=pd(n)}return t}ee();var hh=q("prompt-multimodal"),xh=10*1024*1024,Zb=15e3,Yb=6;async function ph(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let c=n++,d=t[c];d!==void 0&&(e[c]=await Xb(d))}}let s=Array.from({length:Math.min(Yb,t.length)},()=>i());return await Promise.all(s),e}function gh(t){return t.some(e=>e.type==="image")}async function Xb(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Ni(e.uri))return t;try{let{buf:n,contentType:i}=await eE(e.uri),s=e.mimeType||Qb(i)||"application/octet-stream";return hh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:s}),{type:"image",data:n.toString("base64"),mimeType:s}}catch(n){return hh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Qb(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function eE(t){let e=new AbortController,n=setTimeout(()=>e.abort(),Zb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let s=await i.arrayBuffer();if(s.byteLength>xh)throw new Error(`image too large: ${s.byteLength} bytes (max ${xh})`);return{buf:Buffer.from(s),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}un();$e();ee();var W=q("core"),nE=3e4,rE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,iE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",sE="\u5BA1\u6279\u5DF2\u8D85\u65F6",oE=3e4,Co=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Mr;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=oh(e.bridgeConfig)}registerExtension(e,n){this.extensions[e]=n}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(n=>n.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of n)await this.agents.get(i)?.killAllRuntimes("reload");return n}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 n of this.registerHandlers)try{n(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,n,i){let s=i.downstream;s&&(s.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),s.onAgentRequest(c=>{this.handleAgentRequest(e,s,c)}),s.onExit((c,d)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:c,signal:d}),Wi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(s,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[s,c]of this.pendingUpstream)c.downstream===e&&i.push(s);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let s of i){let c=this.pendingUpstream.get(s);if(c){this.pendingUpstream.delete(s),this.upstream.send(Tn(s,{code:J.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).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: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});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 T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(wo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&rE.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let s=this.extensions[e.method];if(!s){n!==null?await this.sendError(n,J.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let c=await s(e,this);n!==null&&await this.upstream.send(Nr(n,c));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Nr(n,s));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Nr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,J.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(s){W.error("handleFrame failed",{method:e.method,err:String(s)}),n!==null&&await this.upstream.send(Tn(n,qi(s)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new T("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new T("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(i);if(!s)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 n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(s,e.method,n);if(e.method==="session/prompt"){let h=s.sessions.get(c);if(h?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,m=uo(n._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:s.agentId,cloudSessionId:c}),this.synthesizePromptReply(s,h,c,iE,x,m)}}let d=Date.now(),u=!1;try{let h=await s.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(s,e.method,n));return u=!0,h}finally{W.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:s}=Mf(i);switch(n){case"session/new":{let c=aE();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=s;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=s,d=c.sessionId;if(!d)throw new T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Yt(e)?Nf(i._meta):void 0;if(u!==void 0&&!kn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${cd(e.framework)}`);let h=await this.ensureRuntime(e,d);if(u!==void 0&&h.permissionMode===void 0&&(h.permissionMode=u,await this.persistSessionMapping(e)),h.replySeq=0,await this.ensureDownstream(e,d,h),!h.downstream||!h.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&h.permissionMode!==void 0&&h.permissionMode!==u){let S=h.permissionMode;h.permissionMode=u,await this.persistSessionMapping(e);try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(y){throw h.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),y}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(h.acpSessionId,x):e.activeTriggers.delete(h.acpSessionId);let m=uo(i._meta);if(m?e.activeGroupIds.set(h.acpSessionId,m):e.activeGroupIds.delete(h.acpSessionId),m&&h.cozeGroupId!==m&&(h.cozeGroupId=m,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&gh(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let _=await ph(c.prompt);try{let S=await h.downstream.sessionPrompt({...c,sessionId:h.acpSessionId,prompt:_});return h.lastActiveAt=Date.now(),S}catch(S){if(S instanceof T&&S.code==="AGENT_APPROVAL_TIMEOUT"){let y=h.pendingPermission;y&&(y.downstream.respondAgentRequest(y.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(y.upstreamId),h.pendingPermission=void 0);let v=h.acpSessionId,I=v?e.activeTriggers.get(v):void 0,A=v?e.activeGroupIds.get(v):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,h,d,sE,I,A)}throw S}finally{if(e.activeTriggers.delete(h.acpSessionId),e.activeGroupIds.delete(h.acpSessionId),h.pendingPermission=void 0,h.reloadAfterTurn){h.reloadAfterTurn=!1;let S=h.downstream;S&&(h.downstream=void 0,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:h.acpSessionId}),S.stop("reload-after-turn").catch(y=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(y)})))}else h.downstream?.isAlive()&&this.armIdleTimer(e,d,h)}}case"session/cancel":{let d=s.sessionId;if(!d)throw new T("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new T("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=s,d=c.sessionId,u=c.modeId,h=uo(i._meta);if(!d)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Yt(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(!kn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${cd(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let m=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=m,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 T("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let s=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&s.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(s.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:s.length});for(let d of s)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of s){let u=d.runtime.downstream,h=d.runtime.acpSessionId;u?.isAlive()&&h&&c.push({downstream:u,acpSessionId:h,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 h of s)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n){let i=e.sessions.get(n);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Yt(e)&&(c.permissionMode=e.framework==="claude-code"?fd:W0),e.sessions.set(n,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,n){let i={sessionId:n,_meta:{cozeAgentId:e}};try{let s=await this.sendRequest(xt.GEN_MODEL_TOKEN,i,oE);if(!s?.modelToken)throw new T("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return s.modelToken}catch(s){throw s instanceof T&&s.code==="MODEL_TOKEN_GEN_FAILED"?s:new T("MODEL_TOKEN_GEN_FAILED",s instanceof Error?s.message:String(s),{cause:s})}}async ensureDownstream(e,n,i){if(Wi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new T("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=3,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=s&&Date.now()-u<c)throw new T("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let h;try{h=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=s&&i.acpSessionId&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=h,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await h.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let m=await h.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.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:n,acpId:i.acpSessionId,err:String(x)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),Yt(e)&&i.acpSessionId&&i.permissionMode)try{await h.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:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(Wi(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});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:n}),this.armIdleTimer(e,n,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let s=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),s&&s.stop("idle timeout").catch(c=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let s of this.pendingUpstream.values())if(s.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,s){let c={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Lr("session/update",{sessionId:i,update:s,_meta:c}))}async synthesizePromptReply(e,n,i,s,c,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return c&&(u.cozeTriggerMsgId=c),d&&(u.cozeGroupId=d),await this.upstream.send(Lr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}},_meta:u})).catch(h=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,s=this.reverseSessionId(e,i);if(!s){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(s);if(!c){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(lE(n)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Yt(e)){let m=d.currentModeId;kn(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(_=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(_)}))):typeof m=="string"&&!kn(e.framework,m)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:m})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Lr("session/update",{...n,sessionId:s,_meta:u})).catch(m=>W.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:J.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let s=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await lh(c,s);n.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await uh(c,s);n.respondAgentRequest(i.id,d)}}catch(s){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(s)}),n.respondAgentRequestError(i.id,qi(s))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let s=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let m=u?e.activeGroupIds.get(u):void 0;m&&(x.cozeGroupId=m);let _=u?this.reverseSessionId(e,u):void 0,S=_?e.sessions.get(_):void 0;S&&(S.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:s});let y={...c,..._?{sessionId:_}:{},_meta:x};this.pendingUpstream.set(s,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:_}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:s,acpSessionId:u,cloudSessionId:_,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(Ui(s,"session/request_permission",y)).catch(v=>{this.pendingUpstream.delete(s),W.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),n.respondAgentRequestError(i.id,{code:J.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let s=n.value;this.clearPendingPermissionFor(s),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:s.agentId,upstreamId:e.id,method:s.method,error:e.error}),s.downstream.respondAgentRequestError(s.agentRequestId,e.error)):(s.method==="session/request_permission"&&cE(e.result,s),W.info("upstream \u2192 permission response (result)",{agentId:s.agentId,upstreamId:e.id,method:s.method,result:e.result}),s.downstream.respondAgentRequest(s.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 mo(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let s=e.get(n);if(s)return{value:s,key:n};if(typeof n=="number"){let c=String(n),d=e.get(c);if(d)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:c}),{value:d,key:c}}}sendRequest(e,n,i=nE){let s=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(s),d(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(s,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(Ui(s,e,n)).catch(h=>{let x=this.pendingBridge.get(s);x&&(clearTimeout(x.timer),this.pendingBridge.delete(s)),d(h)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,s]of e.sessions){let c={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(c.acpSessionId=s.acpSessionId),s.permissionMode&&Yt(e)&&(c.permissionMode=s.permissionMode),s.cozeGroupId&&(c.cozeGroupId=s.cozeGroupId),n.set(i,c)}await ai(e.agentId,n,this.paths)}catch(n){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,s]of e.sessions.entries())if(s.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Tn(e,{code:n,message:i,data:{bridgeVersion:Ot}}))}};function aE(){return tE(16).toString("hex")}function cE(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=n.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 dE=["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 lE(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let{text:s}=i;return dE.some(c=>s.startsWith(c))}ln();ee();Be();import{randomBytes as uE}from"node:crypto";import{createServer as fE}from"node:http";var hE=1e6,mh=q("ipc"),Do=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(n=>[`${n.method} ${n.path}`,n])),this.paths=e.paths??X()}async start(){this.token=uE(32).toString("hex");let e=fE((i,s)=>{this.dispatch(i,s)});this.server=e,await new Promise((i,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),mh.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(s=>s?i(s):n())}),this.server=null)}async persistAuthFiles(){await dn(this.paths.portFile,String(this.port)),await dn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){Ji(n,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(s);if(!c){Ji(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await xE(e)}catch(u){Ji(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Ji(n,200,u??{ok:!0})}catch(u){mh.error("IPC handler failed",{key:s,err:String(u)}),Ji(n,500,{error:u instanceof Error?u.message:String(u)})}}};function Ji(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function xE(t){let e=[],n=0;for await(let s of t){let c=s;if(n+=c.length,n>hE)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 Nv=Ht(fx(),1),Mv=Ht(zo(),1),Bv=Ht(qr(),1),Fv=Ht(Ad(),1),zv=Ht(Cd(),1),Uv=Ht(Nd(),1),Ex=Ht(Ho(),1),Gv=Ht(bx(),1);var vx=Ex.default;$e();ee();var{FWS:rS}=Lx(),Le=q("upstream.frontier"),Mx="application/json",Bx="none",iS=15e3;function sS(t){class e extends vx{constructor(i){super(i,Gf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Le.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,s){this.guardTeardown(),super.close(i,s)}terminate(){this.guardTeardown(),super.terminate()}send(i,...s){if(Il("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");Le.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){Le.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...s)}}return e}var is=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){Le.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:qf,...In(this.opts.ppeOverride)},n=sS(e),i=jf(this.opts.urlOverride),s={url:i,ws:n,fpID:Uf,aID:fo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Mx,force:!0},payloadEncoding:{encoding:Bx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new rS(s),d=!1,u=null,h,x,m=new Promise((y,v)=>{h=y,x=v}),_=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?x(y):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Le.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&_();for(let v of this.connectHandlers)Promise.resolve(v({initial:y})).catch(I=>Le.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,Le.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{Le.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 S=this.opts.openTimeoutMs??iS;u=setTimeout(()=>{_(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await m}catch(y){try{c.close(1e3,"open failed")}catch(v){Le.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Le.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Le.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?(Le.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.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=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let s=JSON.stringify(e),c=e;Fx(c)||Le.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:s.length});try{await n.send(s,{service:33555712,method:1,payloadType:Mx,payloadEncoding:Bx})}catch(u){throw Le.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 n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let s=n(i.cozeAgentId);s&&(i.cozePatToken=s)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Le.debug("drop non-adapter frontier frame",{service:n});return}let i=cS(e);if(!i){Le.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Le.debug("frame received but no onFrame handler",{size:i.length});return}let s;try{s=JSON.parse(i)}catch(d){Le.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=s;Fx(c)||Le.info("frontier frame in",{logid:aS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:oS(i)}),Promise.resolve(this.handler(s)).catch(d=>Le.warn("frontier frame handler threw",{err:String(d)}))}};function Fx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var zx=2e3;function oS(t){return t.length<=zx?t:`${t.slice(0,zx)}...<truncated, total ${t.length} chars>`}function aS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function cS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}$e();ee();var zd=q("skill-publish"),dS="/api/marketplace/product/skill/publish_with_assets",lS=15e4;async function Ux(t,e={}){let i=`${Rr(Pr(e.handshakeBase))}${dS}`,s=e.timeoutMs??lS,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",...In(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),s);zd.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}),m=x.headers.get("x-tt-logid")??"";if(!x.ok){let y=await x.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${m}: ${y.slice(0,200)}`)}let _=await x.json();if(zd.info("skill publish response",{logid:m,httpStatus:x.status,code:_.code,msg:_.msg,dataSkillId:_.data?.skill_id??"",dataVersion:_.data?.version??""}),_.code!==void 0&&_.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${_.code} msg=${_.msg??"-"} logid=${m}`);let S={};return _.data?.skill_id!==void 0&&_.data.skill_id!==""&&(S.skillId=String(_.data.skill_id)),_.data?.version&&(S.version=_.data.version),zd.info("skill publish ok",{logid:m,skillId:S.skillId??"",version:S.version??""}),S}catch(x){throw x instanceof T?x:x.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${s}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}ee();var Ud=q("upstream.switchable"),Xo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;Ud.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let s of this.connectHandlers)e.onConnect(s);try{await e.start()}catch(s){throw Ud.error("swap target start failed, reverting",{err:String(s)}),this.inner=i,s}await i.stop(n??"swapped").catch(s=>Ud.warn("previous upstream stop threw (ignored)",{err:String(s)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ee();var Gd=q("upstream"),Vr=class{handler=null;async start(){Gd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Gd.info("NoopUpstream stopped",{reason:e})}async send(e){Gd.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)}};$e();ee();ln();ee();Be();import{promises as uS}from"node:fs";var Gx=q("pat-token-store");async function Qo(t=X()){try{let n=(await uS.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Gx.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):n}catch(e){let n=e?.code;return n!=="ENOENT"&&Gx.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ss(t,e=X()){if(!t)throw new Error("writePatToken: empty patToken");await dn(e.patTokenFile,t,{mode:384})}Be();Be();import{promises as ea}from"node:fs";import{join as fS}from"node:path";function hS(t,e){return`#!/bin/sh
105
105
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
106
- `}function pS(t,e){return`@echo off\r
106
+ `}function xS(t,e){return`@echo off\r
107
107
  "${e}" "${t}" %*\r
108
- `}async function Gx(t,e=ee()){let r=e.binDir;await Yo.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 Yo.readFile(i,"utf8").catch(()=>null)===c||(await Yo.writeFile(i,c,"utf8"),process.platform!=="win32"&&await Yo.chmod(i,493)),r}ne();Oe();import{execSync as Hx}from"node:child_process";import{readFileSync as qx,unlinkSync as gS}from"node:fs";import{mkdir as mS,open as wS,readFile as jx,unlink as zd,writeFile as _S}from"node:fs/promises";import{dirname as yS}from"node:path";var ES=H("single-instance"),bS=t=>new Promise(e=>setTimeout(e,t)),Jo=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??ee().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&&ES.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 jx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await zd(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 jx(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 l=await this.readPidFrom(r);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await bS(this.claimLockIntervalMs);continue}await zd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await zd(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=qx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Lr)||r.includes("lib/index.js"))}catch{}try{let r=Hx(`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=Hx(`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{qx(this.pidFile,"utf8").trim()===String(this.selfPid)&&gS(this.pidFile)}catch{}})}};Xo();ne();var Qn=H("daemon.upstream-watchdog"),RS=12e4,PS=9e5,DS=3e4;function Gd(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var Qo=class{constructor(e){this.opts=e;this.softMs=e.softMs??Gd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",RS),this.hardMs=e.hardMs??Gd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",PS),this.intervalMs=e.intervalMs??Gd("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 q=H("daemon");async function $x(){let t=ee();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){_l({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:R=>Ve(R,t).logs,listAgentIds:()=>hs(t)});try{let{writeFileSync:R}=await import("node:fs");R(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 qx(t,e=X()){let n=e.binDir;await ea.mkdir(n,{recursive:!0});let i=fS(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),s=process.execPath,c=process.platform==="win32"?xS(t,s):hS(t,s);return await ea.readFile(i,"utf8").catch(()=>null)===c||(await ea.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ea.chmod(i,493)),n}ee();Be();import{execSync as Hx}from"node:child_process";import{readFileSync as jx,unlinkSync as pS}from"node:fs";import{mkdir as gS,open as mS,readFile as Wx,unlink as qd,writeFile as wS}from"node:fs/promises";import{dirname as _S}from"node:path";var yS=q("single-instance"),bS=t=>new Promise(e=>setTimeout(e,t)),ta=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??X().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Hi(n),isDaemon:n=>this.matchesDaemonTitle(n)},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 n=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&&yS.warn("removing stale pid file",{stalePid:i}),await wS(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return n.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),n}async release(){if(this.acquired){try{(await Wx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await qd(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 n=await Wx(e,"utf8"),i=Number.parseInt(n.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(n){if(n.code==="ENOENT")return null;throw n}}async withClaimLock(e){let n=`${this.pidFile}.lock`;await gS(_S(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let s;try{s=await mS(n,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let d=await this.readPidFrom(n);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await bS(this.claimLockIntervalMs);continue}await qd(n).catch(()=>{});continue}try{return await s.writeFile(String(this.selfPid)),await e()}finally{await s.close().catch(()=>{}),await qd(n).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${n} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=jx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Br)||n.includes("lib/index.js"))}catch{}try{let n=Hx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Br)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Hx(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let s=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return s.includes("node")||s.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{jx(this.pidFile,"utf8").trim()===String(this.selfPid)&&pS(this.pidFile)}catch{}})}};na();ee();var nr=q("daemon.upstream-watchdog"),CS=12e4,DS=9e5,RS=3e4;function jd(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ra=class{constructor(e){this.opts=e;this.softMs=e.softMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",CS),this.hardMs=e.hardMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",DS),this.intervalMs=e.intervalMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",RS),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?.(),nr.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&&nr.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&&nr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,nr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){nr.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:n,hardMs:this.hardMs}),this.opts.onFatal(n);return}n>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,nr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>nr.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=q("daemon");async function Vx(){let t=X();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){vl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:R=>Ye(R,t).logs,listAgentIds:()=>ms(t)});try{let{writeFileSync:R}=await import("node:fs");R(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
109
109
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
110
110
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
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 So(),o=i??{};us({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let c=new Vo(new Wr),l=null,u=new Io({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(R,G,W,te)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(R,G,W,te)}}),f=new Eo({paths:t,config:o,registry:u});l=f;let x,g,m=null,S={},_,b=null,I=null,A=null,T=new An;function P(R,G){return T.enqueue(()=>C(R,G))}function y(){I||(I=new Qo({isConnected:()=>c.isConnected()&&!(b?.isLivenessLost()??!1),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:R=>{if(process.env[rs]==="1"){q.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:R});return}q.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:R}),process.exit(1)}})),I.start()}async function C(R,G){let W=R,te=W?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Xe=Li(W.env),xe=W.handshake_url,pe=W.frontier_url,vt=Kx(W.env,xe,pe);if(A=W,!G?.force&&x===te&&g===vt){let we=await OS(t);return u.agents.size===0&&we?(q.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ta(t,f).catch(Ie=>q.warn("connect-noop auto-revive error (ignored)",{err:String(Ie)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let ht=!!x&&x!==te,en=g!==void 0&&g!==vt,Ft=ht||en,tn=await Gc({privatecode:te,...xe?{endpoint:xe}:{},ppeOverride:Xe});if(Ft){q.warn("connect config switched, resetting agents",{pcChanged:ht,envChanged:en,previousPc:x?ea(x):"",nextPc:ea(te)});for(let we of[...u.agents.values()])await we.dispose("connect config switch").catch(()=>{}),u.agents.delete(we.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Wr,"connect switch").catch(()=>{})}m=tn.deviceId,us({deviceId:m,pid:process.pid}),ud({patToken:te,env:W.env}).catch(we=>q.warn("coze-cli setup error (ignored)",{err:String(we)}));let Yr=new ts({handshake:tn,privatecode:te,...pe?{urlOverride:pe}:{},ppeOverride:Xe,getPatTokenForAgent:we=>u.agents.get(we)?.patToken});return await c.swap(Yr,"connect"),x=te,g=vt,S=Xe,_=xe,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),q.info("mock scenario set",{scenario:W.mock_scenario})),b||(b=new Mi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>M.retryPending().catch(we=>q.warn("detailSync.retryPending failed (ignored)",{err:String(we)})),onAuthFailures:Y})),b.start(),y(),Ft&&ta(t,f).catch(we=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(we)})),ns(te,t).catch(we=>q.warn("writePatToken after /connect failed (ignored)",{err:String(we)})),q.info("/connect: WS established",{deviceId:m}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async R=>f.createAgent(R.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let D={},B=new lo({agents:u.agents,publishSkillToMarketplace:async R=>{let G=u.agents.get(R.agentId)?.patToken??x;if(!G)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return zx({patToken:G,zip:R.zip,...R.skillId?{skillId:R.skillId}:{},skillName:R.skillName,...R.description?{description:R.description}:{},agentId:R.agentId,...R.accountId?{accountId:R.accountId}:{}},{handshakeBase:_,ppeOverride:S})},disposeAndMarkDisconnected:async(R,G)=>{let W=u.agents.get(R);if(W){await f.cleanupOpenclawSessionProviders(W).catch(Xe=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:R,err:String(Xe)}));let te=!0;try{await W.dispose(`disconnect: ${G}`)}catch(Xe){te=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:R,err:String(Xe)}),W.status="error"}te&&(W.status="disconnected",u.unregister(R),u.disconnectedAgents.add(R))}else u.disconnectedAgents.add(R)},disposeForDelete:async(R,G)=>{let W=u.agents.get(R);W&&(await f.cleanupOpenclawSessionProviders(W).catch(te=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:R,err:String(te)})),await W.dispose(`delete: ${G}`).catch(te=>q.warn("dispose during delete failed (ignored)",{agentId:R,err:String(te)})),u.unregister(R)),u.disconnectedAgents.delete(R)},detailSyncer:async R=>{if(!D.ref)throw new Error("agent-detail-sync not initialized yet");await D.ref.syncOne(R)},cleanupOpenclawProviders:async R=>{await f.cleanupOpenclawSessionProviders(R)},openclawRepair:async(R,G)=>{await f.openclawRepair(R,G)},isRuntimePendingPermission:R=>u.hasPendingPermissionFor(R)});u.registerExtension("_agent/listSkills",R=>B.listSkills(R.params)),u.registerExtension("_agent/addSkills",R=>B.addSkills(R.params)),u.registerExtension("_agent/removeSkills",R=>B.removeSkills(R.params)),u.registerExtension("_agent/publishSkill",R=>B.publishSkill(R.params)),u.registerExtension("_agent/getFileTree",R=>B.getFileTree(R.params)),u.registerExtension("_agent/getFileContent",R=>B.getFileContent(R.params)),u.registerExtension("_agent/update",R=>B.updateAgent(R.params)),u.registerExtension("_agent/disconnect",R=>B.disconnectAgent(R.params)),u.registerExtension("_agent/switchModel",R=>B.switchModel(R.params)),u.registerExtension("_agent/reset",R=>B.resetAgent(R.params)),u.registerExtension("_agent/repair",R=>B.repairAgent(R.params)),u.registerExtension("_agent/delete",R=>B.deleteAgent(R.params)),u.registerExtension("_agent/upgrade",R=>B.upgradeBridge(R.params));let M=new gs({paths:t,handlers:B,agentManager:f,sendDetail:R=>u.sendRequest("_agent/detail",R)});D.ref=M;let Y=async R=>{await Promise.allSettled(R.map(async G=>{try{await B.disconnectAgent({agentId:G.agentId,reason:`auth_failure: code=${G.code} ${G.message}`}),q.info("agent disconnected due to auth failure from heartbeat response",{agentId:G.agentId,code:G.code,message:G.message})}catch(W){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:G.agentId,err:String(W)})}}))};c.onConnect(({initial:R})=>{q.info("frontier upstream connected, triggering detail sync",{initial:R}),M.syncAll(R?"initial-connect":"reconnect").catch(G=>q.warn("detail sync top-level error (ignored)",{err:String(G)}))});let V=new Ao({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let R=u.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[rs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:m??"",frameworksCache:o.frameworksCache??{},...R?{mockScenario:R}:{}}}},{method:"POST",path:"/pair",handler:async R=>{let G=R,W=G?.privatecode,te=G?.pairing_code;if(!W||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Xe=Li(G.env),xe=G.handshake_url,pe=G.frontier_url,vt=Kx(G.env,xe,pe),ht=!!x&&x!==W,en=g!==void 0&&g!==vt,Ft=ht||en,tn=await Gc({privatecode:W,...xe?{endpoint:xe}:{},ppeOverride:Xe});if(Ft){q.warn("pair config switched, resetting agents",{pcChanged:ht,envChanged:en,previousPc:x?ea(x):"",nextPc:ea(W),previousEnvKey:g??"",nextEnvKey:vt});for(let Ie of[...u.agents.values()])await Ie.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ie.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Wr,"pair switch").catch(()=>{})}m=tn.deviceId,us({deviceId:m,pid:process.pid}),ud({patToken:W,env:G.env}).catch(Ie=>q.warn("coze-cli setup error (ignored)",{err:String(Ie)}));let Yr=new ts({handshake:tn,privatecode:W,...pe?{urlOverride:pe}:{},ppeOverride:Xe,getPatTokenForAgent:Ie=>u.agents.get(Ie)?.patToken});await c.swap(Yr,"pair");try{let Ie=new $n;o.frameworksCache=await Ie.detectAll(),await ji(o),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ie){q.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:te,patToken:W,frameworks:we,_meta:{cozeDeviceId:m}});q.info("_agent/pair ok",{pairResult:Ie}),x=W,g=vt,S=Xe,_=xe,G.mock_scenario!==void 0&&(u.setMockScenario(G.mock_scenario),q.info("mock scenario set",{scenario:G.mock_scenario})),ns(W,t).catch(Pe=>q.warn("writePatToken after /pair failed (ignored)",{err:String(Pe)})),b||(b=new Mi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>M.retryPending().catch(Pe=>q.warn("detailSync.retryPending failed (ignored)",{err:String(Pe)})),onAuthFailures:Y})),b.start(),y(),Ft&&ta(t,f).catch(Pe=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(Pe)}));let er;return G.agent_id&&(er=await NS(G.agent_id,t,f,Pe=>u.sendRequest("_agent/detail",Pe),W).catch(Pe=>(q.error("--agent-id ensureAgent failed",{agentId:G.agent_id,err:String(Pe)}),{ok:!1,agentId:G.agent_id??"",note:String(Pe)}))),{ok:!0,note:"paired with cloud",...er?{agent:er}:{}}}catch(Ie){return q.error("_agent/pair failed",{err:String(Ie)}),{ok:!1,note:`pair failed: ${String(Ie)}`}}}},{method:"POST",path:"/connect",handler:R=>P(R)},{method:"POST",path:"/_agent/create",handler:async R=>{let G=R;return{ok:!0,result:await f.createAgent(G)}}},{method:"POST",path:"/agent/send",handler:async R=>{let G=R;if(!G?.agentId||!G?.sessionId||!G?.kind||!G?.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 W=G;return await(W.groupFile?eh:Q0)(W,{core:u,patToken:x,handshakeBase:_,ppeOverride:S})}catch(W){if(W instanceof k)return{ok:!1,code:W.code,message:W.message};throw W}}},{method:"POST",path:"/reload",handler:async R=>{let G=R?.agent_id,W=await u.reloadAgents(G);return q.info("IPC /reload: recycled agent subprocesses",{agentId:G??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:X}=await V.start();try{await Gx(t.libEntry,t)}catch(R){q.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(R)})}await u.start(),MS({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new $n().detectAll(),await ji(o),o.frameworksCache)}).catch(R=>q.warn("startup warmup error (ignored)",{err:String(R)})),Cl().then(async()=>{let{probeAcpVersion:R}=await Promise.resolve().then(()=>(sn(),kl));for(let G of["claude-code","codex"]){let W=await R(G);W&&q.info("acp wrapper version",{framework:G,version:W})}}).catch(R=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(R)}));let se=null,oe={port:re,token:X,core:u,ipc:V,shutdown(R){return se||(q.info("daemon shutdown",{reason:R}),se=(async()=>{b?.stop(),I?.stop(),await u.stop(R),await V.stop(),await e.release()})(),se)}};for(let R of["SIGTERM","SIGINT"])process.on(R,()=>{oe.shutdown(R).then(()=>process.exit(0))});return process.on("exit",()=>m0()),process.on("unhandledRejection",R=>{q.error("unhandledRejection",{reason:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0})}),process.on("uncaughtException",R=>{q.error("uncaughtException (will exit, supervisor will restart)",{message:R.message,stack:R.stack,name:R.name});try{process.stderr.write(`FATAL uncaughtException: ${R.stack??R.message}
112
- `)}catch{}process.exit(1)}),q.info("daemon ready",{port:re,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:()=>Zo(t),connect:P}).catch(R=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(R)})),oe}async function OS(t){return hs(t).length>0}function ea(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Kx(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function LS(t,e){let r=hs(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(cn(),ps));for(let c of r){await o(c,t).catch(l=>q.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.deletedAt?(e.disconnectedAgents.add(c),q.info("agent marked deleted on startup",{agentId:c,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(c),q.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){q.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function NS(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(cn(),ps)),l=await c(t,e);if(l){if(l.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${l.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let g=Vx(l),m={agentId:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...o?{patToken:o}:{},...g?{_meta:g}:{}};return await r.createAgent(m),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}q.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??q;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 ta(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 ta(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(),ps));q.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,l=0;for(let u of i){let f;try{f=await o(u,t)}catch(x){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),l+=1;continue}if(!f){l+=1;continue}if(f.deletedAt){q.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),l+=1;continue}if(f.disconnectedAt){q.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),l+=1;continue}try{q.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=Vx(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){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),l+=1}}return q.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,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 i0(o,t)).status==="refreshed"&&(i+=1)}catch(c){q.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&q.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??q;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 Vx(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Xo();Oe();import{readFile as Zx}from"node:fs/promises";var Qt=class{paths;constructor(e){this.paths=e??ee()}async probe(e=1e3){let r=await na(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 na(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}),f=await u.text();return{status:u.status,body:zS(f)}}finally{clearTimeout(l)}}};async function na(t){try{let[e,r]=await Promise.all([Zx(t.portFile,"utf8"),Zx(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)}$t();ne();ir();import{spawn as GS}from"node:child_process";import{userInfo as Jx}from"node:os";var Hd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",HS=new Set(["bash","zsh","sh","dash","ksh"]),Yx=$e("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),qS=2e3;function jS(t,e=Hd){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(`
113
- `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.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 KS(t){return new Promise(e=>{let r=`printf '%s' '${Hd}'; env; printf '%s' '${Hd}'`,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,l=g=>{try{i.pid&&process.kill(-i.pid,g)}catch{}},u=g=>{c||(c=!0,clearTimeout(f),clearTimeout(x),e(g))};i.stdout?.on("data",g=>{o+=g.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>l("SIGTERM"),Yx),x=setTimeout(()=>{l("SIGKILL"),u(o.length>0?o:null)},Yx+qS)})}async function qd(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??KS)(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}}Oe();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}}sn();import{chmod as $S,copyFile as Xx,mkdir as ep,readFile as ra,rename as Qx,rm as jd,stat as tp,writeFile as VS}from"node:fs/promises";import{homedir as iP}from"node:os";import{dirname as ZS,join as Kr,resolve as Wd,sep as is}from"node:path";import{fileURLToPath as YS}from"node:url";$t();ne();Oe();var Kd=H("dist-install");function JS(t){let e=YS(t),r=ZS(e),i=`${is}src${is}`;if(r.includes(i)||r.endsWith(`${is}src${is}cli`))return null;let o=Wd(r,"index.js"),c=Wd(r,"..","package.json");return{dist:o,pkgJson:c}}async function Vd(t={}){let e=t.paths??ee(),r=JS(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 S=JSON.parse(await ra(o,"utf8"));c=S.version??"unknown",l=S.dependencies??{}}catch(S){return Kd.warn("cannot read source package.json,skip dist install",{err:String(S)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(S)}`}}let u=ti.map(S=>`${S}@${l[S]??"latest"}`),f=await So(e.configFile)??{},x=f.libVersion,g=await ra(e.libEntry).then(()=>!0).catch(()=>!1),m=x===c;if(m&&g&&await $d(e))return{kind:"already-current",libVersion:c};if(!m||!g){await ep(e.libDir,{recursive:!0}),await Xx(i,e.libEntry),await Xx(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let S=Wd(e.libDir,"package.json"),_=`${JSON.stringify({type:"module"},null,2)}
114
- `;await ra(S,"utf8").catch(()=>null)!==_&&await VS(S,_)}return(!m||!await $d(e))&&await(t.installWrappers??XS)(e,u),f.libVersion=c,await ji(f,e.configFile),Kd.info("dist installed",{libEntry:e.libEntry,fromVersion:x,toVersion:c}),m&&g?{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 $d(t){for(let e of ti){let r=Kr(t.libDir,"node_modules",...e.split("/"),"package.json");if(!await tp(r).then(o=>o.isFile()).catch(()=>!1))return!1}return!0}async function XS(t,e){await t1(t.installLock,async()=>{if(await $d(t))return;let r=Math.random().toString(36).slice(2,10),i=`${t.libDir}${is}.staging-${process.pid}-${r}`,o=Kr(i,"node_modules"),c=Kr(t.libDir,"node_modules");try{await ep(i,{recursive:!0}),await QS(e,i),await e1(o);let l=`${c}.trash-${r}`;await Qx(c,l).catch(()=>{}),await Qx(o,c),await jd(l,{recursive:!0,force:!0}).catch(()=>{}),Kd.info("wrapper closure installed",{liveNm:c,specs:e})}finally{await jd(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"]}),l="";c.stderr?.on("data",f=>{l.length<8192&&(l+=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}: ${l.trim().slice(0,2e3)}`))})})}async function e1(t){for(let e of ti){let r=Kr(t,...e.split("/")),i=JSON.parse(await ra(Kr(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=Kr(t,".bin",o),l=await tp(c);process.platform!=="win32"&&!(l.mode&73)&&await $S(c,l.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 jd(t,{force:!0}).catch(()=>{})}}Aa();ne();Oe();import{closeSync as rp,fstatSync as ip,openSync as sp,readFileSync as n1,readSync as r1,readdirSync as i1,statSync as s1}from"node:fs";import{join as ia}from"node:path";var o1=new Set(["debug","info","warn","error"]);function op(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),f=Number.isInteger(u)&&u>=0?u:200,x=c.value&&o1.has(c.value)?c.value:void 0,g={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(g.agentId=r.value),i.value&&(g.date=i.value),x&&(g.level=x),l.value&&(g.grep=l.value),g}function a1(t,e){return t.agentId?ia(Ve(t.agentId,e).logs,sr("agent",t.date)):ia(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=Ia(o,e);if(!c)continue;let l=0;try{l=s1(ia(t,o)).size}catch{}i.push({file:ia(t,o),date:c,size:l})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function ap(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 np={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 cp(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&&np[o]&&(c=`\x1B[${np[o]}m${c}\x1B[0m`);let l=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",f=Object.entries(r).filter(([x])=>!l1.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${l} ${u}${f}`}function f1(t,e,r){let c=n1(t,"utf8").split(`
115
- `).filter(l=>l.length>0).filter(l=>ap(l,{level:e.level,grep:e.grep}));for(let l of c1(c,e.lines))process.stdout.write(`${cp(l,{raw:e.raw,color:r})}
116
- `)}async function dp(t,e){let r=e.paths??ee(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?Ve(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=d1(l,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
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}
111
+ `)}catch{}}let e=new ta({processTitle:Br}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await ko(),s=i??{};xs({pid:process.pid}),H.info(i?"loaded bridge config":"initialized bridge config");let c=new Xo(new Vr),d=null,u=new Co({upstream:c,paths:t,bridgeConfig:s,sessionSpawner:async(R,U,j,Q)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(R,U,j,Q)}}),h=new Io({paths:t,config:s,registry:u});d=h;let x,m,_=null,S={},y,v=null,I=null,A=null,k=new Cn;function P(R,U){return k.enqueue(()=>D(R,U))}function b(){I||(I=new ra({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:R=>{if(process.env[os]==="1"){H.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:R});return}H.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:R}),process.exit(1)}})),I.start()}async function D(R,U){let j=R,Q=j?.privatecode;if(!Q)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let nt=Bi(j.env),me=j.handshake_url,we=j.frontier_url,At=$x(j.env,me,we);if(A=j,!U?.force&&x===Q&&m===At){let Ee=await PS(t);return u.agents.size===0&&Ee?(H.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),sa(t,h).catch(Ce=>H.warn("connect-noop auto-revive error (ignored)",{err:String(Ce)}))):H.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let mt=!!x&&x!==Q,rn=m!==void 0&&m!==At,Gt=mt||rn,sn=await Hc({privatecode:Q,...me?{endpoint:me}:{},ppeOverride:nt});if(Gt){H.warn("connect config switched, resetting agents",{pcChanged:mt,envChanged:rn,previousPc:x?ia(x):"",nextPc:ia(Q)});for(let Ee of[...u.agents.values()])await Ee.dispose("connect config switch").catch(()=>{}),u.agents.delete(Ee.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 Vr,"connect switch").catch(()=>{})}_=sn.deviceId,xs({deviceId:_,pid:process.pid}),xd({patToken:Q,env:j.env}).catch(Ee=>H.warn("coze-cli setup error (ignored)",{err:String(Ee)}));let Qr=new is({handshake:sn,privatecode:Q,...we?{urlOverride:we}:{},ppeOverride:nt,getPatTokenForAgent:Ee=>u.agents.get(Ee)?.patToken});return await c.swap(Qr,"connect"),x=Q,m=At,S=nt,y=me,j.mock_scenario!==void 0&&(u.setMockScenario(j.mock_scenario),H.info("mock scenario set",{scenario:j.mock_scenario})),v||(v=new zi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>B.retryPending().catch(Ee=>H.warn("detailSync.retryPending failed (ignored)",{err:String(Ee)})),onAuthFailures:V})),v.start(),b(),Gt&&sa(t,h).catch(Ee=>H.warn("post-connect-switch auto-revive error (ignored)",{err:String(Ee)})),ss(Q,t).catch(Ee=>H.warn("writePatToken after /connect failed (ignored)",{err:String(Ee)})),H.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async R=>h.createAgent(R.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},F=new xo({agents:u.agents,publishSkillToMarketplace:async R=>{let U=u.agents.get(R.agentId)?.patToken??x;if(!U)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Ux({patToken:U,zip:R.zip,...R.skillId?{skillId:R.skillId}:{},skillName:R.skillName,...R.description?{description:R.description}:{},agentId:R.agentId,...R.accountId?{accountId:R.accountId}:{}},{handshakeBase:y,ppeOverride:S})},disposeAndMarkDisconnected:async(R,U)=>{let j=u.agents.get(R);if(j){await h.cleanupOpenclawSessionProviders(j).catch(nt=>H.warn("cleanup openclaw providers failed (ignored)",{agentId:R,err:String(nt)}));let Q=!0;try{await j.dispose(`disconnect: ${U}`)}catch(nt){Q=!1,H.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:R,err:String(nt)}),j.status="error"}Q&&(j.status="disconnected",u.unregister(R),u.disconnectedAgents.add(R))}else u.disconnectedAgents.add(R)},disposeForDelete:async(R,U)=>{let j=u.agents.get(R);j&&(await h.cleanupOpenclawSessionProviders(j).catch(Q=>H.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:R,err:String(Q)})),await j.dispose(`delete: ${U}`).catch(Q=>H.warn("dispose during delete failed (ignored)",{agentId:R,err:String(Q)})),u.unregister(R)),u.disconnectedAgents.delete(R)},detailSyncer:async R=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(R)},cleanupOpenclawProviders:async(R,U)=>{await h.cleanupOpenclawSessionProviders(R,U)},openclawRepair:async(R,U)=>{await h.openclawRepair(R,U)},isRuntimePendingPermission:R=>u.hasPendingPermissionFor(R)});u.registerExtension("_agent/listSkills",R=>F.listSkills(R.params)),u.registerExtension("_agent/addSkills",R=>F.addSkills(R.params)),u.registerExtension("_agent/removeSkills",R=>F.removeSkills(R.params)),u.registerExtension("_agent/publishSkill",R=>F.publishSkill(R.params)),u.registerExtension("_agent/getFileTree",R=>F.getFileTree(R.params)),u.registerExtension("_agent/getFileContent",R=>F.getFileContent(R.params)),u.registerExtension("_agent/update",R=>F.updateAgent(R.params)),u.registerExtension("_agent/disconnect",R=>F.disconnectAgent(R.params)),u.registerExtension("_agent/switchModel",R=>F.switchModel(R.params)),u.registerExtension("_agent/reset",R=>F.resetAgent(R.params)),u.registerExtension("_agent/repair",R=>F.repairAgent(R.params)),u.registerExtension("_agent/delete",R=>F.deleteAgent(R.params)),u.registerExtension("_agent/upgrade",R=>F.upgradeBridge(R.params));let B=new ys({paths:t,handlers:F,agentManager:h,sendDetail:R=>u.sendRequest("_agent/detail",R)});O.ref=B;let V=async R=>{await Promise.allSettled(R.map(async U=>{try{await F.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:R})=>{H.info("frontier upstream connected, triggering detail sync",{initial:R}),B.syncAll(R?"initial-connect":"reconnect").catch(U=>H.warn("detail sync top-level error (ignored)",{err:String(U)}))});let K=new Do({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let R=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[os]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:_??"",frameworksCache:s.frameworksCache??{},...R?{mockScenario:R}:{}}}},{method:"POST",path:"/pair",handler:async R=>{let U=R,j=U?.privatecode,Q=U?.pairing_code;if(!j||!Q)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let nt=Bi(U.env),me=U.handshake_url,we=U.frontier_url,At=$x(U.env,me,we),mt=!!x&&x!==j,rn=m!==void 0&&m!==At,Gt=mt||rn,sn=await Hc({privatecode:j,...me?{endpoint:me}:{},ppeOverride:nt});if(Gt){H.warn("pair config switched, resetting agents",{pcChanged:mt,envChanged:rn,previousPc:x?ia(x):"",nextPc:ia(j),previousEnvKey:m??"",nextEnvKey:At});for(let Ce of[...u.agents.values()])await Ce.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ce.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 Vr,"pair switch").catch(()=>{})}_=sn.deviceId,xs({deviceId:_,pid:process.pid}),xd({patToken:j,env:U.env}).catch(Ce=>H.warn("coze-cli setup error (ignored)",{err:String(Ce)}));let Qr=new is({handshake:sn,privatecode:j,...we?{urlOverride:we}:{},ppeOverride:nt,getPatTokenForAgent:Ce=>u.agents.get(Ce)?.patToken});await c.swap(Qr,"pair");try{let Ce=new Zn;s.frameworksCache=await Ce.detectAll(),await $i(s),H.info("frameworks_cache refreshed before pair",{detected:Object.keys(s.frameworksCache)})}catch(Ce){H.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ce)})}let Ee=Object.keys(s.frameworksCache??{});try{let Ce=await u.sendRequest("_agent/pair",{pairCode:Q,patToken:j,frameworks:Ee,_meta:{cozeDeviceId:_}});H.info("_agent/pair ok",{pairResult:Ce}),x=j,m=At,S=nt,y=me,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),H.info("mock scenario set",{scenario:U.mock_scenario})),ss(j,t).catch(Ne=>H.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),v||(v=new zi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>B.retryPending().catch(Ne=>H.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:V})),v.start(),b(),Gt&&sa(t,h).catch(Ne=>H.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let rr;return U.agent_id&&(rr=await LS(U.agent_id,t,h,Ne=>u.sendRequest("_agent/detail",Ne),j).catch(Ne=>(H.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Ne)}),{ok:!1,agentId:U.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...rr?{agent:rr}:{}}}catch(Ce){return H.error("_agent/pair failed",{err:String(Ce)}),{ok:!1,note:`pair failed: ${String(Ce)}`}}}},{method:"POST",path:"/connect",handler:R=>P(R)},{method:"POST",path:"/_agent/create",handler:async R=>{let U=R;return{ok:!0,result:await h.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async R=>{let U=R;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new T("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=U;return await(j.groupFile?th:eh)(j,{core:u,patToken:x,handshakeBase:y,ppeOverride:S})}catch(j){if(j instanceof T)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async R=>{let U=R?.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(()=>{ce.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:te,token:Z}=await K.start();try{await qx(t.libEntry,t)}catch(R){H.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(R)})}await u.start(),NS({paths:t,core:u,agentManager:h,detectAll:async()=>(s.frameworksCache=await new Zn().detectAll(),await $i(s),s.frameworksCache)}).catch(R=>H.warn("startup warmup error (ignored)",{err:String(R)})),Ol().then(async()=>{let{probeAcpVersion:R}=await Promise.resolve().then(()=>(cn(),Rl));for(let U of["claude-code","codex"]){let j=await R(U);j&&H.info("acp wrapper version",{framework:U,version:j})}}).catch(R=>H.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(R)}));let ae=null,ce={port:te,token:Z,core:u,ipc:K,shutdown(R){return ae||(H.info("daemon shutdown",{reason:R}),ae=(async()=>{v?.stop(),I?.stop(),await u.stop(R),await K.stop(),await e.release()})(),ae)}};for(let R of["SIGTERM","SIGINT"])process.on(R,()=>{ce.shutdown(R).then(()=>process.exit(0))});return process.on("exit",()=>v0()),process.on("unhandledRejection",R=>{H.error("unhandledRejection",{reason:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0})}),process.on("uncaughtException",R=>{H.error("uncaughtException (will exit, supervisor will restart)",{message:R.message,stack:R.stack,name:R.name});try{process.stderr.write(`FATAL uncaughtException: ${R.stack??R.message}
112
+ `)}catch{}process.exit(1)}),H.info("daemon ready",{port:te,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(s.frameworksCache??{}),libVersion:s.libVersion??"dev"}),BS({cliSpawned:process.env[os]==="1",readPatToken:()=>Qo(t),connect:P}).catch(R=>H.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(R)})),ce}async function PS(t){return ms(t).length>0}function ia(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function $x(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function OS(t,e){let n=ms(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(un(),_s));for(let c of n){await s(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 LS(t,e,n,i,s){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(un(),_s)),d=await c(t,e);if(d){if(d.deletedAt)throw new T("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 m=Jx(d),_={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...s?{patToken:s}:{},...m?{_meta:m}:{}};return await n.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 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 h={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...s?{patToken:s}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await n.createAgent(h);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function NS(t){let e=t.logger??H;try{let n=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(n??{})})}catch(n){e.warn("framework detection failed (using cached)",{err:String(n)})}await OS(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await sa(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await MS(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function sa(t,e){let{readdir:n}=await import("node:fs/promises"),i;try{i=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(un(),_s));H.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let h;try{h=await s(u,t)}catch(x){H.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){H.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){H.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{H.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=Jx(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){H.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.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 MS(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let s of n)try{(await l0(s,t)).status==="refreshed"&&(i+=1)}catch(c){H.warn("refresh builtin skills failed (skipping agent)",{agentId:s,err:String(c)})}return i>0&&H.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function BS(t){let e=t.logger??H;if(t.cliSpawned)return"skipped-cli";let n=await t.readPatToken();return n?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:n}).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 Jx(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}na();Be();import{readFile as Zx}from"node:fs/promises";var nn=class{paths;constructor(e){this.paths=e??X()}async probe(e=1e3){let n=await oa(this.paths);if(!n)return{kind:"not-running"};try{let i=await this.fetch(n,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...n,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:zS(i)}}}async request(e){let n=await oa(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let i=n.body!==void 0,s={Authorization:`Bearer ${e.token}`};i&&(s["content-type"]="application/json");let c=new AbortController,d=setTimeout(()=>c.abort(),n.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:s,body:i?JSON.stringify(n.body):void 0,signal:c.signal}),h=await u.text();return{status:u.status,body:FS(h)}}finally{clearTimeout(d)}}};async function oa(t){try{let[e,n]=await Promise.all([Zx(t.portFile,"utf8"),Zx(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),s=n.trim();return!Number.isFinite(i)||i<=0||!s?null:{port:i,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}function FS(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function zS(t){return t instanceof Error?t.message:String(t)}Zt();ee();ar();import{spawn as US}from"node:child_process";import{userInfo as Xx}from"node:os";var Wd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",GS=new Set(["bash","zsh","sh","dash","ksh"]),Yx=Ze("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),qS=2e3;function HS(t,e=Wd){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let s=t.slice(n+e.length,i),c={};for(let d of s.split(`
113
+ `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function jS(){let t=(process.env.SHELL??"").trim()||(Xx().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return GS.has(e)?t:null}function WS(t){return new Promise(e=>{let n=`printf '%s' '${Wd}'; env; printf '%s' '${Wd}'`,i;try{i=US(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Xx().homedir}})}catch{e(null);return}let s="",c=!1,d=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{c||(c=!0,clearTimeout(h),clearTimeout(x),e(m))};i.stdout?.on("data",m=>{s+=m.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(s.length>0?s:null));let h=setTimeout(()=>d("SIGTERM"),Yx),x=setTimeout(()=>{d("SIGKILL"),u(s.length>0?s:null)},Yx+qS)})}async function Kd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=jS();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??WS)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let s=HS(i);return s==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:s}}Be();function Pn(t,...e){let n=[],i;for(let s=0;s<t.length;s++){let c=t[s],d=!1;for(let u of e){if(c===u){i=t[s+1],s+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||n.push(c)}return{value:i,rest:n}}cn();import{chmod as KS,copyFile as Qx,mkdir as tp,readFile as cs,rename as ep,rm as Jd,stat as Zd,writeFile as $S}from"node:fs/promises";import{homedir as QR}from"node:os";import{dirname as VS,join as Ut,resolve as Yd,sep as as}from"node:path";import{fileURLToPath as JS}from"node:url";Zt();ee();Be();var Jr=q("dist-install");function np(){return{darwin:{arm64:"@zed-industries/codex-acp-darwin-arm64",x64:"@zed-industries/codex-acp-darwin-x64"},linux:{arm64:"@zed-industries/codex-acp-linux-arm64",x64:"@zed-industries/codex-acp-linux-x64"},win32:{arm64:"@zed-industries/codex-acp-win32-arm64",x64:"@zed-industries/codex-acp-win32-x64"}}[process.platform]?.[process.arch]}function ZS(){return process.platform==="win32"?"codex-acp.exe":"codex-acp"}function YS(t){let e=JS(t),n=VS(e),i=`${as}src${as}`;if(n.includes(i)||n.endsWith(`${as}src${as}cli`))return null;let s=Yd(n,"index.js"),c=Yd(n,"..","package.json");return{dist:s,pkgJson:c}}async function Xd(t={}){let e=t.paths??X(),n=YS(import.meta.url),i=t.sourceDist??n?.dist,s=t.sourcePackageJson??n?.pkgJson;if(!i||!s)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 cs(s,"utf8"));c=v.version??"unknown",d=v.dependencies??{}}catch(v){return Jr.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=ps.map(v=>({name:v,spec:d[v]??"latest"})),h=u.map(({name:v,spec:I})=>`${v}@${I}`),x=await ko(e.configFile)??{},m=x.libVersion,_=await cs(e.libEntry).then(()=>!0).catch(()=>!1),S=m===c,y=await rp(e,u);if(S&&_&&y)return{kind:"already-current",libVersion:c};if(!S||!_){await tp(e.libDir,{recursive:!0}),await Qx(i,e.libEntry),await Qx(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=Yd(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
114
+ `;await cs(v,"utf8").catch(()=>null)!==I&&await $S(v,I)}return y||(t.installWrappers?await t.installWrappers(e,h):await QS(e,h,u)),x.libVersion=c,await $i(x,e.configFile),Jr.info("dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),S&&_?{kind:"already-current",libVersion:c}:m?{kind:"version-changed",fromVersion:m,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function rp(t,e){for(let n of e){let i=Ut(t.libDir,"node_modules",...n.name.split("/"),"package.json"),s;try{s=JSON.parse(await cs(i,"utf8"))}catch(d){return Jr.warn("wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(d)}),!1}let c=s.version;if(!c)return Jr.warn("wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!XS(c,n.spec))return Jr.warn("wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:c,expected:n.spec}),!1}return!!await ip(Ut(t.libDir,"node_modules"))}function XS(t,e){let n=$d(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=$d(i.slice(1));if(!c)return!0;if(Vd(n,c)<0)return!1;let d=c[0]>0?[c[0]+1,0,0]:c[1]>0?[0,c[1]+1,0]:[0,0,c[2]+1];return Vd(n,d)<0}let s=$d(i);return s?Vd(n,s)===0:!0}function $d(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Vd(t,e){for(let n=0;n<3;n++){let i=(t[n]??0)-(e[n]??0);if(i!==0)return i}return 0}async function QS(t,e,n){await n1(t.installLock,async()=>{if(await rp(t,n))return;let i=Math.random().toString(36).slice(2,10),s=`${t.libDir}${as}.staging-${process.pid}-${i}`,c=Ut(s,"node_modules"),d=Ut(t.libDir,"node_modules");try{await tp(s,{recursive:!0}),await e1(e,s),await t1(c);let u=`${d}.trash-${i}`;await ep(d,u).catch(()=>{}),await ep(c,d),await Jd(u,{recursive:!0,force:!0}).catch(()=>{}),Jr.info("wrapper closure installed",{liveNm:d,specs:e})}finally{await Jd(s,{recursive:!0,force:!0}).catch(()=>{})}})}function e1(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,s)=>{let c=st("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";c.stderr?.on("data",h=>{d.length<8192&&(d+=h.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",h=>{clearTimeout(u),s(new Error(`spawn npm failed: ${String(h)}`))}),c.once("close",h=>{clearTimeout(u),h===0?i():s(new Error(`npm install \u9000\u51FA\u7801 ${h}: ${d.trim().slice(0,2e3)}`))})})}async function t1(t){for(let e of ps){let n=Ut(t,...e.split("/")),i=JSON.parse(await cs(Ut(n,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let s=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!s)throw new Error(`${e}: package.json \u7F3A bin`);let c=Ut(t,".bin",s),d=await Zd(c);process.platform!=="win32"&&!(d.mode&73)&&await KS(c,d.mode|73).catch(()=>{})}if(!await ip(t)){let e=np()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex-acp binary \u7F3A\u5931`)}}async function ip(t){let e=np();if(!e)return!0;let n=Ut(t,...e.split("/")),i=Ut(n,"package.json"),s=Ut(n,"bin",ZS()),[c,d]=await Promise.all([Zd(i).then(u=>u.isFile()).catch(()=>!1),Zd(s).then(u=>u.isFile()).catch(()=>!1)]);return c&&d}async function n1(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let s=0;s<60&&!i;s++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await Jd(t,{force:!0}).catch(()=>{})}}ka();ee();Be();import{closeSync as op,fstatSync as ap,openSync as cp,readFileSync as r1,readSync as i1,readdirSync as s1,statSync as o1}from"node:fs";import{join as aa}from"node:path";var a1=new Set(["debug","info","warn","error"]);function dp(t){let e=t,n=Pn(e,"--agent-id");e=n.rest;let i=Pn(e,"--date");e=i.rest;let s=Pn(e,"-n","--lines");e=s.rest;let c=Pn(e,"--level");e=c.rest;let d=Pn(e,"--grep");e=d.rest;let u=s.value===void 0?200:Number(s.value),h=Number.isInteger(u)&&u>=0?u:200,x=c.value&&a1.has(c.value)?c.value:void 0,m={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(m.agentId=n.value),i.value&&(m.date=i.value),x&&(m.level=x),d.value&&(m.grep=d.value),m}function c1(t,e){return t.agentId?aa(Ye(t.agentId,e).logs,cr("agent",t.date)):aa(e.bridgeLogsDir,cr("bridge",t.date))}function d1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function l1(t,e){let n;try{n=s1(t)}catch{return[]}let i=[];for(let s of n){let c=Ta(s,e);if(!c)continue;let d=0;try{d=o1(aa(t,s)).size}catch{}i.push({file:aa(t,s),date:c,size:d})}return i.sort((s,c)=>c.date.localeCompare(s.date)),i}function lp(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let n;try{n=JSON.parse(t).level}catch{return!0}if(typeof n=="string"&&!Al(n,e.level))return!1}return!0}var sp={debug:"90",info:"36",warn:"33",error:"31"},u1=new Set(["ts","level","module","msg"]);function f1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function up(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=f1(n.ts),s=typeof n.level=="string"?n.level:"",c=s.toUpperCase().padEnd(5);e.color&&sp[s]&&(c=`\x1B[${sp[s]}m${c}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",h=Object.entries(n).filter(([x])=>!u1.has(x)).map(([x,m])=>` ${x}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${d} ${u}${h}`}function h1(t,e,n){let c=r1(t,"utf8").split(`
115
+ `).filter(d=>d.length>0).filter(d=>lp(d,{level:e.level,grep:e.grep}));for(let d of d1(c,e.lines))process.stdout.write(`${up(d,{raw:e.raw,color:n})}
116
+ `)}async function fp(t,e){let n=e.paths??X(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Ye(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=l1(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
117
+ `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
118
+ `);return 0}let s=t.date??Ln(new Date),c=c1({agentId:t.agentId,date:s},n);try{h1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
119
119
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
120
- (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
121
- `),1}return t.follow&&await p1(c,t,i),0}var h1=500;function x1(t){try{let e=sp(t,"r");try{return ip(e).size}finally{rp(e)}}catch{return 0}}async function p1(t,e,r){let i=x1(t),o="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let f=sp(t,"r");try{let x=ip(f).size;if(x>i){let g=Buffer.allocUnsafe(x-i),m=r1(f,g,0,g.length,i);u=g.subarray(0,m).toString("utf8"),i+=m}}finally{rp(f)}}catch{}if(u){let f=(o+u).split(`
122
- `);o=f.pop()??"";for(let x of f)x.length>0&&ap(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${cp(x,{raw:e.raw,color:r})}
123
- `)}await new Promise(f=>setTimeout(f,h1))}}finally{process.off("SIGINT",l)}}import{basename as g1,resolve as m1}from"node:path";Oe();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 lp(t,e={}){let r=e.paths??ee();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>
120
+ (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
121
+ `),1}return t.follow&&await g1(c,t,i),0}var x1=500;function p1(t){try{let e=cp(t,"r");try{return ap(e).size}finally{op(e)}}catch{return 0}}async function g1(t,e,n){let i=p1(t),s="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let h=cp(t,"r");try{let x=ap(h).size;if(x>i){let m=Buffer.allocUnsafe(x-i),_=i1(h,m,0,m.length,i);u=m.subarray(0,_).toString("utf8"),i+=_}}finally{op(h)}}catch{}if(u){let h=(s+u).split(`
122
+ `);s=h.pop()??"";for(let x of h)x.length>0&&lp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${up(x,{raw:e.raw,color:n})}
123
+ `)}await new Promise(h=>setTimeout(h,x1))}}finally{process.off("SIGINT",d)}}import{basename as m1,resolve as w1}from"node:path";Be();var _1=9e4,y1={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 b1(t){return y1[t]??1}async function hp(t,e={}){let n=e.paths??X();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>
124
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.
125
- `),3;let i=await na(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 E1(i,"/agent/send",o,w1)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
125
+ `),3;let i=await oa(n).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${n.portFile} / ${n.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
126
+ `),4;let s={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:w1(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 E1(i,"/agent/send",s,_1)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
127
127
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
128
- `),y1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
129
- `);else{let l=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 ${l} (uri=${u})
130
- `)}else process.stdout.write(`Sent ${t.kind} ${l} (${b1(c.bytes)})
131
- `)}return 0}async function E1(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(),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=${l.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function b1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var _p=H("cli");function qe(t,e){let{value:r,rest:i}=Cn(t,e);return{value:r,rest:i}}function la(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
132
- `)}function K1(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}=qe(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 $1(e.slice(1));if(e[0]==="log")return{mode:"log",...op(e.slice(1))};if(e[0]==="connect")return V1(e.slice(1));if(e.includes("--status"))return la("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return la("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return la("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return la("--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}=qe(r,"--pat-token");r=o;let{value:c,rest:l}=qe(r,"--pair-code");r=l;let{value:u,rest:f}=qe(r,"--env");r=f;let{value:x,rest:g}=qe(r,"--handshake-url");r=g;let{value:m,rest:S}=qe(r,"--frontier-url");r=S;let{value:_,rest:b}=qe(r,"--mock-scenario");r=b;let{value:I}=qe(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),m&&(T.frontierUrl=m),_&&(T.mockScenario=_),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function $1(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}=qe(i,"--caption");i=c;let{value:l,rest:u}=qe(i,"--name");i=u;let{value:f,rest:x}=qe(i,"--agent-id");i=x;let{value:g,rest:m}=qe(i,"--session-id");i=m;let{value:S,rest:_}=qe(i,"--mime");i=_;let b=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),l&&(A.name=l),f&&(A.agentId=f),g&&(A.sessionId=g),b&&(A.groupFile=!0),S&&(A.mimeType=S),A}function V1(t){let e=t,{value:r,rest:i}=qe(e,"--pat-token");e=i;let{value:o,rest:c}=qe(e,"--env");e=c;let{value:l,rest:u}=qe(e,"--handshake-url");e=u;let{value:f,rest:x}=qe(e,"--frontier-url");e=x;let{value:g,rest:m}=qe(e,"--mock-scenario");e=m;let S=e.includes("--skip-rebuild-env"),_={mode:"connect"};return r&&(_.privatecode=r),o&&(_.env=o),l&&(_.handshakeUrl=l),f&&(_.frontierUrl=f),g&&(_.mockScenario=g),S&&(_.skipRebuildEnv=!0),_}var Z1=`
128
+ `),b1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
129
+ `);else{let d=t.name??m1(s.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} (${v1(c.bytes)})
131
+ `)}return 0}async function E1(t,e,n,i){let s=new AbortController,c=setTimeout(()=>s.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(n),signal:s.signal}),u=await d.text(),h=u?JSON.parse(u):null;return h&&typeof h=="object"&&"ok"in h?h:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function v1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var vp=q("cli");function Ke(t,e){let{value:n,rest:i}=Pn(t,e);return{value:n,rest:i}}function ha(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:P}=Ke(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 V1(e.slice(1));if(e[0]==="log")return{mode:"log",...dp(e.slice(1))};if(e[0]==="connect")return J1(e.slice(1));if(e.includes("--status"))return ha("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ha("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ha("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ha("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:i,rest:s}=Ke(n,"--pat-token");n=s;let{value:c,rest:d}=Ke(n,"--pair-code");n=d;let{value:u,rest:h}=Ke(n,"--env");n=h;let{value:x,rest:m}=Ke(n,"--handshake-url");n=m;let{value:_,rest:S}=Ke(n,"--frontier-url");n=S;let{value:y,rest:v}=Ke(n,"--mock-scenario");n=v;let{value:I}=Ke(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let k={mode:"pair",privatecode:i,pairingCode:c};return u&&(k.env=u),x&&(k.handshakeUrl=x),_&&(k.frontierUrl=_),y&&(k.mockScenario=y),I&&(k.agentId=I),A&&(k.skipRebuildEnv=!0),k}function V1(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:s,rest:c}=Ke(i,"--caption");i=c;let{value:d,rest:u}=Ke(i,"--name");i=u;let{value:h,rest:x}=Ke(i,"--agent-id");i=x;let{value:m,rest:_}=Ke(i,"--session-id");i=_;let{value:S,rest:y}=Ke(i,"--mime");i=y;let v=i.includes("--group-file");i=i.filter(k=>k!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return s&&(A.caption=s),d&&(A.name=d),h&&(A.agentId=h),m&&(A.sessionId=m),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function J1(t){let e=t,{value:n,rest:i}=Ke(e,"--pat-token");e=i;let{value:s,rest:c}=Ke(e,"--env");e=c;let{value:d,rest:u}=Ke(e,"--handshake-url");e=u;let{value:h,rest:x}=Ke(e,"--frontier-url");e=x;let{value:m,rest:_}=Ke(e,"--mock-scenario");e=_;let S=e.includes("--skip-rebuild-env"),y={mode:"connect"};return n&&(y.privatecode=n),s&&(y.env=s),d&&(y.handshakeUrl=d),h&&(y.frontierUrl=h),m&&(y.mockScenario=m),S&&(y.skipRebuildEnv=!0),y}var Z1=`
133
133
  coze-bridge - local bridge daemon for cloud Agent Service
134
134
 
135
135
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -210,57 +210,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
210
210
 
211
211
  Internal:
212
212
  <node> <entry> --daemon daemon mode (OS supervisor only)
213
- `.trimStart();async function yp(t=process.argv,e={}){let r=K1(t);switch(r.mode){case"help":return process.stdout.write(Z1),0;case"version":return process.stdout.write(`${Dt}
214
- `),0;case"daemon":{try{await $x()}catch(i){return _p.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return Y1(e);case"stop":return bp(e);case"reload":return Q1(r.agentId,e);case"log":return dp(r,e);case"update":return J1(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 lp({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 Ep(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 Y1(t){let e=t.paths??ee(),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 Ep(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
216
- `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
217
- ${JSON.stringify(o.body,null,2)}
218
- `),0}async function bp(t){let e=t.paths??ee(),r=new Qt(e),i=t.daemonSweep??(async()=>{let f=w0();return await _0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await os(t),l=!1;if(c)try{await c.uninstall(),l=!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(l?`coze-bridge: stopped
213
+ `.trimStart();async function Sp(t=process.argv,e={}){let n=$1(t);switch(n.mode){case"help":return process.stdout.write(Z1),0;case"version":return process.stdout.write(`${Ot}
214
+ `),0;case"daemon":{try{await Vx()}catch(i){return vp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return Y1(e);case"stop":return Ap(e);case"reload":return e2(n.agentId,e);case"log":return fp(n,e);case"update":return X1(e);case"purge":return n2(e);case"service-install":return r2(e);case"service-uninstall":return i2(e);case"pair":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),s2(n.privatecode,n.pairingCode,e,i,n.agentId,n.skipRebuildEnv)}case"connect":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),o2(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return hp({kind:n.kind,path:n.path,...n.agentId?{agentId:n.agentId}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.caption?{caption:n.caption}:{},...n.name?{name:n.name}:{},...n.groupFile?{groupFile:!0}:{},...n.mimeType?{mimeType:n.mimeType}:{},json:n.json},e)}}async function Ip(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 Y1(t){let e=t.paths??X(),n=new nn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
215
+ `),1;if(i.kind==="stale")return await Ip(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
216
+ `),1;let s=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
217
+ ${JSON.stringify(s.body,null,2)}
218
+ `),0}async function Ap(t){let e=t.paths??X(),n=new nn(e),i=t.daemonSweep??(async()=>{let h=S0();return await I0(h),h}),s=async()=>{t.skipProcessKill||await i(e)},c=await ls(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
219
+ `)}let u=await n.probe();if(u.kind==="not-running")return await s(),process.stdout.write(d?`coze-bridge: stopped
220
220
  `:`coze-bridge: not running
221
- `),0;if(u.kind==="stale")return await Ep(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
222
- `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
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 J1(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)
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)
221
+ `),0;if(u.kind==="stale")return await Ip(e),await s(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
222
+ `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await s(),process.stdout.write(`coze-bridge: stopped
223
+ `),0}catch(h){return(await n.probe()).kind!=="connected"?(await s(),process.stdout.write(`coze-bridge: stopped
224
+ `),0):(await s(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
225
+ `),1)}}async function X1(t){return await Ap(t),(t.spawnNpx??Q1)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function Q1(t){return new Promise(e=>{let n=st("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
226
+ `),e(1)})})}async function e2(t,e){let n=new nn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
227
+ `),1;try{let s=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(s.status===200&&s.body?.ok){let c=s.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)
228
228
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
229
- `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
230
- `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
231
- `),1}}async function os(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(()=>(mp(),gp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function vp(t,e){let r=await e.probe();if(r.kind==="connected")return r;let i=t.spawnDaemon??Wx,o=t.waitTimeoutMs??15e3,c=t.sleep??oI,l=t.paths??ee(),u=await os(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await wp(e,o,c);if(f.kind==="connected")return f;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(f){It(l.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}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 sI(l.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)}
229
+ `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(s.body)}
230
+ `),1}catch(s){return process.stderr.write(`coze-bridge: reload failed: ${String(s)}
231
+ `),1}}async function ls(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:n}=await Promise.resolve().then(()=>(yp(),_p)),i=e(),s=n();return{platform:i.platform,install:c=>i.install(s,c),uninstall:()=>i.uninstall(s)}}async function Tp(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,s=t.sleep??a2,c=t.paths??X();if(n.kind==="connected"){if(!t2(n.body))return n;ut(c.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:n.body}),await e.request({method:"POST",path:"/shutdown"}).catch(h=>ut(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await Ep(c.pidFile,s)}let d=t.spawnDaemon??Kx,u=await ls(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await bp(e,i,s);if(h.kind==="connected")return h;ut(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(h){ut(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}ut(c.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 Ep(c.pidFile,s)}else u&&await u.install({activate:!1}).catch(h=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(h)}
232
232
  `));return process.stdout.write(`coze-bridge: starting daemon...
233
- `),await i({paths:t.paths}),wp(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(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
235
- `)}await new Promise(l=>setTimeout(l,500))}let i=await os(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
236
- `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
237
- `)}let o=t.paths??ee(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
238
- `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
233
+ `),await d({paths:t.paths}),bp(e,i,s)}function t2(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.nodeExecPath!="string"||typeof e.nodeArch!="string"?!1:e.nodeExecPath!==process.execPath||e.nodeArch!==process.arch}async function n2(t){let e=new nn(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 ls(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)}
237
+ `)}let s=t.paths??X(),{rm:c}=await import("node:fs/promises");try{await c(s.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${s.bridgeRoot}
238
+ `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
239
239
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
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...
240
+ `),0}async function r2(t){let e=await ls(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
241
241
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
242
- `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
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
244
- `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
245
- `),1}}async function Sp(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)
246
- `),It(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 l=new Qt(r.paths),u=r.paths??ee(),f=await Sp(u,c,r.reconstructEnv??qd);if(await td(u,f).catch(m=>It(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!r.skipDistInstall){let m=await Vd({paths:r.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
247
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
248
- `)}let x=await vp(r,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
249
- `),1;let g={privatecode:t,pairing_code:e};i.env&&(g.env=i.env),i.handshakeUrl&&(g.handshake_url=i.handshakeUrl),i.frontierUrl&&(g.frontier_url=i.frontierUrl),i.mockScenario&&(g.mock_scenario=i.mockScenario),o&&(g.agent_id=o);try{let m=await l.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(m.status===200&&m.body?.ok){let S=m.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
242
+ `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
243
+ `),1}}async function i2(t){let e=await ls(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
244
+ `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
245
+ `),1}}async function kp(t,e,n){if(e)return ut(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(ut(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(ut(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
+ `),ut(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function s2(t,e,n,i={},s,c){let d=new nn(n.paths),u=n.paths??X(),h=await kp(u,c,n.reconstructEnv??Kd);if(await sd(u,h).catch(_=>ut(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(_)})),!n.skipDistInstall){let _=await Xd({paths:n.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(y=>setTimeout(y,500)))):_.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${_.libVersion}
248
+ `)}let x=await Tp(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
249
+ `),1;let m={privatecode:t,pairing_code:e};i.env&&(m.env=i.env),i.handshakeUrl&&(m.handshake_url=i.handshakeUrl),i.frontierUrl&&(m.frontier_url=i.frontierUrl),i.mockScenario&&(m.mock_scenario=i.mockScenario),s&&(m.agent_id=s);try{let _=await d.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(_.status===200&&_.body?.ok){let S=_.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
250
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"
251
- `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(m.body)}
252
- `),1}catch(m){return process.stderr.write(`coze-bridge: pair failed: ${String(m)}
253
- `),1}}async function iI(t,e,r={},i){let o=e.paths??ee(),c=t??await Zo(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 Qt(e.paths),u=await Sp(o,i,e.reconstructEnv??qd);if(await td(o,u).catch(g=>It(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await Vd({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
254
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
255
- `)}let f=await vp(e,l);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 g=await l.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return g.status===200&&g.body?.ok?(process.stdout.write(`coze-bridge: connected (${g.body.note??"ok"})
257
- `),t!==void 0&&await ns(c,o).catch(m=>_p.warn("writePatToken after connect failed (ignored)",{err:String(m)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
258
- `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
259
- `),1}}async function wp(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 l;try{l=await o(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!Ui(u))return;await e(i)}}function oI(t){return new Promise(e=>setTimeout(e,t))}ne();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 Ip(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
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
251
+ `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(_.body)}
252
+ `),1}catch(_){return process.stderr.write(`coze-bridge: pair failed: ${String(_)}
253
+ `),1}}async function o2(t,e,n={},i){let s=e.paths??X(),c=t??await Qo(s);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 nn(e.paths),u=await kp(s,i,e.reconstructEnv??Kd);if(await sd(s,u).catch(m=>ut(s.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await Xd({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
254
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
255
+ `)}let h=await Tp(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
256
+ `),1;let x={privatecode:c};n.env&&(x.env=n.env),n.handshakeUrl&&(x.handshake_url=n.handshakeUrl),n.frontierUrl&&(x.frontier_url=n.frontierUrl),n.mockScenario&&(x.mock_scenario=n.mockScenario);try{let m=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
257
+ `),t!==void 0&&await ss(c,s).catch(_=>vp.warn("writePatToken after connect failed (ignored)",{err:String(_)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
258
+ `),1)}catch(m){return process.stderr.write(`coze-bridge: connect failed: ${String(m)}
259
+ `),1}}async function bp(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let s=await t.probe(500);if(s.kind==="connected")return s;await n(200)}return t.probe(500)}async function Ep(t,e,n=60,i=200){let{readFile:s}=await import("node:fs/promises");for(let c=0;c<n;c++){let d;try{d=await s(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Hi(u))return;await e(i)}}function a2(t){return new Promise(e=>setTimeout(e,t))}ee();function c2(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let n=Number(e[1]),i=Number(e[2]??0);return n<18||n===18&&i<4?"fatal":n<20?"warn":"ok"}function Cp(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){let i=c2(t);if(i==="ok")return;let s=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${s} \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
260
+ `),n(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${s},\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
261
261
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
262
262
  npx -y coze-bridge@latest stop
263
263
  npx -y coze-bridge@latest connect
264
264
 
265
- `)}Ip();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&yl("warn");yp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
265
+ `)}Cp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Sl("warn");Sp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
266
266
  `),process.exit(1)});