coze-bridge 0.2.1-alpha.2 → 0.2.1-beta.2

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 +98 -99
  2. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var bg=Object.create;var Ta=Object.defineProperty;var vg=Object.getOwnPropertyDescriptor;var Sg=Object.getOwnPropertyNames;var Ig=Object.getPrototypeOf,Ag=Object.prototype.hasOwnProperty;var xe=(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 nt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ca=(t,e)=>{for(var r in e)Ta(t,r,{get:e[r],enumerable:!0})},kg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Sg(e))!Ag.call(t,o)&&o!==r&&Ta(t,o,{get:()=>e[o],enumerable:!(i=vg(e,o))||i.enumerable});return t};var Ht=(t,e,r)=>(r=t!=null?bg(Ig(t)):{},kg(e||!t||!t.__esModule?Ta(r,"default",{value:t,enumerable:!0}):r,t));function Je(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var cr=nt(()=>{"use strict"});import{createWriteStream as Tg,mkdirSync as Cg,readdirSync as Rg,unlinkSync as Dg}from"node:fs";import{join as vl}from"node:path";function Ln(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function dr(t,e){return`${t}-${e}.log`}function Ra(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function Pg(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 us(t,e,r,i){let o;try{o=Rg(t)}catch{return}for(let c of o){let l=Ra(c,e);if(l&&Pg(l,r,i))try{Dg(vl(t,c))}catch{}}}var ni,Da=nt(()=>{"use strict";ni=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Ln(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{Cg(this.dir,{recursive:!0});let r=Tg(vl(this.dir,dr(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&&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 Og,mkdirSync as Lg}from"node:fs";import{join as Ng}from"node:path";function Il(t){let e=t.retentionDays??Fg,r=t.clock??(()=>Ln(new Date));hs={bridgeSink:new ni(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ni(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();us(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])us(t.agentLogsDir(o),"agent",i,e)}function zg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Al(t){Pa=t}function kl(t){return lr[Pa]<=lr[t]}function Tl(t,e){let r=lr[t];return r===void 0?!0:r>=lr[e]}function xs(t){Sl={...t}}function Cl(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`${Ln(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${l}`}function kt(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Cl(new Date),level:e,module:r,msg:i,...o})}
11
- `;Lg(t,{recursive:!0}),Og(Ng(t,dr("bridge",Ln(new Date))),c)}catch{}}function Ug(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function fs(t,e,r,i,o){if(lr[t]<lr[Pa])return;let c=`${JSON.stringify({ts:Cl(new Date),level:t,module:e,msg:r,...Sl,...i})}
12
- `;if(hs){let l=Ug(o,i),u=l?zg(hs,l):hs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Bg.write(c):Mg.write(c)}function H(t,e){return{debug:(r,i)=>fs("debug",t,r,i,e),info:(r,i)=>fs("info",t,r,i,e),warn:(r,i)=>fs("warn",t,r,i,e),error:(r,i)=>fs("error",t,r,i,e),child:r=>H(`${t}.${r}`,e),forAgent:r=>H(t,r)}}var lr,Pa,Mg,Bg,Sl,Fg,hs,ne=nt(()=>{"use strict";cr();Da();lr={debug:10,info:20,warn:30,error:40},Pa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Mg=process.stdout,Bg=process.stderr,Sl={},Fg=Je("COZE_BRIDGE_LOG_RETENTION_DAYS",30),hs=null});var k,We=nt(()=>{"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 Ol={};Ca(Ol,{ACP_WRAPPER_NPM_PACKAGES:()=>ri,_resetAcpInstallerForTests:()=>Wg,_setBinaryPathCacheForTests:()=>$g,buildAcpSpawn:()=>ii,ensureAcpInstalled:()=>fr,getAcpBinaryPath:()=>gs,pickWhichLine:()=>Na,probeAcpVersion:()=>Kg,resolveAcpCommand:()=>Pl});import{readFileSync as Rl}from"node:fs";import{createRequire as Hg}from"node:module";import{dirname as Gg,resolve as qg}from"node:path";function La(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Na(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 jg(t){let e=Dl.resolve(`${t.npmPackage}/package.json`),r=Gg(e),i=JSON.parse(Rl(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 qg(r,o)}async function fr(t,e){let r=Oa[t];if(!r)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ur.get(t);if(i)return i;let o=La(t);if(o)return ur.set(t,o),ps.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let c=jg(r);return ur.set(t,c),ps.info("acp wrapper resolved",{framework:t,binary:r.binary,path:c}),c}catch(c){throw ps.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(c)}),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:c})}}async function Kg(t){let e=Oa[t];if(e)try{let r=Dl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Rl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){ps.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function gs(t){return ur.get(t)}function Pl(t,e){if(e)return e;let r=La(t);if(r)return r;let i=gs(t);if(!i)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function ii(t,e,r){if(e)return{command:e,args:[...r]};let i=La(t);if(i)return{command:i,args:[...r]};let o=Pl(t);return{command:process.execPath,args:[o,...r]}}function Wg(){ur.clear()}function $g(t,e){ur.set(t,e)}var ps,Oa,ri,Dl,ur,on=nt(()=>{"use strict";We();ne();ps=H("agents.acp-installer"),Oa={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},ri=Object.values(Oa).filter(t=>t!==void 0).map(t=>t.npmPackage),Dl=Hg(import.meta.url),ur=new Map});import{chmod as Jg,mkdir as Zg,readFile as Yg,rename as Xg,rm as Qg,writeFile as em}from"node:fs/promises";import{dirname as tm}from"node:path";async function an(t){try{let e=await Yg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function cn(t,e,r){await Zg(tm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await em(i,e,{encoding:"utf8",mode:r?.mode}),await Xg(i,t),r?.mode!==void 0&&await Jg(t,r.mode)}catch(o){throw await Qg(i,{force:!0}).catch(()=>{}),o}}async function dn(t,e,r){await cn(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var ln=nt(()=>{"use strict"});import{promises as Ml,readdirSync as nm}from"node:fs";import{homedir as rm}from"node:os";import{sep as im,join as Ce,resolve as Bl}from"node:path";function Y(t){let e=t??rm(),r=Ce(e,".coze"),i=Ce(r,"bridge"),o=Ce(i,"lib"),c=Ce(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Ce(o,"index.js"),binDir:Ce(i,"bin"),pidFile:Ce(i,"bridge.pid"),portFile:Ce(i,"bridge.port"),tokenFile:Ce(i,"bridge.token"),patTokenFile:Ce(i,"pat-token"),agentEnvFile:Ce(i,"agent-env.json"),logFile:Ce(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Ce(c,"daemon-stdio.log"),installLock:Ce(i,"install.lock"),configFile:Ce(i,"config.json"),agentsRoot:Ce(r,"agents")}}function Ze(t,e=Y()){let r=Ce(e.agentsRoot,t);return{root:r,config:Ce(r,"config.json"),workspace:Ce(r,"workspace"),logs:Ce(r,"logs")}}function ms(t=Y()){try{return nm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function si(t,e){let r=await Ml.realpath(Bl(t)).catch(()=>null);if(!r)return!1;let i=await Ml.realpath(Bl(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+im)}var Re=nt(()=>{"use strict"});var _s={};Ca(_s,{AGENT_CONFIG_FILE_MODE:()=>ws,enforceAgentConfigMode:()=>am,loadAgentConfig:()=>De,persistAgentSessions:()=>oi,persistAgentSkills:()=>ai,saveAgentConfig:()=>ze});import{chmod as sm,stat as om}from"node:fs/promises";function De(t,e){return an(Ze(t,e).config)}function ze(t,e){return dn(Ze(t.agentId,e).config,t,{mode:ws})}async function am(t,e){if(process.platform==="win32")return;let r=Ze(t,e).config;try{let i=await om(r);if(!i.isFile())return;let o=i.mode&511;o!==ws&&(await sm(r,ws),Fl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Fl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function oi(t,e,r){let i=await De(t,r);i&&(i.sessions=Object.fromEntries(e),await ze(i,r))}async function ai(t,e,r){let i=await De(t,r);i&&(i.skills=e,await ze(i,r))}var Fl,ws,un=nt(()=>{"use strict";ln();ne();Re();Fl=H("agent-config"),ws=384});var Fa=ce((c2,Hl)=>{Hl.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 Es=ce(ql=>{var Gl={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 hm(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(Gl))ql[t]=hm(Gl[t])});var Vl=ce((l2,$l)=>{var xm=xe("fs"),Me=xe("path"),jl=Fa(),pm=Es(),gm=typeof process=="object"&&process.platform==="win32",Kl=t=>typeof t=="object"&&t!==null,Wl=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 Ie(t){this.sep=Me.sep,this.fs=xm,Kl(t)&&Kl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}$l.exports=Ie;Ie.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 pm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Ie.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=Me.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};Ie.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=Me.dirname(t);c.fs.exists(x,function(g){g||c.makeDir(x),c.fs.open(t,"w",438,function(y,S){y?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,v){c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):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)})})})})})};Ie.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=Me.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&l.push(Me.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(l=l.concat(r(f,o,c)))}),l}return r(t,void 0,!0)};Ie.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=Me.join(t,u),r.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Me.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(g,y){if(g)return e(g);i=i.concat(y),--l||e(null,i)}):--l||e(null,i))})})})};Ie.prototype.getAttributes=function(){};Ie.prototype.setAttributes=function(){};Ie.crc32update=function(t,e){return Wl[(t^e)&255]^t>>>8};Ie.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Ie.crc32update(r,t[i++]);return~r>>>0};Ie.methodToString=function(t){switch(t){case jl.STORED:return"STORED ("+t+")";case jl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ie.canonical=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.join(".",e)};Ie.zipnamefix=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.posix.join(".",e)};Ie.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]};Ie.sanitize=function(t,e){t=Me.resolve(Me.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Me.normalize(Me.join(t,r.slice(i,o).join(Me.sep)));if(c.indexOf(t)===0)return c}return Me.normalize(Me.join(t,Me.basename(e)))};Ie.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Ie.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Ie.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)};Ie.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};Ie.isWin=gm;Ie.crcTable=Wl});var Zl=ce((u2,Jl)=>{var mm=xe("path");Jl.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=mm.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 Xl=ce((f2,Yl)=>{Yl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=ce((h2,xr)=>{xr.exports=Vl();xr.exports.Constants=Fa();xr.exports.Errors=Es();xr.exports.FileAttr=Zl();xr.exports.decoder=Xl()});var eu=ce((x2,Ql)=>{var fn=pr(),z=fn.Constants;Ql.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,y=0,S=0,_=0,v=0;t|=fn.isWin?2560:768,r|=z.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,D=E=>Math.max(0,E)&255;return o=fn.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return r},set flags(E){r=E},get flags_efs(){return(r&z.FLG_EFS)>0},set flags_efs(E){E?r|=z.FLG_EFS:r&=~z.FLG_EFS},get flags_desc(){return(r&z.FLG_DESC)>0},set flags_desc(E){E?r|=z.FLG_DESC:r&=~z.FLG_DESC},get method(){return i},set method(E){switch(E){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=E},get time(){return fn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=fn.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=A(E)},get timeHighByte(){return D(o>>>8)},get crc(){return c},set crc(E){c=A(E)},get compressedSize(){return l},set compressedSize(E){l=A(E)},get size(){return u},set size(E){u=A(E)},get fileNameLength(){return f},set fileNameLength(E){f=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return g},set commentLength(E){g=E},get diskNumStart(){return y},set diskNumStart(E){y=A(E)},get inAttr(){return S},set inAttr(E){S=A(E)},get attr(){return _},set attr(E){_=A(E)},get fileAttr(){return(_||0)>>16&4095},get offset(){return v},set offset(E){v=A(E)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+f+x+g},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var C=E.slice(v,v+z.LOCHDR);if(C.readUInt32LE(0)!==z.LOCSIG)throw fn.Errors.INVALID_LOC();I.version=C.readUInt16LE(z.LOCVER),I.flags=C.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=C.readUInt16LE(z.LOCHOW),I.time=C.readUInt32LE(z.LOCTIM),I.crc=C.readUInt32LE(z.LOCCRC),I.compressedSize=C.readUInt32LE(z.LOCSIZ),I.size=C.readUInt32LE(z.LOCLEN),I.fnameLen=C.readUInt16LE(z.LOCNAM),I.extraLen=C.readUInt16LE(z.LOCEXT);let O=v+z.LOCHDR+I.fnameLen,F=O+I.extraLen;return E.slice(O,F)},loadFromBinary:function(E){if(E.length!==z.CENHDR||E.readUInt32LE(0)!==z.CENSIG)throw fn.Errors.INVALID_CEN();t=E.readUInt16LE(z.CENVEM),e=E.readUInt16LE(z.CENVER),r=E.readUInt16LE(z.CENFLG),i=E.readUInt16LE(z.CENHOW),o=E.readUInt32LE(z.CENTIM),c=E.readUInt32LE(z.CENCRC),l=E.readUInt32LE(z.CENSIZ),u=E.readUInt32LE(z.CENLEN),f=E.readUInt16LE(z.CENNAM),x=E.readUInt16LE(z.CENEXT),g=E.readUInt16LE(z.CENCOM),y=E.readUInt16LE(z.CENDSK),S=E.readUInt16LE(z.CENATT),_=E.readUInt32LE(z.CENATX),v=E.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(z.LOCHDR);return E.writeUInt32LE(z.LOCSIG,0),E.writeUInt16LE(e,z.LOCVER),E.writeUInt16LE(r,z.LOCFLG),E.writeUInt16LE(i,z.LOCHOW),E.writeUInt32LE(o,z.LOCTIM),E.writeUInt32LE(c,z.LOCCRC),E.writeUInt32LE(l,z.LOCSIZ),E.writeUInt32LE(u,z.LOCLEN),E.writeUInt16LE(f,z.LOCNAM),E.writeUInt16LE(I.extraLen,z.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(z.CENHDR+f+x+g);return E.writeUInt32LE(z.CENSIG,0),E.writeUInt16LE(t,z.CENVEM),E.writeUInt16LE(e,z.CENVER),E.writeUInt16LE(r,z.CENFLG),E.writeUInt16LE(i,z.CENHOW),E.writeUInt32LE(o,z.CENTIM),E.writeUInt32LE(c,z.CENCRC),E.writeUInt32LE(l,z.CENSIZ),E.writeUInt32LE(u,z.CENLEN),E.writeUInt16LE(f,z.CENNAM),E.writeUInt16LE(x,z.CENEXT),E.writeUInt16LE(g,z.CENCOM),E.writeUInt16LE(y,z.CENDSK),E.writeUInt16LE(S,z.CENATT),E.writeUInt32LE(_,z.CENATX),E.writeUInt32LE(v,z.CENOFF),E},toJSON:function(){let E=function(C){return C+" bytes"};return{made:t,version:e,flags:r,method:fn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:E(l),size:E(u),fileNameLength:E(f),extraLength:E(x),commentLength:E(g),diskNumStart:y,inAttr:S,attr:_,offset:v,centralHeaderSize:E(z.CENHDR+f+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var nu=ce((p2,tu)=>{var gr=pr(),be=gr.Constants;tu.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 be.ENDHDR+o},loadFromBinary:function(c){if((c.length!==be.ENDHDR||c.readUInt32LE(0)!==be.ENDSIG)&&(c.length<be.ZIP64HDR||c.readUInt32LE(0)!==be.ZIP64SIG))throw gr.Errors.INVALID_END();c.readUInt32LE(0)===be.ENDSIG?(t=c.readUInt16LE(be.ENDSUB),e=c.readUInt16LE(be.ENDTOT),r=c.readUInt32LE(be.ENDSIZ),i=c.readUInt32LE(be.ENDOFF),o=c.readUInt16LE(be.ENDCOM)):(t=gr.readBigUInt64LE(c,be.ZIP64SUB),e=gr.readBigUInt64LE(c,be.ZIP64TOT),r=gr.readBigUInt64LE(c,be.ZIP64SIZE),i=gr.readBigUInt64LE(c,be.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(be.ENDHDR+o);return c.writeUInt32LE(be.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,be.ENDSUB),c.writeUInt16LE(e,be.ENDTOT),c.writeUInt32LE(r,be.ENDSIZ),c.writeUInt32LE(i,be.ENDOFF),c.writeUInt16LE(o,be.ENDCOM),c.fill(" ",be.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 Ua=ce(za=>{za.EntryHeader=eu();za.MainHeader=nu()});var iu=ce((m2,ru)=>{ru.exports=function(t){var e=xe("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 ou=ce((w2,su)=>{var wm=+(process.versions?process.versions.node:"").split(".")[0]||0;su.exports=function(t,e){var r=xe("zlib");let i=wm>=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 y=l[g];y.copy(f,x),x+=y.length}o&&o(f)}),c.end(t)}}}});var uu=ce((_2,lu)=>{"use strict";var{randomFillSync:au}=xe("crypto"),_m=Es(),ym=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}),du=(t,e)=>Math.imul(t,e)>>>0,cu=(t,e)=>ym[(t^e)&255]^t>>>8,ci=()=>typeof au=="function"?au(Buffer.alloc(12)):ci.node();ci.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 bs={genSalt:ci};function vs(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])}vs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=cu(e[0],t),e[1]+=e[0]&255,e[1]=du(e[1],134775813)+1,e[2]=cu(e[2],e[1]>>>24),t};vs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return du(t,t^1)>>8&255};function Em(t){let e=new vs(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 bm(t){let e=new vs(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 vm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Em(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw _m.WRONG_PASSWORD();return i(t.slice(12))}function Sm(t){Buffer.isBuffer(t)&&t.length>=12?bs.genSalt=function(){return t.slice(0,12)}:t==="node"?bs.genSalt=ci.node:bs.genSalt=ci}function Im(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=bm(r),c=bs.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)}lu.exports={decrypt:vm,encrypt:Im,_salter:Sm}});var fu=ce(Ss=>{Ss.Deflater=iu();Ss.Inflater=ou();Ss.ZipCrypto=uu()});var Ga=ce((E2,hu)=>{var de=pr(),Am=Ua(),Ae=de.Constants,Ha=fu();hu.exports=function(t,e){var r=new Am.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,y=typeof g.decoder=="object"?g.decoder:de.decoder;x=y.hasOwnProperty("efs")?y.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 _(E){if(!r.flags_desc&&!r.localHeader.flags_desc){if(de.crc32(E)!==r.localHeader.crc)return!1}else{let C={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==Ae.LOCSIG||e.readUInt32LE(O)==Ae.CENSIG)throw de.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Ae.EXTSIG)C.crc=e.readUInt32LE(O+Ae.EXTCRC),C.compressedSize=e.readUInt32LE(O+Ae.EXTSIZ),C.size=e.readUInt32LE(O+Ae.EXTLEN);else if(e.readUInt16LE(O+12)===19280)C.crc=e.readUInt32LE(O+Ae.EXTCRC-4),C.compressedSize=e.readUInt32LE(O+Ae.EXTSIZ-4),C.size=e.readUInt32LE(O+Ae.EXTLEN-4);else throw de.Errors.DESCRIPTOR_UNKNOWN();if(C.compressedSize!==r.compressedSize||C.size!==r.size||C.crc!==r.crc)throw de.Errors.DESCRIPTOR_FAULTY();if(de.crc32(E)!==C.crc)return!1}return!0}function v(E,C,O){if(typeof C>"u"&&typeof E=="string"&&(O=E,E=void 0),c)return E&&C&&C(Buffer.alloc(0),de.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return E&&C&&C(F),F;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw de.Errors.INVALID_PASS_PARAM();F=Ha.ZipCrypto.decrypt(F,r,O)}var B=Buffer.alloc(r.size);switch(r.method){case de.Constants.STORED:if(F.copy(B),_(B))return E&&C&&C(B),B;throw E&&C&&C(B,de.Errors.BAD_CRC()),de.Errors.BAD_CRC();case de.Constants.DEFLATED:var V=new Ha.Inflater(F,r.size);if(E)V.inflateAsync(function($){$.copy($,0),C&&(_($)?C($):C($,de.Errors.BAD_CRC()))});else{if(V.inflate(B).copy(B,0),!_(B))throw de.Errors.BAD_CRC(`"${y.decode(i)}"`);return B}break;default:throw E&&C&&C(Buffer.alloc(0),de.Errors.UNKNOWN_METHOD()),de.Errors.UNKNOWN_METHOD()}}function I(E,C){if((!l||!l.length)&&Buffer.isBuffer(e))return E&&C&&C(S()),S();if(l.length&&!c){var O;switch(r.method){case de.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(l.length),l.copy(O),E&&C&&C(O),O;default:case de.Constants.DEFLATED:var F=new Ha.Deflater(l);if(E)F.deflateAsync(function(V){O=Buffer.alloc(V.length),r.compressedSize=V.length,V.copy(O),C&&C(O)});else{var B=F.deflate();return r.compressedSize=B.length,B}F=null;break}}else if(E&&C)C(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,C){return de.readBigUInt64LE(E,C)}function T(E){try{for(var C=0,O,F,B;C+4<E.length;)O=E.readUInt16LE(C),C+=2,F=E.readUInt16LE(C),C+=2,B=E.slice(C,C+F),C+=F,Ae.ID_ZIP64===O&&D(B)}catch{throw de.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(E){var C,O,F,B;E.length>=Ae.EF_ZIP64_SCOMP&&(C=A(E,Ae.EF_ZIP64_SUNCOMP),r.size===Ae.EF_ZIP64_OR_32&&(r.size=C)),E.length>=Ae.EF_ZIP64_RHO&&(O=A(E,Ae.EF_ZIP64_SCOMP),r.compressedSize===Ae.EF_ZIP64_OR_32&&(r.compressedSize=O)),E.length>=Ae.EF_ZIP64_DSN&&(F=A(E,Ae.EF_ZIP64_RHO),r.offset===Ae.EF_ZIP64_OR_32&&(r.offset=F)),E.length>=Ae.EF_ZIP64_DSN+4&&(B=E.readUInt32LE(Ae.EF_ZIP64_DSN),r.diskNumStart===Ae.EF_ZIP64_OR_16&&(r.diskNumStart=B))}return{get entryName(){return y.decode(i)},get rawEntryName(){return i},set entryName(E){i=de.toBuffer(E,y.encode);var C=i[i.length-1];c=C===47||C===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,r.extraLength=E.length,T(E)},get comment(){return y.decode(o)},set comment(E){if(o=de.toBuffer(E,y.encode),r.commentLength=o.length,o.length>65535)throw de.Errors.COMMENT_TOO_LONG()},get name(){var E=y.decode(i);return c?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){l=de.toBuffer(E,de.decoder.encode),!c&&l.length?(r.size=l.length,r.method=de.Constants.DEFLATED,r.crc=de.crc32(E),r.changed=!0):r.method=de.Constants.STORED},getData:function(E){return r.changed?l:v(!1,null,E)},getDataAsync:function(E,C){r.changed?E(l):v(!0,E,C)},set attr(E){r.attr=E},get attr(){return r.attr},set header(E){r.loadFromBinary(E)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var E=r.centralHeaderToBinary(),C=de.Constants.CENHDR;return i.copy(E,C),C+=i.length,u.copy(E,C),C+=r.extraLength,o.copy(E,C),E},packLocalHeader:function(){let E=0;r.flags_efs=this.efs,r.extraLocalLength=f.length;let C=r.localHeaderToBinary(),O=Buffer.alloc(C.length+i.length+r.extraLocalLength);return C.copy(O,E),E+=C.length,i.copy(O,E),E+=i.length,f.copy(O,E),E+=f.length,O},toJSON:function(){let E=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:E(e),data:E(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var gu=ce((b2,pu)=>{var xu=Ga(),km=Ua(),$e=pr();pu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new km.MainHeader,l=!1,u=null;let f=new Set,x=e,{noSort:g,decoder:y}=x;t?v(x.readEntries):l=!0;function S(){let A=new Set;for(let T of Object.keys(i)){let D=T.split("/");if(D.pop(),!!D.length)for(let E=0;E<D.length;E++){let C=D.slice(0,E+1).join("/")+"/";A.add(C)}}for(let T of A)if(!(T in i)){let D=new xu(x);D.entryName=T,D.attr=16,D.temporary=!0,r.push(D),i[D.entryName]=D,f.add(D)}}function _(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/$e.Constants.CENHDR)throw $e.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,T=0;T<r.length;T++){var D=A,E=new xu(x,t);E.header=t.slice(D,D+=$e.Constants.CENHDR),E.entryName=t.slice(D,D+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(D,D+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(D,D+E.header.commentLength)),A+=E.header.centralHeaderSize,r[T]=E,i[E.entryName]=E}f.clear(),S()}function v(A){var T=t.length-$e.Constants.ENDHDR,D=Math.max(0,T-65535),E=D,C=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(D=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===$e.Constants.ENDSIG){O=T,F=T,C=T+$e.Constants.ENDHDR,E=T-$e.Constants.END64HDR;continue}if(t.readUInt32LE(T)===$e.Constants.END64SIG){E=D;continue}if(t.readUInt32LE(T)===$e.Constants.ZIP64SIG){O=T,C=T+$e.readBigUInt64LE(t,T+$e.Constants.ZIP64SIZE)+$e.Constants.ZIP64LEAD;break}}if(O==-1)throw $e.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,C)),c.commentLength&&(o=t.slice(F+$e.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 y.decode(o)},set comment(A){o=$e.toBuffer(A,y.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 D=i[A];this.getEntryChildren(D,T).map(C=>C.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||_();let T=i[A],D=r.indexOf(T);D>=0&&(r.splice(D,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,T=!0){if(l||_(),typeof A=="object")if(A.isDirectory&&T){let D=[],E=A.entryName;for(let C of r)C.entryName.startsWith(E)&&D.push(C);return D}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){l||_(),I();let A=[],T=[],D=0,E=0;c.size=0,c.offset=0;let C=0;for(let B of this.entries){let V=B.getCompressedData();B.header.offset=E;let $=B.packLocalHeader(),re=$.length+V.length;E+=re,A.push($),A.push(V);let Q=B.packCentralHeader();T.push(Q),c.size+=Q.length,D+=re+Q.length,C++}D+=c.mainHeaderSize,c.offset=E,c.totalEntries=C,E=0;let O=Buffer.alloc(D);for(let B of A)B.copy(O,E),E+=B.length;for(let B of T)B.copy(O,E),E+=B.length;let F=c.toBinary();return o&&o.copy(F,$e.Constants.ENDHDR),F.copy(O,E),t=O,l=!1,O},toAsyncBuffer:function(A,T,D,E){try{l||_(),I();let C=[],O=[],F=0,B=0,V=0;c.size=0,c.offset=0;let $=function(re){if(re.length>0){let Q=re.shift(),se=Q.entryName+Q.extra.toString();D&&D(se),Q.getCompressedDataAsync(function(oe){E&&E(se),Q.header.offset=B;let R=Q.packLocalHeader(),U=R.length+oe.length;B+=U,C.push(R),C.push(oe);let K=Q.packCentralHeader();O.push(K),c.size+=K.length,F+=U+K.length,V++,$(re)})}else{F+=c.mainHeaderSize,c.offset=B,c.totalEntries=V,B=0;let Q=Buffer.alloc(F);C.forEach(function(oe){oe.copy(Q,B),B+=oe.length}),O.forEach(function(oe){oe.copy(Q,B),B+=oe.length});let se=c.toBinary();o&&o.copy(se,$e.Constants.ENDHDR),se.copy(Q,B),t=Q,l=!1,A(Q)}};$(Array.from(this.entries))}catch(C){T(C)}}}}});var _u=ce((v2,wu)=>{var Se=pr(),ve=xe("path"),Tm=Ga(),Cm=gu(),Nn=(...t)=>Se.findLast(t,e=>typeof e=="boolean"),mu=(...t)=>Se.findLast(t,e=>typeof e=="string"),Rm=(...t)=>Se.findLast(t,e=>typeof e=="function"),Dm={noSort:!1,readEntries:!1,method:Se.Constants.NONE,fs:null};wu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Dm);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=Se.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Se(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Se.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Se.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw Se.Errors.INVALID_FILENAME();let c=new Cm(r,i),{canonical:l,sanitize:u,zipnamefix:f}=Se;function x(_){if(_&&c){var v;if(typeof _=="string"&&(v=c.getEntry(ve.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(v=c.getEntry(_.entryName)),v)return v}return null}function g(_){let{join:v,normalize:I,sep:A}=ve.posix;return v(ve.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function y(_){return _ instanceof RegExp?(function(v){return function(I){return v.test(I)}})(_):typeof _!="function"?()=>!0:_}let S=(_,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",ve.relative(_,v)+I};return{readFile:function(_,v){var I=x(_);return I&&I.getData(v)||null},childCount:function(_){let v=x(_);if(v)return c.getChildCount(v)},readFileAsync:function(_,v){var I=x(_);I?I.getDataAsync(v):v(null,"getEntry failed for:"+_)},readAsText:function(_,v){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(_,v,I){var A=x(_);A?A.getDataAsync(function(T,D){if(D){v(T,D);return}T&&T.length?v(T.toString(I||"utf8")):v("")}):v("")},deleteFile:function(_,v=!0){var I=x(_);I&&c.deleteFile(I.entryName,v)},deleteEntry:function(_){var v=x(_);v&&c.deleteEntry(v.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,v){var I=x(_);I&&(I.comment=v)},getZipEntryComment:function(_){var v=x(_);return v&&v.comment||""},updateFile:function(_,v){var I=x(_);I&&I.setData(v)},addLocalFile:function(_,v,I,A){if(o.fs.existsSync(_)){v=v?g(v):"";let T=ve.win32.basename(ve.win32.normalize(_));v+=I||T;let D=o.fs.statSync(_),E=D.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);D.isDirectory()&&(v+=o.sep),this.addFile(v,E,A,D)}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,v){_=typeof _=="object"?_:{localPath:_};let I=ve.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:D}=_,E=this;o.fs.stat(I,function(C,O){if(C)return v(C,!1);T=T?g(T):"";let F=ve.win32.basename(ve.win32.normalize(I));if(T+=D||F,O.isFile())o.fs.readFile(I,function(B,V){return B?v(B,!1):(E.addFile(T,V,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(_,v,I){if(I=y(I),v=v?g(v):"",_=ve.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),T=this;if(A.length)for(let D of A){let E=ve.join(v,S(_,D));I(E)&&T.addLocalFile(D,ve.dirname(E))}}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,v,I,A){A=y(A),I=I?g(I):"",_=ve.normalize(_);var T=this;o.fs.open(_,"r",function(D){if(D&&D.code==="ENOENT")v(void 0,Se.Errors.FILE_NOT_FOUND(_));else if(D)v(void 0,D);else{var E=o.findFiles(_),C=-1,O=function(){if(C+=1,C<E.length){var F=E[C],B=S(_,F).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(B)?o.fs.stat(F,function(V,$){V&&v(void 0,V),$.isFile()?o.fs.readFile(F,function(re,Q){re?v(void 0,re):(T.addFile(I+B,Q,"",$),O())}):(T.addFile(I+B+"/",Buffer.alloc(0),"",$),O())}):process.nextTick(()=>{O()})}else v(!0,void 0)};O()}})},addLocalFolderAsync2:function(_,v){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=ve.resolve(g(_.localPath));let{zipPath:A,filter:T,namefix:D}=_;T instanceof RegExp?T=(function(O){return function(F){return O.test(F)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?g(A):"",D=="latin1"&&(D=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=O=>O);let E=O=>ve.join(A,D(S(localPath,O))),C=O=>ve.win32.basename(ve.win32.normalize(D(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?v(void 0,Se.Errors.FILE_NOT_FOUND(localPath)):O?v(void 0,O):o.findFilesAsync(localPath,function(F,B){if(F)return v(F);B=B.filter(V=>T(E(V))),B.length||v(void 0,!1),setImmediate(B.reverse().reduce(function(V,$){return function(re,Q){if(re||Q===!1)return setImmediate(V,re,!1);I.addLocalFileAsync({localPath:$,zipPath:ve.dirname(E($)),zipName:C($)},V)}},v))})})},addLocalFolderPromise:function(_,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},v),(T,D)=>{T&&A(T),D&&I(this)})})},addFile:function(_,v,I,A){_=f(_);let T=x(_),D=T!=null;D||(T=new Tm(i),T.entryName=_),T.comment=I||"";let E=typeof A=="object"&&A instanceof o.fs.Stats;E&&(T.header.time=A.mtime);var C=T.isDirectory?16:0;let O=T.isDirectory?16384:32768;return E?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=T.isDirectory?493:420,C=(C|O<<16)>>>0,T.attr=C,T.setData(v),D||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(_,v,I,A,T,D){A=Nn(!1,A),T=Nn(!1,T),I=Nn(!0,I),D=mu(T,D);var E=x(_);if(!E)throw Se.Errors.NO_ENTRY();var C=l(E.entryName),O=u(v,D&&!E.isDirectory?D:I?C:ve.basename(C));if(E.isDirectory){var F=c.getEntryChildren(E);return F.forEach(function($){if($.isDirectory)return;var re=$.getData();if(!re)throw Se.Errors.CANT_EXTRACT_FILE();var Q=l($.entryName),se=u(v,I?Q:ve.basename(Q));let oe=T?$.header.fileAttr:void 0;o.writeFileTo(se,re,A,oe)}),!0}var B=E.getData(c.password);if(!B)throw Se.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw Se.Errors.CANT_OVERRIDE();let V=T?_.header.fileAttr:void 0;return o.writeFileTo(O,B,A,V),!0},test:function(_){if(!c)return!1;for(var v in c.entries)try{if(v.isDirectory)continue;var I=c.entries[v].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,v,I,A){if(I=Nn(!1,I),A=mu(I,A),v=Nn(!1,v),!c)throw Se.Errors.NO_ZIP();c.entries.forEach(function(T){var D=u(_,l(T.entryName));if(T.isDirectory){o.makeDir(D);return}var E=T.getData(A);if(!E)throw Se.Errors.CANT_EXTRACT_FILE();let C=I?T.header.fileAttr:void 0;o.writeFileTo(D,E,v,C);try{o.fs.utimesSync(D,T.header.time,T.header.time)}catch{throw Se.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,v,I,A){if(A=Rm(v,I,A),I=Nn(!1,I),v=Nn(!1,v),!A)return new Promise((O,F)=>{this.extractAllToAsync(_,v,I,function(B){B?F(B):O(this)})});if(!c){A(Se.Errors.NO_ZIP());return}_=ve.resolve(_);let T=O=>u(_,ve.normalize(l(O.entryName))),D=(O,F)=>new Error(O+': "'+F+'"'),E=[],C=[];c.entries.forEach(O=>{O.isDirectory?E.push(O):C.push(O)});for(let O of E){let F=T(O),B=I?O.header.fileAttr:void 0;try{o.makeDir(F),B&&o.fs.chmodSync(F,B),o.fs.utimesSync(F,O.header.time,O.header.time)}catch{A(D("Unable to create folder",F))}}C.reverse().reduce(function(O,F){return function(B){if(B)O(B);else{let V=ve.normalize(l(F.entryName)),$=u(_,V);F.getDataAsync(function(re,Q){if(Q)O(Q);else if(!re)O(Se.Errors.CANT_EXTRACT_FILE());else{let se=I?F.header.fileAttr:void 0;o.writeFileToAsync($,re,v,se,function(oe){oe||O(D("Unable to write file",$)),o.fs.utimes($,F.header.time,F.header.time,function(R){R?O(D("Unable to set times",$)):O()})})}})}}},A)()},writeZip:function(_,v){if(arguments.length===1&&typeof _=="function"&&(v=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((T,D)=>{!_&&i.filename&&(_=i.filename),_||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let C=O=>O?T(O):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,E,I,A,C)},D)})},toBufferPromise:function(){return new Promise((_,v)=>{c.toAsyncBuffer(_,v)})},toBuffer:function(_,v,I,A){return typeof _=="function"?(c.toAsyncBuffer(_,v,I,A),null):c.compressToBuffer()}}}});import{execFile as M_,spawn as B_,spawnSync as HA}from"node:child_process";import{promisify as F_}from"node:util";function U_(t){if(process.platform!=="win32")return!1;if(zf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(zf,"").toLowerCase();return z_.has(r)}function Uf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return U_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function it(t,e=[],r={}){return B_(t,e,Uf(t,r))}function Hf(t,e=[],r={}){return H_(t,e,Uf(t,r))}var z_,zf,H_,Vt=nt(()=>{"use strict";z_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),zf=/\.(cmd|bat|ps1)$/i;H_=F_(M_)});var Zt=ce((IR,vh)=>{"use strict";var Eh=["nodebuffer","arraybuffer","fragments"],bh=typeof Blob<"u";bh&&Eh.push("blob");vh.exports={BINARY_TYPES:Eh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Yi=ce((AR,Oo)=>{"use strict";var{EMPTY_BUFFER:Ob}=Zt(),_d=Buffer[Symbol.species];function Lb(t,e){if(t.length===0)return Ob;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 _d(r.buffer,r.byteOffset,i):r}function Sh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Ih(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Nb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function yd(t){if(yd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new _d(t):ArrayBuffer.isView(t)?e=new _d(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),yd.readOnly=!1),e}Oo.exports={concat:Lb,mask:Sh,toArrayBuffer:Nb,toBuffer:yd,unmask:Ih};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");Oo.exports.mask=function(e,r,i,o,c){c<48?Sh(e,r,i,o,c):t.mask(e,r,i,o,c)},Oo.exports.unmask=function(e,r){e.length<32?Ih(e,r):t.unmask(e,r)}}catch{}});var Th=ce((kR,kh)=>{"use strict";var Ah=Symbol("kDone"),Ed=Symbol("kRun"),bd=class{constructor(e){this[Ah]=()=>{this.pending--,this[Ed]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ed]()}[Ed](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ah])}}};kh.exports=bd});var Gr=ce((TR,Ph)=>{"use strict";var Xi=xe("zlib"),Ch=Yi(),Mb=Th(),{kStatusCode:Rh}=Zt(),Bb=Buffer[Symbol.species],Fb=Buffer.from([0,0,255,255]),No=Symbol("permessage-deflate"),Yt=Symbol("total-length"),Ur=Symbol("callback"),Rn=Symbol("buffers"),Hr=Symbol("error"),Lo,vd=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,!Lo){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Lo=new Mb(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[Ur];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){Lo.add(o=>{this._decompress(e,r,(c,l)=>{o(),i(c,l)})})}compress(e,r,i){Lo.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"?Xi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Xi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[No]=this,this._inflate[Yt]=0,this._inflate[Rn]=[],this._inflate.on("error",Ub),this._inflate.on("data",Dh)}this._inflate[Ur]=i,this._inflate.write(e),r&&this._inflate.write(Fb),this._inflate.flush(()=>{let c=this._inflate[Hr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=Ch.concat(this._inflate[Rn],this._inflate[Yt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Yt]=0,this._inflate[Rn]=[],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"?Xi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Xi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[Yt]=0,this._deflate[Rn]=[],this._deflate.on("data",zb)}this._deflate[Ur]=i,this._deflate.write(e),this._deflate.flush(Xi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Ch.concat(this._deflate[Rn],this._deflate[Yt]);r&&(c=new Bb(c.buffer,c.byteOffset,c.length-4)),this._deflate[Ur]=null,this._deflate[Yt]=0,this._deflate[Rn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Ph.exports=vd;function zb(t){this[Rn].push(t),this[Yt]+=t.length}function Dh(t){if(this[Yt]+=t.length,this[No]._maxPayload<1||this[Yt]<=this[No]._maxPayload){this[Rn].push(t);return}this[Hr]=new RangeError("Max payload size exceeded"),this[Hr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Hr][Rh]=1009,this.removeListener("data",Dh),this.reset()}function Ub(t){if(this[No]._inflate=null,this[Hr]){this[Ur](this[Hr]);return}t[Rh]=1007,this[Ur](t)}});var qr=ce((CR,Mo)=>{"use strict";var{isUtf8:Oh}=xe("buffer"),{hasBlob:Hb}=Zt(),Gb=[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 qb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Sd(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 jb(t){return Hb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Mo.exports={isBlob:jb,isValidStatusCode:qb,isValidUTF8:Sd,tokenChars:Gb};if(Oh)Mo.exports.isValidUTF8=function(t){return t.length<24?Sd(t):Oh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");Mo.exports.isValidUTF8=function(e){return e.length<32?Sd(e):t(e)}}catch{}});var Cd=ce((RR,Uh)=>{"use strict";var{Writable:Kb}=xe("stream"),Lh=Gr(),{BINARY_TYPES:Wb,EMPTY_BUFFER:Nh,kStatusCode:$b,kWebSocket:Vb}=Zt(),{concat:Id,toArrayBuffer:Jb,unmask:Zb}=Yi(),{isValidStatusCode:Yb,isValidUTF8:Mh}=qr(),Bo=Buffer[Symbol.species],ht=0,Bh=1,Fh=2,zh=3,Ad=4,kd=5,Fo=6,Td=class extends Kb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Wb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Vb]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ht}_write(e,r,i){if(this._opcode===8&&this._state==ht)return i();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 Bo(i.buffer,i.byteOffset+e,i.length-e),new Bo(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 Bo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case ht:this.getInfo(e);break;case Bh:this.getPayloadLength16(e);break;case Fh:this.getPayloadLength64(e);break;case zh:this.getMask();break;case Ad:this.getData(e);break;case kd:case Fo: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[Lh.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=Bh:this._payloadLength===127?this._state=Fh: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=zh:this._state=Ad}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ad}getData(e){let r=Nh;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&&Zb(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=kd,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Lh.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}this._fragments.push(c)}this.dataMessage(r),this._state===ht&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=ht;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Id(i,r):this._binaryType==="arraybuffer"?o=Jb(Id(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=ht):(this._state=Fo,setImmediate(()=>{this.emit("message",o,!0),this._state=ht,this.startLoop(e)}))}else{let o=Id(i,r);if(!this._skipUTF8Validation&&!Mh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===kd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=ht):(this._state=Fo,setImmediate(()=>{this.emit("message",o,!1),this._state=ht,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Nh),this.end();else{let i=e.readUInt16BE(0);if(!Yb(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Bo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Mh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=ht;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ht):(this._state=Fo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ht,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let l=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(l,this.createError),l.code=c,l[$b]=o,l}};Uh.exports=Td});var Pd=ce((PR,qh)=>{"use strict";var{Duplex:DR}=xe("stream"),{randomFillSync:Xb}=xe("crypto"),Hh=Gr(),{EMPTY_BUFFER:Qb,kWebSocket:ev,NOOP:tv}=Zt(),{isBlob:jr,isValidStatusCode:nv}=qr(),{mask:Gh,toBuffer:Xn}=Yi(),xt=Symbol("kByteLength"),rv=Buffer.alloc(4),zo=8*1024,Qn,Kr=zo,St=0,iv=1,sv=2,Rd=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=St,this.onerror=tv,this[ev]=void 0}static frame(e,r){let i,o=!1,c=2,l=!1;r.mask&&(i=r.maskBuffer||rv,r.generateMask?r.generateMask(i):(Kr===zo&&(Qn===void 0&&(Qn=Buffer.alloc(zo)),Xb(Qn,0,zo),Kr=0),i[0]=Qn[Kr++],i[1]=Qn[Kr++],i[2]=Qn[Kr++],i[3]=Qn[Kr++]),l=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||l)&&r[xt]!==void 0?u=r[xt]:(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?(Gh(e,i,x,c,u),[x]):(Gh(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=Qb;else{if(typeof e!="number"||!nv(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");c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof r=="string"?c.write(r,2):c.set(r,2)}}let l={[xt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==St?this.enqueue([this.dispatch,c,!1,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):jr(e)?(o=e.size,c=!1):(e=Xn(e),o=e.length,c=Xn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[xt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};jr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==St?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):jr(e)?(o=e.size,c=!1):(e=Xn(e),o=e.length,c=Xn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[xt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};jr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==St?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,r,i){let o=this._extensions[Hh.extensionName],c=r.binary?2:1,l=r.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):jr(e)?(u=e.size,f=!1):(e=Xn(e),u=e.length,f=Xn.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={[xt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:f,rsv1:l};jr(e)?this._state!==St?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==St?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[xt],this._state=sv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Dd,this,u,o);return}this._bufferedBytes-=i[xt];let l=Xn(c);r?this.dispatch(l,r,i,o):(this._state=St,this.sendFrame(t.frame(l,i),o),this.dequeue())}).catch(c=>{process.nextTick(ov,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[Hh.extensionName];this._bufferedBytes+=i[xt],this._state=iv,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Dd(this,f,o);return}this._bufferedBytes-=i[xt],this._state=St,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===St&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][xt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][xt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};qh.exports=Rd;function Dd(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 ov(t,e,r){Dd(t,e,r),t.onerror(e)}});var Xh=ce((OR,Yh)=>{"use strict";var{kForOnEventAttribute:Qi,kListener:Od}=Zt(),jh=Symbol("kCode"),Kh=Symbol("kData"),Wh=Symbol("kError"),$h=Symbol("kMessage"),Vh=Symbol("kReason"),Wr=Symbol("kTarget"),Jh=Symbol("kType"),Zh=Symbol("kWasClean"),Xt=class{constructor(e){this[Wr]=null,this[Jh]=e}get target(){return this[Wr]}get type(){return this[Jh]}};Object.defineProperty(Xt.prototype,"target",{enumerable:!0});Object.defineProperty(Xt.prototype,"type",{enumerable:!0});var er=class extends Xt{constructor(e,r={}){super(e),this[jh]=r.code===void 0?0:r.code,this[Vh]=r.reason===void 0?"":r.reason,this[Zh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[jh]}get reason(){return this[Vh]}get wasClean(){return this[Zh]}};Object.defineProperty(er.prototype,"code",{enumerable:!0});Object.defineProperty(er.prototype,"reason",{enumerable:!0});Object.defineProperty(er.prototype,"wasClean",{enumerable:!0});var $r=class extends Xt{constructor(e,r={}){super(e),this[Wh]=r.error===void 0?null:r.error,this[$h]=r.message===void 0?"":r.message}get error(){return this[Wh]}get message(){return this[$h]}};Object.defineProperty($r.prototype,"error",{enumerable:!0});Object.defineProperty($r.prototype,"message",{enumerable:!0});var es=class extends Xt{constructor(e,r={}){super(e),this[Kh]=r.data===void 0?null:r.data}get data(){return this[Kh]}};Object.defineProperty(es.prototype,"data",{enumerable:!0});var av={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Qi]&&o[Od]===e&&!o[Qi])return;let i;if(t==="message")i=function(c,l){let u=new es("message",{data:l?c:c.toString()});u[Wr]=this,Uo(e,this,u)};else if(t==="close")i=function(c,l){let u=new er("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Wr]=this,Uo(e,this,u)};else if(t==="error")i=function(c){let l=new $r("error",{error:c,message:c.message});l[Wr]=this,Uo(e,this,l)};else if(t==="open")i=function(){let c=new Xt("open");c[Wr]=this,Uo(e,this,c)};else return;i[Qi]=!!r[Qi],i[Od]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Od]===e&&!r[Qi]){this.removeListener(t,r);break}}};Yh.exports={CloseEvent:er,ErrorEvent:$r,Event:Xt,EventTarget:av,MessageEvent:es};function Uo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Ho=ce((LR,Qh)=>{"use strict";var{tokenChars:ts}=qr();function Bt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function cv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,l,u,f=-1,x=-1,g=-1,y=0;for(;y<t.length;y++)if(x=t.charCodeAt(y),l===void 0)if(g===-1&&ts[x]===1)f===-1&&(f=y);else if(y!==0&&(x===32||x===9))g===-1&&f!==-1&&(g=y);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${y}`);g===-1&&(g=y);let _=t.slice(f,g);x===44?(Bt(e,_,r),r=Object.create(null)):l=_,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${y}`);else if(u===void 0)if(g===-1&&ts[x]===1)f===-1&&(f=y);else if(x===32||x===9)g===-1&&f!==-1&&(g=y);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${y}`);g===-1&&(g=y),Bt(r,t.slice(f,g),!0),x===44&&(Bt(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,y),f=g=-1;else throw new SyntaxError(`Unexpected character at index ${y}`);else if(o){if(ts[x]!==1)throw new SyntaxError(`Unexpected character at index ${y}`);f===-1?f=y:i||(i=!0),o=!1}else if(c)if(ts[x]===1)f===-1&&(f=y);else if(x===34&&f!==-1)c=!1,g=y;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${y}`);else if(x===34&&t.charCodeAt(y-1)===61)c=!0;else if(g===-1&&ts[x]===1)f===-1&&(f=y);else if(f!==-1&&(x===32||x===9))g===-1&&(g=y);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${y}`);g===-1&&(g=y);let _=t.slice(f,g);i&&(_=_.replace(/\\/g,""),i=!1),Bt(r,u,_),x===44&&(Bt(e,l,r),r=Object.create(null),l=void 0),u=void 0,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${y}`);if(f===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=y);let S=t.slice(f,g);return l===void 0?Bt(e,S,r):(u===void 0?Bt(r,S,!0):i?Bt(r,u,S.replace(/\\/g,"")):Bt(r,u,S),Bt(e,l,r)),e}function dv(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(", ")}Qh.exports={format:dv,parse:cv}});var Ko=ce((BR,ux)=>{"use strict";var lv=xe("events"),uv=xe("https"),fv=xe("http"),nx=xe("net"),hv=xe("tls"),{randomBytes:xv,createHash:pv}=xe("crypto"),{Duplex:NR,Readable:MR}=xe("stream"),{URL:Ld}=xe("url"),Dn=Gr(),gv=Cd(),mv=Pd(),{isBlob:wv}=qr(),{BINARY_TYPES:ex,CLOSE_TIMEOUT:_v,EMPTY_BUFFER:Go,GUID:yv,kForOnEventAttribute:Nd,kListener:Ev,kStatusCode:bv,kWebSocket:je,NOOP:rx}=Zt(),{EventTarget:{addEventListener:vv,removeEventListener:Sv}}=Xh(),{format:Iv,parse:Av}=Ho(),{toBuffer:kv}=Yi(),ix=Symbol("kAborted"),Md=[8,13],Qt=["CONNECTING","OPEN","CLOSING","CLOSED"],Tv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ye=class t extends lv{constructor(e,r,i){super(),this._binaryType=ex[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Go,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]),sx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ex.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 gv({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new mv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[je]=this,c[je]=this,e[je]=this,o.on("conclude",Dv),o.on("drain",Pv),o.on("error",Ov),o.on("message",Lv),o.on("ping",Nv),o.on("pong",Mv),c.onerror=Bv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",cx),e.on("data",jo),e.on("end",dx),e.on("error",lx),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[Dn.extensionName]&&this._extensions[Dn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ct(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ax(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){Bd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Go,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){Bd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Go,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){Bd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Dn.extensionName]||(o.compress=!1),this._sender.send(e||Go,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ct(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ye,"CONNECTING",{enumerable:!0,value:Qt.indexOf("CONNECTING")});Object.defineProperty(ye.prototype,"CONNECTING",{enumerable:!0,value:Qt.indexOf("CONNECTING")});Object.defineProperty(ye,"OPEN",{enumerable:!0,value:Qt.indexOf("OPEN")});Object.defineProperty(ye.prototype,"OPEN",{enumerable:!0,value:Qt.indexOf("OPEN")});Object.defineProperty(ye,"CLOSING",{enumerable:!0,value:Qt.indexOf("CLOSING")});Object.defineProperty(ye.prototype,"CLOSING",{enumerable:!0,value:Qt.indexOf("CLOSING")});Object.defineProperty(ye,"CLOSED",{enumerable:!0,value:Qt.indexOf("CLOSED")});Object.defineProperty(ye.prototype,"CLOSED",{enumerable:!0,value:Qt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ye.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ye.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Nd])return e[Ev];return null},set(e){for(let r of this.listeners(t))if(r[Nd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Nd]:!0})}})});ye.prototype.addEventListener=vv;ye.prototype.removeEventListener=Sv;ux.exports=ye;function sx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_v,protocolVersion:Md[1],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,!Md.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Md.join(", ")})`);let c;if(e instanceof Ld)c=e;else try{c=new Ld(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;qo(t,I);return}let x=l?443:80,g=xv(16).toString("base64"),y=l?uv.request:fv.request,S=new Set,_;if(o.createConnection=o.createConnection||(l?Rv:Cv),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 Dn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Iv({[Dn.extensionName]:_.offer()})),r.length){for(let I of r){if(typeof I!="string"||!Tv.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 v;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")),v=t._req=y(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=y(o);o.timeout&&v.on("timeout",()=>{ct(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[ix]||(v=t._req=null,qo(t,I))}),v.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){ct(t,v,"Maximum redirects exceeded");return}v.abort();let D;try{D=new Ld(A,e)}catch{let C=new SyntaxError(`Invalid URL: ${A}`);qo(t,C);return}sx(t,D,r,i)}else t.emit("unexpected-response",v,I)||ct(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==ye.CONNECTING)return;v=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){ct(t,A,"Invalid Upgrade header");return}let E=pv("sha1").update(g+yv).digest("base64");if(I.headers["sec-websocket-accept"]!==E){ct(t,A,"Invalid Sec-WebSocket-Accept header");return}let C=I.headers["sec-websocket-protocol"],O;if(C!==void 0?S.size?S.has(C)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":S.size&&(O="Server sent no subprotocol"),O){ct(t,A,O);return}C&&(t._protocol=C);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!_){ct(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=Av(F)}catch{ct(t,A,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(B);if(V.length!==1||V[0]!==Dn.extensionName){ct(t,A,"Server indicated an extension that was not requested");return}try{_.accept(B[Dn.extensionName])}catch{ct(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Dn.extensionName]=_}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(v,t):v.end()}function qo(t,e){t._readyState=ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Cv(t){return t.path=t.socketPath,nx.connect(t)}function Rv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=nx.isIP(t.host)?"":t.host),hv.connect(t)}function ct(t,e,r){t._readyState=ye.CLOSING;let i=new Error(r);Error.captureStackTrace(i,ct),e.setHeader?(e[ix]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(qo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Bd(t,e,r){if(e){let i=wv(e)?e.size:kv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Qt[t.readyState]})`);process.nextTick(r,i)}}function Dv(t,e){let r=this[je];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[je]!==void 0&&(r._socket.removeListener("data",jo),process.nextTick(ox,r._socket),t===1005?r.close():r.close(t,e))}function Pv(){let t=this[je];t.isPaused||t._socket.resume()}function Ov(t){let e=this[je];e._socket[je]!==void 0&&(e._socket.removeListener("data",jo),process.nextTick(ox,e._socket),e.close(t[bv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function tx(){this[je].emitClose()}function Lv(t,e){this[je].emit("message",t,e)}function Nv(t){let e=this[je];e._autoPong&&e.pong(t,!this._isServer,rx),e.emit("ping",t)}function Mv(t){this[je].emit("pong",t)}function ox(t){t.resume()}function Bv(t){let e=this[je];e.readyState!==ye.CLOSED&&(e.readyState===ye.OPEN&&(e._readyState=ye.CLOSING,ax(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ax(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function cx(){let t=this[je];if(this.removeListener("close",cx),this.removeListener("data",jo),this.removeListener("end",dx),t._readyState=ye.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[je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",tx),t._receiver.on("finish",tx))}function jo(t){this[je]._receiver.write(t)||this.pause()}function dx(){let t=this[je];t._readyState=ye.CLOSING,t._receiver.end(),this.end()}function lx(){let t=this[je];this.removeListener("error",lx),this.on("error",rx),t&&(t._readyState=ye.CLOSING,this.destroy())}});var px=ce((zR,xx)=>{"use strict";var FR=Ko(),{Duplex:Fv}=xe("stream");function fx(t){t.emit("close")}function zv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function hx(t){this.removeListener("error",hx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Uv(t,e){let r=!0,i=new Fv({...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(fx,i);return}let l=!1;t.once("error",function(f){l=!0,c(f)}),t.once("close",function(){l||c(o),process.nextTick(fx,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",zv),i.on("error",hx),i}xx.exports=Uv});var Fd=ce((UR,gx)=>{"use strict";var{tokenChars:Hv}=qr();function Gv(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&&Hv[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}gx.exports={parse:Gv}});var Sx=ce((GR,vx)=>{"use strict";var qv=xe("events"),Wo=xe("http"),{Duplex:HR}=xe("stream"),{createHash:jv}=xe("crypto"),mx=Ho(),tr=Gr(),Kv=Fd(),Wv=Ko(),{CLOSE_TIMEOUT:$v,GUID:Vv,kWebSocket:Jv}=Zt(),Zv=/^[+/0-9A-Za-z]{22}==$/,_x=0,yx=1,bx=2,zd=class extends qv{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:$v,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wv,...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=Wo.createServer((i,o)=>{let c=Wo.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=Yv(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=_x}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===bx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ns,this);return}if(e&&this.once("close",e),this._state!==yx)if(this._state=yx,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(ns,this):process.nextTick(ns,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{ns(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",Ex);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){nr(this,e,r,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){nr(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!Zv.test(c)){nr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){nr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){rs(r,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=Kv.parse(f)}catch{nr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],y={};if(this.options.perMessageDeflate&&g!==void 0){let S=new tr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=mx.parse(g);_[tr.extensionName]&&(S.accept(_[tr.extensionName]),y[tr.extensionName]=S)}catch{nr(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,(_,v,I,A)=>{if(!_)return rs(r,v||401,I,A);this.completeUpgrade(y,c,x,e,r,i,o)});return}if(!this.options.verifyClient(S))return rs(r,401)}this.completeUpgrade(y,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,l,u){if(!c.readable||!c.writable)return c.destroy();if(c[Jv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>_x)return rs(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${jv("sha1").update(r+Vv).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let y=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;y&&(x.push(`Sec-WebSocket-Protocol: ${y}`),g._protocol=y)}if(e[tr.extensionName]){let y=e[tr.extensionName].params,S=mx.format({[tr.extensionName]:[y]});x.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
8
+ var r_=Object.create;var Qa=Object.defineProperty;var i_=Object.getOwnPropertyDescriptor;var s_=Object.getOwnPropertyNames;var o_=Object.getPrototypeOf,a_=Object.prototype.hasOwnProperty;var pe=(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 at=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ec=(t,e)=>{for(var n in e)Qa(t,n,{get:e[n],enumerable:!0})},c_=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of s_(e))!a_.call(t,s)&&s!==n&&Qa(t,s,{get:()=>e[s],enumerable:!(i=i_(e,s))||i.enumerable});return t};var Nt=(t,e,n)=>(n=t!=null?r_(o_(t)):{},c_(e||!t||!t.__esModule?Qa(n,"default",{value:t,enumerable:!0}):n,t));function Qe(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var pr=at(()=>{"use strict"});import{createWriteStream as l_,mkdirSync as d_,readdirSync as u_,unlinkSync as f_}from"node:fs";import{join as hu}from"node:path";function qn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function gr(t,e){return`${t}-${e}.log`}function tc(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function h_(t,e,n){let i=a=>{let[l,u,f]=a.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>n}function As(t,e,n,i){let s;try{s=u_(t)}catch{return}for(let a of s){let l=tc(a,e);if(l&&h_(l,n,i))try{f_(hu(t,a))}catch{}}}var hi,nc=at(()=>{"use strict";hi=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>qn(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{d_(this.dir,{recursive:!0});let n=l_(hu(this.dir,gr(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&&As(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as x_,mkdirSync as p_}from"node:fs";import{join as g_}from"node:path";function pu(t){let e=t.retentionDays??__,n=t.clock??(()=>qn(new Date));Rs={bridgeSink:new hi(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:s=>new hi(t.agentLogsDir(s),"agent",{retentionDays:e,clock:n})};let i=n();As(t.bridgeLogsDir,"bridge",i,e);for(let s of t.listAgentIds?.()??[])As(t.agentLogsDir(s),"agent",i,e)}function y_(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function gu(t){rc=t}function mu(t){return mr[rc]<=mr[t]}function wu(t,e){let n=mr[t];return n===void 0?!0:n>=mr[e]}function ks(t){xu={...t}}function _u(t){let e=(u,f=2)=>String(u).padStart(f,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",s=Math.abs(n),a=e(Math.floor(s/60)),l=e(s%60);return`${qn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${l}`}function Mt(t,e,n,i,s){try{let a=`${JSON.stringify({ts:_u(new Date),level:e,module:n,msg:i,...s})}
11
+ `;p_(t,{recursive:!0}),x_(g_(t,gr("bridge",qn(new Date))),a)}catch{}}function E_(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function Ts(t,e,n,i,s){if(mr[t]<mr[rc])return;let a=`${JSON.stringify({ts:_u(new Date),level:t,module:e,msg:n,...xu,...i})}
12
+ `;if(Rs){let l=E_(s,i),u=l?y_(Rs,l):Rs.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?w_.write(a):m_.write(a)}function $(t,e){return{debug:(n,i)=>Ts("debug",t,n,i,e),info:(n,i)=>Ts("info",t,n,i,e),warn:(n,i)=>Ts("warn",t,n,i,e),error:(n,i)=>Ts("error",t,n,i,e),child:n=>$(`${t}.${n}`,e),forAgent:n=>$(t,n)}}var mr,rc,m_,w_,xu,__,Rs,oe=at(()=>{"use strict";pr();nc();mr={debug:10,info:20,warn:30,error:40},rc=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),m_=process.stdout,w_=process.stderr,xu={},__=Qe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Rs=null});var T,Ze=at(()=>{"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 vu={};ec(vu,{ACP_WRAPPER_NPM_PACKAGES:()=>Cs,_resetAcpInstallerForTests:()=>T_,_setBinaryPathCacheForTests:()=>R_,buildAcpSpawn:()=>pi,ensureAcpInstalled:()=>wr,getAcpBinaryPath:()=>Ps,pickWhichLine:()=>oc,probeAcpVersion:()=>A_,resolveAcpCommand:()=>bu});import{readFileSync as yu}from"node:fs";import{createRequire as b_}from"node:module";import{dirname as v_,resolve as S_}from"node:path";function oc(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 I_(t){let e=Eu.resolve(`${t.npmPackage}/package.json`),n=v_(e),i=JSON.parse(yu(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 S_(n,s)}async function wr(t,e){let n=sc[t];if(!n)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=xi.get(t);if(i)return i;try{let s=I_(n);return xi.set(t,s),ic.info("acp wrapper resolved",{framework:t,binary:n.binary,path:s}),s}catch(s){throw ic.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 A_(t){let e=sc[t];if(e)try{let n=Eu.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(yu(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){ic.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function Ps(t){return xi.get(t)}function bu(t,e){if(e)return e;let n=Ps(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 pi(t,e,n){if(e)return{command:e,args:[...n]};let i=bu(t);return{command:process.execPath,args:[i,...n]}}function T_(){xi.clear()}function R_(t,e){xi.set(t,e)}var ic,sc,Cs,Eu,xi,pn=at(()=>{"use strict";Ze();oe();ic=$("agents.acp-installer"),sc={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},Cs=Object.values(sc).filter(t=>t!==void 0).map(t=>t.npmPackage),Eu=b_(import.meta.url),xi=new Map});import{chmod as C_,mkdir as P_,readFile as D_,rename as L_,rm as O_,writeFile as N_}from"node:fs/promises";import{dirname as M_}from"node:path";async function _r(t){try{let e=await D_(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function gn(t,e,n){await P_(M_(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await N_(i,e,{encoding:"utf8",mode:n?.mode}),await L_(i,t),n?.mode!==void 0&&await C_(t,n.mode)}catch(s){throw await O_(i,{force:!0}).catch(()=>{}),s}}async function yr(t,e,n){await gn(t,`${JSON.stringify(e,null,2)}
14
+ `,n)}var mn=at(()=>{"use strict"});import{promises as Au,readdirSync as B_}from"node:fs";import{homedir as F_}from"node:os";import{sep as z_,join as Pe,resolve as Tu}from"node:path";function ie(t){let e=t??F_(),n=Pe(e,".coze"),i=Pe(n,"bridge"),s=Pe(i,"lib"),a=Pe(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:s,libEntry:Pe(s,"index.js"),binDir:Pe(i,"bin"),pidFile:Pe(i,"bridge.pid"),portFile:Pe(i,"bridge.port"),tokenFile:Pe(i,"bridge.token"),patTokenFile:Pe(i,"pat-token"),agentEnvFile:Pe(i,"agent-env.json"),logFile:Pe(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:Pe(a,"daemon-stdio.log"),installLock:Pe(i,"install.lock"),configFile:Pe(i,"config.json"),agentsRoot:Pe(n,"agents")}}function et(t,e=ie()){let n=Pe(e.agentsRoot,t);return{root:n,config:Pe(n,"config.json"),workspace:Pe(n,"workspace"),logs:Pe(n,"logs")}}function Ds(t=ie()){try{return B_(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function gi(t,e){let n=await Au.realpath(Tu(t)).catch(()=>null);if(!n)return!1;let i=await Au.realpath(Tu(e)).catch(()=>null);if(!i)return!1;let s=process.platform==="win32"?n.toLowerCase():n,a=process.platform==="win32"?i.toLowerCase():i;return s===a||s.startsWith(a+z_)}var Be=at(()=>{"use strict"});var Os={};ec(Os,{AGENT_CONFIG_FILE_MODE:()=>Ls,enforceAgentConfigMode:()=>q_,loadAgentConfig:()=>De,persistAgentSessions:()=>mi,persistAgentSkills:()=>wi,saveAgentConfig:()=>qe});import{chmod as U_,stat as G_}from"node:fs/promises";function De(t,e){return _r(et(t,e).config)}function qe(t,e){return yr(et(t.agentId,e).config,t,{mode:Ls})}async function q_(t,e){if(process.platform==="win32")return;let n=et(t,e).config;try{let i=await G_(n);if(!i.isFile())return;let s=i.mode&511;s!==Ls&&(await U_(n,Ls),Ru.warn("agent config mode auto-corrected to 0600",{path:n,from:s.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Ru.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function mi(t,e,n){let i=await De(t,n);i&&(i.sessions=Object.fromEntries(e),await qe(i,n))}async function wi(t,e,n){let i=await De(t,n);i&&(i.skills=e,await qe(i,n))}var Ru,Ls,wn=at(()=>{"use strict";mn();oe();Be();Ru=$("agent-config"),Ls=384});var lc=z((BC,Pu)=>{Pu.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=z(Lu=>{var Du={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 V_(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(Du))Lu[t]=V_(Du[t])});var Fu=z((zC,Bu)=>{var Z_=pe("fs"),Fe=pe("path"),Ou=lc(),J_=Ms(),Y_=typeof process=="object"&&process.platform==="win32",Nu=t=>typeof t=="object"&&t!==null,Mu=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 Te(t){this.sep=Fe.sep,this.fs=Z_,Nu(t)&&Nu(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Bu.exports=Te;Te.prototype.makeDir=function(t){let e=this;function n(i){let s=i.split(e.sep)[0];i.split(e.sep).forEach(function(a){if(!(!a||a.substr(-1,1)===":")){s+=e.sep+a;var l;try{l=e.fs.statSync(s)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw u}if(l&&l.isFile())throw J_.FILE_IN_THE_WAY(`"${s}"`)}})}n(t)};Te.prototype.writeFileTo=function(t,e,n,i){let s=this;if(s.fs.existsSync(t)){if(!n)return!1;var a=s.fs.statSync(t);if(a.isDirectory())return!1}var l=Fe.dirname(t);s.fs.existsSync(l)||s.makeDir(l);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};Te.prototype.writeFileToAsync=function(t,e,n,i,s){typeof i=="function"&&(s=i,i=void 0);let a=this;a.fs.exists(t,function(l){if(l&&!n)return s(!1);a.fs.stat(t,function(u,f){if(l&&f.isDirectory())return s(!1);var x=Fe.dirname(t);a.fs.exists(x,function(m){m||a.makeDir(x),a.fs.open(t,"w",438,function(g,v){g?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(w,b){a.fs.write(b,e,0,e.length,0,function(){a.fs.close(b,function(){a.fs.chmod(t,i||438,function(){s(!0)})})})})}):v?a.fs.write(v,e,0,e.length,0,function(){a.fs.close(v,function(){a.fs.chmod(t,i||438,function(){s(!0)})})}):a.fs.chmod(t,i||438,function(){s(!0)})})})})})};Te.prototype.findFiles=function(t){let e=this;function n(i,s,a){typeof s=="boolean"&&(a=s,s=void 0);let l=[];return e.fs.readdirSync(i).forEach(function(u){let f=Fe.join(i,u),x=e.fs.statSync(f);(!s||s.test(f))&&l.push(Fe.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(l=l.concat(n(f,s,a)))}),l}return n(t,void 0,!0)};Te.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(s,a){if(s)return e(s);let l=a.length;if(!l)return e(null,i);a.forEach(function(u){u=Fe.join(t,u),n.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Fe.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(m,g){if(m)return e(m);i=i.concat(g),--l||e(null,i)}):--l||e(null,i))})})})};Te.prototype.getAttributes=function(){};Te.prototype.setAttributes=function(){};Te.crc32update=function(t,e){return Mu[(t^e)&255]^t>>>8};Te.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Te.crc32update(n,t[i++]);return~n>>>0};Te.methodToString=function(t){switch(t){case Ou.STORED:return"STORED ("+t+")";case Ou.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Te.canonical=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.join(".",e)};Te.zipnamefix=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.posix.join(".",e)};Te.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]};Te.sanitize=function(t,e){t=Fe.resolve(Fe.normalize(t));for(var n=e.split("/"),i=0,s=n.length;i<s;i++){var a=Fe.normalize(Fe.join(t,n.slice(i,s).join(Fe.sep)));if(a.indexOf(t)===0)return a}return Fe.normalize(Fe.join(t,Fe.basename(e)))};Te.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Te.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Te.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)};Te.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};Te.isWin=Y_;Te.crcTable=Mu});var Uu=z((UC,zu)=>{var X_=pe("path");zu.exports=function(t,{fs:e}){var n=t||"",i=a(),s=null;function a(){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=X_.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 qu=z((GC,Gu)=>{Gu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var vr=z((qC,br)=>{br.exports=Fu();br.exports.Constants=lc();br.exports.Errors=Ms();br.exports.FileAttr=Uu();br.exports.decoder=qu()});var $u=z((HC,Hu)=>{var _n=vr(),U=_n.Constants;Hu.exports=function(){var t=20,e=10,n=0,i=0,s=0,a=0,l=0,u=0,f=0,x=0,m=0,g=0,v=0,w=0,b=0;t|=_n.isWin?2560:768,n|=U.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,R=E=>Math.max(0,E)&65535,P=E=>Math.max(0,E)&255;return s=_n.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return n},set flags(E){n=E},get flags_efs(){return(n&U.FLG_EFS)>0},set flags_efs(E){E?n|=U.FLG_EFS:n&=~U.FLG_EFS},get flags_desc(){return(n&U.FLG_DESC)>0},set flags_desc(E){E?n|=U.FLG_DESC:n&=~U.FLG_DESC},get method(){return i},set method(E){switch(E){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=E},get time(){return _n.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=_n.fromDate2DOS(E)},get timeval(){return s},set timeval(E){s=A(E)},get timeHighByte(){return P(s>>>8)},get crc(){return a},set crc(E){a=A(E)},get compressedSize(){return l},set compressedSize(E){l=A(E)},get size(){return u},set size(E){u=A(E)},get fileNameLength(){return f},set fileNameLength(E){f=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return m},set commentLength(E){m=E},get diskNumStart(){return g},set diskNumStart(E){g=A(E)},get inAttr(){return v},set inAttr(E){v=A(E)},get attr(){return w},set attr(E){w=A(E)},get fileAttr(){return(w||0)>>16&4095},get offset(){return b},set offset(E){b=A(E)},get encrypted(){return(n&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+f+x+m},get realDataOffset(){return b+U.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var k=E.slice(b,b+U.LOCHDR);if(k.readUInt32LE(0)!==U.LOCSIG)throw _n.Errors.INVALID_LOC();I.version=k.readUInt16LE(U.LOCVER),I.flags=k.readUInt16LE(U.LOCFLG),I.flags_desc=(I.flags&U.FLG_DESC)>0,I.method=k.readUInt16LE(U.LOCHOW),I.time=k.readUInt32LE(U.LOCTIM),I.crc=k.readUInt32LE(U.LOCCRC),I.compressedSize=k.readUInt32LE(U.LOCSIZ),I.size=k.readUInt32LE(U.LOCLEN),I.fnameLen=k.readUInt16LE(U.LOCNAM),I.extraLen=k.readUInt16LE(U.LOCEXT);let L=b+U.LOCHDR+I.fnameLen,B=L+I.extraLen;return E.slice(L,B)},loadFromBinary:function(E){if(E.length!==U.CENHDR||E.readUInt32LE(0)!==U.CENSIG)throw _n.Errors.INVALID_CEN();t=E.readUInt16LE(U.CENVEM),e=E.readUInt16LE(U.CENVER),n=E.readUInt16LE(U.CENFLG),i=E.readUInt16LE(U.CENHOW),s=E.readUInt32LE(U.CENTIM),a=E.readUInt32LE(U.CENCRC),l=E.readUInt32LE(U.CENSIZ),u=E.readUInt32LE(U.CENLEN),f=E.readUInt16LE(U.CENNAM),x=E.readUInt16LE(U.CENEXT),m=E.readUInt16LE(U.CENCOM),g=E.readUInt16LE(U.CENDSK),v=E.readUInt16LE(U.CENATT),w=E.readUInt32LE(U.CENATX),b=E.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(U.LOCHDR);return E.writeUInt32LE(U.LOCSIG,0),E.writeUInt16LE(e,U.LOCVER),E.writeUInt16LE(n,U.LOCFLG),E.writeUInt16LE(i,U.LOCHOW),E.writeUInt32LE(s,U.LOCTIM),E.writeUInt32LE(a,U.LOCCRC),E.writeUInt32LE(l,U.LOCSIZ),E.writeUInt32LE(u,U.LOCLEN),E.writeUInt16LE(f,U.LOCNAM),E.writeUInt16LE(I.extraLen,U.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(U.CENHDR+f+x+m);return E.writeUInt32LE(U.CENSIG,0),E.writeUInt16LE(t,U.CENVEM),E.writeUInt16LE(e,U.CENVER),E.writeUInt16LE(n,U.CENFLG),E.writeUInt16LE(i,U.CENHOW),E.writeUInt32LE(s,U.CENTIM),E.writeUInt32LE(a,U.CENCRC),E.writeUInt32LE(l,U.CENSIZ),E.writeUInt32LE(u,U.CENLEN),E.writeUInt16LE(f,U.CENNAM),E.writeUInt16LE(x,U.CENEXT),E.writeUInt16LE(m,U.CENCOM),E.writeUInt16LE(g,U.CENDSK),E.writeUInt16LE(v,U.CENATT),E.writeUInt32LE(w,U.CENATX),E.writeUInt32LE(b,U.CENOFF),E},toJSON:function(){let E=function(k){return k+" bytes"};return{made:t,version:e,flags:n,method:_n.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:E(l),size:E(u),fileNameLength:E(f),extraLength:E(x),commentLength:E(m),diskNumStart:g,inAttr:v,attr:w,offset:b,centralHeaderSize:E(U.CENHDR+f+x+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Wu=z(($C,ju)=>{var Sr=vr(),Se=Sr.Constants;ju.exports=function(){var t=0,e=0,n=0,i=0,s=0;return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return n},set size(a){n=a},get offset(){return i},set offset(a){i=a},get commentLength(){return s},set commentLength(a){s=a},get mainHeaderSize(){return Se.ENDHDR+s},loadFromBinary:function(a){if((a.length!==Se.ENDHDR||a.readUInt32LE(0)!==Se.ENDSIG)&&(a.length<Se.ZIP64HDR||a.readUInt32LE(0)!==Se.ZIP64SIG))throw Sr.Errors.INVALID_END();a.readUInt32LE(0)===Se.ENDSIG?(t=a.readUInt16LE(Se.ENDSUB),e=a.readUInt16LE(Se.ENDTOT),n=a.readUInt32LE(Se.ENDSIZ),i=a.readUInt32LE(Se.ENDOFF),s=a.readUInt16LE(Se.ENDCOM)):(t=Sr.readBigUInt64LE(a,Se.ZIP64SUB),e=Sr.readBigUInt64LE(a,Se.ZIP64TOT),n=Sr.readBigUInt64LE(a,Se.ZIP64SIZE),i=Sr.readBigUInt64LE(a,Se.ZIP64OFF),s=0)},toBinary:function(){var a=Buffer.alloc(Se.ENDHDR+s);return a.writeUInt32LE(Se.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,Se.ENDSUB),a.writeUInt16LE(e,Se.ENDTOT),a.writeUInt32LE(n,Se.ENDSIZ),a.writeUInt32LE(i,Se.ENDOFF),a.writeUInt16LE(s,Se.ENDCOM),a.fill(" ",Se.ENDHDR),a},toJSON:function(){let a=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:n+" bytes",offset:a(i,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var uc=z(dc=>{dc.EntryHeader=$u();dc.MainHeader=Wu()});var Vu=z((WC,Ku)=>{Ku.exports=function(t){var e=pe("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),a=[],l=0;s.on("data",function(u){a.push(u),l+=u.length}),s.on("end",function(){var u=Buffer.alloc(l),f=0;u.fill(0);for(var x=0;x<a.length;x++){var m=a[x];m.copy(u,f),f+=m.length}i&&i(u)}),s.end(t)}}}});var Ju=z((KC,Zu)=>{var Q_=+(process.versions?process.versions.node:"").split(".")[0]||0;Zu.exports=function(t,e){var n=pe("zlib");let i=Q_>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(s){var a=n.createInflateRaw(i),l=[],u=0;a.on("data",function(f){l.push(f),u+=f.length}),a.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var m=0;m<l.length;m++){var g=l[m];g.copy(f,x),x+=g.length}s&&s(f)}),a.end(t)}}}});var tf=z((VC,ef)=>{"use strict";var{randomFillSync:Yu}=pe("crypto"),ey=Ms(),ty=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}),Qu=(t,e)=>Math.imul(t,e)>>>0,Xu=(t,e)=>ty[(t^e)&255]^t>>>8,_i=()=>typeof Yu=="function"?Yu(Buffer.alloc(12)):_i.node();_i.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 Bs={genSalt:_i};function Fs(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])}Fs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Xu(e[0],t),e[1]+=e[0]&255,e[1]=Qu(e[1],134775813)+1,e[2]=Xu(e[2],e[1]>>>24),t};Fs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Qu(t,t^1)>>8&255};function ny(t){let e=new Fs(t);return function(n){let i=Buffer.alloc(n.length),s=0;for(let a of n)i[s++]=e.updateKeys(a^e.next());return i}}function ry(t){let e=new Fs(t);return function(n,i,s=0){i||(i=Buffer.alloc(n.length));for(let a of n){let l=e.next();i[s++]=a^l,e.updateKeys(a)}return i}}function iy(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=ny(n),s=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==a)throw ey.WRONG_PASSWORD();return i(t.slice(12))}function sy(t){Buffer.isBuffer(t)&&t.length>=12?Bs.genSalt=function(){return t.slice(0,12)}:t==="node"?Bs.genSalt=_i.node:Bs.genSalt=_i}function oy(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=ry(n),a=Bs.genSalt();a[11]=e.crc>>>24&255,i&&(a[10]=e.crc>>>16&255);let l=Buffer.alloc(t.length+12);return s(a,l),s(t,l,12)}ef.exports={decrypt:iy,encrypt:oy,_salter:sy}});var nf=z(zs=>{zs.Deflater=Vu();zs.Inflater=Ju();zs.ZipCrypto=tf()});var hc=z((JC,rf)=>{var ue=vr(),ay=uc(),Re=ue.Constants,fc=nf();rf.exports=function(t,e){var n=new ay.EntryHeader,i=Buffer.alloc(0),s=Buffer.alloc(0),a=!1,l=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let m=t,g=typeof m.decoder=="object"?m.decoder:ue.decoder;x=g.hasOwnProperty("efs")?g.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function w(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(ue.crc32(E)!==n.localHeader.crc)return!1}else{let k={},L=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(L)==Re.LOCSIG||e.readUInt32LE(L)==Re.CENSIG)throw ue.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(L)==Re.EXTSIG)k.crc=e.readUInt32LE(L+Re.EXTCRC),k.compressedSize=e.readUInt32LE(L+Re.EXTSIZ),k.size=e.readUInt32LE(L+Re.EXTLEN);else if(e.readUInt16LE(L+12)===19280)k.crc=e.readUInt32LE(L+Re.EXTCRC-4),k.compressedSize=e.readUInt32LE(L+Re.EXTSIZ-4),k.size=e.readUInt32LE(L+Re.EXTLEN-4);else throw ue.Errors.DESCRIPTOR_UNKNOWN();if(k.compressedSize!==n.compressedSize||k.size!==n.size||k.crc!==n.crc)throw ue.Errors.DESCRIPTOR_FAULTY();if(ue.crc32(E)!==k.crc)return!1}return!0}function b(E,k,L){if(typeof k>"u"&&typeof E=="string"&&(L=E,E=void 0),a)return E&&k&&k(Buffer.alloc(0),ue.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var B=v();if(B.length===0)return E&&k&&k(B),B;if(n.encrypted){if(typeof L!="string"&&!Buffer.isBuffer(L))throw ue.Errors.INVALID_PASS_PARAM();B=fc.ZipCrypto.decrypt(B,n,L)}var M=Buffer.alloc(n.size);switch(n.method){case ue.Constants.STORED:if(B.copy(M),w(M))return E&&k&&k(M),M;throw E&&k&&k(M,ue.Errors.BAD_CRC()),ue.Errors.BAD_CRC();case ue.Constants.DEFLATED:var X=new fc.Inflater(B,n.size);if(E)X.inflateAsync(function(Z){Z.copy(Z,0),k&&(w(Z)?k(Z):k(Z,ue.Errors.BAD_CRC()))});else{if(X.inflate(M).copy(M,0),!w(M))throw ue.Errors.BAD_CRC(`"${g.decode(i)}"`);return M}break;default:throw E&&k&&k(Buffer.alloc(0),ue.Errors.UNKNOWN_METHOD()),ue.Errors.UNKNOWN_METHOD()}}function I(E,k){if((!l||!l.length)&&Buffer.isBuffer(e))return E&&k&&k(v()),v();if(l.length&&!a){var L;switch(n.method){case ue.Constants.STORED:return n.compressedSize=n.size,L=Buffer.alloc(l.length),l.copy(L),E&&k&&k(L),L;default:case ue.Constants.DEFLATED:var B=new fc.Deflater(l);if(E)B.deflateAsync(function(X){L=Buffer.alloc(X.length),n.compressedSize=X.length,X.copy(L),k&&k(L)});else{var M=B.deflate();return n.compressedSize=M.length,M}B=null;break}}else if(E&&k)k(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,k){return ue.readBigUInt64LE(E,k)}function R(E){try{for(var k=0,L,B,M;k+4<E.length;)L=E.readUInt16LE(k),k+=2,B=E.readUInt16LE(k),k+=2,M=E.slice(k,k+B),k+=B,Re.ID_ZIP64===L&&P(M)}catch{throw ue.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(E){var k,L,B,M;E.length>=Re.EF_ZIP64_SCOMP&&(k=A(E,Re.EF_ZIP64_SUNCOMP),n.size===Re.EF_ZIP64_OR_32&&(n.size=k)),E.length>=Re.EF_ZIP64_RHO&&(L=A(E,Re.EF_ZIP64_SCOMP),n.compressedSize===Re.EF_ZIP64_OR_32&&(n.compressedSize=L)),E.length>=Re.EF_ZIP64_DSN&&(B=A(E,Re.EF_ZIP64_RHO),n.offset===Re.EF_ZIP64_OR_32&&(n.offset=B)),E.length>=Re.EF_ZIP64_DSN+4&&(M=E.readUInt32LE(Re.EF_ZIP64_DSN),n.diskNumStart===Re.EF_ZIP64_OR_16&&(n.diskNumStart=M))}return{get entryName(){return g.decode(i)},get rawEntryName(){return i},set entryName(E){i=ue.toBuffer(E,g.encode);var k=i[i.length-1];a=k===47||k===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,n.extraLength=E.length,R(E)},get comment(){return g.decode(s)},set comment(E){if(s=ue.toBuffer(E,g.encode),n.commentLength=s.length,s.length>65535)throw ue.Errors.COMMENT_TOO_LONG()},get name(){var E=g.decode(i);return a?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){l=ue.toBuffer(E,ue.decoder.encode),!a&&l.length?(n.size=l.length,n.method=ue.Constants.DEFLATED,n.crc=ue.crc32(E),n.changed=!0):n.method=ue.Constants.STORED},getData:function(E){return n.changed?l:b(!1,null,E)},getDataAsync:function(E,k){n.changed?E(l):b(!0,E,k)},set attr(E){n.attr=E},get attr(){return n.attr},set header(E){n.loadFromBinary(E)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var E=n.centralHeaderToBinary(),k=ue.Constants.CENHDR;return i.copy(E,k),k+=i.length,u.copy(E,k),k+=n.extraLength,s.copy(E,k),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=f.length;let k=n.localHeaderToBinary(),L=Buffer.alloc(k.length+i.length+n.extraLocalLength);return k.copy(L,E),E+=k.length,i.copy(L,E),E+=i.length,f.copy(L,E),E+=f.length,L},toJSON:function(){let E=function(k){return"<"+(k&&k.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:E(e),data:E(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var af=z((YC,of)=>{var sf=hc(),cy=uc(),Je=vr();of.exports=function(t,e){var n=[],i={},s=Buffer.alloc(0),a=new cy.MainHeader,l=!1,u=null;let f=new Set,x=e,{noSort:m,decoder:g}=x;t?b(x.readEntries):l=!0;function v(){let A=new Set;for(let R of Object.keys(i)){let P=R.split("/");if(P.pop(),!!P.length)for(let E=0;E<P.length;E++){let k=P.slice(0,E+1).join("/")+"/";A.add(k)}}for(let R of A)if(!(R in i)){let P=new sf(x);P.entryName=R,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,f.add(P)}}function w(){if(l=!0,i={},a.diskEntries>(t.length-a.offset)/Je.Constants.CENHDR)throw Je.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var A=a.offset,R=0;R<n.length;R++){var P=A,E=new sf(x,t);E.header=t.slice(P,P+=Je.Constants.CENHDR),E.entryName=t.slice(P,P+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(P,P+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(P,P+E.header.commentLength)),A+=E.header.centralHeaderSize,n[R]=E,i[E.entryName]=E}f.clear(),v()}function b(A){var R=t.length-Je.Constants.ENDHDR,P=Math.max(0,R-65535),E=P,k=t.length,L=-1,B=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),R;R>=E;R--)if(t[R]===80){if(t.readUInt32LE(R)===Je.Constants.ENDSIG){L=R,B=R,k=R+Je.Constants.ENDHDR,E=R-Je.Constants.END64HDR;continue}if(t.readUInt32LE(R)===Je.Constants.END64SIG){E=P;continue}if(t.readUInt32LE(R)===Je.Constants.ZIP64SIG){L=R,k=R+Je.readBigUInt64LE(t,R+Je.Constants.ZIP64SIZE)+Je.Constants.ZIP64LEAD;break}}if(L==-1)throw Je.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(L,k)),a.commentLength&&(s=t.slice(B+Je.Constants.ENDHDR)),A&&w()}function I(){n.length>1&&!m&&n.sort((A,R)=>A.entryName.toLowerCase().localeCompare(R.entryName.toLowerCase()))}return{get entries(){return l||w(),n.filter(A=>!f.has(A))},get comment(){return g.decode(s)},set comment(A){s=Je.toBuffer(A,g.encode),a.commentLength=s.length},getEntryCount:function(){return l?n.length:a.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return l||w(),i[A]||null},setEntry:function(A){l||w(),n.push(A),i[A.entryName]=A,a.totalEntries=n.length},deleteFile:function(A,R=!0){l||w();let P=i[A];this.getEntryChildren(P,R).map(k=>k.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||w();let R=i[A],P=n.indexOf(R);P>=0&&(n.splice(P,1),delete i[A],a.totalEntries=n.length)},getEntryChildren:function(A,R=!0){if(l||w(),typeof A=="object")if(A.isDirectory&&R){let P=[],E=A.entryName;for(let k of n)k.entryName.startsWith(E)&&P.push(k);return P}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let R=this.getEntryChildren(A);return R.includes(A)?R.length-1:R.length}return 0},compressToBuffer:function(){l||w(),I();let A=[],R=[],P=0,E=0;a.size=0,a.offset=0;let k=0;for(let M of this.entries){let X=M.getCompressedData();M.header.offset=E;let Z=M.packLocalHeader(),ae=Z.length+X.length;E+=ae,A.push(Z),A.push(X);let te=M.packCentralHeader();R.push(te),a.size+=te.length,P+=ae+te.length,k++}P+=a.mainHeaderSize,a.offset=E,a.totalEntries=k,E=0;let L=Buffer.alloc(P);for(let M of A)M.copy(L,E),E+=M.length;for(let M of R)M.copy(L,E),E+=M.length;let B=a.toBinary();return s&&s.copy(B,Je.Constants.ENDHDR),B.copy(L,E),t=L,l=!1,L},toAsyncBuffer:function(A,R,P,E){try{l||w(),I();let k=[],L=[],B=0,M=0,X=0;a.size=0,a.offset=0;let Z=function(ae){if(ae.length>0){let te=ae.shift(),le=te.entryName+te.extra.toString();P&&P(le),te.getCompressedDataAsync(function(de){E&&E(le),te.header.offset=M;let C=te.packLocalHeader(),G=C.length+de.length;M+=G,k.push(C),k.push(de);let W=te.packCentralHeader();L.push(W),a.size+=W.length,B+=G+W.length,X++,Z(ae)})}else{B+=a.mainHeaderSize,a.offset=M,a.totalEntries=X,M=0;let te=Buffer.alloc(B);k.forEach(function(de){de.copy(te,M),M+=de.length}),L.forEach(function(de){de.copy(te,M),M+=de.length});let le=a.toBinary();s&&s.copy(le,Je.Constants.ENDHDR),le.copy(te,M),t=te,l=!1,A(te)}};Z(Array.from(this.entries))}catch(k){R(k)}}}}});var df=z((XC,lf)=>{var Ae=vr(),Ie=pe("path"),ly=hc(),dy=af(),Hn=(...t)=>Ae.findLast(t,e=>typeof e=="boolean"),cf=(...t)=>Ae.findLast(t,e=>typeof e=="string"),uy=(...t)=>Ae.findLast(t,e=>typeof e=="function"),fy={noSort:!1,readEntries:!1,method:Ae.Constants.NONE,fs:null};lf.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),fy);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=Ae.Constants.BUFFER,t=void 0)),Object.assign(i,e);let s=new Ae(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ae.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))i.method=Ae.Constants.FILE,i.filename=t,n=s.fs.readFileSync(t);else throw Ae.Errors.INVALID_FILENAME();let a=new dy(n,i),{canonical:l,sanitize:u,zipnamefix:f}=Ae;function x(w){if(w&&a){var b;if(typeof w=="string"&&(b=a.getEntry(Ie.posix.normalize(w))),typeof w=="object"&&typeof w.entryName<"u"&&typeof w.header<"u"&&(b=a.getEntry(w.entryName)),b)return b}return null}function m(w){let{join:b,normalize:I,sep:A}=Ie.posix;return b(Ie.isAbsolute(w)?"/":".",I(A+w.split("\\").join(A)+A))}function g(w){return w instanceof RegExp?(function(b){return function(I){return b.test(I)}})(w):typeof w!="function"?()=>!0:w}let v=(w,b)=>{let I=b.slice(-1);return I=I===s.sep?s.sep:"",Ie.relative(w,b)+I};return{readFile:function(w,b){var I=x(w);return I&&I.getData(b)||null},childCount:function(w){let b=x(w);if(b)return a.getChildCount(b)},readFileAsync:function(w,b){var I=x(w);I?I.getDataAsync(b):b(null,"getEntry failed for:"+w)},readAsText:function(w,b){var I=x(w);if(I){var A=I.getData();if(A&&A.length)return A.toString(b||"utf8")}return""},readAsTextAsync:function(w,b,I){var A=x(w);A?A.getDataAsync(function(R,P){if(P){b(R,P);return}R&&R.length?b(R.toString(I||"utf8")):b("")}):b("")},deleteFile:function(w,b=!0){var I=x(w);I&&a.deleteFile(I.entryName,b)},deleteEntry:function(w){var b=x(w);b&&a.deleteEntry(b.entryName)},addZipComment:function(w){a.comment=w},getZipComment:function(){return a.comment||""},addZipEntryComment:function(w,b){var I=x(w);I&&(I.comment=b)},getZipEntryComment:function(w){var b=x(w);return b&&b.comment||""},updateFile:function(w,b){var I=x(w);I&&I.setData(b)},addLocalFile:function(w,b,I,A){if(s.fs.existsSync(w)){b=b?m(b):"";let R=Ie.win32.basename(Ie.win32.normalize(w));b+=I||R;let P=s.fs.statSync(w),E=P.isFile()?s.fs.readFileSync(w):Buffer.alloc(0);P.isDirectory()&&(b+=s.sep),this.addFile(b,E,A,P)}else throw Ae.Errors.FILE_NOT_FOUND(w)},addLocalFileAsync:function(w,b){w=typeof w=="object"?w:{localPath:w};let I=Ie.resolve(w.localPath),{comment:A}=w,{zipPath:R,zipName:P}=w,E=this;s.fs.stat(I,function(k,L){if(k)return b(k,!1);R=R?m(R):"";let B=Ie.win32.basename(Ie.win32.normalize(I));if(R+=P||B,L.isFile())s.fs.readFile(I,function(M,X){return M?b(M,!1):(E.addFile(R,X,A,L),setImmediate(b,void 0,!0))});else if(L.isDirectory())return R+=s.sep,E.addFile(R,Buffer.alloc(0),A,L),setImmediate(b,void 0,!0)})},addLocalFolder:function(w,b,I){if(I=g(I),b=b?m(b):"",w=Ie.normalize(w),s.fs.existsSync(w)){let A=s.findFiles(w),R=this;if(A.length)for(let P of A){let E=Ie.join(b,v(w,P));I(E)&&R.addLocalFile(P,Ie.dirname(E))}}else throw Ae.Errors.FILE_NOT_FOUND(w)},addLocalFolderAsync:function(w,b,I,A){A=g(A),I=I?m(I):"",w=Ie.normalize(w);var R=this;s.fs.open(w,"r",function(P){if(P&&P.code==="ENOENT")b(void 0,Ae.Errors.FILE_NOT_FOUND(w));else if(P)b(void 0,P);else{var E=s.findFiles(w),k=-1,L=function(){if(k+=1,k<E.length){var B=E[k],M=v(w,B).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?s.fs.stat(B,function(X,Z){X&&b(void 0,X),Z.isFile()?s.fs.readFile(B,function(ae,te){ae?b(void 0,ae):(R.addFile(I+M,te,"",Z),L())}):(R.addFile(I+M+"/",Buffer.alloc(0),"",Z),L())}):process.nextTick(()=>{L()})}else b(!0,void 0)};L()}})},addLocalFolderAsync2:function(w,b){let I=this;w=typeof w=="object"?w:{localPath:w},localPath=Ie.resolve(m(w.localPath));let{zipPath:A,filter:R,namefix:P}=w;R instanceof RegExp?R=(function(L){return function(B){return L.test(B)}})(R):typeof R!="function"&&(R=function(){return!0}),A=A?m(A):"",P=="latin1"&&(P=L=>L.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=L=>L);let E=L=>Ie.join(A,P(v(localPath,L))),k=L=>Ie.win32.basename(Ie.win32.normalize(P(L)));s.fs.open(localPath,"r",function(L){L&&L.code==="ENOENT"?b(void 0,Ae.Errors.FILE_NOT_FOUND(localPath)):L?b(void 0,L):s.findFilesAsync(localPath,function(B,M){if(B)return b(B);M=M.filter(X=>R(E(X))),M.length||b(void 0,!1),setImmediate(M.reverse().reduce(function(X,Z){return function(ae,te){if(ae||te===!1)return setImmediate(X,ae,!1);I.addLocalFileAsync({localPath:Z,zipPath:Ie.dirname(E(Z)),zipName:k(Z)},X)}},b))})})},addLocalFolderPromise:function(w,b){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:w},b),(R,P)=>{R&&A(R),P&&I(this)})})},addFile:function(w,b,I,A){w=f(w);let R=x(w),P=R!=null;P||(R=new ly(i),R.entryName=w),R.comment=I||"";let E=typeof A=="object"&&A instanceof s.fs.Stats;E&&(R.header.time=A.mtime);var k=R.isDirectory?16:0;let L=R.isDirectory?16384:32768;return E?L|=4095&A.mode:typeof A=="number"?L|=4095&A:L|=R.isDirectory?493:420,k=(k|L<<16)>>>0,R.attr=k,R.setData(b),P||a.setEntry(R),R},getEntries:function(w){return a.password=w,a?a.entries:[]},getEntry:function(w){return x(w)},getEntryCount:function(){return a.getEntryCount()},forEach:function(w){return a.forEach(w)},extractEntryTo:function(w,b,I,A,R,P){A=Hn(!1,A),R=Hn(!1,R),I=Hn(!0,I),P=cf(R,P);var E=x(w);if(!E)throw Ae.Errors.NO_ENTRY();var k=l(E.entryName),L=u(b,P&&!E.isDirectory?P:I?k:Ie.basename(k));if(E.isDirectory){var B=a.getEntryChildren(E);return B.forEach(function(Z){if(Z.isDirectory)return;var ae=Z.getData();if(!ae)throw Ae.Errors.CANT_EXTRACT_FILE();var te=l(Z.entryName),le=u(b,I?te:Ie.basename(te));let de=R?Z.header.fileAttr:void 0;s.writeFileTo(le,ae,A,de)}),!0}var M=E.getData(a.password);if(!M)throw Ae.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(L)&&!A)throw Ae.Errors.CANT_OVERRIDE();let X=R?w.header.fileAttr:void 0;return s.writeFileTo(L,M,A,X),!0},test:function(w){if(!a)return!1;for(var b in a.entries)try{if(b.isDirectory)continue;var I=a.entries[b].getData(w);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(w,b,I,A){if(I=Hn(!1,I),A=cf(I,A),b=Hn(!1,b),!a)throw Ae.Errors.NO_ZIP();a.entries.forEach(function(R){var P=u(w,l(R.entryName));if(R.isDirectory){s.makeDir(P);return}var E=R.getData(A);if(!E)throw Ae.Errors.CANT_EXTRACT_FILE();let k=I?R.header.fileAttr:void 0;s.writeFileTo(P,E,b,k);try{s.fs.utimesSync(P,R.header.time,R.header.time)}catch{throw Ae.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(w,b,I,A){if(A=uy(b,I,A),I=Hn(!1,I),b=Hn(!1,b),!A)return new Promise((L,B)=>{this.extractAllToAsync(w,b,I,function(M){M?B(M):L(this)})});if(!a){A(Ae.Errors.NO_ZIP());return}w=Ie.resolve(w);let R=L=>u(w,Ie.normalize(l(L.entryName))),P=(L,B)=>new Error(L+': "'+B+'"'),E=[],k=[];a.entries.forEach(L=>{L.isDirectory?E.push(L):k.push(L)});for(let L of E){let B=R(L),M=I?L.header.fileAttr:void 0;try{s.makeDir(B),M&&s.fs.chmodSync(B,M),s.fs.utimesSync(B,L.header.time,L.header.time)}catch{A(P("Unable to create folder",B))}}k.reverse().reduce(function(L,B){return function(M){if(M)L(M);else{let X=Ie.normalize(l(B.entryName)),Z=u(w,X);B.getDataAsync(function(ae,te){if(te)L(te);else if(!ae)L(Ae.Errors.CANT_EXTRACT_FILE());else{let le=I?B.header.fileAttr:void 0;s.writeFileToAsync(Z,ae,b,le,function(de){de||L(P("Unable to write file",Z)),s.fs.utimes(Z,B.header.time,B.header.time,function(C){C?L(P("Unable to set times",Z)):L()})})}})}}},A)()},writeZip:function(w,b){if(arguments.length===1&&typeof w=="function"&&(b=w,w=""),!w&&i.filename&&(w=i.filename),!!w){var I=a.compressToBuffer();if(I){var A=s.writeFileTo(w,I,!0);typeof b=="function"&&b(A?null:new Error("failed"),"")}}},writeZipPromise:function(w,b){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},b);return new Promise((R,P)=>{!w&&i.filename&&(w=i.filename),w||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let k=L=>L?R(L):P("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(w,E,I,A,k)},P)})},toBufferPromise:function(){return new Promise((w,b)=>{a.toAsyncBuffer(w,b)})},toBuffer:function(w,b,I,A){return typeof w=="function"?(a.toAsyncBuffer(w,b,I,A),null):a.compressToBuffer()}}}});import{execFile as mb,spawn as wb,spawnSync as gD}from"node:child_process";import{promisify as _b}from"node:util";function Eb(t){if(process.platform!=="win32")return!1;if(k0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(k0,"").toLowerCase();return yb.has(n)}function C0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return Eb(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function lt(t,e=[],n={}){return wb(t,e,C0(t,n))}function P0(t,e=[],n={}){return bb(t,e,C0(t,n))}var yb,k0,bb,rn=at(()=>{"use strict";yb=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),k0=/\.(cmd|bat|ps1)$/i;bb=_b(mb)});var on=z((X3,hx)=>{"use strict";var ux=["nodebuffer","arraybuffer","fragments"],fx=typeof Blob<"u";fx&&ux.push("blob");hx.exports={BINARY_TYPES:ux,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:fx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var os=z((Q3,Wo)=>{"use strict";var{EMPTY_BUFFER:e1}=on(),ql=Buffer[Symbol.species];function t1(t,e){if(t.length===0)return e1;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let s=0;s<t.length;s++){let a=t[s];n.set(a,i),i+=a.length}return i<e?new ql(n.buffer,n.byteOffset,i):n}function xx(t,e,n,i,s){for(let a=0;a<s;a++)n[i+a]=t[a]^e[a&3]}function px(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function n1(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Hl(t){if(Hl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ql(t):ArrayBuffer.isView(t)?e=new ql(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Hl.readOnly=!1),e}Wo.exports={concat:t1,mask:xx,toArrayBuffer:n1,toBuffer:Hl,unmask:px};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=pe("bufferutil");Wo.exports.mask=function(e,n,i,s,a){a<48?xx(e,n,i,s,a):t.mask(e,n,i,s,a)},Wo.exports.unmask=function(e,n){e.length<32?px(e,n):t.unmask(e,n)}}catch{}});var _x=z((eN,mx)=>{"use strict";var gx=Symbol("kDone"),$l=Symbol("kRun"),jl=class{constructor(e){this[gx]=()=>{this.pending--,this[$l]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[$l]()}[$l](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[gx])}}};mx.exports=jl});var Jr=z((tN,vx)=>{"use strict";var as=pe("zlib"),yx=os(),r1=_x(),{kStatusCode:Ex}=on(),i1=Buffer[Symbol.species],s1=Buffer.from([0,0,255,255]),Vo=Symbol("permessage-deflate"),an=Symbol("total-length"),Vr=Symbol("callback"),Bn=Symbol("buffers"),Zr=Symbol("error"),Ko,Wl=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ko){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ko=new r1(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[Vr];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 a=+s;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let a=+s;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=a}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){Ko.add(s=>{this._decompress(e,n,(a,l)=>{s(),i(a,l)})})}compress(e,n,i){Ko.add(s=>{this._compress(e,n,(a,l)=>{s(),i(a,l)})})}_decompress(e,n,i){let s=this._isServer?"client":"server";if(!this._inflate){let a=`${s}_max_window_bits`,l=typeof this.params[a]!="number"?as.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=as.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[Vo]=this,this._inflate[an]=0,this._inflate[Bn]=[],this._inflate.on("error",a1),this._inflate.on("data",bx)}this._inflate[Vr]=i,this._inflate.write(e),n&&this._inflate.write(s1),this._inflate.flush(()=>{let a=this._inflate[Zr];if(a){this._inflate.close(),this._inflate=null,i(a);return}let l=yx.concat(this._inflate[Bn],this._inflate[an]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[an]=0,this._inflate[Bn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,l)})}_compress(e,n,i){let s=this._isServer?"server":"client";if(!this._deflate){let a=`${s}_max_window_bits`,l=typeof this.params[a]!="number"?as.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=as.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[an]=0,this._deflate[Bn]=[],this._deflate.on("data",o1)}this._deflate[Vr]=i,this._deflate.write(e),this._deflate.flush(as.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=yx.concat(this._deflate[Bn],this._deflate[an]);n&&(a=new i1(a.buffer,a.byteOffset,a.length-4)),this._deflate[Vr]=null,this._deflate[an]=0,this._deflate[Bn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};vx.exports=Wl;function o1(t){this[Bn].push(t),this[an]+=t.length}function bx(t){if(this[an]+=t.length,this[Vo]._maxPayload<1||this[an]<=this[Vo]._maxPayload){this[Bn].push(t);return}this[Zr]=new RangeError("Max payload size exceeded"),this[Zr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zr][Ex]=1009,this.removeListener("data",bx),this.reset()}function a1(t){if(this[Vo]._inflate=null,this[Zr]){this[Vr](this[Zr]);return}t[Ex]=1007,this[Vr](t)}});var Yr=z((nN,Zo)=>{"use strict";var{isUtf8:Sx}=pe("buffer"),{hasBlob:c1}=on(),l1=[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 d1(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Kl(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 u1(t){return c1&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Zo.exports={isBlob:u1,isValidStatusCode:d1,isValidUTF8:Kl,tokenChars:l1};if(Sx)Zo.exports.isValidUTF8=function(t){return t.length<24?Kl(t):Sx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=pe("utf-8-validate");Zo.exports.isValidUTF8=function(e){return e.length<32?Kl(e):t(e)}}catch{}});var Xl=z((rN,Px)=>{"use strict";var{Writable:f1}=pe("stream"),Ix=Jr(),{BINARY_TYPES:h1,EMPTY_BUFFER:Ax,kStatusCode:x1,kWebSocket:p1}=on(),{concat:Vl,toArrayBuffer:g1,unmask:m1}=os(),{isValidStatusCode:w1,isValidUTF8:Tx}=Yr(),Jo=Buffer[Symbol.species],yt=0,Rx=1,kx=2,Cx=3,Zl=4,Jl=5,Yo=6,Yl=class extends f1{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||h1[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[p1]=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=yt}_write(e,n,i){if(this._opcode===8&&this._state==yt)return i();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 Jo(i.buffer,i.byteOffset+e,i.length-e),new Jo(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 Jo(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 yt:this.getInfo(e);break;case Rx:this.getPayloadLength16(e);break;case kx:this.getPayloadLength64(e);break;case Cx:this.getMask();break;case Zl:this.getData(e);break;case Jl:case Yo: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[Ix.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=Rx:this._payloadLength===127?this._state=kx: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=Cx:this._state=Zl}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Zl}getData(e){let n=Ax;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&&m1(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Jl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Ix.extensionName].decompress(e,this._fin,(s,a)=>{if(s)return n(s);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(l);return}this._fragments.push(a)}this.dataMessage(n),this._state===yt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=yt;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=Vl(i,n):this._binaryType==="arraybuffer"?s=g1(Vl(i,n)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=yt):(this._state=Yo,setImmediate(()=>{this.emit("message",s,!0),this._state=yt,this.startLoop(e)}))}else{let s=Vl(i,n);if(!this._skipUTF8Validation&&!Tx(s)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===Jl||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=yt):(this._state=Yo,setImmediate(()=>{this.emit("message",s,!1),this._state=yt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ax),this.end();else{let i=e.readUInt16BE(0);if(!w1(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let s=new Jo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Tx(s)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(a);return}this._loop=!1,this.emit("conclude",i,s),this.end()}this._state=yt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=yt):(this._state=Yo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=yt,this.startLoop(n)}))}createError(e,n,i,s,a){this._loop=!1,this._errored=!0;let l=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(l,this.createError),l.code=a,l[x1]=s,l}};Px.exports=Yl});var td=z((sN,Ox)=>{"use strict";var{Duplex:iN}=pe("stream"),{randomFillSync:_1}=pe("crypto"),Dx=Jr(),{EMPTY_BUFFER:y1,kWebSocket:E1,NOOP:b1}=on(),{isBlob:Xr,isValidStatusCode:v1}=Yr(),{mask:Lx,toBuffer:sr}=os(),Et=Symbol("kByteLength"),S1=Buffer.alloc(4),Xo=8*1024,or,Qr=Xo,Lt=0,I1=1,A1=2,Ql=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=Lt,this.onerror=b1,this[E1]=void 0}static frame(e,n){let i,s=!1,a=2,l=!1;n.mask&&(i=n.maskBuffer||S1,n.generateMask?n.generateMask(i):(Qr===Xo&&(or===void 0&&(or=Buffer.alloc(Xo)),_1(or,0,Xo),Qr=0),i[0]=or[Qr++],i[1]=or[Qr++],i[2]=or[Qr++],i[3]=or[Qr++]),l=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||l)&&n[Et]!==void 0?u=n[Et]:(e=Buffer.from(e),u=e.length):(u=e.length,s=n.mask&&n.readOnly&&!l);let f=u;u>=65536?(a+=8,f=127):u>125&&(a+=2,f=126);let x=Buffer.allocUnsafe(s?u+a:a);return x[0]=n.fin?n.opcode|128:n.opcode,n.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)),n.mask?(x[1]|=128,x[a-4]=i[0],x[a-3]=i[1],x[a-2]=i[2],x[a-1]=i[3],l?[x,e]:s?(Lx(e,i,x,a,u),[x]):(Lx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,s){let a;if(e===void 0)a=y1;else{if(typeof e!="number"||!v1(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");a=Buffer.allocUnsafe(2+u),a.writeUInt16BE(e,0),typeof n=="string"?a.write(n,2):a.set(n,2)}}let l={[Et]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Lt?this.enqueue([this.dispatch,a,!1,l,s]):this.sendFrame(t.frame(a,l),s)}ping(e,n,i){let s,a;if(typeof e=="string"?(s=Buffer.byteLength(e),a=!1):Xr(e)?(s=e.size,a=!1):(e=sr(e),s=e.length,a=sr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[Et]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};Xr(e)?this._state!==Lt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==Lt?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}pong(e,n,i){let s,a;if(typeof e=="string"?(s=Buffer.byteLength(e),a=!1):Xr(e)?(s=e.size,a=!1):(e=sr(e),s=e.length,a=sr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[Et]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};Xr(e)?this._state!==Lt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==Lt?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,n,i){let s=this._extensions[Dx.extensionName],a=n.binary?2:1,l=n.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Xr(e)?(u=e.size,f=!1):(e=sr(e),u=e.length,f=sr.readOnly),this._firstFragment?(this._firstFragment=!1,l&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=u>=s._threshold),this._compress=l):(l=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[Et]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:f,rsv1:l};Xr(e)?this._state!==Lt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Lt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,s){this._bufferedBytes+=i[Et],this._state=A1,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(ed,this,u,s);return}this._bufferedBytes-=i[Et];let l=sr(a);n?this.dispatch(l,n,i,s):(this._state=Lt,this.sendFrame(t.frame(l,i),s),this.dequeue())}).catch(a=>{process.nextTick(T1,this,a,s)})}dispatch(e,n,i,s){if(!n){this.sendFrame(t.frame(e,i),s);return}let a=this._extensions[Dx.extensionName];this._bufferedBytes+=i[Et],this._state=I1,a.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");ed(this,f,s);return}this._bufferedBytes-=i[Et],this._state=Lt,i.readOnly=!1,this.sendFrame(t.frame(u,i),s),this.dequeue()})}dequeue(){for(;this._state===Lt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Et],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Et],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)}};Ox.exports=Ql;function ed(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let s=t._queue[i],a=s[s.length-1];typeof a=="function"&&a(e)}}function T1(t,e,n){ed(t,e,n),t.onerror(e)}});var Hx=z((oN,qx)=>{"use strict";var{kForOnEventAttribute:cs,kListener:nd}=on(),Nx=Symbol("kCode"),Mx=Symbol("kData"),Bx=Symbol("kError"),Fx=Symbol("kMessage"),zx=Symbol("kReason"),ei=Symbol("kTarget"),Ux=Symbol("kType"),Gx=Symbol("kWasClean"),cn=class{constructor(e){this[ei]=null,this[Ux]=e}get target(){return this[ei]}get type(){return this[Ux]}};Object.defineProperty(cn.prototype,"target",{enumerable:!0});Object.defineProperty(cn.prototype,"type",{enumerable:!0});var ar=class extends cn{constructor(e,n={}){super(e),this[Nx]=n.code===void 0?0:n.code,this[zx]=n.reason===void 0?"":n.reason,this[Gx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Nx]}get reason(){return this[zx]}get wasClean(){return this[Gx]}};Object.defineProperty(ar.prototype,"code",{enumerable:!0});Object.defineProperty(ar.prototype,"reason",{enumerable:!0});Object.defineProperty(ar.prototype,"wasClean",{enumerable:!0});var ti=class extends cn{constructor(e,n={}){super(e),this[Bx]=n.error===void 0?null:n.error,this[Fx]=n.message===void 0?"":n.message}get error(){return this[Bx]}get message(){return this[Fx]}};Object.defineProperty(ti.prototype,"error",{enumerable:!0});Object.defineProperty(ti.prototype,"message",{enumerable:!0});var ls=class extends cn{constructor(e,n={}){super(e),this[Mx]=n.data===void 0?null:n.data}get data(){return this[Mx]}};Object.defineProperty(ls.prototype,"data",{enumerable:!0});var R1={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[cs]&&s[nd]===e&&!s[cs])return;let i;if(t==="message")i=function(a,l){let u=new ls("message",{data:l?a:a.toString()});u[ei]=this,Qo(e,this,u)};else if(t==="close")i=function(a,l){let u=new ar("close",{code:a,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[ei]=this,Qo(e,this,u)};else if(t==="error")i=function(a){let l=new ti("error",{error:a,message:a.message});l[ei]=this,Qo(e,this,l)};else if(t==="open")i=function(){let a=new cn("open");a[ei]=this,Qo(e,this,a)};else return;i[cs]=!!n[cs],i[nd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[nd]===e&&!n[cs]){this.removeListener(t,n);break}}};qx.exports={CloseEvent:ar,ErrorEvent:ti,Event:cn,EventTarget:R1,MessageEvent:ls};function Qo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var ea=z((aN,$x)=>{"use strict";var{tokenChars:ds}=Yr();function Wt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function k1(t){let e=Object.create(null),n=Object.create(null),i=!1,s=!1,a=!1,l,u,f=-1,x=-1,m=-1,g=0;for(;g<t.length;g++)if(x=t.charCodeAt(g),l===void 0)if(m===-1&&ds[x]===1)f===-1&&(f=g);else if(g!==0&&(x===32||x===9))m===-1&&f!==-1&&(m=g);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);m===-1&&(m=g);let w=t.slice(f,m);x===44?(Wt(e,w,n),n=Object.create(null)):l=w,f=m=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);else if(u===void 0)if(m===-1&&ds[x]===1)f===-1&&(f=g);else if(x===32||x===9)m===-1&&f!==-1&&(m=g);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);m===-1&&(m=g),Wt(n,t.slice(f,m),!0),x===44&&(Wt(e,l,n),n=Object.create(null),l=void 0),f=m=-1}else if(x===61&&f!==-1&&m===-1)u=t.slice(f,g),f=m=-1;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(s){if(ds[x]!==1)throw new SyntaxError(`Unexpected character at index ${g}`);f===-1?f=g:i||(i=!0),s=!1}else if(a)if(ds[x]===1)f===-1&&(f=g);else if(x===34&&f!==-1)a=!1,m=g;else if(x===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(x===34&&t.charCodeAt(g-1)===61)a=!0;else if(m===-1&&ds[x]===1)f===-1&&(f=g);else if(f!==-1&&(x===32||x===9))m===-1&&(m=g);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);m===-1&&(m=g);let w=t.slice(f,m);i&&(w=w.replace(/\\/g,""),i=!1),Wt(n,u,w),x===44&&(Wt(e,l,n),n=Object.create(null),l=void 0),u=void 0,f=m=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);if(f===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=g);let v=t.slice(f,m);return l===void 0?Wt(e,v,n):(u===void 0?Wt(n,v,!0):i?Wt(n,u,v.replace(/\\/g,"")):Wt(n,u,v),Wt(e,l,n)),e}function C1(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 a=i[s];return Array.isArray(a)||(a=[a]),a.map(l=>l===!0?s:`${s}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}$x.exports={format:C1,parse:k1}});var ia=z((dN,np)=>{"use strict";var P1=pe("events"),D1=pe("https"),L1=pe("http"),Kx=pe("net"),O1=pe("tls"),{randomBytes:N1,createHash:M1}=pe("crypto"),{Duplex:cN,Readable:lN}=pe("stream"),{URL:rd}=pe("url"),Fn=Jr(),B1=Xl(),F1=td(),{isBlob:z1}=Yr(),{BINARY_TYPES:jx,CLOSE_TIMEOUT:U1,EMPTY_BUFFER:ta,GUID:G1,kForOnEventAttribute:id,kListener:q1,kStatusCode:H1,kWebSocket:Ke,NOOP:Vx}=on(),{EventTarget:{addEventListener:$1,removeEventListener:j1}}=Hx(),{format:W1,parse:K1}=ea(),{toBuffer:V1}=os(),Zx=Symbol("kAborted"),sd=[8,13],ln=["CONNECTING","OPEN","CLOSING","CLOSED"],Z1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,be=class t extends P1{constructor(e,n,i){super(),this._binaryType=jx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ta,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]),Jx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){jx.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 B1({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new F1(e,this._extensions,i.generateMask);this._receiver=s,this._sender=a,this._socket=e,s[Ke]=this,a[Ke]=this,e[Ke]=this,s.on("conclude",X1),s.on("drain",Q1),s.on("error",eI),s.on("message",tI),s.on("ping",nI),s.on("pong",rI),a.onerror=iI,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Qx),e.on("data",ra),e.on("end",ep),e.on("error",tp),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[Fn.extensionName]&&this._extensions[Fn.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){xt(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())}),Xx(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){od(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ta,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){od(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ta,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){od(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Fn.extensionName]||(s.compress=!1),this._sender.send(e||ta,s,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){xt(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:ln.indexOf("CONNECTING")});Object.defineProperty(be.prototype,"CONNECTING",{enumerable:!0,value:ln.indexOf("CONNECTING")});Object.defineProperty(be,"OPEN",{enumerable:!0,value:ln.indexOf("OPEN")});Object.defineProperty(be.prototype,"OPEN",{enumerable:!0,value:ln.indexOf("OPEN")});Object.defineProperty(be,"CLOSING",{enumerable:!0,value:ln.indexOf("CLOSING")});Object.defineProperty(be.prototype,"CLOSING",{enumerable:!0,value:ln.indexOf("CLOSING")});Object.defineProperty(be,"CLOSED",{enumerable:!0,value:ln.indexOf("CLOSED")});Object.defineProperty(be.prototype,"CLOSED",{enumerable:!0,value:ln.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[id])return e[q1];return null},set(e){for(let n of this.listeners(t))if(n[id]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[id]:!0})}})});be.prototype.addEventListener=$1;be.prototype.removeEventListener=j1;np.exports=be;function Jx(t,e,n,i){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:U1,protocolVersion:sd[1],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,!sd.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${sd.join(", ")})`);let a;if(e instanceof rd)a=e;else try{a=new rd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),t._url=a.href;let l=a.protocol==="wss:",u=a.protocol==="ws+unix:",f;if(a.protocol!=="ws:"&&!l&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!a.pathname?f="The URL's pathname is empty":a.hash&&(f="The URL contains a fragment identifier"),f){let I=new SyntaxError(f);if(t._redirects===0)throw I;na(t,I);return}let x=l?443:80,m=N1(16).toString("base64"),g=l?D1.request:L1.request,v=new Set,w;if(s.createConnection=s.createConnection||(l?Y1:J1),s.defaultPort=s.defaultPort||x,s.port=a.port||x,s.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},s.path=a.pathname+a.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Fn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=W1({[Fn.extensionName]:w.offer()})),n.length){for(let I of n){if(typeof I!="string"||!Z1.test(I)||v.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.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),(a.username||a.password)&&(s.auth=`${a.username}:${a.password}`),u){let I=s.path.split(":");s.socketPath=I[0],s.path=I[1]}let b;if(s.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=l,t._originalHostOrSocketPath=u?s.socketPath:a.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,R]of Object.entries(I))i.headers[A.toLowerCase()]=R}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!l)&&(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")),b=t._req=g(s),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=g(s);s.timeout&&b.on("timeout",()=>{xt(t,b,"Opening handshake has timed out")}),b.on("error",I=>{b===null||b[Zx]||(b=t._req=null,na(t,I))}),b.on("response",I=>{let A=I.headers.location,R=I.statusCode;if(A&&s.followRedirects&&R>=300&&R<400){if(++t._redirects>s.maxRedirects){xt(t,b,"Maximum redirects exceeded");return}b.abort();let P;try{P=new rd(A,e)}catch{let k=new SyntaxError(`Invalid URL: ${A}`);na(t,k);return}Jx(t,P,n,i)}else t.emit("unexpected-response",b,I)||xt(t,b,`Unexpected server response: ${I.statusCode}`)}),b.on("upgrade",(I,A,R)=>{if(t.emit("upgrade",I),t.readyState!==be.CONNECTING)return;b=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){xt(t,A,"Invalid Upgrade header");return}let E=M1("sha1").update(m+G1).digest("base64");if(I.headers["sec-websocket-accept"]!==E){xt(t,A,"Invalid Sec-WebSocket-Accept header");return}let k=I.headers["sec-websocket-protocol"],L;if(k!==void 0?v.size?v.has(k)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":v.size&&(L="Server sent no subprotocol"),L){xt(t,A,L);return}k&&(t._protocol=k);let B=I.headers["sec-websocket-extensions"];if(B!==void 0){if(!w){xt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=K1(B)}catch{xt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let X=Object.keys(M);if(X.length!==1||X[0]!==Fn.extensionName){xt(t,A,"Server indicated an extension that was not requested");return}try{w.accept(M[Fn.extensionName])}catch{xt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Fn.extensionName]=w}t.setSocket(A,R,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(b,t):b.end()}function na(t,e){t._readyState=be.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function J1(t){return t.path=t.socketPath,Kx.connect(t)}function Y1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Kx.isIP(t.host)?"":t.host),O1.connect(t)}function xt(t,e,n){t._readyState=be.CLOSING;let i=new Error(n);Error.captureStackTrace(i,xt),e.setHeader?(e[Zx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(na,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function od(t,e,n){if(e){let i=z1(e)?e.size:V1(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${ln[t.readyState]})`);process.nextTick(n,i)}}function X1(t,e){let n=this[Ke];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Ke]!==void 0&&(n._socket.removeListener("data",ra),process.nextTick(Yx,n._socket),t===1005?n.close():n.close(t,e))}function Q1(){let t=this[Ke];t.isPaused||t._socket.resume()}function eI(t){let e=this[Ke];e._socket[Ke]!==void 0&&(e._socket.removeListener("data",ra),process.nextTick(Yx,e._socket),e.close(t[H1])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Wx(){this[Ke].emitClose()}function tI(t,e){this[Ke].emit("message",t,e)}function nI(t){let e=this[Ke];e._autoPong&&e.pong(t,!this._isServer,Vx),e.emit("ping",t)}function rI(t){this[Ke].emit("pong",t)}function Yx(t){t.resume()}function iI(t){let e=this[Ke];e.readyState!==be.CLOSED&&(e.readyState===be.OPEN&&(e._readyState=be.CLOSING,Xx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Xx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Qx(){let t=this[Ke];if(this.removeListener("close",Qx),this.removeListener("data",ra),this.removeListener("end",ep),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[Ke]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Wx),t._receiver.on("finish",Wx))}function ra(t){this[Ke]._receiver.write(t)||this.pause()}function ep(){let t=this[Ke];t._readyState=be.CLOSING,t._receiver.end(),this.end()}function tp(){let t=this[Ke];this.removeListener("error",tp),this.on("error",Vx),t&&(t._readyState=be.CLOSING,this.destroy())}});var op=z((fN,sp)=>{"use strict";var uN=ia(),{Duplex:sI}=pe("stream");function rp(t){t.emit("close")}function oI(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ip(t){this.removeListener("error",ip),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function aI(t,e){let n=!0,i=new sI({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,l){let u=!l&&i._readableState.objectMode?a.toString():a;i.push(u)||t.pause()}),t.once("error",function(a){i.destroyed||(n=!1,i.destroy(a))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,a){if(t.readyState===t.CLOSED){a(s),process.nextTick(rp,i);return}let l=!1;t.once("error",function(f){l=!0,a(f)}),t.once("close",function(){l||a(s),process.nextTick(rp,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,a,l){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(s,a,l)});return}t.send(s,l)},i.on("end",oI),i.on("error",ip),i}sp.exports=aI});var ad=z((hN,ap)=>{"use strict";var{tokenChars:cI}=Yr();function lI(t){let e=new Set,n=-1,i=-1,s=0;for(s;s<t.length;s++){let l=t.charCodeAt(s);if(i===-1&&cI[l]===1)n===-1&&(n=s);else if(s!==0&&(l===32||l===9))i===-1&&n!==-1&&(i=s);else if(l===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 a=t.slice(n,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return e.add(a),e}ap.exports={parse:lI}});var xp=z((pN,hp)=>{"use strict";var dI=pe("events"),sa=pe("http"),{Duplex:xN}=pe("stream"),{createHash:uI}=pe("crypto"),cp=ea(),cr=Jr(),fI=ad(),hI=ia(),{CLOSE_TIMEOUT:xI,GUID:pI,kWebSocket:gI}=on(),mI=/^[+/0-9A-Za-z]{22}==$/,lp=0,dp=1,fp=2,cd=class extends dI{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:xI,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:hI,...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=sa.createServer((i,s)=>{let a=sa.STATUS_CODES[426];s.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),s.end(a)}),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=wI(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,a,l)=>{this.handleUpgrade(s,a,l,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=lp}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===fp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(us,this);return}if(e&&this.once("close",e),this._state!==dp)if(this._state=dp,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(us,this):process.nextTick(us,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{us(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",up);let a=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){lr(this,e,n,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){lr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!mI.test(a)){lr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){lr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){fs(n,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=fI.parse(f)}catch{lr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],g={};if(this.options.perMessageDeflate&&m!==void 0){let v=new cr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=cp.parse(m);w[cr.extensionName]&&(v.accept(w[cr.extensionName]),g[cr.extensionName]=v)}catch{lr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(w,b,I,A)=>{if(!w)return fs(n,b||401,I,A);this.completeUpgrade(g,a,x,e,n,i,s)});return}if(!this.options.verifyClient(v))return fs(n,401)}this.completeUpgrade(g,a,x,e,n,i,s)}completeUpgrade(e,n,i,s,a,l,u){if(!a.readable||!a.writable)return a.destroy();if(a[gI])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>lp)return fs(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${uI("sha1").update(n+pI).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let g=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;g&&(x.push(`Sec-WebSocket-Protocol: ${g}`),m._protocol=g)}if(e[cr.extensionName]){let g=e[cr.extensionName].params,v=cp.format({[cr.extensionName]:[g]});x.push(`Sec-WebSocket-Extensions: ${v}`),m._extensions=e}this.emit("headers",x,s),a.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",Ex),g.setSocket(c,l,{allowSynchronousEvents:this.options.allowSynchronousEvents,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(ns,this)})),u(g,o)}};vx.exports=zd;function Yv(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 ns(t){t._state=bx,t.emit("close")}function Ex(){this.destroy()}function rs(t,e,r,i){r=r||Wo.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} ${Wo.STATUS_CODES[e]}\r
17
- `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
16
+ `)),a.removeListener("error",up),m.setSocket(a,l,{allowSynchronousEvents:this.options.allowSynchronousEvents,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(us,this)})),u(m,s)}};hp.exports=cd;function wI(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 us(t){t._state=fp,t.emit("close")}function up(){this.destroy()}function fs(t,e,n,i){n=n||sa.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} ${sa.STATUS_CODES[e]}\r
17
+ `+Object.keys(i).map(s=>`${s}: ${i[s]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+r)}function nr(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let l=new Error(o);Error.captureStackTrace(l,nr),t.emit("wsClientError",l,r,e)}else rs(r,i,o,c)}});var Bx=ce(Fe=>{"use strict";var N=q;function q(t,e){t=t-314;let r=Zo(),i=r[t];if(q.LYvFVQ===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",y="";for(let S=0,_,v,I=0;v=f.charAt(I++);~v&&(_=S%4?_*64+v:v,S++%4)?g+=String.fromCharCode(255&_>>(-2*S&6)):0)v=x.indexOf(v);for(let S=0,_=g.length;S<_;S++)y+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(y)};q.qndrmt=o,q.bOqRaD={},q.LYvFVQ=!0}let c=r[0],l=t+c,u=q.bOqRaD[l];return u?i=u:(i=q.qndrmt(i),q.bOqRaD[l]=i),i}(function(t,e){let r=q,i=t();for(;;)try{if(-parseInt(r(1883))/1*(-parseInt(r(679))/2)+-parseInt(r(951))/3+-parseInt(r(777))/4+parseInt(r(380))/5+parseInt(r(1081))/6+-parseInt(r(1269))/7+-parseInt(r(761))/8===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Zo,987965);var sS=Object[N(600)+N(877)],oS=Object[N(1151)+"opertyNames"],Px=(t,e)=>function(){return t&&(e=(0,t[{gxzVq:function(c,l){return c(l)}}[N(1377)](oS,t)[0]])(t=0)),e},aS=(t,e)=>{let r=N,i={fOJTK:function(c,l,u,f){return c(l,u,f)}};for(var o in e)i[r(489)](sS,t,o,{get:e[o],enumerable:!0})};function cS(){return kx||(kx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function dS(){let t=N;return Tx||(Tx=[IDBCursor.prototype.advance,IDBCursor[t(337)+"e"][t(653)],IDBCursor[t(337)+"e"][t(653)+t(1241)+"ey"]])}function lS(t){let e=N,r={GMIyO:e(1483),dSPno:"error",CCiCa:function(o,c,l){return o(c,l)},jTQAz:function(o,c,l){return o(c,l)},XGsEP:e(1769),pGdrK:function(o,c){return o===c},RGjHN:e(705),HaLCx:function(o,c){return o(c)},pTjyW:function(o){return o()},ykhXo:function(o,c){return o===c},TpIak:e(1866),UjMtE:e(1576),EpZkC:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let l=e,u={miTDq:function(f,x){return r[q(886)](f,x)},ufTvD:function(f,x){return f(x)},JGJbC:function(f){return f()}};if(r[l(1037)](r[l(797)],r.UjMtE))return 0;{let f=()=>{let y=l;t[y(1193)+y(864)+y(1499)](r[y(1760)],x),t[y(1193)+y(864)+y(1499)](r[y(634)],g)},x=()=>{let y=l;u[y(1050)](o,u[y(1457)](zt,t.result)),u[y(1300)](f)},g=()=>{let y=l,S={MKYpr:function(_,v,I){return r[q(1112)](_,v,I)},ijIde:y(1069),HEhNn:function(_,v,I){return r[y(808)](_,v,I)},bnzjg:r[y(322)]};r.pGdrK(y(1534),r[y(1454)])?_0x3be0b4[y(474)]()[y(862)](()=>{let _=y,v=S[_(1087)](_0x3df022,S.ijIde,{message:this[_(594)+_(872)+_(1815)](_0x363b0f)});this[_(985)](_(1069),v);let I=S[_(944)](_0x42b005,S[_(778)],{reason:this["_formatE"+_(872)+_(1815)](_0x4b5826)});this[_(985)](_(1769),I)}):(r.HaLCx(c,t.error),r[y(1352)](f))};t[l(1509)+l(1559)](r.GMIyO,x),t[l(1509)+l(1559)](r[l(634)],g)}});return i.then(o=>{let c=e;r[c(1674)](o,IDBCursor)&&Hd[c(1680)](o,t)}).catch(()=>{}),Xo[e(1680)](i,t),i}function uS(t){let e=N,r={CdzKo:e(401),kKyOQ:e(1069),OcRUJ:e(1668),BdUnt:function(o,c){return o(c)},eoWcp:"AbortError",wLGkT:function(o){return o()}};if(Yo[e(451)](t))return;let i=new Promise((o,c)=>{let l=e,u={OamZM:r[l(1717)],UEJmT:r[l(408)],wjWRR:r[l(1353)],oedtW:function(y,S){return r[l(758)](y,S)},wEbfx:r.eoWcp,XJfEa:function(y){return r[l(900)](y)}},f=()=>{let y=l;t["removeEventListe"+y(1499)](u[y(1328)],x),t["removeEv"+y(864)+y(1499)](u.UEJmT,g),t[y(1193)+y(864)+y(1499)](u[y(1880)],g)},x=()=>{o(),f()},g=()=>{let y=l;u[y(1488)](c,t[y(1069)]||new DOMException(u[y(1237)],u[y(1237)])),u[y(738)](f)};t[l(1509)+l(1559)](r[l(1717)],x),t[l(1509)+l(1559)](r[l(408)],g),t[l(1509)+l(1559)](r[l(1353)],g)});Yo.set(t,i)}function Zo(){let t=["qKnPuKy","wNH5u0G","zxH0ugf5Bg8","yMjtzMe","r2DuseW","y2HHCKnVzgu","B21mCLK","C3vIyxjYyxK","zfvkz2K","yvjesfO","CMfmwuS","ufvwreK","qu1HrKG","qNjvrMi","igfYCMf5yNu","DgfNCvC","zcbLCNjVCI4","v0PTCw4","u1f1vNG","BKfvvuO","x2rPC3bHDgm","BNrbBMrvCgq","CMvHC29U","v2LUzg93","wuTUCMS","Dg9cExrLC0W","twLZC2LUzYa","CMr5su4","Cgu6ia","x2nSzwfYvgK","CMvXDwLYzwq","AxnrB1nnzxm","ysbTDxn0igi","D0TquuC","x2LZtM9Kzq","sKHzCgy","swLXqLO","wvbxrKy","mdaWmdaWmda","vhvUvgG","vgLTzw91Da","sLvKAg8","uwzzrKq","zw5JB2rLrNi","BuvyD2y","qxbeswO","vePrrvm","y3vYC29Y","rNPYre4","sxvVsxa","C3jJ","ChvSqMO","yNL0zu9MzNm","sxLtA1m","vMDtt3O","D3PoDLG","reXlzxe","sfbwBha","zcWG","sw9fzMO","wwzvzxC","twLktLe","x29UugfNzu4","t2vOs3i","zwfKzwu","r2XwEu0","AvbYzhe","uw5uA3m","u0rSEvm","De1HBMfNzxi","zeL1Exe","DKTtBuy","r1HJwgG","u3PNzKO","BxvHAMS","ufrIAMC","wvLTt2u","Dw5ZAwDUzwq","sKPuwK4","wuzut3C","qNHfCLm","zNjHBwvuExa","Bg9IywXty28","ALfTu08","ywjVCNq","ALv6Ae8","CMvZzxrfBMq","DgXmz20","qNLYwxO","zeDyuha","rxbAA0m","AxnszwfKEq","DgvZDa","uxvqzvu","zuTvrgK","C0PhwuG","C2v0","yLLRDMW","ChbL","BgLUzq","ihrYEsbYzwm","q0Xpu0ve","D3vPA1a","CMvKDwnL","Egfpww0","C2DPza","v1fnB2W","ugzty2W","BeHHBMrSzxi","vfH5tee","zMHcCxy","ALjtwvK","ChrVCG","B3bLBKrc","ALzitxi","CKXXAve","Cgf5Bg9Hzfq","B25VCgvU","Afrvugi","v3PZvvi","B25ozxr3B3i","z1vXtMm","DfLNq2S","ufrvyvO","x3bYzwzPEa","A2v5CW","A0jVvgu","s3niqMG","x2nYzwf0zvm","wxjWvhq","C3rHCNq","Dg9tDhjPBMC","vufQrui","q2r6s28","zgrjrcWGzgu","ywzgvw4","x2HHBMrSzvi","q0vUu20","Buv6zNC","u1LzB3q","ve1MAwu","BxnN","uxbjALe","v0LQzuu","wNP5CKC","svLYA2S","D09QwM0","B3L6EMe","CYbWyxjHBxm","zuvuzxq","qKLoDei","EMfQDLi","B3jRig9MzMW","AgfZt3DUuhi","EMDfALO","D1zfz1K","Cg1Jr3a","rujrtxG","AvzIt2G","DfjRAwG","yLz1BgK","DezLsgW","yw1LoIa","CMfUzg9T","Dgv4Dc9WBge","Cxzwv0q","qxbJqxG","z2v2y3O","Dgznqwm","uw5wtfa","B3bLBIa","D3m6lY8","DLrlvvG","BejVBfy","CffsB2K","Ae1Jshe","r01jEu8","DwT3zxK","ANDZsge","CgLUz09Uy2u","y3vYCMvUDeu","Dwjlzxa","B3fVy3K","x2XPC3rLBMu","DuP3ufK","y2XVC2u","yMfSrxzLBNq","Aw5L","yNL0zxm","BgDZEMm","sMrrz0m","mhW2FdeWFdK","AgvHzgvYCW","BvnTBxm","C2veC2u","z2v0qwXSs2u","y3j0Cuy","A1fowhe","vLPQEvG","zMLSDgvY","s01iv3G","y29UBMvJDgK","vNrLuha","zxHWB3j0CW","vLPRy0e","sgvsv2C","C2XPy2u","vM5TCLO","sKLKuuy","vgHcENe","sNH1wKu","rfzuA3q","zufQB1O","B2fuq3G","u1bdrhO","u1rIA2e","ruvyEgi","qu9vzKC","tNzlEMS","sxjJsNG","x3bPBMDmB3m","z2zXwg0","EfvZzuvUDG","rMrwreK","tgjTzuG","tufyx1jfvfi","A2v0ignVBNm","D2rArMm","uuvuDvC","s2nouei","CfjgAwS","ywDL","C3bSAwnL","B3nLrxzLBNq","uujVCM8","CwPRywK","wujoB24","rKLyAwq","AMnbs28","x2n1CNnVCKy","sKfyANa","uKPJrKu","ve5zqNO","vhbLtKi","yMfSu2nVCgu","BMDuAw1LCG","ENbPEhG","r1PVrwC","tKfusvzfx0u","rhzOvK4","yLfyB2K","s1r1tg4","wufQv2G","v3LqwNu","DxnLCKLW","zgj3svG","BMzqtfO","B2LUDfjLywm","rLDWsMW","ru9qyvy","uwzWzKO","uefeC1u","zw1LBNq","sNvWEg8","DxbKyxrLq3u","z2v0u3rVCMe","zfrXyM8","AxnAzxjV","qLrVExO","rfHOChG","BLbhyxm","yufvCfO","x2rItMfTzq","C29Tzq","zM9YrwfJAa","EffNAhm","Au9UDKm","ywDLu2HVDW","ywnRDxbfBMq","vfH4zxi","DuveAMm","B3jRzxjhBg8","AKHjD0m","zw5JB2rPBMC","AwTlC0u","CMzNDK8","B25TzxnZywC","sePeBgS","yM9L","C0XUvvO","C1zkve8","zNDZxZeUmc4","u3D0tMS","q0jYuwK","weLhENy","qMHyr3C","D2PxuLi","EvzewLy","DhvKwwu","mZq0mtrVtLveCuS","BMCGzMfPBgu","nhWYFdb8mxW","tg5bu1i","ign1CNnVCIa","yM9KEq","DgfYz2v0","mNW3FdeWFdu","u25lEwS","q291BNq","B2zMC2v0","Aw5JBhvKzxm","wvzSsuW","ExvcvLa","Du1cENi","id4G","weDZrva","sLvkC0e","Cgjry0e","DvnOA1K","Cgf5Bg9Hza","DhLWzq","DgLTzw91Da","DhjPBq","wLfcCgK","tw5wDfm","y2Hcre8","z2v0q3vYC28","sunewuG","EhrhDxy","t0DtBNy","ChjVDg90Exa","BNDfq3O","z09dA0q","wKLfyNy","yvnVBxG","DxrMofDYAxq","B2LXEey","uKP2AfC","AvnQv1a","z2v0q3vYCMu","sNnhBwu","B25fCNjVCG","rgvKAwnHDgu","wK51z3y","EhvSthO","sxjgt2K","B1PntuW","B25SAw5L","DLHAwLu","tfbqB0u","vuHVAfa","rgrzAeu","CgfNzxnOB3C","thPyshO","zMzMzG","vKf3rK0","EunVy3i","zM9Yy2u","quPbA3G","BgvrDNi","C0Xf","yKjNENi","BgvY","zwnVBM5Ly3q","Dxnly0W","DMvUDa","DxDRAvy","C0zArwu","r25Ovge","Dw5RBM93BIa","zgzUseS","wfjADem","u0rdAxa","otG2mJi4mhrdzhbuvW","C2v0q3vYC28","AxmGDw5Kzwy","CgfYC2u","sujiCe0","CKPmBvG","rKDAr0S","DLLqEvy","uhzIq2i","uuLLrLC","BwLUAvbYB2C","vvDiv3u","ueDzD0S","tMT1D0O","x2TLEvbHDgG","BKXPBMu","vMrrtue","uhvXz2u","tvzrEKi","CMvJB25Uzwm","Dgfzswq","y29TCgXLDgu","vxLWBhK","EKrxC24","tNbXC3i","wxLRwLu","AgfUz2u","DunwtLu","A0T5t1e","t1njswC","AhfYzNq","yNvMzMvYzwq","BwvZC2fNzv8","uLritvi","CMvQzwn0","AwrI","CfDnthK","u2HHCMvKv28","vw5Oyw5KBgu","AhLpyMK","u3LIt0W","C3nHz2vfDMu","BwLUzW","x2rLC3rYB3K","teLywuO","A1n0yxr1C0m","rwHQCfO","Bg9NsurozxC","t1zTqMm","zKLkuLa","B25LCNjVCG","v0HfzKm","yw5Nzq","ugL0zha","D0LMAu0","u0LKwMm","B1ftqLC","Dfv2ueO","Aw9UvgLTzw8","B25tDgfYDfi","u1fzzve","qLvXs2W","y3jLyxrLt2i","Aw5Lza","y2HnyxHdB3u","BMfTzq","FdL8mhWZFdq","rwv6whC","wNnVu3O","qu1YueG","yw5Hz2vY","AgfZ","Dxvly28","CMvHzhDYAxq","tfzRvgi","x29Uq2XVC2u","Ae1LC3nHz2u","zfDVCMTLCKC","wKXRqNC","AuLftNi","zKLZthO","DfDKq0m","C0nWz0C","BgLZDgvUtMu","rufJqKi","ChPIte4","y3vYC29Yx24","AuXeyKy","rLfOANC","CMPzuem","yMjyvM8","Aw5PDcbrB1m","Dhzmqui","x3vYBa","CMvZB2X2zq","A3bIB3m","zeLYy3q","CgXLyxnLiha","r3rkDNa","AwHntMq","zxfKD28","yMLUCw0","x2HHBMrSzu8","B25XtwS","EvzJsxC","ywXPzcb1CMW","t1fvrfe","q25bAgm","s2vQu0K","zK9kveS","ue9JANa","uhvrree","x0vysvnu","DgfIyxnL","sfnusfm","vvflzwK","x3bPBMDqB24","x3DHAxq","uxvLDwu","BwLetgy","veLwD20","qwHlB2u","v2Xhwfy","wMzgt1i","ywTAwLi","Fdr8mNWZFdu","Dhj1y3rVCIa","sgLQsum","yxLYrfu","AfjKt0i","qMvUqwO","x2HHBMrSzva","tvDnswO","B3bUrgm","CM9YrxzLBNq","DLn5z2e","ywnRx2LK","tfzwr2W","A1v0u1O","Ec1TC2CTy3u","uuTiDNO","EvjyzeC","zgvS","A1HMtuC","rw9Ot1a","Ec1TC2CTCw8","y2LryNe","vMLvDwe","CMvJzwL2zwq","Cg9W","zxH0zw5ZAw8","yw1Lu3bHy2u","Cgf5Bg9Hzeu","BMCGB3iGyw4","wKDbrxa","uLfyCgu","B2zMBgLUzq","rNbYC3O","C3rVCMu","vwvsDxG","uwHptue","C211yMy","CNzHBfzHBhu","D3jPDgvvAw4","EwnrywG","tfDeAfi","BuT2Dxe","yMLUza","twHiDg8","BuLuDKm","D0HKC3y","ALDZA0W","Dgv4DfbHEwW","rKLtDvy","CgHRzNC","A3PewvK","zvvqvgS","C3bSAxq","DxbhrwC","x3fVC0rc","DKDPs04","BMXkv1e","wwjqCLO","u3HwuwS","mNWWFdr8m3W","qNHZzMC","yNvMzMvY","zeTdsva","BMDLza","AvP3Bwy","zxrxB3jRq2G","qLveDhy","Bujpte0","zhzXwha","ENnUC0G","C2vUzf9Hy2S","C2vYDMLJzs0","Aw5KzxG","DMvY","vM1yseC","uhnUvwK","vvbrwey","B3zAExe","x2jPBMfYEvq","vu1OvxG","CMDUEfe","su5tvefova","B3nLza","EMjsAu4","l3DZl3yY","zwDhCu0","ELLqwgW","zw5HyMXLuw8","q3vZDg9Tq2W","x2zVCM1HDeu","uvbAugu","C2vUza","y0DXsKS","Dxrjza","DKvKC2i","zgvMAw5Luhi","z2u6ia","qvvNsMm","CeT2rKm","r1rcvKS","ywnRtxnNswq","sNzszeq","A0T5u2C","wurNA24","rNfnsxG","u3Lyyum","zw50zwqGDhK","qxjvy2u","qKrdrfm","zgrdEeK","t21wugy","CvbJCva","zxjYtxnN","zKftBey","u1P5tvG","C0nVDw50zxi","t1DUufG","BxjpuKe","AwDHDg9Yt24","yxbWBgLJyxq","y0zADLm","zxjFywnRx20","zMvY","z29PBMCGyxC","x1fVu01HBMe","rfzVBue","y09Wzw4","quXm","wMzfCge","zfnqBM8","yuHLCwe","DxriteC","CgLsC2m","B25mAw5L","r1jUBeG","uurhwfq","wK5gt0W","C1vvvwG","EhrrDwC","B2nRzxq","AvnYqK0","BeTdq1m","Ehf5y2m","BKTtCwm","CM92AwrLige","ywnOzwq","B3vUDa","A3rysNC","y29UDgLUDwu","BMrWB2LUDca","y29UBMvJDa","u0DVqNa","DhjPzxm","DgLUzYbZzxi","AxDAvMO","zNLgCue","Dw5KzwzPBMu","Aw5KzxHpzG","uwveCwe","vgfN","z2v0qwXS","tKDFrvjst1i","uMvHzcbWyxm","zxjHDg9Y","EvjLy29UBMu","x3nLCuLK","qxjVCNe","zM9pEM0","y2nSuuq","svrHv24","A2nqBwO","Aw1LCYbPBIa","CNLmyNm","tLPKzKK","ndbsz3vIEei","tM9Tvu0","vNnsAg8","zhDSz2i","x2LUAxrqCM8","svf4sKm","uKHJB3u","BgfPD3q","CNfMAKe","u2Pbq0W","Eu5YuLy","vvDsBMS","y1bLzwG","qwXpvgi","t2HOrNC","ELzgCfe","EsbJBg9Zzwq","x3nVy2TLDa","zNvUy3rPB24","r1jcCLK","B25dBg9Zzq","x2LUDgvYDMe","yujQvM8","v0nhqMG","yuvPC1y","rKLmrv9ot1q","rKfly3q","zxbSD2m","x2DLDeLUDgu","Cfzzwum","DMLJzuLeig8","zNrduLm","C29YDa","ALbyywe","CMvHzhLtDge","ELDKBhq","svHkDfq","qxDjrw4","lcbxzwjtB2m","BMrLEa","y29UBMvJDfm","zxq9DxrMltG","qLLzuM0","ALfTEhO","r3rHCeW","B2zM","BwDUu1m","DKjMqNq","DhDVCMTdAge","m3W1Fdr8mNW","rMzNvwC","ENn1uei","y3jLyxrLrxi","y3vYDMfSDwu","y2XVC2uSihC","Bgrdv3q","Bg93","BwvZC2fNzq","ihzHBgLKihm","wePMrwe","CMfTugfYyw0","DKXIEfG","wxLiwgq","x3bYB3rVy28","x2DLBMvYyxq","x2nVBM5Ly3q","EwzdzNe","wwPwA04","Cg9PBNrdB24","thnAA1e","s1DXrem","s29LrMy","tMDHEKC","zufJAW","ALLgq1i","te94CeW","q29Kzq","D05uBvi","AxnrB1nby2S","qMrvBNq","zNjVBunOyxi","EePIBwi","odeXndCXmKjutwTJsG","CNnVCL9Uyw0","BwvKAwf0zwW","BgLTAxq","Dgv4Dc9Qyxy","CfzQsKK","reTxBMO","DwPWCNC","Efrks3u","zNrYr2q","u093yLi","vMXfAue","rNzozNu","vfbRu2W","s1rQuhK","s3PLv3i","mJy0ntK1nMnrzK5dCG","yM56AMC","vejUug8","x3bPBMC","x2fKzfDZtgK","wuzqt28","Aw9U","tKfTwK4","sefvveu","DxbNCMfKzw4","sfbnquu","DNLiBMm","y3vYCMvUDeK","lcbOB3n0BMe","vg9OA2u","zgHqzgq","rhPUs2G","C2PpAfa","wMr6uLK","yxrLq291BNq","vhbjywS","EwHjr04","tw1fCva","y2vZC0HHBMq","B3HRzMy","Dhztyvi","vg5wr3q","x3jLywr5q2W","C2jtruG","zxreu3e","vxjyvwK","ALrrqxO","ywDLrxzLBNq","tLbAvLa","qM1jDLO","Dg9oDw1Izxi","yMXVy2TLza","CwjjvK0","zgf0yq","sw5tzeS","BenHDfO","y1LPvLK","ywXSzwqGBxu","EeHeCeG","zwn0","zLDbCgG","DMfSDwu","DufNBwy","AfzdA3y","tfvnu3y","CMvWBgfJzq","Cvr6A1u","rLDt","s1HSAgm","BM5Ly3q","B3bLBG","vw5PBxbSzw0","zgvSzxrLrge","qvH6wxO","Cg9PBNrbBMq","DeLK","DKHJreK","vxbKyxrLq28","BNDcAum","x2vUzhbVAw4","x2LZv29YA2u","yufMBeu","rNziruq","rKPZz3e","x3DZsw5ZDge","AMzfDMq","zvvYBa","DffSt3i","reiGzMfPBgu","vfPdCNC","Aw9Ul2PZB24","AM16DLC","C0PxuuK","Dg9Y","q0nMvvK","DwzVEK0","BMrWB2LUDfq","CfjeBge","yxnYu2K","lcbTyxGGCMu","DgHLBG","CevyEwW","zw50tgLZDgu","AxvKvLO","igzPzwXKoIa","yMLUyxj5vhK","v2vMu2e","q3vZDg9Trxi","twfJvu4","wuz4zhG","CNjVCK1LC3m","BvbgBNq","C1vtDK8","x2n1CNnVCK0","B2nRzxrtDwm","B3bLCNr5","rNjVBNrPzxi","rxzLBNq","yw51Ce1LC3m","zejTy1y","BIWGAg9ZDg4","tg5tzNe","zLfZzxq","AxHjtxe","sgfmq3G","Dg9hzw5LCMe","ExbL","qK13q20","y3jLyxrLuMu","z0vgtvK","uxnMBw0","Ahnlsu8","DwriB0K","BuDgu2q","zxjFCw9Z","Bwu6ia","DxrVuMvJB24","C2vYDMvYvgK","D0XhA1q","BxnNsuq","zMLSzw5HBwu","y2fSBa","yxnZAwDU","r2Tpr1G","BLzwrgK","A2Lwyw0","zgHgqxq","Dw1Qrwm","D3nZoI8V","AwfTzMm","AxnbCNjHEq","EwHuD0y","C21Krfm","BwLZzq","DeLUDgvYy2u","v2vIu29JA2u","sNj1C1C","sLflsuO","vgnnseO","CunbA3y","zNjVBuHHC2G","q1fUrfa","C2fNzq","ywzgyxm","EvDoD0m","B3jL","x3jLy29UBMu","qMvns3e","yKfuqwu","yuHOu2u","ChvZAa","zvjfuK4","zgriwMS","ChnIq2m","zxf1ywXZ","CvLSu3i","zg9Uzq","CgXQCfe","CgLYy1C","AhHVD3a","CLL0y2G","shnSDuu","sevOtM4","ywnRpwzYB24","wgHfthq","BKrTqNO","uKrMCwm","FdH8mxW3","BLrJrxq","mtiWmdmZoxLjsMDpAG","CgLUz0LUDgu","s2zqvMK","te94AK8","wgrVzxm","DfvUuNG","rvPVAgu","AvjUs0i","rNvrBgS","sMnbCxa","BfrPBwvVDxq","y2HLy2TdDxi","zw50","ywrKq291BNq","wwvruwu","wezHDvq","zv9ZDwnJzxm","qvnwswS","C1bXyvi","EfrfC0e","uvnbqvi","ue5UvNC","u0jpvxi","C2vYDMLJzq","B25pCgvU","uw9JCxi","ALnUELu","z1zhtuq","yuzvzxq","tuHdEwW","A2vAuhC","AwXLtMfTzq","ihrPBwvVDxq","ignVzgu6ia","zw1PDa","DMvYC2LVBG","y3vYC29YlNm","CMvUDevUzha","CNzHBa","tLHlweW","zxjFBxnNAwq","y2HnyxHuCMK","r2rTr28","uNrRuvu","CvHQtw4","rhnZD0S","yLHLuLm","v3LIC2K","zxjFCw9Zx2e","B3rRCeO","tM5Nwg4","twvZC2fNzuu","ywDlsfC","D3zouM8","y29UDgv4Da","wvrQqNu","EhnWEfq","Bhm6ia","BNruCMLLC0m","D3r5vfO","B3jLtMfTzxm","CMv0CNLdB3u","CMjlqK0","DwXJvgu","sKLHsva","AxnFywnR","rxjYB3jdB2q","AxbYChK","rNvuzNq","CM92AwrLigi","wfniENK","t2jQzwn0","BMfowwG","y2HLy2Tszwe","r3rsCLy","uLjpuG","tKPTq1G","reXvu1a","t2jMBNG","igzHAwWSig0","yuPeswy","CeviEu8","yxKSihrYEsa","C3rYAw5N","zw9UBwi","zKXyAMy","EwTOwg8","u29MwMy","u1bSB1e","rLjptLrjrvi","z296DLa","qvzOqNe","qw9qz0W","uwrLvuy","rg5qqvq","tg9NsurozxC","B3v0sw50zxi","wg9hA2e","y29UBMvJDeu","BwLurhe","Bgjszwq","zvPWEKe","EwTftNy","ywrKt25L","AevYCM9Yrxy","zw5KCg9PBNq","ywDLsgLKzq","r3bLz3a","v21xzee","CxLuBNu","uKjzv2C","z2v0sxrLBq","C3jfBge","uuDXAKW","BK5MuwO","uu56r0C","CgLUz0XVC3m","rwfzwuW","zxjYB3i","Cu5cAKm","uu54Evy","yxv0B21HDgK","y2juy0K","tg9Nsuq","zwrPyxrLBhK","Au5sEKu","ExbPA0C","y3vZDg9Tshq","qKjuAvm","u0niAw4","mteZmJeWnJrRzxnkA3m","rgXRtgW","A2f3EwO","t1nqvLa","y3ruAw1LB3u","AM9PBG","tuTzChi","uhHLuw0","y29UBMvJDca","A0PXu2O","x2n1CNnVCK4","tfnPC3C","weTQuKm","CgvSD0C","uwXgEgm","B0fsCee","BMv4DcGPigm","BgndzKi","ihrVihjLDhi","B2fK","A3rkt1O","Cw9RDLC","z3PQqvC","EeHIv2y","y29Kzq","zwvKzwq","vNvUtKC","BK9LBNK","wfDMwhC","v1fXs1y","x2rYB3bhBg8","q0nPq2e","qw1VDw50","BezSDxnO","AxnmB25N","uxrUwMi","q0Xpu0LorW","C2v0y3vYC28","D05rtwq","CKLiv2W","m3W1","DhbizwfKzxi","EgTPCNm","DwTeDee","wNrkyLe","zNjVBNrPzxi","BhDvyMm","BwvZC2fNztO","s3LOvxK","CMvTB3zLq2G","C05ezLa","ywXSB2nvBNm","vwzzqMG","x2LZqNjVD3m","C0DvB0y","zgvIDwC","rLnlA0e","DK5yuKC","suTyAMC","BwLcAxq","ihrPBwvZ","mNW1","wufRzKW","u294uK8","u2vYDMLJzvC","y2uGBM90igK","icSG","A2v5","Ae9Wzw5fDMu","qNvTqKe","z2v0t3DUuhi","AefJA01LC3m","zw5NDgG","uMvJB25Uzwm","C0XPC3rLBMu","AgP1CM0","BMvJDa","yxjYyxLIDwy","x29UrxjYB3i","zvHfAKW","twneANa","y1PyuLy","EgHnzMS","ywr1zva","B25nzxnZywC","Dwvuwwe","zw9TB0m","yLLYwgy","B25szwnLAxy","C2v0sxrLBq","D2LSBfjLy28","ALnIBMu","y2XLyxi","ru1ytg4","ywPjB1q","qurwwxq","uvPWyLe","veHQyKG","vMjtB0m","uxvmzgy","z3ryz2W","ywnRx2nVzgu","y2XesK0","u1bJshG","x2LUAxrhBg8","C2nYAxb0","CKDMtwW","tg9JAW","ywXty29Wzq","ENfitwW","ihjLy29UBMu","tMfTzq","CMvTB3zLrxy","CNnVCKzPBgu","vgHjwwO","shrhrKS","s0DTsNG","x2rLyNvN","AKfMBLa","DNv4zwm","ywzL","C3rYAw5NAwy","uhfYr0m","zNjVBu51Bwi","qvDYtxK","wgnjB3i","C0jf","zMzmAw5L","C2HPzNq","zgLZCgf0y2G","Cw53Dhm","Bg9N","Dev2zw50","tePLENi","uNDytfG","t0rrCgO","BNvTyMvY","tuPWuMi","vNjLtMW","thz3qNu","B09KAxC","CMvHzfvjBNq","CMvRzxC","x29WDgLVBNm","zxjYtM8","CfrPrfy","ru9ZCMi","yvb4C3K","AwLPzeG","x194x21Zz18","ExL6Ceq","yNL0zuXLBMC","tw9KDwXL","BKn3AeW","zfPICNi","DcbSAw1PDa","D0vIzNG","Cw9Z","txvrwuS","zxj2AwnL","uhjPBwfYEuS","v0L6wui","x0rctMfTzq","zNjVBuj5Dgu","qvPlBwq","CgLUz19VBMm","tgz2D0u","DMzeBxi","q2fnBxO","CuPZDgS","DKHsCwy","Au1TquW","B2jQzwn0u3q","x2LZtwLUAvq","EuLzDw8","qKnOruS","zhPxuK4","yK1gt3i","ihzHBgLKigq","vNntC2i","CKXICMK","DMvYC2LVBMm","uhLiu1O","ug16seW","q2zMvuG","su9fuKC","yxnL","CKnSCMK","mtaZodu3mtHMDMDUy0K","BwvY","B3r6sMG","BNf5wMS","DhjPzxmGCMu","A2Lvzve","zfzqAK8","z1rPBwvVDxq","x19LC01Vzhu","EuvTrLy","yMrFzgLK","vNL2A2e","yNf5AxO","ELnLAKq","wK9jsKi","x29UtwvZC2e","u0rOywC","u2zLwKi","FdH8mxW2","rvjst1i","CMLLC0nVDw4","D2fZq2XLyw4","y3jLyxrLq2W","t1bgq1q","BMnVzgLUzW","zxmGCMvHy2G","Ef9MCM9UDgK","BffbBgO","AMfbvMK","v2DmAxa","qvblCxe","sKDkyKm","s2DZz2K","y3jLyxrLtwu","wMDnquW","ue1HAwq","zvrpCLy","zwf2tg8","x3nLBMrby2S","Dw50","A3z0r3C","mdaWma","DxjS","B3jNEMO","A1bzAKi","CMvZzxrdB3u","ENfftKy","rgDhy08","u2Lyrhm","qvDVwKi","zw5fDMvUDa","CKfcr0W","y291BNq","mhWZFdf8nhW","q09otKvdveK","thfeDNy","yNLL","EvDsAMS","AML5rgW","t2fTwK0","z2vY","y3r4","Ee90z0K","AxzrzMm","zK1IEK4","Bwv0Ag9K","x3jLBw92zvC","BwfW","B25tDg9Wsw0","Avv3rva","q1PlB1q","y2XkDeO","y3jLyxrLt3a","yuP1rKK","Dg9VigXHCMC","t1bftG","D2fUsxm","yMLUyxj5","AgTJzvq","tuvtu0fhrv8","tvHiq2K","x25HDMLNyxq","CxH5wNu","CfrQEvC","t2nsvuO","ig1LC3nHz2u","v2vPEgLUsLm","y3jLyxrLrwW","z2v0s2v5","shPNEeW","t01Lsxe","Ee5hyxa","CM92AwrLihC","DgLTzw91DcW","y2XVC2veqG","zNjVBujPDhm","x2LZsw5PDa","teHXChO","yw1htfC","rM1OEw8","tvHOvhy","EM1oBLO","t1Lfwwq","AgLNAa","ufHWCMm","swnbD24","vvrPAKK","AMTXC1q","z3H6vNe","yxbWzw5Kq2G","wKTdqwC","CMvHzg9UBhK","Ec11C2uT","DhHkDu8","BMnLq2XVC2u","CfrXBLy","ALvjvu0","wu5KDgO","yKvoEfy","yw5ZzM9YBvq","Dg9cExrLC0i","x2nSzwfYugK","EhrLzNC","AwXK","EgrhvKG","zK1ss2K","CgfNzwHPzgu","Ahr0Chm6","CMTLCKDSB2i","BgzPrg0","CgvYC2LZDgu","Afz0wMq","sNnOvwW","B25Uzwn0Aw4","zMLUza","ywX3yxLZ","AxjLza","Ew5Kru8","BgvUz3rO","rMPbre4","CeHlCg8","rgDiwNm","C3zHuwu","EgrVCxy","rw94AeO","zfrxrKS","yMfJA3vWigu","y2f0y2G","uxz4y3e","B3jpBMXPBMu","y1r2we4","sLnptLa","z2vjBMzVu3K","sefuAeu","sK9usee","Aw50zwDLCIa","nNWYFdD8oxW","tvviBwm","zgvJB2rLzey","thDbu3u","sgLgB3G","wfrfr0S","D24GCMvHC28","suvtx0vsuK8","C3rLBMvYCW","x29Ut3bLBG","wKXjDwy","B2XKvMvYC2K","r2XZD0W","ChjVDg9JB2W","BLfwru4","zeTNzKK","CuHVBK0","tuLSwKi","ExvICLi","wezjuuu","Cvvtsgu","u1vvBeO","EKzRuLq","BeTjsKG","z2vtEw5J","vMD3wvi","AhPiwue","AMfIz20","rw11re0","uKDQse4","u2vXsuq","B1njBfq","DwzuDKq","EuXKq0S","zMLN","y29SBM8","Dg9mB3DLCKm","A2LZrNO","zw5XDwv1zq","ywXS","Bwf4tg9ZC0m","uxjeyKC","AwfyC0y","y2Pluhi","uhjuCue","ENzcrwG","tvLRreC","Dg9iyxnO","BgLUzw5V","v0zNy2O","AvP3D0i","wuHAzxm","r1bXBxq","zunHAgW","q09oveLovuu","DhjHBNnHy3q","ufzTq1q","x2LUAxq","C3vJy2vZCW","zg5KvMi","zgLZywjSzue","s213yMm","EeXWuxm","B2vKDfC","BNrLCG","x2LZtwLUAvC","wMXyvhu","CgjICdi","yxbWBhK","ruzlwMS","t3bLBKv2zw4","wNDSwwK","BM9mDuG","AgvKtwf4uMu","BMvY","AenSB3nLrxy","vuHVBNq","AwPJBfO","zfPLtw8","A2Tqr1O","s3v5Dxq","yxrHlcbKyxq","DM5pr2q","tuvxBhm","ywrKrxzLBNq","swrRvxq","q29UzMLN","y2HwD1q","ihn1y2nLC3m","q21uwKi","z2Lzzvi","zMX1C2HfEha","C3vIC3rYAw4","BgPWC3y","y29UC3rYDwm","zw5HyMXLqxu","wgv6C2e","vK9PvxK","zKnxEMG","DMfS","zwvttey","zMn5BuC","yNLxEMO","y29Uy2f0","wwTczwS","D1Lorum","sxbjDhy","DgHHBIbSB2m","Bwf4uMv0CMK","sKTiCMq","EMv5B3m","B3HPuuO","CMfTzq","B1PpELq","CKjzB0C","u2TPCcbWyxm","Chv0","yuvrq0O","shjRuxa","sgLyv0O","zK1OBNK","z2v0","tLzwvLC","BNrfBMrWB2K","B3D1vgm","AhbHq0W","x3DZ","BM93","veD4D2e","u3rYyxrLz3K","rvrkquC","D2LOt3O","quLUB1q","wu13CvK","tgLZDgvUzxi","B25JBg9Zzq","BunMCvy","zgvSzxrL","ywnR","wwfKzfu","uwrysKC","svvfCgO","r2z4AMG","s1jLq0W","DNHrDva","zv90Aw1LB3u","x21LC3nHz2u","x2rPC2nVBM4","yw1L","zvnNs2K","AgvHzgvY","t0veqMC","x21PBMLoyxy","AKXRq3e","x3bHDgHlzxK","DerLyNC","yxnJCMLWDa","Ahn1Dgq","rhLLAfG"];return Zo=function(){return t},Zo()}function fS(t){Qo={yLdCK:function(i,o){return i(o)}}[N(1458)](t,Qo)}function hS(t){let e=N,r={vBfBt:function(i,o){return i(o)},FvNfu:"AbortError",nAUUJ:function(i){return i()},xQghs:e(1069),DlkLl:e(1668),RJcFE:function(i,o){return i==o},CQnDP:"wss://",PsnUi:e(1755),BChEK:function(i,o){return i===o},mSmms:e(1549),tQlOr:function(i,o){return i(o)},GdmGo:function(i,o){return i===o},Uyply:function(i,o){return i in o},OehKr:e(1253)+e(1011),VhSnV:"kkPGZ"};if(r[e(993)](t,IDBDatabase[e(337)+"e"]["transact"+e(783)])&&!r[e(402)](r[e(1647)],IDBTransaction[e(337)+"e"])){if(r.BChEK(e(1504),r.VhSnV))return function(i,...o){let c=e;if(c(314)!=="pYlHQ"){let l=t[c(903)](r[c(726)](is,this),i,...o);return Ud[c(1680)](l,i[c(711)]?i.sort():[i]),r[c(726)](zt,l)}else return this[c(1764)+c(858)+c(1289)+"t"]=1,this[c(789)+"ndex"]++,this.endpoints[this[c(789)+"ndex"]]};{let i={wdZFc:eFUDDu[e(1859)]},o=()=>{let u=e;_0x61df75["removeEventListe"+u(1499)](u(401),c),_0x1847b2[u(1193)+"entListe"+u(1499)](i[u(1811)],l),_0x48548d["removeEventListe"+u(1499)](u(1668),l)},c=()=>{_0x31a7f0(),o()},l=()=>{let u=e;_0x3bb215(_0x41ddb1[u(1069)]||new _0x529150(eFUDDu[u(773)],eFUDDu[u(773)])),eFUDDu.nAUUJ(o)};_0x25fd00[e(1509)+e(1559)](e(401),c),_0x5bc8db[e(1509)+e(1559)](eFUDDu.xQghs,l),_0xa3cb72[e(1509)+e(1559)](eFUDDu[e(1082)],l)}}return r[e(1603)](dS)[e(317)](t)?function(...i){let o=e,c={eAjoZ:function(l,u){return r[q(1825)](l,u)},vGiKN:r[o(923)],eonmb:r[o(580)]};if(r[o(1256)](r[o(1777)],o(1549)))return t.apply(is(this),i),r.vBfBt(zt,Hd.get(this));_0x5b4388=_0x4d999a&&c[o(1796)](o(1396),_0xc23613.protocol)?c[o(560)]:c[o(1035)],_0x14cf04=_0xea719c[o(827)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),_0x6d0134=/^wss(.*:\/\/)/[o(1676)](_0xf7a76)?_0x5b5661:""+_0x553f55+_0x2dce02}:function(...i){let o=e;return r[o(849)](zt,t[o(1493)](is(this),i))}}function xS(t){let e=N,r={SPcHx:function(i,o){return i===o},EOsrb:e(697),GZSeg:function(i,o){return i(o)},iIENr:function(i,o,c){return i(o,c)},ovZyq:function(i){return i()}};return r[e(1184)](typeof t,r[e(1227)])?hS(t):(t instanceof IDBTransaction&&r.GZSeg(uS,t),r[e(459)](Ox,t,r[e(582)](cS))?new Proxy(t,Qo):t)}function zt(t){let e=N,r={pHixE:function(o,c){return o instanceof c},eaCCM:function(o,c){return o(c)},jwsHa:function(o,c){return o!==c},KejSI:e(1881)};if(r.pHixE(t,IDBRequest))return lS(t);if(Vo[e(451)](t))return Vo[e(1546)](t);let i=r.eaCCM(xS,t);return r[e(1762)](i,t)&&(r[e(488)]!==r[e(488)]?_0x497dac.d=(o,c)=>{let l=e;for(var u in c)_0x3180cd.o(c,u)&&!_0x47a9a2.o(o,u)&&_0x5bed12[l(600)+"operty"](o,u,{enumerable:!0,get:c[u]})}:(Vo[e(1680)](t,i),Xo[e(1680)](i,t))),i}var Ox,kx,Tx,Hd,Yo,Ud,Vo,Xo,Qo,is,Cx=Px({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={cclQD:function(r,i){return r<i},wRHQB:function(r,i,o){return r(i,o)},ajIoT:function(r,i,o,c){return r(i,o,c)},gtXgl:function(r,i){return r+i},Obfnx:function(r,i){return r instanceof i},CuAtg:function(r,i){return r!==i},QETuW:t(1298),vEdsb:function(r,i){return r===i},vuxec:function(r,i){return r===i},xhMfk:function(r,i){return r(i)},iLDbF:"done",WyPZu:function(r,i){return r===i},chBDO:t(538),qCAkv:function(r,i){return r in i}};Ox=(r,i)=>i[t(1857)](o=>r instanceof o),Hd=new WeakMap,Yo=new WeakMap,Ud=new WeakMap,Vo=new WeakMap,Xo=new WeakMap,Qo={get(r,i,o){let c=t,l={qbIVM:function(u,f){return e[q(673)](u,f)},KTuLn:function(u,f,x){return e.wRHQB(u,f,x)},EokFw:function(u,f,x){return e.wRHQB(u,f,x)},QZpbQ:function(u,f,x,g){return e[q(1175)](u,f,x,g)},Bygse:function(u,f){return e[q(1181)](u,f)},IQxJC:function(u,f,x){return u(f,x)}};if(e[c(1029)](r,IDBTransaction))if(e.CuAtg("YXeMW",e[c(1812)])){if(e[c(599)](i,c(938)))return Yo[c(1546)](r);if(e[c(599)](i,c(1253)+c(1011)))return r[c(1253)+c(1011)]||Ud.get(r);if(e[c(1200)](i,c(538)))return o[c(1253)+"oreNames"][1]?void 0:o["objectSt"+c(927)](o[c(1253)+"oreNames"][0])}else{let u=0,f=[];for(;l[c(814)](u,_0x5be5fc[c(1232)+"th"]);){let{offset:x}=l[c(1835)](_0x165359,_0x1a0363,u);u=x;let g={cursor_name:"",cursor:0,service:0},{value:y,offset:S}=l.KTuLn(_0xc4cb90,_0xe3fcd3,u);g.service=y,u=S;let{value:_,offset:v}=l.EokFw(_0x53bc8d,_0x427b4f,u);u=v,g[c(466)+"ame"]=l[c(1177)](_0x2cfb8f,_0x9bba1c,u,l.Bygse(u,_)),u+=_;let{value:I,offset:A}=l[c(684)](_0x5bd47a,_0x27cde2,u);g[c(1631)]=I[c(812)](),u=A,f[c(932)](g)}return f}return e[c(1163)](zt,r[i])},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return e[o(1029)](r,IDBTransaction)&&(i===e[o(467)]||e[o(1837)](i,e[o(332)]))?!0:e[o(921)](i,r)}},is=r=>Xo[t(1546)](r)}}),Lx={};aS(Lx,{deleteDB:()=>gS,openDB:()=>pS,unwrap:()=>is,wrap:()=>zt});function pS(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let l=N,u={hTUPb:function(g,y){return g(y)},jWskL:l(1769),MVQzB:l(1262)+"hange",MIlZB:l(786)+l(1106),TCkrj:"blocked"},f=indexedDB[l(832)](t,e),x=u[l(1702)](zt,f);return i&&f[l(1509)+l(1559)](u[l(1442)],g=>{let y=l;i(u.hTUPb(zt,f.result),g[y(1436)+"on"],g.newVersion,u.hTUPb(zt,f[y(1480)+y(783)]))}),r&&f[l(1509)+l(1559)](u.TCkrj,()=>r()),x[l(862)](g=>{let y=l;c&&g.addEventListener(u[y(551)],()=>c()),o&&g.addEventListener(u[y(398)],()=>o())})[l(1416)](()=>{}),x}function gS(t,{blocked:e}={}){let r=N,i={sLnUZ:r(813),KTjPy:function(c,l){return c(l)}},o=indexedDB[r(834)+r(493)](t);return e&&o[r(1509)+r(1559)](i[r(1873)],()=>e()),i[r(775)](zt,o)[r(862)](()=>{})}function Rx(t,e){let r=N,i={wpooA:r(453)+"e",YrpTt:r(1380),zmNnZ:function(f,x){return f instanceof x},iSrBM:function(f,x){return f in x},JcAqp:function(f,x){return f===x},yWNwC:function(f,x){return f!==x}};if(!(i[r(1370)](t,IDBDatabase)&&!i[r(645)](e,t)&&i[r(960)](typeof e,r(1034))))return;if(Jo[r(1546)](e))return Jo[r(1546)](e);let o=e[r(827)](/FromIndex$/,""),c=i[r(926)](e,o),l=Mx.includes(o);if(!i[r(645)](o,(c?IDBIndex:IDBObjectStore)[r(337)+"e"])||!(l||Nx[r(317)](o)))return;let u=async function(f,...x){let g=r,y=this[g(1480)+g(783)](f,l?i.wpooA:i[g(1713)]),S=y[g(538)];return c&&(S=S[g(577)](x[g(1209)]())),(await Promise[g(1464)]([S[o](...x),l&&y[g(938)]]))[0]};return Jo.set(e,u),u}var Nx,Mx,Jo,mS=Px({"node_modules/idb/build/index.js"(){let t=N,e={mPFnt:"4|1|3|0|"+t(1142),NVVVW:t(1541),BenAj:t(1562),iwZVj:t(1173),oyzza:function(o){return o()},QPZPe:"get",QnTks:t(1357),jQmSO:t(665),XFIQE:t(1779)+"ys",QIeFW:function(o){return o()},fASlF:function(o,c){return o(c)}},r=e[t(873)][t(557)]("|"),i=0;for(;;){switch(r[i++]){case"0":Mx=[e[t(1547)],"add",e[t(510)],e[t(659)]];continue;case"1":e[t(1731)](Cx);continue;case"2":Jo=new Map;continue;case"3":Nx=[e[t(595)],e[t(1651)],e[t(1667)],e[t(1444)],t(1321)];continue;case"4":e[t(389)](Cx);continue;case"5":e[t(618)](fS,o=>({...o,get:(c,l,u)=>Rx(c,l)||o[t(1546)](c,l,u),has:(c,l)=>!!Rx(c,l)||o[t(451)](c,l)}));continue}break}}}),wS={idb:function(t){let e=N;t.exports=Promise[e(474)]()[e(862)](()=>(mS(),Lx))[e(862)](function(r){return r})}},Dx={};function Ft(t){let e=N;var r=Dx[t];if(r!==void 0)return r[e(1787)];var i=Dx[t]={exports:{}};return wS[t](i,i[e(1787)],Ft),i[e(1787)]}Ft.d=(t,e)=>{let r=q;for(var i in e)Ft.o(e,i)&&!Ft.o(t,i)&&Object["definePr"+r(877)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;Ft.o=(e,r)=>Object[t(337)+"e"][t(1737)+t(877)][t(903)](e,r)})(),(()=>{let t=N,e={zqENF:function(r,i){return r!=i},qNBjC:t(661)+"d",yJiSe:t(1233),CnAhc:t(1277)+"le"};Ft.r=r=>{let i=t;e[i(1315)](e[i(1070)],typeof Symbol)&&Symbol[i(1715)+"Tag"]&&Object[i(600)+"operty"](r,Symbol[i(1715)+i(664)],{value:e.yJiSe}),Object.defineProperty(r,e[i(487)],{value:!0})}})();var Oe={};(()=>{let t=N,e={dZeMo:t(909),zSejD:function(a,n){return a+n},aHeqa:function(a,n){return a+n},kJqSj:function(a,n){return a+n},zYPXl:function(a,n){return a*n},FvHED:function(a,n){return a*n},LSisw:function(a,n){return a+n},RJvhW:function(a,n){return a(n)},DKWnj:function(a,n){return a+n},aAUpZ:function(a,n,s){return a(n,s)},tfMAc:function(a,n){return a(n)},EhjpZ:t(1310),iRnKB:t(361),VgwYR:function(a,n){return a(n)},bZEcR:t(399)+"t",hMcHq:"stop imm"+t(1075)+t(1191)+"ct",BxErS:function(a,n){return a>n},QfYFD:function(a,n){return a===n},rABGL:t(1071),mEXwf:function(a,n){return a<n},OPFCT:function(a,n){return a!==n},LVkTb:function(a,n){return a-n},AUgJc:function(a,n){return a-n},NJmCX:function(a,n){return a-n},pEXyl:function(a,n){return a===n},NgazG:t(885),VmXHG:function(a,n){return a<n},muajk:t(973),UWHWu:function(a,n){return a(n)},yCocr:function(a,n){return a!==n},RBYWg:function(a,n){return a!==n},IBHpM:t(953),jtwLi:t(1735),IXJtT:function(a,n,s){return a(n,s)},IySkS:function(a,n,s,d){return a(n,s,d)},lKCCS:t(732),wKPQG:t(445),MnVtS:"service",PyHSZ:t(1575),DdYhE:t(1255),Pitdp:function(a,n){return a>>>n},rdyIN:function(a,n){return a(n)},eTOrV:function(a,n,s){return a(n,s)},uCVNU:function(a,n){return a&n},aSomx:function(a,n){return a===n},HSTHS:"Missing "+t(1614)+t(866)+"key",qYlSr:function(a,n){return a===n},BINtB:function(a){return a()},wanIs:function(a,n){return a>>>n},smdDS:function(a,n){return a>>>n},BumBA:function(a,n){return a&n},tagqW:function(a,n){return a>>>n},PTbjg:function(a,n){return a&n},Gfxjh:function(a,n){return a!==n},cTvXN:function(a,n,s){return a(n,s)},IuoIp:function(a,n){return a!==n},QpIjQ:function(a,n){return a!==n},MUHmc:function(a,n){return a(n)},yEmFV:function(a,n){return a!==n},IOERG:function(a,n,s){return a(n,s)},jRSYY:function(a,n){return a!==n},LWDhR:function(a,n,s){return a(n,s)},SIdZc:function(a,n,s){return a(n,s)},oSIlT:function(a,n){return a===n},wYNEC:t(478),mITvC:function(a,n,s){return a(n,s)},nQVEN:function(a,n){return a!==n},rqfjA:function(a,n,s){return a(n,s)},gVGMD:function(a,n,s){return a(n,s)},TFrdm:function(a,n,s){return a(n,s)},HtGFK:function(a,n,s){return a(n,s)},kpbos:function(a,n){return a(n)},HAUTE:function(a,n){return a(n)},iamfc:function(a,n){return a(n)},qJstk:function(a,n){return a(n)},IfKlO:function(a,n,s){return a(n,s)},kzDYY:function(a,n,s){return a(n,s)},AMaFH:function(a,n){return a(n)},rLbri:function(a,n){return a(n)},ktJOZ:function(a,n){return a(n)},GTBVK:function(a,n,s){return a(n,s)},sUSvO:function(a,n,s){return a(n,s)},rbKBM:"Missing "+t(1614)+t(866)+t(1455),BDCDS:t(1610)+t(1614)+t(866)+t(1074),xulLz:"Missing "+t(1614)+t(866)+t(974),nHBgv:t(1610)+"required field: "+t(1334),qSduL:t(575),MXHCi:function(a,n){return a(n)},Fmhyo:function(a,n,s){return a(n,s)},qPcqP:function(a,n){return a>>n},edmmt:function(a,n){return a>=n},bPRRt:function(a,n){return a===n},yWRjk:function(a,n){return a(n)},EoxhJ:t(1220),mgnSS:function(a,n){return a>n},hVtZd:function(a,n){return a+n},TDdhS:t(1540)+t(1236),VZkcA:function(a,n){return a>n},IKXjg:function(a,n,s){return a(n,s)},ddCxI:function(a,n,s){return a(n,s)},etDSq:t(628)+t(1033)+t(399)+t(658)+t(578),QdeUF:t(1668),cPeeh:function(a,n){return a<n},NZdfI:function(a,n){return a+n},dfnHK:function(a,n){return a===n},BEjdP:function(a,n){return a>=n},hHloP:function(a,n){return a+n},VlEiA:function(a,n){return a+n},byWzj:function(a,n){return a===n},BeMKq:t(1366),hRdOB:function(a,n){return a|n},uShkY:function(a,n){return a<<n},UPQXF:function(a,n){return a&n},BToyz:function(a,n){return a<n},MhHto:t(795),yhTwF:t(625),nlJWQ:function(a,n){return a==n},kisFz:function(a,n){return a>=n},dKgfI:function(a,n){return a+n},nOeny:function(a,n){return a&n},hpaCL:function(a,n){return a|n},wNQMd:function(a,n){return a<<n},OGSnv:function(a,n){return a&n},ByrYz:function(a,n){return a<n},Xdoes:function(a,n){return a>=n},zvBEh:function(a,n){return a+n},LnSfq:function(a,n){return a+n},JJTZN:function(a,n){return a|n},sGUoF:function(a,n){return a|n},XIGzv:function(a,n){return a<<n},xmYJJ:function(a,n){return a|n},upGEg:function(a,n){return a<<n},WFgcj:function(a,n){return a<<n},eCahl:function(a,n){return a<n},HPMAE:function(a,n,s){return a(n,s)},pVYYC:function(a,n){return a<n},JdQgC:function(a,n){return a>=n},PUVDI:function(a,n){return a<=n},LwASu:function(a,n){return a<<n},rClri:function(a,n){return a<n},aRDHZ:function(a,n,s){return a(n,s)},NPZVP:function(a,n){return a<n},SDCip:t(1819),QeDqa:t(1729),phkfw:function(a,n){return a>=n},psbCc:function(a,n){return a<=n},BCiRF:function(a,n){return a-n},ftCRS:function(a,n){return a<<n},LnASR:function(a,n){return a<n},EmuDM:function(a,n){return a&n},AInoT:function(a,n){return a|n},PMaid:function(a,n){return a>>n},ZGAEp:function(a,n){return a>>n},ihMNd:function(a,n){return a|n},EezXw:function(a,n){return a&n},QPMJq:function(a,n){return a&n},fMRKi:function(a,n){return a|n},SOwbR:function(a,n){return a<n},bXeRS:function(a,n,s){return a(n,s)},rekew:t(1782),aBjVo:function(a,n){return a(n)},giYeR:function(a,n){return a<n},OMeIq:function(a,n){return a>=n},qHonM:function(a,n,s){return a(n,s)},nwECz:function(a,n,s){return a(n,s)},SPCDz:function(a,n){return a>=n},mrORA:function(a,n,s){return a(n,s)},HiXWJ:function(a,n){return a>>>n},oARpA:function(a,n,s){return a(n,s)},nKSqc:function(a,n,s){return a(n,s)},iaXsF:function(a,n,s){return a(n,s)},ViUua:t(1452),qnwts:function(a,n){return a&n},BhXGw:function(a,n){return a&n},ZNFOL:function(a,n){return a&n},bQXoi:function(a,n){return a&n},AhKoe:function(a,n){return a&n},vfDmr:function(a,n){return a(n)},mvuDE:function(a,n){return a<<n},yNrRV:function(a,n){return a(n)},SYYot:function(a,n){return a&n},UMhUx:function(a,n){return a&n},noSXP:t(1077),rjYPC:function(a,n){return a(n)},pHKpo:function(a,n){return a&n},AlOTb:function(a,n){return a!==n},wHdsv:"GnhTa",VdQMA:function(a,n){return a<<n},uwkiV:function(a,n){return a&n},ryLbs:function(a,n){return a(n)},nVgXW:function(a,n){return a&n},iSjWP:function(a,n){return a<<n},IivgU:function(a,n){return a<<n},TpeNB:function(a,n){return a<<n},dTWFK:function(a,n){return a|n},qvVWD:function(a,n){return a>>>n},RTHMR:function(a,n){return a<<n},Vyvka:function(a,n){return a>>>n},JQKIJ:function(a,n){return a===n},IdkUt:function(a,n){return a===n},mGFSd:function(a,n){return a<n},PdsUB:function(a,n){return a<n},ZAIYM:function(a,n,s){return a(n,s)},sNDfP:function(a,n){return a>>>n},xBPzp:function(a,n){return a+n},jAfnP:function(a,n){return a!==n},gEFMY:function(a,n){return a|n},jcAKo:function(a,n){return a+n},EEXxb:function(a,n){return a&n},adueP:function(a,n){return a!==n},VAwFM:function(a,n){return a>>>n},ODQpj:function(a,n){return a>>>n},dKCIP:function(a,n){return a+n},ASVIk:function(a,n){return a|n},KXlhc:function(a,n){return a&n},QfpfJ:function(a,n){return a+n},QnVLP:function(a,n){return a!==n},VOiUy:function(a,n){return a&n},zDWsn:function(a,n){return a+n},nqyZk:function(a,n){return a!==n},sPqaR:function(a,n){return a|n},pTqnV:function(a,n){return a>>>n},otzJh:function(a,n){return a>>>n},nPGas:function(a,n){return a&n},QhOMA:function(a,n){return a(n)},pRFik:function(a,n){return a|n},ZLIuf:function(a,n){return a===n},PfScl:function(a,n){return a<<n},eavLo:function(a,n){return a|n},LbmeH:function(a,n){return a<<n},SQuVx:function(a,n){return a<<n},QrDbG:function(a,n){return a|n},QDGXT:function(a,n){return a|n},McDjp:function(a,n){return a<<n},Wvmwf:function(a,n){return a|n},nCwhL:function(a,n){return a|n},fLXjf:function(a,n){return a<<n},taYId:function(a,n){return a|n},wuikP:function(a,n){return a|n},dvqXp:function(a,n){return a<<n},YAjWh:function(a,n){return a&n},jiyDl:function(a,n){return a>>>n},dBmcV:function(a,n){return a&n},LRthl:function(a,n){return a>>>n},QbyQZ:t(774),GlpFk:t(1824),zsnsH:function(a,n){return a(n)},JIaIP:"YAkfL",yhIGN:function(a,n){return a>=n},xTEsA:t(597),PxrRT:function(a,n){return a<=n},tflof:function(a,n){return a+n},bYkvl:function(a,n){return a/n},iudVZ:function(a,n){return a(n)},JvRdD:t(690),CCfUY:function(a,n){return a*n},pbQcA:function(a,n){return a>>>n},VsSsb:function(a,n){return a>>>n},zaKiK:function(a,n){return a+n},egGqM:function(a,n){return a*n},lcCfB:function(a,n){return a>>>n},lQAlj:function(a,n){return a&n},UXdvy:t(746),lfBYz:function(a,n){return a>>>n},MQmpX:function(a,n){return a&n},ukwey:function(a,n){return a>>>n},uMBzr:function(a,n){return a&n},wvNRo:function(a,n){return a&n},BBTiS:function(a,n){return a+n},Kgsgi:function(a,n){return a>>>n},vTKUX:function(a,n){return a+n},crtqF:function(a,n){return a+n},APKqq:function(a,n){return a+n},IiqBZ:function(a,n){return a|n},pVjJI:function(a,n){return a<<n},OVmBc:function(a,n){return a>>>n},PqrGC:function(a,n){return a===n},qokvW:function(a,n){return a===n},tRkih:function(a,n){return a===n},naNYh:t(1845),LfvwE:function(a,n){return a&n},WlGXV:function(a,n){return a&n},wVEgY:function(a,n){return a>>>n},sgBXe:function(a,n){return a>>>n},BUDtv:function(a,n){return a>>>n},zsnWR:function(a,n){return a&n},Xezsa:function(a,n){return a&n},YKnrk:function(a,n){return a>>>n},Tohke:function(a,n){return a&n},oRpRX:function(a,n){return a&n},ftrGd:function(a,n){return a>>>n},lQOVg:t(1832)+t(1026),GkOGX:"CONNECTI"+t(666),SZyMX:"MAX_RETR"+t(1432)+"R",SjACL:"OPEN_ERROR",rgnxQ:function(a,n){return a|n},rBYoG:t(1580),mKvuq:t(1818),ddHZk:function(a,n){return a!==n},xNGap:t(536),rfgvO:t(524),ivQfc:t(621),PmzHL:t(1309),gzjAW:t(811),kQNXq:t(409),HeRWg:function(a,n){return a===n},pPJvu:function(a,n){return a-n},pzbLN:t(1069),rLqiQ:"hNXRy",xTJKu:t(353),yRXdG:function(a,n){return a==n},tudYe:function(a,n){return a>n},oqocy:function(a,n){return a===n},piRsc:t(624)+t(852),SCHin:t(624)+t(852)+";charset=utf-8",kBoTe:t(1034),pKvFC:"none_none",FjADN:t(1346),SyXaC:"bSkwB",gOCkD:function(a,n){return a===n},GtapL:function(a,n){return a instanceof n},Cxhuz:t(418)+t(1600),hsutd:function(a,n){return a+n},iPrdq:function(a,n){return a===n},EZohe:t(359),NomUM:t(1084),aEQCJ:t(1872),XKjRC:function(a,n){return a===n},aFUet:"sfAbW",bVuli:function(a,n,s){return a(n,s)},fIsLz:t(1769),srEla:t(832),KGmJx:function(a,n,s){return a(n,s)},DVomA:t(1021),fcymG:t(736),SDlyS:function(a,n,s){return a(n,s)},OmVPf:function(a,n){return a instanceof n},ubKep:function(a,n){return a+n},xspxT:function(a,n){return a!==n},iszPR:"naPOi",ycdPw:t(1690),JIdQF:function(a,n){return a|n},gfqXm:function(a,n){return a<<n},yVcIw:t(805),LIXYJ:"ZLaYN",KyhUy:function(a,n){return a||n},amGLW:function(a,n){return a!=n},POcjp:t(661)+"d",YFTOw:"3|1|2|4|0",hxowp:function(a,n){return a||n},YBNon:function(a,n){return a!=n},MXhTv:function(a,n){return a<=n},EFKZk:function(a,n){return a===n},IrcJx:function(a,n){return a<n},KMHWx:function(a,n){return a&n},eXEjL:function(a,n){return a+n},jmzvW:t(1429),arKCO:function(a,n){return a<=n},UfYBh:function(a,n){return a>=n},usKcL:function(a,n){return a<n},mEzfw:function(a,n){return a|n},sjOhP:function(a,n){return a<<n},hkceT:function(a,n){return a&n},BLqXK:function(a,n){return a>=n},Nkpcr:function(a,n){return a<n},PuJDw:function(a,n){return a|n},SoxRO:function(a,n){return a|n},ZIEbv:function(a,n){return a&n},vLbxX:function(a,n){return a&n},MacUN:function(a,n){return a<<n},ZLkBw:function(a,n){return a&n},qxyZu:function(a,n){return a&n},YfUew:function(a,n){return a+n},IUEpj:function(a,n){return a+n},oxMVV:function(a,n,s){return a(n,s)},utHLG:function(a,n,s){return a(n,s)},aJuFI:function(a,n){return a(n)},DXhpx:t(513),miDLf:function(a,n){return a<n},LLzOa:function(a,n){return a|n},hjurm:function(a,n){return a===n},pircW:function(a,n){return a&n},YFxdx:t(1297),UpgEP:t(1885)+t(1121),wVulW:function(a,n){return a|n},XrfuR:function(a,n){return a>>n},LOxpL:function(a,n){return a|n},miBit:function(a,n){return a&n},yuHHa:function(a,n){return a<<n},HPVlp:function(a,n){return a&n},RtkQU:function(a,n){return a>>n},LVVGl:function(a,n){return a|n},nwBiC:function(a,n){return a>>n},UTijI:function(a,n){return a-n},TvsEH:function(a,n){return a instanceof n},QKHvz:function(a,n){return a instanceof n},tvSaR:function(a,n){return a==n},fMbzN:t(1748)+"in;chars"+t(720),cbTcI:"OnYyg",YYmOe:t(1682),akZZR:function(a,n){return a>=n},fyFqA:function(a,n){return a>>>n},CIAgs:function(a,n){return a<<n},QlFxc:function(a,n){return a<n},DvhVN:function(a,n){return a<n},xtGuv:function(a,n){return a<n},HzgxL:function(a,n){return a&n},tFeHl:function(a,n){return a|n},wzNvX:function(a,n){return a+n},gevcz:function(a,n){return a|n},VgSOz:function(a,n){return a&n},ukDtA:function(a,n){return a+n},gUqNc:function(a,n){return a&n},hqrft:function(a,n){return a!==n},OYEYd:function(a,n){return a>>>n},dhPdd:function(a,n){return a+n},AXzYz:function(a,n){return a+n},seDse:function(a,n){return a|n},fWAph:function(a,n){return a>>>n},WCGBh:function(a,n){return a&n},kiVam:function(a,n){return a>>>n},vxQuP:function(a,n){return a+n},zTZOQ:function(a,n){return a!==n},JsGme:function(a,n){return a>>>n},kUtSZ:function(a,n){return a&n},qBacL:function(a,n){return a|n},bqyiz:function(a,n){return a(n)},ThBzq:t(376)+"reason",PTUaZ:function(a,n){return a(n)},sJGYH:t(1186),clJtJ:t(765)+t(1581),hIfCg:"http",PuQDA:"oJtwg",binqm:t(1578),ZOIJB:"PvZZs",eFcUC:t(416),bbSfa:function(a,n,s,d){return a(n,s,d)},QHSwN:function(a,n){return a>>n},Arorq:t(946),nNfQj:t(1673),EaYYL:t(1830),DgHZs:t(734),yfCfq:t(1215),DyehX:"GtRrV",BYYRm:function(a,n){return a===n},nfPLZ:"HWLdZ",rYtch:t(889),TIVwm:t(528),KmbpQ:t(319),CBrQi:"HDPFP",CEnSm:function(a,n){return a||n},PEtri:t(1238),JUJsA:t(412)+"id",afFas:function(a,n,s){return a(n,s)},foOzm:function(a,n){return a!==n},GPqmt:t(405),bENxV:function(a,n){return a>=n},MiJNQ:function(a,n){return a&n},lgszc:function(a,n){return a&n},KoeFf:function(a,n){return a<<n},MYkDG:function(a,n){return a-n},Bxsfg:function(a,n){return a&n},EAcBB:t(1417),ZwlYi:t(1028),sFZEe:t(1295)+t(896),ljpsv:t(1295)+t(999)+"ck",ISqez:function(a,n,s,d){return a(n,s,d)},ZNugv:t(1295)+"er_is_ack",YHZes:function(a,n,s){return a(n,s)},cjKPr:t(1040)+">",iTPAl:function(a,n){return a!==n},iVbOh:t(1556),YMwqY:"Module",nTcEt:t(1277)+"le",WmWdA:t(1561),YaddU:"need_ack",nAwoN:"is_ack",GqgWf:function(a,n){return a&&n},wNTmR:t(516),zqHMl:function(a){return a()},InSdK:function(a,n){return a>>>n},ZJClV:function(a,n){return a>>>n},cYiVY:function(a,n){return a&n},nwnRk:function(a,n){return a>>>n},afFUn:function(a,n){return a&n},FQhjw:function(a,n){return a&n},Qsfmm:function(a,n){return a+n},WHEfC:function(a,n){return a+n},YPWFF:function(a,n){return a>>>n},ayrDU:function(a,n){return a+n},RZuJK:function(a,n){return a<<n},GlswL:function(a,n){return a(n)},NkuwJ:function(a,n){return a(n)},Wybsi:function(a,n){return a===n},yubrR:"yrqVa",MJpRb:function(a,n){return a instanceof n},BUqKl:function(a,n){return a instanceof n},nvGsO:function(a){return a()},mqhdB:function(a,n){return a||n},dZbrr:function(a,n){return a||n},QNzGG:function(a,n){return a<n},NngXn:function(a,n){return a>n},tUvPJ:function(a,n){return a+n},IHDJO:function(a,n){return a===n},YbPrZ:t(703),oiqxF:function(a,n){return a(n)},DVTkt:function(a,n){return a||n},pSScq:function(a,n){return a>>>n},noLuH:function(a,n){return a!==n},ETJAG:t(472),WQqKV:function(a,n){return a+n},KReCL:function(a,n){return a+n},aJDIf:function(a,n){return a+n},FGZGK:"index out of ran"+t(601),QGqjL:t(1147),LAkPw:t(321),GgTHL:function(a,n){return a>n},jVHMr:t(1424)+t(1343)+"e",kiUeQ:function(a,n){return a+n},ApcAx:function(a,n){return a<<n},eKUDi:function(a,n){return a<n},VtePp:function(a,n,s,d){return a(n,s,d)},ycQah:function(a,n){return a+n},LzXHz:function(a,n){return a|n},lfiDm:function(a,n){return a|n},nDmBz:function(a,n){return a+n},oOdiw:function(a,n){return a+n},eQeaD:function(a,n){return a<<n},VnmrZ:function(a,n){return a<<n},ktXJw:function(a,n){return a+n},GlVyM:function(a,n){return a+n},AJAkx:function(a,n){return a+n},RQXpe:function(a,n){return a&n},awacv:function(a,n){return a+n},ijclZ:function(a,n){return a&n},zsuPB:function(a,n){return a+n},iZwmf:function(a,n){return a&n},hzHYA:function(a,n){return a+n},bBgzr:t(1425)+"3|5|4|1|11|0|8|10",iOnvC:function(a,n){return a<n},KKucg:function(a,n){return a>>>n},vSyga:function(a,n){return a|n},DgGcO:function(a,n){return a<n},XFauT:function(a,n){return a<n},PNnVw:function(a,n){return a(n)},DLKeq:function(a,n,s){return a(n,s)},zbRiN:function(a,n){return a&n},CffUH:t(1775)+t(505)+t(949),DnPAT:t(987)+t(1240),Puqge:t(576)+"name",PxeQm:function(a,n){return a===n},sCpgG:t(1475),lBolV:"cursor_file_name",NXKXL:function(a,n){return a<n},TunTh:function(a,n,s,d){return a(n,s,d)},wIfiM:t(704)+t(492),uizKF:function(a,n,s){return a(n,s)},lexsB:"cursor_n"+t(1573),bYrXf:"allCursorValues",qXjMn:t(632),NvKzk:t(586),yyzpD:t(1479),chVwT:function(a,n,s,d){return a(n,s,d)},jUzhO:t(1448),IpItv:"NtpRy",sVJTO:"setdb",kKySg:function(a,n){return a(n)},gKvuA:t(1118)+"r",fMhny:function(a,n){return a(n)},vHcDI:t(357),yndEO:function(a,n,s,d){return a(n,s,d)},tlLgm:t(1105),PmNRE:function(a,n,s,d){return a(n,s,d)},zVFpQ:t(1295)+t(991),VbSoC:t(1295)+"er_ttl",STbka:t(519)+t(762)+"e",GeesE:function(a,n){return a(n)},FISuV:t(519)+"rsor_value",asrSi:function(a,n){return a>n},orgzj:function(a){return a()},jSnzU:function(a,n){return a<n},WIzYB:function(a){return a()},pTiDV:function(a,n,s){return a(n,s)},THjbH:function(a){return a()},pOfnA:function(a){return a()},fCWzh:function(a,n){return a(n)},lbRed:function(a,n){return a!==n},bATAe:function(a,n){return a<n},dIrct:function(a,n){return a===n},WIjeE:function(a,n){return a!==n},raLYK:t(1127),SxVQk:function(a,n,s){return a(n,s)},AMrPH:function(a,n){return a!==n},IpWTz:t(1039),ZlXTu:t(1543),wHMwJ:function(a,n){return a!==n},IrFOi:t(1648),xtQug:function(a,n){return a<<n},kPYjB:function(a,n){return a!==n},JHYpf:"sYKNP",nVVDi:function(a,n){return a===n},YNdtj:t(1404),TXyLA:"auto",fhBqv:t(1246)+t(967)+"s",dbwIX:"success",HEIRM:function(a,n,s){return a(n,s)},ZHCgD:function(a,n){return a===n},TZCrw:t(1158)+t(627),EBQMx:function(a,n){return a==n},PXprc:function(a,n){return a===n},xJbmb:"please provide v"+t(485),pQRoi:function(a,n){return a(n)},VreNl:function(a,n){return a===n},RHcou:t(429),FdVDI:t(1395),ujprw:"online",sYMBO:function(a,n){return a!==n},kcPmj:t(910),QXobR:t(1755),JrusW:"ttwid",vXZZU:"device_id",QuLdf:function(a,n){return a||n},dhFAt:function(a,n){return a==n},xHDpH:function(a){return a()},smubf:"web",ZfFOR:t(1875)+"0",YDgkn:function(a,n){return a&n},qyTnu:t(1120),iiidH:function(a,n,s){return a(n,s)},vyHnc:function(a,n){return a(n)},iMmAL:t(1541),vpYQX:t(1173),KcNPB:t(1546),sJWQI:t(1357),tUnRx:t(665),TnVGt:t(1779)+"ys",XTEGK:t(1321),ITaWn:"NXDXj",LJezr:t(1048),XrpIY:function(a,n){return a>n},XcIor:function(a,n){return a===n},fQset:t(1246)+t(1570)+"t",KWqDC:t(328),ADVYt:function(a,n){return a>=n},CaMmz:function(a,n){return a<=n},AwIEn:function(a,n){return a+n},DsswK:function(a,n){return a-n},dVPjO:function(a,n){return a<n},SnKJf:function(a,n){return a<n},xgclC:function(a,n){return a!==n},UAjEB:t(799),UHont:function(a,n){return a===n},lCatZ:t(564)+"1",LOxjO:t(1322)+"2",oaTCx:function(a,n){return a===n},vHRqf:t(1536),pelwG:function(a,n,s){return a(n,s)},QrfAi:t(628)+"ay, netw"+t(1736)+t(1771),agKHW:t(1563),ONkfM:function(a,n){return a+n},njuur:function(a,n){return a!==n},LsZkQ:"vluvs",otkpJ:function(a,n){return a+n},FfgUg:t(733)+"s instan"+t(1146)+"nitialized",AZKmd:function(a,n){return a===n},jYFCR:function(a,n){return a===n},AVhBq:t(477)+"rovide a"+t(1259)+t(1506)+t(1616)+"e a stri"+t(533)+t(1598)+"ffer",lwWfJ:t(1217),IcAwn:function(a,n){return a instanceof n},SiXDs:function(a,n){return a(n)},yevXL:function(a,n){return a(n)},NNYzI:function(a,n){return a||n},ArUce:t(477)+t(649)+t(737)+"ervice",bbwkK:function(a,n){return a instanceof n},SwtNk:function(a,n){return a===n},pEHyO:"sent",pmcGp:function(a,n){return a<n},EOPaV:t(461),Jupxo:t(470),eeSLF:t(1463),GHKTo:function(a,n){return a||n},qYfxJ:function(a,n){return a!==n},WiMYy:"manual r"+t(370)+"ing",SybOL:function(a,n){return a===n},lgUUN:t(1422),zgEjZ:t(1331),GZoEg:function(a,n){return a*n},clDJM:function(a,n){return a*n},AWrMy:function(a,n){return a===n},MSjel:"Window",WJmqn:function(a,n){return a!=n},UrXUi:"Object",xaOYm:t(349)+t(457)+t(1666)+"pe",ufozM:function(a,n){return a!=n},YkBek:function(a,n){return a!=n},uJwPY:function(a,n){return a===n},BrUFb:function(a,n){return a===n},jUIUM:t(1145)+t(1865)+t(1828),mBOLM:function(a,n){return a!=n},hVCkv:function(a,n){return a!=n},Gpegp:function(a,n,s){return a(n,s)}};Ft.r(Oe),Ft.d(Oe,{FWS:()=>wg,CustomErrorEvent:()=>al,createCloseEvent:()=>gt,ReconnectEvent:()=>ol,createErrorEvent:()=>dt,decodedFrame:()=>tn,createOpenEvent:()=>hl,CustomCloseEvent:()=>cl,createReconnectEvent:()=>ma,FrontierMessageEvent:()=>ll,encodeFrame:()=>Ut,createMessageEvent:()=>fl,OpenEvent:()=>ul,ErrorCode:()=>rn,Event:()=>sr,MessageEvent:()=>dl});let r="";function i(a=""){let n=t;if(e[n(1503)]!==e.dZeMo)_0x46d3c3[n(1126)+n(1420)]=void 0,_0x4dc985(n(376)+n(1606));else{let d=""+Date[n(1552)](),h=r||(r=f(a)),w=Math[n(1747)]()[n(1715)](16)[n(1790)](-6);return e[n(1282)](e[n(635)](e.kJqSj("02",d),h),w)}}function o(){let a=t;return e[a(591)](1e4,Date[a(1552)]())+Math.floor(e[a(844)](1e4,Math[a(1747)]()))}function c(a){let n=t;return e.LSisw(e[n(344)](Array,8)[n(1086)]("0"),parseInt(a,10)[n(1715)](2)).slice(-8)}function l(a){let n=t;return e[n(767)](e[n(344)](Array,4)[n(1086)]("0"),e[n(1855)](parseInt,a,2)[n(1715)](16)).slice(-4)}function u(a){let n=t,s=a[n(557)](/\./)[n(1336)](w=>c(w)),d=[];return d[0]=e[n(1752)](l,s[0]+s[1]),d[1]=e[n(344)](l,s[2]+s[3]),[e[n(426)],"0000",e[n(426)],e[n(426)],n(1310),e[n(958)],d[0],d[1]].join("")}function f(a){let n=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(1676)](a),d=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[n(1676)](a);return s?e[n(344)](u,a):d?e.VgwYR(x,a):n(1622)+n(1622)+n(1622)+n(1622)}function x(a){let n=t,s="",d=[],h=0,w=0,m=!0,b=e[n(426)];if(e[n(1664)](a[n(662)]("::"),-1))if(e[n(1626)](n(1071),e[n(1320)])){let p=a.split("::");for(let L=0;e[n(1628)](L,p[n(1407)]);L++){let M=p[L];if(e[n(1664)](M[n(662)](":"),0)){let G=M[n(557)](":");m&&(h=G[n(1407)]),w+=G[n(1407)];for(let J=0;J<G[n(1407)];J++)if(e[n(1292)](4,G[J][n(1407)])){let Z=b[n(1517)+"g"](0,e[n(454)](4,G[J][n(1407)])),we=Z.concat(G[J]);d[n(932)](we)}else d[n(932)](G[J]);m=!1}else{if(e[n(1292)](4,M.length)){let G=b.substring(0,e[n(602)](4,M[n(1407)])),J=G[n(1528)](M);d[n(932)](J)}else d[n(932)](M);m&&(h+=1),w+=1,m=!1}}let P="";for(let L=0;L<e[n(1027)](8,w);L++)P=P[n(1528)](b);for(let L=0;e[n(1628)](L,d[n(1407)]);L++)e[n(1626)](L,h)&&(s=s[n(1528)](P)),s=s[n(1528)](d[L]);return s}else{this["_destroy"+n(917)+"t"]();let p=_0x29c6b8(e.bZEcR,{message:e[n(1759)]});this[n(1337)+"mediatel"+n(669)+"ct"]&&this[n(1337)+n(763)+"yReconnect"](p)}{if(e[n(863)]("pBjuR",e[n(751)]))return;{let p=a[n(557)](":");for(let P=0;e[n(579)](P,p[n(1407)]);P++){let L=p[P];if(e[n(1292)](4,p[P].length)){if(e[n(1658)]!==e.muajk)return this._socket[n(530)+"ns"];{let M=b[n(1517)+"g"](0,e[n(454)](4,p[P][n(1407)])),G=M[n(1528)](L);s=s[n(1528)](G)}}else s=s[n(1528)](L)}return s}}}function g(a,n){let s=t,d={leQvr:function(m,b,p){return m(b,p)},SSIsh:function(m,b){return e[q(391)](m,b)}},h=a.key;e.yCocr(void 0,h)&&(e[s(1855)](me,n,10),e[s(1855)](U,n,h));let w=a[s(823)];w!==void 0&&(e[s(1061)](e[s(384)],e.jtwLi)?(e[s(715)](me,n,18),e.IXJtT(U,n,w)):(d[s(366)](_0x35c53a,_0x580d4e,32),d[s(366)](_0x124fdd,_0x3f061b,d.SSIsh(_0x5847d5,_0x1efc92))))}function y(a){let n=t,s={laiwt:function(h,w,m,b){return h(w,m,b)},YFPOo:n(576)+n(445),FJsgq:function(h,w,m,b){return e[n(1637)](h,w,m,b)},uEDjc:function(h,w,m,b){return e[n(1637)](h,w,m,b)},txJuO:e[n(646)],UscAa:e[n(1617)],XnDiG:e[n(331)],PVmCT:e[n(1263)]},d={};e:for(;!$(a);)if(e[n(363)]("RyGvF",e[n(358)])){let h=ge(a);switch(e[n(433)](h,3)){case 0:break e;case 1:d.key=R(a,e[n(1611)](ge,a));break;case 2:d[n(823)]=e[n(1855)](R,a,e[n(1752)](ge,a));break;default:e[n(1305)](T,a,e.uCVNU(7,h))}}else{let h=(n(1890)+n(446)+n(1287))[n(557)]("|"),w=0;for(;;){switch(h[w++]){case"0":_0x3570a9=s[n(686)](_0x28b0cf,_0x1f1e3d[_0x38bbf1[n(466)+n(1573)]],_0x1a2453,_0x20a514);continue;case"1":_0x3937d0=s.laiwt(_0x3d7e2c,_0x28be08.fromNumber(_0x56772d.cursor||_0x5df364),_0x32e2c9,_0x3a6677);continue;case"2":_0x24aa71[n(1212)](n(987)+n(1240),_0x44208a,_0x12e3f3[n(974)]);continue;case"3":_0xf97571[n(1212)](s[n(782)],_0x34031f);continue;case"4":_0x1c3033=s[n(845)](_0x144992,_0x15f551[n(466)+"ame"],_0xef7581,_0x3cf896);continue;case"5":_0x1a1d97=s[n(1864)](_0x1452b9,_0x4c103a,_0x13bcdd,_0x1ec235[n(974)]||0);continue;case"6":_0x296054[n(1212)](s[n(1382)],_0x5582f0);continue;case"7":_0x539f2d=s.FJsgq(_0x29d1eb,0,_0x1b9ab7,_0xfdd01e);continue;case"8":_0x2b6309.log(s.UscAa,_0x531743);continue;case"9":_0x26a381[n(1212)](s.XnDiG,_0x3167c5);continue;case"10":_0x5492be[n(1212)](s[n(1481)],_0x281f78);continue}break}}if(e[n(341)](void 0,d.key))throw new Error(e[n(494)]);if(e[n(937)](void 0,d[n(823)]))throw new Error(n(1610)+n(1614)+n(866)+n(823));return d}function S(a){let n=t,s=e[n(1734)](C);return _(a,s),B(s)}function _(a,n){let s=t,d={svaQe:function(fe,ae){return e[q(1345)](fe,ae)},ThIYj:function(fe,ae){return e[q(914)](fe,ae)},wkSCp:function(fe,ae){return e[q(1150)](fe,ae)},MuQYK:function(fe,ae){return e[q(433)](fe,ae)},ZxySH:function(fe,ae){return e[q(1150)](fe,ae)},rYwaL:function(fe,ae){return fe&ae},TBnPo:function(fe,ae){return e.tagqW(fe,ae)},fhWYa:function(fe,ae){return e[q(1659)](fe,ae)}},h=a[s(1455)];e[s(1567)](void 0,h)&&(e[s(1419)](me,n,8),e.cTvXN(pt,n,h));let w=a[s(1074)];e[s(1633)](void 0,w)&&(e[s(1305)](me,n,16),e.aAUpZ(pt,n,w));let m=a[s(974)];e[s(1726)](void 0,m)&&(me(n,24),e.eTOrV(pt,n,e.MUHmc(D,m)));let b=a[s(1334)];e[s(1278)](void 0,b)&&(e[s(1855)](me,n,32),e[s(1266)](pt,n,D(b)));let p=a[s(1776)];if(e[s(1695)](void 0,p))for(let fe of p){e[s(545)](me,n,42);let ae=e[s(1734)](C);e.SIdZc(g,fe,ae),e[s(1419)](me,n,ae[s(764)]),K(n,ae),O(ae)}let P=a[s(532)+"ncoding"];if(e.Gfxjh(void 0,P))if(e[s(1456)](e[s(1530)],e.wYNEC))me(n,50),e[s(549)](U,n,P);else{let fe=this[s(1372)],ae=this.low;return[d[s(1411)](fe,24),d[s(1195)](fe,16)&255,d.wkSCp(d[s(1239)](fe,8),255),d[s(1585)](255,fe),d.MuQYK(ae,24),d.rYwaL(d[s(779)](ae,16),255),d.ZxySH(ae>>>8,255),d.fhWYa(255,ae)]}let L=a[s(1700)+s(888)];e[s(1439)](void 0,L)&&(me(n,58),e[s(687)](U,n,L));let M=a[s(326)];e[s(1695)](void 0,M)&&(me(n,66),e[s(435)](me,n,M[s(1407)]),e[s(435)](oe,n,M));let G=a[s(1046)];e[s(1292)](void 0,G)&&(me(n,74),e.eTOrV(U,n,G));let J=a["serverTi"+s(422)];e.RBYWg(void 0,J)&&(e.gVGMD(me,n,82),e.TFrdm(U,n,J));let Z=a[s(901)];e[s(1633)](void 0,Z)&&(e[s(1196)](me,n,90),e.TFrdm(U,n,Z));let we=a[s(1665)+"e"];we!==void 0&&(me(n,96),e[s(1419)](pt,n,e.VgwYR(D,we)))}function v(a){return e[t(475)](I,F(a))}function I(a){let n=t,s={};e:for(;!e[n(785)]($,a);){let d=e[n(911)](ge,a);switch(e.Pitdp(d,3)){case 0:break e;case 1:s[n(1455)]=It(a,!0);break;case 2:s[n(1074)]=It(a,!0);break;case 3:s[n(974)]=ge(a);break;case 4:s[n(1334)]=e[n(1250)](ge,a);break;case 5:{let h=e.RJvhW(A,a);(s[n(1776)]||(s[n(1776)]=[])).push(e[n(1752)](y,a)),a[n(764)]=h;break}case 6:s[n(532)+"ncoding"]=R(a,e[n(911)](ge,a));break;case 7:s[n(1700)+n(888)]=e.IfKlO(R,a,e[n(1450)](ge,a));break;case 8:s[n(326)]=e[n(555)](se,a,e.AMaFH(ge,a));break;case 9:s[n(1046)]=e.LWDhR(R,a,e.rLbri(ge,a));break;case 10:s[n(899)+"ming"]=e[n(549)](R,a,e[n(1101)](ge,a));break;case 11:s.msgID=e[n(604)](R,a,ge(a));break;case 12:s[n(1665)+"e"]=ge(a);break;default:e[n(874)](T,a,e[n(407)](7,d))}}if(e[n(341)](void 0,s[n(1455)]))throw new Error(e[n(1013)]);if(s[n(1074)]===void 0)throw new Error(e[n(613)]);if(e[n(1626)](void 0,s[n(974)]))throw new Error(e[n(351)]);if(s[n(1334)]===void 0)throw new Error(e.nHBgv);return s}function A(a){let n=t,s=e[n(1250)](ge,a),d=a[n(764)];return a[n(764)]=a[n(316)]+s,d}function T(a,n){let s=t;if(s(847)===s(847))switch(n){case 0:for(;e[s(407)](128,e[s(475)](te,a)););break;case 2:V(a,e[s(1349)](ge,a));break;case 5:e[s(1368)](V,a,4);break;case 1:e[s(1855)](V,a,8);break;default:throw new Error(s(833)+s(611)+s(1612)+n)}else this._ws&&this[s(1551)][s(596)](_0xab6e5d),this[s(1198)](e.qSduL,_0x3ea542)}function D(a){let n=t;return a|=0,{low:a,high:e[n(616)](a,31),unsigned:e.edmmt(a,0)}}let E=[];function C(){let a=t,n=E[a(529)]();return n?(n[a(316)]=n[a(764)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){let n=t;n(965)!==n(793)?E[n(932)](a):this[n(724)](_0x46baab,_0x487f5a)}function F(a){return{bytes:a,offset:0,limit:a.length}}function B(a){let n=t,s=a[n(1772)],d=a.limit;return e.bPRRt(s[n(1407)],d)?s:s[n(1591)](0,d)}function V(a,n){let s=t,d={SUUlJ:function(h,w){return e[q(1326)](h,w)},KzeWr:function(h,w){return h===w},uDtfb:s(575)};if(e[s(363)](e[s(1413)],s(1574))){if(e[s(725)](e.hVtZd(a[s(316)],n),a[s(764)]))throw new Error(e.TDdhS);a[s(316)]+=n}else{let h=d[s(1446)](_0x15dbcd,_0x41bc01);this._ws&&d[s(776)](this[s(1551)][s(713)+"te"],this[s(1344)])&&(this[s(1551)]&&this[s(1551)].send(h),this[s(1198)](d.uDtfb,_0x34e00a))}}function $(a){let n=t;return a[n(316)]>=a[n(764)]}function re(a,n){let s=t,d=a[s(1772)],h=a[s(316)],w=a[s(764)],m=e[s(767)](h,n);if(e[s(725)](m,d.length)){let b=new Uint8Array(e[s(844)](2,m));b[s(1680)](d),a[s(1772)]=b}return a[s(316)]=m,m>w&&(a[s(764)]=m),h}function Q(a,n){let s=t,d=a[s(316)];if(e[s(1788)](e.kJqSj(d,n),a[s(764)]))throw new Error(s(667)+s(1236));return a.offset+=n,d}function se(a,n){let s=t,d=e[s(1139)](Q,a,n);return a[s(1772)][s(1591)](d,e[s(1090)](d,n))}function oe(a,n){let s=t,d=e[s(614)](re,a,n[s(1407)]);a[s(1772)].set(n,d)}function R(a,n){let s=t,d={vYPyV:"error",jQmxz:e[s(1044)]},h=e[s(1419)](Q,a,n),w=String[s(759)+s(755)],m=a.bytes,b="\uFFFD",p="";for(let P=0;e[s(691)](P,n);P++){let L=m[e[s(678)](P,h)],M,G,J,Z;if(e.dfnHK(e[s(407)](128,L),0))p+=e[s(1426)](w,L);else if(e[s(377)](224&L,192))if(e.BEjdP(P+1,n))p+=b;else if(M=m[e.hHloP(e.VlEiA(P,h),1)],e[s(407)](192,M)!==128)p+=b;else if(e[s(1527)](e[s(929)],s(1366)))if(Z=e[s(509)](e[s(325)](31&L,6),e[s(581)](63,M)),e[s(1852)](Z,128))p+=b;else if(e[s(863)](e[s(548)],e[s(913)])){if(!this[s(1350)+s(1418)]()||this[s(804)+"osed"])return;this[s(841)+s(1653)]?.[s(1670)+s(747)+"fig"](),this["_pingLos"+s(620)]?.[s(1314)+s(1489)](),this[s(1551)]?this[s(1572)+s(821)](1001,e[s(806)],!0):this[s(744)]()}else p+=w(Z),P++;else _0x2f2906["removeEv"+s(864)+s(1499)](s(401),_0x465fc0),_0x4b0a9b[s(1193)+s(864)+s(1499)](cmSBIq[s(387)],_0x4455ff),_0x100667[s(1193)+s(864)+s(1499)](cmSBIq[s(722)],_0x36c404);else e.nlJWQ(e[s(1150)](240,L),224)?e[s(1462)](P+2,n)?p+=b:(M=m[e[s(1440)](P+h,1)],G=m[e[s(678)](P+h,2)],e[s(1108)](e[s(1550)](M,G<<8),49344)!==32896?p+=b:(Z=e[s(509)](e.wNQMd(e[s(407)](15,L),12)|e[s(1119)](e[s(1150)](63,M),6),e[s(336)](63,G)),e[s(1672)](Z,2048)||e.edmmt(Z,55296)&&Z<=57343?p+=b:(p+=e[s(911)](w,Z),P+=2))):e[s(561)](248&L,240)?e[s(955)](e[s(1092)](P,3),n)?p+=b:(M=m[e.zvBEh(P+h,1)],G=m[e[s(1092)](P+h,2)],J=m[e[s(1400)](e[s(883)](P,h),3)],e.OGSnv(e[s(1662)](e.sGUoF(M,e[s(1878)](G,8)),e.uShkY(J,16)),12632256)!==8421504?p+=b:(Z=e.xmYJJ(e[s(558)](e[s(407)](7,L),18),e[s(1474)](e[s(336)](63,M),12))|e[s(336)](63,G)<<6|e[s(1659)](63,J),e[s(1478)](Z,65536)||Z>1114111?p+=b:(Z-=65536,p+=e[s(787)](w,e[s(616)](Z,10)+55296,e[s(1400)](1023&Z,56320)),P+=3))):p+=b}return p}function U(a,n){let s=t,d=n.length,h=0;for(let b=0;e[s(708)](b,d);b++){let p=n[s(1589)+"At"](b);e[s(1774)](p,55296)&&e[s(1595)](p,56319)&&e[s(772)](b,1)<d&&(p=e[s(1027)](e.LSisw(e.LwASu(p,10),n[s(1589)+"At"](++b)),56613888)),h+=e[s(1268)](p,128)?1:e[s(1478)](p,2048)?2:e[s(1628)](p,65536)?3:4}e[s(1593)](me,a,h);let w=e.aRDHZ(re,a,h),m=a[s(1772)];for(let b=0;e[s(810)](b,d);b++)if(e[s(379)]!==e[s(663)]){let p=n[s(1589)+"At"](b);e.phkfw(p,55296)&&e[s(935)](p,56319)&&e[s(678)](b,1)<d&&(p=e[s(1584)](e.LnSfq(e[s(710)](p,10),n[s(1589)+"At"](++b)),56613888)),e[s(1886)](p,128)?m[w++]=p:(e[s(1672)](p,2048)?m[w++]=e[s(1550)](e[s(1453)](p>>6,31),192):(e[s(1672)](p,65536)?m[w++]=e[s(1557)](e[s(1659)](e[s(1304)](p,12),15),224):(m[w++]=e[s(509)](e[s(581)](e[s(534)](p,18),7),240),m[w++]=e[s(479)](e[s(447)](e[s(616)](p,12),63),128)),m[w++]=e.xmYJJ(e.QPMJq(p>>6,63),128)),m[w++]=e[s(1394)](e[s(336)](63,p),128))}else _0x262322[s(1212)](_0x41c4ab)}function K(a,n){let s=t,d=re(a,n[s(764)]),h=a.bytes,w=n.bytes;for(let m=0,b=n[s(764)];e[s(771)](m,b);m++)h[m+d]=w[m]}function te(a){let n=t;return a.bytes[e[n(997)](Q,a,1)]}function et(a,n){let s=t,d=e.HPMAE(re,a,1);a[s(1772)][d]=n}function ge(a){let n=t;if(e[n(1223)]===n(1630))return new _0x465774(_0x3ccdcf,{data:_0x25aef2});{let s=0,d=0,h;do h=e[n(701)](te,a),e.giYeR(s,32)&&(d|=(127&h)<<s),s+=7;while(128&h);return d}}function me(a,n){let s=t;for(n>>>=0;e[s(1359)](n,128);)e.qHonM(et,a,e[s(1557)](e.uCVNU(127,n),128)),n>>>=7;e[s(338)](et,a,n)}function It(a,n){let s=t;if(e[s(527)]!==s(1401)){let d=0,h=0,w=0,m;if(m=te(a),d=e[s(1211)](127,m),e[s(1879)](128,m)&&(m=e.RJvhW(te,a),d|=e[s(641)](127,m)<<7,e[s(1834)](128,m)&&(m=te(a),d|=e.upGEg(e[s(447)](127,m),14),e[s(501)](128,m)&&(m=e[s(1248)](te,a),d|=e.mvuDE(e.ZNFOL(127,m),21),e[s(1150)](128,m)&&(m=e[s(689)](te,a),h=e[s(1108)](127,m),e[s(1723)](128,m)&&(m=te(a),h|=e.EmuDM(127,m)<<7,e[s(584)](128,m)))))))if(e[s(1527)](e.noSXP,"ypikG")){if(m=e[s(469)](te,a),h|=e[s(1878)](e[s(1409)](127,m),14),e[s(407)](128,m)){if(e[s(692)](e[s(550)],s(375)))return e[s(1798)](this.count,this[s(1465)+s(651)]);m=e.AMaFH(te,a),h|=e[s(396)](e[s(373)](127,m),21),128&m&&(m=e[s(677)](te,a),w=e.nVgXW(127,m),e[s(1834)](128,m)&&(m=e[s(1261)](te,a),w|=e[s(345)](e.nOeny(127,m),7)))}}else{let{value:b,offset:p}=e[s(622)](_0x4520c8,_0x411e65,_0x5e0bc6);_0x39ae8b=p,_0x538ce3=e[s(1544)](e.uShkY(_0x1d71e5,8),0),_0x7184a6+=b}return{low:d|e.IivgU(h,28),high:h>>>4|e[s(1827)](w,24),unsigned:n}}else{e[s(1096)](_0xe29b5e,_0x17eb7f,42);let d=_0x4bbb6c();e[s(648)](_0x3f93d6,_0x544c94,d),e[s(1467)](_0x1a4383,_0x6af406,d[s(764)]),e[s(435)](_0x426956,_0x4488e2,d),e.rLbri(_0x55866e,d)}}function pt(a,n){let s=t,d=e.smdDS(n[s(735)],0),h=e[s(1414)](e[s(1749)](n[s(735)],28),e[s(413)](n[s(1372)],4))>>>0,w=e.Vyvka(n[s(1372)],24),m=e[s(919)](0,w)?e[s(1510)](0,h)?d<16384?d<128?1:2:e[s(895)](d,2097152)?3:4:e[s(1886)](h,16384)?h<128?5:6:e.PdsUB(h,2097152)?7:8:e[s(1852)](w,128)?9:10,b=e.ZAIYM(re,a,m),p=a[s(1772)];switch(m){case 10:p[b+9]=e[s(1131)](w,7)&1;case 9:p[e.xBPzp(b,8)]=e[s(1199)](9,m)?e.gEFMY(128,w):e[s(1453)](127,w);case 8:p[e[s(1822)](b,7)]=m!==8?e[s(1557)](h>>>21,128):e[s(1800)](e.qvVWD(h,21),127);case 7:p[e.xBPzp(b,6)]=e[s(1164)](7,m)?e[s(362)](h,14)|128:e.pHKpo(e[s(1345)](h,14),127);case 6:p[b+5]=e[s(1278)](6,m)?e[s(1216)](h,7)|128:e[s(1723)](e[s(1599)](h,7),127);case 5:p[e[s(567)](b,4)]=e.IuoIp(5,m)?e[s(968)](128,h):e[s(830)](127,h);case 4:p[e[s(1844)](b,3)]=e[s(1753)](4,m)?d>>>21|128:e[s(1522)](d>>>21,127);case 3:p[e[s(403)](b,2)]=m!==3?e[s(968)](e.sNDfP(d,14),128):e.EmuDM(d>>>14,127);case 2:p[b+1]=e[s(1272)](2,m)?e.sPqaR(e[s(1384)](d,7),128):e[s(1271)](d,7)&127;case 1:p[b]=m!==1?e.xmYJJ(128,d):e[s(1854)](127,d)}}function tn(a){return e[t(540)](v,a)}function Ut(a){return S(a)}let nn=65536,Qr="\0\0\0\0\0\0\0\0",Ee=e[t(1831)](nn,nn),Te=e[t(1183)](Ee,Ee),ir=Te/2,Ne=String[t(337)+"e"].charCodeAt;class he{constructor(n,s,d){let h=t;this[h(1115)]=!0,this[h(735)]=e[h(1814)](0,n),this[h(1372)]=0|s,this[h(1661)]=!!d}static[t(1115)](n){return n&&e[t(1435)](!0,n.isLong)}static[t(1364)](n,s,d){return new he(n,s,d)}static[t(1244)+"s"](n,s,d){let h=t;return d?he[h(1244)+h(367)](n,s):he[h(1244)+"sBE"](n,s)}static[t(1244)+t(367)](n,s){let d=t;return new he(e[d(1414)](e[d(969)](e.dTWFK(n[0],n[1]<<8),e[d(558)](n[2],16)),e[d(1691)](n[3],24)),e[d(968)](e[d(1306)](n[4]|e[d(1878)](n[5],8),e[d(1808)](n[6],16)),e[d(1602)](n[7],24)),s)}static[t(1244)+t(1207)](n,s){let d=t;return new he(e[d(1466)](e[d(640)](e[d(1119)](n[4],24),n[5]<<16)|e[d(1161)](n[6],8),n[7]),e[d(1814)](e[d(1306)](n[0]<<24,e[d(345)](n[1],16)),n[2]<<8)|n[3],s)}static[t(922)](n){let s=t;return n===Qr?sl:new he(e[s(1271)](e.Wvmwf(e[s(1234)](e[s(1135)](Ne[s(903)](n,0),e[s(1827)](Ne.call(n,1),8)),e.fLXjf(Ne[s(903)](n,2),16)),Ne[s(903)](n,3)<<24),0),e[s(1384)](e[s(1135)](e[s(400)](e.wuikP(Ne.call(n,4),e[s(1036)](Ne.call(n,5),8)),e[s(1808)](Ne[s(903)](n,6),16)),e[s(573)](Ne[s(903)](n,7),24)),0),!0)}[t(1472)](){let n=t;return String[n(759)+n(755)](e[n(1879)](255,this[n(735)]),e[n(1836)](e[n(1327)](this.low,8),255),e.ZNFOL(e[n(433)](this.low,16),255),e[n(1544)](this[n(735)],24),255&this[n(1372)],e[n(881)](e.LRthl(this[n(1372)],8),255),e[n(830)](this.high>>>16,255),this[n(1372)]>>>24)}static[t(1204)+"er"](n,s=!0){let d=t;if(e.QbyQZ!==e.GlpFk){if(e.zsnsH(isNaN,n))return s?Rp:sl;if(s){if(d(1143)!==e[d(1015)])return this[d(1551)]?this[d(1551)][d(713)+"te"]:this._options[d(1072)+d(631)]?this[d(1323)+"NG"]:this[d(1685)];if(e[d(798)](n,Te))return Pp}else if(e[d(970)]!=="vGpKT"){if(e.PxrRT(n,-ir))return Op;if(e.SPCDz(e.tflof(n,1),ir))return Dp}else throw this[d(744)+d(1188)]=!1,_0xb14caa;return he[d(1364)](e[d(1686)](n%Ee,0),e[d(400)](e.bYkvl(n,Ee),0),s)}else return{bytes:_0x598c31,offset:0,limit:_0x5050f7[d(1407)]}}[t(812)](){let n=t,s={eomoC:function(d,h){return e[q(865)](d,h)}};return e.JQKIJ(e[n(606)],n(698))?(_0x131ced[n(1493)](CLQjpG[n(1167)](_0x5ccaa0,this),_0xa88557),CLQjpG[n(1167)](_0x41cc92,_0x1ccb65[n(1546)](this))):this[n(1661)]?e[n(856)](e[n(324)](this[n(1372)],0),Ee)+e[n(1260)](this[n(735)],0):e.zaKiK(e[n(590)](this[n(1372)],Ee),e[n(1098)](this[n(735)],0))}[t(1851)](){let n=t;return e[n(1456)](0,this.high)&&e[n(937)](0,this.low)}add(n){let s=t,d={UeRux:function(h,w){return h<<w},ZgMAL:function(h,w){return h&w},PvbCb:function(h,w){return e[q(1296)](h,w)},FuQlk:function(h,w){return h<w},oMRbj:function(h,w){return e[q(1596)](h,w)}};if(e.UXdvy!==e.UXdvy)_0x2964ab=AjmxIA[s(539)](AjmxIA[s(1303)](31,_0x181304),6)|AjmxIA[s(388)](63,_0x249526),AjmxIA[s(959)](_0x535d6c,128)?_0x592aee+=_0x3cec4f:(_0xc6cdfc+=AjmxIA.oMRbj(_0x4446d2,_0x3d21b5),_0x2c5831++);else{he[s(1115)](n)||(n=he[s(1204)+"er"](n));let h=e.lfBYz(this.high,16),w=e[s(1453)](65535,this[s(1372)]),m=this.low>>>16,b=e.MQmpX(65535,this[s(735)]),p=e[s(1761)](n[s(1372)],16),P=e[s(320)](65535,n[s(1372)]),L=e[s(1260)](n[s(735)],16),M=e[s(1004)](65535,n.low),G=0,J=0,Z=0,we=0;return we+=e[s(1079)](b,M),Z+=e[s(1301)](we,16),we&=65535,Z+=e[s(1756)](m,L),J+=Z>>>16,Z&=65535,J+=e[s(1780)](w,P),G+=e[s(1098)](J,16),J&=65535,G+=e.APKqq(h,p),G&=65535,he[s(1364)](e[s(1620)](e.IivgU(Z,16),we),e[s(1135)](e[s(766)](G,16),J),this.unsigned)}}[t(936)](n){let s=t;return he.isLong(n)||(n=he[s(1204)+"er"](n)),this[s(1661)]!==n[s(1661)]&&e[s(1510)](this[s(1372)]>>>31,1)&&e[s(1527)](e[s(428)](n[s(1372)],31),1)?!1:e.PqrGC(this[s(1372)],n.high)&&this[s(735)]===n.low}[t(1054)](){let n=t;return e[n(1102)](-1,this[n(735)])&&this[n(1372)]===-1?he[n(1364)](0,0,this[n(1661)]):e[n(1435)](-1,this[n(735)])?he.fromBits(0,e[n(1282)](this.high,1),this[n(1661)]):he[n(1364)](e[n(1092)](this.low,1),this[n(1372)],this.unsigned)}toBytes(n){let s=t;if(e[s(1743)](e[s(1023)],e.naNYh))return n?this[s(1609)+"E"]():this.toBytesBE();this[s(1823)+"ileName"]=_0x536ac9}[t(1609)+"E"](){let n=t,s=this[n(1372)],d=this[n(735)];return[e[n(1247)](255,d),e[n(502)](e[n(1739)](d,8),255),e[n(1098)](d,16)&255,e.sgBXe(d,24),e.dBmcV(255,s),e[n(324)](s,8)&255,e[n(407)](e.BUDtv(s,16),255),e[n(1280)](s,24)]}[t(1389)+"E"](){let n=t,s=this.high,d=this[n(735)];return[s>>>24,e.UPQXF(s>>>16,255),e.zsnWR(e.BUDtv(s,8),255),e[n(1521)](255,s),e[n(1608)](d,24),e[n(791)](e[n(571)](d,16),255),e.oRpRX(e[n(770)](d,8),255),255&d]}}let sl=new he(0,0,!1),Rp=new he(0,0,!0),Dp=he.fromBits(-1,2147483647,!1),Pp=he[t(1364)](-1,-1,!0),Op=he.fromBits(0,-2147483648,!1);var rn=(function(a){let n=t;return a[a[e.lQOVg]=5001]="NATIVE_E"+n(1026),a[a[e[n(905)]]=5002]=e[n(905)],a[a[e[n(619)]]=5003]=e[n(619)],a[a[n(1348)+n(1288)]=5004]=n(1348)+"ERROR",a[a[e[n(688)]]=5005]=e[n(688)],a})({});class sr{constructor(n){let s=t,d={AoPgL:function(h,w){return e[q(585)](h,w)},dndVb:function(h,w){return e[q(1004)](h,w)}};e[s(1539)]===e[s(546)]?(_0x370899[_0x2cd457++]=mYFJzN[s(1043)](mYFJzN[s(1484)](_0x346259>>18,7),240),_0x13f02e[_0x165089++]=mYFJzN[s(1484)](_0x188b8f>>12,63)|128):(this[s(327)]=n,this[s(1889)]=null)}}class ol extends sr{constructor(n,s){let d=t;super(n),this[d(736)]=s&&s[d(736)]||null}}class al extends sr{constructor(n,s){let d=t;super(n),this[d(1069)]=s&&s.error||null,this[d(1460)]=s&&s[d(1460)]||0,this[d(902)]=s&&s[d(902)]||"",this[d(1473)]=s&&s[d(1473)]||0,this[d(736)]=s&&s.message||"",this[d(1105)]=s&&s[d(1105)]||5001}}class cl extends sr{constructor(n,s){let d=t;super(n),this[d(1105)]=s&&s[d(1105)]||0,this[d(1606)]=s&&s[d(1606)]||"",this[d(1290)]=s&&s[d(1290)]||!1,this[d(1171)+d(831)]=s&&s[d(1171)+d(831)]||!1}}class dl extends sr{constructor(n,s){let d=t;super(n),this[d(815)]=s&&s[d(815)]||null}}class ll extends dl{constructor(n,s){let d=t;super(n),this[d(815)]=s&&s[d(815)]||null,this[d(736)]=s&&s[d(736)]||null}}class ul extends sr{constructor(n,s){let d=t;e[d(1203)](e[d(1869)],e[d(1869)])?(super(n),this[d(815)]=s&&s.data||null):_0x5df468[d(1399)+"d"]&&(this["_navigat"+d(1418)]()&&(!this[d(1551)]||e[d(1292)](this._ws[d(713)+"te"],this.OPEN)||e.ddHZk(this[d(1551)][d(713)+"te"],this[d(1323)+"NG"]))&&this[d(482)+d(395)](),this[d(1134)+"er"]&&_0x7820d5[d(1509)+"Listener"]("online",this[d(482)+d(395)]),this[d(1134)+"er"]&&_0x2db010[d(1509)+d(1559)](e.xNGap,this[d(482)+d(1208)]))}}function dt(a,{message:n,code:s,error:d}){return new al(a,{message:n,code:s,error:d})}function gt(a,{code:n,reason:s,wasClean:d,willReconnect:h}){return new cl(a,{code:n,reason:s,wasClean:d,willReconnect:h})}function fl(a,{data:n,message:s}){let d=t;return e[d(1567)](e[d(1332)],e[d(1264)])?new ll(a,{data:n,message:s}):new _0x5fca2b(_0x597c57,_0x1ae17b,_0x489c1c)}function hl(a,{data:n}){return new ul(a,{data:n})}function ma(a,{message:n}){return new ol(a,{message:n})}class xl{constructor(n,s){let d=t;this.endpoints=n,this.maxRetries=s,this[d(789)+d(718)]=0,this["currentE"+d(858)+d(1289)+"t"]=0}[t(1670)+t(747)+"fig"](){let n=t;this[n(789)+n(718)]=0,this[n(1764)+n(858)+n(1289)+"t"]=0}resetTries(){let n=t;if(e.yCocr(e.gzjAW,e[n(1103)])){let s={SQYeQ:function(d,h){return PBuhzc.RJvhW(d,h)}};return function(...d){let h=n;return _0x571ea0.apply(_0x4b2724(this),d),s[h(440)](_0x513a69,_0x500cbd.get(this))}}else this[n(1764)+n(858)+n(1289)+"t"]=0}[t(346)+t(1548)+"nt"](){let n=t,s={ZQBpi:function(d,h,w){return e[q(1305)](d,h,w)},JUdho:function(d,h){return d<h},iprpy:function(d,h){return d+h}};if(e.kQNXq!==e[n(1781)]){let d=PCpaUI[n(330)](_0x593af9,_0xd74e74,_0x404a55[n(764)]),h=_0x2a888a[n(1772)],w=_0x3ab20f.bytes;for(let m=0,b=_0x462883.limit;PCpaUI[n(1625)](m,b);m++)h[PCpaUI[n(1018)](m,d)]=w[m]}else return this.endpoints[this[n(789)+"ndex"]]}["getCurre"+t(1548)+"ntTriesCount"](){let n=t;return this[n(1764)+n(858)+n(1289)+"t"]}[t(1024)+t(992)+"es"](){let n=t;return!!(e[n(554)](this[n(789)+n(718)],this[n(1056)+"s"][n(1407)])||e.HeRWg(this[n(789)+"ndex"],e.pPJvu(this[n(1056)+"s"][n(1407)],1))&&e.oSIlT(this[n(1764)+n(858)+n(1289)+"t"],this.maxRetries))}[t(962)+t(988)+t(1841)+t(1498)+t(657)](){let n=t,s={zWdlt:function(d,h,w){return e[q(715)](d,h,w)},kXfMG:e[n(465)],jkqsT:function(d,h,w){return e[n(1096)](d,h,w)}};if(e[n(1699)]===e[n(769)]){let d=s[n(714)](_0x36edce,s[n(523)],{message:this[n(594)+n(872)+n(1815)](_0x1a108d)});this[n(985)](s[n(523)],d);let h=s[n(1376)](_0xb1e39c,n(1769),{reason:this[n(594)+"rrorMess"+n(1815)](_0x40e966)});this[n(985)]("close",h)}else return e[n(521)](this[n(789)+n(718)],this[n(1056)+"s"][n(1407)])?!0:e[n(1882)](this[n(1764)+n(858)+n(1289)+"t"],this.maxRetries)}["replaceBackupEnd"+t(836)+t(839)+t(1308)](){let n=t;return this["currentE"+n(858)+n(1289)+"t"]=1,this[n(789)+"ndex"]++,this[n(1056)+"s"][this["currentI"+n(718)]]}[t(346)+t(1548)+"ntAndUpdateCount"](){let n=t,s={bdQBx:function(d,h,w){return d(h,w)}};if(e[n(1766)](n(868),n(868)))return this[n(1764)+n(858)+n(1289)+"t"]++,this[n(346)+n(1548)+"nt"]();{let d=JQBAaH.bdQBx(_0x361e60,_0x5b0270,_0x25f6c0);return _0xe18978.bytes[n(1591)](d,d+_0x484dcb)}}}let or=(e.POcjp!=typeof globalThis&&e[t(1206)](t(1607),globalThis[t(1519)+t(855)][t(445)])||e[t(1820)]("undefined",typeof window)&&e[t(1205)](e.MSjel,window[t(1519)+t(855)][t(445)]))&&e[t(1601)]("undefined",typeof document),On=e.amGLW(e[t(490)],typeof globalThis)&&(e[t(341)](e[t(807)],globalThis[t(1519)+t(855)][t(445)])||e[t(906)](e[t(1688)],globalThis[t(1519)+t(855)][t(445)]))&&e[t(857)](e[t(490)],typeof tt),ei=(e[t(1367)](e.POcjp,typeof globalThis)&&e[t(341)](t(1022),globalThis[t(1519)+t(855)][t(445)])||e.yRXdG(t(661)+"d",typeof globalThis)||e[t(1367)](e[t(490)],typeof globalThis)&&!!globalThis[t(1355)+"Bridge"])&&e[t(857)](t(661)+"d",typeof wx),ti=e[t(1529)](e[t(490)],typeof globalThis)&&(e[t(1768)](e[t(1688)],globalThis[t(1519)+"tor"][t(445)])||e[t(1219)](t(417)+t(1397)+t(1189),globalThis[t(1519)+t(855)][t(445)])||e[t(1597)](e[t(1385)],globalThis["construc"+t(855)][t(445)]))&&e[t(572)](e.POcjp,typeof self),Lp=e.YkBek(e.POcjp,typeof globalThis)&&e[t(1435)](e[t(807)],globalThis.constructor[t(445)])&&e[t(490)]!=typeof global&&e[t(1597)](e[t(807)],global[t(1519)+t(855)].name)&&e[t(825)](e[t(490)],typeof process)&&!!process[t(986)];class wa{constructor(){let n=t;this[n(1767)+"rs"]={}}[t(985)](n,...s){let d=t,h={xhxGT:function(w,m){return w instanceof m},MEWls:d(1748)+"in;chars"+d(720),CmTZB:e[d(637)],wVlyM:e[d(1080)],LUMSv:e.kBoTe,DwFWG:e[d(603)],SDhag:e.FjADN,ikKsE:function(w,m,b,p){return e[d(1637)](w,m,b,p)}};if(e[d(610)]===e[d(610)]){let w=this[d(1767)+"rs"][n];if(w)w[d(1790)]()[d(1858)](m=>m.fn[d(1493)](m[d(1330)],s));else if(e[d(339)](e[d(465)],n)&&!this.onerror){let m=s[d(1407)]&&s[0];if(e.GtapL(m,Error))throw m;let b=new Error(e[d(1299)](e.Cxhuz,m?e[d(1582)](e[d(403)](" (",m[d(736)]),")"):""));throw b[d(1005)]=m,m}return this}else{let w=h.xhxGT(this._options["payloadE"+d(1293)],_0x5b4432)?{force:!!this._options["payloadE"+d(1293)][d(364)],encoding:this[d(1224)][d(532)+"ncoding"][d(1867)]?this[d(1224)][d(532)+d(1293)][d(1867)][d(827)](/\s/g,"")["toLowerC"+d(1267)]():""}:{force:!1,encoding:this[d(1224)][d(532)+d(1293)]?this[d(1224)]["payloadE"+d(1293)][d(827)](/\s/g,"").toLowerCase():""},m=_0x100acd[d(532)+"ncoding"]?_0xfe85c9[d(532)+d(1293)].replace(/\s/g,"")["toLowerC"+d(1267)]():"",b=this[d(1224)][d(1700)+d(888)]instanceof _0x4ef2b8?{force:!!this._options[d(1700)+d(888)][d(364)],type:this._options[d(1700)+d(888)][d(327)]?this._options["payloadT"+d(888)][d(327)].replace(/\s/g,"")[d(1461)+d(1267)]():""}:{force:!1,type:this[d(1224)][d(1700)+d(888)]?this[d(1224)][d(1700)+d(888)][d(827)](/\s/g,"")[d(1461)+"ase"]():""},p=_0x25f5b5["payloadT"+d(888)]?_0x2c2cb8[d(1700)+d(888)][d(827)](/\s/g,"")[d(1461)+d(1267)]():"",P=b.force?b[d(327)]:p||b[d(327)],L=w[d(364)]?w[d(1867)]:m||w.encoding,M=[h[d(1508)],h[d(1514)],h.wVlyM,h[d(826)]],G=[h.DwFWG,h[d(1285)]];this[d(1224)]["enableTr"+d(1388)+"extPayload"]&&M[d(317)](P)&&(!L||G[d(317)](L))?_0x57fe27[d(552)+"oad"]=h[d(1868)](_0x3386ee,_0x51349a[d(326)],0,_0xe7ef5a.payload[d(1232)+"th"]):_0x18cebc[d(552)+d(1100)]=""}}[t(724)](n,s){let d=t;if(n===void 0)this._listeners={};else if(e[d(1789)](void 0,s))this[d(1767)+"rs"][n]=null;else{let h=this[d(1767)+"rs"][n];if(h)for(let w=0;e[d(1515)](w,h[d(1407)]);)e[d(1650)](h[w].fn,s)?h[d(1816)](w,1):++w}return this}on(n,s,d){let h=t;return(this._listeners[n]||(this[h(1767)+"rs"][n]=[])).push({fn:s,ctx:d||this}),this}}class Np extends wa{[t(594)+t(872)+t(1815)](n){let s=t;return n[s(617)]||n[s(1225)]?(s(1128)+" "+(n[s(617)]||"")+s(984)+(n[s(1225)]||""))[s(329)]():JSON.stringify(n)}constructor(n,s,d){let h=t;super(),this[h(696)]=null,ei&&wx[h(719)+h(644)]&&(this[h(696)]=wx[h(719)+h(644)]({url:n,protocols:s,header:d,fail:this[h(1712)+"ocketFai"+h(1692)][h(547)](this),success:this[h(1712)+"ocketSuc"+h(800)+h(369)][h(547)](this)})),On&&tt[h(719)+"ocket"]&&(this[h(696)]=tt[h(719)+h(644)]({url:n,protocols:s,header:d,fail:this[h(1712)+"ocketFai"+h(1692)][h(547)](this),success:this[h(1712)+h(876)+h(800)+h(369)].bind(this)}))}[t(1712)+t(876)+t(800)+t(369)](){let n=t;Promise[n(474)]()[n(862)](()=>{let s=n,d={aAflE:s(354),MWMIj:s(1395),bMFOr:e[s(957)]};e[s(680)]!==s(1084)?(this[s(1134)+"er"]&&_0x465a45[s(1509)+"Listener"](d[s(843)],this[s(482)+"nLine"]),this[s(1134)+"er"]&&_0x3bd12a[s(1509)+s(1559)](s(536),this["_handleO"+s(1208)]),this[s(1134)+"er"]&&_0x55ddb6[s(1509)+s(1559)](d[s(512)],this[s(511)+"ageHide"]),this._isBrowser&&_0x10fc8[s(1509)+"Listener"](d[s(1258)],this[s(511)+s(1861)])):this[s(781)+s(1433)]()})}[t(1712)+"ocketFailHandler"](n){let s=t,d={ENatX:e[s(1542)],dzWRN:function(h,w){return e[s(1093)](h,w)},cEsQq:e[s(979)],REFky:function(h,w,m){return e[s(1744)](h,w,m)},kawyj:e[s(465)],xkynl:function(h,w,m){return h(w,m)},LqDvv:e[s(460)]};Promise[s(474)]()[s(862)](()=>{let h=s,w={FIXid:d.ENatX};if(d[h(1257)](h(1125),d.cEsQq))switch(_0x137b3c){case w[h(1821)]:case h(1682):return{[h(1381)+_0x580ebe]:1,"x-tt-env":_0x456d8e};default:return{}}else{let m=d.REFky(dt,"error",{message:this[h(594)+h(872)+"age"](n)});this[h(985)](d[h(1083)],m);let b=d.xkynl(gt,d[h(1324)],{reason:this[h(594)+"rrorMess"+h(1815)](n)});this[h(985)](d[h(1324)],b)}})}[t(781)+t(1433)](){let n=t,s={YyHXd:e[n(460)],xLpQs:function(d,h){return e[n(339)](d,h)},oMygt:e[n(630)],Kuyut:function(d,h,w){return d(h,w)},cQvJL:e[n(1526)]};this[n(696)][n(975)](d=>{let h=n;this[h(985)](e[h(1063)],hl(e.srEla,{...d,data:d[h(617)]||""}))}),this[n(696)][n(699)](d=>{let h=n;this[h(985)](s[h(741)],gt(s[h(741)],{...d}))}),this[n(696)][n(1165)+"e"](d=>{let h=n;if(s[h(1487)](s.oMygt,"MRfOd"))try{this._qosDB?.[h(1769)](),this[h(559)]=void 0}catch(w){_0xb8d322.log(w)}else this[h(985)]("message",s[h(1505)](fl,s.cQvJL,{...d}))}),this._socket[n(348)](d=>{let h=n;this[h(985)](h(1069),e[h(1197)](dt,e[h(465)],{...d,message:d[h(617)]||""}))})}[t(596)](n){let s=t,d={VunNG:e.pzbLN,vnOGd:function(h,w,m){return e[q(1652)](h,w,m)},eZpzA:function(h,w,m){return h(w,m)}};if(e.OmVPf(n,Uint8Array)){let h=n[s(566)][s(1790)](n[s(1636)+"et"],e[s(1765)](n[s(1232)+"th"],n[s(1636)+"et"]));this[s(696)]&&this._socket.send({data:h,fail:w=>{let m=s;this[m(985)](d[m(1107)],d[m(1507)](dt,d[m(1107)],{message:this["_formatE"+m(872)+m(1815)](w)}))}})}else this[s(696)]&&this._socket[s(596)]({data:n,fail:h=>{let w=s;this[w(985)](w(1069),d[w(1052)](dt,d[w(1107)],{message:this["_formatE"+w(872)+w(1815)](h)}))}})}[t(1769)](n,s){let d=t;if(e[d(1007)](e.iszPR,e.ycdPw))this[d(696)]&&this[d(696)][d(1769)]({code:n,reason:s});else return _0x3c5b54[d(474)]()}[t(1509)+"Listener"](n,s){this.on(n,s)}["removeEv"+t(864)+"ner"](n,s){this.off(n,s)}get[t(713)+"te"](){return this[t(696)].readyState}get[t(867)+"pe"](){let n=t;return this[n(696)][n(867)+"pe"]}set[t(867)+"pe"](n){}get[t(1311)](){let n=t;return this[n(696)][n(1311)]}get[t(1438)](){let n=t;return this._socket[n(1438)]}get[t(530)+"ns"](){let n=t;return this[n(696)][n(530)+"ns"]}get[t(411)+t(1113)](){return 0}}function Mp(a,n){let s=t;if(e.iPrdq(e[s(484)],e[s(424)]))_0x9aa666=_0x54e956[e[s(1079)](_0x19b81b,_0x2ebdfe)+1],e[s(1292)](192&_0x302cc6,128)?_0x2661fa+=_0x1c572d:(_0x59f2c9=e[s(1792)](e[s(1805)](e[s(881)](31,_0x43aa6a),6),e[s(1854)](63,_0x46e552)),_0x11935d<128?_0x3a7580+=_0x4f87c9:(_0x1ede10+=e.rdyIN(_0x34f3cb,_0xd978b5),_0x1f0e8f++));else{if(n)return new n(a[s(1311)],a[s(1438)]);if(e[s(1129)](ei,On))return new Np(a[s(1311)],a.protocol,a[s(1776)]);if(e.KyhUy(or,ti)&&e[s(1367)](e.POcjp,typeof WebSocket)&&WebSocket)return new WebSocket(a[s(1311)],a[s(1438)+"s"])}}function Bp(a){let n=t,s=e[n(1663)][n(557)]("|"),d=0;for(;;){switch(s[d++]){case"0":return!1;case"1":if(ei&&wx[n(719)+n(644)])return!0;continue;case"2":if(On&&tt[n(719)+"ocket"])return!0;continue;case"3":if(a)return!0;continue;case"4":if(e[n(941)](or,ti)&&e[n(1820)](e.POcjp,typeof WebSocket)&&WebSocket)return!0;continue}break}}function pl(a,n,s){let d=-1;async function h(w){let m=q;return e[m(1369)](w,d)?Promise[m(414)](new Error(m(1097)+m(819)+"ltiple t"+m(676)+"process")):(d=w,e[m(1494)](w,s[m(1407)])?Promise[m(474)]():s[w][m(547)](a)(n,h[m(547)](null,e[m(1582)](w,1))))}h(0)}function gl(a){let n=t,s=0,d=0;for(let h=0;e[n(1803)](h,a[n(1407)]);++h)d=a[n(1589)+"At"](h),e[n(1886)](d,128)?s+=1:d<2048?s+=2:e[n(1784)](64512,d)===55296&&(64512&a[n(1589)+"At"](e[n(1160)](h,1)))===56320?(++h,s+=4):s+=3;return s}function ml(a,n,s){let d=t;if(e.XKjRC(e[d(853)],d(378)))this[d(985)](e[d(1063)],_0x19e324),this[d(1701)]&&this[d(1701)](_0x477fab);else{if(e[d(1852)](s-n,1))return"";let h="";for(let w=n;w<s;){let m=a[w++];if(e.arKCO(m,127))h+=String[d(759)+d(755)](m);else if(e[d(1133)](m,192)&&e[d(371)](m,224))h+=String[d(759)+d(755)](e[d(1722)](e[d(794)](31&m,6),e[d(1347)](63,a[w++])));else if(e.BLqXK(m,224)&&e.Nkpcr(m,240))h+=String[d(759)+d(755)](e.PuJDw(e[d(1144)](e[d(340)](15,m)<<12,e.SQuVx(e[d(336)](63,a[w++]),6)),63&a[w++]));else if(e[d(1774)](m,240)){let b=e[d(968)](e.QDGXT(e[d(1144)](e[d(573)](e[d(740)](7,m),18),e[d(870)](e[d(458)](63,a[w++]),12)),e[d(1351)](63,a[w++])<<6),e[d(336)](63,a[w++]))-65536;h+=String[d(759)+d(755)](e[d(1644)](55296,b>>10)),h+=String[d(759)+d(755)](e[d(1566)](56320,1023&b))}}return h}}function _a(a,n,s){let d=t,h={IZoZE:function(w,m){return e[q(1342)](w,m)}};if(e.yCocr("opnDc",e[d(1853)]))e.oxMVV(_0x31264a,_0x8c9b03,8),e[d(636)](_0x215e7f,_0x171c33,_0x2ab38e);else{let w=s,m,b;for(let p=0;e[d(708)](p,a[d(1407)]);++p)if(m=a[d(1589)+"At"](p),e[d(499)](m,128))n[s++]=m;else if(e[d(1803)](m,2048))n[s++]=e[d(1550)](e.qPcqP(m,6),192),n[s++]=e.LLzOa(63&m,128);else if(e[d(1156)](e.pircW(64512,m),55296)&&e.byWzj(64512&(b=a[d(1589)+"At"](e[d(1282)](p,1))),56320))if(d(1538)===e[d(871)])this[d(1764)+d(858)+d(1289)+"t"]=0;else{let P=e.UpgEP.split("|"),L=0;for(;;){switch(P[L++]){case"0":n[s++]=e.wVulW(e.XrfuR(m,18),240);continue;case"1":n[s++]=e[d(1814)](e[d(1659)](e[d(1304)](m,12),63),128);continue;case"2":++p;continue;case"3":n[s++]=e[d(754)](e[d(1140)](e[d(616)](m,6),63),128);continue;case"4":m=e.LnSfq(65536,e.yuHHa(e[d(1800)](1023,m),10))+e[d(791)](1023,b);continue;case"5":n[s++]=e[d(754)](e.HPVlp(63,m),128);continue}break}}else if(e[d(1789)](d(1019),d(1019)))n[s++]=e[d(1722)](e.RtkQU(m,12),224),n[s++]=e[d(517)](e[d(840)](m,6)&63,128),n[s++]=e.lQAlj(63,m)|128;else return _0x4a9b15&&(_0x51ffc7=(0,_0xde8270[cOLAVK.IZoZE(_0xf95851,_0x11e498)[0]])(_0x1b86f8=0)),_0x307813;return e[d(1375)](s,w)}}async function wl(a){let n=t;if(e[n(521)](e[n(1710)],typeof a)){let s=new Uint8Array(gl(a));return e[n(1637)](_a,a,s,0),s}return a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a.buffer,a.byteOffset,a[n(1232)+"th"])}function Fp(a){let n=t;try{return e[n(1710)]!=typeof a&&(e.TvsEH(a,ArrayBuffer)||a[n(566)]&&e[n(520)](a[n(566)],ArrayBuffer))||e[n(1820)](e[n(1710)],typeof a)?"":(JSON[n(383)](a),"applicat"+n(852))}catch{return e[n(802)](e[n(1710)],typeof a)?e.fMbzN:""}}let zp=(a,n)=>{let s=t;if(e[s(1073)]===e[s(1073)])switch(a){case e[s(1542)]:case e[s(1660)]:return{[s(1381)+a]:1,"x-tt-env":n};default:return{}}else{let d=new _0x500acf(e[s(844)](2,_0x41988a));d.set(_0x445296),_0x497c31[s(1772)]=d}};class Up{constructor(n){let s=t;this.maxLossCount=n,this[s(1321)]=0}[t(964)](){let n=t;this[n(1321)]++}["checkRea"+t(444)+"nt"](){let n=t;return e[n(504)](this[n(1321)],this[n(1465)+"ount"])}[t(1314)+t(1489)](n=0){let s=t;this["maxLossC"+s(651)]=n,this[s(1321)]=0}}async function Hp(a){let n=t,s={vKSmF:function(d,h){return e[q(1281)](d,h)},AWoZB:e[n(1793)],eqdwo:function(d,h){return d+h},zeyos:function(d,h){return d+h},HjiFn:"aTSym",rGfMl:function(d,h){return e[n(1707)](d,h)},pOhFl:e[n(1679)],YIeRW:e[n(1340)],VsRho:e.hIfCg,ZFEpA:function(d,h){return d===h},uAgmf:e[n(491)],bwDxO:e[n(481)]};if(n(1592)!==e[n(1283)])return new Promise(d=>{let h=n,w={ZfEpa:function(m,b){return s[q(480)](m,b)},QuPeU:function(m,b){return s[q(1535)](m,b)}};if(s.HjiFn!==s.HjiFn)_0xf22331[h(1888)][h(1378)+h(1392)](_0x2dee62);else{if(!or)return s[h(1187)](d,h(376)+h(1606));try{let m=document[h(1356)+h(1846)](s.pOhFl);window["frontier"+h(1420)]=b=>{let p=h;document[p(1888)][p(1130)+p(1392)](m),window[p(1126)+p(1420)]=void 0,s[p(1655)](d,b&&b[p(1725)]||s[p(1318)])},m[h(327)]=s.YIeRW,m[h(1634)]=a[h(827)](/^ws/,s[h(681)])+("&jscallb"+h(945)+"tierJSONP");try{if(s.ZFEpA(s[h(824)],s.bwDxO)){let p=""+_0xa33bad[h(1552)](),P=_0x2ba1a0||(_0x3b040a=_0x153590(_0x1f9805)),L=_0x2ad5c4[h(1747)]()[h(1715)](16).slice(-6);return DyHgLb[h(633)](DyHgLb.QuPeU(DyHgLb[h(1677)]("02",p),P),L)}else document.body[h(1378)+h(1392)](m)}catch{document[h(1888)][h(1130)+h(1392)](m)}}catch{window["frontier"+h(1420)]=void 0,s[h(1187)](d,s.AWoZB)}}});{let d=e[n(571)](_0x4a2e92[n(735)],0),h=e.fyFqA(_0x136861.low>>>28|e.CIAgs(_0x154c61[n(1372)],4),0),w=e.pbQcA(_0x412db3[n(1372)],24),m=w===0?h===0?d<16384?e.mEXwf(d,128)?1:2:e[n(1095)](d,2097152)?3:4:h<16384?e[n(1833)](h,128)?5:6:e[n(335)](h,2097152)?7:8:w<128?9:10,b=e[n(1139)](_0x20f00e,_0x1d2212,m),p=_0xc13691[n(1772)];switch(m){case 10:p[e[n(1644)](b,9)]=e.HzgxL(e[n(770)](w,7),1);case 9:p[b+8]=m!==9?e[n(1745)](128,w):127&w;case 8:p[e[n(1639)](b,7)]=e.Gfxjh(8,m)?e[n(1751)](e.YKnrk(h,21),128):e[n(1638)](h>>>21,127);case 7:p[e[n(1124)](b,6)]=e[n(1753)](7,m)?e[n(1544)](h,14)|128:e[n(1705)](e[n(362)](h,14),127);case 6:p[e[n(1400)](b,5)]=e.hqrft(6,m)?e[n(479)](e[n(1371)](h,7),128):h>>>7&127;case 5:p[e[n(792)](b,4)]=e[n(1278)](5,m)?128|h:e.Tohke(127,h);case 4:p[e[n(835)](b,3)]=m!==4?e[n(1778)](e[n(822)](d,21),128):e[n(1296)](e.Kgsgi(d,21),127);case 3:p[b+2]=e[n(1278)](3,m)?e[n(660)](d,14)|128:e[n(702)](e[n(907)](d,14),127);case 2:p[e[n(1569)](b,1)]=e.zTZOQ(2,m)?e[n(968)](e[n(347)](d,7),128):e[n(518)](e[n(1371)](d,7),127);case 1:p[b]=e[n(1199)](1,m)?e.qBacL(128,d):e[n(1358)](127,d)}}}function sn(a,n,s){let d=t;return!!a?.find(h=>h[d(1148)]===n&&h[d(823)]===s)}function ar(a,n){let s=t;return a?.[s(1403)](d=>d[s(1148)]===n)?.[s(823)]}let ya=null;async function Gp(){let a=t;if(e.ZLIuf(e.eFcUC,a(436)))_0x49922a[a(932)](_0x534d33);else return ya||(ya=Promise.resolve()[a(862)](Ft[a(547)](Ft,a(415)))),ya}class qp extends wa{constructor(n,s){let d=t;super(),this[d(1856)]=n,this[d(394)]=s,this[d(559)]=void 0,this["_initPro"+d(915)]=null}async[t(1697)](){await this[t(1482)]()}async[t(1482)](){let n=t;if(!this[n(559)]){if(this[n(683)+n(915)])return this._initPromise;try{let s=this[n(1856)],d=this._keyPath;this["_initPro"+n(915)]=(async()=>{let h=n,{openDB:w}=await Gp();this[h(559)]=await e[h(1587)](w,h(1126)+"_"+s,1,{upgrade(m){m[h(442)+"jectStore"](s,{keyPath:d})}})})(),await this[n(683)+n(915)]}catch(s){console.log(s)}finally{this[n(683)+n(915)]=null}}}async get(n){let s=t,d={udHoI:function(h,w){return e.QHSwN(h,w)},SzgfJ:function(h,w){return e.BumBA(h,w)}};try{if(e[s(671)]!==e[s(1065)])return await this[s(1482)](),this[s(559)]?.[s(1546)](this[s(1856)],n);_0x59f604[s(1888)][s(1130)+"ild"](_0x389884)}catch(h){e.AlOTb(e[s(1068)],e[s(1068)])?(_0x3efa09[_0x396992++]=MfyvLb[s(894)](_0xf6525f,6)|192,_0x18c030[_0x213957++]=MfyvLb[s(1657)](63,_0x1f99c3)|128):console[s(1212)](h)}}async[t(1680)](n,s){let d=t;return await this._init(),this[d(559)]?.[d(1541)](this[d(1856)],n)}async[t(522)](n){let s=t;try{return await this._init(),this[s(559)]?.[s(1562)](this._dbName,n)}catch(d){if(e[s(1410)]===e[s(745)])return _0x2e5ad6+=_0x164660&&_0x585ae1.byteLength||0,_0x406526;console[s(1212)](d)}}async[t(1173)](){let n=t;try{return e[n(1583)]===n(1025)?(await this._init(),this[n(559)]?.clear(this[n(1856)])):this[n(559)][n(1675)]}catch(s){console[n(1212)](s)}}async[t(1709)](){let n=t;return await this._init(),this[n(559)]?.getAllKeys(this[n(1856)])}async getAll(){let n=t;return await this[n(1482)](),this[n(559)]?.[n(665)](this._dbName)}async[t(1363)](){let n=t;try{this[n(559)]?.[n(1769)](),this._qosDB=void 0}catch(s){console[n(1212)](s)}}get[t(1675)](){let n=t;try{if(e[n(721)](e[n(1840)],e[n(942)]))this[n(1056)+"s"]=_0x477c68,this[n(1533)+"es"]=_0x649fd4,this[n(789)+n(718)]=0,this["currentE"+n(858)+n(1289)+"t"]=0;else return!!this._qosDB}catch(s){return console[n(1212)](s),!1}}}class jp{constructor(n,s){let d=t;this[d(1243)]=n,this[d(1579)]=s,this[d(559)]=localStorage}async[t(1697)](){}get[t(1708)](){let n=t;return n(1126)+"_"+this[n(1243)]}async[t(1546)](n){let s=t,d=this[s(559)].getItem(this._prefix);return JSON.parse(d||"{}")[n]}async[t(1680)](n,s){let d=t,h=this[d(559)].getItem(this[d(1708)]),w=JSON[d(383)](h||"{}");return w[s||n[this[d(1579)]]]=n,this[d(559)][d(1170)](this._prefix,JSON[d(1202)+"y"](w)),s||n[this._pathKey]}async del(n){let s=t;if(e[s(410)](e.KmbpQ,e[s(1877)])){let d=this[s(559)][s(1062)](this._prefix),h=JSON.parse(d||"{}");return h[n]=void 0,this._qosDB.setItem(this._prefix,JSON[s(1202)+"y"](h))}else this[s(1198)](e[s(500)],_0x323351.message),e[s(1734)](_0x5ba6d3)}async clear(){let n=t;return this[n(559)][n(1173)]()}async[t(1709)](){let n=t,s=this._qosDB[n(1062)](this[n(1708)]),d=JSON[n(383)](e[n(1721)](s,"{}"));return Object.keys(d)}async getAll(){let n=t,s=this[n(559)][n(1062)](this._prefix),d=JSON.parse(e.hxowp(s,"{}"));return Object.values(d)}[t(1363)](){return Promise[t(474)]()}get[t(1675)](){return!!this._qosDB}}class Kp{constructor(n,s){let d=t;this[d(1243)]=n,this[d(1579)]=s,this[d(559)]=On?tt:ei?wx:null}async[t(1697)](){}get[t(1708)](){return"frontier_"+this[t(1243)]}async[t(1546)](n){let s=t,d=this[s(559)][s(1849)+s(1449)](this[s(1708)]);return JSON.parse(e.KyhUy(d,"{}"))[n]}async[t(1680)](n,s){let d=t,h=this._qosDB[d(1849)+d(1449)](this[d(1708)]),w=JSON[d(383)](e[d(1129)](h,"{}"));return w[s||n[this[d(1579)]]]=n,this._qosDB["setStora"+d(1449)](this[d(1708)],JSON.stringify(w)),s||n[this[d(1579)]]}async[t(522)](n){let s=t,d=this[s(559)][s(1849)+"geSync"](this[s(1708)]),h=JSON[s(383)](d||"{}");return h[n]=void 0,this._qosDB.setStorageSync(this[s(1708)],JSON[s(1202)+"y"](h))}async clear(){return this[t(559)].clearStorageSync()}async[t(1709)](){let n=t,s=this[n(559)][n(1849)+n(1421)+"nc"](this._prefix),d=JSON[n(383)](s||"{}");return Object[n(1709)](d)}async[t(665)](){let n=t,s=this[n(559)][n(1849)+n(1421)+"nc"](this[n(1708)]),d=JSON[n(383)](s||"{}");return Object.values(d)}[t(1363)](){return Promise.resolve()}get[t(1675)](){return!!this[t(559)]}}function _l(a,n){let s=t;if(On||On)return new Kp(a,n);if(e[s(1721)](or,ti)&&e[s(1367)](e[s(490)],typeof indexedDB))return new qp(a,n);if(e.CEnSm(or,ti)&&e[s(1367)](e[s(490)],typeof localStorage))return new jp(a,n);throw new Error(s(471)+s(850)+"d")}class Wp{constructor(){let n=t;this[n(700)+n(961)+"Id"]=null,this._interval=36e5,this[n(559)]=_l(e.PEtri,e[n(323)])}async[t(700)+t(1114)](){let n=t;clearInterval(this["_interva"+n(961)+"Id"]),this[n(700)+n(961)+"Id"]=e[n(925)](setInterval,()=>{let s=n;this[s(1516)+s(1405)]()},this._interval)}async openDB(){let n=t,s={OZvna:function(d,h){return e.psbCc(d,h)},ApDIj:function(d,h){return e[q(1387)](d,h)},cZXRV:function(d,h){return d|h},aHhSe:function(d,h){return d<<h},xtefw:function(d,h){return e[q(1645)](d,h)},Npqsr:function(d,h){return e[q(1773)](d,h)},xdoqv:function(d,h){return d<h},jSbne:function(d,h){return e[q(750)](d,h)},JOTHA:function(d,h){return d<<h},IoEfj:function(d,h){return e[q(798)](d,h)},bjmAu:function(d,h){return e[q(1471)](d,h)},xHbWf:function(d,h){return e[q(1440)](d,h)},TMfie:function(d,h){return e[q(994)](d,h)},GXcXh:function(d,h){return e[q(565)](d,h)}};await this[n(559)][n(1697)]()[n(862)](()=>{let d=n;if(e[d(672)](e[d(1477)],"TnpLj"))this[d(700)+d(1114)]();else{let h=_0x29b03d[_0x254ea1++];if(AnFBBR.OZvna(h,127))_0x28d09c+=_0x371042[d(759)+d(755)](h);else if(AnFBBR.ApDIj(h,192)&&h<224)_0x56a8ab+=_0x59c4bc[d(759)+d(755)](AnFBBR.cZXRV(AnFBBR[d(931)](AnFBBR[d(1391)](31,h),6),AnFBBR[d(404)](63,_0x40028a[_0x40a3e2++])));else if(AnFBBR[d(1629)](h,224)&&AnFBBR[d(1412)](h,240))_0x5a8bdd+=_0xae2c10[d(759)+d(755)](AnFBBR.cZXRV(AnFBBR[d(1162)](AnFBBR[d(1172)](AnFBBR.Npqsr(15,h),12),AnFBBR[d(1423)](AnFBBR[d(1391)](63,_0x283a15[_0x5581a6++]),6)),AnFBBR.Npqsr(63,_0x132ede[_0x1102e8++])));else if(AnFBBR[d(1643)](h,240)){let w=AnFBBR.bjmAu(AnFBBR[d(1162)](AnFBBR[d(1162)](AnFBBR[d(1162)](AnFBBR.JOTHA(7&h,18),AnFBBR[d(404)](63,_0x21972c[_0x53a41a++])<<12),(63&_0x11e63c[_0x45b9ed++])<<6),AnFBBR[d(404)](63,_0x34f4e0[_0x3c4b33++])),65536);_0x466674+=_0x388c0d[d(759)+"Code"](AnFBBR[d(1104)](55296,AnFBBR[d(1724)](w,10))),_0x1d2f7c+=_0x462e52[d(759)+"Code"](AnFBBR[d(1104)](56320,AnFBBR[d(1656)](1023,w)))}}})}async["flushExp"+t(1405)](){let n=t;(await this[n(559)]?.[n(665)]()||[])[n(1783)](({timestamp:h})=>h<Date[n(1552)]())[n(1858)](h=>{let w=n;this[w(559)]?.del(h[w(412)+"id"])})}async del(n){let s=t;return this[s(559)]?.[s(522)](n)}async[t(1680)](n,s){let d=t;return e[d(1527)](d(419),e[d(464)])?this[d(1764)+d(858)+"riesCount"]:this._qosDB?.set({message_id:n,timestamp:s})}async[t(1546)](n){let s=t;return this._qosDB?.[s(1546)](n)}async closeDB(){let n=t;clearInterval(this[n(700)+n(961)+"Id"]),await this[n(559)]?.[n(1363)]()}get isReady(){let n=t;return this._qosDB?.[n(1675)]}}function Ea(a){let n=t;if(e.ZwlYi===e[n(1496)]){let s=!!this[n(1224)][n(592)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let d=e[n(1637)](sn,a[n(736)][n(1776)],e[n(374)],"2"),h=d&&sn(a.message[n(1776)],e[n(1518)],"1"),w=d&&e.ISqez(sn,a[n(736)].headers,e[n(350)],"1"),m=w?e[n(1476)](ar,a[n(736)][n(1776)],n(1295)+n(626)+n(1689))?.[n(557)](",")[n(1783)](Boolean)||[]:[];return{enabled:s,isQoSMessage:d,isQoSAck:h,isAckCleanupMessage:w,ackMsgIds:m}}else return this[n(1604)+n(456)+n(879)](_0xf64d41),e.BINtB(_0x3d81d0)}async function yl(){let a=t;if(e.iTPAl(e[a(1742)],e[a(1742)]))this._options[a(1136)]&&_0x1cc057[a(1212)][a(1493)](_0x5ab9fe,[e[a(1468)],..._0x47a5ff]);else return this[a(629)+"ger"]||(this[a(629)+a(1329)]=new Wp),this[a(629)+"ger"].isReady||await this["_QoSMana"+a(1329)][a(1697)](),this[a(629)+a(1329)]}async function $p(a,n){let s=t;if(e[s(919)](e[s(1059)],e[s(1059)])){let{enableAutoAck:d}=this[s(1224)],h=sn(a[s(736)][s(1776)],e[s(1564)],"1"),w=sn(a.message.headers,e.nAwoN,"1"),m=Ea[s(903)](this,a);if(e.GqgWf(d,h)){let{SeqID:b,LogID:p,service:P,LogIDNew:L,method:M}=a[s(736)];this[s(1307)]({SeqID:b,LogID:p,LogIDNew:L,service:P,method:M,headers:[{key:s(1016),value:"1"},{key:e[s(756)],value:e.CEnSm(L,"")},{key:s(1182),value:"0"}]})}w&&!m[s(757)]&&this["_dispatc"+s(1152)+s(809)](a),n()}else PBuhzc[s(490)]!=typeof _0x3abbd5&&_0x3503d2[s(1715)+s(664)]&&_0x4bafc8[s(600)+"operty"](_0x1c9173,_0xe1cdc2[s(1715)+"Tag"],{value:PBuhzc[s(1558)]}),_0x377159[s(600)+s(877)](_0x3cc95b,PBuhzc[s(950)],{value:!0})}async function Vp(a,n){let s=t;this[s(1198)](s(528),a[s(736)]),e[s(1190)](n)}async function Jp(a,n){let s=t,d=e[s(1437)](tn,await e[s(393)](wl,a[s(815)]));try{if(e[s(998)](e[s(1443)],"vDQRo")){_0x41c5d0[s(1115)](_0xb9b639)||(_0x2e0d28=_0x5351e6.fromNumber(_0x455612));let h=e[s(816)](this.high,16),w=65535&this[s(1372)],m=e.ZJClV(this[s(735)],16),b=e.cYiVY(65535,this[s(735)]),p=e.nwnRk(_0x1ec7eb[s(1372)],16),P=e[s(1719)](65535,_0x117891[s(1372)]),L=e[s(1371)](_0x4d6af5[s(735)],16),M=e[s(468)](65535,_0x21d67f[s(735)]),G=0,J=0,Z=0,we=0;return we+=e[s(403)](b,M),Z+=we>>>16,we&=65535,Z+=e[s(892)](m,L),J+=Z>>>16,Z&=65535,J+=e[s(431)](w,P),G+=e[s(1621)](J,16),J&=65535,G+=e[s(508)](h,p),G&=65535,_0x4ce836[s(1364)](e.RZuJK(Z,16)|we,e[s(1602)](G,16)|J,this.unsigned)}else if(e[s(1218)](d[s(326)],Uint8Array)){let h=e[s(723)](this._options[s(532)+s(1293)],Object)?{force:!!this[s(1224)][s(532)+"ncoding"][s(364)],encoding:this[s(1224)][s(532)+s(1293)][s(1867)]?this._options[s(532)+s(1293)][s(1867)][s(827)](/\s/g,"")[s(1461)+s(1267)]():""}:{force:!1,encoding:this[s(1224)][s(532)+s(1293)]?this[s(1224)][s(532)+s(1293)].replace(/\s/g,"")["toLowerC"+s(1267)]():""},w=d[s(532)+s(1293)]?d[s(532)+s(1293)][s(827)](/\s/g,"")[s(1461)+"ase"]():"",m=e[s(441)](this[s(1224)][s(1700)+s(888)],Object)?{force:!!this[s(1224)][s(1700)+s(888)][s(364)],type:this[s(1224)][s(1700)+s(888)][s(327)]?this._options[s(1700)+"ype"][s(327)].replace(/\s/g,"")[s(1461)+s(1267)]():""}:{force:!1,type:this[s(1224)][s(1700)+s(888)]?this[s(1224)][s(1700)+s(888)][s(827)](/\s/g,"").toLowerCase():""},b=d[s(1700)+s(888)]?d[s(1700)+"ype"][s(827)](/\s/g,"")[s(1461)+s(1267)]():"",p=m.force?m[s(327)]:b||m[s(327)],P=h[s(364)]?h.encoding:w||h[s(1867)],L=[e[s(1333)],e[s(637)],e[s(1080)],e[s(1710)]],M=[e[s(603)],e[s(1408)]];this[s(1224)]["enableTransformT"+s(1586)+"ad"]&&L[s(317)](p)&&(!P||M.includes(P))?d[s(552)+"oad"]=ml(d[s(326)],0,d[s(326)].byteLength):d[s(552)+s(1100)]=""}else d[s(552)+s(1100)]=""}catch(h){d[s(552)+s(1100)]="",console.log(h)}a[s(736)]=d,e.nvGsO(n)}function Zp(a,n,s){let d=t,h=e[d(1795)](s,8192),w=e.pSScq(h,1),m=null,b=h;return function(p){let P=d,L={eETet:function(G,J){return e.mqhdB(G,J)},UQKei:function(G,J){return e[q(1235)](G,J)},dwlgb:function(G,J){return G!=J},WzsUR:e[P(490)]};if(e[P(1066)](p,1)||p>w)return e[P(1342)](a,p);if(e[P(1001)](e[P(437)](b,p),h))if(e.IHDJO(e[P(562)],e[P(562)]))m=e[P(343)](a,h),b=0;else{if(_0x524082)return new _0x2db793(_0x3dc264[P(1311)],_0x4cdae5[P(1438)]);if(aAyUZX[P(1733)](_0x12aac7,_0x479c15))return new _0x44446f(_0x5c8d44.url,_0xf8fa4c[P(1438)],_0x22a934[P(1776)]);if(aAyUZX[P(495)](_0x40a6c8,_0x1756d7)&&aAyUZX[P(682)](aAyUZX[P(1703)],typeof _0x3be0c7)&&_0x437175)return new _0x3a3991(_0x5f165f[P(1311)],_0x39cda7[P(1438)+"s"])}let M=n[P(903)](m,b,b+=p);return e[P(940)](7,b)&&(b=e[P(1822)](e[P(1722)](7,b),1)),M}}let Yp=4294967295;function Xp(a,n,s){let d=t;if(e[d(1497)](d(642),e[d(1555)]))return e[d(911)](RangeError,e[d(678)](e[d(1110)](e[d(1568)](e[d(1582)](e[d(1031)](e[d(386)],a),e[d(1064)]),n||1),e.LAkPw),s));this[d(1804)+"sCounter"]?.[d(964)](),this[d(985)](d(1246)+d(1570)+"t","timeout"),this[d(1804)+d(620)]?.[d(1024)+d(444)+"nt"]()?this[d(1720)+"econnect"]():this[d(780)]()}function Qp(a,n,s){let d=t;if(e[d(1588)](s,Yp))throw new Error(e[d(1698)]);let h=3;for(;e.JdQgC(h,0);){let w=255&s;e[d(1637)](va,w,a,e[d(1274)](n,h)),s>>>=8,h--}return e[d(1440)](n,4)}function eg(a,n){let s=t,d=0,h=n,w=e[s(1470)](n,4);for(;e[s(691)](h,w);){let{value:m,offset:b}=ba(a,h);h=b,d=e[s(1739)](e[s(1750)](d,8),0),d+=m}return{value:d,offset:w}}function tg(a,n,s){let d=t;return a?e[d(1678)](a[d(1407)],40)?e[d(678)](e[d(1786)](_a,a,n,s),s):n[d(342)+"e"]?e.hsutd(n[d(342)+"e"](a,s),s):n.write?n.write(a,s)+s:e[d(544)](_a(a,n,s),s):s}function ng(a,n){let s=t,d=new he(e[s(360)](e[s(1398)](e.yuHHa(a[n+4],24),e[s(1428)](a[e[s(947)](n,5)],16)),e[s(750)](a[e.oOdiw(n,6)],8))|a[n+7],e[s(891)](e[s(640)](e[s(509)](e.dvqXp(a[n+0],24),e.eQeaD(a[e.APKqq(n,1)],16)),e[s(1791)](a[e.ktXJw(n,2)],8)),a[n+3]),!0);return n+=8,{value:d,offset:e[s(1649)](n,8)}}function rg(a,n,s){let d=t,h=a[d(735)],w=a[d(1372)];return n[s]=e[d(1621)](w,24),n[s+1]=e[d(818)](e[d(1301)](w,16),255),n[e[d(567)](s,2)]=e.miBit(e.jiyDl(w,8),255),n[e[d(365)](s,3)]=e[d(535)](255,w),n[e.awacv(s,4)]=h>>>24,n[s+5]=e[d(1502)](e[d(1384)](h,16),255),n[e[d(431)](s,6)]=e.UPQXF(e.wVEgY(h,8),255),n[e[d(730)](s,7)]=e[d(1854)](255,h),s+=8,s}function ba(a,n){let s=t;return a[s(1222)+"8"]?{value:a[s(1222)+"8"](n),offset:n+1}:{value:e[s(569)](255,a[n]),offset:e[s(1451)](n,1)}}function va(a,n,s){let d=t;return n[d(543)+"t8"]?n.writeUint8(a,s):n[s]=255&a,e[d(1221)](s,1)}let ig=function(a){return new Uint8Array(a)},sg=e[t(1820)](e[t(490)],typeof Buffer)?Buffer[t(1132)+t(1201)]:e[t(1058)](Zp,ig,Uint8Array[t(337)+"e"][t(1591)]);(()=>{let a=t,n={HijIC:e[a(368)],LPPoE:function(d,h){return e.iOnvC(d,h)},ykENv:function(d,h){return e[a(517)](d,h)},omLrY:function(d,h){return d<h},NAmZN:function(d,h){return e.KKucg(d,h)},OQUDQ:function(d,h){return e[a(1161)](d,h)},PrTqA:function(d,h){return e[a(1641)](d,h)},TcMHJ:function(d,h){return e[a(515)](d,h)},pljpQ:function(d,h){return e[a(1316)](d,h)},ebsNV:function(d,h){return e[a(1409)](d,h)},MHCyl:function(d,h){return e.RTHMR(d,h)},FSKkA:function(d,h){return e[a(1659)](d,h)},QdXJG:function(d,h){return e.NngXn(d,h)},XWfXw:function(d,h){return e[a(1761)](d,h)},xqycc:function(d,h){return e[a(1750)](d,h)},YVlIL:function(d,h){return e[a(1784)](d,h)}},s=4294967295;return function(d,h,w=!0){let m=a,b=n[m(507)][m(557)]("|"),p=0;for(;;){switch(b[p++]){case"0":if(n[m(356)](d[h++],128))return{value:w?s:n[m(1053)](0,s),offset:h};continue;case"1":if(n[m(1590)](d[h++],128))return{value:w?s:n[m(1053)](0,s),offset:h};continue;case"2":if(n.omLrY(d[h++],128))return{value:w?s:0|s,offset:h};continue;case"3":s=n[m(784)](s|n[m(486)](n[m(1469)](127,d[h]),14),0);continue;case"4":s=n[m(920)](s,n[m(1469)](127,d[h])<<21)>>>0;continue;case"5":if(n[m(939)](d[h++],128))return{value:w?s:n[m(920)](0,s),offset:h};continue;case"6":s=n[m(784)](n.ebsNV(127,d[h]),0);continue;case"7":s=n.NAmZN(s|n[m(980)](n[m(1137)](127,d[h]),7),0);continue;case"8":if(n[m(1565)](h+=5,d[m(1407)]))throw h=d.length,Xp(h,10,d[m(1407)]);continue;case"9":if(d[h++]<128)return{value:w?s:n[m(920)](0,s),offset:h};continue;case"10":return{value:w?s:n[m(920)](0,s),offset:h};case"11":s=n[m(1109)](n.TcMHJ(s,n[m(647)](n[m(318)](15,d[h]),28)),0);continue}break}}})();let og=16,Sa=32;function ag(a){let n=t,s=0,d={};for(let h=0;e[n(966)](h,a[n(1407)]);h++)d[a[h][n(466)+n(1573)]]=e[n(972)](gl,a[h][n(466)+n(1573)]),s+=e.zvBEh(14,d[a[h][n(466)+n(1573)]]);return[s,d]}function El(a,n,s){let d=t,h={HsluE:function(w,m,b){return e[q(1640)](w,m,b)},eRERN:function(w,m){return e[q(588)](w,m)},hsKIO:e[d(1265)],ZsoSz:e[d(1045)],KsHBh:function(w,m,b,p){return e[d(1587)](w,m,b,p)},Kovif:e[d(397)],BZequ:e.MnVtS,jPXaa:e.lKCCS,ueTYa:e.PyHSZ};if(e[d(1088)](e[d(462)],d(976)))LSoTnX[d(943)](_0x3a4cd7,_0x132554,LSoTnX[d(933)](127,_0x552dfa)|128),_0x423840>>>=7;else{let[w,m]=e[d(574)](ag,a),b=sg(w),p=0;return a[d(1858)](P=>{let L=d,M=h[L(893)][L(557)]("|"),G=0;for(;;){switch(M[G++]){case"0":console.log(h[L(448)],P,P[L(974)]);continue;case"1":p=rg(he[L(1204)+"er"](P[L(1631)]||n),b,p);continue;case"2":p=h.KsHBh(va,m[P[L(466)+L(1573)]],b,p);continue;case"3":console[L(1212)](h.Kovif,p);continue;case"4":console[L(1212)](h.BZequ,p);continue;case"5":p=h.KsHBh(tg,P["cursor_n"+L(1573)],b,p);continue;case"6":p=h[L(1711)](va,0,b,p);continue;case"7":console.log(h[L(712)],p);continue;case"8":console.log("name",p);continue;case"9":p=h[L(1711)](Qp,b,p,P[L(974)]||0);continue;case"10":console.log(h[L(1166)],p);continue}break}}),{frameType:Sa,headers:[{key:e.lBolV,value:s}],payload:b}}}function cg(a){let n=t,s=0,d=[];for(;e[n(990)](s,a[n(1232)+"th"]);){let{offset:h}=e[n(1266)](ba,a,s);s=h;let w={cursor_name:"",cursor:0,service:0},{value:m,offset:b}=eg(a,s);w.service=m,s=b;let{value:p,offset:P}=e[n(549)](ba,a,s);s=P,w[n(466)+n(1573)]=e[n(1623)](ml,a,s,e[n(544)](s,p)),s+=p;let{value:L,offset:M}=e[n(1467)](ng,a,s);w[n(1631)]=L[n(812)](),s=M,d[n(932)](w)}return d}function dg(){let a=t;return{frameType:Sa,headers:[{key:e[a(1757)],value:e[a(434)]}],payload:void 0}}class lg{constructor(n,s,d){let h=t;this["_cursorN"+h(531)]=n,this._cursorFileName=s,this[h(1571)+h(1554)]=d,this[h(559)]=e.uizKF(_l,this[h(1091)+"ameSpace"],e.lexsB)}async[t(1697)](){let n=t;await this[n(559)][n(1697)]()}async[t(333)+"rs"](){let n=t;if(!this._qosDB[n(1675)])return;let s=this[n(1571)+"Strategy"],d=await this[n(559)][n(665)]();switch(console[n(1212)](e[n(1168)],d),s){case e[n(995)]:return d&&d.length?El(d,0,this["_cursorF"+n(982)]):void 0;case e[n(1802)]:return;case e[n(1231)]:return d&&d.length?El(d,0,this[n(1823)+n(982)]):e[n(1190)](dg)}}async[t(1680)](n,s,d){let h=t,w={eUPTk:function(b,p,P,L){return e[q(1512)](b,p,P,L)}};if(e[h(1669)]!==e[h(1531)])return console[h(1212)](e[h(1874)],n,s,d),this[h(559)][h(1680)]({cursor_name:n,cursor:s,service:d});for(var m in _0x2c67b3)pbqPAA[h(556)](_0x421174,_0x109edc,m,{get:_0x2de917[m],enumerable:!0})}async[t(381)+"rs"](n){let s=t,d=e[s(607)](cg,n);for(let h of d)console[s(1212)](e.gKvuA,d),await this[s(559)][s(1680)](h)}async[t(1546)](n){let s=t;return(await this[s(559)][s(1546)](n))?.[s(1631)]}async[t(1363)](){let n=t;await this[n(559)][n(1363)]()}[t(1848)+t(1194)+t(1192)](n){let s=t;this[s(1823)+s(982)]=n}get[t(1675)](){return this[t(559)].isReady}}let ug=t(1230)+"qos__";async function bl(a){let n=t;if(!this[n(1224)][n(592)+"S"])return null;let{aID:s,fpID:d,messageStrategy:h}=this[n(1224)],w=e.DVTkt(a,ug);try{if(e.vHcDI===e[n(838)])return this[n(875)+n(450)]?a&&this[n(875)+n(450)]["updateCu"+n(1194)+n(1192)](a):this[n(875)+"anager"]=new lg(d+"_"+s+"_"+w,w,h),this._cursorManager[n(1675)]||await this[n(875)+n(450)].openDB(),this[n(875)+"anager"];{let m=0,b={};for(let p=0;e[n(1803)](p,_0x2cfe5a[n(1407)]);p++)b[_0x497848[p]["cursor_n"+n(1573)]]=e[n(1545)](_0x59a1d6,_0x5ca206[p][n(466)+n(1573)]),m+=14+b[_0x5ada70[p][n(466)+"ame"]];return[m,b]}}catch{return null}}async function fg(a,n){let s=t,d=e[s(1406)](sn,a[s(736)].headers,e[s(1671)],"-1"),h=e.PmNRE(sn,a.message.headers,"is_ack","1"),w=ar(a.message[s(1776)],e[s(694)]),m=e[s(1342)](Number,e.nwECz(ar,a.message[s(1776)],e[s(1179)]))||0,b=Ea.call(this,a),p=e[s(1786)](sn,a[s(736)].headers,s(525)+"s","2"),P=ar(a[s(736)][s(1776)],e[s(1799)]),L=e.GeesE(Number,ar(a.message[s(1776)],e[s(553)]));if(b[s(757)])return n();let M=b[s(1615)+s(924)]?await yl.call(this):null;if(e[s(860)](a[s(736)].service,0)&&h&&!d||e.asrSi(a[s(736)][s(974)],0)){if(w&&b[s(1615)+s(924)]&&M)return!!!await M[s(1546)](w)&&(this[s(1604)+s(456)+s(879)](a),await M[s(1680)](w,e[s(1282)](Date[s(1552)](),m))),e[s(1312)](n);if(p){let G=await bl[s(903)](this);if(!G)return this["_dispatchMessage"+s(879)](a),e[s(1312)](n);let J=await G[s(1546)](P)??-1;if(e[s(977)](J,L))this[s(1604)+s(456)+s(879)](a),G[s(1680)](P,L,a[s(736)][s(974)]);else throw new Error("recevied"+s(1354)+s(1887)+L+(" larger "+s(1532)+"al cursor ")+J);return n()}return this[s(1604)+"hMessage"+s(879)](a),n()}}async function hg(a,n){let s=t,d=Ea.call(this,a);if(!d[s(1615)+s(924)])return n();let h=await yl.call(this);if(d["isAckCle"+s(880)+s(1815)]&&d.ackMsgIds[s(1407)])for(let w of d[s(605)+"s"])await h[s(522)](w);e[s(1242)](n)}async function xg(a,n){let s=t,d=a[s(736)][s(1665)+"e"]===og,h=e[s(1203)](a[s(736)][s(1665)+"e"],Sa);if(!d&&!h)return e[s(1242)](n);let w=e[s(1226)](ar,a[s(736)].headers,e.lBolV);if(!w)return e[s(1178)](n);let m=await bl.call(this,w);if(!m)return e.pOfnA(n);if(d){let b=await m[s(333)+"rs"](),p={frameType:b?.["frameType"],SeqID:he[s(1204)+"er"](this[s(670)]++),LogID:he[s(1204)+"er"](this[s(1224)].logIDGenerator()),service:9e3,method:5,headers:b?.headers,payload:b?.[s(326)]},P=e[s(1523)](S,p);this._ws&&this[s(1551)].readyState&&this._ws[s(596)](P)}if(h){let b=a[s(736)][s(326)];b&&m[s(381)+"rs"](b)}}let pg=async function(a,n){let s=t;this._isInit=!1,e[s(1250)](clearTimeout,this[s(744)+s(438)+"utId"]),n()},gg=async function(a,n){let s=t;if(!this[s(1551)]||e[s(1051)](this._ws.readyState,this[s(1344)]))return e[s(1190)](n);let{pingInterval:d}=this[s(1224)];this[s(841)+s(1653)]?.[s(1670)+s(747)+s(1459)]();for(let w=0;e[s(930)](w,this["_message"+s(498)][s(1407)]);w++){let m=this[s(1571)+s(498)][w];if(e[s(476)](this[s(1551)][s(713)+"te"],this[s(1344)])&&m!==null)this[s(1551)]&&this[s(1551)][s(596)](m),this[s(1571)+s(498)][w]=null;else break}this["_message"+s(498)]=this["_message"+s(498)][s(1783)](w=>!!w),this[s(496)+s(1276)+"Id"]=e[s(1096)](setTimeout,()=>this._ping(),d),this["_dispatc"+s(1149)+"nt"](a),this._isBrowser&&this[s(1551)]&&(this[s(1551)].binaryType=this[s(583)+"ype"]);let h=this[s(841)+s(1653)]?.[s(346)+s(1548)+"nt"]();this[s(1198)](s(1754)+h+s(1513)),n()},mg=async function(a,n){let s=t,d=this[s(841)+s(1653)]?.[s(346)+"ntEndpoint"]();this[s(1198)](s(1754)+d),n()};class wg extends wa{constructor(n){let s=t,d={EMXLn:function(b,p){return e.UTijI(b,p)},FWpJl:function(b,p){return b(p)},onqMk:function(b,p){return b<<p},dTqbo:function(b,p){return b&p},uuKco:function(b,p){return e[q(569)](b,p)},aPxsy:function(b,p){return b(p)},keZPw:function(b,p){return e[q(449)](b,p)},qTzkU:e.IpWTz,omNWy:e[s(1491)],tUNQw:function(b,p){return e.wHMwJ(b,p)},HDaEK:e[s(352)],KZaGU:function(b,p,P){return e[s(435)](b,p,P)},PGYwK:e[s(465)],GRnlH:function(b,p){return b(p)},pulBj:function(b,p){return e[s(643)](b,p)},iUwEP:function(b,p){return e[s(1347)](b,p)},dIuyq:function(b,p){return e[s(1313)](b,p)},QSAAR:e[s(1619)],tYgCk:function(b,p){return e[s(906)](b,p)},YTjBu:e[s(1386)],wtyTZ:e.TXyLA,SGoBp:e[s(1694)],ChUyF:e[s(1839)],zFkRT:function(b,p,P){return e.HEIRM(b,p,P)},TGxwa:function(b,p,P,L){return b(p,P,L)},gozvP:function(b,p,P){return b(p,P)},JxuZE:function(b,p){return e.Wybsi(b,p)},RDfqc:function(b,p){return e.ZHCgD(b,p)}};super(),this[s(1577)+s(623)+"line"]=!0,this[s(1134)+"er"]=or,this[s(1618)]=Lp,this[s(1254)+"T"]=On,this._isMiniWX=ei,this[s(842)+"r"]=ti,this[s(1571)+s(498)]=[],this["_endpoin"+s(1653)]=null,this["_readyCl"+s(587)]=!1,this[s(583)+s(888)]=e[s(851)],this[s(744)+s(1188)]=!1,this._connectionTimeoutId=null,this["_reconne"+s(1085)+s(837)]=null,this[s(496)+s(1276)+"Id"]=null,this[s(670)]=0,this[s(1365)]=!1,this[s(473)]="",this[s(629)+"ger"]=null,this[s(875)+s(450)]=null,this[s(1804)+"sCounter"]=null,this._protocols=s(1492),this[s(1685)]=3,this[s(1323)+"NG"]=0,this[s(1344)]=1,this[s(1117)]=2,this[s(1434)]=b=>{let p=s,P={FqMIx:function(L,M){return d[q(1842)](L,M)},TNYBz:function(L,M){return d[q(483)](L,M)},LXpvI:function(L,M){return d[q(1850)](L,M)},xdGVH:function(L,M){return L&M},ESMWh:function(L,M){return L(M)},ICDYH:function(L,M){return d.onqMk(L,M)},ZzyrG:function(L,M){return L&M},rJLmX:function(L,M){return d[q(1842)](L,M)},wOjZm:function(L,M){return d.dTqbo(L,M)},AOUfG:function(L,M){return d[q(452)](L,M)},HJDlk:function(L,M){return d[q(1228)](L,M)}};try{if(d[p(981)](d[p(828)],d.omNWy))pl(this,b,[pg,gg,mg]);else{let L=_0x33b03a[p(1517)+"g"](0,IoEQLk[p(1174)](4,_0x589b03[p(1407)])),M=L[p(1528)](_0x492d7d);_0xba4954[p(932)](M)}}catch(L){if(d.tUNQw(p(706),d.HDaEK)){let M=d.KZaGU(dt,d[p(392)],{message:L[p(736)],code:rn.OPEN_ERROR,error:L});this[p(1604)+p(1055)+"ent"](M)}else _0x15a593=yHKeoF[p(609)](_0x4f98bc,_0xadfbf1),_0x147f51|=yHKeoF[p(1826)](yHKeoF.LXpvI(127,_0x1a1a90),14),yHKeoF[p(1393)](128,_0x39ab9a)&&(_0x132ccb=yHKeoF.ESMWh(_0x52a9af,_0x6ca413),_0x490699|=yHKeoF[p(334)](127&_0xa0571b,21),yHKeoF[p(1728)](128,_0x19cc9d)&&(_0x530c15=yHKeoF[p(385)](_0x2afb8e,_0x2a6961),_0x4d7104=yHKeoF[p(1730)](127,_0x5a2768),yHKeoF[p(1801)](128,_0x5a39a3)&&(_0x551d4a=yHKeoF[p(1871)](_0x4a99c4,_0x844c7f),_0x2b7dca|=yHKeoF[p(1801)](127,_0x5b8afe)<<7)))}},this[s(1284)+"ge"]=async b=>{let p=s;if(d[p(1654)](d.QSAAR,d[p(971)]))_0x2ac862=IoEQLk[p(639)](_0x39221f,_0x10331a),_0xe24997|=IoEQLk[p(1635)](IoEQLk[p(1338)](127,_0x3c4dfd),7);else{let{pingInterval:P,pingFrequency:L}=this[p(1224)];if((d[p(1706)]("hi",b.data)&&d[p(1706)](d[p(1006)],L)||d[p(1010)]===L)&&(this[p(1390)+p(1829)](),this[p(985)](d[p(656)],d.ChUyF),this[p(496)+p(1276)+"Id"]=d[p(1447)](setTimeout,this[p(780)][p(547)](this),P)),b[p(815)]==="hi")return;try{d[p(1553)](pl,this,b,[Jp,$p,hg,xg,fg,Vp])}catch(M){let G=d[p(1447)](dt,d[p(392)],{message:M[p(736)],code:rn[p(1348)+p(1288)],error:M});this[p(1604)+p(1055)+p(963)](G)}}},this[s(1159)]=b=>{let p=s,P=this[p(841)+"tManager"]?.[p(1024)+p(992)+"es"](),L=this[p(841)+"tManager"]?.[p(346)+p(1548)+"nt"]();if(P&&!b[p(736)]){let M=p(1089)+L+(p(1030)+"ax retri"+p(1294)+"ed");this[p(1604)+p(1055)+p(963)](d.gozvP(dt,d.PGYwK,{message:M,code:rn[p(1809)+p(1432)+"R"],error:b}));return}this._ws&&d[p(1794)](this[p(1551)][p(713)+"te"],this[p(1344)])&&this["_disconn"+p(821)](),this[p(1604)+"hErrorEv"+p(963)](d[p(1041)](dt,d[p(392)],{message:b[p(736)],code:rn[p(1832)+p(1026)],error:b}))},this[s(455)]=async b=>{let p=s;this[p(1613)+p(1270)](),this[p(1390)+p(1829)](),this[p(1335)+"sListeners"](),this[p(1551)]=null,this[p(744)+p(1188)]=!1;let P=this[p(841)+p(1653)]?.["checkRea"+p(992)+"es"]();if(!P&&this[p(1350)+"orOnline"]()&&!this[p(804)+p(587)]){let L=this[p(841)+p(1653)]?.["getCurre"+p(1548)+"nt"](),M=this[p(1224)][p(399)+"tInterce"+p(1696)](b[p(1105)],b[p(1606)]);this[p(1604)+"hCloseEvent"](gt(e[p(460)],{code:1006,reason:b[p(1606)]||p(1785)+"ng failed, unkno"+p(1431)+p(882)+p(1746)+L,willReconnect:M})),M&&this[p(744)]();return}if(e[p(934)](1e3,b[p(1105)])&&this[p(804)+p(587)]){this["_dispatc"+p(1500)+p(963)](e[p(435)](gt,e[p(460)],{code:1e3,reason:p(1325)})),this._endpointManager?.[p(1670)+p(747)+p(1459)](),this[p(1804)+"sCounter"]?.[p(1314)+p(1489)]();return}if(e[p(1727)](1e3,b[p(1105)])&&P){if(e[p(1093)](p(537),e[p(1594)]))return _0x1633a6&&IoEQLk[p(948)](!0,_0x476dc2[p(1115)]);{let L=this[p(841)+"tManager"]?.[p(346)+"ntEndpoint"](),M=b[p(1606)];M||(M=await e[p(1101)](Hp,this[p(473)])),M=p(1785)+"ng faile"+p(1642)+M+(p(790)+p(897))+L+(p(861)+p(1273)+p(650)),this[p(1604)+p(1500)+p(963)](gt(e[p(460)],{code:b[p(1105)],reason:M}));let G="connect "+L+(p(1030)+"ax retri"+p(1294)+"ed");this[p(1604)+"hErrorEv"+p(963)](e[p(563)](dt,e[p(465)],{message:G,code:rn[p(1809)+p(1432)+"R"]})),this[p(841)+p(1653)]?.[p(1670)+p(747)+p(1459)](),this[p(1804)+p(620)]?.[p(1314)+p(1489)]();return}}if(b[p(1105)]!==1e3&&!b.reason){let L=this["_endpoin"+p(1653)]?.[p(346)+p(1548)+"nt"]();this[p(1604)+p(1500)+"ent"](e[p(563)](gt,e[p(460)],{code:b.code,reason:p(1785)+p(1884)+"d, unknown reason, hostname: "+L})),this[p(841)+"tManager"]?.[p(1670)+"pointCon"+p(1459)](),this[p(1804)+p(620)]?.[p(1314)+p(1489)]();return}this._dispatchCloseEvent(b),this["_endpoin"+p(1653)]?.[p(1670)+"pointConfig"](),this[p(1804)+p(620)]?.["resetCou"+p(1489)]()},this[s(1560)]=null,this[s(430)]=null,this.onmessage=null,this[s(1701)]=null,this[s(439)+s(370)]=null,this["onReceiv"+s(752)]=null,this[s(1337)+s(763)+"yReconnect"]=null,this[s(482)+s(395)]=this[s(482)+s(395)][s(547)](this),this[s(482)+s(1208)]=this[s(482)+"ffLine"][s(547)](this),this["_handleP"+s(1057)]=this[s(511)+s(1057)][s(547)](this),this[s(511)+s(1861)]=this["_handleP"+s(1861)][s(547)](this),this[s(1224)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1681)](1,0),service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[s(1693)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1231)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:w}=n,m=Array[s(912)](h)?h:e[s(1741)](e[s(1710)],typeof h)?[h]:[];if(!m||e[s(1373)](0,m[s(1407)]))throw new Error(e[s(760)]);if(!e[s(1758)](Bp,w))throw new Error("please p"+s(1361)+s(1732)+s(717)+s(1810)+s(506)+s(382)+s(443));Object[s(904)](this[s(1224)],n),this[s(841)+s(1653)]=new xl(m,this[s(1224)][s(1533)+"es"]),this[s(1804)+"sCounter"]=new Up(this[s(1224)]["pingLoss"+s(315)]),this[s(1224)][s(1072)+s(631)]&&(this[s(1365)]=!0,this[s(744)]()),this._options[s(463)+s(727)+s(568)]&&(this[s(1254)+"T"]||this[s(1490)+"X"]?this[s(1646)+"etWorkCh"+s(432)]():this[s(1134)+"er"]&&this[s(1185)+s(1770)+s(1559)]())}[t(482)+t(395)](){let n=t;this[n(1224)][n(1485)+n(898)+n(1157)]||this[n(804)+n(587)]||this[n(1720)+"econnect"]()}[t(482)+t(1208)](){let n=t;this["_destroy"+n(917)+"t"]();let s=ma(n(399)+"t",{message:e.hMcHq});this["onStopImmediatel"+n(669)+"ct"]&&this[n(1337)+n(763)+n(669)+"ct"](s)}[t(1185)+t(1770)+t(1559)](){let n=t;this._isBrowser&&window[n(1509)+n(1559)]("online",this[n(482)+n(395)]),this[n(1134)+"er"]&&window[n(1509)+n(1559)](e.xNGap,this[n(482)+n(1208)]),this[n(1134)+"er"]&&window[n(1509)+"Listener"](n(1395),this[n(511)+n(1057)]),this._isBrowser&&window[n(1509)+n(1559)](e[n(957)],this[n(511)+"ageShow"])}[t(1111)+t(1770)+"Listener"](){let n=t,s={SofZf:e[n(460)]};e[n(1219)](e[n(685)],e[n(685)])?(this[n(1134)+"er"]&&window["removeEv"+n(864)+n(1499)](n(354),this[n(482)+n(395)]),this[n(1134)+"er"]&&window[n(1193)+n(864)+n(1499)](e[n(1360)],this[n(482)+"ffLine"]),this[n(1134)+"er"]&&window[n(1193)+n(864)+n(1499)](e[n(1807)],this[n(511)+"ageHide"]),this[n(1134)+"er"]&&window[n(1193)+"entListe"+n(1499)](e[n(957)],this[n(511)+"ageShow"])):(_0x4f47db&&_0x49eb18[n(1509)+n(1559)](LyjaNv[n(1038)],()=>_0x6de5bd()),_0x50af87&&_0x18ebff[n(1509)+n(1559)]("versionc"+n(406),()=>_0x366382()))}[t(511)+t(1057)](n){let s=t;!n[s(1399)+"d"]&&(this._isBrowser&&window[s(1193)+s(864)+s(1499)](s(1395),this["_handleP"+s(1057)]),this[s(1134)+"er"]&&window[s(1193)+s(864)+"ner"](s(359),this["_handleP"+s(1861)]),this[s(1769)]()),this[s(1134)+"er"]&&window[s(1193)+"entListener"](e[s(768)],this[s(482)+"nLine"]),this._isBrowser&&window[s(1193)+s(864)+s(1499)](e[s(1360)],this[s(482)+s(1208)])}[t(511)+t(1861)](n){let s=t;n[s(1399)+"d"]&&(this[s(1350)+s(1418)]()&&(!this[s(1551)]||this[s(1551)].readyState!==this.OPEN||e.sYMBO(this[s(1551)][s(713)+"te"],this[s(1323)+"NG"]))&&this[s(482)+s(395)](),this[s(1134)+"er"]&&window[s(1509)+s(1559)](e.ujprw,this[s(482)+s(395)]),this[s(1134)+"er"]&&window[s(1509)+"Listener"](e[s(1360)],this["_handleO"+s(1208)]))}async[t(743)+"eUrl"](n){let s=t,{fpID:d,deviceID:h,bddID:w,ttwID:m,accessKey:b,aID:p,customParams:P={},enableAutoAck:L,enableQoS:M,QoSLevel:G,env:J}=this._options,Z,we,fe;this._isBrowser||this._isMiniWX||this[s(1254)+"T"]?(Z=location&&location[s(1438)]=="https:"?e[s(675)]:e.QXobR,we=n[s(827)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),fe=/^wss(.*:\/\/)/[s(1676)](n)?n:""+Z+we):(Z=e.kcPmj,we=n[s(827)](/(^http)((?:[s]*:\/\/))/,""),fe=/(^ws)((?:[s]*:\/\/))/[s(1676)](we)?we:""+Z+we);let ae=w?s(1279):m?e[s(918)]:e[s(355)],At=w||m||h;if(e[s(1180)](!At,!ae))throw new Error(s(477)+s(1020)+s(1718)+s(709)+"r ttwID");let _g=e[s(908)](s(697),typeof P)?await e[s(820)](P):P,yg=J?zp(J[s(1806)],J.xTTEnv):{},Ia=Object[s(904)]({device_platform:e[s(541)],version_code:e[s(503)],access_key:b,fpid:d,aid:p,[ae]:At,xsack:L?1:0,xaack:L?1:0,xsqos:M?1:0,qos_level:M?G:void 0,qos_sdk_version:2,...yg},_g),Eg=Object[s(1709)](Ia)[s(1687)]((Aa,ka)=>Ia[ka]!==void 0?""+Aa+(Aa?"&":"?")+ka+"="+Ia[ka]:Aa,"");return fe+s(589)+Eg}async[t(744)](){let n=t,s={XLcma:function(d,h){return e.jSnzU(d,h)},iNRzE:function(d,h){return e[q(860)](d,h)},SfeZB:function(d,h){return d+h},OVHhn:function(d,h){return d(h)},ulcTe:function(d,h){return e[q(608)](d,h)},qUSHe:function(d,h){return e[q(1568)](d,h)},vNXRG:function(d,h){return e.IiqBZ(d,h)}};if(!(this[n(744)+"Lock"]||this[n(804)+n(587)])){this[n(744)+n(1188)]=!0;try{let d=this[n(841)+"tManager"]?.[n(962)+n(988)+n(1841)+n(1498)+n(657)](),{timeoutInterval:h}=this._options;if(d){let m=this[n(841)+"tManager"]?.["getCurre"+n(1548)+"nt"](),b=this["_endpoin"+n(1653)]?.["replaceB"+n(1862)+n(836)+n(839)+"unt"](),p=this[n(841)+"tManager"]?.[n(346)+n(1548)+n(1009)+"ount"]();if(b){let P=n(1089)+m+(n(983)+n(861)+n(1273)+"ached, will use "+n(1415)+n(654))+b+(n(1099)+"y"),L=e[n(1368)](dt,n(1069),{message:P,code:rn["MAX_RETR"+n(1432)+"R"]});this[n(1198)](P),this[n(1604)+n(1055)+n(963)](L),this[n(473)]=await this[n(743)+n(848)](b),this[n(1198)](n(1089)+b+" "+p+n(1141)),this._removeWsListeners()}else{let P=n(1089)+m+(n(983)+n(861)+n(1273)+n(650));this[n(1198)](P),this["_dispatc"+n(1055)+n(963)](e[n(1441)](dt,e[n(465)],{message:P,code:rn[n(1809)+"IES_ERROR"]}));return}}else if(e[n(1061)](e[n(1060)],e[n(1060)])){if(goWGgD.XLcma(_0x29d223,1)||goWGgD.iNRzE(_0x1dc40d,_0x3f3ec5))return _0x13cfca(_0x20f422);goWGgD[n(1076)](goWGgD[n(1286)](_0x292afb,_0x4a8059),_0x1e426c)&&(_0x7aa8cc=goWGgD.OVHhn(_0x1f261d,_0x50ce74),_0x3ad941=0);let m=_0x2c0e15.call(_0xb354be,_0x4a6636,_0x2ef684+=_0x34a56c);return goWGgD[n(1014)](7,_0x513623)&&(_0x123307=goWGgD[n(1445)](goWGgD[n(1138)](7,_0x25fd22),1)),m}else{let m=this[n(841)+"tManager"]?.[n(346)+n(1548)+n(1605)+n(796)](),b=this[n(841)+n(1653)]?.[n(346)+n(1548)+n(1009)+"ount"]();this[n(473)]=await this[n(743)+n(848)](e[n(941)](m,"")),this._debug(n(1089)+m+" "+b+n(1141)),this[n(1335)+n(1155)+"rs"]()}if(this[n(1365)])this[n(1365)]=!1;else{let m=ma("reconnect",{message:n(1714)});this[n(439)+n(370)]&&this["onStartR"+n(370)](m)}let w=this[n(841)+n(1653)]?.[n(346)+n(1548)+n(1009)+n(651)]()||0;w>1&&await this._wait(w-1),this[n(1198)]("connecting url: "+this._url+(" protoco"+n(1008))+this[n(742)+"ls"]),this[n(1551)]=e[n(1229)](Mp,{url:this[n(473)],protocols:[this[n(742)+"ls"]],headers:this[n(1224)][n(390)+n(739)+"s"][n(1078)+n(1122)]},this[n(1224)].ws),(this[n(1134)+"er"]||this[n(842)+"r"])&&this[n(1551)]&&(this[n(1551)][n(867)+"pe"]=this[n(583)+n(888)]),this[n(781)+"steners"](),this[n(744)+n(438)+"utId"]=e.IOERG(setTimeout,this._onTimeout[n(547)](this),h)}catch(d){throw this[n(744)+"Lock"]=!1,d}}}["_clearTi"+t(1270)](){let n=t;e.bqyiz(clearTimeout,this[n(744)+n(438)+n(598)]),this[n(744)+n(438)+n(598)]=null}[t(1390)+t(1829)](){let n=t;e[n(788)](clearTimeout,this[n(496)+n(1276)+"Id"]),e[n(1752)](clearTimeout,this[n(928)+"ctTimeoutId"]),this[n(496)+n(1276)+"Id"]=null,this["_reconne"+n(1085)+"tId"]=null}[t(1198)](...n){let s=t;if(e[s(339)](e[s(674)],e[s(1214)])){let d=(s(728)+"0|1")[s(557)]("|"),h=0;for(;;){switch(d[h++]){case"0":_0x1b143f=new _0xa969bf;continue;case"1":_0x260517(w=>({...w,get:(m,b,p)=>_0x5aec39(m,b)||w.get(m,b,p),has:(m,b)=>!!_0x460780(m,b)||w.has(m,b)}));continue;case"2":_0x5f4b66=[PBuhzc[s(1252)],"add",s(1562),PBuhzc.vpYQX];continue;case"3":PBuhzc.THjbH(_0x37f7fc);continue;case"4":_0x4f9a4e=[PBuhzc[s(1813)],PBuhzc[s(854)],PBuhzc[s(956)],PBuhzc[s(803)],PBuhzc[s(1430)]];continue;case"5":_0x46c256();continue}break}}else this[s(1224)][s(1136)]&&console[s(1212)][s(1493)](console,[e.cjKPr,...n])}[t(707)+t(542)+"e"](n){let s=t,{initReconnectInterval:d,maxReconnectInterval:h,reconnectIntervalGrowFactor:w}=this._options,m=e[s(844)](d,Math.pow(w,n-1));return e.XrpIY(m,h)?h:m}[t(780)](){let n=t;if(this._ws&&e[n(1206)](this[n(1551)][n(713)+"te"],this[n(1323)+"NG"])){this[n(1390)+n(1829)](),this[n(496)+n(1276)+"Id"]=setTimeout(this._ping[n(547)](this),this[n(1224)][n(952)+"rval"]);return}if(!this[n(1551)]||e[n(692)](this._ws.readyState,this[n(1344)]))return void this[n(1720)+n(370)]();this._ws&&this._ws[n(596)]("hi"),this[n(928)+n(1085)+"tId"]=e[n(1467)](setTimeout,this[n(1720)+n(370)+"Timeout"].bind(this),this[n(1224)]["pingTime"+n(1047)+n(1524)])}[t(1720)+t(370)+t(1624)](){let n=t;this["_pingLos"+n(620)]?.[n(964)](),this[n(985)](e[n(884)],e[n(749)]),this[n(1804)+"sCounter"]?.[n(1024)+n(444)+"nt"]()?this[n(1720)+n(370)]():this[n(780)]()}[t(1350)+t(1418)](){let n=t;return this._isMiniTT||this[n(1490)+"X"]?this["_miniNav"+n(623)+"line"]:(this[n(1134)+"er"]||this[n(842)+"r"])&&this[n(1224)][n(463)+n(727)+n(568)]?navigator[n(638)]:!0}[t(1720)+"econnect"](){let n=t;!this[n(1350)+n(1418)]()||this[n(804)+n(587)]||(this[n(841)+n(1653)]?.[n(1670)+n(747)+n(1459)](),this[n(1804)+"sCounter"]?.[n(1314)+"nter"](),this[n(1551)]?this[n(1572)+n(821)](1001,e.etDSq,!0):this[n(744)]())}[t(1646)+t(570)+t(432)](){let n=t;this[n(1254)+"T"]?tt[n(1704)+n(425)+n(406)](({isConnected:s})=>{let d=n;this[d(1577)+d(623)+d(1683)]=s,s?this[d(482)+d(395)]():this[d(482)+"ffLine"]()}):this[n(1490)+"X"]&&wx[n(1704)+n(425)+n(406)](({isConnected:s})=>{let d=n;this[d(1577)+d(623)+"line"]=s,s?this["_handleO"+d(395)]():this[d(482)+d(1208)]()})}[t(497)](n){return new Promise(s=>{let d=q;e[d(978)](setTimeout,s,this[d(707)+d(542)+"e"](n))})}[t(1572)+"ect"](n=1e3,s="",d=!1){let h=t;this._ws&&this["_destroy"+h(917)+"t"](n,s,d)}_onTimeout(){let n=t;if(e.xgclC(e.UAjEB,e[n(1716)])){let s=_0x4561fe[n(1589)+"At"](_0x3fc80d);e[n(1176)](s,55296)&&e[n(1249)](s,56319)&&e[n(1860)](e[n(716)](_0xbb808f,1),_0x123d9b)&&(s=e[n(996)](e[n(652)](e[n(1791)](s,10),_0x32e212[n(1589)+"At"](++_0x396b84)),56613888)),_0x4c7d4f+=e[n(1275)](s,128)?1:e.SnKJf(s,2048)?2:e[n(579)](s,65536)?3:4}else{let s=this["_endpoin"+n(1653)]?.[n(346)+n(1548)+"nt"]();this[n(1198)]("connect "+s+n(983)),this[n(1572)+n(821)](1001,n(1362)+n(1684)+n(1402)+"g",!0)}}[t(1307)](n){let s=t,d=Ut(n);this[s(1551)]&&e[s(1501)](this[s(1551)].readyState,this.OPEN)&&(this._ws&&this[s(1551)].send(d),this[s(1198)](e.qSduL,n))}[t(1335)+t(1155)+"rs"](){let n=t,s=e[n(817)][n(557)]("|"),d=0;for(;;){switch(s[d++]){case"0":this[n(1551)][n(1193)+"entListener"](e[n(1063)],this[n(1434)]);continue;case"1":this[n(1551)][n(1193)+n(864)+n(1499)](e[n(465)],this[n(1159)]);continue;case"2":if(!this._ws)return;continue;case"3":this._ws.removeEventListener(n(736),this[n(1284)+"ge"]);continue;case"4":this[n(1551)].removeEventListener(e.fIsLz,this[n(455)]);continue}break}}[t(781)+"steners"](){let n=t,s=e[n(954)][n(557)]("|"),d=0;for(;;){switch(s[d++]){case"0":if(!this[n(1551)])return;continue;case"1":this[n(1551)][n(1509)+"Listener"](e[n(460)],this[n(455)]);continue;case"2":this[n(1551)][n(1509)+"Listener"](e[n(465)],this[n(1159)]);continue;case"3":this[n(1551)][n(1509)+n(1559)](n(832),this[n(1434)]);continue;case"4":this._ws[n(1509)+n(1559)](e[n(1526)],this[n(1284)+"ge"]);continue}break}}[t(846)+t(1383)](n=1e3,s=""){let d=t;try{this[d(1551)]&&this[d(1551)][d(1769)](n,s)}catch{}}["_destroy"+t(917)+"t"](n=1e3,s="",d=!1){let h=t,w={ZKCAg:function(m,b){return e[q(1261)](m,b)},QtnZb:function(m,b){return m(b)}};if(this["_clearPi"+h(1829)](),this[h(1613)+"mer"](),this["_removeW"+h(1155)+"rs"](),this[h(846)+h(1383)](1e3,s),this[h(744)+"Lock"]=!1,d&&this[h(1350)+h(1418)]()&&!this[h(804)+h(587)]){if(this["_endpoin"+h(1653)]?.[h(1024)+"chMaxTries"]())if(e[h(1797)](h(1536),e[h(1251)])){let b=this[h(841)+h(1653)]?.getCurrentEndpoint();this["_dispatchCloseEv"+h(963)](gt(e[h(460)],{code:1006,reason:"connect "+b+(h(983)+h(861)+h(1273)+h(650)),wasClean:!0}))}else return TwnNwd[h(1379)](_0x326c1a,_0x36f9de[h(1493)](TwnNwd[h(1116)](_0x54fb0a,this),_0xa3b7a6));else{let b=this[h(1224)][h(399)+h(916)+"ptor"](n,s);this._dispatchCloseEvent(gt(e[h(460)],{code:n,reason:s,wasClean:!0,willReconnect:b})),b&&this[h(744)]()}return}this._navigatorOnline()||this[h(804)+"osed"]?this[h(1604)+h(1500)+h(963)](e[h(1368)](gt,"close",{code:n,reason:h(1325)})):this[h(1604)+h(1500)+"ent"](e[h(1094)](gt,h(1769),{code:1006,reason:e.QrfAi})),this._ws=null,this[h(841)+"tManager"]?.[h(1670)+h(747)+"fig"](),this[h(1804)+"sCounter"]?.[h(1314)+h(1489)]()}[t(1604)+t(1149)+"nt"](n){let s=t;this[s(985)](e[s(1063)],n),this[s(1701)]&&this.onopen(n)}[t(1604)+t(456)+t(879)](n){let s=t;this[s(985)](e[s(1526)],n),this[s(1870)+"e"]&&this[s(1870)+"e"](n)}["_dispatchAckMess"+t(809)](n){let s=t;this.emit(e[s(1003)],n),this[s(1169)+s(752)]&&this[s(1169)+s(752)](n)}[t(1604)+"hErrorEv"+t(963)](n){let s=t;this[s(985)](e[s(465)],n),this.onerror&&this.onerror(n)}["_dispatc"+t(1500)+"ent"](n){let s=t,d={oxkff:function(h,w){return h(w)},OhhFw:function(h,w){return e.ONkfM(h,w)},pRDla:e[s(426)],xkirs:e[s(958)]};if(e.njuur(e[s(748)],e.LsZkQ)){let h=_0xf968da[s(557)](/\./).map(b=>_0x19141b(b)),w=[];return w[0]=myNlyT[s(801)](_0x5f15c1,h[0]+h[1]),w[1]=myNlyT[s(801)](_0x355834,myNlyT[s(693)](h[2],h[3])),[myNlyT.pRDla,myNlyT.pRDla,myNlyT.pRDla,s(1310),myNlyT[s(859)],myNlyT[s(1123)],w[0],w[1]][s(1086)]("")}else this[s(985)](e.fIsLz,n),this[s(1560)]&&this.onclose(n)}get[t(867)+"pe"](){let n=t;return this[n(1551)]?this[n(1551)][n(867)+"pe"]:this[n(583)+n(888)]}set[t(867)+"pe"](n){let s=t;this[s(583)+s(888)]=n,this[s(1551)]&&(this[s(1551)][s(867)+"pe"]=n)}get[t(1012)+"nt"](){let n=t;return this[n(841)+n(1653)]?.["getCurre"+n(1548)+n(1009)+n(651)]()||0}get[t(411)+"Amount"](){let n=t,s=this[n(1571)+n(498)][n(1687)]((d,h)=>(d+=h&&h[n(1232)+"th"]||0,d),0);return e[n(1e3)](s,this[n(1551)]?this[n(1551)][n(411)+n(1113)]:0)}get[t(530)+"ns"](){let n=t;return this._ws?this[n(1551)][n(530)+"ns"]:""}get[t(1438)](){let n=t;return this[n(1551)]?this[n(1551)][n(1438)]:""}get[t(713)+"te"](){let n=t;return this[n(1551)]?this[n(1551)].readyState:this[n(1224)][n(1072)+n(631)]?this.CONNECTING:this[n(1685)]}get[t(1311)](){let n=t;return this[n(1551)]?this[n(1551)].url:this[n(473)]}[t(1769)](n=1e3,s){let d=t;if(this[d(804)+d(587)]=!0,this["_clearTi"+d(1270)](),this[d(1390)+d(1829)](),this["_dropGlo"+d(1770)+d(1559)](),this[d(629)+d(1329)]?.[d(1363)](),!this._ws)return void this[d(1198)](e[d(729)]);if(e[d(1245)](this[d(1551)].readyState,this.CLOSED)||e[d(753)](this[d(1551)][d(713)+"te"],this[d(1117)]))return void this._debug(d(733)+"s alread"+d(695));this[d(423)+d(917)+"t"](n,s)}async[t(596)](n,s){let d=t,h={TXxer:function(fe,ae,At){return e.Fmhyo(fe,ae,At)}};if(e[d(521)](null,n))throw new Error(e[d(1042)]);e.EBQMx(e.lwWfJ,typeof n)&&(n=JSON.stringify(n)),e[d(1710)]!=typeof n&&!e[d(615)](n,ArrayBuffer)&&!(n[d(566)]&&e[d(1374)](n[d(566)],ArrayBuffer))&&(n=JSON[d(1202)+"y"](n));let w=await wl(n),m=e[d(1317)](Fp,n),{method:b=0,service:p=this._options[d(974)],logID:P=this._options["logIDGen"+d(668)](),headers:L=this._options.headers,payloadEncoding:M=this[d(1224)][d(532)+d(1293)],payloadType:G=this[d(1224)][d(1700)+d(888)],logIDNew:J=this[d(1224)][d(427)+d(1511)][d(1520)+d(887)+"teLogIDNew"]?e.yevXL(i,this[d(1224)][d(427)+d(1511)][d(1838)]):""}=e.NNYzI(s,{});if(!p)throw new Error(e[d(612)]);let Z={SeqID:he[d(1204)+"er"](this[d(670)]++),LogID:he[d(1204)+"er"](P),service:p,method:b,headers:L,payloadEncoding:e[d(441)](M,Object)?M.encoding?M[d(1867)]:"":M,payloadType:e.bbwkK(G,Object)?G[d(327)]?G[d(327)]:m:G||m,payload:w,LogIDNew:J},we=Ut(Z);return this._ws&&e[d(1876)](this[d(1551)][d(713)+"te"],this.OPEN)?(this[d(1551)]&&this[d(1551)][d(596)](we),this._debug(e[d(1032)],Z)):e[d(1740)](this["_message"+d(498)][d(1407)],this[d(1224)]["maxMessageQueueL"+d(1153)])?e[d(1843)]===e[d(1847)]?(QCfZrR[d(1863)](_0x21f3fd,_0x288c8c,82),QCfZrR.TXxer(_0x2eb7f2,_0x1aeed4,_0x4f61be)):(this[d(1571)+d(498)].push(we),this[d(1198)](e[d(1525)],Z)):(this[d(1571)+d(498)][d(1209)](),this[d(1571)+d(498)][d(932)](we)),{seqID:this[d(670)],logID:P,logIDNew:J}}async[t(399)+"t"](n){let s=t,{url:d}=e.GHKTo(n,{}),h=Array[s(912)](d)?d:e.yRXdG(s(1034),typeof d)?[d]:[];n&&Object[s(904)](this[s(1224)],n),h&&h[s(1407)]?this[s(841)+"tManager"]=new xl(h,this[s(1224)][s(1533)+"es"]):this[s(841)+s(1653)]?.[s(1670)+s(747)+s(1459)](),this[s(1804)+s(620)]?.[s(1314)+s(1489)](this[s(1224)][s(1067)+"Count"]),this["_readyCl"+s(587)]=!1,this[s(1551)]&&e.qYfxJ(this[s(1551)][s(713)+"te"],this[s(1685)])?this[s(1572)+"ect"](1e3,e.WiMYy,!0):(this[s(1365)]=!0,this[s(744)]())}async[t(655)](){let n=t;!this[n(744)+n(1188)]&&(e[n(420)](e.lgUUN,e[n(1738)])?this._qosDB?.[n(522)](_0x3054eb.message_id):(this[n(841)+n(1653)]?.[n(1670)+n(747)+n(1459)](),this["_pingLos"+n(620)]?.resetCounter(),this["_readyCl"+n(587)]=!1,this[n(1365)]=!0,this[n(744)]()))}["addEvent"+t(1559)](n,s){this.on(n,s)}[t(1210)+t(879)](n){let s=t,{type:d}=n;this[s(985)](d,n)}["removeEv"+t(864)+t(1499)](n,s){this.off(n,s)}[t(1763)](){let n=t,s={FzrDN:function(d,h){return e[q(475)](d,h)},clzQV:e[n(1839)],Kmwbc:e[n(1694)],ciQbq:n(1246)+n(1570)+"t"};return new Promise((d,h)=>{let w=n,m={CZKoT:function(P,L){return e.zsnsH(P,L)},sBGfX:e.KWqDC};this[w(1390)+w(1829)](),this._pingPongTimeoutId=setTimeout(this[w(780)][w(547)](this),this[w(1224)][w(952)+w(989)]);let b=()=>{let P=w;s[P(1632)](d,s.clzQV),this[P(724)](s[P(1486)],b),this[P(724)](s[P(526)],p)},p=()=>{let P=w;m[P(1339)](h,m.sBGfX),this[P(724)](P(1246)+P(967)+"s",b),this[P(724)]("ping_once_timeout",p)};this.on(e[w(1694)],b),this.on(e.fQset,p),this._ping()})}}})(),Fe[N(593)+N(1817)]=Oe[N(593)+N(1817)],Fe[N(869)+N(514)]=Oe["CustomEr"+N(514)],Fe[N(1017)+"e"]=Oe[N(1017)+"e"],Fe.Event=Oe[N(879)],Fe[N(829)]=Oe.FWS,Fe[N(878)+N(1002)+N(372)]=Oe[N(878)+N(1002)+"vent"],Fe[N(1002)+"vent"]=Oe[N(1002)+N(372)],Fe.OpenEvent=Oe[N(1495)+"t"],Fe[N(1154)+N(1213)]=Oe[N(1154)+N(1213)],Fe[N(1291)+N(1817)]=Oe.createCloseEvent,Fe["createEr"+N(514)]=Oe["createEr"+N(514)],Fe[N(1302)+"ssageEvent"]=Oe[N(1302)+N(421)+"nt"],Fe[N(1341)+N(1319)]=Oe[N(1341)+N(1319)],Fe[N(890)+"connectE"+N(372)]=Oe[N(890)+N(1049)+N(372)],Fe[N(1427)+N(1537)]=Oe[N(1427)+N(1537)],Fe[N(1627)+N(1573)]=Oe[N(1627)+N(1573)];for($o in Oe)[N(593)+N(1817),N(869)+N(514),N(1017)+"e","Event",N(829),"FrontierMessageE"+N(372),N(1002)+N(372),N(1495)+"t","Reconnec"+N(1213),"createCl"+N(1817),N(731)+"rorEvent",N(1302)+N(421)+"nt",N(1341)+N(1319),N(890)+N(1049)+N(372),"decodedF"+N(1537),N(1627)+N(1573)][N(662)]($o)===-1&&(Fe[$o]=Oe[$o]);var $o;Object["definePr"+N(877)](Fe,N(1277)+"le",{value:!0})});import{existsSync as zS,openSync as US}from"node:fs";import{mkdir as HS}from"node:fs/promises";import{dirname as GS}from"node:path";import{fileURLToPath as qS}from"node:url";function KS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Wd(t=Y()){return zS(t.libEntry)?t.libEntry:qS(new URL("../index.ts",import.meta.url))}async function Jx(t={}){let e=t.paths??Y(),r=t.entryOverride??Wd(e),i=KS(e,process.env.COZE_BRIDGE_LOG_MODE);await HS(GS(i),{recursive:!0});let o=US(i,"a"),l=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=it(process.execPath,l,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[as]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return jS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var jS,as,ia=nt(()=>{"use strict";Vt();ne();Re();jS=H("spawn-daemon"),as="COZE_BRIDGE_DAEMON"});import{spawn as z1}from"node:child_process";import{mkdir as U1,unlink as H1,writeFile as G1}from"node:fs/promises";import{dirname as q1,join as j1}from"node:path";function Yr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function K1(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Yr(r)}</key>
21
- <string>${Yr(i)}</string>`).join(`
20
+ `+n)}function lr(t,e,n,i,s,a){if(t.listenerCount("wsClientError")){let l=new Error(s);Error.captureStackTrace(l,lr),t.emit("wsClientError",l,n,e)}else fs(n,i,s,a)}});var Tp=z(Ue=>{"use strict";var N=V;(function(t,e){let n=V,i=t();for(;;)try{if(parseInt(n(1216))/1*(parseInt(n(1039))/2)+parseInt(n(383))/3*(-parseInt(n(771))/4)+parseInt(n(914))/5+-parseInt(n(1340))/6+parseInt(n(1262))/7+-parseInt(n(653))/8+parseInt(n(1041))/9===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(la,983518);var AI=Object[N(247)+N(219)],TI=Object["getOwnPr"+N(1055)+"mes"],bp=(t,e)=>function(){return t&&(e=(0,t[TI(t)[0]])(t=0)),e},RI=(t,e)=>{for(var n in e)AI(t,n,{get:e[n],enumerable:!0})};function kI(){return mp||(mp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function CI(){let t=N;return wp||(wp=[IDBCursor[t(1490)+"e"][t(569)],IDBCursor.prototype[t(542)],IDBCursor[t(1490)+"e"][t(542)+t(635)+"ey"]])}function PI(t){let e=N,n={mCDgM:function(s,a){return s>=a},olwIF:function(s,a){return s|a},uCoiz:function(s,a){return s/a},CJwhN:function(s,a){return s!==a},XHmos:e(619),azMvu:function(s,a,l){return s(a,l)},VISAi:function(s,a){return s&a},GPgGm:e(871),JxtAQ:function(s,a){return s(a)},JGixO:function(s){return s()},nEnTG:"success",peGbW:function(s,a){return s instanceof a}},i=new Promise((s,a)=>{let l=e,u={TrkRe:l(527),gBXMZ:function(g,v){return n[l(1401)](g,v)},YFtSh:function(g,v){return n[l(892)](g,v)},nidwP:function(g,v){return n.uCoiz(g,v)},lTaOj:function(g,v){return n[l(718)](g,v)},wZFOQ:n[l(169)],uGJgz:function(g,v){return g(v)},QwDJc:function(g){return g()},lSEVT:function(g,v,w){return n[l(1179)](g,v,w)},MNiNL:function(g,v){return n[l(1231)](g,v)},GpspQ:function(g,v){return n[l(718)](g,v)},LnstY:n[l(548)],KsdNb:function(g,v){return n[l(328)](g,v)},UwfIF:function(g){return n[l(697)](g)}},f=()=>{let g=l;t[g(472)+g(1209)+g(764)](u[g(884)],x),t["removeEventListe"+g(764)]("error",m)},x=()=>{let g=l,v={KgDyN:function(w,b){return w(b)},kkLzt:function(w,b){return u.gBXMZ(w,b)},dJFTP:function(w,b){return u.YFtSh(w,b)},qzwZm:function(w,b){return w%b},NEHEr:function(w,b){return u.nidwP(w,b)}};if(u[g(591)](u[g(188)],u.wZFOQ)){if(v[g(608)](_0x41e13a,_0x4dae41))return _0x1db247?_0x323334:_0x211817;if(_0x32ee0c){if(v[g(1215)](_0x52e447,_0x399c06))return _0x4b64bd}else{if(_0x3e98e9<=-_0x58272f)return _0x2bff6d;if(v[g(1215)](_0x6d81a9+1,_0x46b86f))return _0x389f38}return _0x39377d[g(576)](v[g(1494)](v[g(380)](_0x36e80e,_0x2f4676),0),v[g(1494)](v[g(1617)](_0x24d0b5,_0x53b17e),0),_0x4200ba)}else u[g(806)](s,u[g(806)](Vt,t[g(748)])),u[g(1389)](f)},m=()=>{let g=l;if(u.GpspQ(u[g(927)],u[g(927)])){for(_0x2c3a16>>>=0;u.gBXMZ(_0x3203ad,128);)u[g(525)](_0xe804a4,_0x4e24bf,u[g(1210)](u[g(1272)](127,_0x213712),128)),_0xbc418c>>>=7;u[g(525)](_0x20598b,_0x363bd3,_0x53f9b4)}else u[g(1675)](a,t[g(369)]),u[g(1613)](f)};t[l(853)+l(405)](n[l(1439)],x),t[l(853)+"Listener"]("error",m)});return i[e(832)](s=>{let a=e;n[a(631)](s,IDBCursor)&&dd[a(577)](s,t)}).catch(()=>{}),ua.set(i,t),i}function DI(t){let e=N,n={omgcP:function(s){return s()},IQqtA:function(s,a,l){return s(a,l)},xNzGG:function(s,a){return s>>>a},tIpKq:function(s,a){return s<<a},YjCGH:function(s,a){return s===a},Fflcd:e(1517),WZXlh:function(s,a){return s(a)},jzNmP:e(1013)+"or",lWGgD:e(369),CcMie:e(681),xwaKm:"complete"};if(da.has(t))return;let i=new Promise((s,a)=>{let l=e,u={fPHpc:l(761),WEgUN:n.lWGgD,YhtbP:n[l(390)]},f=()=>{let g=l;t[g(472)+g(1209)+g(764)](u.fPHpc,x),t[g(472)+g(1209)+g(764)](u[g(1519)],m),t[g(472)+"entListe"+g(764)](u[g(1449)],m)},x=()=>{n[l(835)](s),f()},m=()=>{let g=l,v={HGgOR:function(w,b,I){return n[V(1079)](w,b,I)},OAqMi:function(w,b){return n[V(529)](w,b)},tDvOW:function(w,b){return n[V(552)](w,b)}};if(n[g(824)](n.Fflcd,n[g(355)]))n[g(793)](a,t.error||new DOMException("AbortError",n[g(1346)])),n.omgcP(f);else{let w=0,b=_0x348632,I=_0x3f07b9+4;for(;b<I;){let{value:A,offset:R}=v.HGgOR(_0x4062c8,_0x381584,b);b=R,w=v[g(343)](v[g(738)](w,8),0),w+=A}return{value:w,offset:I}}};t[l(853)+"Listener"](n.xwaKm,x),t["addEvent"+l(405)](n[l(232)],m),t[l(853)+l(405)](n[l(390)],m)});da.set(t,i)}function LI(t){fa={uDMMs:function(n,i){return n(i)}}.uDMMs(t,fa)}function OI(t){let e=N,n={dzyDI:function(i,s){return i(s)},NwiCY:function(i,s){return i(s)},fJeGD:function(i,s){return i(s)},AoKVW:function(i,s){return i===s},adwtJ:"objectSt"+e(1068),ZpeFP:function(i){return i()}};return n[e(496)](t,IDBDatabase[e(1490)+"e"][e(375)+e(1486)])&&!(n.adwtJ in IDBTransaction[e(1490)+"e"])?function(i,...s){let a=e,l=t.call(n[a(1329)](hs,this),i,...s);return ld[a(577)](l,i.sort?i.sort():[i]),Vt(l)}:n[e(1585)](CI)[e(540)](t)?function(...i){let s=e;return t[s(1575)](n[s(713)](hs,this),i),Vt(dd[s(298)](this))}:function(...i){return Vt(t[e(1575)](n.fJeGD(hs,this),i))}}function la(){let t=["zhLWzLy","ufL1yNC","ChbL","ywnRtxnNswq","vvL4uwm","zgfVs1m","tMrev2u","Dxrjza","tg9JAW","u2TPCcbWyxm","vejzuhi","uNPqtgG","t01uuee","ywnRx2LK","yKLUDwS","ywrtvuq","B25tDgfYDfi","q09oveLovuu","whjPyvm","zw50tgLZDgu","wuz0u2G","reLQt2O","zgj6Cfq","z2vjBMzVu3K","AxnAzxjV","A2TmENq","mZCWnJKZsK1wyNjL","CgLUz09Uy2u","CgLUz0XVC3m","zgrjrcWGzgu","ChrVCG","y29UBMvJDa","z0jtA3m","r1jovfO","CgLUz19VBMm","zufJAW","yxGGCMv0CMK","EgLJDgG","zwflzLy","yMLUyxj5vhK","DgLLCKPtt04","vKLtqwK","whrPyNO","yvLMqxe","ENPltxi","y2HnyxHdB3u","r2nPvwW","ihrVihjLDhi","ufP5teG","rvfrC2m","thn6twe","uuThtuG","we1WqNC","Bg9NsurozxC","wMXHAfG","vuPoChm","Bwf4tg9ZC0m","yMLUza","wgHothm","s3PeBeO","z2v0q3vYC28","B25JBg9Zzq","t3HRCxG","B2nRzxrgywK","v0nYEhy","rwrouee","v2T5rKu","CMTLCKDSB2i","FdeXFdf8oxW","y1veuhG","ENPZzvi","suHdAxG","mZKZmtKWmezWAwD2CG","y2HnyxHuCMK","DMfS","BKX2yvO","y2vZC0HHBMq","zgL1rw0","EsbJBg9Zzwq","AerPzKC","CMvKDwnL","D1fkEfm","tu5PtKW","z1rPBwvVDxq","zgLZywjSzue","x25HDMLNyxq","EfbKqvy","Be9lvvm","DhLWzq","t1riAgW","u3rYyxrLz3K","s2jJA1O","rurZwum","svn6r0W","Ae92DMO","CNnVCL92ywW","zMX1C2HfEha","BgPTsMe","BMvJDa","BMCGB3iGyw4","y0Hvt0y","B2zMBgLUzq","Dg5Iv3m","AgLNAa","zhHjEhy","AxjLza","B0jrDg0","wLruBNK","C2v0u3rVCMe","AKTgwNy","x3nLBMrby2S","vKX6shG","y0HpqLK","rNfsEva","CMv0CNLdB3u","ruvxwKm","zw1LBNq","DMfSDwvZ","serdveu","zwjmAfC","B3bLBIa","BNrbBMrvCgq","ywnRx2nVzgu","Ew5jCLu","EK1Ly2y","tMfIChq","yM9L","C3bSAxq","rgXztKC","CMLLC0nVDw4","BxDiBwu","AwXLtMfTzq","wLnOtw8","tMLyAue","s2jNAK0","rufov24","BMrLEa","zxjHDg9Y","r2HWwvm","zhP5reK","x2nYzwf0zvm","zNPsB2K","yM9KEq","C2vYDMLJzq","ChLZt3i","Cgf5Bg9Hza","qNjPzgDL","Chviu0m","Bwu6ia","zcWGDw5RBM8","nJy5mJq5nNrPwuDdqG","tvHzvMe","CNzHBfzHBhu","uMLVB24","A3PdzNO","vM5vBKy","ANPoBva","t3zmuK4","thvfBwO","vwrNyKm","Ce1oBhu","B25tDg9Wsw0","C3bhq3q","y29UBMvJDgK","t1bftL9fuLi","tLLuBw8","BNHzDKy","AMrvCMW","CefbEem","A3bnr0K","ywrKq291BNq","BhrPCgXLihq","t2jQzwn0","BwvZC2fNzq","EKvbvLe","x2rLC3rYB3K","x3jLywr5q2W","BMDuAw1LCG","tvfjq2W","CNjVCK1LC3m","rvDqzvu","yxbstKS","Bwv0Ag9K","tg5cqxe","t2v1Aw4","yw1LoIa","sM5LrNu","m3WXFdj8na","wvnJv2q","EhDIwKu","DxrMofDYAxq","s2XrsLe","mhWWFdz8mNW","wxLKBNK","DuvhA1e","Ae1LC3nHz2u","ChrOB0e","ENr4u1q","y29Kzq","uxDesMm","rfjpCKi","BevrAKG","ywPWCLC","uwzMBM0","u0L3C08","C1fptve","B2jsBum","DgHHBIbSB2m","zeLUz1K","uKLPvK4","C3fqA0e","Bunez00","uu1vrw8","wKzlA3O","rvjgzMq","zNjVBu51Bwi","zMzmAw5L","uNjRyMu","AwXLx25HBwu","D2HNCMi","rwjMENK","wgLMvLK","Dfjhrg8","vhnhwLa","wMzdrwC","CMf4ueq","BgLUzw5V","C1DPuLa","zw50","rKLmrv9ot1q","teDZufu","vfHSC3q","y3vYC29YlNm","C2XPy2u","v2LUzg93","CMvUDevUzha","veTtELa","CMvZzxrfBMq","sg5PrM8","D1frAg0","x2nVBM5Ly3q","DMzgwuu","zgvSzxrLrge","vhvzwKC","tNLhD3e","BKvJDKW","y3jLyxrLrxi","C3nQv0y","v1H1vvK","BKvUveC","D3LzAuu","shjrueW","qxnRB0C","AxnFywnR","C3DkDMu","D1zoA3K","Bg9IywXty28","CNLLzwK","quXm","wwH0yLa","x2rLyNvN","DMHcDgG","AgfZ","B25SAw5L","wvLOEMC","x29UrxjYB3i","EhHnze8","CKHrr2G","q09xD00","zxH0zw5ZAw8","BwLUzW","z3HfCwu","BIWGAg9ZDg4","ywnOzwqSihC","EuLMD0y","AenSB3nLrxy","z2Pezge","u0HWsvu","y0Txr1u","quTqrKG","q2riz1y","tffOs1m","CK9VreS","DMvYC2LVBMm","sKzJD0G","mdaWmdaWmda","y0rNreW","CLPTEwW","ze9dENq","x2DLDeLUDgu","y2XLyxi","wxrABvq","u3vLCNa","B2nRzxrtDwm","vfn2t2q","x2n1CNnVCK4","Aw9U","y3r4","zMr5Evy","A0rnAKG","ChjVDg90Exa","zv9ZDwnJzxm","EuDsCvm","vujmBuq","zePgvfa","ufrwEwm","DwjyuK8","BfvJA2C","rhv1svu","BMrWB2LUDfq","txzwsvu","twvZC2fNzuu","Efrhu0C","tufyx1jfvfi","CNnVCKzPBgu","CMvXDwLYzwq","zMP3rNm","y29SBM8","tvrXD1m","lcbOB3n0BMe","suvtx0vsuK8","vhP4yNq","zw5fDMvUDa","y3vYDMfSDwu","EgzPAKW","sgjhzge","uMvHzcbWyxm","swXnzMG","yMrFzgLK","v0vNvu4","r29hCu4","AfLQt3K","vMjjqNi","sKzWweq","wgL1DfC","ANHht3m","zMreBNK","D0fhEvK","B3bLBG","DKnfwLG","yu5Jthu","D0zbz1C","vxzbqK8","ug94qNC","ihjLy29UBMu","BgvUz3rO","AxmGDw5Kzwy","DxbNCMfKzw4","x3nLCuLK","x2HHBMrSzu8","t1bZBvy","s1bSsM8","y3ruAw1LB3u","EMLcELy","z2v0u3rVCMe","r3L3BMO","Cgf5Bg9Hzfq","Aw9Vrei","AwDHDg9Yt24","x2LZtwLUAvq","Bg9Nsurhzw4","reT0CMy","u0n1vMC","wfrtDKe","q291BNq","zxrzDLe","r1nfu3a","tLr5veO","CwXHrfu","vwTPug8","C0XPC3rLBMu","u0PAyLe","tvfhDhi","ywDLsgLKzq","pxv0zI04","C3jJ","BM93","CIb0DhDjra","Dg9mB3DLCKm","CfrJBeK","zvDsuwi","yxnL","Cg9W","vK1Iu20","Ec1TC2CTy3u","yxbWBhK","s3jpB0G","ue9bBey","s2zAEfa","ywDLu2HVDW","Bg9N","t1bftG","A0jLCxq","BKvWCvq","z2v0q3vYCMu","wNbLrLa","uKPbr1i","yNbSvvq","mdaWma","r2v3vhG","DeLgC0O","BgThqMy","BKroC3C","ysbTDxn0igi","zMLN","r05Rz2m","B2jtq2u","qxz3Bfi","sfjiq3y","EhfLug8","D0TVq2u","y3jLyxrLtwu","BNruCMLLC0m","BfrPBwvVDxq","x3bPBMDmB3m","z2LbCKO","yxbWzw5Kq2G","CwLTuMW","DhDVCMTdAge","rM5RsK0","q01wwhm","DMvY","DgLTzw91DcW","vxDMsuy","q1fxuxe","C2v0sxrLBq","zxjFCw9Zx2e","tKvirxi","C2nYAxb0","z1Hyv3G","zNjVBuHHC2G","yxbWBgLJyxq","zNjVBNrPzxi","yuPYExy","DKL4Cxu","Dg5MAuW","BhPYChG","uLLPBxa","nhWWFdj8m3W","EeT3s3m","y0PWvwW","yuvjyMK","uePcv2C","CMnxAee","C2vUzf9Hy2S","Aw5KzxHpzG","B0PYD2G","sNHXv1q","DgLUzYbZzxi","reiGzMfPBgu","z21Vuhu","vwvRvxa","Evjfvei","x2HHBMrSzva","C2fNzq","A3jzt3O","q3vZDg9Trxi","qKj0v0q","ywnRpwzYB24","C3bKu0C","yMXntMe","Cg9PBNrdB24","BvbYrhq","Cgu6ia","DgLTzw91Da","AuTvueC","CeLXAMC","BMCGzMfPBgu","Cu5VuMK","C2v0zgi","y29Uy2f0","rNvKr3m","zgvIDwC","ExbL","EgP2wgm","CMvHC29U","AhroA00","tK1ts2C","Bfbnu3a","CMH5BK8","t1HvA0S","yMXVy2TLza","vMTLEM4","suzSshm","uuLZy1K","s3nKtMi","Aw9Ul2PZB24","DMTftu8","su5tvefova","qLDLsfu","D2fZq2XLyw4","y3DuwLC","wgHHvNy","Aw47y2HHCNm","y3jLyxrLrwW","AxjZyKS","Cg9PBNrbBMq","zwDqt24","tfjsBuG","svjJCMC","zNbeu3m","weHTB3m","mhWZFdi","zNjVBunOyxi","tw5QENK","wMLuv1O","AwrI","AffMCMO","t2vdEwi","zhzsC2O","Be1cr0C","D2vI","CgfNzxnOB3C","BML0AwfSAxO","AM9PBG","sgPZs04","BgLTAxq","yNL0zu9MzNm","DMvNwhy","uefQAxC","D1Pgt1e","qKzwC2m","EwLXAgu","zMLSDgvY","uvzQt1e","rg1jrNG","vvPtufu","sffIyuy","zxrxB3jRq2G","x2n1CNnVCKy","zcWG","CgfYC2u","tuvtu0fhrv8","nhW1Fdf8m3W","rhzHD0e","A01kuKu","wezzExa","DNjKC1q","Bxn5Ahu","AgfUz2u","yxv0B21HDgK","zxjFywnRx20","BhzoC2W","wvzZAKq","rM1puwe","Cxfet00","svDmrNy","wKz2vw8","AgvHzgvY","z2vY","Aw9UvgLTzw8","B3bLCNr5","ChjVy2vZCW","vu1dsge","jMPZy2fSBgi","ruzXA3q","u2jeyLi","BezSDxnO","vxbKyxrLq28","ywX3yxLZ","uvL0AMe","EvvjA3q","y3rIwhO","wwzWDKy","BfDhz0q","x2LZsw5PDa","C3ndEfC","CgLUz1rPBwu","wundt3y","C1DXtK0","zvfuA1i","x2rYB3bhBg8","vw5PBxbSzw0","rK9Az0y","vw5Oyw5KBgu","zw5XDwv1zq","Cvbkruy","uMPJwwq","u2HHCMvKv28","zgvMAw5Luhi","rLjptLrjrvi","BfDIC1m","q0Xpu0ve","wK9UELu","nhW1Fdj8mhW","wvjLDxm","zxjFDhrS","Eg1Hz2i","vg5HA0q","DLLKAhi","ve5ozLK","EfbitNK","sgzIsMS","x29UtwvZC2e","B25ozxr3B3i","u2Pmzwi","C0Xf","y2HHCKnVzgu","AevYCM9Yrxy","vfvzCvi","BfbMr0i","BNvTyMvY","ALrMDeK","r1jUuuy","rwzgCMe","CwfLBuu","DxPrueq","yvzpuNi","sxH6q3G","zgf0yq","ELrHEu8","u2vXsuq","x29WDgLVBNm","y2XVC2veqG","DfLgwMi","ENzNrM8","y01Ru0y","qw1VDw50","D3jPDgu","AM1OBu8","r2zACMC","ig1LC3nHz2u","zMzLCG","x2vUzhbVAw4","rLnjueu","qLnssha","q2v3Bge","AgvHzgvYCW","AezPAgy","tKDFrvjst1i","z2v0","BKfot2e","txnnrue","C3rHCNq","C2rPwM0","BwvZC2fNzv8","zwn0","x29UugfNzu4","yw1L","t3jjBvC","B3bLBKrc","Aw5Lza","vvfTuhe","C2HPzNq","BMCGDxjSoIa","ww1cBhe","ihrPBwvZ","tLLNzu8","yw5ZzM9YBvq","x19LC01Vzhu","sfrsCMy","o2nOyxjZzxq","B25LCNjVCG","vuLLvNK","ALbryw0","B2zM","BK1Msvu","BgLUzq","whbxuw8","Chv0","sNH0qve","DKrkAey","D1z1CKu","ywXPzcb1CMW","x0vysvnu","C0nVDw50zxi","DfbOuLa","zw50zwqGDhK","sNPHzLi","y3vYC29Y","q29Kzq","C3bSAwnL","CMvJzxzPzwq","BwLUAvbYB2C","zwrPyxrLBhK","t0fXtwK","svf0CKe","ChvZAa","yMfSu2nVCgu","x29Uq2XVC2u","zxmGCMvHy2G","r0T4sMK","r2LSBha","zhHVAfG","DxbKyxrLq3u","q0T1DLC","ExD3vNu","rMzSy2q","CM9YrxzLBNq","C3rVCcbPBw0","AwrZrNO","tNjuAxa","zMzMzG","sxH1vLe","CuzpEge","Aw50zwDLCIa","AxnrB1nnzxm","zsbHihn0CMK","shzxAwi","tevRCLC","zw5HyMXLqxu","zxjYB3i","EeTOsvm","B3jRig9MzMW","C3vIC3rYAw4","BLjXtue","yMfRALu","DhjHBNnHy3q","vgnltgm","x2LZqNjVD3m","q3vZDg9Tq2W","z2v0qwXSs2u","CxP3wM0","tLzlDxu","x2LUAxq","nJi2nZiXu1vpwu5c","B3vttKW","x3jLy29UBMu","Dg9hzw5LCMe","Dhj1y3rVCIa","vNnfq1q","BKjHuNy","q2nnAwu","suz5zKq","u2vYDMLJzvC","t0HmshG","sNPAz0G","tuHgALC","BwLZzq","C2vYDMvYvgK","ENDzqNm","svPlD1C","sg5Nq2u","twfevfu","ueXftwS","AxjAD20","zM9Yy2u","tgLZDgvUzxi","CeTLvNm","seLsteq","AuX6sMO","BhnJA1a","EvztEg8","ANzcwu8","DcbVzIbYyw4","BMrWB2LUDca","BvD5DKW","tMTwr2e","C05qA2C","qvrnDha","tw9KDwXL","tKrOzfe","Bhm6ia","B3v0sw50zxi","qvPAv2e","yK1JALy","v2XdvwS","C3rYAw5NAwy","yw5Hz2vY","x2zVCM1HDeu","twLZC2LUzYa","vgLTzw91Da","r1LdDui","B0HKDg4","BgvY","z2v0qwXS","ign1CNnVCIa","BKXPBMu","CM92AwrLige","ufbyzgi","quXRzuS","BMDLza","r0DUvKq","BvLLDMK","vxztsxu","ANniwhq","rMnyvhq","BwTeAve","sLnptLa","Dw5KzwzPBMu","ignVzgu6ia","s21KrKS","A2HlD2O","x2LUAxrqCM8","wNHyzwi","A2PsCNG","BNPQq1C","u2TtC3e","v2vIu29JA2u","C3rVCMu","DvLStgy","C0jf","AefJA01LC3m","zw1PDa","rLfzvMe","Aw1LCYbPBIa","BwfW","B2fK","EwTmDLe","CwfOwfq","y3vYC29Yx24","B3nLza","x2TLEvbHDgG","thz4y3u","CMvTB3zLrxy","BxnNsuq","CKrkqLe","rgXoAem","y29UBMvJDeu","EvvhD1G","u3jxvuW","AwnYwhu","uKndCxa","Cfbez1C","whfkteq","B0fQtwm","zhL1CuC","y09Wzw4","ywDL","qwvVA28","ChHkrhG","x3bYzwzPEa","vKPzwuy","D05Jr1C","CMrKu1O","CM53s0i","Ec1TC2CTCw8","AK90wg4","qw9lvLC","zg9Uzq","Dg9cExrLCW","B3jpBMXPBMu","CgvYC2LZDgu","Dw1jA2m","EMD4qxi","twz5DeK","B2LUDfjLywm","BMfTzq","CvrhtLO","z0vVyue","qwf5veq","twTYrg0","Axz0z2y","rhvHBgi","zxjYtM8","uujYD2u","verKzMO","AxnmB25N","DND0r2i","yufSDg4","txrNCfi","q2TeAve","sgrNsgC","x21LC3nHz2u","l3DZl3yY","sK1fu1m","DhjPzxm","BfnfvLq","zezxCwe","C3vJy2vZCW","BwvY","Ee56r0C","t3DYs3i","ywvcAMK","BLbwD0K","tuvwD2y","igzHAwWSig0","A01JBwe","n3WZFdf8ohW","vxrkDuG","svjJCe4","wxvsBeS","Aw5JBhvKzxm","y2f0y2G","y29UDgLUDwu","Aw5N","zNPZzLe","yxrHlcbKyxq","y3bnu3K","DMPlBK0","r1bNr20","swTMwMG","rNzMA2i","DML1vLi","DeLWs3e","rvzmAwi","t1H4rKi","DK1yDwW","vKHTEei","DeXxtNe","uMPNweG","t3bLBKv2zw4","Dgv4Dc9WBge","wwv6qw4","vgfN","ChjQB2q","uNrSsfu","s0nyt2W","zv90Aw1LB3u","AxnrB1nby2S","x3bHDgHlzxK","ywr2yw5Jzq","A3buDwe","C3nHz2vfDMu","ywXSB2nvBNm","CMvHzg9UBhK","tfjsA2u","CMvHzhLtDge","zNjVBujPDhm","C2v0","y3bwruu","zMnVqwC","x2XPC3rLBMu","t1DVveW","yNL0zxm","wgzes3K","x2jPBMfYEvq","DgD2DM4","nhWYFdn8mhW","x21PBMLoyxy","BfPSueC","rxHLvK0","B1fTExi","BfrHt2O","t2ruDLK","v3LkuM8","AwTtAhy","tenKwKm","u0jYBe0","ueDos1m","q0jNyw4","t3DAzLK","Bfnxt3e","C25gEei","qvPtruu","ywnR","rKjrEu0","zvvYBa","igXHCMDLCIa","u0jqBg8","s2DeEu4","sfvIrfK","ywWGy3vYC28","DMvUDa","uM9sDwO","B25szwnLAxy","vwjyyLm","qKrhswq","zMLSzw5HBwu","BgLZDgvUtMu","x29UvgLTzw8","rKLlAKu","tuHez0y","x3jLBw92zvC","q2LNA2i","mtb8nNWYFdC","zK1Xy2u","q09otKvdveK","zM1kseC","zgvJB2rLzey","y3HOCfC","Dg9cExrLC0i","D3jPDgvvAw4","CgvhyLC","x3nVy2TLDa","v214Cxa","r3Hdt1m","uhjPBwfYEuS","tLrnuhy","Dg9tDhjPBMC","yKHdEMm","AhPAshG","teL3ENa","CgvOtgu","Dw5ZAwDUzwq","uMvJB25Uzwm","zxf1ywXZ","AwXK","ihzHBgLKihm","EKLpCgy","ufzrBhK","D2nyyLa","AxnszwfKEq","wgnmuuK","z0LWt0W","ntu1nZC0ne9evNnvtG","lcbxzwjtB2m","BfnrBhm","q29UzMLN","wwT1qxa","BNnpthq","uLjpuG","ywD2tgO","Cgzxy0y","CwPPEhu","rxr0vK0","s1j2Dg4","C0z4Bgy","yNvMzMvY","rLP5q1m","mtf8oxW1Fde","BNjduvi","zxjYtxnN","r2fXshe","y2flAfi","tfnSA1i","B3Lpvee","u0jzEha","AwDPrNO","svjHDMq","r1b2yLK","r25Ws1a","wfPkDhy","ywjVCNq","zw5JB2rLrNi","x194x21Zz18","x2rItMfTzq","rxjTs1q","aaaaaaaaaaa","zhrjuK0","u2vlvLu","vwriCfa","DeLUDgvYy2u","DcbSAw1PDa","zKHZqKe","x2DLBMvYyxq","Ef9MCM9UDgK","x2LUDgvYDMe","x0rctMfTzq","sKDPEe8","zKPJwgO","u0jeuvG","C29Tzq","uLnXuw0","DfbxAxu","BNrfBMrWB2K","t29oAvq","rxjYB3jdB2q","seHOBe0","B25TzxnZywC","y2HLy2Tszwe","B25pCgvU","ChjVDg9JB2W","B25mAw5L","yNL0zuXLBMC","tNDPq1K","x2rPC2nVBM4","y2HLy2TdDxi","A2zWq0e","zw5JB2rPBMC","q0P3Ae4","D1j0qxG","ywrK","CvrxA3K","CM5Aufm","ywnOzwq","DhbizwfKzxi","yvrouNq","B25VCgvU","rLDt","t2viD2i","D3m6lY8","BNforvu","DwPvs3K","wfHXyui","zevMv0K","qK9nDLi","z3jMrNC","v2vPEgLUsLm","ExjZDMu","Der2t1C","tM1cEhG","AMPyDgO","wNPjENe","qxretei","A3DAvxO","yxv0BW","B25dBg9Zzq","CMvZB2X2zq","C2jJt1a","CMvZDwX0","A2DZDfe","x2nSzwfYvgK","rMfoDge","vxPMAfe","AKf3q1K","q1zSyxm","AhDSBvi","zvbsyNG","y3jLyxrLt3a","x3DZsw5ZDge","qNDOEhu","Ae9Wzw5fDMu","y29TCgXLDgu","z2vtEw5J","sw9OBha","BMvY","zfDVCMTLCKC","BxzlA2m","r3r5sMm","rhvOEwu","x2LZtwLUAvC","sKDIAu0","mJb0AKLzsNC","A2r3B3a","tg9NsurozxC","AxnbCNjHEq","zgvS","rNbLv0m","De1jC04","zMXVB3i","v2jlqMu","zgnst0S","AfDlDeW","B2zMC2v0","EKrMEfe","s0HuCMu","zu5iq0O","wK12zuK","zw5HyMXLvhi","zcbLCNjVCI4","CLzHBhvLCW","rxDutfm","mxW0Fdj8mhW","yxrLq291BNq","v1PyBgG","z2v0sxrLBq","vgrtswC","zvHcr2y","Afzerg4","DxjS","B0jfs1u","C3vIyxjYyxK","ze1uEwC","igfYCMf5yNu","qMLbv2W","tMLfqNa","z3j6EuG","DuDkz3O","swXduu0","te9wsgS","Ew9mC2S","swzPDK8","v3zWqLy","DujHs08","zNDZxZeUmc4","EwfQshq","A2PMt0m","D09Vu20","EuH4vNC","B1HkEuW","y3vTqwe","uhPmr1a","BMnLq2XVC2u","AgfZt3DUuhi","uNHzExa","wwPdr0G","qM5ivfa","ufzkzu8","y3jLyxrLuMu","zMLUza","CMH1r3O","vhrpvuy","DxnLCKLW","DgHLBG","qKnADMG","AfbHr1e","B21Ny1a","ufDxzwG","v0TWqxm","u1LVr1O","y291BNq","y29UBMvJDfm","B3jL","yuL4q3a","Dg9iyxnO","Ehv0DhG","Bvz5zu0","x3bYB3rVy28","z3Pmy2e","wwzqB0W","Bvz0zKe","t2D0C1y","Dw50","x2nSzwfYugK","ywrKrxzLBNq","svDWC2K","D2LSBfjLy28","qLjIv1q","C2v0q3vYC28","qwn3v0W","CYbWyxjHBxm","sw9Zqwi","r21JDNi","ugfzCKG","CMfUzg9T","BfrVChC","y2uGBM90igK","D2fjDeW","y0roC1C","Bwf4twvZC2e","B25fCNjVCG","rejktfe","sxLNq0K","ywnRDxbfBMq","svLZrLi","CYbPBNn0yw4","yw1Lu3bHy2u","DgHWtvq","BuH1DKq","yMfSrxzLBNq","Dg9oDw1Izxi","C1nxBKu","x3bPBMC","zxj2AwnL","CMvJB25Uzwm","vhjRuMu","Bwf4uMv0CMK","icSG","zLf1vxK","Cgf5Bg9Hzeu","ihn1y2nLC3m","zwHSuK4","y29UBMvJDca","B2X3suy","tKfqz3i","z29PBMCGyxC","y3jLyxrLq2W","s3DQuLC","B2HzAgq","igzPzwXKoIa","yMfxzfO","q0Xpu0LorW","sxnVruK","EM1QB2W","D2vkqvu","Aw1TBxi","BMvLzf9Hy2S","zw5mAxi","zxjFCw9Z","rhfosei","s2fRsNa","CgXdwwG","svDeDwC","CLDkChy","Cw9Z","nJC1odC0mfPhtKPKDa","z3LUwgy","t0vfuMq","CMfTzq","BMnVzgLUzW","quLNuNm","D2TZDKS","zK5mzu4","wxzWuKm","x3vYBa","Ec11C2uT","uxLXuMW","zuz1DK0","tg5ZDfK","z2vrDwv1zuW","lcbTyxGGCMu","y1revxq","CMTWCue","CKPswey","C1nwAxa","zhvjsvi","wKrrquW","EMz6BLy","AgvKtwf4uMu","thrlBKC","rvjst1i","thvsv2C","B2nRzxq","x2rPC3bHDgm","sevLvwW","zgzVzvC","Aw5L","B0Hcweq","DgfYz2v0","tuzTsuW","DeLiyxO","EwfOwgK","rxzLBNq","DKfiyKG","uLzruMW","y2XVC2uSihC","x1fVu01HBMe","zNDPvLq","v2X1DM8","x3fVC0rc","u25cEMO","rfHqDuu","zxHWB3j0CW","zM9YrwfJAa","vwPlt1u","z3fOELC","y3vYC29Yx2y","EvHND3C","C3fVB0q","CgntCMG","ze94v2S","yNPHquy","Ahr0Chm6","wLLNtvy","sLjAveK","CufICuG","EgLJzvm","DNPxs1G","CMvZzxruCMK","yLjUzwK","vNbprNq","rNjVBNrPzxi","D3nZoI8V","AxLYt3e","tMfTzq","Bg93","uvPjthi","A0jiALq","uxrMuhy","BNrLCG","A2TOCKO","svL3C3a","sLHlCNu","BeHHBMrSzxi","CNzHBa","CMvQzwn0","vhrovve","B3nLrxzLBNq","Dg9Y","zvbnvwO","vxzMBMi","EfbTEgG","CKXryNy","swH1Ag0","sgDpC0S","CfzVshi","BgrxD3y","tNjPzva","BuvZzu8","Dw5RBM93BIa","Aw5PDcbrB1m","sK5QB0C","B0XjDw0","CgLUz0LUDgu","qwjVCNrfCNi","rLfuu2u","zxjFBxnNAwq","DvryDLi","Dhr3Awq","u1HUANO","u0nfzu4","y3vYCMvUDeu","wNnJufm","Dw9NrKK","DeLK","Efj4sMq","v3bTEgO","A2v5CW","thjIsxO","CMfNzvn5BMm","yvzpDhm","r3biuM8","BvP0vNi","Cxjhs2q","teTOC00","qwvVyw4","uLbvt0u","EvjLy29UBMu","CNnVCL9Uyw0","x3DHAxq","nNLJqMDJEG","rKDpqxu","nZmXmZK0mg1Nquztsq","uMvpC2e","qMncBMW","AfnoBMy","BgLfCMu","EwLnq0W","BwvKAwf0zwW","wujVt2i","y29UC3rYDwm","D24GCMvHC28","DgjZu1y","rxLvq0u","ENrLALC","qwX5rNO","B3bLCNr5tMe","Dgv4DfbHEwW","CLLuzg4","tePLB2e","u0nZuuy","uxvLDwu","x2HHBMrSzvi","zvrsD2y","v2XnuLK","yMfJA3vWigu","z2rZD2O","zgrdDgy","AeDRtKu","B3jLtMfTzxm","DgvZDa","qMXPsu8","CMLPAhi","vLHNCKS","A1bWDMG","Ee5xqMq","x2LUAxrhBg8","C2vUza","BgnYBKe","zxq9DxrMltG","svfXDee","y3vYCMvUDeK","C3rLBMvYCW","rvD5uKe","zNvUy3rPB24","uujqEhq","Bw9xCgq","DMLJzuLeig8","y1rhAKm","BM5Ly3q","vvnbtvy","AvnnwMG","uNDlswe","y2jZwxu","CgjICdi","yw9ys0S","Dev2zw50","yuPyy0i","zNjVBuj5Dgu","tuffvum","z2v0s2v5","Dxnqq2K","vKLUB2m","CMvHzfvjBNq","ywXSzwqGBxu","CMvZzxrdB3u","v0nTq08","CMvWBgfJzui","C2vUDa","DxrVuMvJB24","CvzHAvi","rLPwsMK","zw5HyMXLuw8","yNLL","BevjzfG","C3rYAw5N","qNvLCfG","rgfJtue","rgvKAwnHDgu","x3bPBMDqB24","B2LTshu","y2fSBa","BLHrtKy","x2LZv29YA2u","sgLODMG","q2rUsLK","txHfrLq","ugLcvhO","x3DZ","vu1tDMW","rM93qLm","zej6B1G","x29Ut3bLBG","v2vJA0K","Axnby2TdBgu","sfbnCha","yw5Nzq","DgfIyxnL","DhfUD1C","s2vZCeu","y29UDgv4Da","tejmELq","DMvTzwC","A1n0yxr1C0m","tfDUyvm","ANrvu1y","BxnN","B2jQzwn0u3q","x2n1CNnVCK0","ywzL","ihrPBwvVDxq","zwnVBM5Ly3q","DfPjtxy","CMvWBgfJzq","mhWYFdr8mxW","AhPHzxi","zw5KCg9PBNq","yvPet28","y2XVC2u","DhjPzxmGCMu","ENDrsuS","yxnZAwDU","qMfuwu0","B3jRzxjhBg8","A2v5","uK5lt2q","AKvmELO","CgXLyxnLiha","uhD2wfO","yuLiwvy","DwHICgO","x2fKzfDZtgK","tg9Nsuq","DMfSDwu","twPzyMu","q3PyDhO","CMfTugfYyw0","teDwAwS","rwHwz2m","zNjHBwvuExa","yxPnDNu","Axjosgq","yvPpzfG","mxWZ","B3vUDa","C2vYDMLJzs0","AwXSihvZzsa","BgD4DwG","De1HBMfNzxi","zgv2AwnLx2K","CMvTB3zLq2G"];return la=function(){return t},la()}function NI(t){let e=N,n={QZILr:function(i,s){return i===s},LOVHk:e(1083),rYTdn:function(i,s){return i(s)},LszMa:function(i,s){return i instanceof s},NdDWe:function(i,s){return i(s)},kzCfz:function(i){return i()}};return n[e(985)](typeof t,n[e(808)])?n[e(1057)](OI,t):(n[e(1240)](t,IDBTransaction)&&n[e(1196)](DI,t),vp(t,n[e(1344)](kI))?new Proxy(t,fa):t)}function Vt(t){let e=N,n={iooDB:function(s,a){return s instanceof a},xNWBd:function(s,a){return s(a)},ypnRo:function(s,a){return s!==a}};if(n[e(1547)](t,IDBRequest))return n[e(1074)](PI,t);if(aa.has(t))return aa[e(298)](t);let i=NI(t);return n.ypnRo(i,t)&&(aa[e(577)](t,i),ua[e(577)](i,t)),i}var vp,mp,wp,dd,da,ld,aa,ua,fa,hs,_p=bp({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={wVNky:function(n,i){return n(i)},gxEqe:t(1008)+t(1665),PPXdb:function(n,i){return n instanceof i},ucIMZ:function(n,i){return n===i},daoKS:"done",dxIxv:function(n,i){return n===i},IRcpN:t(1146)+"oreNames",wQJxS:t(1016),ZTTny:t(457),AOmyb:function(n,i){return n in i}};vp=(n,i)=>i[t(700)](s=>n instanceof s),dd=new WeakMap,da=new WeakMap,ld=new WeakMap,aa=new WeakMap,ua=new WeakMap,fa={get(n,i,s){let a=t,l={ohYhd:function(u,f){return e[V(1445)](u,f)},yiqhe:e[a(1461)]};if(e.PPXdb(n,IDBTransaction)){if(e.ucIMZ(i,e[a(1195)]))return da.get(n);if(e[a(1294)](i,e[a(538)]))if(e[a(1271)]!=="uTXvR")_0x14f206[a(1332)][a(1189)+a(645)](_0x3cc6fe),_0x32b0b5[a(1622)+"JSONP"]=void 0,l[a(897)](_0xc7fd3f,_0x3791d2&&_0x37117b[a(1145)]||l[a(190)]);else return n[a(1146)+"oreNames"]||ld.get(n);if(e.ucIMZ(i,a(457)))return s[a(1146)+a(1068)][1]?void 0:s[a(1146)+a(841)](s.objectStoreNames[0])}return Vt(n[i])},set(n,i,s){return n[i]=s,!0},has(n,i){let s=t;return e[s(437)](n,IDBTransaction)&&(e[s(1294)](i,e[s(1195)])||e[s(1294)](i,e[s(1297)]))?!0:e.AOmyb(i,n)}},hs=n=>ua[t(298)](n)}}),Sp={};RI(Sp,{deleteDB:()=>BI,openDB:()=>MI,unwrap:()=>hs,wrap:()=>Vt});function MI(t,e,{blocked:n,upgrade:i,blocking:s,terminated:a}={}){let l=N,u={TsGZP:function(m,g,v){return m(g,v)},dSFwC:function(m,g,v){return m(g,v)},gzLca:function(m,g){return m!==g},ldwWB:l(916),xHNnN:function(m,g,v,w,b){return m(g,v,w,b)},aVORr:function(m,g){return m(g)},FudGs:"close",WywgF:l(1537)+"eeded",hwlmR:l(1671)},f=indexedDB.open(t,e),x=u[l(275)](Vt,f);return i&&f[l(853)+"Listener"](u.WywgF,m=>{let g=l;u[g(847)](u.ldwWB,g(767))?u.xHNnN(i,u[g(275)](Vt,f[g(748)]),m.oldVersion,m.newVersion,u[g(275)](Vt,f[g(375)+g(1486)])):(u[g(1413)](_0x3e0f17,_0x1683b8,58),u.dSFwC(_0x38711c,_0x375447,_0x298f76))}),n&&f[l(853)+l(405)](u[l(755)],()=>n()),x[l(832)](m=>{let g=l;a&&m["addEvent"+g(405)](u[g(1661)],()=>a()),s&&m[g(853)+g(405)](g(1473)+g(207),()=>s())})[l(541)](()=>{}),x}function BI(t,{blocked:e}={}){let n=N,i={apRNK:n(1671),rHQGh:function(a,l){return a(l)}},s=indexedDB[n(1432)+n(1136)](t);return e&&s[n(853)+n(405)](i[n(1371)],()=>e()),i[n(1457)](Vt,s)[n(832)](()=>{})}function yp(t,e){let n=N,i={aTNRt:function(f,x){return f+x},HPMpp:function(f,x){return f+x},UYxQc:function(f,x){return f+x},tnfiL:function(f,x){return f+x},yUIkt:function(f,x){return f+x},SCuVg:function(f,x){return f!==x},RCCqp:function(f,x){return f&x},GSESp:function(f,x){return f|x},QIscY:function(f,x){return f<<x},pdBYZ:function(f,x){return f|x},SVbtM:function(f,x){return f|x},duIIR:function(f,x){return f<<x},jRQZt:function(f,x){return f<<x},NrieP:function(f,x){return f&x},yudjt:function(f,x){return f<x},oQmyr:function(f,x){return f>x},tPhRP:function(f,x,m){return f(x,m)},NyGwq:function(f,x){return f+x},ztejW:function(f,x){return f&x},NtOVA:n(573),HTRrf:function(f,x){return f instanceof x},Rrkbe:function(f,x){return f in x},ePRbx:function(f,x){return f===x},GhpYS:n(1456),PYubw:function(f,x){return f in x}};if(!(i[n(318)](t,IDBDatabase)&&!i[n(1407)](e,t)&&typeof e===n(1114))){if(i[n(756)](i.GhpYS,i[n(1328)]))return;_0xa6f0b0=_0x345d85[i[n(725)](i[n(1134)](_0x5bb4e8,_0x1342e6),1)],_0x46deaa=_0x16702c[i[n(1134)](i[n(1194)](_0x1c4d89,_0x10aeae),2)],_0x4dafbc=_0x505007[i[n(1625)](i[n(229)](_0x170750,_0x29025d),3)],i[n(1552)](i[n(480)](i[n(1556)](_0x44fdc4|i[n(1674)](_0x1bfa69,8),_0xf2548e<<16),12632256),8421504)?_0x1f777d+=_0x43558d:(_0x4895f4=i.pdBYZ(i.SVbtM(i.GSESp(i[n(934)](7&_0xe42141,18),i.jRQZt(i.RCCqp(63,_0x43d323),12)),i[n(1674)](i[n(1006)](63,_0x288228),6)),i[n(1006)](63,_0x59ca4a)),i.yudjt(_0x17d372,65536)||i[n(590)](_0x5cafc3,1114111)?_0x47a83d+=_0x588920:(_0x3fbb46-=65536,_0xb1ed30+=i[n(334)](_0x2d5bb2,i[n(1434)](_0x2ac534>>10,55296),i[n(1134)](i[n(1053)](1023,_0x397750),56320)),_0x47d4a6+=3))}if(ca[n(298)](e))return ca[n(298)](e);let s=e.replace(/FromIndex$/,""),a=e!==s,l=Ap[n(540)](s);if(!i[n(1191)](s,(a?IDBIndex:IDBObjectStore).prototype)||!(l||Ip[n(540)](s)))return;let u=async function(f,...x){let m=n,g=this["transact"+m(1486)](f,l?"readwrite":i.NtOVA),v=g[m(457)];return a&&(v=v.index(x[m(311)]())),(await Promise.all([v[s](...x),l&&g[m(497)]]))[0]};return ca[n(577)](e,u),u}var Ip,Ap,ca,FI=bp({"node_modules/idb/build/index.js"(){let t=N,e={KODRv:t(327),XpWQo:t(1480),CMVXs:t(1099),irNHd:t(433),IyvaW:t(379)+"ys",BBtWD:t(839),RNKOd:function(s,a){return s(a)},YScWd:function(s){return s()},OoNiT:function(s){return s()}},n=(t(252)+t(1182)).split("|"),i=0;for(;;){switch(n[i++]){case"0":Ap=[e.KODRv,t(720),"delete",e[t(326)]];continue;case"1":ca=new Map;continue;case"2":Ip=[t(298),e[t(1610)],e[t(1180)],e.IyvaW,e[t(1647)]];continue;case"3":e[t(1164)](LI,s=>({...s,get:(a,l,u)=>yp(a,l)||s[t(298)](a,l,u),has:(a,l)=>!!yp(a,l)||s[t(1452)](a,l)}));continue;case"4":e[t(1378)](_p);continue;case"5":e[t(704)](_p);continue}break}}}),zI={idb:function(t){let e=N;t[e(961)]=Promise[e(746)]()[e(832)](()=>(FI(),Sp))[e(832)](function(n){return n})}},Ep={};function Kt(t){let e=N,n="0|2|3|4|1"[e(1317)]("|"),i=0;for(;;){switch(n[i++]){case"0":var s=Ep[t];continue;case"1":return a[e(961)];case"2":if(s!==void 0)return s[e(961)];continue;case"3":var a=Ep[t]={exports:{}};continue;case"4":zI[t](a,a.exports,Kt);continue}break}}function V(t,e){t=t-161;let n=la(),i=n[t];if(V.tRMjbO===void 0){var s=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",g="";for(let v=0,w,b,I=0;b=f.charAt(I++);~b&&(w=v%4?w*64+b:b,v++%4)?m+=String.fromCharCode(255&w>>(-2*v&6)):0)b=x.indexOf(b);for(let v=0,w=m.length;v<w;v++)g+="%"+("00"+m.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(g)};V.TLYcgk=s,V.YqDSEB={},V.tRMjbO=!0}let a=n[0],l=t+a,u=V.YqDSEB[l];return u?i=u:(i=V.TLYcgk(i),V.YqDSEB[l]=i),i}Kt.d=(t,e)=>{let n=V;for(var i in e)Kt.o(e,i)&&!Kt.o(t,i)&&Object[n(247)+n(219)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;Kt.o=(e,n)=>Object[t(1490)+"e"][t(822)+t(219)].call(e,n)})(),(()=>{let t=N,e={zLBSk:function(n,i){return n===i},BOMvR:t(766),enLir:t(447)+"d",yXgww:"Module",SbLgW:t(317)+"le"};Kt.r=n=>{let i=t;e.zLBSk(e[i(734)],i(484))||(e[i(906)]!=typeof Symbol&&Symbol[i(637)+i(562)]&&Object[i(247)+i(219)](n,Symbol[i(637)+"Tag"],{value:e[i(966)]}),Object["definePr"+i(219)](n,e.SbLgW,{value:!0}))}})();var Oe={};(()=>{let t=N,e={IFyfD:function(c,r){return c(r)},eQTkR:function(c,r){return c+r},LuRWg:function(c,r){return c+r},nBaRv:function(c,r){return c*r},UdgbC:function(c,r){return c*r},DJWFn:function(c,r,o){return c(r,o)},BnHTP:function(c,r){return c+r},BiAWl:function(c,r){return c(r)},TnakD:function(c,r,o){return c(r,o)},LQhKS:function(c,r){return c+r},JFcwH:"0000",rWJpv:t(360),ZFKkz:function(c,r){return c(r)},Aeoan:function(c,r){return c(r)},nRqMA:t(1475)+"0000000000000000"+t(1475),vIxqu:function(c,r){return c<<r},KHTre:function(c,r){return c&r},yGRqS:function(c,r){return c(r)},zEAVQ:function(c,r,o){return c(r,o)},DacMA:function(c,r){return c+r},BWeHU:t(369),ljmJa:function(c,r){return c!==r},Ihuhm:t(322),ZFvUo:function(c,r){return c>r},hDifG:function(c,r){return c<r},MjYbe:function(c,r){return c===r},oHdtn:t(539),xjvXc:function(c,r){return c<r},UvSIu:function(c,r){return c-r},qZztw:t(915),GciUl:function(c,r){return c-r},mYevi:function(c,r){return c<r},fQuUy:t(411),IQtrA:function(c,r){return c!==r},vjKnM:function(c,r){return c-r},fpDSs:function(c,r,o){return c(r,o)},lPMSp:function(c,r,o){return c(r,o)},GRNTZ:function(c,r,o){return c(r,o)},TtNUQ:t(772),Tzxbt:function(c,r){return c>>>r},KGTqO:function(c,r,o){return c(r,o)},WKpAs:function(c,r,o){return c(r,o)},TUYqR:function(c,r){return c===r},yahXi:t(428)+"required field: "+t(1163),NMSKg:t(428)+t(1505)+t(898)+t(1172),IWLFv:function(c){return c()},qimRl:function(c,r){return c instanceof r},xRxJd:function(c,r){return c===r},AZZWa:t(497),ldWwv:function(c,r){return c===r},qPJEF:t(1146)+t(1068),fMqce:t(457),QBrwe:function(c,r,o){return c(r,o)},PXXjB:function(c,r,o){return c(r,o)},FQYVa:function(c,r){return c!==r},vMXul:function(c,r){return c!==r},grfFw:function(c,r){return c(r)},sWqNM:function(c,r,o){return c(r,o)},YCCOv:function(c,r){return c(r)},pOjGa:function(c,r){return c!==r},HjsKN:t(1677),JRZTI:function(c,r,o){return c(r,o)},QYtja:function(c,r,o){return c(r,o)},pcSrh:function(c,r){return c!==r},EVLib:"dYfuB",RjcYd:function(c,r,o){return c(r,o)},wVurE:function(c,r,o){return c(r,o)},ehlRN:function(c,r,o){return c(r,o)},EDsYC:function(c,r,o){return c(r,o)},huVCf:t(1318),pxJDx:t(849),UJNps:function(c,r,o){return c(r,o)},irZwm:function(c,r){return c(r)},MQICl:function(c,r,o){return c(r,o)},xtSKe:function(c,r,o){return c(r,o)},pmzgS:function(c,r,o){return c(r,o)},USAMV:function(c,r){return c(r)},MFmIL:function(c,r,o){return c(r,o)},MHFjW:function(c,r){return c(r)},EwTLS:function(c,r,o){return c(r,o)},LbHkV:function(c,r,o){return c(r,o)},pthoA:function(c,r,o){return c(r,o)},dIngY:function(c,r){return c===r},GewTx:"Missing required"+t(898)+t(1171),KCXOl:function(c,r){return c===r},VbIBr:function(c,r){return c===r},aZOdX:t(428)+t(1505)+" field: "+t(1372),gBSks:function(c,r){return c+r},vzWKX:function(c,r){return c===r},tMIsN:t(1650),YBoOb:function(c,r){return c(r)},nlFaO:function(c,r,o){return c(r,o)},pIDIr:t(240)+t(335)+t(1653),sWiRP:function(c,r){return c||r},FqRyP:function(c,r){return c!=r},yRETB:"undefined",vDJhF:function(c,r){return c===r},RxYyp:t(1276),KuVuv:t(307),RwKIa:function(c,r){return c!==r},Gywnj:"QnJFi",NTMPv:t(483),ynIrU:function(c,r){return c===r},ctbXz:function(c,r){return c+r},UtJuH:function(c,r){return c>=r},prjod:function(c,r){return c+r},XqJLD:function(c,r){return c>r},xPHNy:function(c,r){return c>r},IHCix:t(1516)+t(691),ryeei:function(c,r){return c+r},CVlas:function(c,r){return c(r)},kkhrJ:function(c,r){return c(r)},ztxST:t(1224)+t(566)+"t",dOxWk:t(1654),UdHpP:function(c,r){return c||r},GyPSv:"jpAmI",kgstQ:function(c,r){return c<r},IRavd:function(c,r){return c+r},aoXKK:function(c,r){return c&r},aYfAq:function(c,r){return c>=r},kBHjT:function(c,r){return c+r},RYimp:function(c,r){return c===r},LGsPU:"LWSvL",mWyvL:t(1109),SrWUL:function(c,r){return c+r},HdgHg:t(1065),fNLeN:function(c,r){return c|r},htNkM:function(c,r){return c<<r},GnpKP:function(c,r){return c&r},RtlHU:function(c,r){return c<r},WlMRY:function(c,r){return c==r},ePMUj:function(c,r){return c&r},NTwsj:function(c,r){return c+r},rOoDK:function(c,r){return c+r},Suerp:function(c,r){return c+r},PoxBw:function(c,r){return c!==r},YfPoL:function(c,r){return c|r},WlCUk:function(c,r){return c<<r},pPDgW:function(c,r){return c&r},jOtXn:function(c,r){return c<<r},KwjRW:function(c,r){return c>=r},vAHbH:function(c,r){return c<=r},qTWky:function(c,r){return c>=r},KfZxP:function(c,r){return c+r},zfznV:function(c,r){return c+r},Aeoko:function(c,r){return c+r},wcXbP:function(c,r){return c+r},DROrB:function(c,r){return c|r},aIHYV:function(c,r){return c<<r},ZxXeb:function(c,r){return c&r},ErmKT:function(c,r){return c&r},IYsFR:function(c,r){return c<r},GKxJi:function(c,r){return c<r},xwbZE:function(c,r){return c+r},qFOxa:function(c,r){return c-r},OXUkK:function(c,r){return c+r},EWyRA:function(c,r){return c<r},JneFu:function(c,r,o){return c(r,o)},ZfCEg:function(c,r){return c<r},QKGMH:function(c,r){return c>=r},fmJHG:function(c,r){return c<=r},HDCTE:function(c,r){return c<r},BliIO:function(c,r){return c+r},WSMaX:function(c,r){return c-r},sqPkA:function(c,r){return c<<r},YtZmT:function(c,r){return c<r},tSlUX:function(c,r){return c&r},xiceS:function(c,r){return c>>r},EFqkt:function(c,r){return c>>r},ZzIzq:function(c,r){return c|r},VvYIj:function(c,r){return c&r},OqjdN:function(c,r){return c>>r},gXXWx:function(c,r){return c|r},zzKMr:function(c,r){return c&r},UGCMb:function(c,r){return c>>r},caKhR:function(c,r){return c|r},onDyV:function(c,r,o){return c(r,o)},gjhUi:function(c,r){return c+r},bMcjV:function(c,r){return c<r},BaTYM:function(c,r,o){return c(r,o)},UjKOU:function(c,r){return c(r)},mwHme:function(c,r){return c&r},AcwWL:function(c,r){return c(r)},JzafR:function(c,r){return c&r},Xtibz:function(c,r){return c&r},NYgeO:function(c,r){return c&r},YezAn:function(c,r){return c&r},Lvxcu:function(c,r){return c<<r},dfoeW:function(c,r){return c<<r},NrTip:function(c,r){return c&r},aAltn:function(c,r){return c&r},NYTmo:t(599),JzcKr:function(c,r){return c<<r},oBQtm:t(981),cJpUl:t(729),wRtAx:function(c,r){return c===r},RSqQm:t(926),waItL:function(c,r){return c>>>r},hSNnf:function(c,r){return c>>>r},NmBxx:function(c,r){return c>>>r},GaqHq:function(c,r){return c>>>r},Nabpt:function(c,r){return c===r},HHhlM:function(c,r){return c<r},hOvvj:function(c,r){return c<r},Qffnm:function(c,r,o){return c(r,o)},ALkeK:function(c,r){return c&r},EdNPA:function(c,r){return c+r},AvwlR:function(c,r){return c&r},Afcwl:function(c,r){return c+r},nqNEU:function(c,r){return c!==r},HniFo:function(c,r){return c|r},irsbK:function(c,r){return c!==r},thpMT:function(c,r){return c&r},nANOa:function(c,r){return c>>>r},LtKnG:function(c,r){return c+r},bInuk:function(c,r){return c!==r},IlCQM:function(c,r){return c!==r},pKeVs:function(c,r){return c>>>r},GRnQF:function(c,r){return c&r},uzQPD:function(c,r){return c|r},MtgpR:function(c,r){return c>>>r},GTRLe:function(c,r){return c&r},bplUT:function(c,r){return c>>>r},LLNAp:function(c,r){return c!==r},rJRXF:function(c,r,o){return c(r,o)},YYhzg:t(990),Dualb:function(c,r){return c|r},GYCuB:function(c,r){return c|r},IZKwW:function(c,r){return c<<r},EEWZC:function(c,r){return c<<r},wWCmN:function(c,r){return c<<r},PzLGP:function(c,r){return c<<r},SJZbQ:function(c,r){return c<<r},FSIPE:function(c,r){return c|r},iSMZh:function(c,r){return c<<r},Asavl:function(c,r){return c===r},JxqWT:function(c,r){return c<<r},zDfxQ:function(c,r){return c<<r},rGmpK:function(c,r){return c|r},MkrDm:function(c,r){return c|r},KPlJo:function(c,r){return c<<r},aJryv:function(c,r){return c<<r},umIkc:function(c,r){return c&r},cDgDL:function(c,r){return c>>>r},kRjwp:function(c,r){return c&r},XiutW:function(c,r){return c(r)},cHOBY:function(c,r){return c|r},ivtgf:function(c,r){return c/r},JeSiu:function(c,r){return c*r},OMTPA:function(c,r){return c>>>r},oJrwh:function(c,r){return c>>>r},MaDTU:function(c,r){return c&r},swJve:function(c,r){return c>>>r},kQuoN:function(c,r){return c&r},tLWNq:function(c,r){return c&r},AIgRs:function(c,r){return c>>>r},kDMjH:function(c,r){return c+r},mHuvD:function(c,r){return c+r},QBPxt:function(c,r){return c===r},ZscPS:function(c,r){return c===r},NAPgr:function(c,r){return c>>>r},cMkSF:function(c,r){return c===r},lOKUS:function(c,r){return c===r},iKUPG:function(c,r){return c&r},vegXv:function(c,r){return c>>>r},Oxkqx:function(c,r){return c>>>r},LIwzp:function(c,r){return c&r},XhNLs:function(c,r){return c>>>r},lqwQP:function(c,r){return c>>>r},weJAU:function(c,r){return c>>>r},SBPlo:function(c,r){return c&r},Itnsk:function(c,r){return c>>>r},XiQiw:function(c,r){return c&r},tqnwW:"3|1|5|2|0|4",CkDiQ:t(1354)+"OR",TtOUF:t(625)+t(297),RMPtE:t(200)+t(939),UekUp:t(1503)+t(1510)+"R",XZJtv:t(570),YVsjD:function(c,r){return c(r)},IxzCx:function(c,r,o,d){return c(r,o,d)},AZSEE:function(c,r){return c!==r},AtDLB:"PLEMk",fdyyV:function(c,r,o){return c(r,o)},ykLvQ:t(1569),kpMGI:t(298),lSQls:t(1099),ATEgL:t(379)+"ys",RIiVN:"count",FfVLS:t(720),pysOr:"delete",ejUVt:"clear",zMecf:function(c,r){return c(r)},WzOuy:t(862),xuttx:function(c,r){return c===r},qahXT:function(c,r){return c==r},UvABO:t(1114),aIxCp:function(c,r){return c(r)},Yydny:t(1609),zTayO:function(c,r){return c===r},KmdFK:function(c,r){return c+r},vemeg:function(c,r){return c===r},sNPkg:function(c,r){return c===r},fcoAg:function(c,r){return c!==r},ZlahX:t(1570),aEIbi:function(c,r){return c instanceof r},kMcma:t(785),Wluvo:t(1528),GPvbY:function(c,r,o){return c(r,o)},nEpqT:t(1157),nEcvL:function(c,r,o){return c(r,o)},cxhpW:t(1363),ExeVM:function(c,r){return c instanceof r},COWwM:function(c,r){return c+r},cwTZW:t(1358),KespE:t(193),PiBTz:function(c,r){return c!==r},adSUD:t(1540),kMJRE:function(c,r){return c||r},ssjWF:function(c,r){return c<=r},zmjol:"next() c"+t(1103)+t(1361)+t(463)+t(220),EWPeU:"HIrGC",WbKBe:function(c,r){return c===r},LSlkR:"Fekea",LnBAq:function(c,r){return c<r},TcKLc:function(c,r){return c===r},xUlMC:function(c,r){return c&r},mVyeM:function(c,r){return c+r},Vkezn:function(c,r){return c-r},vrdsT:function(c,r){return c>=r},KzDlJ:function(c,r){return c|r},vYdhr:function(c,r){return c<<r},cDNsW:function(c,r){return c&r},HbGda:function(c,r){return c|r},eXBGf:function(c,r){return c&r},lSWOq:function(c,r){return c>=r},gGNtP:function(c,r){return c|r},dPapa:function(c,r){return c&r},IWDug:function(c,r){return c<<r},jSeLo:function(c,r){return c&r},UzfhQ:function(c,r){return c+r},nXQNF:function(c,r){return c+r},eaKfV:function(c,r){return c<r},TQUoV:function(c,r){return c|r},mPrDt:function(c,r){return c>>r},qrGKd:function(c,r){return c|r},plCYh:function(c,r){return c&r},LBLzT:function(c,r){return c+r},yHxVw:t(201)+"0|2",tYFZb:function(c,r){return c|r},ZYgMV:function(c,r){return c|r},bakjU:function(c,r){return c<<r},lcrnA:function(c,r){return c&r},cTDUt:function(c,r){return c|r},lEIdX:function(c,r){return c&r},jELzZ:function(c,r){return c-r},sFxlf:function(c,r){return c!==r},XFYyp:"online",wKoCe:"offline",idsFz:"DbLlO",yIfwF:"IzRqi",WCmCO:function(c,r){return c instanceof r},HQbaF:function(c,r){return c!=r},vfFYE:"applicat"+t(1676),GfZrg:function(c,r){return c==r},QKyUH:"text/pla"+t(161)+t(1078),KRvtn:function(c,r,o){return c(r,o)},xKhIS:function(c,r){return c!==r},OeCyb:t(1478),Lfcun:function(c,r){return c>=r},dtIRM:t(1008)+"reason",jtiDc:t(1618),riihr:t(222)+t(1648)+t(1230)+"P",KjMpE:t(174),uhbpj:function(c){return c()},viuVR:"dMTyg",moWpd:t(453),VpOFt:t(1004),qAbqH:"pagehide",SIwsO:t(180),BDGId:function(c,r){return c!==r},GICHl:t(1322),WyJRo:t(799),PJBWg:function(c,r){return c!==r},dEfWI:t(455),FpeWC:function(c,r){return c===r},EttVM:function(c,r){return c===r},SBYxp:function(c,r){return c===r},cKWGU:t(908),IRcrg:function(c,r){return c(r)},Gillp:t(920),yKyFB:"fHrKd",PwvXZ:function(c,r){return c||r},fJcXj:function(c,r){return c||r},CzXtz:function(c,r){return c||r},baWdZ:function(c,r){return c||r},pfWcF:t(1009)+t(1639)+"d",XfDKy:t(913),BcBnl:function(c,r){return c===r},vCEZX:t(592),QMUEo:function(c,r){return c(r)},IxuVQ:function(c,r,o,d){return c(r,o,d)},lvNsl:function(c,r){return c+r},kPpvh:t(531),VJYYF:function(c,r){return c<<r},dbzpT:function(c,r){return c>>>r},EQQsc:function(c,r){return c>r},vwtGb:function(c,r){return c<r},sQOMQ:function(c,r){return c<r},DuuIU:function(c,r){return c!==r},hksfi:"bMDZn",TuYZG:t(978),POAlF:function(c,r){return c===r},qjixu:t(1011),OeHwb:t(694)+t(907),rDJBQ:function(c,r,o,d){return c(r,o,d)},pIqjg:t(694)+t(1616)+"ck",gjDda:t(694)+"er_is_ack",HncTM:function(c,r,o){return c(r,o)},FQTSe:function(c,r){return c&r},NTyTJ:t(1443),whgrb:"xZJZr",Duhye:t(1203),FmOQa:t(1312),BRbWT:function(c){return c()},EfFra:function(c,r){return c(r)},ywwVu:function(c,r){return c instanceof r},KakJp:function(c,r){return c instanceof r},nMfIU:t(1621)+t(1676)+t(319)+t(1564),FowBS:"none_none",LGVik:"binary",jLZyc:function(c){return c()},Mypyc:function(c,r){return c+r},UQmPq:function(c,r){return c|r},nLvaZ:t(818),dxohX:function(c,r,o){return c(r,o)},YkuAp:t(894)+"ay, netw"+t(371)+t(945),sdiZm:t(1357),FGnOD:function(c,r){return c+r},GxCOS:"index ou"+t(412)+"ge: ",SBrlM:t(886),NVKuu:function(c,r){return c||r},MEVwf:" > ",yVSxo:function(c,r){return c>r},Gmcvr:t(363)+"too large",AskoG:function(c,r){return c+r},QVjOQ:function(c,r,o){return c(r,o)},ZiTWZ:function(c,r){return c<<r},GoGqN:"3|0|2|1|4",RJxoK:function(c,r){return c<r},zjAld:function(c,r){return c+r},DvawA:function(c,r){return c+r},cUDPx:function(c,r){return c+r},hzrtP:function(c,r){return c|r},hzZHx:function(c,r){return c+r},cumAa:function(c,r){return c+r},sLagm:function(c,r){return c+r},UZSPU:function(c,r){return c|r},JMESS:function(c,r){return c|r},egPOn:function(c,r){return c<<r},kwZUz:function(c,r){return c<<r},uEGkQ:function(c,r){return c+r},wNcGW:t(949),BFVsc:function(c,r){return c+r},rkpqA:function(c,r){return c>>>r},qqDOM:function(c,r){return c+r},igiFz:function(c,r){return c+r},HfbJk:function(c,r){return c&r},CbLAL:function(c,r){return c+r},EPSwo:function(c,r){return c&r},CKuvW:function(c,r){return c>>>r},AlyFz:function(c,r){return c+r},PVqyI:function(c,r){return c+r},gIpOL:"wOoSm",NiEBp:t(1626),YvpRC:"KeBWw",dvRsj:t(623)+"|3|8|0|4"+t(1258)+"5",kjfOC:function(c,r){return c>>>r},Hihvh:function(c,r){return c|r},ISzGL:function(c,r){return c&r},OWoTL:function(c,r){return c<r},CBDMa:function(c,r){return c&r},hYjOy:function(c,r){return c<r},YReus:function(c,r){return c|r},TLLLY:function(c,r){return c|r},HYtyD:function(c,r){return c|r},LEkrW:function(c,r){return c<<r},KNSEl:function(c,r){return c<r},GQaoG:function(c,r){return c+r},cpMSy:t(1422)+t(882),lTopw:function(c,r,o,d){return c(r,o,d)},PwYHI:t(216),FpgAI:t(505),KbckZ:t(1513),fdDny:function(c,r){return c(r)},NkVGa:t(965)+t(1408),ssCxW:function(c,r){return c<r},HvWib:function(c,r){return c===r},khAWn:function(c,r,o){return c(r,o)},NGeqr:function(c,r,o){return c(r,o)},tnbWs:t(1419)+t(332),lkGBf:function(c,r,o){return c(r,o)},kFokH:t(468)+t(306),SCsQF:function(c,r,o){return c(r,o)},jwKMm:"jKFZv",fzRoi:"allCurso"+t(789),ajprW:function(c,r,o,d){return c(r,o,d)},etYvQ:t(1678),KlQJQ:t(1207),SCEeN:function(c,r,o,d){return c(r,o,d)},IkfZh:function(c){return c()},yzyOB:"setcursor",eTRwf:function(c,r){return c===r},UbYRP:t(702),TXlst:t(1388),MfytI:"x_fronti"+t(1015),tZIMv:t(694)+t(254),LCdZC:t(494)+"s",jmhmO:t(1574)+t(1037)+"e",UIeVy:"x-msg-cu"+t(1285)+"ue",qlaDU:"lWOXP",VInoc:t(231),eTHUb:function(c,r){return c<r},spdSG:function(c,r){return c===r},qTGNZ:"oLntS",RJAGR:function(c){return c()},lWbsS:function(c){return c()},aufvu:function(c,r){return c||r},YmBlq:function(c,r){return c<<r},ERFfd:function(c,r){return c&r},LKhsM:t(479),xPmxh:function(c,r){return c===r},LRRke:function(c,r,o){return c(r,o)},sbcOP:function(c,r){return c!==r},liEre:t(692),lMBGG:t(1066),LGlFV:function(c,r){return c===r},oyOTA:t(1441),CQWQq:function(c,r){return c!==r},WeckI:function(c,r){return c<r},uOvGJ:function(c){return c()},mkDiQ:function(c,r,o,d){return c(r,o,d)},snFxB:function(c,r,o){return c(r,o)},LrbIz:"bxZal",FcXTt:t(556),GGnVD:t(227),rcWhA:t(744),nzjCW:t(1224)+t(1491)+"s",khKwj:t(527),wLXyA:function(c,r,o){return c(r,o)},DXPuE:t(647),hVDDn:function(c,r){return c===r},JGbiM:t(1254),iLzJj:t(1112),DIjOj:function(c,r){return c!==r},nDNsw:function(c,r){return c(r)},ikShv:t(1573),OgtsV:function(c,r,o){return c(r,o)},TzeAG:t(1093),MAEUC:function(c,r){return c===r},mZtVr:function(c,r){return c(r)},kBeqt:function(c,r,o){return c(r,o)},zwQIK:"reconnect",ebLhW:t(578),PTVyc:function(c,r){return c===r},CBgan:"XDBCg",UkiPo:"sOSig",giArJ:function(c,r){return c===r},wAGyY:t(1201),EVXCn:function(c,r){return c==r},gsVPY:t(971),BuepX:function(c,r){return c!==r},ocAxd:"LcnvE",dcROK:t(1518),JNjoG:t(1188)+"d",RoRuj:function(c,r){return c||r},UBLmD:t(1166)+"rovide b"+t(1219)+t(1086)+t(1567),spGCt:t(1083),JtlJc:function(c,r,o){return c(r,o)},PAjiw:t(179),iyrOq:t(301),xKVSh:function(c,r){return c>r},MtVqy:function(c,r){return c-r},lZlPG:function(c,r){return c!=r},IfivO:function(c,r){return c instanceof r},dDNui:t(270),zvgFo:t(838),NiXiA:function(c,r){return c(r)},rnwKB:t(1177),PGNKS:t(812),ouSNL:t(248)+">",yyHcZ:function(c,r){return c*r},ZDQAL:function(c,r){return c>r},EANWn:function(c,r,o){return c(r,o)},Uvfnb:t(1290),aZDOo:"manual r"+t(1150)+t(543),Wpmxj:"SnBzj",grZkE:t(894)+"ay, try "+t(883)+t(1638)+t(1611),Oeuin:function(c,r){return c<<r},VLzHx:function(c,r,o){return c(r,o)},OvLRN:function(c,r){return c&r},puHSC:t(1562),UbXbS:t(660),EyUCE:t(1612)+" try reconnecting",WXuUY:t(251),zzseR:t(791)+"3",mAbLC:function(c,r){return c>r},rhynO:function(c,r){return c(r)},srRBv:function(c,r){return c||r},KbgjM:"YopAU",ubXRO:t(722),grzyH:function(c,r){return c+r},dBzoX:t(273),dypfV:t(263),xmagb:function(c,r,o){return c(r,o)},oHBXD:t(603),wQQhm:function(c,r){return c!==r},UBTNS:t(1341),yUGwX:function(c,r){return c+r},upkHr:function(c,r,o){return c(r,o)},Cigkb:function(c,r){return c!==r},PZyLH:t(870),dsRJP:function(c,r){return c-r},pehLe:"eXoUS",jsHXt:function(c,r,o){return c(r,o)},IFlHs:t(1058),xTGSG:t(954)+t(874)+t(865)+t(181)+"ed",PVJeO:"close, ws alread"+t(1268),FZVJi:t(731),LuEmj:t(1166)+t(436)+" valid d"+t(545)+t(1593)+t(365)+t(1289)+t(802)+t(290),ZMveI:function(c,r){return c==r},tRGDo:function(c,r){return c instanceof r},KKiQt:function(c,r){return c(r)},yoLsk:function(c,r){return c(r)},immmr:function(c,r){return c||r},OnGwR:function(c,r){return c===r},wFAgW:t(1107),rddSZ:function(c,r){return c<r},fQrrJ:t(243),vhBth:function(c,r){return c!==r},SXnjz:function(c,r){return c!==r},jtUSV:"yiqwh",zwYBs:t(586)+"1",CzlwS:function(c,r){return c!==r},LRRmH:t(1426),HUbDY:function(c,r,o){return c(r,o)},ntzmW:t(686),fjwFs:function(c,r){return c!=r},obSCe:function(c,r){return c===r},nrCQR:t(1424),Bwhxu:function(c,r){return c!=r},obRmC:function(c,r){return c!=r},bzaAF:t(1362),tohjz:t(1117)+t(765)+t(1446)+"pe",hGkNE:function(c,r){return c!=r},Fvfkb:function(c,r){return c===r},twKQt:function(c,r){return c===r},AKPFH:t(246)+t(1257)+"alScope",hPaGQ:function(c,r){return c===r},sSWnE:t(392)+t(1162)+t(346),TDdfj:function(c,r){return c!=r},yiMCL:function(c,r){return c!=r},SbDbR:function(c,r){return c!=r},rLQbv:t(683)+"qos__"};Kt.r(Oe),Kt.d(Oe,{FWS:()=>Qw,CustomErrorEvent:()=>Zd,createCloseEvent:()=>It,ReconnectEvent:()=>Vd,createErrorEvent:()=>pt,decodedFrame:()=>un,createOpenEvent:()=>tu,CustomCloseEvent:()=>Jd,createReconnectEvent:()=>Ga,FrontierMessageEvent:()=>Xd,encodeFrame:()=>Jt,createMessageEvent:()=>eu,OpenEvent:()=>Qd,ErrorCode:()=>hn,Event:()=>fr,MessageEvent:()=>Yd});let n="";function i(c=""){let r=t,o="02",d=""+Date.now(),h=n||(n=e[r(391)](f,c)),p=Math[r(863)]()[r(637)](16)[r(1423)](-6);return e[r(238)](e[r(238)](e[r(238)](o,d),h),p)}function s(){let c=t;return e[c(940)](e[c(389)](1e4,Date[c(1566)]()),Math[c(778)](e[c(1349)](1e4,Math[c(863)]())))}function a(c){let r=t;return e[r(238)](Array(8)[r(182)]("0"),e.DJWFn(parseInt,c,10)[r(637)](2))[r(1423)](-8)}function l(c){let r=t;return e[r(825)](e[r(803)](Array,4)[r(182)]("0"),e[r(256)](parseInt,c,2)[r(637)](16))[r(1423)](-4)}function u(c){let r=t,o=c[r(1317)](/\./)[r(464)](p=>a(p)),d=[];return d[0]=e[r(803)](l,e[r(940)](o[0],o[1])),d[1]=e[r(391)](l,e.LQhKS(o[2],o[3])),[e[r(1474)],e[r(1474)],r(1588),e[r(1474)],e[r(1474)],e[r(912)],d[0],d[1]][r(182)]("")}function f(c){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(1069)](c),d=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(1069)](c);return o?e[r(1403)](u,c):d?e.Aeoan(x,c):e[r(373)]}function x(c){let r=t,o={nxYvF:e[r(1679)]};if(e[r(1287)](r(1658),e[r(1002)])){let d="",h=[],p=0,y=0,S=!0,_=e.JFcwH;if(e[r(215)](c[r(1635)]("::"),-1)){let D=c[r(1317)]("::");for(let F=0;e[r(1269)](F,D[r(1535)]);F++)if(e[r(1173)](e[r(431)],e[r(431)])){let J=D[F];if(J[r(1635)](":")>0){let re=J[r(1317)](":");S&&(p=re[r(1535)]),y+=re[r(1535)];for(let Y=0;e.xjvXc(Y,re[r(1535)]);Y++)if(re[Y].length!==4){let gt=_[r(372)+"g"](0,e[r(442)](4,re[Y][r(1535)])),dt=gt.concat(re[Y]);h.push(dt)}else h.push(re[Y]);S=!1}else{if(e[r(1287)](4,J.length)){if(e.qZztw!==e.qZztw)return this._qosDB?.[r(775)](_0x5d357c);{let re=_[r(372)+"g"](0,e[r(1236)](4,J[r(1535)])),Y=re.concat(J);h[r(345)](Y)}}else h[r(345)](J);S&&(p+=1),y+=1,S=!1}}else _0x58babe=e[r(1034)](_0x3c3750,_0x18fb60),_0x14cff8|=e[r(1624)](e[r(784)](127,_0x57a1f2),21),128&_0x3ab5e6&&(_0x516379=e[r(1492)](_0x59c768,_0x4f82d5),_0x43cb02=e[r(784)](127,_0x39681a),128&_0x2e7871&&(_0x29dd42=e[r(1403)](_0x69bfb3,_0x5003ef),_0x31a66f|=e.KHTre(127,_0x26cabf)<<7));let O="";for(let F=0;e[r(441)](F,8-y);F++)O=O[r(1660)](_);for(let F=0;e[r(1269)](F,h[r(1535)]);F++)F===p&&(d=d[r(1660)](O)),d=d[r(1660)](h[F]);return d}{let D=c.split(":");for(let O=0;e.hDifG(O,D[r(1535)]);O++)if(e.fQuUy===e[r(887)]){let F=D[O];if(e[r(344)](4,D[O][r(1535)]))if(r(811)!=="WvpBV")_0x54c656(_0x1038be,10),e[r(1364)](_0x43fae5,_0x3398fe,_0x167ab9);else{let J=_[r(372)+"g"](0,e.vjKnM(4,D[O].length)),re=J[r(1660)](F);d=d.concat(re)}else d=d[r(1660)](F)}else this[r(461)](o[r(1356)],_0x5c997a),this[r(320)]&&this.onerror(_0x429d45);return d}}else _0x154bc2[_0x12e24e[_0x558cfc][r(468)+"ame"]]=e[r(391)](_0x22a1f1,_0x17914d[_0x9171b4][r(468)+r(306)]),_0x2c0a5c+=e[r(1116)](14,_0x48c250[_0x33c66f[_0x46b2c8][r(468)+r(306)]])}function m(c,r){let o=t,d=c[o(1163)];e[o(344)](void 0,d)&&(e[o(168)](we,r,10),e.fpDSs(G,r,d));let h=c[o(1172)];e[o(1287)](void 0,h)&&(e[o(1668)](we,r,18),e.GRNTZ(G,r,h))}function g(c){let r=t,o={YQith:function(h,p){return e.DacMA(h,p)}},d={};e:for(;!e[r(1492)](Z,c);){if(e[r(1287)](e.TtNUQ,e[r(995)]))return _0x1007c9[r(1102)+"8"]?{value:_0x52f326[r(1102)+"8"](_0x3c582f),offset:o.YQith(_0x354f34,1)}:{value:255&_0x1c377e[_0x3f8c82],offset:_0x20a2e4+1};{let h=e.ZFKkz(me,c);switch(e[r(1511)](h,3)){case 0:break e;case 1:d.key=e.KGTqO(C,c,me(c));break;case 2:d.value=e[r(837)](C,c,e.Aeoan(me,c));break;default:e[r(1223)](R,c,e.KHTre(7,h))}}}if(e[r(267)](void 0,d[r(1163)]))throw new Error(e[r(950)]);if(d.value===void 0)throw new Error(e[r(1667)]);return d}function v(c){let r=t,o=e[r(214)](k);return e.DJWFn(w,c,o),e.Aeoan(M,o)}function w(c,r){let o=t,d=c.SeqID;d!==void 0&&(e[o(513)](we,r,8),e.PXXjB(St,r,d));let h=c[o(1171)];e[o(344)](void 0,h)&&(e[o(168)](we,r,16),e[o(1668)](St,r,h));let p=c.service;e[o(462)](void 0,p)&&(e[o(513)](we,r,24),St(r,e[o(1403)](P,p)));let y=c.method;e[o(555)](void 0,y)&&(e.GRNTZ(we,r,32),St(r,e[o(735)](P,y)));let S=c[o(295)];if(e[o(555)](void 0,S))for(let gt of S){e[o(837)](we,r,42);let dt=e.IWLFv(k);e.zEAVQ(m,gt,dt),e[o(256)](we,r,dt[o(184)]),e[o(237)](W,r,dt),e[o(236)](L,dt)}let _=c[o(888)+o(918)];if(e.pOjGa(void 0,_))if(e[o(555)](o(860),e[o(183)]))we(r,50),e[o(973)](G,r,_);else{let gt=_0x5e5d99(e.BWeHU,{message:_0x55ecad[o(1363)],code:_0x2e1b45[o(1354)+"OR"],error:_0x55f2f2});this[o(942)+"hErrorEv"+o(1418)](gt)}let D=c[o(1546)+"ype"];e.vMXul(void 0,D)&&(e[o(228)](we,r,58),e[o(168)](G,r,D));let O=c[o(1335)];if(e.pcSrh(void 0,O))if(e[o(1024)](e[o(553)],e[o(553)]))we(r,66),we(r,O[o(1535)]),e.RjcYd(de,r,O);else{let gt=o(891)+_0x3724ac+(o(534)+o(1226)+o(348)+"ed");this["_dispatc"+o(266)+o(1418)](e[o(837)](_0x2cc5ff,o(369),{message:gt,code:_0x5c33b5[o(1503)+o(1510)+"R"],error:_0x455422}));return}let F=c[o(773)];e[o(462)](void 0,F)&&(e[o(1668)](we,r,74),e[o(1668)](G,r,F));let J=c[o(397)+"ming"];e.pOjGa(void 0,J)&&(e.wVurE(we,r,82),e[o(890)](G,r,J));let re=c[o(473)];e[o(344)](void 0,re)&&(e[o(228)](we,r,90),e[o(1282)](G,r,re));let Y=c.frameType;if(Y!==void 0)if(e.huVCf===e[o(488)]){if(xHgYwR[o(1607)](_0x3398da,_0x59cdd6)){if(xHgYwR[o(1024)](_0x85146e,xHgYwR[o(422)]))return _0x48a23c[o(298)](_0x9e02e7);if(xHgYwR.ldWwv(_0x1c2622,xHgYwR[o(244)]))return _0x478a65[o(1146)+"oreNames"]||_0x33ac22.get(_0x500a9b);if(xHgYwR.ldWwv(_0x2fbeb0,xHgYwR[o(624)]))return _0xb9a309["objectSt"+o(1068)][1]?void 0:_0x1cee91[o(1146)+o(841)](_0x1e839e["objectSt"+o(1068)][0])}return _0x16356f(_0x1ded14[_0x17de7d])}else e[o(1245)](we,r,96),e[o(1223)](St,r,e[o(1403)](P,Y))}function b(c){let r=t;return e[r(403)](I,e[r(391)](B,c))}function I(c){let r=t,o={};e:for(;!Z(c);){let d=e[r(1403)](me,c);switch(e[r(1511)](d,3)){case 0:break e;case 1:o[r(279)]=e[r(1368)](Ot,c,!0);break;case 2:o[r(1171)]=e[r(237)](Ot,c,!0);break;case 3:o.service=e[r(803)](me,c);break;case 4:o[r(1372)]=e[r(403)](me,c);break;case 5:{let h=e[r(803)](A,c);(o[r(295)]||(o.headers=[]))[r(345)](e.BiAWl(g,c)),c[r(184)]=h;break}case 6:o[r(888)+r(918)]=e.xtSKe(C,c,e[r(803)](me,c));break;case 7:o[r(1546)+r(1663)]=e.pmzgS(C,c,e[r(1089)](me,c));break;case 8:o[r(1335)]=e[r(948)](le,c,e[r(395)](me,c));break;case 9:o[r(773)]=e[r(790)](C,c,e[r(391)](me,c));break;case 10:o["serverTi"+r(1460)]=e.LbHkV(C,c,me(c));break;case 11:o[r(473)]=C(c,me(c));break;case 12:o.frameType=e[r(236)](me,c);break;default:e.pthoA(R,c,e.KHTre(7,d))}}if(e.dIngY(void 0,o[r(279)]))throw new Error(r(428)+r(1505)+" field: SeqID");if(e[r(1398)](void 0,o[r(1171)]))throw new Error(e[r(1589)]);if(e[r(565)](void 0,o[r(1333)]))throw new Error(r(428)+r(1505)+" field: "+r(1333));if(e.VbIBr(void 0,o[r(1372)]))throw new Error(e[r(1181)]);return o}function A(c){let r=t,o=e.YCCOv(me,c),d=c[r(184)];return c[r(184)]=e[r(1222)](c.offset,o),d}function R(c,r){let o=t,d={sSVip:function(h,p){return e[V(1664)](h,p)},TgqIx:function(h,p){return e.vzWKX(h,p)}};if(o(658)!==e[o(777)])switch(r){case 0:for(;e.KHTre(128,e[o(1048)](se,c)););break;case 2:e.nlFaO(X,c,me(c));break;case 5:e[o(973)](X,c,4);break;case 1:X(c,8);break;default:throw new Error(e[o(825)](e.pIDIr,r))}else{let h=this[o(580)+"rs"][_0x77a9c1];if(h)for(let p=0;d[o(933)](p,h[o(1535)]);)d.TgqIx(h[p].fn,_0x41ea15)?h[o(339)](p,1):++p}}function P(c){let r=t;if(e.vDJhF(e[r(823)],e.KuVuv)){if(_0x14489e)return new _0x1c0346(_0x2b6790[r(798)],_0x3ee065[r(710)]);if(_0x5d8a32||_0x4a9198)return new _0x232b39(_0x9d82d2[r(798)],_0x593291.protocol,_0x332bc0[r(295)]);if(e[r(1417)](_0x3e3db3,_0x8292f4)&&e[r(1303)](e.yRETB,typeof _0x29ed50)&&_0x3d71a7)return new _0x3b9e63(_0x419310[r(798)],_0x47ed51[r(710)+"s"])}else return c|=0,{low:c,high:c>>31,unsigned:c>=0}}let E=[];function k(){let c=t,r=E[c(1572)]();return r?(r.offset=r.limit=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function L(c){E[t(345)](c)}function B(c){return{bytes:c,offset:0,limit:c[t(1535)]}}function M(c){let r=t;if(e[r(1091)](e[r(1545)],e[r(636)])){let o=c[r(582)],d=c[r(184)];return e[r(1313)](o[r(1535)],d)?o:o[r(800)](0,d)}else return _0x1213a2}function X(c,r){let o=t;if(e[o(230)](c[o(782)],r)>c.limit)throw new Error(o(1199)+"t limit");c[o(782)]+=r}function Z(c){let r=t;return e[r(537)](c[r(782)],c[r(184)])}function ae(c,r){let o=t,d=c[o(582)],h=c[o(782)],p=c[o(184)],y=e[o(563)](h,r);if(y>d[o(1535)]){let S=new Uint8Array(e[o(1349)](2,y));S.set(d),c[o(582)]=S}return c[o(782)]=y,e[o(482)](y,p)&&(c.limit=y),h}function te(c,r){let o=t,d=c.offset;if(e[o(259)](e[o(1116)](d,r),c[o(184)]))throw new Error(e[o(1261)]);return c[o(782)]+=r,d}function le(c,r){let o=t,d=e[o(168)](te,c,r);return c[o(582)][o(800)](d,e[o(1447)](d,r))}function de(c,r){let o=t,d=ae(c,r[o(1535)]);c[o(582)].set(r,d)}function C(c,r){let o=t,d={OwrKr:function(h,p){return e.UdHpP(h,p)}};if(e.GyPSv!==e.GyPSv){let h=this[o(958)].getItem(this[o(489)]),p=_0xcf4901.parse(d[o(530)](h,"{}"));return p[_0x48dc5d||_0x196d37[this._pathKey]]=_0x40dabc,this._qosDB[o(1615)](this[o(489)],_0x2ef6ea[o(425)+"y"](p)),_0x34d55c||_0xf80acc[this[o(568)]]}else{let h=te(c,r),p=String[o(171)+o(338)],y=c[o(582)],S="\uFFFD",_="";for(let D=0;e[o(749)](D,r);D++){let O=y[e.IRavd(D,h)],F,J,re,Y;if(e[o(1005)](e[o(784)](128,O),0))_+=e[o(1492)](p,O);else if(e[o(1094)](224,O)===192)if(e[o(1233)](e[o(986)](D,1),r))_+=S;else{if(e[o(1627)](e[o(1420)],e[o(414)]))return e[o(754)](_0x4f21cd,e.kkhrJ(_0x3d489d,_0x29f147));F=y[e[o(825)](e[o(478)](D,h),1)],e.vMXul(e.KHTre(192,F),128)?_+=S:e[o(520)]===e.HdgHg?(Y=e[o(921)](e[o(1666)](e[o(1094)](31,O),6),e[o(679)](63,F)),e[o(564)](Y,128)?_+=S:(_+=e[o(1089)](p,Y),D++)):(this["_pingLos"+o(333)]?.[o(1360)](),this.emit(e[o(1387)],e[o(969)]),this._pingLossCounter?.[o(708)+o(1235)+"nt"]()?this[o(1061)+"econnect"]():this._ping())}else e[o(1063)](e[o(998)](240,O),224)?e.NTwsj(D,2)>=r?_+=S:(F=y[e[o(478)](e[o(1472)](D,h),1)],J=y[e[o(986)](e[o(1482)](D,h),2)],e[o(1533)](e[o(679)](e[o(848)](F,e[o(424)](J,8)),49344),32896)?_+=S:(Y=e[o(921)](e[o(921)](e[o(481)](15,O)<<12,e[o(495)](63&F,6)),63&J),e[o(441)](Y,2048)||e.KwjRW(Y,55296)&&e[o(952)](Y,57343)?_+=S:(_+=e[o(1403)](p,Y),D+=2))):e[o(1063)](e.aoXKK(248,O),240)?e[o(721)](e[o(563)](D,3),r)?_+=S:(F=y[e[o(1578)](e[o(936)](D,h),1)],J=y[e[o(487)](e[o(649)](D,h),2)],re=y[D+h+3],e[o(1287)](e[o(921)](F|J<<8,re<<16)&12632256,8421504)?_+=S:(Y=e[o(1390)](e[o(848)](e[o(784)](7,O)<<18|e[o(424)](63&F,12),e[o(1168)](e.ZxXeb(63,J),6)),e[o(685)](63,re)),Y<65536||Y>1114111?_+=S:(Y-=65536,_+=e[o(1668)](p,e[o(677)](Y>>10,55296),e.ctbXz(1023&Y,56320)),D+=3))):_+=S}return _}}function G(c,r){let o=t,d=r[o(1535)],h=0;for(let S=0;e[o(873)](S,d);S++){let _=r[o(265)+"At"](S);e[o(537)](_,55296)&&e[o(952)](_,56319)&&e.GKxJi(e[o(1379)](S,1),d)&&(_=e.qFOxa(e[o(1670)](e[o(495)](_,10),r.charCodeAt(++S)),56613888)),h+=e[o(749)](_,128)?1:_<2048?2:e[o(1082)](_,65536)?3:4}we(c,h);let p=e[o(1376)](ae,c,h),y=c[o(582)];for(let S=0;e[o(1414)](S,d);S++){let _=r[o(265)+"At"](S);e[o(1241)](_,55296)&&e[o(626)](_,56319)&&e[o(1308)](e[o(1070)](S,1),d)&&(_=e.WSMaX(e[o(230)](e[o(1400)](_,10),r[o(265)+"At"](++S)),56613888)),e[o(1481)](_,128)?y[p++]=_:(e[o(349)](_,2048)?y[p++]=e.tSlUX(e[o(975)](_,6),31)|192:(e.EWyRA(_,65536)?y[p++]=e[o(921)](e.GnpKP(e[o(223)](_,12),15),224):(y[p++]=e[o(741)](e.VvYIj(e.OqjdN(_,18),7),240),y[p++]=e.gXXWx(e.zzKMr(e[o(975)](_,12),63),128)),y[p++]=e.fNLeN(e.UGCMb(_,6)&63,128)),y[p++]=e[o(672)](63&_,128))}}function W(c,r){let o=t,d=e.onDyV(ae,c,r[o(184)]),h=c[o(582)],p=r.bytes;for(let y=0,S=r.limit;y<S;y++)h[e.gjhUi(y,d)]=p[y]}function se(c){let r=t;return c[r(582)][e[r(513)](te,c,1)]}function ot(c,r){let o=ae(c,1);c.bytes[o]=r}function me(c){let r=t,o=0,d=0,h;do h=se(c),e[r(423)](o,32)&&(d|=e.htNkM(127&h,o)),o+=7;while(e[r(452)](128,h));return d}function we(c,r){let o=t;for(r>>>=0;r>=128;)e[o(1161)](ot,c,e[o(672)](e.ErmKT(127,r),128)),r>>>=7;e[o(1376)](ot,c,r)}function Ot(c,r){let o=t,d=0,h=0,p=0,y;if(y=e[o(963)](se,c),d=127&y,e[o(1320)](128,y)&&(y=e[o(858)](se,c),d|=e[o(1168)](e[o(336)](127,y),7),e[o(1232)](128,y)&&(y=e[o(858)](se,c),d|=e.pPDgW(127,y)<<14,e[o(315)](128,y)&&(y=se(c),d|=(127&y)<<21,e[o(561)](128,y)&&(y=se(c),h=127&y,128&y&&(y=e[o(1403)](se,c),h|=e[o(471)](127&y,7),128&y&&(y=e.CVlas(se,c),h|=e[o(944)](127&y,14),e[o(679)](128,y)&&(y=se(c),h|=e[o(495)](e[o(685)](127,y),21),128&y&&(y=e[o(803)](se,c),p=e[o(359)](127,y),e[o(517)](128,y)))))))))){if(e[o(1627)](e[o(1355)],o(1051)))return this[o(632)].binaryType;y=e.grfFw(se,c),p|=e[o(424)](127&y,7)}return{low:e[o(672)](d,e[o(1400)](h,28)),high:e[o(848)](h>>>4,e.JzcKr(p,24)),unsigned:r}}function St(c,r){let o=t,d={xKwKs:function(h,p){return e[V(1063)](h,p)},Iohlp:o(971),EMRqo:e[o(1296)],OTHhl:e[o(1630)]};if(e[o(719)](e[o(701)],o(926))){let h=e.waItL(r[o(984)],0),p=e[o(1044)](e[o(739)](r[o(984)],28)|e[o(424)](r[o(1293)],4),0),y=e[o(671)](r[o(1293)],24),S=e[o(565)](0,y)?e[o(1315)](0,p)?e[o(749)](h,16384)?e[o(423)](h,128)?1:2:h<2097152?3:4:e[o(441)](p,16384)?e[o(706)](p,128)?5:6:e[o(1284)](p,2097152)?7:8:y<128?9:10,_=e[o(1393)](ae,c,S),D=c[o(582)];switch(S){case 10:D[_+9]=e.ALkeK(e[o(1511)](y,7),1);case 9:D[e.EdNPA(_,8)]=e[o(968)](9,S)?128|y:e[o(1597)](127,y);case 8:D[e.Afcwl(_,7)]=e[o(730)](8,S)?e.HniFo(e[o(866)](p,21),128):e[o(452)](e.NmBxx(p,21),127);case 7:D[_+6]=e[o(163)](7,S)?e.fNLeN(p>>>14,128):e[o(876)](e.nANOa(p,14),127);case 6:D[e[o(677)](_,5)]=e[o(968)](6,S)?e[o(299)](p,7)|128:e[o(481)](p>>>7,127);case 5:D[_+4]=e.RwKIa(5,S)?128|p:127&p;case 4:D[e[o(938)](_,3)]=e[o(1204)](4,S)?e[o(1044)](h,21)|128:e[o(359)](e[o(866)](h,21),127);case 3:D[_+2]=e[o(807)](3,S)?e.ZzIzq(e[o(406)](h,14),128):e[o(271)](e.Tzxbt(h,14),127);case 2:D[e[o(1670)](_,1)]=S!==2?e[o(274)](e[o(518)](h,7),128):e.GTRLe(e[o(1587)](h,7),127);case 1:D[_]=e.LLNAp(1,S)?e.gXXWx(128,h):127&h}}else _0x2b631b=_0x49fe44&&d[o(1629)](d[o(763)],_0x40088f[o(710)])?d.EMRqo:d[o(1279)],_0x7c72ed=_0x30618d[o(1152)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),_0x366533=/^wss(.*:\/\/)/.test(_0x1de51e)?_0x1b978a:""+_0xcb7549+_0x346e5a}function un(c){return b(c)}function Jt(c){return v(c)}let fn=65536,di=e.ntzmW,ve=fn*fn,Ce=ve*ve,ur=Ce/2,Me=String[t(1490)+"e"][t(265)+"At"];class xe{constructor(r,o,d){let h=t;this[h(515)]=!0,this[h(984)]=0|r,this[h(1293)]=0|o,this[h(642)]=!!d}static isLong(r){let o=t,d={uYlLf:function(h,p,y){return e[V(1223)](h,p,y)},TBYPr:function(h,p,y){return e[V(932)](h,p,y)},hFihf:function(h,p,y){return e.JneFu(h,p,y)}};if(e[o(1454)]===e[o(1454)])return r&&e[o(719)](!0,r.isLong);IwYTpF[o(458)](_0x5c0d60,_0x24e2be,66),IwYTpF[o(1200)](_0x172b9a,_0x501cd0,_0x270225[o(1535)]),IwYTpF[o(296)](_0x2ee1b0,_0x589544,_0x542517)}static[t(576)](r,o,d){return new xe(r,o,d)}static[t(1097)+"s"](r,o,d){let h=t;return d?xe[h(1097)+"sLE"](r,o):xe[h(1097)+h(459)](r,o)}static[t(1097)+t(264)](r,o){let d=t;return new xe(e[d(511)](e.ZzIzq(e[d(430)](r[0],e[d(399)](r[1],8)),e[d(1305)](r[2],16)),e.wWCmN(r[3],24)),e[d(921)](e[d(1390)](r[4],r[5]<<8),r[6]<<16)|e[d(471)](r[7],24),o)}static["fromByte"+t(459)](r,o){let d=t;return new xe(e.ZzIzq(e[d(1619)](e.GYCuB(e[d(820)](r[4],24),e[d(1561)](r[5],16)),r[6]<<8),r[7]),e.uzQPD(e[d(292)](e[d(1305)](r[0],24),e[d(1090)](r[1],16))|r[2]<<8,r[3]),o)}static[t(1620)](r){let o=t;return e.Asavl(r,di)?Kd:new xe(e.HniFo(e[o(292)](e.gXXWx(Me[o(1120)](r,0),e[o(1637)](Me.call(r,1),8)),e[o(783)](Me[o(1120)](r,2),16)),Me[o(1120)](r,3)<<24)>>>0,e[o(1587)](e.rGmpK(e[o(509)](e[o(848)](Me.call(r,4),e.KPlJo(Me[o(1120)](r,5),8)),e[o(1623)](Me[o(1120)](r,6),16)),e[o(1624)](Me[o(1120)](r,7),24)),0),!0)}[t(843)](){let r=t;return String[r(171)+r(338)](255&this.low,e.nANOa(this[r(984)],8)&255,e[r(501)](e[r(1476)](this[r(984)],16),255),e.bplUT(this[r(984)],24),e[r(1234)](255,this[r(1293)]),e.kRjwp(e[r(739)](this.high,8),255),e[r(1511)](this[r(1293)],16)&255,e.nANOa(this.high,24))}static[t(1405)+"er"](r,o=!0){let d=t;if(e[d(1524)](isNaN,r))return o?uw:Kd;if(o){if(r>=Ce)return hw}else{if(e[d(952)](r,-ur))return xw;if(e[d(1241)](e[d(938)](r,1),ur))return fw}return xe.fromBits(r%ve|0,e[d(1302)](e[d(510)](r,ve),0),o)}[t(879)](){let r=t;return this[r(642)]?e[r(230)](e.JeSiu(this.high>>>0,ve),e[r(1476)](this[r(984)],0)):this[r(1293)]*ve+e[r(1202)](this[r(984)],0)}[t(1214)](){let r=t;return this[r(1293)]===0&&e.KCXOl(0,this[r(984)])}[t(720)](r){let o=t;xe.isLong(r)||(r=xe[o(1405)+"er"](r));let d=e[o(1636)](this.high,16),h=e[o(401)](65535,this[o(1293)]),p=e[o(1444)](this[o(984)],16),y=e.kQuoN(65535,this[o(984)]),S=e[o(518)](r.high,16),_=e[o(557)](65535,r[o(1293)]),D=r.low>>>16,O=e.kRjwp(65535,r[o(984)]),F=0,J=0,re=0,Y=0;return Y+=e[o(563)](y,O),re+=e.Tzxbt(Y,16),Y&=65535,re+=e[o(1379)](p,D),J+=e[o(919)](re,16),re&=65535,J+=e[o(1489)](h,_),F+=e[o(866)](J,16),J&=65535,F+=e[o(877)](d,S),F&=65535,xe[o(576)](e[o(430)](re<<16,Y),e.HniFo(F<<16,J),this[o(642)])}[t(644)](r){let o=t;return xe.isLong(r)||(r=xe[o(1405)+"er"](r)),e[o(163)](this[o(642)],r.unsigned)&&e[o(1084)](this[o(1293)]>>>31,1)&&e[o(1021)](e[o(893)](r[o(1293)],31),1)?!1:this.high===r.high&&e.TUYqR(this.low,r[o(984)])}addOne(){let r=t;return e[r(284)](-1,this.low)&&e[r(1084)](-1,this[r(1293)])?xe[r(576)](0,0,this.unsigned):e[r(1277)](-1,this[r(984)])?xe[r(576)](0,this.high+1,this.unsigned):xe[r(576)](this[r(984)]+1,this[r(1293)],this[r(642)])}[t(498)](r){return r?this.toBytesLE():this[t(629)+"E"]()}toBytesLE(){let r=t,o=this[r(1293)],d=this.low;return[255&d,e[r(1655)](e[r(186)](d,8),255),e[r(481)](e.oJrwh(d,16),255),e[r(1252)](d,24),e[r(640)](255,o),e[r(1248)](o,8)&255,e.Tzxbt(o,16)&255,e[r(518)](o,24)]}[t(629)+"E"](){let r=t,o=this[r(1293)],d=this[r(984)];return[e.lqwQP(o,24),e[r(501)](e[r(903)](o,16),255),e[r(607)](e[r(186)](o,8),255),e[r(1320)](255,o),e.Itnsk(d,24),e.XiQiw(d>>>16,255),e[r(1252)](d,8)&255,e.JzafR(255,d)]}}let Kd=new xe(0,0,!1),uw=new xe(0,0,!0),fw=xe[t(576)](-1,2147483647,!1),hw=xe[t(576)](-1,-1,!0),xw=xe[t(576)](0,-2147483648,!1);var hn=(function(c){let r=t,o=e[r(1137)][r(1317)]("|"),d=0;for(;;){switch(o[d++]){case"0":c[c[e[r(519)]]=5005]=e.CkDiQ;continue;case"1":c[c[e[r(830)]]=5002]=e[r(830)];continue;case"2":c[c[r(200)+r(939)]=5004]=e.RMPtE;continue;case"3":c[c.NATIVE_ERROR=5001]="NATIVE_E"+r(659);continue;case"4":return c;case"5":c[c[e.UekUp]=5003]=e[r(1641)];continue}break}})({});class fr{constructor(r){let o=t;e[o(1021)](o(570),e[o(680)])?(this[o(1278)]=r,this[o(947)]=null):_0x44bfc2[o(1580)](_0x26ea95)}}class Vd extends fr{constructor(r,o){let d=t;super(r),this[d(1363)]=o&&o.message||null}}class Zd extends fr{constructor(r,o){let d=t,h=("4|1|5|6|"+d(170))[d(1317)]("|"),p=0;for(;;){switch(h[p++]){case"0":this.lineno=o&&o[d(1416)]||0;continue;case"1":this.error=o&&o[d(369)]||null;continue;case"2":this[d(1388)]=o&&o[d(1388)]||5001;continue;case"3":this[d(1363)]=o&&o[d(1363)]||"";continue;case"4":super(r);continue;case"5":this[d(1507)]=o&&o[d(1507)]||0;continue;case"6":this.filename=o&&o[d(616)]||"";continue}break}}}class Jd extends fr{constructor(r,o){let d=t,h=(d(1628)+"1")[d(1317)]("|"),p=0;for(;;){switch(h[p++]){case"0":this[d(1388)]=o&&o.code||0;continue;case"1":this[d(855)+d(1088)]=o&&o["willReco"+d(1088)]||!1;continue;case"2":this[d(1665)]=o&&o[d(1665)]||"";continue;case"3":this.wasClean=o&&o[d(1680)]||!1;continue;case"4":super(r);continue}break}}}class Yd extends fr{constructor(r,o){let d=t;super(r),this[d(277)]=o&&o[d(277)]||null}}class Xd extends Yd{constructor(r,o){let d=t;super(r),this[d(277)]=o&&o[d(277)]||null,this[d(1363)]=o&&o[d(1363)]||null}}class Qd extends fr{constructor(r,o){let d=t;super(r),this[d(277)]=o&&o.data||null}}function pt(c,{message:r,code:o,error:d}){let h=t;if(e.AZSEE(e[h(742)],h(402))){let p=new _0x3c0cfd(e[h(211)](_0x1b286a,_0x59009d));return e[h(276)](_0x52d6d7,_0x13398e,p,0),p}else return new Zd(c,{message:r,code:o,error:d})}function It(c,{code:r,reason:o,wasClean:d,willReconnect:h}){return new Jd(c,{code:r,reason:o,wasClean:d,willReconnect:h})}function eu(c,{data:r,message:o}){return new Xd(c,{data:r,message:o})}function tu(c,{data:r}){return new Qd(c,{data:r})}function Ga(c,{message:r}){let o=t,d={Sbnpo:function(h,p,y){return e[V(1488)](h,p,y)},KfhCs:o(883)+"t"};if(e[o(329)](e[o(466)],e[o(466)]))return new Vd(c,{message:r});{this[o(1365)+o(456)+"t"]();let h=d.Sbnpo(_0x253683,d.KfhCs,{message:"stop imm"+o(342)+o(1534)+"ct"});this[o(1351)+o(1047)+o(1036)+"ct"]&&this["onStopIm"+o(1047)+o(1036)+"ct"](h)}}class nu{constructor(r,o){let d=t;this[d(1155)+"s"]=r,this.maxRetries=o,this[d(1080)+"ndex"]=0,this["currentE"+d(1499)+d(1319)+"t"]=0}[t(1427)+t(1651)+t(1594)](){let r=t;this.currentIndex=0,this["currentE"+r(1499)+r(1319)+"t"]=0}[t(977)+"es"](){let r=t;this[r(1020)+"ndpointT"+r(1319)+"t"]=0}[t(1584)+t(703)+"nt"](){let r=t;if(r(862)===e.WzOuy)return this[r(1155)+"s"][this[r(1080)+r(1326)]];_0x2d0147(),xHgYwR[r(214)](_0x1922c9),_0x45d606=[xHgYwR[r(1359)],xHgYwR[r(655)],r(433),xHgYwR.ATEgL,xHgYwR[r(1399)]],_0x27cce1=[r(327),xHgYwR.FfVLS,xHgYwR[r(1334)],xHgYwR.ejUVt],_0x252741=new _0x3061f7,xHgYwR[r(1314)](_0x2a6a75,o=>({...o,get:(d,h,p)=>_0x178da7(d,h)||o[r(298)](d,h,p),has:(d,h)=>!!_0x2c2c8d(d,h)||o[r(1452)](d,h)}))}[t(1584)+"ntEndpoi"+t(1602)+t(1183)](){let r=t;return this[r(1020)+r(1499)+r(1319)+"t"]}[t(708)+t(1263)+"es"](){let r=t;return!!(this[r(1080)+r(1326)]>=this[r(1155)+"s"].length||e[r(844)](this.currentIndex,e[r(362)](this[r(1155)+"s"][r(1535)],1))&&e[r(719)](this[r(1020)+"ndpointT"+r(1319)+"t"],this.maxRetries))}[t(715)+"rentEndp"+t(504)+t(937)+t(524)](){let r=t;return e[r(1063)](this[r(1080)+"ndex"],this[r(1155)+"s"][r(1535)])?!0:this[r(1020)+r(1499)+r(1319)+"t"]>this[r(885)+"es"]}["replaceBackupEnd"+t(164)+t(226)+t(851)](){let r=t;return this[r(1020)+r(1499)+r(1319)+"t"]=1,this[r(1080)+"ndex"]++,this[r(1155)+"s"][this[r(1080)+r(1326)]]}["getCurre"+t(703)+"ntAndUpdateCount"](){let r=t;return this[r(1020)+"ndpointT"+r(1319)+"t"]++,this[r(1584)+r(703)+"nt"]()}}let hr=(e[t(1506)](e.yRETB,typeof globalThis)&&e[t(1596)](e[t(669)],globalThis[t(1049)+t(997)][t(505)])||e[t(759)](e[t(1642)],typeof window)&&e[t(669)]===window[t(1049)+t(997)][t(505)])&&e[t(1396)](e[t(1642)],typeof document),Gn=t(447)+"d"!=typeof globalThis&&(e.lOKUS(e[t(970)],globalThis["construc"+t(997)].name)||e[t(565)](e.tohjz,globalThis[t(1049)+t(997)].name))&&e[t(1067)](e[t(1642)],typeof tt),ui=(e[t(588)](e[t(1642)],typeof globalThis)&&e[t(1522)](t(1362),globalThis[t(1049)+t(997)][t(505)])||e[t(288)](e.yRETB,typeof globalThis)||e[t(1642)]!=typeof globalThis&&!!globalThis[t(736)+t(1336)])&&e.yRETB!=typeof wx,fi=e[t(1642)]!=typeof globalThis&&(e[t(550)](t(1117)+t(765)+"lobalScope",globalThis[t(1049)+t(997)][t(505)])||e.twKQt(e[t(1469)],globalThis.constructor[t(505)])||e[t(834)](e[t(880)],globalThis[t(1049)+t(997)][t(505)]))&&e[t(1303)](t(447)+"d",typeof self),pw=e[t(514)](e[t(1642)],typeof globalThis)&&e.bzaAF===globalThis[t(1049)+t(997)][t(505)]&&e[t(1046)](e[t(1642)],typeof global)&&e[t(1627)](e[t(970)],global[t(1049)+t(997)][t(505)])&&e[t(224)](e[t(1642)],typeof process)&&!!process.version;class qa{constructor(){let r=t;if(e[r(284)](e[r(1383)],e[r(1383)]))this[r(580)+"rs"]={};else{if(e[r(467)](e[r(1532)],typeof _0x22a130)){let o=new _0xe9773d(e[r(842)](_0x385da6,_0x158acb));return e[r(276)](_0x1592dd,_0x36b77c,o,0),o}return e[r(1607)](_0x521b6c,_0x3cc11e)?new _0x29fa62(_0x580386):new _0x46511e(_0x115748[r(666)],_0x3103f4[r(185)+"et"],_0x166b6f[r(712)+"th"])}}[t(461)](r,...o){let d=t,h=this[d(580)+"rs"][r];if(h)h[d(1423)]()[d(962)](p=>p.fn[d(1575)](p[d(1487)],o));else if(e[d(278)](d(369),r)&&!this[d(320)]){let p=o[d(1535)]&&o[0];if(e[d(1607)](p,Error))throw p;let y=new Error(e.LuRWg(d(242)+d(788),p?e[d(449)](e[d(230)](" (",p.message),")"):""));throw y[d(1139)]=p,p}return this}[t(323)](r,o){let d=t;if(e[d(1398)](void 0,r))this[d(580)+"rs"]={};else if(e[d(1141)](void 0,o))this._listeners[r]=null;else{let h=this[d(580)+"rs"][r];if(h)for(let p=0;p<h[d(1535)];)e[d(416)](h[p].fn,o)?h.splice(p,1):++p}return this}on(r,o,d){let h=t;return(this._listeners[r]||(this[h(580)+"rs"][r]=[])).push({fn:o,ctx:d||this}),this}}class gw extends qa{[t(427)+t(1369)+"age"](r){let o=t;return r.errMsg||r[o(512)]?("message: "+(r[o(670)]||"")+o(448)+(r[o(512)]||"")).trim():JSON[o(425)+"y"](r)}constructor(r,o,d){let h=t;if(e[h(579)](h(1570),e[h(1244)]))return _0xe1c8d5?this.toBytesLE():this[h(629)+"E"]();super(),this[h(632)]=null,ui&&wx["connectS"+h(941)]&&(this[h(632)]=wx[h(840)+h(941)]({url:r,protocols:o,header:d,fail:this["_createS"+h(1253)+h(992)][h(1247)](this),success:this[h(1330)+h(1483)+h(1266)+h(432)].bind(this)})),Gn&&tt[h(840)+h(941)]&&(this[h(632)]=tt[h(840)+"ocket"]({url:r,protocols:o,header:d,fail:this[h(1330)+h(1253)+h(992)][h(1247)](this),success:this[h(1330)+h(1483)+h(1266)+h(432)][h(1247)](this)}))}[t(1330)+t(1483)+t(1266)+"ler"](){let r=t,o={cTGjC:function(d,h){return e[V(844)](d,h)},JXKru:function(d,h){return e[V(989)](d,h)},gqhzW:function(d,h){return e[V(1631)](d,h)},SHpIU:function(d,h,p){return d(h,p)},KrOoH:function(d){return e[V(214)](d)},nZrRe:function(d,h){return d!==h},OslBF:e[r(535)]};if(e[r(1313)](r(781),r(781)))Promise[r(746)]()[r(832)](()=>{let d=r;if(o.nZrRe(o.OslBF,o.OslBF))return UVzNal[d(1087)](typeof _0x4412cd,d(1083))?UVzNal[d(991)](_0x716dce,_0x2949ea):(UVzNal[d(964)](_0x3a24a3,_0x41f041)&&UVzNal[d(991)](_0x291755,_0x53d48d),UVzNal[d(1467)](_0x17dee9,_0x2bba92,UVzNal[d(1576)](_0x3d3410))?new _0xfb4710(_0x33c85e,_0x56f4ad):_0x1e3784);this[d(1170)+"steners"]()});else return!!this[r(958)]}["_createSocketFai"+t(992)](r){let o=t,d={CdHgV:function(h,p,y){return e.JneFu(h,p,y)},XTSvA:o(369),toNxz:"close"};Promise[o(746)]()[o(832)](()=>{let h=o,p=d[h(1470)](pt,h(369),{message:this[h(427)+h(1369)+h(486)](r)});this.emit(d[h(1553)],p);let y=d[h(1470)](It,h(1157),{reason:this[h(427)+h(1369)+h(486)](r)});this[h(461)](d.toNxz,y)})}[t(1170)+t(1081)](){let r=t,o={ADQkV:function(d,h,p){return e[V(1435)](d,h,p)},sWqQb:e.cxhpW,bHCzc:r(369)};this[r(632)][r(709)](d=>{let h=r;this[h(461)](e[h(957)],e[h(678)](tu,e[h(957)],{...d,data:d[h(670)]||""}))}),this._socket[r(745)](d=>{let h=r;this[h(461)](e.nEpqT,It(e[h(1583)],{...d}))}),this._socket.onMessage(d=>{let h=r;this[h(461)](h(1363),o.ADQkV(eu,o.sWqQb,{...d}))}),this._socket[r(869)](d=>{let h=r;this.emit(o[h(638)],pt(o.bHCzc,{...d,message:d[h(670)]||""}))})}[t(1076)](r){let o=t,d={DlNhC:function(h,p,y){return e.fdyyV(h,p,y)},XriaS:e[o(1679)],jOTEN:function(h,p,y){return h(p,y)}};if(e[o(589)](r,Uint8Array)){let h=r[o(666)][o(1423)](r[o(185)+"et"],e[o(1458)](r.byteLength,r[o(185)+"et"]));this._socket&&this[o(632)][o(1076)]({data:h,fail:p=>{let y=o;this.emit(y(369),d[y(475)](pt,"error",{message:this[y(427)+y(1369)+"age"](p)}))}})}else this[o(632)]&&this[o(632)].send({data:r,fail:h=>{let p=o;this[p(461)](d[p(1208)],d.jOTEN(pt,d[p(1208)],{message:this[p(427)+"rrorMessage"](h)}))}})}close(r,o){let d=t;e[d(1091)](e[d(1681)],e[d(1681)])?_0x2417d0.push(_0x5b3700):this[d(632)]&&this[d(632)][d(1157)]({code:r,reason:o})}[t(853)+t(405)](r,o){this.on(r,o)}["removeEv"+t(1209)+t(764)](r,o){let d=t,h={ViuPp:function(p,y){return p+y}};if(e[d(1138)]===e[d(1138)])this.off(r,o);else{if(TQnjdL.ViuPp(_0x36548d.offset,_0x4eb6c9)>_0xdebc8b[d(184)])throw new _0x25446a("Skip pas"+d(691));_0x5ad303.offset+=_0x10ddb6}}get readyState(){let r=t;return e.PiBTz(e[r(1205)],e[r(1205)])?this[r(1127)]?this[r(1127)][r(575)+"te"]:this[r(280)][r(208)+r(485)]?this[r(625)+"NG"]:this[r(250)]:this[r(632)][r(575)+"te"]}get[t(1229)+"pe"](){let r=t;return this[r(632)][r(1229)+"pe"]}set[t(1229)+"pe"](r){}get[t(798)](){let r=t;return this._socket[r(798)]}get protocol(){let r=t;return this[r(632)][r(710)]}get extensions(){let r=t;return this[r(632)][r(1459)+"ns"]}get bufferedAmount(){return 0}}function mw(c,r){let o=t;if(r)return new r(c.url,c[o(710)]);if(e[o(1417)](ui,Gn))return new gw(c[o(798)],c[o(710)],c[o(295)]);if(e.kMJRE(hr,fi)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(c.url,c[o(710)+"s"])}function ww(c){let r=t;return!!(c||ui&&wx[r(840)+r(941)]||Gn&&tt[r(840)+r(941)]||(hr||fi)&&e.FqRyP(r(447)+"d",typeof WebSocket)&&WebSocket)}function ru(c,r,o){let d=t;if(e.IlCQM(e[d(1370)],d(1440))){let h=-1;async function p(y){let S=d;return e[S(1437)](y,h)?Promise[S(994)](new Error(e[S(902)])):(h=y,y===o[S(1535)]?Promise[S(746)]():o[y][S(1247)](c)(r,p.bind(null,e[S(1489)](y,1))))}p(0)}else xHgYwR.yRETB!=typeof _0x4b298d&&_0x507e9a["toString"+d(562)]&&_0x239860[d(247)+d(219)](_0x39b395,_0x29863e[d(637)+d(562)],{value:d(418)}),_0x2b95c2["definePr"+d(219)](_0x28f05e,d(317)+"le",{value:!0})}function iu(c){let r=t,o={cbsYu:function(d,h){return d(h)}};if(e[r(779)](e[r(673)],e[r(673)])){let d=0,h=0;for(let p=0;e[r(873)](p,c.length);++p)h=c[r(265)+"At"](p),h<128?d+=1:e[r(1373)](h,2048)?d+=2:e[r(1655)](64512,h)===55296&&e[r(376)](e.xUlMC(64512,c.charCodeAt(e[r(845)](p,1))),56320)?(++p,d+=4):d+=3;return d}else _0x4eb50d=o[r(1092)](_0x4e2eb3,_0x266086),_0x567215=0}function su(c,r,o){let d=t;if(e[d(1672)](o,r)<1)return"";let h="";for(let p=r;p<o;){let y=c[p++];if(y<=127)h+=String[d(171)+d(338)](y);else if(e[d(205)](y,192)&&e[d(1481)](y,224))h+=String[d(171)+d(338)](e[d(1249)](e[d(257)](e[d(867)](31,y),6),63&c[p++]));else if(y>=224&&y<240)h+=String[d(171)+d(338)](e[d(1515)](e.GRnQF(15,y)<<12,e[d(501)](63,c[p++])<<6)|e[d(796)](63,c[p++]));else if(e[d(600)](y,240)){let S=e.vjKnM(e[d(1249)](e[d(1302)](e.gGNtP(e.dPapa(7,y)<<18,e[d(1541)](e[d(784)](63,c[p++]),12)),e[d(911)](e.jSeLo(63,c[p++]),6)),e[d(1234)](63,c[p++])),65536);h+=String[d(171)+d(338)](e.UzfhQ(55296,e[d(223)](S,10))),h+=String[d(171)+d(338)](e.nXQNF(56320,e.cDNsW(1023,S)))}}return h}function Ha(c,r,o){let d=t,h=o,p,y;for(let S=0;e[d(1284)](S,c[d(1535)]);++S)if(p=c[d(265)+"At"](S),e[d(1228)](p,128))r[o++]=p;else if(e[d(1414)](p,2048))r[o++]=e.TQUoV(e[d(1652)](p,6),192),r[o++]=e[d(1032)](63&p,128);else if(e[d(976)](e[d(910)](64512,p),55296)&&e.tSlUX(64512,y=c[d(265)+"At"](e[d(1140)](S,1)))===56320){let _=e[d(817)][d(1317)]("|"),D=0;for(;;){switch(_[D++]){case"0":r[o++]=e[d(282)](e[d(1652)](p,6)&63,128);continue;case"1":r[o++]=p>>18|240;continue;case"2":r[o++]=e[d(509)](e.eXBGf(63,p),128);continue;case"3":r[o++]=e[d(972)](e[d(501)](p>>12,63),128);continue;case"4":p=e[d(563)](65536+e[d(374)](e[d(1077)](1023,p),10),1023&y);continue;case"5":++S;continue}break}}else r[o++]=e[d(930)](e.UGCMb(p,12),224),r[o++]=e[d(1249)](e[d(438)](e.UGCMb(p,6),63),128),r[o++]=e.cTDUt(e[d(1113)](63,p),128);return e[d(1165)](o,h)}async function ou(c){let r=t;if(e[r(1063)](e.UvABO,typeof c)){let o=new Uint8Array(e.XiutW(iu,c));return e[r(276)](Ha,c,o,0),o}return e[r(589)](c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c[r(666)],c[r(185)+"et"],c.byteLength)}function _w(c){let r=t,o={HngCe:function(d,h){return e[V(665)](d,h)},HgOsK:function(d,h){return e.fcoAg(d,h)},LWnaS:e[r(204)],TNNfY:e[r(1600)]};if(e[r(1024)](e[r(358)],e[r(1464)]))_0x43d522[r(500)+"d"]&&(this[r(1275)+r(499)]()&&(!this[r(1127)]||o[r(400)](this._ws[r(575)+"te"],this[r(1581)])||o[r(1003)](this._ws[r(575)+"te"],this.CONNECTING))&&this[r(1539)+"nLine"](),this[r(377)+"er"]&&_0x5a2887[r(853)+"Listener"](o[r(1143)],this[r(1539)+"nLine"]),this[r(377)+"er"]&&_0xa17ed9[r(853)+r(405)](o[r(258)],this[r(1539)+r(1406)]));else try{return e[r(1303)](e[r(1532)],typeof c)&&(c instanceof ArrayBuffer||c[r(666)]&&e[r(1105)](c.buffer,ArrayBuffer))||e[r(195)](r(1114),typeof c)?"":(JSON[r(199)](c),e[r(1431)])}catch{return e[r(288)](e[r(1532)],typeof c)?e.QKyUH:""}}let yw=(c,r)=>{let o=t,d={tIFsJ:function(h,p,y){return e[V(664)](h,p,y)},XifVY:function(h,p,y){return e[V(330)](h,p,y)},oimHu:function(h,p){return e[V(391)](h,p)}};if(e.xKhIS(e[o(176)],e.OeCyb))pBHOOH[o(1590)](_0x30fa5a,_0x345b6f,96),pBHOOH[o(1411)](_0x432ea8,_0x41ddd3,pBHOOH[o(1119)](_0x39e5a7,_0x1a2203));else switch(c){case o(1316):case o(1192):return{[o(924)+c]:1,"x-tt-env":r};default:return{}}};class Ew{constructor(r){let o=t;this[o(1246)+o(1183)]=r,this[o(839)]=0}addCount(){let r=t;this[r(839)]++}[t(708)+"chMaxCount"](){let r=t;return e.Lfcun(this.count,this["maxLossC"+r(1183)])}[t(1104)+"nter"](r=0){let o=t;this[o(1246)+"ount"]=r,this[o(839)]=0}}async function bw(c){let r=t,o={xicth:function(d,h){return d(h)},nPVwI:e[r(687)],QyqRl:function(d,h){return e[r(1034)](d,h)},hxLYJ:e.jtiDc,aNcLu:"text/javascript",CxJUN:function(d,h){return d+h},unsDD:e[r(1071)]};return new Promise(d=>{let h=r;if(!hr)return o[h(925)](d,o[h(532)]);try{let p=document[h(162)+h(1306)](o.hxLYJ);window[h(1622)+"JSONP"]=y=>{let S=h;document[S(1332)][S(1189)+S(645)](p),window["frontier"+S(446)]=void 0,o[S(1227)](d,y&&y[S(1145)]||o[S(532)])},p[h(1278)]=o[h(1530)],p[h(1565)]=o.CxJUN(c[h(1152)](/^ws/,"http"),o.unsDD);try{document[h(1332)][h(1606)+"ild"](p)}catch{document[h(1332)]["removeCh"+h(645)](p)}}catch{window[h(1622)+h(446)]=void 0,d(o[h(532)])}})}function xn(c,r,o){let d=t;return!!c?.[d(828)](h=>h[d(1163)]===r&&h[d(1172)]===o)}function xr(c,r){let o=t;return c?.[o(828)](d=>d[o(1163)]===r)?.[o(1172)]}let $a=null;async function vw(){let c=t;return $a||($a=Promise[c(746)]()[c(832)](Kt[c(1247)](Kt,e.KjMpE))),$a}class Sw extends qa{constructor(r,o){let d=t;super(),this[d(684)]=r,this[d(470)]=o,this[d(958)]=void 0,this[d(451)+d(396)]=null}async[t(308)](){await this[t(382)]()}async[t(382)](){let r=t,o={MHDgF:function(d){return e.uhbpj(d)},hQfrj:function(d,h,p,y){return e.IxzCx(d,h,p,y)}};if(!this[r(958)]){if(this._initPromise)return this[r(451)+r(396)];try{let d=this[r(684)],h=this[r(470)];this["_initPro"+r(396)]=(async()=>{let p=r,{openDB:y}=await o[p(620)](vw);this[p(958)]=await o[p(175)](y,p(1622)+"_"+d,1,{upgrade(S){S.createObjectStore(d,{keyPath:h})}})})(),await this[r(451)+r(396)]}catch(d){console[r(1580)](d)}finally{this["_initPro"+r(396)]=null}}}async get(r){let o=t;try{return await this[o(382)](),this[o(958)]?.[o(298)](this[o(684)],r)}catch(d){console[o(1580)](d)}}async[t(577)](r,o){let d=t;return await this[d(382)](),this[d(958)]?.put(this._dbName,r)}async[t(775)](r){let o=t;try{return e[o(278)](e[o(551)],o(801))?(await this[o(382)](),this._qosDB?.delete(this[o(684)],r)):this[o(1127)]?this[o(1127)][o(710)]:""}catch(d){if(e[o(1021)](e[o(1085)],e[o(979)])){if(this._options["disableA"+o(1108)+o(1288)]||this[o(1366)+o(469)])return;this[o(1061)+o(1150)]()}else console.log(d)}}async clear(){let r=t;try{return await this._init(),this[r(958)]?.[r(1480)](this[r(684)])}catch(o){console[r(1580)](o)}}async keys(){let r=t;return await this._init(),this[r(958)]?.[r(379)+"ys"](this[r(684)])}async[t(433)](){let r=t;return await this._init(),this[r(958)]?.[r(433)](this[r(684)])}async[t(281)](){let r=t;try{this[r(958)]?.[r(1157)](),this[r(958)]=void 0}catch(o){console[r(1580)](o)}}get[t(650)](){let r=t,o={hzaer:r(1453),pHohC:e.wKoCe,lsckP:e[r(974)],SBDQX:e[r(1394)]};try{return!!this._qosDB}catch(d){if(e.BDGId(r(1322),e.GICHl))this[r(377)+"er"]&&_0x198cb4[r(853)+r(405)](o[r(1154)],this[r(1539)+r(435)]),this[r(377)+"er"]&&_0x4b6a19[r(853)+r(405)](o.pHohC,this[r(1539)+r(1406)]),this[r(377)+"er"]&&_0x432d88[r(853)+r(405)](o[r(409)],this["_handleP"+r(1563)]),this[r(377)+"er"]&&_0x52b8f4[r(853)+r(405)](o[r(699)],this[r(1643)+"ageShow"]);else return console[r(1580)](d),!1}}}class Iw{constructor(r,o){let d=t,h={HIRLD:function(p,y){return e.mVyeM(p,y)},FZyCS:function(p,y){return e[V(211)](p,y)},kbrQM:function(p,y,S){return p(y,S)}};if(e.AZSEE(e[d(593)],e[d(593)]))return GIGebN[d(407)](GIGebN[d(667)](_0x3f5a21,8)[d(182)]("0"),GIGebN.kbrQM(_0x58cfef,_0x1c1f90,10)[d(637)](2))[d(1423)](-8);this[d(696)]=r,this[d(568)]=o,this[d(958)]=localStorage}async openDB(){}get[t(489)](){let r=t;return r(1622)+"_"+this[r(696)]}async[t(298)](r){let o=t,d=this[o(958)][o(794)](this._prefix);return JSON[o(199)](e[o(689)](d,"{}"))[r]}async[t(577)](r,o){let d=t,h=this[d(958)][d(794)](this[d(489)]),p=JSON[d(199)](e[d(203)](h,"{}"));return p[o||r[this._pathKey]]=r,this[d(958)][d(1615)](this._prefix,JSON[d(425)+"y"](p)),o||r[this[d(568)]]}async[t(775)](r){let o=t;if(e[o(1632)](e[o(733)],e[o(733)]))this[o(1278)]=_0x59a5ce,this.target=null;else{let d=this[o(958)].getItem(this._prefix),h=JSON[o(199)](e[o(203)](d,"{}"));return h[r]=void 0,this[o(958)][o(1615)](this[o(489)],JSON[o(425)+"y"](h))}}async clear(){return this[t(958)].clear()}async[t(1026)](){let r=t,o=this[r(958)].getItem(this[r(489)]),d=JSON[r(199)](e[r(689)](o,"{}"));return Object[r(1026)](d)}async[t(433)](){let r=t,o=this[r(958)][r(794)](this[r(489)]),d=JSON[r(199)](e[r(689)](o,"{}"));return Object[r(1307)](d)}[t(281)](){return Promise[t(746)]()}get[t(650)](){let r=t;return e[r(675)](e[r(1468)],e[r(1468)])?!!this[r(958)]:this.low===-1&&e[r(776)](-1,this.high)?_0x24943c[r(576)](0,0,this[r(642)]):e[r(663)](-1,this[r(984)])?_0xa734bf[r(576)](0,e[r(877)](this[r(1293)],1),this[r(642)]):_0xa3f2f7[r(576)](this.low+1,this[r(1293)],this[r(642)])}}class Aw{constructor(r,o){let d=t,h={ATMtp:function(p,y){return p instanceof y},RPUVf:function(p,y){return e[V(167)](p,y)}};if(e[d(350)]!==e.yKyFB)this[d(696)]=r,this._pathKey=o,this[d(958)]=Gn?tt:ui?wx:null;else{if(kkAYqy[d(417)](_0x4d8c5b,_0x526742))return _0x519ec5(_0x556203);if(_0x54d6a6[d(1452)](_0x27aa8b))return _0x5c0838.get(_0x37defe);let p=kkAYqy.RPUVf(_0x5230df,_0x3991b5);return p!==_0x47f58d&&(_0x54ccae[d(577)](_0x5c708a,p),_0x26bb7f.set(p,_0x1e94d0)),p}}async[t(308)](){}get[t(489)](){return t(1622)+"_"+this._DBName}async[t(298)](r){let o=t,d=this[o(958)][o(1544)+o(762)](this[o(489)]);return JSON[o(199)](e[o(1167)](d,"{}"))[r]}async[t(577)](r,o){let d=t,h=this._qosDB[d(1544)+"geSync"](this[d(489)]),p=JSON.parse(e.fJcXj(h,"{}"));return p[o||r[this[d(568)]]]=r,this[d(958)][d(1298)+"geSync"](this[d(489)],JSON.stringify(p)),o||r[this[d(568)]]}async[t(775)](r){let o=t,d=this._qosDB[o(1544)+o(762)](this[o(489)]),h=JSON[o(199)](e[o(1417)](d,"{}"));return h[r]=void 0,this._qosDB.setStorageSync(this[o(489)],JSON.stringify(h))}async[t(1480)](){let r=t;return this[r(958)]["clearSto"+r(1028)]()}async[t(1026)](){let r=t,o=this[r(958)]["getStora"+r(1213)+"nc"](this._prefix),d=JSON[r(199)](e.CzXtz(o,"{}"));return Object[r(1026)](d)}async[t(433)](){let r=t,o=this[r(958)][r(1544)+r(1213)+"nc"](this._prefix),d=JSON.parse(e.UdHpP(o,"{}"));return Object.values(d)}[t(281)](){return Promise[t(746)]()}get[t(650)](){return!!this[t(958)]}}function au(c,r){let o=t;if(e[o(689)](Gn,Gn))return new Aw(c,r);if(e[o(899)](hr,fi)&&e[o(1642)]!=typeof indexedDB)return new Sw(c,r);if(e[o(698)](hr,fi)&&e[o(195)](e[o(1642)],typeof localStorage))return new Iw(c,r);throw new Error(e[o(661)])}class Tw{constructor(){let r=t;this[r(695)+r(1603)+"Id"]=null,this._interval=36e5,this[r(958)]=au(e[r(583)],r(303)+"id")}async[t(695)+"lFlush"](){let r=t,o={mEseO:e[r(583)]};e[r(1043)](e[r(1529)],e[r(1529)])?(e[r(1402)](clearInterval,this[r(695)+r(1603)+"Id"]),this["_interva"+r(1603)+"Id"]=e[r(1386)](setInterval,()=>{let d=r;this[d(1286)+d(1295)]()},this[r(695)+"l"])):(this["_interva"+r(1603)+"Id"]=null,this._interval=36e5,this[r(958)]=_0x1e13ea(WSAdER[r(1007)],r(303)+"id"))}async[t(308)](){let r=t;await this[r(958)][r(308)]().then(()=>{let o=r;this[o(695)+o(225)]()})}async[t(1286)+t(1295)](){let r=t,o={RjgXH:function(d,h,p,y){return e[V(361)](d,h,p,y)},BSRHp:function(d,h){return e[V(210)](d,h)}};if(e[r(1073)]===e[r(1073)])(await this[r(958)]?.[r(433)]()||[])[r(191)](({timestamp:p})=>p<Date[r(1566)]())[r(962)](p=>{let y=r;this[y(958)]?.[y(775)](p[y(303)+"id"])});else{let d=255&_0xe837c2;o[r(558)](_0x49626f,d,_0x1bd515,o[r(293)](_0x2732c6,_0x2adce2)),_0xf3e3cc>>>=8,_0x18fbf7--}}async del(r){let o=t;return this[o(958)]?.[o(775)](r)}async[t(577)](r,o){let d=t;return this._qosDB?.[d(577)]({message_id:r,timestamp:o})}async[t(298)](r){let o=t;return this[o(958)]?.[o(298)](r)}async[t(281)](){let r=t,o={lgxuh:r(536)+r(668)+r(1382)+"4",MsMEA:function(d,h){return e[r(490)](d,h)},IWpsi:function(d,h){return e[r(336)](d,h)},Mnjzy:function(d,h){return e[r(1212)](d,h)},krYOz:function(d,h){return e.EQQsc(d,h)},CJDPO:function(d,h,p,y){return e[r(361)](d,h,p,y)},ziBzV:function(d,h){return e[r(516)](d,h)},MvVIU:function(d,h){return e[r(672)](d,h)},CdnJY:function(d,h){return e[r(1395)](d,h)}};if(e[r(1498)](e.hksfi,e[r(1433)]))e[r(842)](clearInterval,this["_interva"+r(1603)+"Id"]),await this[r(958)]?.[r(281)]();else{let d={gmoPu:o[r(1186)],pMNlu:function(p,y){return p>>>y},jxGOs:function(p,y){return o[r(300)](p,y)},RPUOE:function(p,y){return o[r(854)](p,y)},VXgrK:function(p,y){return o[r(172)](p,y)},NDhdQ:function(p,y){return o[r(300)](p,y)},rhuGz:function(p,y){return o[r(1645)](p,y)},msyhu:function(p,y,S,_){return o.CJDPO(p,y,S,_)},usPCi:function(p,y){return o[r(1543)](p,y)},fzsfQ:function(p,y){return p|y},zgxAr:function(p,y){return o[r(1500)](p,y)},SeKVU:function(p,y){return p|y},UMCHa:function(p,y){return o[r(1124)](p,y)},FOZgF:function(p,y){return p>>>y},Ebfzy:function(p,y){return o.CdnJY(p,y)},aVOts:function(p,y){return p>>>y},YbgqN:function(p,y){return p|y}},h=4294967295;return function(p,y,S=!0){let _=r,D=d[_(1640)][_(1317)]("|"),O=0;for(;;){switch(D[O++]){case"0":h=d[_(1350)](h|d[_(1525)](d.RPUOE(15,p[y]),28),0);continue;case"1":h=d[_(1072)](h|d[_(419)](127&p[y],7),0);continue;case"2":if(d[_(829)](y+=5,p[_(1535)]))throw y=p[_(1535)],d[_(206)](_0x3124f8,y,10,p[_(1535)]);continue;case"3":if(d[_(1100)](p[y++],128))return{value:S?h:d.fzsfQ(0,h),offset:y};continue;case"4":return{value:S?h:d[_(502)](0,h),offset:y};case"5":h=d.VXgrK(d[_(688)](h,d.jxGOs(d.RPUOE(127,p[y]),21)),0);continue;case"6":if(d[_(221)](p[y++],128))return{value:S?h:d[_(544)](0,h),offset:y};continue;case"7":h=d[_(241)](d[_(1035)](127,p[y]),0);continue;case"8":if(d[_(221)](p[y++],128))return{value:S?h:d[_(688)](0,h),offset:y};continue;case"9":if(d[_(1410)](p[y++],128))return{value:S?h:0|h,offset:y};continue;case"10":if(d[_(1410)](p[y++],128))return{value:S?h:d[_(502)](0,h),offset:y};continue;case"11":h=d[_(1029)](d.YbgqN(h,d[_(419)](d[_(1035)](127,p[y]),14)),0);continue}break}}}}get isReady(){let r=t;return this[r(958)]?.[r(650)]}}function ja(c){let r=t;if(e[r(1577)](e[r(662)],r(1011))){let o=!!this._options[r(1111)+"S"];if(!o)return{enabled:o,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let d=xn(c.message.headers,e[r(728)],"2"),h=d&&e[r(474)](xn,c[r(1363)].headers,e[r(1656)],"1"),p=d&&e[r(276)](xn,c[r(1363)][r(295)],e[r(1466)],"1"),y=p?e.HncTM(xr,c[r(1363)][r(295)],r(694)+r(209)+"sgid")?.[r(1317)](",")[r(191)](Boolean)||[]:[];return{enabled:o,isQoSMessage:d,isQoSAck:h,isAckCleanupMessage:p,ackMsgIds:y}}else!this[r(1430)+r(1198)]&&(this[r(291)+r(1187)]?.[r(1427)+r(1651)+r(1594)](),this[r(1604)+r(333)]?.["resetCou"+r(988)](),this[r(1366)+r(469)]=!1,this[r(233)]=!0,this[r(1430)]())}async function cu(){let c=t;return this[c(955)+c(217)]||(this[c(955)+c(217)]=new Tw),this[c(955)+"ger"][c(650)]||await this[c(955)+c(217)][c(308)](),this._QoSManager}async function Rw(c,r){let o=t,d={VnUnF:function(_,D){return _<D},lEQjH:function(_,D){return e[V(1014)](_,D)}},{enableAutoAck:h}=this[o(280)],p=e[o(361)](xn,c[o(1363)][o(295)],o(905),"1"),y=e[o(361)](xn,c[o(1363)][o(295)],e[o(1557)],"1"),S=ja[o(1120)](this,c);if(h&&p)if(e[o(1627)](e[o(1409)],e[o(1409)])){let{SeqID:_,LogID:D,service:O,LogIDNew:F,method:J}=c[o(1363)];this[o(1300)]({SeqID:_,LogID:D,LogIDNew:F,service:O,method:J,headers:[{key:e.NTyTJ,value:"1"},{key:e[o(768)],value:F||""},{key:e[o(212)],value:"0"}]})}else _0x47a9d5=_0x354134(_0x46852d),kWfUXo[o(1345)](_0x1c8789,32)&&(_0x4c9755|=kWfUXo[o(1391)](127,_0x1c8530)<<_0x5d017c),_0x2e7b54+=7;y&&!S.isQoSAck&&this._dispatchAckMessageEvent(c),e.BRbWT(r)}async function kw(c,r){let o=t;this[o(1450)]("received",c[o(1363)]),r()}async function Cw(c,r){let o=t,d=e[o(272)](un,await ou(c[o(277)]));try{if(e[o(354)](d[o(1335)],Uint8Array)){let h=e[o(1631)](this._options["payloadE"+o(918)],Object)?{force:!!this[o(280)]["payloadE"+o(918)][o(404)],encoding:this._options[o(888)+o(918)][o(717)]?this[o(280)][o(888)+o(918)].encoding[o(1152)](/\s/g,"")["toLowerC"+o(1571)]():""}:{force:!1,encoding:this[o(280)][o(888)+o(918)]?this._options[o(888)+o(918)][o(1152)](/\s/g,"").toLowerCase():""},p=d[o(888)+o(918)]?d[o(888)+o(918)][o(1152)](/\s/g,"")[o(1568)+o(1571)]():"",y=e[o(909)](this[o(280)]["payloadT"+o(1663)],Object)?{force:!!this[o(280)]["payloadT"+o(1663)][o(404)],type:this[o(280)]["payloadT"+o(1663)][o(1278)]?this[o(280)][o(1546)+o(1663)][o(1278)].replace(/\s/g,"")[o(1568)+o(1571)]():""}:{force:!1,type:this[o(280)][o(1546)+o(1663)]?this._options[o(1546)+"ype"][o(1152)](/\s/g,"")[o(1568)+"ase"]():""},S=d[o(1546)+o(1663)]?d[o(1546)+o(1663)][o(1152)](/\s/g,"")[o(1568)+o(1571)]():"",_=y.force?y[o(1278)]:S||y[o(1278)],D=h[o(404)]?h.encoding:p||h[o(717)],O=[o(560)+o(161)+"et=utf-8",o(1621)+"ion/json",e[o(324)],e[o(1532)]],F=[e[o(1129)],e[o(1176)]];this[o(280)][o(787)+o(316)+"extPayload"]&&O.includes(_)&&(!D||F[o(540)](D))?d[o(1056)+"oad"]=e.IxzCx(su,d[o(1335)],0,d[o(1335)][o(712)+"th"]):d[o(1056)+"oad"]=""}else d[o(1056)+o(465)]=""}catch(h){d[o(1056)+o(465)]="",console[o(1580)](h)}c[o(1363)]=d,e.jLZyc(r)}function Pw(c,r,o){let d=t,h={RVQRl:function(p,y,S){return e[V(837)](p,y,S)},GpHRo:function(p,y){return p(y)}};if(e[d(1265)]===e[d(1265)]){let p=o||8192,y=e[d(406)](p,1),S=null,_=p;return function(D){let O=d;if(e[O(564)](D,1)||D>y)return e[O(1402)](c,D);e[O(1239)](e.Mypyc(_,D),p)&&(S=e.ZFKkz(c,p),_=0);let F=r[O(1120)](S,_,_+=D);return e[O(271)](7,_)&&(_=e[O(1458)](e[O(310)](7,_),1)),F}}else mMqmeF[d(953)](_0x16cbe6,_0x495d89,32),mMqmeF[d(953)](_0x49e9fb,_0x9ffde2,mMqmeF[d(1030)](_0x1ec85a,_0x17b059))}let Dw=4294967295;function Lw(c,r,o){let d=t,h={JzZgH:function(p,y,S){return p(y,S)},xfijL:"close",QdOkQ:function(p,y,S){return e[V(351)](p,y,S)},Wmxqp:d(1112),JFpXD:e.YkuAp};if(e[d(302)]===e[d(302)])return RangeError(e[d(1255)](e[d(649)](e[d(563)](e.FGnOD(e[d(634)],c),e[d(596)])+e[d(381)](r,1),e[d(533)]),o));if(this[d(852)+d(1367)](),this[d(750)+"mer"](),this["_removeW"+d(1560)+"rs"](),this["_wsInsta"+d(821)](1e3,_0x1c7e07),this[d(1430)+"Lock"]=!1,_0x58ef25&&this[d(1275)+d(499)]()&&!this[d(1366)+d(469)]){if(this[d(291)+d(1187)]?.[d(708)+d(1263)+"es"]()){let y=this[d(291)+d(1187)]?.[d(1584)+d(703)+"nt"]();this["_dispatc"+d(1465)+d(1418)](h[d(394)](_0x4b7a6f,h[d(1514)],{code:1006,reason:d(891)+y+(d(1149)+d(929)+"tries re"+d(723)),wasClean:!0}))}else{let y=this._options[d(883)+d(690)+d(1220)](_0xee6213,_0x231d0c);this[d(942)+d(1465)+"ent"](_0x5dc22c(h[d(1514)],{code:_0x1e9c2d,reason:_0x3947b7,wasClean:!0,willReconnect:y})),y&&this[d(1430)]()}return}this[d(1275)+d(499)]()||this._readyClosed?this[d(942)+d(1465)+d(1418)](h.QdOkQ(_0x3f9216,h[d(1514)],{code:_0x1804f7,reason:h[d(633)]})):this[d(942)+d(1465)+d(1418)](_0xf234d6(h[d(1514)],{code:1006,reason:h[d(1523)]})),this[d(1127)]=null,this[d(291)+d(1187)]?.[d(1427)+"pointCon"+d(1594)](),this[d(1604)+"sCounter"]?.[d(1104)+d(988)]()}function Ow(c,r,o){let d=t;if(e[d(410)](o,Dw))throw new Error(e[d(861)]);let h=3;for(;h>=0;){let p=255&o;Ka(p,c,e[d(1442)](r,h)),o>>>=8,h--}return e[d(1116)](r,4)}function Nw(c,r){let o=t,d=0,h=r,p=r+4;for(;e[o(1082)](h,p);){let{value:y,offset:S}=e[o(192)](Wa,c,h);h=S,d=e.XhNLs(e[o(173)](d,8),0),d+=y}return{value:d,offset:p}}function Mw(c,r,o){let d=t,h=e[d(1520)].split("|"),p=0;for(;;){switch(h[p++]){case"0":if(e.RJxoK(c[d(1535)],40))return e.zjAld(Ha(c,r,o),o);continue;case"1":if(r[d(286)])return e[d(202)](r[d(286)](c,o),o);continue;case"2":if(r[d(1380)+"e"])return e[d(1259)](r[d(1380)+"e"](c,o),o);continue;case"3":if(!c)return o;continue;case"4":return e[d(1471)](Ha(c,r,o),o)}break}}function Bw(c,r){let o=t,d=new xe(e[o(282)](e.hzrtP(e[o(399)](c[e[o(639)](r,4)],24),e[o(173)](c[e[o(819)](r,5)],16))|c[e.sLagm(r,6)]<<8,c[r+7]),e[o(194)](e.ZzIzq(e[o(523)](e.ZiTWZ(c[r+0],24),e[o(165)](c[e[o(1121)](r,1)],16)),e[o(743)](c[e[o(1384)](r,2)],8)),c[r+3]),!0);return r+=8,{value:d,offset:e[o(1116)](r,8)}}function Fw(c,r,o){let d=t;if(e[d(1126)](e[d(491)],d(1242))){let h=c[d(984)],p=c[d(1293)];return r[o]=e[d(671)](p,24),r[e[d(189)](o,1)]=e[d(903)](p,16)&255,r[o+2]=e[d(931)](p,8)&255,r[e[d(213)](o,3)]=255&p,r[e[d(238)](o,4)]=e[d(903)](h,24),r[e[d(676)](o,5)]=e[d(260)](h>>>16,255),r[e.CbLAL(o,6)]=e.EPSwo(e[d(353)](h,8),255),r[e[d(1140)](o,7)]=255&h,o+=8,o}else this[d(377)+"er"]&&_0x2e9df1[d(472)+d(1209)+"ner"](e[d(204)],this[d(1539)+d(435)]),this._isBrowser&&_0x5e0d68["removeEv"+d(1209)+d(764)](e[d(1600)],this[d(1539)+d(1406)]),this[d(377)+"er"]&&_0x50ee0b[d(472)+"entListener"](e.qAbqH,this[d(1643)+d(1563)]),this[d(377)+"er"]&&_0x5d6c50[d(472)+d(1209)+d(764)](e[d(1394)],this[d(1643)+d(1579)])}function Wa(c,r){let o=t;return c[o(1102)+"8"]?{value:c.readUInt8(r),offset:e[o(1054)](r,1)}:{value:e[o(1077)](255,c[r]),offset:e.PVqyI(r,1)}}function Ka(c,r,o){let d=t;return e[d(652)]!==d(816)?!!this[d(958)]:(r[d(630)+"t8"]?r[d(630)+"t8"](c,o):r[o]=255&c,o+1)}let zw=function(c){return new Uint8Array(c)},Uw=e[t(195)]("undefined",typeof Buffer)?Buffer[t(572)+t(1148)]:Pw(zw,Uint8Array[t(1490)+"e"][t(800)]),Gw=16,Va=32;function qw(c){let r=t,o=0,d={};for(let h=0;e.KNSEl(h,c.length);h++)d[c[h][r(468)+r(306)]]=e.Aeoan(iu,c[h][r(468)+r(306)]),o+=e.GQaoG(14,d[c[h][r(468)+r(306)]]);return[o,d]}function lu(c,r,o){let d=t,h={HEeUl:e[d(546)],lUckg:function(D,O,F,J){return e[d(864)](D,O,F,J)},VKSDW:e.PwYHI,uogFI:d(1333),OUiJx:e.FpgAI,jjXtj:e[d(1281)]},[p,y]=e.fdDny(qw,c),S=e.MHFjW(Uw,p),_=0;return c[d(962)](D=>{let O=d;console[O(1580)](h[O(943)],D,D[O(1333)]),_=h.lUckg(Ka,0,S,_),console[O(1580)](h.VKSDW,_),_=h[O(1497)](Ow,S,_,D[O(1333)]||0),console.log(h[O(1022)],_),_=h[O(1497)](Ka,y[D[O(468)+"ame"]],S,_),console[O(1580)](O(1184)+O(505),_),_=h.lUckg(Mw,D[O(468)+"ame"],S,_),console.log(h.OUiJx,_),_=h.lUckg(Fw,xe[O(1405)+"er"](D[O(337)]||r),S,_),console.log(h[O(740)],_)}),{frameType:Va,headers:[{key:e.NkVGa,value:o}],payload:S}}function Hw(c){let r=t,o=0,d=[];for(;e[r(234)](o,c[r(712)+"th"]);)if(e.HvWib(r(1125),"CdEvo")){let h=_0x5eddca[r(782)];if(e[r(410)](e.hzZHx(h,_0x52aed8),_0x211840[r(184)]))throw new _0x33e6e2(r(1516)+r(691));return _0x4c79d8[r(782)]+=_0x3fc6d9,h}else{let{offset:h}=e.QBrwe(Wa,c,o);o=h;let p={cursor_name:"",cursor:0,service:0},{value:y,offset:S}=e[r(330)](Nw,c,o);p[r(1333)]=y,o=S;let{value:_,offset:D}=e.khAWn(Wa,c,o);o=D,p[r(468)+r(306)]=e[r(864)](su,c,o,e.IRavd(o,_)),o+=_;let{value:O,offset:F}=e.NGeqr(Bw,c,o);p[r(337)]=O[r(879)](),o=F,d[r(345)](p)}return d}function $w(){let c=t;return{frameType:Va,headers:[{key:e[c(415)],value:e[c(1292)]}],payload:void 0}}class jw{constructor(r,o,d){let h=t;this[h(1485)+h(875)]=r,this[h(197)+h(1321)]=o,this[h(521)+h(1280)]=d,this[h(958)]=e[h(1591)](au,this[h(1485)+h(875)],e.kFokH)}async[t(308)](){let r=t;await this._qosDB[r(308)]()}async[t(1250)+"rs"](){let r=t,o={fwiVT:function(d,h,p){return e[V(1059)](d,h,p)}};if(e.FpeWC(r(1299),e.jwKMm)){if(!this[r(958)][r(650)])return;let d=this[r(521)+r(1280)],h=await this[r(958)].getAll();switch(console[r(1580)](e[r(1331)],h),d){case r(1448):return h&&h[r(1535)]?e[r(1392)](lu,h,0,this[r(197)+r(1321)]):void 0;case e[r(1555)]:return;case e.KlQJQ:return h&&h[r(1535)]?e[r(1019)](lu,h,0,this[r(197)+r(1321)]):e.IkfZh($w)}}else{let d=this[r(291)+r(1187)]?.[r(1584)+"ntEndpoint"](),h=this._options[r(883)+r(690)+r(1220)](_0x540102[r(1388)],_0x238743[r(1665)]);this["_dispatc"+r(1465)+r(1418)](o[r(956)](_0x2d505e,r(1157),{code:1006,reason:_0x3fc016[r(1665)]||r(1353)+r(1657)+"d, unknown reaso"+r(1462)+"ame: "+d,willReconnect:h})),h&&this[r(1430)]();return}}async[t(577)](r,o,d){let h=t;return console[h(1580)](h(1659),r,o,d),this[h(958)][h(577)]({cursor_name:r,cursor:o,service:d})}async setCursors(r){let o=t,d=e[o(1403)](Hw,r);for(let h of d)console.log(e.yzyOB,d),await this[o(958)][o(577)](h)}async[t(298)](r){let o=t;return(await this[o(958)][o(298)](r))?.[o(337)]}async closeDB(){let r=t;await this[r(958)][r(281)]()}[t(352)+t(1504)+"Name"](r){let o=t;this[o(197)+o(1321)]=r}get isReady(){let r=t;return this[r(958)][r(650)]}}let Ww=e[t(1001)];async function du(c){let r=t;if(!this[r(280)][r(1111)+"S"])return null;let{aID:o,fpID:d,messageStrategy:h}=this[r(280)],p=e[r(381)](c,Ww);try{return this[r(1147)+r(426)]?c&&this[r(1147)+r(426)][r(352)+r(1504)+r(983)](c):this[r(1147)+r(426)]=new jw(d+"_"+o+"_"+p,p,h),this[r(1147)+r(426)].isReady||await this[r(1147)+"anager"].openDB(),this["_cursorM"+r(426)]}catch{return null}}async function Kw(c,r){let o=t;if(e.eTRwf(e.UbYRP,o(702))){let d=e[o(1392)](xn,c[o(1363)][o(295)],e[o(1421)],"-1"),h=e[o(1392)](xn,c.message.headers,e[o(1557)],"1"),p=e.nlFaO(xr,c.message.headers,e[o(503)]),y=e[o(803)](Number,xr(c.message[o(295)],e[o(1151)]))||0,S=ja[o(1120)](this,c),_=xn(c[o(1363)][o(295)],e[o(595)],"2"),D=e[o(245)](xr,c[o(1363)][o(295)],e[o(287)]),O=e[o(1403)](Number,xr(c[o(1363)][o(295)],e[o(321)]));if(S[o(567)])return e.IWLFv(r);let F=S["isQoSMes"+o(1644)]?await cu[o(1120)](this):null;if(e[o(1239)](c[o(1363)][o(1333)],0)&&h&&!d||e.xPHNy(c[o(1363)][o(1333)],0)){if(p&&S[o(364)+o(1644)]&&F)return!!!await F[o(298)](p)&&(this[o(942)+o(1385)+o(951)](c),await F[o(577)](p,e.kDMjH(Date[o(1566)](),y))),r();if(_)if(e[o(1558)]===e[o(1101)])this[o(696)]=_0x9bc96d,this[o(568)]=_0x160b67,this[o(958)]=_0x304b49;else{let J=await du.call(this);if(!J)return this[o(942)+o(1385)+o(951)](c),e[o(214)](r);let re=await J[o(298)](D)??-1;if(e.eTHUb(re,O))if(e[o(1649)](e[o(506)],e[o(506)]))this[o(942)+o(1385)+o(951)](c),J[o(577)](D,O,c[o(1363)].service);else{let Y=_0x35eb97[o(1572)]();return Y?(Y[o(782)]=Y.limit=0,Y):{bytes:new _0x6af238(64),offset:0,limit:0}}else throw new Error(o(340)+o(289)+o(434)+O+(o(606)+o(1397)+o(610)+"r ")+re);return e[o(549)](r)}return this["_dispatc"+o(1385)+"Event"](c),e[o(1586)](r)}}else return this._qosDB?.[o(298)](_0x47e954)}async function Vw(c,r){let o=t,d=ja.call(this,c);if(!d[o(364)+o(1644)])return e[o(249)](r);let h=await cu[o(1120)](this);if(d[o(1133)+"anupMess"+o(486)]&&d.ackMsgIds[o(1535)])for(let p of d[o(1193)+"s"])await h[o(775)](p);r()}async function Zw(c,r){let o=t;if(e.irsbK(e[o(1033)],o(479))){let{SeqID:d,LogID:h,service:p,LogIDNew:y,method:S}=_0x170eb7.message;this[o(1300)]({SeqID:d,LogID:h,LogIDNew:y,service:p,method:S,headers:[{key:e.NTyTJ,value:"1"},{key:e[o(768)],value:e.aufvu(y,"")},{key:e[o(212)],value:"0"}]})}else{let d=c.message.frameType===Gw,h=e[o(1e3)](c[o(1363)][o(1178)+"e"],Va);if(!d&&!h)return e.BRbWT(r);let p=e[o(574)](xr,c[o(1363)].headers,e[o(415)]);if(!p)return e[o(1169)](r);let y=await du[o(1120)](this,p);if(!y)return r();if(d){let S=await y[o(1250)+"rs"](),_={frameType:S?.[o(1178)+"e"],SeqID:xe[o(1405)+"er"](this[o(1538)]++),LogID:xe[o(1405)+"er"](this._options[o(1550)+"erator"]()),service:9e3,method:5,headers:S?.headers,payload:S?.[o(1335)]},D=e[o(754)](v,_);this._ws&&this[o(1127)].readyState&&this[o(1127)][o(1076)](D)}if(h)if(e[o(747)](e[o(1045)],e[o(178)])){let S=c[o(1363)][o(1335)];S&&y[o(857)+"rs"](S)}else{let S=0,_=0,D;do D=e.grfFw(_0x5a5d53,_0x1fd260),e[o(581)](S,32)&&(_|=e[o(313)](e[o(685)](127,D),S)),S+=7;while(e[o(1404)](128,D));return _}}}let Jw=async function(c,r){let o=t,d={sqooD:function(h,p,y){return e.dxohX(h,p,y)}};if(e.LGlFV(o(1441),e[o(674)]))this._isInit=!1,clearTimeout(this[o(1430)+"ionTimeo"+o(1197)]),r();else{this["_clearPi"+o(1367)](),this[o(1118)+o(1273)+"Id"]=d[o(967)](_0x262e1d,this[o(881)][o(1247)](this),this[o(280)][o(1012)+o(993)]);return}},Yw=async function(c,r){let o=t;if(!this[o(1127)]||e[o(1614)](this[o(1127)].readyState,this[o(1581)]))return e[o(856)](r);let{pingInterval:d}=this[o(280)];this._endpointManager?.[o(1427)+o(1651)+o(1594)]();for(let p=0;e[o(1132)](p,this[o(521)+o(1060)].length);p++){let y=this[o(521)+o(1060)][p];if(this[o(1127)].readyState===this[o(1581)]&&e[o(370)](null,y))this[o(1127)]&&this[o(1127)][o(1076)](y),this[o(521)+"Queue"][p]=null;else break}this[o(521)+o(1060)]=this._messageQueue.filter(p=>!!p),this["_pingPon"+o(1273)+"Id"]=setTimeout(()=>this[o(881)](),d),this[o(942)+o(760)+"nt"](c),this[o(377)+"er"]&&this._ws&&(this._ws[o(1229)+"pe"]=this[o(584)+"ype"]);let h=this[o(291)+o(1187)]?.["getCurre"+o(703)+"nt"]();this[o(1450)](o(1310)+h+o(889)),e.uhbpj(r)},Xw=async function(c,r){let o=t,d=this["_endpoin"+o(1187)]?.[o(1584)+o(703)+"nt"]();this[o(1450)](o(1310)+d),e.uOvGJ(r)};class Qw extends qa{constructor(r){let o=t,d={jAwCY:function(S,_,D){return e[V(1376)](S,_,D)},TdSIg:e[o(1679)],HRHCv:function(S,_){return e[o(1315)](S,_)},WkyFE:function(S,_){return S===_},PVQly:function(S,_){return e[o(896)](S,_)}};super(),this[o(587)+o(1548)+o(325)]=!0,this._isBrowser=hr,this._isNode=pw,this[o(1549)+"T"]=Gn,this[o(769)+"X"]=ui,this[o(1122)+"r"]=fi,this["_message"+o(1060)]=[],this[o(291)+o(1187)]=null,this[o(1366)+"osed"]=!1,this[o(584)+o(1663)]="arraybuffer",this[o(1430)+"Lock"]=!1,this[o(1430)+o(218)+"utId"]=null,this[o(385)+o(1542)+"tId"]=null,this[o(1118)+o(1273)+"Id"]=null,this[o(1538)]=0,this[o(233)]=!1,this[o(923)]="",this[o(955)+o(217)]=null,this[o(1147)+o(426)]=null,this._pingLossCounter=null,this[o(846)+"ls"]=e.TzeAG,this[o(250)]=3,this[o(625)+"NG"]=0,this[o(1581)]=1,this[o(900)]=2,this._onOpen=S=>{let _=o;try{e[_(445)](ru,this,S,[Jw,Yw,Xw])}catch(D){let O=e[_(601)](pt,e.BWeHU,{message:D[_(1363)],code:hn.OPEN_ERROR,error:D});this[_(942)+_(266)+"ent"](O)}},this._onMessage=async S=>{let _=o,D={Jwqca:function(O,F){return e[V(1174)](O,F)}};if(e[_(1277)](e[_(1027)],e[_(444)])){let O=this[_(958)]["getStora"+_(762)](this[_(489)]);return _0x3b8190[_(199)](tYNkrx.Jwqca(O,"{}"))[_0x3f8621]}else{let{pingInterval:O,pingFrequency:F}=this[_(280)];if((e.xPmxh("hi",S[_(277)])&&e[_(440)]===F||e.rcWhA===F)&&(this["_clearPi"+_(1367)](),this[_(461)](e[_(454)],e[_(450)]),this["_pingPon"+_(1273)+"Id"]=e.wLXyA(setTimeout,this[_(881)].bind(this),O)),e.SBYxp("hi",S.data))return;try{ru(this,S,[Cw,Rw,Vw,Zw,Kw,kw])}catch(J){if(e.LGlFV(e[_(960)],_(647))){let re=pt(e.BWeHU,{message:J.message,code:hn[_(200)+_(939)],error:J});this["_dispatc"+_(266)+_(1418)](re)}else{let re=_0x56625d(_0x5eb922,1);_0x39afb5.bytes[re]=_0x354fda}}}},this._onError=S=>{let _=o,D=this["_endpoin"+_(1187)]?.[_(708)+_(1263)+"es"](),O=this[_(291)+_(1187)]?.[_(1584)+_(703)+"nt"]();if(D&&!S[_(1363)]){let F=_(891)+O+(_(534)+_(1226)+"es reached");this[_(942)+_(266)+_(1418)](d[_(753)](pt,d.TdSIg,{message:F,code:hn[_(1503)+_(1510)+"R"],error:S}));return}this[_(1127)]&&d[_(1598)](this[_(1127)].readyState,this[_(1581)])&&this[_(714)+_(304)](),this[_(942)+"hErrorEvent"](pt(d[_(795)],{message:S[_(1363)],code:hn["NATIVE_E"+_(659)],error:S}))},this[o(347)]=async S=>{let _=o;if(e[_(797)]("pCeZd",e[_(770)]))return zcFlBd[_(1598)](0,this[_(1293)])&&zcFlBd[_(1256)](0,this.low);{this._clearTimer(),this[_(852)+_(1367)](),this[_(621)+"sListeners"](),this._ws=null,this["_connect"+_(1198)]=!1;let D=this._endpointManager?.["checkRea"+_(1263)+"es"]();if(!D&&this[_(1275)+"orOnline"]()&&!this[_(1366)+"osed"]){let O=this["_endpoin"+_(1187)]?.[_(1584)+_(703)+"nt"](),F=this[_(280)][_(883)+_(690)+"ptor"](S[_(1388)],S.reason);this[_(942)+"hCloseEvent"](e[_(678)](It,_(1157),{code:1006,reason:S[_(1665)]||_(1353)+_(1657)+_(1339)+_(1050)+_(1462)+_(1375)+O,willReconnect:F})),F&&this[_(1430)]();return}if(S[_(1388)]!==1e3&&this[_(1366)+"osed"]){this[_(942)+"hCloseEvent"](It(e[_(1583)],{code:1e3,reason:e[_(408)]})),this[_(291)+_(1187)]?.["resetEnd"+_(1651)+_(1594)](),this[_(1604)+"sCounter"]?.["resetCou"+_(988)]();return}if(e[_(1211)](1e3,S.code)&&D){let O=this[_(291)+_(1187)]?.["getCurre"+_(703)+"nt"](),F=S[_(1665)];F||(F=await e[_(1592)](bw,this[_(923)])),F=_(1353)+"ng faile"+_(198)+F+(_(1509)+_(1338))+O+(_(929)+_(1158)+_(723)),this[_(942)+_(1465)+"ent"](It(e[_(1583)],{code:S[_(1388)],reason:F}));let J=_(891)+O+(_(534)+_(1226)+_(348)+"ed");this[_(942)+"hErrorEv"+_(1418)](pt(e[_(1679)],{message:J,code:hn[_(1503)+_(1510)+"R"]})),this[_(291)+_(1187)]?.[_(1427)+_(1651)+_(1594)](),this[_(1604)+"sCounter"]?.[_(1104)+"nter"]();return}if(e[_(602)](1e3,S[_(1388)])&&!S[_(1665)]){if(e[_(615)]("UwtXI",e[_(594)])){let O=this["_endpoin"+_(1187)]?.[_(1584)+_(703)+"nt"]();this[_(942)+_(1465)+_(1418)](e[_(850)](It,e[_(1583)],{code:S.code,reason:"connecti"+_(1657)+"d, unkno"+_(1050)+_(1462)+_(1375)+O})),this[_(291)+"tManager"]?.[_(1427)+_(1651)+"fig"](),this[_(1604)+_(333)]?.[_(1104)+_(988)]();return}else if(zcFlBd[_(648)](_0x201042,_0x5ca63d))return _0x4830b7}this[_(942)+_(1465)+_(1418)](S),this._endpointManager?.[_(1427)+_(1651)+_(1594)](),this["_pingLos"+_(333)]?.["resetCou"+_(988)]()}},this[o(1251)]=null,this[o(320)]=null,this[o(707)+"e"]=null,this[o(726)]=null,this[o(1206)+o(1150)]=null,this[o(613)+"eAck"]=null,this[o(1351)+o(1047)+o(1036)+"ct"]=null,this["_handleO"+o(435)]=this["_handleO"+o(435)][o(1247)](this),this["_handleO"+o(1406)]=this[o(1539)+o(1406)][o(1247)](this),this["_handleP"+o(1563)]=this[o(1643)+o(1563)][o(1247)](this),this["_handleP"+o(1579)]=this[o(1643)+o(1579)][o(1247)](this),this[o(280)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[o(510)](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(1633)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[o(1381)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:p}=r,y=Array[o(774)](h)?h:o(1114)==typeof h?[h]:[];if(!y||e[o(1098)](0,y[o(1535)]))throw new Error(o(1166)+"rovide v"+o(331));if(!e[o(1031)](ww,p))throw new Error(o(1166)+"rovide w"+o(859)+o(654)+"ket cons"+o(387)+o(1536)+o(309));Object[o(1160)](this[o(280)],r),this[o(291)+"tManager"]=new nu(y,this[o(280)][o(885)+"es"]),this[o(1604)+o(333)]=new Ew(this._options[o(1218)+o(1554)]),this[o(280)]["automati"+o(485)]&&(this[o(233)]=!0,this._connect()),this[o(280)]["listenNe"+o(1608)+o(439)]&&(this._isMiniTT||this[o(769)+"X"]?this[o(305)+o(196)+o(1135)]():this._isBrowser&&this[o(1075)+o(878)+o(405)]())}[t(1539)+"nLine"](){let r=t;this[r(280)][r(1274)+r(1108)+r(1288)]||this[r(1366)+r(469)]||this[r(1061)+r(1150)]()}[t(1539)+t(1406)](){let r=t;this[r(1365)+r(456)+"t"]();let o=e[r(1582)](Ga,e[r(1159)],{message:r(357)+r(342)+r(1534)+"ct"});this["onStopImmediatel"+r(1036)+"ct"]&&this[r(1351)+"mediatel"+r(1036)+"ct"](o)}["_initGlo"+t(878)+"Listener"](){let r=t;this[r(377)+"er"]&&window[r(853)+"Listener"](e[r(204)],this[r(1539)+r(435)]),this[r(377)+"er"]&&window[r(853)+"Listener"](e.wKoCe,this[r(1539)+"ffLine"]),this._isBrowser&&window[r(853)+r(405)](e[r(974)],this[r(1643)+r(1563)]),this[r(377)+"er"]&&window[r(853)+r(405)](e[r(1394)],this[r(1643)+"ageShow"])}[t(239)+"balEvent"+t(405)](){let r=t;e[r(1309)]===r(268)?this.on(_0x8483a6,_0xa6656d):(this[r(377)+"er"]&&window["removeEv"+r(1209)+r(764)](e[r(204)],this["_handleO"+r(435)]),this[r(377)+"er"]&&window[r(472)+r(1209)+r(764)](e[r(1600)],this[r(1539)+r(1406)]),this[r(377)+"er"]&&window[r(472)+r(1209)+r(764)](e[r(974)],this[r(1643)+"ageHide"]),this[r(377)+"er"]&&window[r(472)+r(1209)+"ner"]("pageshow",this[r(1643)+r(1579)]))}[t(1643)+"ageHide"](r){let o=t;!r.persisted&&(this[o(377)+"er"]&&window[o(472)+o(1209)+o(764)](e.qAbqH,this._handlePageHide),this[o(377)+"er"]&&window[o(472)+"entListener"]("pageshow",this[o(1643)+o(1579)]),this.close()),this[o(377)+"er"]&&window["removeEv"+o(1209)+"ner"](e.XFYyp,this[o(1539)+"nLine"]),this[o(377)+"er"]&&window[o(472)+"entListe"+o(764)](e.wKoCe,this[o(1539)+"ffLine"])}[t(1643)+t(1579)](r){let o=t,d={TvVmg:function(h,p,y){return e.SCsQF(h,p,y)},dCANw:function(h,p){return h+p}};if(e[o(1495)](e[o(598)],e[o(1559)])){let h=iMDspG.TvVmg(_0xc0c038,_0x410d67,_0x44deb7);return _0x72cebf[o(582)][o(800)](h,iMDspG.dCANw(h,_0x3b04da))}else r[o(500)+"d"]&&(this["_navigat"+o(499)]()&&(!this[o(1127)]||this._ws.readyState!==this.OPEN||e.xKhIS(this[o(1127)][o(575)+"te"],this[o(625)+"NG"]))&&this[o(1539)+"nLine"](),this[o(377)+"er"]&&window[o(853)+o(405)](e.XFYyp,this[o(1539)+o(435)]),this[o(377)+"er"]&&window["addEvent"+o(405)](o(1291),this[o(1539)+"ffLine"]))}async[t(693)+t(605)](r){let o=t,d={yrsve:"sent"},{fpID:h,deviceID:p,bddID:y,ttwID:S,accessKey:_,aID:D,customParams:O={},enableAutoAck:F,enableQoS:J,QoSLevel:re,env:Y}=this[o(280)],gt,dt,Za;this[o(377)+"er"]||this._isMiniWX||this[o(1549)+"T"]?e[o(1605)](o(836),e[o(1527)])?(this[o(1127)]&&this[o(1127)][o(1076)](_0x5b9fa4),this[o(1450)](d[o(737)],_0x5e61ac)):(gt=location&&e.EVXCn(e.gsVPY,location[o(710)])?e[o(1296)]:e[o(1630)],dt=r[o(1152)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),Za=/^wss(.*:\/\/)/[o(1069)](r)?r:""+gt+dt):e[o(1115)](o(1682),e.ocAxd)?(gt=e.oBQtm,dt=r[o(1152)](/(^http)((?:[s]*:\/\/))/,""),Za=/(^ws)((?:[s]*:\/\/))/.test(dt)?dt:""+gt+dt):this[o(197)+o(1321)]=_0x11d480;let uu=y?e[o(780)]:S?o(1017):e[o(1010)],fu=y||S||p;if(e.RoRuj(!fu,!uu))throw new Error(e[o(1493)]);let e_=e[o(1352)]==typeof O?await e[o(1169)](O):O,t_=Y?e.JtlJc(yw,Y.xUseEnv,Y.xTTEnv):{},Ja=Object[o(1160)]({device_platform:e[o(187)],version_code:o(813)+"0",access_key:_,fpid:h,aid:D,[uu]:fu,xsack:F?1:0,xaack:F?1:0,xsqos:J?1:0,qos_level:J?re:void 0,qos_sdk_version:2,...t_},e_),n_=Object[o(1026)](Ja)[o(1270)]((Ya,Xa)=>Ja[Xa]!==void 0?""+Ya+(Ya?"&":"?")+Xa+"="+Ja[Xa]:Ya,"");return Za+o(522)+n_}async _connect(){let r=t;if(!(this[r(1430)+r(1198)]||this[r(1366)+r(469)])){this[r(1430)+"Lock"]=!0;try{let o=this._endpointManager?.[r(715)+r(1425)+r(504)+r(937)+r(524)](),{timeoutInterval:d}=this[r(280)];if(o){let p=this[r(291)+"tManager"]?.getCurrentEndpoint(),y=this["_endpoin"+r(1187)]?.[r(1106)+r(872)+r(164)+r(226)+r(851)](),S=this[r(291)+r(1187)]?.[r(1584)+r(703)+r(1602)+r(1183)]();if(y){let _="connect "+p+(r(1149)+r(929)+r(1158)+r(1463)+r(1185)+r(1064)+r(413))+y+(r(1237)+"y"),D=e[r(192)](pt,e[r(1679)],{message:_,code:hn[r(1503)+"IES_ERROR"]});this[r(1450)](_),this[r(942)+r(266)+"ent"](D),this[r(923)]=await this["_generat"+r(605)](y),this._debug(r(891)+y+" "+S+r(314)),this[r(621)+r(1560)+"rs"]()}else{let _="connect "+p+(r(1149)+", max re"+r(1158)+r(723));this[r(1450)](_),this[r(942)+r(266)+r(1418)](pt(e[r(1679)],{message:_,code:hn[r(1503)+r(1510)+"R"]}));return}}else{let p=this[r(291)+r(1187)]?.[r(1584)+"ntEndpoi"+r(1311)+r(792)](),y=this[r(291)+r(1187)]?.[r(1584)+"ntEndpoi"+r(1602)+"ount"]();this[r(923)]=await this["_generat"+r(605)](e.PwvXZ(p,"")),this[r(1450)]("connect "+p+" "+y+r(314)),this[r(621)+r(1560)+"rs"]()}if(this[r(233)])this._isInit=!1;else{let p=e.HncTM(Ga,r(883)+"t",{message:e[r(982)]});this[r(1206)+r(1150)]&&this[r(1206)+r(1150)](p)}let h=this[r(291)+r(1187)]?.[r(1584)+r(703)+r(1602)+r(1183)]()||0;e.xKVSh(h,1)&&await this[r(1038)](e.MtVqy(h,1)),this[r(1450)](r(1353)+r(312)+this[r(923)]+(" protoco"+r(420))+this._protocols),this._ws=mw({url:this[r(923)],protocols:[this[r(846)+"ls"]],headers:this._options[r(341)+r(1175)+"s"]["customHt"+r(724)]},this[r(280)].ws),(this._isBrowser||this[r(1122)+"r"])&&this[r(1127)]&&(this[r(1127)][r(1229)+"pe"]=this[r(584)+r(1663)]),this[r(1170)+r(1081)](),this[r(1430)+r(218)+r(1197)]=e[r(948)](setTimeout,this[r(618)+"ut"][r(1247)](this),d)}catch(o){throw this["_connect"+r(1198)]=!1,o}}}[t(750)+t(528)](){let r=t;clearTimeout(this[r(1430)+r(218)+"utId"]),this["_connect"+r(218)+r(1197)]=null}["_clearPi"+t(1367)](){let r=t;if(e[r(1533)](e.dDNui,e[r(283)]))e[r(1323)](clearTimeout,this[r(1118)+r(1273)+"Id"]),e.MHFjW(clearTimeout,this[r(385)+r(1542)+"tId"]),this["_pingPon"+r(1273)+"Id"]=null,this[r(385)+"ctTimeou"+r(1023)]=null;else return e.lZlPG(e[r(1532)],typeof _0x12ab93)&&(e.IfivO(_0x242e7e,_0x417de1)||_0x4c5e1f[r(666)]&&e[r(810)](_0x4ea9af.buffer,_0xe0d83e))||e.FqRyP(e[r(1532)],typeof _0x87e430)?"":(_0x3a072f[r(199)](_0x52b4a6),r(1621)+r(1676))}[t(1450)](...r){let o=t,d={VsECT:function(h,p,y){return e[V(1393)](h,p,y)}};e[o(163)](e[o(493)],e[o(597)])?this[o(280)][o(1662)]&&console[o(1580)][o(1575)](console,[e[o(384)],...r]):d[o(388)](_0x211131,_0x69d247,this[o(1479)+o(1342)+"e"](_0x4b865e))}[t(1479)+t(1342)+"e"](r){let o=t,{initReconnectInterval:d,maxReconnectInterval:h,reconnectIntervalGrowFactor:p}=this[o(280)],y=e.yyHcZ(d,Math.pow(p,e[o(547)](r,1)));return e[o(935)](y,h)?h:y}[t(881)](){let r=t;if(this._ws&&e.ldWwv(this[r(1127)][r(575)+"te"],this[r(625)+"NG"])){this[r(852)+r(1367)](),this[r(1118)+r(1273)+"Id"]=e.onDyV(setTimeout,this._ping[r(1247)](this),this[r(280)][r(1012)+"rval"]);return}if(!this[r(1127)]||e.IQtrA(this[r(1127)][r(575)+"te"],this[r(1581)]))return void this[r(1061)+r(1150)]();this[r(1127)]&&this._ws[r(1076)]("hi"),this[r(385)+r(1542)+"tId"]=e[r(1325)](setTimeout,this[r(1061)+"econnectTimeout"][r(1247)](this),this._options[r(235)+r(421)+r(1264)])}["_handleR"+t(1150)+t(429)](){let r=t;this[r(1604)+r(333)]?.[r(1360)](),this[r(461)](e[r(1387)],e[r(969)]),this[r(1604)+r(333)]?.[r(708)+r(1235)+"nt"]()?this[r(1061)+"econnect"]():this[r(881)]()}[t(1275)+t(499)](){let r=t;if(e[r(366)]("cHUOF",e[r(999)]))return this[r(1549)+"T"]||this[r(769)+"X"]?this[r(587)+r(1548)+r(325)]:(this._isBrowser||this[r(1122)+"r"])&&this[r(280)][r(617)+r(1608)+r(439)]?navigator[r(711)]:!0;{let o=e.JRZTI(_0x189eb5,e[r(1159)],{message:e[r(982)]});this[r(1206)+r(1150)]&&this[r(1206)+"econnect"](o)}}[t(1061)+t(1150)](){let r=t;if(e.HvWib(e[r(1025)],r(959))){if(!this[r(1275)+"orOnline"]()||this[r(1366)+r(469)])return;this[r(291)+r(1187)]?.[r(1427)+r(1651)+r(1594)](),this[r(1604)+r(333)]?.["resetCou"+r(988)](),this[r(1127)]?this[r(714)+r(304)](1001,e.grZkE,!0):this[r(1430)]()}else{let{url:o}=_0x201239||{},d=_0x401b67[r(774)](o)?o:e[r(467)]("string",typeof o)?[o]:[];_0x24aaea&&_0x199b10[r(1160)](this[r(280)],_0x44563a),d&&d[r(1535)]?this["_endpoin"+r(1187)]=new _0xbec085(d,this[r(280)][r(885)+"es"]):this[r(291)+r(1187)]?.[r(1427)+r(1651)+r(1594)](),this._pingLossCounter?.resetCounter(this._options[r(1218)+"Count"]),this._readyClosed=!1,this[r(1127)]&&e.fcoAg(this[r(1127)][r(575)+"te"],this[r(250)])?this[r(714)+r(304)](1e3,e.aZDOo,!0):(this[r(233)]=!0,this[r(1430)]())}}["_onPageN"+t(196)+"ange"](){let r=t;this[r(1549)+"T"]?tt[r(262)+r(1142)+r(207)](({isConnected:o})=>{let d=r;this[d(587)+d(1548)+d(325)]=o,o?this[d(1539)+d(435)]():this["_handleO"+d(1406)]()}):this[r(769)+"X"]&&wx["onNetworkStatusC"+r(207)](({isConnected:o})=>{let d=r,h={Cewla:function(p,y){return e[V(1374)](p,y)},FGOAu:function(p,y){return p&y},yajHt:function(p,y){return e[V(452)](p,y)},xvuTG:function(p,y){return p<y},raxPD:function(p,y){return e[V(410)](p,y)},AayTD:function(p,y,S){return e[V(1301)](p,y,S)},XXqaB:function(p,y){return e[V(752)](p,y)},FaNta:function(p,y){return e[V(1347)](p,y)}};e[d(1098)](e[d(1337)],e[d(614)])?(_0x49924c=rZluSR[d(294)](rZluSR[d(1040)](7,_0x2ccf35),18)|rZluSR[d(294)](63&_0x4a9539,12)|rZluSR[d(814)](63,_0x38149d)<<6|rZluSR[d(814)](63,_0x3f6f7e),rZluSR.xvuTG(_0x75c13d,65536)||rZluSR[d(1415)](_0x539056,1114111)?_0x46c0c4+=_0x19ce3a:(_0x307a4a-=65536,_0x485bd+=rZluSR[d(508)](_0xb1a394,rZluSR[d(732)](_0x1cdedb>>10,55296),rZluSR[d(732)](rZluSR[d(751)](1023,_0x3ea12f),56320)),_0x470d0e+=3)):(this["_miniNavigatorOn"+d(325)]=o,o?this[d(1539)+d(435)]():this[d(1539)+"ffLine"]())})}[t(1038)](r){let o={lqdmy:function(d,h,p){return e.VLzHx(d,h,p)}};return new Promise(d=>{let h=V;o.lqdmy(setTimeout,d,this[h(1479)+h(1342)+"e"](r))})}[t(714)+t(304)](r=1e3,o="",d=!1){let h=t;this._ws&&this[h(1365)+h(456)+"t"](r,o,d)}[t(618)+"ut"](){let r=t,o=this[r(291)+r(1187)]?.[r(1584)+"ntEndpoint"]();this._debug("connect "+o+r(1149)),this[r(714)+r(304)](1001,e[r(1052)],!0)}_sendAck(r){let o=t,d={BCZvh:function(h,p){return e[V(482)](h,p)},XcLQI:e[o(861)],TSvOd:function(h,p){return h&p},IsoEI:function(h,p){return e.Mypyc(h,p)}};if(e[o(719)](o(251),e[o(1438)])){let h=Jt(r);this[o(1127)]&&this._ws[o(575)+"te"]===this[o(1581)]&&(this[o(1127)]&&this[o(1127)][o(1076)](h),this[o(1450)](o(1634),r))}else{if(usfsjZ[o(833)](_0x584b8d,_0x16ccce))throw new _0x50e75e(usfsjZ[o(651)]);let h=3;for(;h>=0;){let p=usfsjZ[o(1484)](255,_0x5845d7);_0x7468ae(p,_0x31ae4a,usfsjZ[o(901)](_0x4c38e0,h)),_0x3dac3a>>>=8,h--}return usfsjZ[o(901)](_0x45c5bb,4)}}["_removeW"+t(1560)+"rs"](){let r=t,o=(r(1153)+"3")[r(1317)]("|"),d=0;for(;;){switch(o[d++]){case"0":if(!this._ws)return;continue;case"1":this[r(1127)][r(472)+r(1209)+r(764)](e[r(628)],this[r(261)+"ge"]);continue;case"2":this[r(1127)]["removeEv"+r(1209)+"ner"](e[r(957)],this._onOpen);continue;case"3":this[r(1127)]["removeEv"+r(1209)+r(764)](e[r(1679)],this[r(1455)]);continue;case"4":this[r(1127)]["removeEventListe"+r(764)](e.nEpqT,this[r(347)]);continue}break}}[t(1170)+t(1081)](){let r=t,o=e[r(1260)][r(1317)]("|"),d=0;for(;;){switch(o[d++]){case"0":this._ws[r(853)+r(405)](e.cxhpW,this._onMessage);continue;case"1":if(!this._ws)return;continue;case"2":this[r(1127)].addEventListener(r(1157),this[r(347)]);continue;case"3":this[r(1127)][r(853)+r(405)](e[r(1679)],this[r(1455)]);continue;case"4":this[r(1127)][r(853)+r(405)](e.Wluvo,this[r(1131)]);continue}break}}[t(758)+"nceClose"](r=1e3,o=""){let d=t;try{if(e[d(602)](e[d(1324)],e[d(1496)]))this[d(1127)]&&this[d(1127)][d(1157)](r,o);else{let h={tgvvn:function(D,O){return D<O},MTqwS:function(D,O){return e.mAbLC(D,O)},QtfPv:function(D,O){return e[d(1669)](D,O)},kfpCA:function(D,O){return D>O},OXxFB:function(D,O){return e[d(1255)](D,O)},diuEm:function(D,O){return D(O)},JqkQX:function(D,O){return e[d(1655)](D,O)},UMSvl:function(D,O){return e.cTDUt(D,O)}},p=e.srRBv(_0x199a0a,8192),y=e[d(1444)](p,1),S=null,_=p;return function(D){let O=d;if(h[O(585)](D,1)||h[O(1508)](D,y))return h[O(987)](_0x3dd4a9,D);h[O(716)](h[O(554)](_,D),p)&&(S=h[O(1267)](_0x24c9cc,p),_=0);let F=_0x3ea681[O(1120)](S,_,_+=D);return h.JqkQX(7,_)&&(_=h[O(554)](h[O(1128)](7,_),1)),F}}}catch{}}[t(1365)+"WebSocket"](r=1e3,o="",d=!1){let h=t;if(this[h(852)+h(1367)](),this["_clearTi"+h(528)](),this[h(621)+h(1560)+"rs"](),this["_wsInsta"+h(821)](1e3,o),this[h(1430)+h(1198)]=!1,d&&this[h(1275)+h(499)]()&&!this[h(1366)+h(469)]){if(this._endpointManager?.[h(708)+h(1263)+"es"]()){if(e[h(1495)](e[h(1130)],e[h(1190)]))return e[h(805)](e.YVsjD(_0x4e11a1,4)[h(182)]("0"),e[h(1282)](_0x33ee96,_0x242d74,2)[h(637)](16))[h(1423)](-4);{let y=this[h(291)+h(1187)]?.[h(1584)+h(703)+"nt"]();this[h(942)+h(1465)+h(1418)](It(e[h(1583)],{code:1006,reason:h(891)+y+(h(1149)+h(929)+h(1158)+"ached"),wasClean:!0}))}}else{let y=this[h(280)][h(883)+h(690)+h(1220)](r,o);this[h(942)+h(1465)+h(1418)](e[h(255)](It,e[h(1583)],{code:r,reason:o,wasClean:!0,willReconnect:y})),y&&this[h(1430)]()}return}this[h(1275)+"orOnline"]()||this["_readyCl"+h(469)]?this[h(942)+h(1465)+"ent"](It(e[h(1583)],{code:r,reason:e[h(408)]})):this[h(942)+"hCloseEv"+h(1418)](e[h(237)](It,e.nEpqT,{code:1006,reason:e[h(657)]})),this._ws=null,this[h(291)+"tManager"]?.["resetEnd"+h(1651)+h(1594)](),this[h(1604)+h(333)]?.["resetCou"+h(988)]()}[t(942)+t(760)+"nt"](r){let o=t;this[o(461)](o(1528),r),this[o(726)]&&this[o(726)](r)}["_dispatc"+t(1385)+t(951)](r){let o=t;this.emit(e[o(628)],r),this[o(707)+"e"]&&this[o(707)+"e"](r)}["_dispatc"+t(460)+"ageEvent"](r){let o=t;this[o(461)](e[o(946)],r),this[o(613)+o(1225)]&&this[o(613)+o(1225)](r)}["_dispatchErrorEv"+t(1418)](r){let o=t;this[o(461)]("error",r),this.onerror&&this[o(320)](r)}[t(942)+t(1465)+t(1418)](r){let o=t;this[o(461)](e.nEpqT,r),this[o(1251)]&&this.onclose(r)}get[t(1229)+"pe"](){let r=t;return this._ws?this._ws[r(1229)+"pe"]:this["_binaryT"+r(1663)]}set[t(1229)+"pe"](r){let o=t;this[o(584)+o(1663)]=r,this[o(1127)]&&(this[o(1127)][o(1229)+"pe"]=r)}get[t(1304)+"nt"](){let r=t;if(e[r(1429)](e.UBTNS,r(1341)))this[r(233)]=!0,this[r(1430)]();else return this._endpointManager?.[r(1584)+r(703)+r(1602)+r(1183)]()||0}get["buffered"+t(285)](){let r=t,o=this[r(521)+r(1060)][r(1270)]((d,h)=>(d+=h&&h[r(712)+"th"]||0,d),0);return e[r(477)](o,this._ws?this[r(1127)]["buffered"+r(285)]:0)}get[t(1459)+"ns"](){let r=t;if(e[r(622)](e[r(1238)],e.PZyLH))this[r(852)+r(1367)](),this[r(461)](e.nzjCW,r(527)),this[r(1118)+"gTimeoutId"]=e.upkHr(_0x2db37c,this._ping[r(1247)](this),_0x1d67fe);else return this[r(1127)]?this._ws.extensions:""}get[t(710)](){let r=t;if(e[r(641)]!=="eXoUS"){let o=_0x4ad184[r(372)+"g"](0,e.dsRJP(4,_0x3de999[_0x3dd5af].length)),d=o.concat(_0x443dd4);_0x2dd785=_0x5c239a.concat(d)}else return this._ws?this[r(1127)][r(710)]:""}get[t(575)+"te"](){let r=t;if(e[r(1211)](r(1058),e[r(1673)]))this[r(461)](e[r(628)],e[r(443)](_0xed7767,"message",{..._0x591959}));else return this[r(1127)]?this[r(1127)][r(575)+"te"]:this[r(280)][r(208)+r(485)]?this[r(625)+"NG"]:this[r(250)]}get[t(798)](){let r=t;return this[r(1127)]?this[r(1127)][r(798)]:this[r(923)]}[t(1157)](r=1e3,o){let d=t,h=("6|0|5|7|"+d(1377))[d(1317)]("|"),p=0;for(;;){switch(h[p++]){case"0":this[d(750)+d(528)]();continue;case"1":if(!this[d(1127)])return void this._debug(e[d(1502)]);continue;case"2":if(this._ws.readyState===this.CLOSED||e[d(1062)](this._ws[d(575)+"te"],this[d(900)]))return void this[d(1450)](e[d(826)]);continue;case"3":this[d(955)+d(217)]?.[d(281)]();continue;case"4":this[d(1365)+d(456)+"t"](r,o);continue;case"5":this[d(852)+d(1367)]();continue;case"6":this._readyClosed=!0;continue;case"7":this._dropGlobalEventListener();continue}break}}async[t(1076)](r,o){let d=t;if(e[d(366)](e[d(1110)],e[d(1110)])){if(e[d(288)](null,r))throw new Error(e[d(1348)]);e[d(786)](d(269),typeof r)&&(r=JSON.stringify(r)),e[d(588)](e[d(1532)],typeof r)&&!e[d(1412)](r,ArrayBuffer)&&!(r[d(666)]&&e[d(1631)](r[d(666)],ArrayBuffer))&&(r=JSON[d(425)+"y"](r));let h=await e.KKiQt(ou,r),p=e[d(809)](_w,r),{method:y=0,service:S=this[d(280)][d(1333)],logID:_=this[d(280)][d(1550)+d(1327)](),headers:D=this[d(280)][d(295)],payloadEncoding:O=this._options[d(888)+"ncoding"],payloadType:F=this[d(280)][d(1546)+d(1663)],logIDNew:J=this[d(280)][d(1243)+d(656)][d(368)+d(386)+"teLogIDNew"]?e[d(1526)](i,this[d(280)][d(1243)+d(656)][d(831)]):""}=e[d(904)](o,{});if(!S)throw new Error(d(1166)+d(436)+d(646)+d(882));let re={SeqID:xe.fromNumber(this[d(1538)]++),LogID:xe[d(1405)+"er"](_),service:S,method:y,headers:D,payloadEncoding:e[d(909)](O,Object)?O[d(717)]?O[d(717)]:"":O,payloadType:e.WCmCO(F,Object)?F[d(1278)]?F[d(1278)]:p:F||p,payload:h,LogIDNew:J},Y=e[d(1669)](Jt,re);return this[d(1127)]&&e.OnGwR(this[d(1127)][d(575)+"te"],this.OPEN)?(this[d(1127)]&&this[d(1127)][d(1076)](Y),this[d(1450)](e[d(1531)],re)):e[d(492)](this[d(521)+d(1060)][d(1535)],this[d(280)][d(868)+d(928)+"ength"])?(this[d(521)+d(1060)][d(345)](Y),this[d(1450)](e.fQrrJ,re)):(this[d(521)+d(1060)][d(311)](),this[d(521)+"Queue"][d(345)](Y)),{seqID:this[d(1538)],logID:_,logIDNew:J}}else _0x2b23b5.d=(h,p)=>{let y=d;for(var S in p)_0x4979a0.o(p,S)&&!_0x14a7dc.o(h,S)&&_0x3a3f33["definePr"+y(219)](h,S,{enumerable:!0,get:p[S]})}}async reconnect(r){let o=t,{url:d}=e[o(612)](r,{}),h=Array[o(774)](d)?d:typeof d=="string"?[d]:[];r&&Object.assign(this[o(280)],r),h&&h[o(1535)]?this["_endpoin"+o(1187)]=new nu(h,this[o(280)][o(885)+"es"]):this._endpointManager?.[o(1427)+o(1651)+o(1594)](),this[o(1604)+o(333)]?.[o(1104)+o(988)](this._options[o(1218)+"Count"]),this[o(1366)+"osed"]=!1,this[o(1127)]&&e[o(1451)](this[o(1127)].readyState,this[o(250)])?this[o(714)+o(304)](1e3,e[o(1156)],!0):e[o(1018)](e[o(1144)],e.jtUSV)?this[o(632)]&&this[o(632)][o(1157)]({code:_0xde4bbb,reason:_0xa0e806}):(this[o(233)]=!0,this._connect())}async[t(1221)](){let r=t;if(!this["_connect"+r(1198)]){let o=e[r(398)][r(1317)]("|"),d=0;for(;;){switch(o[d++]){case"0":this[r(233)]=!0;continue;case"1":this[r(1430)]();continue;case"2":this[r(1604)+r(333)]?.[r(1104)+r(988)]();continue;case"3":this[r(1366)+r(469)]=!1;continue;case"4":this[r(291)+r(1187)]?.["resetEnd"+r(1651)+r(1594)]();continue}break}}}[t(853)+t(405)](r,o){this.on(r,o)}dispatchEvent(r){let o=t,{type:d}=r;this[o(461)](d,r)}[t(472)+t(1209)+t(764)](r,o){let d=t;e.CzlwS(e[d(166)],e[d(166)])?this[d(695)+d(225)]():this[d(323)](r,o)}[t(1217)](){let r=t,o={DKtrf:function(d,h){return d(h)},wKJQI:e[r(450)],MpFHm:e[r(1387)],Rioon:e.nzjCW,GNkgc:function(d,h,p){return e[r(609)](d,h,p)}};return new Promise((d,h)=>{let p=r,y={dFWqa:function(D,O){return o[V(1551)](D,O)},LIxaV:o.wKJQI,OHLHx:o.MpFHm,aJXcB:p(1654),xqePo:o[p(1343)]};this[p(852)+p(1367)](),this[p(1118)+"gTimeoutId"]=o[p(1595)](setTimeout,this[p(881)][p(1247)](this),this[p(280)]["pingInte"+p(993)]);let S=()=>{let D=p;y[D(526)](d,y.LIxaV),this[D(323)](D(1224)+D(1491)+"s",S),this[D(323)](y[D(393)],_)},_=()=>{let D=p;h(y[D(1096)]),this.off(y[D(1599)],S),this[D(323)](y[D(393)],_)};this.on(p(1224)+"e_success",S),this.on(o.MpFHm,_),this[p(881)]()})}}})(),Ue["CustomCl"+N(996)]=Oe[N(378)+"oseEvent"],Ue[N(1646)+"rorEvent"]=Oe[N(1646)+N(356)],Ue[N(705)+"e"]=Oe.ErrorCode,Ue[N(951)]=Oe[N(951)],Ue[N(727)]=Oe.FWS,Ue[N(980)+N(1501)+N(611)]=Oe[N(980)+"MessageE"+N(611)],Ue["MessageE"+N(611)]=Oe["MessageE"+N(611)],Ue[N(559)+"t"]=Oe[N(559)+"t"],Ue[N(643)+"tEvent"]=Oe[N(643)+N(1095)],Ue[N(895)+N(996)]=Oe[N(895)+N(996)],Ue["createEr"+N(356)]=Oe[N(1436)+N(356)],Ue["createMe"+N(571)+"nt"]=Oe[N(1601)+N(571)+"nt"],Ue["createOp"+N(1512)]=Oe[N(757)+N(1512)],Ue[N(827)+N(476)+N(611)]=Oe[N(827)+N(476)+N(611)],Ue[N(627)+N(917)]=Oe[N(627)+"rame"],Ue.encodeFrame=Oe[N(682)+N(306)];for(oa in Oe)[N(378)+N(996),N(1646)+"rorEvent",N(705)+"e",N(951),N(727),N(980)+N(1501)+N(611),N(1501)+N(611),N(559)+"t",N(643)+"tEvent",N(895)+"oseEvent",N(1436)+N(356),N(1601)+N(571)+"nt",N(757)+N(1512),N(827)+"connectE"+N(611),N(627)+N(917),N(682)+N(306)].indexOf(oa)===-1&&(Ue[oa]=Oe[oa]);var oa;Object[N(247)+N(219)](Ue,N(317)+"le",{value:!0})});import{existsSync as oA,openSync as aA}from"node:fs";import{mkdir as cA}from"node:fs/promises";import{dirname as lA}from"node:path";import{fileURLToPath as dA}from"node:url";function fA(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function pd(t=ie()){return oA(t.libEntry)?t.libEntry:dA(new URL("../index.ts",import.meta.url))}async function zp(t={}){let e=t.paths??ie(),n=t.entryOverride??pd(e),i=fA(e,process.env.COZE_BRIDGE_LOG_MODE);await cA(lA(i),{recursive:!0});let s=aA(i,"a"),l=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=lt(process.execPath,l,{detached:!0,stdio:["ignore",s,s],env:{...process.env,[gs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return uA.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var uA,gs,ma=at(()=>{"use strict";rn();oe();Be();uA=$("spawn-daemon"),gs="COZE_BRIDGE_DAEMON"});var ri=z((q4,Wp)=>{"use strict";var CA="2.0.0",PA=Number.MAX_SAFE_INTEGER||9007199254740991,DA=16,LA=250,OA=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Wp.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:DA,MAX_SAFE_BUILD_LENGTH:LA,MAX_SAFE_INTEGER:PA,RELEASE_TYPES:OA,SEMVER_SPEC_VERSION:CA,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var ms=z((H4,Kp)=>{"use strict";var NA=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};Kp.exports=NA});var ii=z((Zt,Vp)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:_d,MAX_SAFE_BUILD_LENGTH:MA,MAX_LENGTH:BA}=ri(),FA=ms();Zt=Vp.exports={};var zA=Zt.re=[],UA=Zt.safeRe=[],q=Zt.src=[],GA=Zt.safeSrc=[],H=Zt.t={},qA=0,yd="[a-zA-Z0-9-]",HA=[["\\s",1],["\\d",BA],[yd,MA]],$A=t=>{for(let[e,n]of HA)t=t.split(`${e}*`).join(`${e}{0,${n}}`).split(`${e}+`).join(`${e}{1,${n}}`);return t},Q=(t,e,n)=>{let i=$A(e),s=qA++;FA(t,s,e),H[t]=s,q[s]=e,GA[s]=i,zA[s]=new RegExp(e,n?"g":void 0),UA[s]=new RegExp(i,n?"g":void 0)};Q("NUMERICIDENTIFIER","0|[1-9]\\d*");Q("NUMERICIDENTIFIERLOOSE","\\d+");Q("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${yd}*`);Q("MAINVERSION",`(${q[H.NUMERICIDENTIFIER]})\\.(${q[H.NUMERICIDENTIFIER]})\\.(${q[H.NUMERICIDENTIFIER]})`);Q("MAINVERSIONLOOSE",`(${q[H.NUMERICIDENTIFIERLOOSE]})\\.(${q[H.NUMERICIDENTIFIERLOOSE]})\\.(${q[H.NUMERICIDENTIFIERLOOSE]})`);Q("PRERELEASEIDENTIFIER",`(?:${q[H.NONNUMERICIDENTIFIER]}|${q[H.NUMERICIDENTIFIER]})`);Q("PRERELEASEIDENTIFIERLOOSE",`(?:${q[H.NONNUMERICIDENTIFIER]}|${q[H.NUMERICIDENTIFIERLOOSE]})`);Q("PRERELEASE",`(?:-(${q[H.PRERELEASEIDENTIFIER]}(?:\\.${q[H.PRERELEASEIDENTIFIER]})*))`);Q("PRERELEASELOOSE",`(?:-?(${q[H.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${q[H.PRERELEASEIDENTIFIERLOOSE]})*))`);Q("BUILDIDENTIFIER",`${yd}+`);Q("BUILD",`(?:\\+(${q[H.BUILDIDENTIFIER]}(?:\\.${q[H.BUILDIDENTIFIER]})*))`);Q("FULLPLAIN",`v?${q[H.MAINVERSION]}${q[H.PRERELEASE]}?${q[H.BUILD]}?`);Q("FULL",`^${q[H.FULLPLAIN]}$`);Q("LOOSEPLAIN",`[v=\\s]*${q[H.MAINVERSIONLOOSE]}${q[H.PRERELEASELOOSE]}?${q[H.BUILD]}?`);Q("LOOSE",`^${q[H.LOOSEPLAIN]}$`);Q("GTLT","((?:<|>)?=?)");Q("XRANGEIDENTIFIERLOOSE",`${q[H.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Q("XRANGEIDENTIFIER",`${q[H.NUMERICIDENTIFIER]}|x|X|\\*`);Q("XRANGEPLAIN",`[v=\\s]*(${q[H.XRANGEIDENTIFIER]})(?:\\.(${q[H.XRANGEIDENTIFIER]})(?:\\.(${q[H.XRANGEIDENTIFIER]})(?:${q[H.PRERELEASE]})?${q[H.BUILD]}?)?)?`);Q("XRANGEPLAINLOOSE",`[v=\\s]*(${q[H.XRANGEIDENTIFIERLOOSE]})(?:\\.(${q[H.XRANGEIDENTIFIERLOOSE]})(?:\\.(${q[H.XRANGEIDENTIFIERLOOSE]})(?:${q[H.PRERELEASELOOSE]})?${q[H.BUILD]}?)?)?`);Q("XRANGE",`^${q[H.GTLT]}\\s*${q[H.XRANGEPLAIN]}$`);Q("XRANGELOOSE",`^${q[H.GTLT]}\\s*${q[H.XRANGEPLAINLOOSE]}$`);Q("COERCEPLAIN",`(^|[^\\d])(\\d{1,${_d}})(?:\\.(\\d{1,${_d}}))?(?:\\.(\\d{1,${_d}}))?`);Q("COERCE",`${q[H.COERCEPLAIN]}(?:$|[^\\d])`);Q("COERCEFULL",q[H.COERCEPLAIN]+`(?:${q[H.PRERELEASE]})?(?:${q[H.BUILD]})?(?:$|[^\\d])`);Q("COERCERTL",q[H.COERCE],!0);Q("COERCERTLFULL",q[H.COERCEFULL],!0);Q("LONETILDE","(?:~>?)");Q("TILDETRIM",`(\\s*)${q[H.LONETILDE]}\\s+`,!0);Zt.tildeTrimReplace="$1~";Q("TILDE",`^${q[H.LONETILDE]}${q[H.XRANGEPLAIN]}$`);Q("TILDELOOSE",`^${q[H.LONETILDE]}${q[H.XRANGEPLAINLOOSE]}$`);Q("LONECARET","(?:\\^)");Q("CARETTRIM",`(\\s*)${q[H.LONECARET]}\\s+`,!0);Zt.caretTrimReplace="$1^";Q("CARET",`^${q[H.LONECARET]}${q[H.XRANGEPLAIN]}$`);Q("CARETLOOSE",`^${q[H.LONECARET]}${q[H.XRANGEPLAINLOOSE]}$`);Q("COMPARATORLOOSE",`^${q[H.GTLT]}\\s*(${q[H.LOOSEPLAIN]})$|^$`);Q("COMPARATOR",`^${q[H.GTLT]}\\s*(${q[H.FULLPLAIN]})$|^$`);Q("COMPARATORTRIM",`(\\s*)${q[H.GTLT]}\\s*(${q[H.LOOSEPLAIN]}|${q[H.XRANGEPLAIN]})`,!0);Zt.comparatorTrimReplace="$1$2$3";Q("HYPHENRANGE",`^\\s*(${q[H.XRANGEPLAIN]})\\s+-\\s+(${q[H.XRANGEPLAIN]})\\s*$`);Q("HYPHENRANGELOOSE",`^\\s*(${q[H.XRANGEPLAINLOOSE]})\\s+-\\s+(${q[H.XRANGEPLAINLOOSE]})\\s*$`);Q("STAR","(<|>)?=?\\s*\\*");Q("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Q("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var ba=z(($4,Zp)=>{"use strict";var jA=Object.freeze({loose:!0}),WA=Object.freeze({}),KA=t=>t?typeof t!="object"?jA:t:WA;Zp.exports=KA});var Ed=z((j4,Xp)=>{"use strict";var Jp=/^[0-9]+$/,Yp=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let n=Jp.test(t),i=Jp.test(e);return n&&i&&(t=+t,e=+e),t===e?0:n&&!i?-1:i&&!n?1:t<e?-1:1},VA=(t,e)=>Yp(e,t);Xp.exports={compareIdentifiers:Yp,rcompareIdentifiers:VA}});var Ye=z((W4,eg)=>{"use strict";var va=ms(),{MAX_LENGTH:Qp,MAX_SAFE_INTEGER:Sa}=ri(),{safeRe:Ia,t:Aa}=ii(),ZA=ba(),{compareIdentifiers:bd}=Ed(),JA=(t,e)=>{let n=e.split(".");if(n.length>t.length)return!1;for(let i=0;i<n.length;i++)if(bd(t[i],n[i])!==0)return!1;return!0},vd=class t{constructor(e,n){if(n=ZA(n),e instanceof t){if(e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Qp)throw new TypeError(`version is longer than ${Qp} characters`);va("SemVer",e,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let i=e.trim().match(n.loose?Ia[Aa.LOOSE]:Ia[Aa.FULL]);if(!i)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>Sa||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Sa||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Sa||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let a=+s;if(a>=0&&a<Sa)return a}return s}):this.prerelease=[],this.build=i[5]?i[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(va("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let n=0;do{let i=this.prerelease[n],s=e.prerelease[n];if(va("prerelease compare",n,i,s),i===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(i===void 0)return-1;if(i===s)continue;return bd(i,s)}while(++n)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let n=0;do{let i=this.build[n],s=e.build[n];if(va("build compare",n,i,s),i===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(i===void 0)return-1;if(i===s)continue;return bd(i,s)}while(++n)}inc(e,n,i){if(e.startsWith("pre")){if(!n&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(n){let s=`-${n}`.match(this.options.loose?Ia[Aa.PRERELEASELOOSE]:Ia[Aa.PRERELEASE]);if(!s||s[1]!==n)throw new Error(`invalid identifier: ${n}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,i),this.inc("pre",n,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",n,i),this.inc("pre",n,i);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let a=this.prerelease.length;for(;--a>=0;)typeof this.prerelease[a]=="number"&&(this.prerelease[a]++,a=-2);if(a===-1){if(n===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(n){let a=[n,s];if(i===!1&&(a=[n]),JA(this.prerelease,n)){let l=this.prerelease[n.split(".").length];isNaN(l)&&(this.prerelease=a)}else this.prerelease=a}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};eg.exports=vd});var Un=z((K4,ng)=>{"use strict";var tg=Ye(),YA=(t,e,n=!1)=>{if(t instanceof tg)return t;try{return new tg(t,e)}catch(i){if(!n)return null;throw i}};ng.exports=YA});var ig=z((V4,rg)=>{"use strict";var XA=Un(),QA=(t,e)=>{let n=XA(t,e);return n?n.version:null};rg.exports=QA});var og=z((Z4,sg)=>{"use strict";var e2=Un(),t2=(t,e)=>{let n=e2(t.trim().replace(/^[=v]+/,""),e);return n?n.version:null};sg.exports=t2});var lg=z((J4,cg)=>{"use strict";var ag=Ye(),n2=(t,e,n,i,s)=>{typeof n=="string"&&(s=i,i=n,n=void 0);try{return new ag(t instanceof ag?t.version:t,n).inc(e,i,s).version}catch{return null}};cg.exports=n2});var fg=z((Y4,ug)=>{"use strict";var dg=Un(),r2=(t,e)=>{let n=dg(t,null,!0),i=dg(e,null,!0),s=n.compare(i);if(s===0)return null;let a=s>0,l=a?n:i,u=a?i:n,f=!!l.prerelease.length;if(!!u.prerelease.length&&!f){if(!u.patch&&!u.minor)return"major";if(u.compareMain(l)===0)return u.minor&&!u.patch?"minor":"patch"}let m=f?"pre":"";return n.major!==i.major?m+"major":n.minor!==i.minor?m+"minor":n.patch!==i.patch?m+"patch":"prerelease"};ug.exports=r2});var xg=z((X4,hg)=>{"use strict";var i2=Ye(),s2=(t,e)=>new i2(t,e).major;hg.exports=s2});var gg=z((Q4,pg)=>{"use strict";var o2=Ye(),a2=(t,e)=>new o2(t,e).minor;pg.exports=a2});var wg=z((eM,mg)=>{"use strict";var c2=Ye(),l2=(t,e)=>new c2(t,e).patch;mg.exports=l2});var yg=z((tM,_g)=>{"use strict";var d2=Un(),u2=(t,e)=>{let n=d2(t,e);return n&&n.prerelease.length?n.prerelease:null};_g.exports=u2});var bt=z((nM,bg)=>{"use strict";var Eg=Ye(),f2=(t,e,n)=>new Eg(t,n).compare(new Eg(e,n));bg.exports=f2});var Sg=z((rM,vg)=>{"use strict";var h2=bt(),x2=(t,e,n)=>h2(e,t,n);vg.exports=x2});var Ag=z((iM,Ig)=>{"use strict";var p2=bt(),g2=(t,e)=>p2(t,e,!0);Ig.exports=g2});var Ta=z((sM,Rg)=>{"use strict";var Tg=Ye(),m2=(t,e,n)=>{let i=new Tg(t,n),s=new Tg(e,n);return i.compare(s)||i.compareBuild(s)};Rg.exports=m2});var Cg=z((oM,kg)=>{"use strict";var w2=Ta(),_2=(t,e)=>t.sort((n,i)=>w2(n,i,e));kg.exports=_2});var Dg=z((aM,Pg)=>{"use strict";var y2=Ta(),E2=(t,e)=>t.sort((n,i)=>y2(i,n,e));Pg.exports=E2});var ws=z((cM,Lg)=>{"use strict";var b2=bt(),v2=(t,e,n)=>b2(t,e,n)>0;Lg.exports=v2});var Ra=z((lM,Og)=>{"use strict";var S2=bt(),I2=(t,e,n)=>S2(t,e,n)<0;Og.exports=I2});var Sd=z((dM,Ng)=>{"use strict";var A2=bt(),T2=(t,e,n)=>A2(t,e,n)===0;Ng.exports=T2});var Id=z((uM,Mg)=>{"use strict";var R2=bt(),k2=(t,e,n)=>R2(t,e,n)!==0;Mg.exports=k2});var ka=z((fM,Bg)=>{"use strict";var C2=bt(),P2=(t,e,n)=>C2(t,e,n)>=0;Bg.exports=P2});var Ca=z((hM,Fg)=>{"use strict";var D2=bt(),L2=(t,e,n)=>D2(t,e,n)<=0;Fg.exports=L2});var Ad=z((xM,zg)=>{"use strict";var O2=Sd(),N2=Id(),M2=ws(),B2=ka(),F2=Ra(),z2=Ca(),U2=(t,e,n,i)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t===n;case"!==":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t!==n;case"":case"=":case"==":return O2(t,n,i);case"!=":return N2(t,n,i);case">":return M2(t,n,i);case">=":return B2(t,n,i);case"<":return F2(t,n,i);case"<=":return z2(t,n,i);default:throw new TypeError(`Invalid operator: ${e}`)}};zg.exports=U2});var Gg=z((pM,Ug)=>{"use strict";var G2=Ye(),q2=Un(),{safeRe:Pa,t:Da}=ii(),H2=(t,e)=>{if(t instanceof G2)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let n=null;if(!e.rtl)n=t.match(e.includePrerelease?Pa[Da.COERCEFULL]:Pa[Da.COERCE]);else{let f=e.includePrerelease?Pa[Da.COERCERTLFULL]:Pa[Da.COERCERTL],x;for(;(x=f.exec(t))&&(!n||n.index+n[0].length!==t.length);)(!n||x.index+x[0].length!==n.index+n[0].length)&&(n=x),f.lastIndex=x.index+x[1].length+x[2].length;f.lastIndex=-1}if(n===null)return null;let i=n[2],s=n[3]||"0",a=n[4]||"0",l=e.includePrerelease&&n[5]?`-${n[5]}`:"",u=e.includePrerelease&&n[6]?`+${n[6]}`:"";return q2(`${i}.${s}.${a}${l}${u}`,e)};Ug.exports=H2});var Hg=z((gM,qg)=>{"use strict";var $2=Un(),j2=ri(),W2=Ye(),K2=(t,e,n)=>{if(!j2.RELEASE_TYPES.includes(e))return null;let i=V2(t,n);return i&&Z2(i,e)},V2=(t,e)=>{let n=t instanceof W2?t.version:t;return $2(n,e)},Z2=(t,e)=>{if(J2(e))return t.version;switch(t.prerelease=[],e){case"major":t.minor=0,t.patch=0;break;case"minor":t.patch=0;break}return t.format()},J2=t=>t.startsWith("pre");qg.exports=K2});var jg=z((mM,$g)=>{"use strict";var Td=class{constructor(){this.max=1e3,this.map=new Map}get(e){let n=this.map.get(e);if(n!==void 0)return this.map.delete(e),this.map.set(e,n),n}delete(e){return this.map.delete(e)}set(e,n){if(!this.delete(e)&&n!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(e,n)}return this}};$g.exports=Td});var vt=z((wM,Zg)=>{"use strict";var Y2=/\s+/g,Rd=class t{constructor(e,n){if(n=Q2(n),e instanceof t)return e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease?e:new t(e.raw,n);if(e instanceof kd)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=e.trim().replace(Y2," "),this.set=this.raw.split("||").map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter(s=>!Kg(s[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&cT(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let n=this.set[e];for(let i=0;i<n.length;i++)i>0&&(this.formatted+=" "),this.formatted+=n[i].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(aT,"");let i=((this.options.includePrerelease&&sT)|(this.options.loose&&oT))+":"+e,s=Wg.get(i);if(s)return s;let a=this.options.loose,l=a?st[Xe.HYPHENRANGELOOSE]:st[Xe.HYPHENRANGE];e=e.replace(l,_T(this.options.includePrerelease)),ye("hyphen replace",e),e=e.replace(st[Xe.COMPARATORTRIM],nT),ye("comparator trim",e),e=e.replace(st[Xe.TILDETRIM],rT),ye("tilde trim",e),e=e.replace(st[Xe.CARETTRIM],iT),ye("caret trim",e);let u=e.split(" ").map(g=>lT(g,this.options)).join(" ").split(/\s+/).map(g=>wT(g,this.options));a&&(u=u.filter(g=>(ye("loose invalid filter",g,this.options),!!g.match(st[Xe.COMPARATORLOOSE])))),ye("range list",u);let f=new Map,x=u.map(g=>new kd(g,this.options));for(let g of x){if(Kg(g))return[g];f.set(g.value,g)}f.size>1&&f.has("")&&f.delete("");let m=[...f.values()];return Wg.set(i,m),m}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(i=>Vg(i,n)&&e.set.some(s=>Vg(s,n)&&i.every(a=>s.every(l=>a.intersects(l,n)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new eT(e,this.options)}catch{return!1}for(let n=0;n<this.set.length;n++)if(yT(this.set[n],e,this.options))return!0;return!1}};Zg.exports=Rd;var X2=jg(),Wg=new X2,Q2=ba(),kd=_s(),ye=ms(),eT=Ye(),{safeRe:st,src:tT,t:Xe,comparatorTrimReplace:nT,tildeTrimReplace:rT,caretTrimReplace:iT}=ii(),{FLAG_INCLUDE_PRERELEASE:sT,FLAG_LOOSE:oT}=ri(),aT=new RegExp(tT[Xe.BUILD],"g"),Kg=t=>t.value==="<0.0.0-0",cT=t=>t.value==="",Vg=(t,e)=>{let n=!0,i=t.slice(),s=i.pop();for(;n&&i.length;)n=i.every(a=>s.intersects(a,e)),s=i.pop();return n},lT=(t,e)=>(t=t.replace(st[Xe.BUILD],""),ye("comp",t,e),t=hT(t,e),ye("caret",t),t=uT(t,e),ye("tildes",t),t=pT(t,e),ye("xrange",t),t=mT(t,e),ye("stars",t),t),Ge=t=>!t||t.toLowerCase()==="x"||t==="*",dT=(t,e,n)=>Ge(t)&&!Ge(e)||Ge(e)&&n&&!Ge(n),uT=(t,e)=>t.trim().split(/\s+/).map(n=>fT(n,e)).join(" "),fT=(t,e)=>{let n=e.loose?st[Xe.TILDELOOSE]:st[Xe.TILDE],i=e.includePrerelease?"-0":"";return t.replace(n,(s,a,l,u,f)=>{ye("tilde",t,s,a,l,u,f);let x;return Ge(a)?x="":Ge(l)?x=`>=${a}.0.0${i} <${+a+1}.0.0-0`:Ge(u)?x=`>=${a}.${l}.0${i} <${a}.${+l+1}.0-0`:f?(ye("replaceTilde pr",f),x=`>=${a}.${l}.${u}-${f} <${a}.${+l+1}.0-0`):x=`>=${a}.${l}.${u} <${a}.${+l+1}.0-0`,ye("tilde return",x),x})},hT=(t,e)=>t.trim().split(/\s+/).map(n=>xT(n,e)).join(" "),xT=(t,e)=>{ye("caret",t,e);let n=e.loose?st[Xe.CARETLOOSE]:st[Xe.CARET],i=e.includePrerelease?"-0":"";return t.replace(n,(s,a,l,u,f)=>{ye("caret",t,s,a,l,u,f);let x;return Ge(a)?x="":Ge(l)?x=`>=${a}.0.0${i} <${+a+1}.0.0-0`:Ge(u)?a==="0"?x=`>=${a}.${l}.0${i} <${a}.${+l+1}.0-0`:x=`>=${a}.${l}.0${i} <${+a+1}.0.0-0`:f?(ye("replaceCaret pr",f),a==="0"?l==="0"?x=`>=${a}.${l}.${u}-${f} <${a}.${l}.${+u+1}-0`:x=`>=${a}.${l}.${u}-${f} <${a}.${+l+1}.0-0`:x=`>=${a}.${l}.${u}-${f} <${+a+1}.0.0-0`):(ye("no pr"),a==="0"?l==="0"?x=`>=${a}.${l}.${u} <${a}.${l}.${+u+1}-0`:x=`>=${a}.${l}.${u} <${a}.${+l+1}.0-0`:x=`>=${a}.${l}.${u} <${+a+1}.0.0-0`),ye("caret return",x),x})},pT=(t,e)=>(ye("replaceXRanges",t,e),t.split(/\s+/).map(n=>gT(n,e)).join(" ")),gT=(t,e)=>{t=t.trim();let n=e.loose?st[Xe.XRANGELOOSE]:st[Xe.XRANGE];return t.replace(n,(i,s,a,l,u,f)=>{if(ye("xRange",t,i,s,a,l,u,f),dT(a,l,u))return t;let x=Ge(a),m=x||Ge(l),g=m||Ge(u),v=g;return s==="="&&v&&(s=""),f=e.includePrerelease?"-0":"",x?s===">"||s==="<"?i="<0.0.0-0":i="*":s&&v?(m&&(l=0),u=0,s===">"?(s=">=",m?(a=+a+1,l=0,u=0):(l=+l+1,u=0)):s==="<="&&(s="<",m?a=+a+1:l=+l+1),s==="<"&&(f="-0"),i=`${s+a}.${l}.${u}${f}`):m?i=`>=${a}.0.0${f} <${+a+1}.0.0-0`:g&&(i=`>=${a}.${l}.0${f} <${a}.${+l+1}.0-0`),ye("xRange return",i),i})},mT=(t,e)=>(ye("replaceStars",t,e),t.trim().replace(st[Xe.STAR],"")),wT=(t,e)=>(ye("replaceGTE0",t,e),t.trim().replace(st[e.includePrerelease?Xe.GTE0PRE:Xe.GTE0],"")),_T=t=>(e,n,i,s,a,l,u,f,x,m,g,v)=>(Ge(i)?n="":Ge(s)?n=`>=${i}.0.0${t?"-0":""}`:Ge(a)?n=`>=${i}.${s}.0${t?"-0":""}`:l?n=`>=${n}`:n=`>=${n}${t?"-0":""}`,Ge(x)?f="":Ge(m)?f=`<${+x+1}.0.0-0`:Ge(g)?f=`<${x}.${+m+1}.0-0`:v?f=`<=${x}.${m}.${g}-${v}`:t?f=`<${x}.${m}.${+g+1}-0`:f=`<=${f}`,`${n} ${f}`.trim()),yT=(t,e,n)=>{for(let i=0;i<t.length;i++)if(!t[i].test(e))return!1;if(e.prerelease.length&&!n.includePrerelease){for(let i=0;i<t.length;i++)if(ye(t[i].semver),t[i].semver!==kd.ANY&&t[i].semver.prerelease.length>0){let s=t[i].semver;if(s.major===e.major&&s.minor===e.minor&&s.patch===e.patch)return!0}return!1}return!0}});var _s=z((_M,tm)=>{"use strict";var ys=Symbol("SemVer ANY"),Dd=class t{static get ANY(){return ys}constructor(e,n){if(n=Jg(n),e instanceof t){if(e.loose===!!n.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Pd("comparator",e,n),this.options=n,this.loose=!!n.loose,this.parse(e),this.semver===ys?this.value="":this.value=this.operator+this.semver.version,Pd("comp",this)}parse(e){let n=this.options.loose?Yg[Xg.COMPARATORLOOSE]:Yg[Xg.COMPARATOR],i=e.match(n);if(!i)throw new TypeError(`Invalid comparator: ${e}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new Qg(i[2],this.options.loose):this.semver=ys}toString(){return this.value}test(e){if(Pd("Comparator.test",e,this.options.loose),this.semver===ys||e===ys)return!0;if(typeof e=="string")try{e=new Qg(e,this.options)}catch{return!1}return Cd(e,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new em(e.value,n).test(this.value):e.operator===""?e.value===""?!0:new em(this.value,n).test(e.semver):(n=Jg(n),n.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!n.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Cd(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Cd(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};tm.exports=Dd;var Jg=ba(),{safeRe:Yg,t:Xg}=ii(),Cd=Ad(),Pd=ms(),Qg=Ye(),em=vt()});var Es=z((yM,nm)=>{"use strict";var ET=vt(),bT=(t,e,n)=>{try{e=new ET(e,n)}catch{return!1}return e.test(t)};nm.exports=bT});var im=z((EM,rm)=>{"use strict";var vT=vt(),ST=(t,e)=>new vT(t,e).set.map(n=>n.map(i=>i.value).join(" ").trim().split(" "));rm.exports=ST});var om=z((bM,sm)=>{"use strict";var IT=Ye(),AT=vt(),TT=(t,e,n)=>{let i=null,s=null,a=null;try{a=new AT(e,n)}catch{return null}return t.forEach(l=>{a.test(l)&&(!i||s.compare(l)===-1)&&(i=l,s=new IT(i,n))}),i};sm.exports=TT});var cm=z((vM,am)=>{"use strict";var RT=Ye(),kT=vt(),CT=(t,e,n)=>{let i=null,s=null,a=null;try{a=new kT(e,n)}catch{return null}return t.forEach(l=>{a.test(l)&&(!i||s.compare(l)===1)&&(i=l,s=new RT(i,n))}),i};am.exports=CT});var um=z((SM,dm)=>{"use strict";var Ld=Ye(),PT=vt(),lm=ws(),DT=(t,e)=>{t=new PT(t,e);let n=new Ld("0.0.0");if(t.test(n)||(n=new Ld("0.0.0-0"),t.test(n)))return n;n=null;for(let i=0;i<t.set.length;++i){let s=t.set[i],a=null;s.forEach(l=>{let u=new Ld(l.semver.version);switch(l.operator){case">":u.prerelease.length===0?u.patch++:u.prerelease.push(0),u.raw=u.format();case"":case">=":(!a||lm(u,a))&&(a=u);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),a&&(!n||lm(n,a))&&(n=a)}return n&&t.test(n)?n:null};dm.exports=DT});var hm=z((IM,fm)=>{"use strict";var LT=vt(),OT=(t,e)=>{try{return new LT(t,e).range||"*"}catch{return null}};fm.exports=OT});var La=z((AM,mm)=>{"use strict";var NT=Ye(),gm=_s(),{ANY:MT}=gm,BT=vt(),FT=Es(),xm=ws(),pm=Ra(),zT=Ca(),UT=ka(),GT=(t,e,n,i)=>{t=new NT(t,i),e=new BT(e,i);let s,a,l,u,f;switch(n){case">":s=xm,a=zT,l=pm,u=">",f=">=";break;case"<":s=pm,a=UT,l=xm,u="<",f="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(FT(t,e,i))return!1;for(let x=0;x<e.set.length;++x){let m=e.set[x],g=null,v=null;if(m.forEach(w=>{w.semver===MT&&(w=new gm(">=0.0.0")),g=g||w,v=v||w,s(w.semver,g.semver,i)?g=w:l(w.semver,v.semver,i)&&(v=w)}),g.operator===u||g.operator===f||(!v.operator||v.operator===u)&&a(t,v.semver))return!1;if(v.operator===f&&l(t,v.semver))return!1}return!0};mm.exports=GT});var _m=z((TM,wm)=>{"use strict";var qT=La(),HT=(t,e,n)=>qT(t,e,">",n);wm.exports=HT});var Em=z((RM,ym)=>{"use strict";var $T=La(),jT=(t,e,n)=>$T(t,e,"<",n);ym.exports=jT});var Sm=z((kM,vm)=>{"use strict";var bm=vt(),WT=(t,e,n)=>(t=new bm(t,n),e=new bm(e,n),t.intersects(e,n));vm.exports=WT});var Am=z((CM,Im)=>{"use strict";var KT=Es(),VT=bt();Im.exports=(t,e,n)=>{let i=[],s=null,a=null,l=t.sort((m,g)=>VT(m,g,n));for(let m of l)KT(m,e,n)?(a=m,s||(s=m)):(a&&i.push([s,a]),a=null,s=null);s&&i.push([s,null]);let u=[];for(let[m,g]of i)m===g?u.push(m):!g&&m===l[0]?u.push("*"):g?m===l[0]?u.push(`<=${g}`):u.push(`${m} - ${g}`):u.push(`>=${m}`);let f=u.join(" || "),x=typeof e.raw=="string"?e.raw:String(e);return f.length<x.length?f:e}});var Dm=z((PM,Pm)=>{"use strict";var Tm=vt(),Md=_s(),{ANY:Od}=Md,Nd=Es(),Bd=bt(),ZT=(t,e,n={})=>{if(t===e)return!0;t=new Tm(t,n),e=new Tm(e,n);let i=!1;e:for(let s of t.set){for(let a of e.set){let l=YT(s,a,n);if(i=i||l!==null,l)continue e}if(i)return!1}return!0},JT=[new Md(">=0.0.0-0")],Rm=[new Md(">=0.0.0")],YT=(t,e,n)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===Od){if(e.length===1&&e[0].semver===Od)return!0;n.includePrerelease?t=JT:t=Rm}if(e.length===1&&e[0].semver===Od){if(n.includePrerelease)return!0;e=Rm}let i=new Set,s,a;for(let w of t)w.operator===">"||w.operator===">="?s=km(s,w,n):w.operator==="<"||w.operator==="<="?a=Cm(a,w,n):i.add(w.semver);if(i.size>1)return null;let l;if(s&&a){if(l=Bd(s.semver,a.semver,n),l>0)return null;if(l===0&&(s.operator!==">="||a.operator!=="<="))return null}for(let w of i){if(s&&!Nd(w,String(s),n)||a&&!Nd(w,String(a),n))return null;for(let b of e)if(!Nd(w,String(b),n))return!1;return!0}let u,f,x,m,g=a&&!n.includePrerelease&&a.semver.prerelease.length?a.semver:!1,v=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;g&&g.prerelease.length===1&&a.operator==="<"&&g.prerelease[0]===0&&(g=!1);for(let w of e){if(m=m||w.operator===">"||w.operator===">=",x=x||w.operator==="<"||w.operator==="<=",s){if(v&&w.semver.prerelease&&w.semver.prerelease.length&&w.semver.major===v.major&&w.semver.minor===v.minor&&w.semver.patch===v.patch&&(v=!1),w.operator===">"||w.operator===">="){if(u=km(s,w,n),u===w&&u!==s)return!1}else if(s.operator===">="&&!w.test(s.semver))return!1}if(a){if(g&&w.semver.prerelease&&w.semver.prerelease.length&&w.semver.major===g.major&&w.semver.minor===g.minor&&w.semver.patch===g.patch&&(g=!1),w.operator==="<"||w.operator==="<="){if(f=Cm(a,w,n),f===w&&f!==a)return!1}else if(a.operator==="<="&&!w.test(a.semver))return!1}if(!w.operator&&(a||s)&&l!==0)return!1}return!(s&&x&&!a&&l!==0||a&&m&&!s&&l!==0||v||g)},km=(t,e,n)=>{if(!t)return e;let i=Bd(t.semver,e.semver,n);return i>0?t:i<0||e.operator===">"&&t.operator===">="?e:t},Cm=(t,e,n)=>{if(!t)return e;let i=Bd(t.semver,e.semver,n);return i<0?t:i>0||e.operator==="<"&&t.operator==="<="?e:t};Pm.exports=ZT});var Mm=z((DM,Nm)=>{"use strict";var Fd=ii(),Lm=ri(),XT=Ye(),Om=Ed(),QT=Un(),eR=ig(),tR=og(),nR=lg(),rR=fg(),iR=xg(),sR=gg(),oR=wg(),aR=yg(),cR=bt(),lR=Sg(),dR=Ag(),uR=Ta(),fR=Cg(),hR=Dg(),xR=ws(),pR=Ra(),gR=Sd(),mR=Id(),wR=ka(),_R=Ca(),yR=Ad(),ER=Gg(),bR=Hg(),vR=_s(),SR=vt(),IR=Es(),AR=im(),TR=om(),RR=cm(),kR=um(),CR=hm(),PR=La(),DR=_m(),LR=Em(),OR=Sm(),NR=Am(),MR=Dm();Nm.exports={parse:QT,valid:eR,clean:tR,inc:nR,diff:rR,major:iR,minor:sR,patch:oR,prerelease:aR,compare:cR,rcompare:lR,compareLoose:dR,compareBuild:uR,sort:fR,rsort:hR,gt:xR,lt:pR,eq:gR,neq:mR,gte:wR,lte:_R,cmp:yR,coerce:ER,truncate:bR,Comparator:vR,Range:SR,satisfies:IR,toComparators:AR,maxSatisfying:TR,minSatisfying:RR,minVersion:kR,validRange:CR,outside:PR,gtr:DR,ltr:LR,intersects:OR,simplifyRange:NR,subset:MR,SemVer:XT,re:Fd.re,src:Fd.src,tokens:Fd.t,SEMVER_SPEC_VERSION:Lm.SEMVER_SPEC_VERSION,RELEASE_TYPES:Lm.RELEASE_TYPES,compareIdentifiers:Om.compareIdentifiers,rcompareIdentifiers:Om.rcompareIdentifiers}});import{spawn as xk}from"node:child_process";import{mkdir as pk,unlink as gk,writeFile as mk}from"node:fs/promises";import{dirname as wk,join as _k}from"node:path";function ci(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function yk(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${ci(n)}</key>
21
+ <string>${ci(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function W1(t,e){return new Promise((r,i)=>{let o=z1(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 Zr,ds,ua,tl,pp=nt(()=>{"use strict";ne();Zr=H("supervisor.launchd"),ds="ai.coze.bridge",ua=W1,tl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function Ek(t,e){return new Promise((n,i)=>{let s=xk(t,e,{stdio:["ignore","pipe","pipe"]}),a="";s.stderr?.on("data",l=>{a+=l.toString("utf8")}),s.on("error",i),s.on("close",l=>{l===0?n():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${a.trim()}`))})})}var ai,Ss,Na,Hd,Jm=at(()=>{"use strict";oe();ai=$("supervisor.launchd"),Ss="ai.coze.bridge",Na=Ek,Hd={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>${ds}</string>
31
+ <string>${Ss}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Yr(t.nodeBin)}</string>
35
- <string>${Yr(t.entry)}</string>
34
+ <string>${ci(t.nodeBin)}</string>
35
+ <string>${ci(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>${Yr(t.logFile)}</string>
45
+ <string>${ci(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Yr(t.logFile)}</string>${K1(t.env)}
47
+ <string>${ci(t.logFile)}</string>${yk(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return j1(t.homeDir,"Library","LaunchAgents",`${ds}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await U1(q1(i),{recursive:!0}),await G1(i,this.renderConfig(t),"utf8"),Zr.info("plist written",{plistPath:i,activate:r}),!r)return;await ua("launchctl",["unload","-w",i]).catch(c=>Zr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ua("launchctl",["load","-w",i]),Zr.info("launchd job loaded",{label:ds});let o=process.getuid?.()??0;await ua("launchctl",["kickstart","-k",`gui/${o}/${ds}`]),Zr.info("launchd job kickstarted",{label:ds,uid:o})},async uninstall(t){let e=this.configPath(t);await ua("launchctl",["unload","-w",e]).catch(r=>Zr.warn("launchctl unload failed (ignored)",{err:String(r)})),await H1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Zr.info("launchd job removed",{plistPath:e})}}});import{spawn as $1}from"node:child_process";import{mkdir as V1,unlink as J1,writeFile as Z1}from"node:fs/promises";import{dirname as Y1,join as gp}from"node:path";function ha(t,e){return t.isRoot?e:["--user",...e]}function Q1(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function xa(t,e){return new Promise((r,i)=>{let o=$1(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 fa,Xr,X1,nl,mp=nt(()=>{"use strict";ne();fa=H("supervisor.systemd"),Xr="coze-bridge.service",X1="/etc/systemd/system";nl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return _k(t.homeDir,"Library","LaunchAgents",`${Ss}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await pk(wk(i),{recursive:!0}),await mk(i,this.renderConfig(t),"utf8"),ai.info("plist written",{plistPath:i,activate:n}),!n)return;await Na("launchctl",["unload","-w",i]).catch(a=>ai.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await Na("launchctl",["load","-w",i]),ai.info("launchd job loaded",{label:Ss});let s=process.getuid?.()??0;await Na("launchctl",["kickstart","-k",`gui/${s}/${Ss}`]),ai.info("launchd job kickstarted",{label:Ss,uid:s})},async uninstall(t){let e=this.configPath(t);await Na("launchctl",["unload","-w",e]).catch(n=>ai.warn("launchctl unload failed (ignored)",{err:String(n)})),await gk(e).catch(n=>{if(n.code!=="ENOENT")throw n}),ai.info("launchd job removed",{plistPath:e})}}});import{spawn as bk}from"node:child_process";import{mkdir as vk,unlink as Sk,writeFile as Ik}from"node:fs/promises";import{dirname as Ak,join as Ym}from"node:path";function Ba(t,e){return t.isRoot?e:["--user",...e]}function Rk(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function Fa(t,e){return new Promise((n,i)=>{let s=bk(t,e,{stdio:["ignore","pipe","pipe"]}),a="";s.stderr?.on("data",l=>{a+=l.toString("utf8")}),s.on("error",i),s.on("close",l=>{l===0?n():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${a.trim()}`))})})}var Ma,li,Tk,$d,Xm=at(()=>{"use strict";oe();Ma=$("supervisor.systemd"),li="coze-bridge.service",Tk="/etc/systemd/system";$d={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
- ${Q1(t.env)}
62
+ ${Rk(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?gp(X1,Xr):gp(t.homeDir,".config","systemd","user",Xr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await V1(Y1(i),{recursive:!0}),await Z1(i,this.renderConfig(t),"utf8"),fa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await xa("systemctl",ha(t,["daemon-reload"])),await xa("systemctl",ha(t,r?["enable","--now",Xr]:["enable",Xr])),fa.info("systemd unit enabled",{unitName:Xr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await xa("systemctl",ha(t,["disable","--now",Xr])).catch(r=>fa.warn("systemctl disable failed (ignored)",{err:String(r)})),await J1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await xa("systemctl",ha(t,["daemon-reload"])).catch(()=>{}),fa.info("systemd unit removed",{unitPath:e})}}});import{spawn as eI}from"node:child_process";import{join as tI}from"node:path";function wp(t,e){return new Promise((r,i)=>{let o=eI(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 rl,pa,il,_p=nt(()=>{"use strict";ne();rl=H("supervisor.taskscheduler"),pa="CozeBridge",il={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Ym(Tk,li):Ym(t.homeDir,".config","systemd","user",li)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),s=t.isRoot?"system":"user";await vk(Ak(i),{recursive:!0}),await Ik(i,this.renderConfig(t),"utf8"),Ma.info("systemd unit written",{unitPath:i,mode:s,activate:n}),await Fa("systemctl",Ba(t,["daemon-reload"])),await Fa("systemctl",Ba(t,n?["enable","--now",li]:["enable",li])),Ma.info("systemd unit enabled",{unitName:li,mode:s,activate:n})},async uninstall(t){let e=this.configPath(t);await Fa("systemctl",Ba(t,["disable","--now",li])).catch(n=>Ma.warn("systemctl disable failed (ignored)",{err:String(n)})),await Sk(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Fa("systemctl",Ba(t,["daemon-reload"])).catch(()=>{}),Ma.info("systemd unit removed",{unitPath:e})}}});import{spawn as kk}from"node:child_process";import{join as Ck}from"node:path";function Qm(t,e){return new Promise((n,i)=>{let s=kk(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),a="";s.stderr?.on("data",l=>{a+=l.toString("utf8")}),s.on("error",i),s.on("close",l=>{l===0?n():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${a.trim()}`))})})}var jd,za,Wd,ew=at(()=>{"use strict";oe();jd=$("supervisor.taskscheduler"),za="CozeBridge",Wd={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,51 +86,50 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return tI(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 wp("schtasks",["/Create","/SC","ONLOGON","/TN",pa,"/TR",r,"/RU",t.userName,"/F"]),rl.info("task scheduler entry created",{task:pa,logFile:t.logFile})},async uninstall(t){await wp("schtasks",["/Delete","/TN",pa,"/F"]).catch(e=>rl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),rl.info("task scheduler entry removed",{task:pa})}}});var yp={};Ca(yp,{buildContext:()=>aI,getSupervisor:()=>iI,launchdSupervisor:()=>tl,systemdSupervisor:()=>nl,taskSchedulerSupervisor:()=>il});import{homedir as nI,userInfo as rI}from"node:os";function iI(t=process.platform){switch(t){case"darwin":return tl;case"linux":return nl;case"win32":return il;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function oI(){let t={};for(let e of sI){let r=process.env[e];r&&(t[e]=r)}return t}function aI(){let t=Y();return{nodeBin:process.execPath,entry:Wd(t),logFile:t.logFile,homeDir:nI(),userName:rI().username,isRoot:process.getuid?.()===0,env:oI()}}var sI,Ep=nt(()=>{"use strict";Re();ia();pp();mp();_p();sI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();on();var Ll=H("acp-installer-warmup"),Vg=["claude-code","codex"];async function Nl(t={}){let e=t.ensure??fr,i=(await Promise.allSettled(Vg.map(async o=>{let c=await e(o);Ll.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Ll.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))})}un();ne();import{readdir as lm}from"node:fs/promises";import{mkdir as zl,readFile as cm,writeFile as Ul}from"node:fs/promises";import{join as Ma}from"node:path";var dm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function hr(t,e,r){await zl(t,{recursive:!0});let i=dm[e],o=Ma(t,i);return await Ul(o,r??"","utf8"),o}async function Ba(t,e,r){let i=Ma(t,".claude");await zl(i,{recursive:!0});let o=Ma(i,"settings.local.json"),c={};try{let u=await cm(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 Ul(o,JSON.stringify(c,null,2),"utf8"),o}var Xe=H("agent-detail-sync"),um=6e4,fm=5*6e4,ys=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await lm(r)}catch(o){Xe.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Xe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await De(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Xe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(l){Xe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(l)})}}})),Xe.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){Xe.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Xe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await De(e,this.opts.paths);if(!i){Xe.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){Xe.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,fm):um;this.retryQueue.set(e,{dueAt:Date.now()+g,currentDelay:g});return}if(o.agentId&&o.agentId!==e){Xe.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"?(Xe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Xe.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Xe.debug("detail sync: no diff",{agentId:e});return}await ze(i,this.opts.paths),Xe.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}),Xe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await hr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var id=Ht(_u(),1);import{createHash as K_}from"node:crypto";import{lstat as Yc,mkdir as Xc,readFile as ho,readdir as s0,rm as Qc,stat as n0,writeFile as ed}from"node:fs/promises";import{dirname as W_,join as Ve,normalize as $_,relative as rd,resolve as td,sep as o0}from"node:path";import{Readable as a0}from"node:stream";import{pipeline as c0}from"node:stream/promises";import Lm from"events";import rt from"fs";import{EventEmitter as Mc}from"node:events";import ef from"node:stream";import{StringDecoder as Nm}from"node:string_decoder";import rf from"node:path";import Ir from"node:fs";import{dirname as Vm,parse as Jm}from"path";import{EventEmitter as rw}from"events";import mc from"assert";import{Buffer as Kn}from"buffer";import*as Su from"zlib";import iw from"zlib";import{posix as wr}from"node:path";import{basename as Dw}from"node:path";import Xs from"fs";import Dt from"fs";import Du from"path";import{win32 as Gw}from"node:path";import Fu from"path";import _f from"node:fs";import s_ from"node:assert";import{randomBytes as yf}from"node:crypto";import ie from"node:fs";import Be from"node:path";import Ef from"fs";import ao from"node:fs";import Ai from"node:path";import at from"node:fs";import f_ from"node:fs/promises";import to from"node:path";import{join as Pf}from"node:path";import ot from"node:fs";import Nf from"node:path";var Pm=Object.defineProperty,Om=(t,e)=>{for(var r in e)Pm(t,r,{get:e[r],enumerable:!0})},yu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Mm=t=>!!t&&typeof t=="object"&&(t instanceof Vn||t instanceof ef||Bm(t)||Fm(t)),Bm=t=>!!t&&typeof t=="object"&&t instanceof Mc&&typeof t.pipe=="function"&&t.pipe!==ef.Writable.prototype.pipe,Fm=t=>!!t&&typeof t=="object"&&t instanceof Mc&&typeof t.write=="function"&&typeof t.end=="function",Gt=Symbol("EOF"),qt=Symbol("maybeEmitEnd"),hn=Symbol("emittedEnd"),Is=Symbol("emittingEnd"),di=Symbol("emittedError"),As=Symbol("closed"),Eu=Symbol("read"),ks=Symbol("flush"),bu=Symbol("flushChunk"),mt=Symbol("encoding"),mr=Symbol("decoder"),Ue=Symbol("flowing"),li=Symbol("paused"),br=Symbol("resume"),He=Symbol("buffer"),Qe=Symbol("pipes"),Ge=Symbol("bufferLength"),qa=Symbol("bufferPush"),Ts=Symbol("bufferShift"),Ye=Symbol("objectMode"),ke=Symbol("destroyed"),ja=Symbol("error"),Ka=Symbol("emitData"),vu=Symbol("emitEnd"),Wa=Symbol("emitEnd2"),Tt=Symbol("async"),$a=Symbol("abort"),Cs=Symbol("aborted"),ui=Symbol("signal"),Mn=Symbol("dataListeners"),st=Symbol("discarded"),fi=t=>Promise.resolve().then(t),zm=t=>t(),Um=t=>t==="end"||t==="finish"||t==="prefinish",Hm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Gm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),tf=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[br](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},qm=class extends tf{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)}},jm=t=>!!t.objectMode,Km=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Vn=class extends Mc{[Ue]=!1;[li]=!1;[Qe]=[];[He]=[];[Ye];[mt];[Tt];[mr];[Gt]=!1;[hn]=!1;[Is]=!1;[As]=!1;[di]=null;[Ge]=0;[ke]=!1;[ui];[Cs]=!1;[Mn]=0;[st]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");jm(e)?(this[Ye]=!0,this[mt]=null):Km(e)?(this[mt]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[mt]=null),this[Tt]=!!e.async,this[mr]=this[mt]?new Nm(this[mt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:r}=e;r&&(this[ui]=r,r.aborted?this[$a]():r.addEventListener("abort",()=>this[$a]()))}get bufferLength(){return this[Ge]}get encoding(){return this[mt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}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}[$a](){this[Cs]=!0,this.emit("abort",this[ui]?.reason),this.destroy(this[ui]?.reason)}get aborted(){return this[Cs]}set aborted(t){}write(t,e,r){if(this[Cs])return!1;if(this[Gt])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"&&(r=e,e="utf8"),e||(e="utf8");let i=this[Tt]?fi:zm;if(!this[Ye]&&!Buffer.isBuffer(t)){if(Gm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Hm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ye]?(this[Ue]&&this[Ge]!==0&&this[ks](!0),this[Ue]?this.emit("data",t):this[qa](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):t.length?(typeof t=="string"&&!(e===this[mt]&&!this[mr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[mt]&&(t=this[mr].write(t)),this[Ue]&&this[Ge]!==0&&this[ks](!0),this[Ue]?this.emit("data",t):this[qa](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):(this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue])}read(t){if(this[ke])return null;if(this[st]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[qt](),null;this[Ye]&&(t=null),this[He].length>1&&!this[Ye]&&(this[He]=[this[mt]?this[He].join(""):Buffer.concat(this[He],this[Ge])]);let e=this[Eu](t||null,this[He][0]);return this[qt](),e}[Eu](t,e){if(this[Ye])this[Ts]();else{let r=e;t===r.length||t===null?this[Ts]():typeof r=="string"?(this[He][0]=r.slice(t),e=r.slice(0,t),this[Ge]-=t):(this[He][0]=r.subarray(t),e=r.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[He].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[Ue]||!this[li])&&this[qt](),this}[br](){this[ke]||(!this[Mn]&&!this[Qe].length&&(this[st]=!0),this[li]=!1,this[Ue]=!0,this.emit("resume"),this[He].length?this[ks]():this[Gt]?this[qt]():this.emit("drain"))}resume(){return this[br]()}pause(){this[Ue]=!1,this[li]=!0,this[st]=!1}get destroyed(){return this[ke]}get flowing(){return this[Ue]}get paused(){return this[li]}[qa](t){this[Ye]?this[Ge]+=1:this[Ge]+=t.length,this[He].push(t)}[Ts](){return this[Ye]?this[Ge]-=1:this[Ge]-=this[He][0].length,this[He].shift()}[ks](t=!1){do;while(this[bu](this[Ts]())&&this[He].length);!t&&!this[He].length&&!this[Gt]&&this.emit("drain")}[bu](t){return this.emit("data",t),this[Ue]}pipe(t,e){if(this[ke])return t;this[st]=!1;let r=this[hn];return e=e||{},t===yu.stdout||t===yu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Qe].push(e.proxyErrors?new qm(this,t,e):new tf(this,t,e)),this[Tt]?fi(()=>this[br]()):this[br]()),t}unpipe(t){let e=this[Qe].find(r=>r.dest===t);e&&(this[Qe].length===1?(this[Ue]&&this[Mn]===0&&(this[Ue]=!1),this[Qe]=[]):this[Qe].splice(this[Qe].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[st]=!1,this[Mn]++,!this[Qe].length&&!this[Ue]&&this[br]();else if(t==="readable"&&this[Ge]!==0)super.emit("readable");else if(Um(t)&&this[hn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[di]){let i=e;this[Tt]?fi(()=>i.call(this,this[di])):i.call(this,this[di])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Mn]=this.listeners("data").length,this[Mn]===0&&!this[st]&&!this[Qe].length&&(this[Ue]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Mn]=0,!this[st]&&!this[Qe].length&&(this[Ue]=!1)),e}get emittedEnd(){return this[hn]}[qt](){!this[Is]&&!this[hn]&&!this[ke]&&this[He].length===0&&this[Gt]&&(this[Is]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[As]&&this.emit("close"),this[Is]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==ke&&this[ke])return!1;if(t==="data")return!this[Ye]&&!r?!1:this[Tt]?(fi(()=>this[Ka](r)),!0):this[Ka](r);if(t==="end")return this[vu]();if(t==="close"){if(this[As]=!0,!this[hn]&&!this[ke])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[di]=r,super.emit(ja,r);let o=!this[ui]||this.listeners("error").length?super.emit("error",r):!1;return this[qt](),o}else if(t==="resume"){let o=super.emit("resume");return this[qt](),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[qt](),i}[Ka](t){for(let r of this[Qe])r.dest.write(t)===!1&&this.pause();let e=this[st]?!1:super.emit("data",t);return this[qt](),e}[vu](){return this[hn]?!1:(this[hn]=!0,this.readable=!1,this[Tt]?(fi(()=>this[Wa]()),!0):this[Wa]())}[Wa](){if(this[mr]){let e=this[mr].end();if(e){for(let r of this[Qe])r.dest.write(e);this[st]||super.emit("data",e)}}for(let e of this[Qe])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ye]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Ye]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Ye])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[mt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ke,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[st]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Gt])return e();let i,o,c=x=>{this.off("data",l),this.off("end",u),this.off(ke,f),e(),o(x)},l=x=>{this.off("error",c),this.off("end",u),this.off(ke,f),this.pause(),i({value:x,done:!!this[Gt]})},u=()=>{this.off("error",c),this.off("data",l),this.off(ke,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(ke,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[st]=!1;let t=!1,e=()=>(this.pause(),this.off(ja,e),this.off(ke,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(ja,e),this.once(ke,e),{next:r,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[st]=!0,this[He].length=0,this[Ge]=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 Mm}},Wm=rt.writev,vn=Symbol("_autoClose"),Et=Symbol("_close"),hi=Symbol("_ended"),le=Symbol("_fd"),Va=Symbol("_finished"),$t=Symbol("_flags"),Ja=Symbol("_flush"),pc=Symbol("_handleChunk"),gc=Symbol("_makeBuf"),Si=Symbol("_mode"),Rs=Symbol("_needDrain"),kr=Symbol("_onerror"),Tr=Symbol("_onopen"),Za=Symbol("_onread"),vr=Symbol("_onwrite"),Sn=Symbol("_open"),yt=Symbol("_path"),wn=Symbol("_pos"),Ct=Symbol("_queue"),Sr=Symbol("_read"),Ya=Symbol("_readSize"),Wt=Symbol("_reading"),xi=Symbol("_remain"),Xa=Symbol("_size"),Us=Symbol("_write"),Bn=Symbol("_writing"),Hs=Symbol("_defaultFlag"),jn=Symbol("_errored"),Bc=class extends Vn{[jn]=!1;[le];[yt];[Ya];[Wt]=!1;[Xa];[xi];[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[le]=typeof e.fd=="number"?e.fd:void 0,this[yt]=t,this[Ya]=e.readSize||16*1024*1024,this[Wt]=!1,this[Xa]=typeof e.size=="number"?e.size:1/0,this[xi]=this[Xa],this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[Sr]():this[Sn]()}get fd(){return this[le]}get path(){return this[yt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Sn](){rt.open(this[yt],"r",(t,e)=>this[Tr](t,e))}[Tr](t,e){t?this[kr](t):(this[le]=e,this.emit("open",e),this[Sr]())}[gc](){return Buffer.allocUnsafe(Math.min(this[Ya],this[xi]))}[Sr](){if(!this[Wt]){this[Wt]=!0;let t=this[gc]();if(t.length===0)return process.nextTick(()=>this[Za](null,0,t));rt.read(this[le],t,0,t.length,null,(e,r,i)=>this[Za](e,r,i))}}[Za](t,e,r){this[Wt]=!1,t?this[kr](t):this[pc](e,r)&&this[Sr]()}[Et](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[kr](t){this[Wt]=!0,this[Et](),this.emit("error",t)}[pc](t,e){let r=!1;return this[xi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[xi]<=0)&&(r=!1,this[Et](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[Sr](),!1;case"error":return this[jn]?!1:(this[jn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},$m=class extends Bc{[Sn](){let t=!0;try{this[Tr](null,rt.openSync(this[yt],"r")),t=!1}finally{t&&this[Et]()}}[Sr](){let t=!0;try{if(!this[Wt]){this[Wt]=!0;do{let e=this[gc](),r=e.length===0?0:rt.readSync(this[le],e,0,e.length,null);if(!this[pc](r,e))break}while(!0);this[Wt]=!1}t=!1}finally{t&&this[Et]()}}[Et](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,rt.closeSync(t),this.emit("close")}}},no=class extends Lm{readable=!1;writable=!0;[jn]=!1;[Bn]=!1;[hi]=!1;[Ct]=[];[Rs]=!1;[yt];[Si];[vn];[le];[Hs];[$t];[Va]=!1;[wn];constructor(t,e){e=e||{},super(e),this[yt]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Si]=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 r=this[wn]!==void 0?"r+":"w";this[Hs]=e.flags===void 0,this[$t]=e.flags===void 0?r:e.flags,this[le]===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[le]}get path(){return this[yt]}[kr](t){this[Et](),this[Bn]=!0,this.emit("error",t)}[Sn](){rt.open(this[yt],this[$t],this[Si],(t,e)=>this[Tr](t,e))}[Tr](t,e){this[Hs]&&this[$t]==="r+"&&t&&t.code==="ENOENT"?(this[$t]="w",this[Sn]()):t?this[kr](t):(this[le]=e,this.emit("open",e),this[Bn]||this[Ja]())}end(t,e){return t&&this.write(t,e),this[hi]=!0,!this[Bn]&&!this[Ct].length&&typeof this[le]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[hi]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[Bn]||this[Ct].length?(this[Ct].push(t),this[Rs]=!0,!1):(this[Bn]=!0,this[Us](t),!0)}[Us](t){rt.write(this[le],t,0,t.length,this[wn],(e,r)=>this[vr](e,r))}[vr](t,e){t?this[kr](t):(this[wn]!==void 0&&typeof e=="number"&&(this[wn]+=e),this[Ct].length?this[Ja]():(this[Bn]=!1,this[hi]&&!this[Va]?(this[Va]=!0,this[Et](),this.emit("finish")):this[Rs]&&(this[Rs]=!1,this.emit("drain"))))}[Ja](){if(this[Ct].length===0)this[hi]&&this[vr](null,0);else if(this[Ct].length===1)this[Us](this[Ct].pop());else{let t=this[Ct];this[Ct]=[],Wm(this[le],t,this[wn],(e,r)=>this[vr](e,r))}}[Et](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},nf=class extends no{[Sn](){let t;if(this[Hs]&&this[$t]==="r+")try{t=rt.openSync(this[yt],this[$t],this[Si])}catch(e){if(e?.code==="ENOENT")return this[$t]="w",this[Sn]();throw e}else t=rt.openSync(this[yt],this[$t],this[Si]);this[Tr](null,t)}[Et](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,rt.closeSync(t),this.emit("close")}}[Us](t){let e=!0;try{this[vr](null,rt.writeSync(this[le],t,0,t.length,this[wn])),e=!1}finally{if(e)try{this[Et]()}catch{}}}},Zm=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"]]),Ym=t=>!!t.sync&&!!t.file,Xm=t=>!t.sync&&!!t.file,Qm=t=>!!t.sync&&!t.file,ew=t=>!t.sync&&!t.file,tw=t=>!!t.file,nw=t=>Zm.get(t)||t,Fc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=nw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Oi=(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=Fc(c);if(o?.(f,l),Ym(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,l)}else if(Xm(f)){let x=e(f,l);return u?x.then(()=>u(),u):x}else if(Qm(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(f,l)}else if(ew(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}),sw=iw.constants||{ZLIB_VERNUM:4736},Ot=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},sw)),ow=Kn.concat,Iu=Object.getOwnPropertyDescriptor(Kn,"concat"),aw=t=>t,Qa=Iu?.writable===!0||Iu?.set!==void 0?t=>{Kn.concat=t?aw:ow}:t=>{},Wn=Symbol("_superWrite"),Ds=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"}},ec=Symbol("flushFlag"),zc=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 Su[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Su[e](t)}catch(r){throw new Ds(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 Ds(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return mc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Kn.alloc(0),{[ec]: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}[Wn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Kn.from(t,e)),this.#e)return;mc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Qa(!0);let l;try{let f=typeof t[ec]=="number"?t[ec]:this.#r;l=this.#t._processChunk(t,f),Qa(!1)}catch(f){Qa(!1),this.#o(new Ds(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 Ds(f,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let f=l[0];u=this[Wn](Kn.from(f));for(let x=1;x<l.length;x++)u=this[Wn](l[x])}else u=this[Wn](Kn.from(l));return r&&r(),u}},sf=class extends zc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ot.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ot.Z_FINISH,t.fullFlushFlag=Ot.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(Ot.Z_SYNC_FLUSH),mc(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)}}}},cw=class extends sf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Wn](t){return this.#e?(this.#e=!1,t[9]=255,super[Wn](t)):super[Wn](t)}},dw=class extends sf{constructor(t){super(t,"Unzip")}},of=class extends zc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ot.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ot.BROTLI_OPERATION_FLUSH,super(t,e)}},lw=class extends of{constructor(t){super(t,"BrotliCompress")}},uw=class extends of{constructor(t){super(t,"BrotliDecompress")}},af=class extends zc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ot.ZSTD_e_end,t.fullFlushFlag=Ot.ZSTD_e_flush,super(t,e)}},fw=class extends af{constructor(t){super(t,"ZstdCompress")}},hw=class extends af{constructor(t){super(t,"ZstdDecompress")}},xw=(t,e)=>{if(Number.isSafeInteger(t))t<0?gw(t,e):pw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},pw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},gw=(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]=cf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=df(o))}},mw=t=>{let e=t[0],r=e===128?_w(t.subarray(1,t.length)):e===255?ww(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},ww=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),l;i?l=cf(c):c===0?l=c:(i=!0,l=df(c)),l!==0&&(r-=l*Math.pow(256,e-o-1))}return r},_w=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},cf=t=>(255^t)&255,df=t=>(255^t)+1&255,yw={};Om(yw,{code:()=>Uc,isCode:()=>Gs,isName:()=>Ew,name:()=>ro});var Gs=t=>ro.has(t),Ew=t=>Uc.has(t),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"]]),Uc=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,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");this.path=r?.path??Fn(t,e,100),this.mode=r?.mode??i?.mode??_n(t,e+100,8),this.uid=r?.uid??i?.uid??_n(t,e+108,8),this.gid=r?.gid??i?.gid??_n(t,e+116,8),this.size=r?.size??i?.size??_n(t,e+124,12),this.mtime=r?.mtime??i?.mtime??tc(t,e+136,12),this.cksum=_n(t,e+148,12),i&&this.#n(i,!0),r&&this.#n(r);let o=Fn(t,e+156,1);if(Gs(o)&&(this.#e=o||"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=r?.uname??i?.uname??Fn(t,e+265,32),this.gname=r?.gname??i?.gname??Fn(t,e+297,32),this.devmaj=r?.devmaj??i?.devmaj??_n(t,e+329,8)??0,this.devmin=r?.devmin??i?.devmin??_n(t,e+337,8)??0,t[e+475]!==0){let l=Fn(t,e+345,155);this.path=l+"/"+this.path}else{let l=Fn(t,e+345,130);l&&(this.path=l+"/"+this.path),this.atime=r?.atime??i?.atime??tc(t,e+476,12),this.ctime=r?.ctime??i?.ctime??tc(t,e+488,12)}let c=256;for(let l=e;l<e+148;l++)c+=t[l];for(let l=e+156;l<e+512;l++)c+=t[l];this.cksumValid=c===this.cksum,this.cksum===void 0&&c===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=bw(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=zn(t,e,100,o)||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=nc(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,r,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=nc(t,e+476,12,this.atime)||this.needPax,this.needPax=nc(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,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(Uc.get(t));if(Gs(e)||e==="Unsupported")this.#e=e;else if(Gs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},bw=(t,e)=>{let r=t,i="",o,c=wr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=wr.dirname(r),r=wr.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=wr.join(wr.basename(i),r),i=wr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Fn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),tc=(t,e,r)=>vw(_n(t,e,r)),vw=t=>t===void 0?void 0:new Date(t*1e3),_n=(t,e,r)=>Number(t[e])&128?mw(t.subarray(e,e+r)):Iw(t,e,r),Sw=t=>isNaN(t)?void 0:t,Iw=(t,e,r)=>Sw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Aw={12:8589934591,8:2097151},yn=(t,e,r,i)=>i===void 0?!1:i>Aw[r]||i<0?(xw(i,t.subarray(e,e+r)),!0):(kw(t,e,r,i),!1),kw=(t,e,r,i)=>t.write(Tw(i,r),e,r,"ascii"),Tw=(t,e)=>Cw(Math.floor(t).toString(8),e),Cw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",nc=(t,e,r,i)=>i===void 0?!1:yn(t,e,r,i.getTime()/1e3),Rw=new Array(156).join("\0"),zn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Rw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Ys=class lf{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 $n({path:("PaxHeader/"+Dw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
- `,c=Buffer.byteLength(o),l=Math.floor(Math.log(c)/Math.log(10))+1;return c+l>=Math.pow(10,l)&&(l+=1),l+c+o}static parse(e,r,i=!1){return new lf(Pw(Ow(e),r),i)}},Pw=(t,e)=>e?Object.assign({},e,t):t,Ow=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(Lw,Object.create(null)),Lw=(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},Nw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ee=Nw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),uf=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,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=ee(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?ee(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=ee(t.path)),t.linkpath&&(t.linkpath=ee(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},io=(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))},Mw=1024*1024,wc=Buffer.from([31,139]),_c=Buffer.from([40,181,47,253]),Bw=Math.max(wc.length,_c.length),lt=Symbol("state"),Un=Symbol("writeEntry"),jt=Symbol("readEntry"),rc=Symbol("nextEntry"),Au=Symbol("processEntry"),Rt=Symbol("extendedHeader"),pi=Symbol("globalExtendedHeader"),xn=Symbol("meta"),ku=Symbol("emitMeta"),_e=Symbol("buffer"),Kt=Symbol("queue"),pn=Symbol("ended"),ic=Symbol("emittedEnd"),Hn=Symbol("emit"),Pe=Symbol("unzip"),Ps=Symbol("consumeChunk"),Os=Symbol("consumeChunkSub"),sc=Symbol("consumeBody"),Tu=Symbol("consumeMeta"),Cu=Symbol("consumeHeader"),gi=Symbol("consuming"),oc=Symbol("bufferConcat"),Ls=Symbol("maybeEnd"),_r=Symbol("writing"),gn=Symbol("aborted"),Ns=Symbol("onDone"),Gn=Symbol("sawValidEntry"),Ms=Symbol("sawNullBlock"),Bs=Symbol("sawEOF"),Ru=Symbol("closeStream"),Fw=()=>!0,Pi=class extends rw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Kt]=[];[_e];[jt];[Un];[lt]="begin";[xn]="";[Rt];[pi];[pn]=!1;[Pe];[gn]=!1;[Gn];[Ms]=!1;[Bs]=!1;[_r]=!1;[gi]=!1;[ic]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ns,()=>{(this[lt]==="begin"||this[Gn]===!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||Mw,this.filter=typeof t.filter=="function"?t.filter:Fw;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[Ru]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){io(this,t,e,r)}[Cu](t,e){this[Gn]===void 0&&(this[Gn]=!1);let r;try{r=new $n(t,e,this[Rt],this[pi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Ms]?(this[Bs]=!0,this[lt]==="begin"&&(this[lt]="header"),this[Hn]("eof")):(this[Ms]=!0,this[Hn]("nullBlock"));else if(this[Ms]=!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[Un]=new uf(r,this[Rt],this[pi]);if(!this[Gn])if(o.remain){let c=()=>{o.invalid||(this[Gn]=!0)};o.on("end",c)}else this[Gn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Hn]("ignoredEntry",o),this[lt]="ignore",o.resume()):o.size>0&&(this[xn]="",o.on("data",c=>this[xn]+=c),this[lt]="meta"):(this[Rt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Hn]("ignoredEntry",o),this[lt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[lt]="body":(this[lt]="header",o.end()),this[jt]?this[Kt].push(o):(this[Kt].push(o),this[rc]())))}}}[Ru](){queueMicrotask(()=>this.emit("close"))}[Au](t){let e=!0;if(!t)this[jt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[jt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[rc]()),e=!1);return e}[rc](){do;while(this[Au](this[Kt].shift()));if(this[Kt].length===0){let t=this[jt];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[sc](t,e){let r=this[Un];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[lt]="header",this[Un]=void 0,r.end()),o.length}[Tu](t,e){let r=this[Un],i=this[sc](t,e);return!this[Un]&&r&&this[ku](r),i}[Hn](t,e,r){this[Kt].length===0&&!this[jt]?this.emit(t,e,r):this[Kt].push([t,e,r])}[ku](t){switch(this[Hn]("meta",this[xn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Rt]=Ys.parse(this[xn],this[Rt],!1);break;case"GlobalExtendedHeader":this[pi]=Ys.parse(this[xn],this[pi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Rt]??Object.create(null);this[Rt]=e,e.path=this[xn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Rt]||Object.create(null);this[Rt]=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,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[gn])return r?.(),!1;if((this[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[_e]&&(t=Buffer.concat([this[_e],t]),this[_e]=void 0),t.length<Bw)return this[_e]=t,r?.(),!0;for(let l=0;this[Pe]===void 0&&l<wc.length;l++)t[l]!==wc[l]&&(this[Pe]=!1);let o=!1;if(this[Pe]===!1&&this.zstd!==!1){o=!0;for(let l=0;l<_c.length;l++)if(t[l]!==_c[l]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Pe]===!1&&c)if(t.length<512)if(this[pn])this.brotli=!0;else return this[_e]=t,r?.(),!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||o)){let l=this[pn];this[pn]=!1,this[Pe]=this[Pe]===void 0?new dw({}):o?new hw({}):new uw({}),this[Pe].on("data",f=>this[Ps](f)),this[Pe].on("error",f=>this.abort(f)),this[Pe].on("end",()=>{this[pn]=!0,this[Ps]()}),this[_r]=!0;let u=!!this[Pe][l?"end":"write"](t);return this[_r]=!1,r?.(),u}}this[_r]=!0,this[Pe]?this[Pe].write(t):this[Ps](t),this[_r]=!1;let i=this[Kt].length>0?!1:this[jt]?this[jt].flowing:!0;return!i&&this[Kt].length===0&&this[jt]?.once("drain",()=>this.emit("drain")),r?.(),i}[oc](t){t&&!this[gn]&&(this[_e]=this[_e]?Buffer.concat([this[_e],t]):t)}[Ls](){if(this[pn]&&!this[ic]&&!this[gn]&&!this[gi]){this[ic]=!0;let t=this[Un];if(t&&t.blockRemain){let e=this[_e]?this[_e].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[_e]&&t.write(this[_e]),t.end()}this[Hn](Ns)}}[Ps](t){if(this[gi]&&t)this[oc](t);else if(!t&&!this[_e])this[Ls]();else if(t){if(this[gi]=!0,this[_e]){this[oc](t);let e=this[_e];this[_e]=void 0,this[Os](e)}else this[Os](t);for(;this[_e]&&this[_e]?.length>=512&&!this[gn]&&!this[Bs];){let e=this[_e];this[_e]=void 0,this[Os](e)}this[gi]=!1}(!this[_e]||this[pn])&&this[Ls]()}[Os](t){let e=0,r=t.length;for(;e+512<=r&&!this[gn]&&!this[Bs];)switch(this[lt]){case"begin":case"header":this[Cu](t,e),e+=512;break;case"ignore":case"body":e+=this[sc](t,e);break;case"meta":e+=this[Tu](t,e);break;default:throw new Error("invalid state: "+this[lt])}e<r&&(this[_e]=this[_e]?Buffer.concat([t.subarray(e),this[_e]]):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[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}},Ii=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)},zw=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},ff=(t,e)=>{let r=new Map(e.map(c=>[Ii(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(Vm(c),u)}return r.set(c,f),f};t.filter=i?(c,l)=>i(c,l)&&o(Ii(c)):c=>o(Ii(c))},Uw=t=>{let e=new Pi(t),r=t.file,i;try{i=Ir.openSync(r,"r");let o=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let l=Buffer.allocUnsafe(o.size),u=Ir.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=Ir.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{Ir.closeSync(i)}catch{}}},Hw=(t,e)=>{let r=new Pi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("end",c),Ir.stat(o,(u,f)=>{if(u)l(u);else{let x=new Bc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Cr=Oi(Uw,Hw,t=>new Pi(t),t=>new Pi(t),(t,e)=>{e?.length&&ff(t,e),t.noResume||zw(t)}),hf=(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:qw,parse:Pu}=Gw,Hc=t=>{let e="",r=Pu(t);for(;qw(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Pu(t)}return[e,t]},so=["|","<",">","?",":"],Gc=so.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),jw=new Map(so.map((t,e)=>[t,Gc[e]])),Kw=new Map(Gc.map((t,e)=>[t,so[e]])),Ou=t=>so.reduce((e,r)=>e.split(r).join(jw.get(r)),t),Ww=t=>Gc.reduce((e,r)=>e.split(r).join(Kw.get(r)),t),xf=(t,e)=>e?(t=ee(t).replace(/^\.(\/|$)/,""),Ii(e)+"/"+t):ee(t),$w=16*1024*1024,Lu=Symbol("process"),Nu=Symbol("file"),Mu=Symbol("directory"),yc=Symbol("symlink"),Bu=Symbol("hardlink"),mi=Symbol("header"),qs=Symbol("read"),Ec=Symbol("lstat"),js=Symbol("onlstat"),bc=Symbol("onread"),vc=Symbol("onreadlink"),Sc=Symbol("openfile"),Ic=Symbol("onopenfile"),En=Symbol("close"),Qs=Symbol("mode"),Ac=Symbol("awaitDrain"),ac=Symbol("ondrain"),Pt=Symbol("prefix"),pf=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 r=Fc(e);super(),this.path=ee(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||$w,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=ee(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?ee(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]=Hc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=Ww(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ee(r.absolute||Du.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[js](o):this[Ec]()}warn(t,e,r={}){return io(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Ec](){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=Zw(t),this.emit("stat",t),this[Lu]()}[Lu](){switch(this.type){case"File":return this[Nu]();case"Directory":return this[Mu]();case"SymbolicLink":return this[yc]();default:return this.end()}}[Qs](t){return hf(t,this.type==="Directory",this.portable)}[Pt](t){return xf(t,this.prefix)}[mi](){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[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](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[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Mu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[mi](),this.end()}[yc](){Dt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[vc](e)})}[vc](t){this.linkpath=ee(t),this[mi](),this.end()}[Bu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ee(Du.relative(this.cwd,t)),this.stat.size=0,this[mi](),this.end()}[Nu](){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[Bu](e);this.linkCache.set(t,this.absolute)}if(this[mi](),this.stat.size===0)return this.end();this[Sc]()}[Sc](){Dt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ic](e)})}[Ic](t){if(this.fd=t,this.#e)return this[En]();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[qs]()}[qs](){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");Dt.read(t,e,r,i,o,(c,l)=>{if(c)return this[En](()=>this.emit("error",c));this[bc](l)})}[En](t=()=>{}){this.fd!==void 0&&Dt.close(this.fd,t)}[bc](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[En](()=>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[En](()=>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[ac]():this[Ac](()=>this[ac]())}[Ac](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)}[ac](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[En](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[qs]()}},Vw=class extends pf{sync=!0;[Ec](){this[js](Dt.lstatSync(this.absolute))}[yc](){this[vc](Dt.readlinkSync(this.absolute))}[Sc](){this[Ic](Dt.openSync(this.absolute,"r"))}[qs](){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=Dt.readSync(e,r,i,o,c);this[bc](l),t=!1}finally{if(t)try{this[En](()=>{})}catch{}}}[Ac](t){t()}[En](t=()=>{}){this.fd!==void 0&&Dt.closeSync(this.fd),t()}},Jw=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,r={}){return io(this,t,e,r)}constructor(t,e={}){let r=Fc(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=ee(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: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?ee(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[l,u]=Hc(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 $n({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new 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[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Pt](t){return xf(t,this.prefix)}[Qs](t){return hf(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}},Zw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",Yw=class Ar{tail;head;length=0;static create(e=[]){return new Ar(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++)Qw(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)e_(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 Ar;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 Ar;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 Ar;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 Ar;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=Xw(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 Xw(t,e,r){let i=e,o=e?e.next:t.head,c=new qc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function Qw(t,e){t.tail=new qc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function e_(t,e){t.head=new qc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var qc=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}},zu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Uu=Buffer.alloc(1024),Ks=Symbol("onStat"),wi=Symbol("ended"),wt=Symbol("queue"),_i=Symbol("queue"),mn=Symbol("current"),qn=Symbol("process"),yi=Symbol("processing"),Fs=Symbol("processJob"),_t=Symbol("jobs"),cc=Symbol("jobDone"),Ws=Symbol("addFSEntry"),Hu=Symbol("addTarEntry"),kc=Symbol("stat"),Tc=Symbol("readdir"),$s=Symbol("onreaddir"),Vs=Symbol("pipe"),Gu=Symbol("entry"),dc=Symbol("entryOpt"),Js=Symbol("writeEntryClass"),gf=Symbol("write"),lc=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;[wt];[_i]=new Map;[_t]=0;[yi]=!1;[wi]=!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=ee(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]=pf,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 cw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new lw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new fw(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[lc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[lc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[wt]=new Yw,this[_t]=0,this.jobs=Number(t.jobs)||4,this[yi]=!1,this[wi]=!1}[gf](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[wi]=!0,this[qn](),r&&r(),this}write(t){if(this[wi])throw new Error("write after end");return t instanceof uf?this[Hu](t):this[Ws](t),this.flowing}[Hu](t){let e=ee(Fu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new zu(t.path,e);r.entry=new Jw(t,this[dc](r)),r.entry.on("end",()=>this[cc](r)),this[_t]+=1,this[wt].push(r)}this[qn]()}[Ws](t){let e=ee(Fu.resolve(this.cwd,t));this[wt].push(new zu(t,e)),this[qn]()}[kc](t){t.pending=!0,this[_t]+=1;let e=this.follow?"stat":"lstat";Xs[e](t.absolute,(r,i)=>{t.pending=!1,this[_t]-=1,r?this.emit("error",r):this[Ks](t,i)})}[Ks](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 r=`${e.dev}:${e.ino}`,i=this[_i].get(r);i?i.push(t):this[_i].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[qn]()}[Tc](t){t.pending=!0,this[_t]+=1,Xs.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[_t]-=1,e)return this.emit("error",e);this[$s](t,r)})}[$s](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[qn]()}[qn](){if(!this[yi]){this[yi]=!0;for(let t=this[wt].head;t&&this[_t]<this.jobs;t=t.next)if(this[Fs](t.value),t.value.ignore){let e=t.next;this[wt].removeNode(t),t.next=e}this[yi]=!1,this[wi]&&this[wt].length===0&&this[_t]===0&&(this.zip?this.zip.end(Uu):(super.write(Uu),super.end()))}}get[mn](){return this[wt]&&this[wt].head&&this[wt].head.value}[cc](t){this[wt].shift(),this[_t]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[_i].get(r);if(i){this[_i].delete(r);for(let o of i)o.pending=!1,this[Fs](o)}}this[qn]()}[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[Ks](t,e):this[kc](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[Tc](t),!t.readdir)return}if(t.entry=this[Gu](t),!t.entry){t.ignore=!0;return}t===this[mn]&&!t.piped&&this[Vs](t)}}}[dc](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}}[Gu](t){this[_t]+=1;try{return new this[Js](t.path,this[dc](t)).on("end",()=>this[cc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[lc](){this[mn]&&this[mn].entry&&this[mn].entry.resume()}[Vs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ws](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={}){io(this,t,e,r)}},jc=class extends oo{sync=!0;constructor(t){super(t),this[Js]=Vw}pause(){}resume(){}[kc](t){let e=this.follow?"statSync":"lstatSync";this[Ks](t,Xs[e](t.absolute))}[Tc](t){this[$s](t,Xs.readdirSync(t.absolute))}[Vs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ws](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[gf](i)})}},t_=(t,e)=>{let r=new jc(t),i=new nf(t.file,{mode:t.mode||438});r.pipe(i),mf(r,e)},n_=(t,e)=>{let r=new oo(t),i=new no(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 wf(r,e).catch(c=>r.emit("error",c)),o},mf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:rf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},wf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:rf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},r_=(t,e)=>{let r=new jc(t);return mf(r,e),r},i_=(t,e)=>{let r=new oo(t);return wf(r,e).catch(i=>r.emit("error",i)),r},q2=Oi(t_,n_,r_,i_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),o_=process.env.__FAKE_PLATFORM__||process.platform,bf=o_==="win32",{O_CREAT:vf,O_NOFOLLOW:qu,O_TRUNC:Sf,O_WRONLY:If}=Ef.constants,Af=Number(process.env.__FAKE_FS_O_FILENAME__)||Ef.constants.UV_FS_O_FILEMAP||0,a_=bf&&!!Af,c_=512*1024,d_=Af|Sf|vf|If,ju=!bf&&typeof qu=="number"?qu|Sf|vf|If:null,kf=ju!==null?()=>ju:a_?t=>t<c_?d_:"w":()=>"w",Cc=(t,e,r)=>{try{return ao.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},eo=(t,e,r,i)=>{ao.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},l_=(t,e,r,i,o)=>{if(e.isDirectory())Tf(Ai.resolve(t,e.name),r,i,c=>{if(c)return o(c);let l=Ai.resolve(t,e.name);eo(l,r,i,o)});else{let c=Ai.resolve(t,e.name);eo(c,r,i,o)}},Tf=(t,e,r,i)=>{ao.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 eo(t,e,r,i);let l=c.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--l===0)return eo(t,e,r,i)}};for(let x of c)l_(t,x,e,r,f)})},u_=(t,e,r,i)=>{e.isDirectory()&&Cf(Ai.resolve(t,e.name),r,i),Cc(Ai.resolve(t,e.name),r,i)},Cf=(t,e,r)=>{let i;try{i=ao.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Cc(t,e,r);throw c}for(let o of i)u_(t,o,e,r);return Cc(t,e,r)},Rf=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"}},h_=(t,e)=>{at.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Rf(t,r?.code||"ENOTDIR")),e(r)})},x_=(t,e,r)=>{t=ee(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,y=ee(e.cwd),S=(v,I)=>{v?r(v):I&&f?Tf(I,l,u,A=>S(A)):c?at.chmod(t,o,r):r()};if(t===y)return h_(t,S);if(x)return f_.mkdir(t,{mode:o,recursive:!0}).then(v=>S(null,v??void 0),S);let _=ee(to.relative(y,t)).split("/");Rc(y,_,o,g,y,void 0,S)},Rc=(t,e,r,i,o,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),f=ee(to.resolve(t+"/"+u));at.mkdir(f,r,Df(f,e,r,i,o,c,l))},Df=(t,e,r,i,o,c,l)=>u=>{u?at.lstat(t,(f,x)=>{if(f)f.path=f.path&&ee(f.path),l(f);else if(x.isDirectory())Rc(t,e,r,i,o,c,l);else if(i)at.unlink(t,g=>{if(g)return l(g);at.mkdir(t,r,Df(t,e,r,i,o,c,l))});else{if(x.isSymbolicLink())return l(new co(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,Rc(t,e,r,i,o,c,l))},p_=t=>{let e=!1,r;try{e=at.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Rf(t,r??"ENOTDIR")}},g_=(t,e)=>{t=ee(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=ee(e.cwd),y=v=>{v&&u&&Cf(v,c,l),o&&at.chmodSync(t,i)};if(t===g)return p_(g),y();if(f)return y(at.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=ee(to.relative(g,t)).split("/"),_;for(let v=S.shift(),I=g;v&&(I+="/"+v);v=S.shift()){I=ee(to.resolve(I));try{at.mkdirSync(I,i),_=_||I}catch{let A=at.lstatSync(I);if(A.isDirectory())continue;if(x){at.unlinkSync(I),at.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new co(I,I+"/"+S.join("/"))}}return y(_)},uc=Object.create(null),Ku=1e4,yr=new Set,m_=t=>{yr.has(t)?yr.delete(t):uc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=uc[t],r=yr.size-Ku;if(r>Ku/10){for(let i of yr)if(yr.delete(i),delete uc[i],--r<=0)break}return e},w_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,__=w_==="win32",y_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Pf(i,r)),e.push(r||"/"),e},[]),E_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=__?["win32 parallelization disabled"]:t.map(i=>Ii(Pf(m_(i))));let r=new Set(t.map(i=>y_(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}},b_=()=>process.umask(),Wu=Symbol("onEntry"),Dc=Symbol("checkFs"),$u=Symbol("checkFs2"),Pc=Symbol("isReusable"),ut=Symbol("makeFs"),Oc=Symbol("file"),Lc=Symbol("directory"),Zs=Symbol("link"),Vu=Symbol("symlink"),Ju=Symbol("hardlink"),vi=Symbol("ensureNoSymlink"),Zu=Symbol("unsupported"),Yu=Symbol("checkPath"),fc=Symbol("stripAbsolutePath"),bn=Symbol("mkdir"),qe=Symbol("onError"),zs=Symbol("pending"),Xu=Symbol("pend"),Er=Symbol("unpend"),hc=Symbol("ended"),xc=Symbol("maybeClose"),Nc=Symbol("skip"),ki=Symbol("doChown"),Ti=Symbol("uid"),Ci=Symbol("gid"),Ri=Symbol("checkedCwd"),v_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Di=v_==="win32",S_=1024,I_=(t,e)=>{if(!Di)return ie.unlink(t,e);let r=t+".DELETE."+yf(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},A_=t=>{if(!Di)return ie.unlinkSync(t);let e=t+".DELETE."+yf(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},Qu=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Kc=class extends Pi{[hc]=!1;[Ri]=!1;[zs]=0;reservations=new E_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[hc]=!0,this[xc]()},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:S_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Di,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ee(Be.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[Wu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[xc](){this[hc]&&this[zs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[fc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Hc(r),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Di&&/^[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=Be.posix.dirname(t.path),f=Be.posix.normalize(Be.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}[Yu](t){let e=ee(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=ee(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[fc](t,"path")||!this[fc](t,"linkpath"))return!1;if(t.absolute=Be.isAbsolute(t.path)?ee(Be.resolve(t.path)):ee(Be.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:ee(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}=Be.win32.parse(String(t.absolute));t.absolute=i+Ou(String(t.absolute).slice(i.length));let{root:o}=Be.win32.parse(t.path);t.path=o+Ou(t.path.slice(o.length))}return!0}[Wu](t){if(!this[Yu](t))return t.resume();switch(s_.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[Dc](t);default:return this[Zu](t)}}[qe](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Er](),e.resume())}[bn](t,e,r){x_(ee(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)}[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}[Ti](t){return Qu(this.uid,t.uid,this.processUid)}[Ci](t){return Qu(this.gid,t.gid,this.processGid)}[Oc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new no(String(t.absolute),{flags:kf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[qe](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[qe](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,f=>{f?this[qe](f,t):this[Er](),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,y=>y?ie.utimes(u,x,g,S=>c(S&&y)):c())}if(typeof f=="number"&&this[ki](t)){o++;let x=this[Ti](t),g=this[Ci](t);typeof x=="number"&&typeof g=="number"&&ie.fchown(f,x,g,y=>y?ie.chown(u,x,g,S=>c(S&&y)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[qe](u,t),e()}),t.pipe(l)),l.pipe(i)}[Lc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[bn](String(t.absolute),r,i=>{if(i){this[qe](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[Er](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[ki](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ti](t)),Number(this[Ci](t)),c)),c()})}[Zu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Vu](t,e){let r=ee(Be.relative(this.cwd,Be.resolve(Be.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[vi](t,this.cwd,r,()=>this[Zs](t,String(t.linkpath),"symlink",e),i=>{this[qe](i,t),e()})}[Ju](t,e){let r=ee(Be.resolve(this.cwd,String(t.linkpath))),i=ee(String(t.linkpath)).split("/");this[vi](t,this.cwd,i,()=>this[Zs](t,r,"link",e),o=>{this[qe](o,t),e()})}[vi](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let l=Be.resolve(e,c);ie.lstat(l,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new co(l,Be.resolve(l,r.join("/"))));this[vi](t,l,r,i,o)})}[Xu](){this[zs]++}[Er](){this[zs]--,this[xc]()}[Nc](t){this[Er](),t.resume()}[Pc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Di}[Dc](t){this[Xu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[$u](t,r))}[$u](t,e){let r=l=>{e(l)},i=()=>{this[bn](this.cwd,this.dmode,l=>{if(l){this[qe](l,t),r();return}this[Ri]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let l=ee(Be.dirname(String(t.absolute)));if(l!==this.cwd)return this[bn](l,this.dmode,u=>{if(u){this[qe](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[Nc](t),r();return}if(l||this[Pc](t,u))return this[ut](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[ut](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[ut](f??null,t,r))}if(t.absolute===this.cwd)return this[ut](null,t,r);I_(String(t.absolute),f=>this[ut](f??null,t,r))})};this[Ri]?o():i()}[ut](t,e,r){if(t){this[qe](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Oc](e,r);case"Link":return this[Ju](e,r);case"SymbolicLink":return this[Vu](e,r);case"Directory":case"GNUDumpDir":return this[Lc](e,r)}}[Zs](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[qe](o,t):(this[Er](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},Of=class extends Kc{sync=!0;[ut](t,e){return super[ut](t,e,()=>{})}[Dc](t){if(!this[Ri]){let o=this[bn](this.cwd,this.dmode);if(o)return this[qe](o,t);this[Ri]=!0}if(t.absolute!==this.cwd){let o=ee(Be.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[bn](o,this.dmode);if(c)return this[qe](c,t)}}let[e,r]=Ei(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Nc](t);if(e||this[Pc](t,r))return this[ut](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[l]=c?Ei(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ut](l,t)}let[o]=Ei(()=>ie.rmdirSync(String(t.absolute)));this[ut](o,t)}let[i]=t.absolute===this.cwd?[]:Ei(()=>A_(String(t.absolute)));this[ut](i,t)}[Oc](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[qe](l||u,t),e()},o;try{o=ie.openSync(String(t.absolute),kf(t.size),r)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[qe](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[ki](t)){let u=this[Ti](t),f=this[Ci](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)})}[Lc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[bn](String(t.absolute),r);if(i){this[qe](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ki](t))try{ie.chownSync(String(t.absolute),Number(this[Ti](t)),Number(this[Ci](t)))}catch{}e(),t.resume()}[bn](t,e){try{return g_(ee(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}}[vi](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let l of r){c=Be.resolve(c,l);let[u,f]=Ei(()=>ie.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new co(c,Be.resolve(e,r.join("/"))))}i()}[Zs](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[qe](c,t)}}},k_=t=>{let e=new Of(t),r=t.file,i=_f.statSync(r),o=t.maxReadSize||16*1024*1024;new $m(r,{readSize:o,size:i.size}).pipe(e)},T_=(t,e)=>{let r=new Kc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("close",c),_f.stat(o,(u,f)=>{if(u)l(u);else{let x=new Bc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Lf=Oi(k_,T_,t=>new Of(t),t=>new Kc(t),(t,e)=>{e?.length&&ff(t,e)}),C_=(t,e)=>{let r=new jc(t),i=!0,o,c;try{try{o=ot.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=ot.openSync(t.file,"w+");else throw f}let l=ot.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<l.size;c+=512){for(let g=0,y=0;g<512;g+=y){if(y=ot.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(!y)break e}let f=new $n(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,R_(t,r,c,o,e)}finally{if(i)try{ot.closeSync(o)}catch{}}},R_=(t,e,r,i,o)=>{let c=new nf(t.file,{fd:i,start:r});e.pipe(c),P_(e,o)},D_=(t,e)=>{e=Array.from(e);let r=new oo(t),i=(o,c,l)=>{let u=(S,_)=>{S?ot.close(o,v=>l(S)):l(null,_)},f=0;if(c===0)return u(null,0);let x=0,g=Buffer.alloc(512),y=(S,_)=>{if(S||_===void 0)return u(S);if(x+=_,x<512&&_)return ot.read(o,g,x,g.length-x,f+x,y);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 v=new $n(g);if(!v.cksumValid)return u(null,f);let I=512*Math.ceil((v.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,ot.read(o,g,0,512,f,y)};ot.read(o,g,0,512,f,y)};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+",ot.open(t.file,l,u);if(f||!x)return c(f);ot.fstat(x,(g,y)=>{if(g)return ot.close(x,()=>c(g));i(x,y.size,(S,_)=>{if(S)return c(S);let v=new no(t.file,{fd:x,start:_});r.pipe(v),v.on("error",c),v.on("close",o),O_(r,e)})})};ot.open(t.file,l,u)})},P_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:Nf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},O_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:Nf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},bi=Oi(C_,D_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!tw(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")}),iA=Oi(bi.syncFile,bi.asyncFile,bi.syncNoFile,bi.asyncNoFile,(t,e=[])=>{bi.validate?.(t,e),L_(t)}),L_=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))};un();var ft={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function lo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Mf(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 Bf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Ff(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Jn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Vt();We();ne();Re();We();function Rr(t,e){if(lo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Li(t){return t.startsWith("http://")||t.startsWith("https://")}function Dr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as JA}from"node:fs";import{dirname as YA,join as XA}from"node:path";import{fileURLToPath as ek}from"node:url";var Lt="0.2.1-alpha.2";We();ne();var fo="1008033",Gf="1289";var qf="pbbp2",jf="https://www.coze.cn",Kf="/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 Wf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??q_}function In(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 Mi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Ni=H("handshake");async function Wc(t){let e=Pr(t.endpoint),r=t.timeoutMs??1e4,i=`${Dr(e)}${Kf}?aid=${encodeURIComponent(fo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...In(t.ppeOverride)},c=new AbortController,l=setTimeout(()=>c.abort(),r);Ni.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 v=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${v.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 y=g.data??{},S=typeof y.access_key=="string"&&y.access_key||typeof y.accessKey=="string"&&y.accessKey||void 0,_=typeof y.device_id=="string"&&y.device_id||typeof y.deviceId=="string"&&y.deviceId||void 0;if(!S||!_){let v=JSON.stringify(g).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${v}`)}return Ni.info("handshake ok",{remoteDeviceId:_,logid:f,traceId:x}),{accessKey:S,deviceId:_}}catch(u){if(u instanceof k)throw Ni.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Ni.warn("handshake timeout",{base:e,timeoutMs:r}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let f=u.cause;throw Ni.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 $c=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",bt="auto",$f=15e4;function Vf(t){return{model:Vc(t.model)??bt,...t.modelToken?{modelToken:t.modelToken}:{}}}function Jf(t){return!t||t===bt}var j_=new Set(["auto","\u81EA\u52A8"]);function Vc(t){let e=t?.trim();if(e)return j_.has(e.toLowerCase())?bt:e}function Zf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=$c,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||bt;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else Jf(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Yf(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||bt}"`):Jf(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="${$c}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"');let r=t.modelInfo?.contextWindow??$f;e.push("-c",`model_context_window=${r}`)}return e}function Xf(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function Jc(t,e){let{ttEnv:r,usePpe:i}=Mi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function Qf(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 Zc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function e0(t,e,r){if(!t.modelToken)return null;let i=t.model||bt,o=Jc(e,r),c=["text"];t.modelInfo?.capabilities?.image===!0&&c.push("image");let l={baseUrl:`${$c}/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??$f,maxTokens:8192,api:"openai-completions"}]};return Object.keys(o).length>0&&(l.headers=o),l}function t0(t,e,r){if(!t.modelToken)return[];let i=Jc(e,r),o=[];for(let[c,l]of Object.entries(i))o.push("-c",`model_providers.coze.http_headers.${c}="${l}"`);return o}var pe=H("agent-handlers"),r0=5*1024*1024,V_=1,J_=6,Z_=new Set(["node_modules",".git",".coze","dist","build",".next"]),Y_=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,X_=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Q_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function ey(t){let e=t?.trim();return e?Q_.test(e)||X_.test(e)?e:(pe.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function ty(t){return new Promise((e,r)=>{let i=it("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 xo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Jn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ze(r).workspace,c=i?.skills??[],l=[],u=new Set;for(let f of c){let x=Ve(o,f.relPath,"SKILL.md");await n0(x).then(y=>y.isFile()).catch(()=>!1)&&(l.push(sy(f)),u.add(f.relPath))}if(e.scanLocal){let f=i?.framework??"claude-code",x=await ny(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=Jn(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 po({agentId:r,workspace:i.workspace,framework:i.framework,skill:f});go(c,l,x),u.push(f)}return await ai(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Jn(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=Ve(i.workspace,u.relPath);await Qc(f,{recursive:!0,force:!0}),pe.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await ai(r,l),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Jn(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");pe.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??Ze(r).workspace,c=i?.framework??"claude-code",l=d0(e.skillName),u=Ve(sd(c),l),f=Ve(o,u),x=Ve(f,"SKILL.md");if(!await n0(x).then(T=>T.isFile()).catch(()=>!1))throw new k("SKILL_NOT_FOUND",`skill not found locally: ${e.skillName} (${u})`);let y=new id.default;y.addLocalFolder(f,l);let S=y.toBuffer();if(S.length>i0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${S.length} bytes exceeds limit ${i0}`);let _=await ho(x,{encoding:"utf8"}).then(T=>u0(T).description).catch(()=>{}),v={};this.opts.publishSkillToMarketplace?v=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}:{}}):pe.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let I=v.version??"v1.0",A=v.skillId??e.skillId??l0(r,u);if(i){let T=i.skills??[],D=T.find(E=>E.relPath===u);D?(D.version=I,D.skillId=A):T.push({skillId:A,skillName:e.skillName,relPath:u,version:I,installedAt:Date.now(),..._?{description:_}:{}}),await ai(r,T)}return pe.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,pe.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,pe.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l}),f.stop(r).catch(x=>pe.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 pe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await De(r);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return pe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await hr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw pe.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 ze(i),pe.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 De(r))throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Li(e.registry)&&o.push(`--registry=${e.registry}`);let c=ey(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&Y_.test(l)&&o.push("--env",l);let u=await ty(o);return pe.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 De(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await ze(i),pe.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}):(pe.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST",`${ft.DELETE}: missing agentId`);let i=await De(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=Ze(r);return c==="cloud"?await Qc(l.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await ze(i)),pe.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Rr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Vc(e.model)??bt,i=await De(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 ze(i),pe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return pe.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=>pe.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),pe.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(Rr(e._meta,ft.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ft.RESET),await this.runDetailSync(e.agentId,ft.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),pe.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 oi(e,o)}async clearPersistedAcpSessionIds(e){let r=await De(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 ze(r)}async repairAgent(e){if(Rr(e._meta,ft.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${ft.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){pe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ft.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){pe.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){pe.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Rr(e._meta,"_agent/getFileTree");let r=e._meta,i=Jn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(o,c),u=await Yc(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 si(l,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=my(e.depth);return u.isDirectory()?{tree:await gy(o,l,c,f)}:{tree:[{name:wy(c),path:x0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Rr(e._meta,"_agent/getFileContent");let r=Jn(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 Yc(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 si(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>r0)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${r0})`);let l=await ho(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 De(e).catch(()=>null))?.workspace??Ze(e).workspace}safeJoin(e,r){let i=td(e,r||"."),o=rd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${o0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return De(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 d0(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 sd(t){return t==="claude-code"?Ve(".claude","skills"):Ve(".agents","skills")}function l0(t,e){return(K_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function u0(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 ny(t,e,r){let i=sd(r),o=Ve(e,i),c=await s0(o,{withFileTypes:!0}).catch(()=>null);if(!c)return[];let l=[];for(let u of c){if(!u.isDirectory())continue;let f=u.name,x=Ve(i,f),g=Ve(o,f,"SKILL.md"),y=await ho(g,{encoding:"utf8"}).catch(()=>null);if(y===null)continue;let S=u0(y);l.push({relPath:x,skill:{skillId:l0(t,x),skillName:S.name||f,...S.description?{description:S.description}:{}}})}return l}var ry=3e4,iy=50*1024*1024,i0=10*1024*1024,Or=3e4;async function po(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=d0(o.skillName),f=sd(i),x=Ve(f,u),g=Ve(r,x);if(await Xc(g,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");Bi(S.length),await ed(Ve(g,"SKILL.md"),S,"utf8")}else{let S=await ay(o.downloadUrl);dy(S)?await hy(S,g):ly(S)?await uy(S,g):await ed(Ve(g,"SKILL.md"),S.toString("utf8"),"utf8")}let y={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 pe.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:c?"content":"downloadUrl"}),y}function go(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 sy(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 oy(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 f0(t,e){let r=await De(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Lt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],l=new Map(c.map((g,y)=>[g.skillId,y])),u=c.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"noop",count:0};let f=0,x=0;for(let g of u)try{await Qc(Ve(r.workspace,g.relPath),{recursive:!0,force:!0});let y=await po({agentId:t,workspace:r.workspace,framework:r.framework,skill:oy(g)});go(c,l,y),f+=1}catch(y){x+=1,pe.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(y)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await ze(r,e),pe.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function ay(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Bi(e);let r=cy(t);return Bi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await ho(e);return Bi(r.length),r}if(Li(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),ry);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 Bi(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 Bi(t){if(t>iy)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function cy(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 dy(t){return t.length>=2&&t[0]===31&&t[1]===139}function ly(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 nd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function uy(t,e){let r,i;try{r=new id.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||nd(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=fy(i),c=td(e);for(let l of i){if(nd(l.entryName))continue;let u=l.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=td(e,u),x=rd(c,f);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await Xc(f,{recursive:!0});continue}await Xc(W_(f),{recursive:!0});let g;try{g=l.getData()}catch(y){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${y.message}`,{cause:y})}await ed(f,g)}}function fy(t){let e;for(let r of t){let i=r.entryName;if(!i||nd(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 hy(t,e){await xy(t);let r=Lf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await c0(a0.from(t),r)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function xy(t){let e=[],r=Cr({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 (${Or}ms)`))},Or);try{await c0(a0.from(t),r)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Or}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 py=5e3;async function gy(t,e,r,i){return h0(t,e,r,i,{count:0})}async function h0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await s0(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if(Z_.has(u.name)||u.isSymbolicLink())continue;if(o.count>=py){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=Ve(e,u.name),x=$_(Ve(r,u.name)),g=null;try{g=await Yc(f)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let y={name:u.name,path:x0(rd(t,f)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(y.children=await h0(t,f,x,i-1,o)),l.push(y)}return l.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),l}function my(t){return!t||t<=0?V_:Math.min(t,J_)}function wy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function x0(t){return t.split(o0).join("/")}ne();var An=H("agent-health-reporter"),_y=1e4,yy=3,Fi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??_y,this.livenessFailureThreshold=e.livenessFailureThreshold??yy}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 r=[];for(let l of this.opts.core.agents.values()){let u=Ey(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:Lt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(l){this.consecutiveFailures+=1,An.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let c=o?.authFailures;if(c&&c.length>0&&(An.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){An.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){An.warn("onTickEnd hook failed",{err:String(r)})}}};function Ey(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}un();import{mkdir as hd,rm as CE,stat as RE}from"node:fs/promises";import{homedir as DE}from"node:os";import{join as j0}from"node:path";on();import{existsSync as Ly}from"node:fs";import{release as Ny}from"node:os";import{basename as My,isAbsolute as By}from"node:path";function zi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}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 kn(t,e){return{jsonrpc:"2.0",id:t,error:e}}We();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)}},X={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 p0(t){return"method"in t&&"id"in t&&t.id!==void 0}function g0(t){return"method"in t&&!("id"in t)}function wo(t){return!("method"in t)&&"id"in t}var by={AGENT_NOT_FOUND:X.AGENT_NOT_FOUND,AGENT_BUSY:X.AGENT_BUSY,AGENT_DISCONNECTED:X.AGENT_DISCONNECTED,AGENT_TIMEOUT:X.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:X.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:X.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:X.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:X.INTERNAL_ERROR,BRIDGE_INTERNAL:X.INTERNAL_ERROR,IPC_AUTH_FAILED:X.INTERNAL_ERROR,IPC_BAD_REQUEST:X.INVALID_REQUEST,METHOD_NOT_FOUND:X.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:X.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:X.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:X.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:X.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:X.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:X.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:X.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:X.FILE_TOO_LARGE,UNSUPPORTED_MIME:X.UNSUPPORTED_MIME,UPLOAD_FAILED:X.UPLOAD_FAILED,UPSTREAM_NOT_READY:X.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:X.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:X.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:X.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:X.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:X.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:X.SKILL_ZIP_TOO_LARGE};function vy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Ui(t.message)}:typeof t=="string"?Ui(t):typeof t=="object"?Iy(t):t}var Sy=[[/\/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 Ui(t){let e=t;for(let[r,i]of Sy)e=e.replace(r,i);return e}function Iy(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Ui(i):e[r]=i;return e}function Hi(t){if(t instanceof k){let e=vy(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:by[t.code]??X.INTERNAL_ERROR,message:Ui(t.message),data:r}}return{code:X.INTERNAL_ERROR,message:Ui(t instanceof Error?t.message:String(t))}}function m0(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 _0(t){return`${JSON.stringify(t)}
95
- `}var w0=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>w0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${w0} 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 E0={"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"},Fk=Object.fromEntries(Object.entries(E0).map(([t,e])=>[e,t])),Ay={"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,r){this.seq+=1;let i=E0[e]??ky(e),o=Ay[i]??[],c=[i,String(this.seq)];if(o.length>0){let l=o.map(f=>y0(r?.[f]??"")),u=Ty(l).join(":");u&&c.push(u)}else r&&Object.values(r).some(l=>l)&&c.push(Object.values(r).filter(Boolean).map(l=>y0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function ky(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function y0(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 Cy}from"node:fs";var Ry=384;async function od(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await dn(t.agentEnvFile,r,{mode:Ry})}function Gi(t){try{let e=JSON.parse(Cy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function yo(t,e,r={},i=o=>o){return{...i({...t,...Gi(e)}),...r}}Vt();cr();We();ne();Re();import{execFileSync as Dy,spawnSync as Py}from"node:child_process";function qi(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 r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Py("taskkill",r,{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 v0(t){typeof t=="number"&&ad.delete(t)}function S0(){for(let t of ad)ji(t,"SIGKILL")}var Br="coze-bridge-daemon";function I0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return Dy("pgrep",["-U",String(o),"-f",Br],{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 A0(t,e){if(t.length===0)return;let r=e?.killFn??ji,i=e?.isAliveFn??qi,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 Oy=[{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\/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|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 k0(t,e){if(!e)return null;for(let r of Oy)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function T0(t,e){return k0(t,e)}function C0(t,e){return k0(t,e)}function Fr(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 R0(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:Fr(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:Fr(c,!0,e)}:r-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=Je("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Fy=200,zy=40,Uy=Je("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Hy=Je("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Gy=Je("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),qy=Je("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),jy=Je("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Ky=Je("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),P0=500;function Wy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=P0?t:`${e.slice(0,P0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function $y(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 O0(t){try{return Ly(t)}catch{return}}function Vy(t,e){return{platform:process.platform,osRelease:Ny(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:By(e.command)?O0(e.command):void 0,cwd:e.cwd,cwdExists:O0(e.cwd),envKeys:e.envKeys}}function Jy(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${My(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Nt=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new _o({onError:r=>this.log.warn("decode line failed",{line:r.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 k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=yo(process.env,this.opts.agentEnvFile??Y().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=it(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,b0(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>Fy&&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,v0(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=Vy(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",Jy(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()));ji(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||ji(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:jy,phase2GateMs:Uy,livenessWindowMs:Hy,absoluteMaxMs:Gy,approvalMaxMs:Ky,suspendThresholdMs:qy,...r};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,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Nr(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(kn(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=D0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=zi(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 y=this.now(),S={cfg:o,startedAt:y,lastActivityAt:y,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:y,expectedIntervalMs:Fr(0,!1,o),sessionId:u};g.promptTimeout=S;let _=()=>{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=R0(v,S.cfg,I),T=D=>{S.armedAt=I,S.expectedIntervalMs=D,g.timer=setTimeout(_,D)};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(y){g.timer&&clearTimeout(g.timer),this.pending.delete(c),x(y)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(_0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(wo(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:Wy(e.result)}),r.resolve(e.result));return}if(g0(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(p0(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(kn(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(kn(e.id,Hi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=m0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=C0(this.framework,$y(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(zy).join(`
98
- `),o=T0(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 Zy(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 Eo=class extends Nt{framework="claude-code";constructor(e){let{command:r,args:i}=ii("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 Zy(e)}};on();import{spawn as Yy}from"node:child_process";import{closeSync as Xy,existsSync as M0,mkdirSync as Qy,mkdtempSync as eE,openSync as tE,readFileSync as nE,readSync as rE,readdirSync as iE,rmSync as sE,statSync as oE}from"node:fs";import{homedir as aE,tmpdir as cE}from"node:os";import{join as Ki}from"node:path";Re();var dd=9e4,dE=64*1024,lE=100;function uE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?dd:Math.max(1,Math.floor(e*1e3))}function fE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?dd:Math.max(1,Math.floor(e))}function hE(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[r,i]of Object.entries(t))typeof i=="string"&&(e[r]=i);return Object.keys(e).length>0?e:void 0}function L0(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:dd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let r=typeof e.command=="string"?e.command.trim():"";if(!r)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,o=hE(e.env);return{command:r,timeoutMs:e.timeout_ms===void 0?uE(e.timeout):fE(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function cd(t){if(Array.isArray(t))return t.flatMap(i=>cd(i));if(!t||typeof t!="object"){let i=L0(t);return i?[i]:[]}let e=t;if(e.hooks)return cd(e.hooks);let r=L0(e);return r?[r]:[]}function xE(t){let e=Ki(t,"hooks.json");if(!M0(e))return[];let r=JSON.parse(nE(e,"utf8")),o=r.hooks&&typeof r.hooks=="object"?r.hooks:r;return cd(o.Stop??o.stop)}function pE(t,e){let r=Ki(t,"sessions");if(!M0(r))return;let i=[],o=c=>{let l;try{l=iE(c,{withFileTypes:!0})}catch{return}for(let u of l){let f=Ki(c,u.name);if(u.isDirectory())o(f);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:f,mtimeMs:oE(f).mtimeMs})}catch{}}};o(r),i.sort((c,l)=>l.mtimeMs-c.mtimeMs);for(let c of i.slice(0,lE))if(gE(c.path,e))return c.path;return i[0]?.path}function gE(t,e){let r;try{r=tE(t,"r");let i=Buffer.alloc(dE),o=rE(r,i,0,i.length,0),c=i.subarray(0,o).toString("utf8");return c.includes(JSON.stringify(e))||c.includes(e)}catch{return!1}finally{if(r!==void 0)try{Xy(r)}catch{}}}function mE(t){return Gi(t??Y().agentEnvFile)}function N0(t){let e=t?.trim();return e||void 0}function wE(t){let e=mE(t.agentEnvFile),r=N0(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(r)return r;let i=N0(t.env?.HOME??e.HOME??process.env.HOME)??aE();return Ki(i,".codex")}var bo=class extends Nt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ii("codex",e.command,i),l=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??eE(Ki(cE(),"coze-bridge-codex-home-")):wE(e),u=!!e.isolateCodexHome&&!!l&&!e.codexHomeDir&&e.env?.CODEX_HOME!==l;e.isolateCodexHome&&l&&!u&&Qy(l,{recursive:!0});let f=e.isolateCodexHome&&l?{...e.env??{},CODEX_HOME:l}:e.env,x={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...f?{env:f}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=l,this.cleanupCodexHomeDir=u}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}async sessionPrompt(e){let r=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),r}async runStopHooksBestEffort(e){let r=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!r)return;let i;try{i=xE(r)}catch(l){this.log.warn("codex stop hook load failed",{codexHomeDir:r,err:String(l)});return}if(i.length===0)return;let o=pE(r,e),c=JSON.stringify({hook_event_name:"Stop",session_id:e,...o?{transcript_path:o}:{},trigger:"coze-bridge"});await Promise.all(i.map(async l=>{try{await this.runHookCommand(l,c)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:r,command:l.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,r){return new Promise((i,o)=>{let c=Yy(e.command,{cwd:e.cwd??this.opts.cwd,env:yo(process.env,this.opts.agentEnvFile??Y().agentEnvFile,{...this.opts.env??{},...e.env??{}}),shell:!0,stdio:["pipe","ignore","pipe"]}),l="",u=setTimeout(()=>{c.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);c.stderr?.setEncoding("utf8"),c.stderr?.on("data",f=>{l+=f,l.length>4e3&&(l=l.slice(-4e3))}),c.on("error",f=>{clearTimeout(u),o(f)}),c.on("close",(f,x)=>{if(clearTimeout(u),f===0){i();return}o(new Error(`hook exited code=${f} signal=${x} stderr=${l.slice(-1e3)}`))}),c.stdin.end(`${r}
99
- `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{sE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};We();var _E=3e4,zr=class extends Nt{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}`}]},_E))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var B0=["default","acceptEdits","plan","auto","bypassPermissions"],F0=["read-only","auto","full-access"];function Tn(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return B0.includes(e);case"codex":return F0.includes(e);case"openclaw":return!1}}function ld(t){switch(t){case"claude-code":return B0.join("/");case"codex":return F0.join("/");case"openclaw":return""}}ln();We();ne();Re();function ud(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}on();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((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 vo=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 Cn,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)Wi(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 Wi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Jt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Vt();ne();import{constants as z0}from"node:fs";import{access as yE}from"node:fs/promises";import{delimiter as EE,join as bE}from"node:path";var vt=H("framework-detector"),U0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},vE=[".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??it,access:e.access??yE}}async detect(e){let r=U0[e],i=await this.which(r);if(!i)return vt.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,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(U0).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(EE).filter(Boolean),i=this.env.platform==="win32"?["",...vE]:[""];for(let o of r)for(let c of i){let l=bE(o,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?z0.F_OK:z0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return vt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return vt.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return vt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return vt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(l=>l?.isDefault===!0);return c?!c.id||!c.workspace?(vt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(vt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return vt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return vt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||vt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let 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){vt.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&&(IE(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)}})}},SE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function IE(t){return t.replace(SE,"")}import{homedir as G0}from"node:os";import{join as Io}from"node:path";ln();Vt();cr();We();ne();async function q0(){let t=Io(G0(),".openclaw/openclaw.json");return(await an(t))?.gateway?.auth?.token??""}var Yn=H("openclaw.config"),AE=[0,5e3,5e3],kE=Je("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),H0="models.providers.",So="agents.defaults.models",TE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function fd(t,e){if(!Array.isArray(t))return!1;let r=new Set(t);return e.every(i=>r.has(i))}var Ao=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Cn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??AE,this.cliTimeoutMs=e.cliTimeoutMs??kE,this.openclawDir=e.openclawDir??Io(G0(),".openclaw")}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,Yn.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=it(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){Yn.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",`${H0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${H0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${So}[${e}]`,()=>this.runCli(["config","set",So,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${So}[${e}]`,`${So}.${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"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}async ensureAcpDeviceScopes(){try{let e=Io(this.openclawDir,"identity","device.json"),i=(await an(e))?.deviceId?.trim();if(!i)return Yn.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Io(this.openclawDir,"devices","paired.json"),c=await an(o),l=c?.[i];if(!c||!l)return Yn.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=[...TE],f=l.tokens?.operator;return fd(l.scopes,u)&&fd(l.approvedScopes,u)&&fd(f?.scopes,u)?(Yn.debug("acp device already has full operator scopes",{deviceId:i}),!1):(l.scopes=[...u],l.approvedScopes=[...u],f&&(f.scopes=[...u]),await dn(o,c,{mode:384}),Yn.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:u}),!0)}catch(e){return Yn.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};var ue=H("agent-manager"),pd="acceptEdits",$0="full-access",V0="read-only";function PE(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 OE=(t,e,r,i,o,c,l,u,f,x)=>{switch(t){case"claude-code":{let g={...o?{...Zf(o),...Qf(o,l,u)}:{},...f??{},IS_SANDBOX:"1"};return new Eo({cwd:r,env:g,agentId:i})}case"codex":{let g=o?[...Yf(o),...t0(o,l,u)]:[],y=$0;x!==void 0&&(Tn("codex",x)?y=x:ue.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let S=[...g,...PE(y)],_={...o?Xf(o):{},...f??{}},v=!!o;return new bo({cwd:r,agentId:i,...S.length>0?{extraArgs:S}:{},...Object.keys(_).length>0?{env:_}:{},...v?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new zr({command:e,cwd:r,agentId:i,...c?{sessionName:ud(c)}:{}})}};function xd(t){return t==="claude-code"||t==="codex"}function LE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(NE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return Ck(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 Qm("schtasks",["/Create","/SC","ONLOGON","/TN",za,"/TR",n,"/RU",t.userName,"/F"]),jd.info("task scheduler entry created",{task:za,logFile:t.logFile})},async uninstall(t){await Qm("schtasks",["/Delete","/TN",za,"/F"]).catch(e=>jd.warn("schtasks /Delete failed (ignored)",{err:String(e)})),jd.info("task scheduler entry removed",{task:za})}}});var tw={};ec(tw,{buildContext:()=>Mk,getSupervisor:()=>Lk,launchdSupervisor:()=>Hd,systemdSupervisor:()=>$d,taskSchedulerSupervisor:()=>Wd});import{homedir as Pk,userInfo as Dk}from"node:os";function Lk(t=process.platform){switch(t){case"darwin":return Hd;case"linux":return $d;case"win32":return Wd;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function Nk(){let t={};for(let e of Ok){let n=process.env[e];n&&(t[e]=n)}return t}function Mk(){let t=ie();return{nodeBin:process.execPath,entry:pd(t),logFile:t.logFile,homeDir:Pk(),userName:Dk().username,isRoot:process.getuid?.()===0,env:Nk()}}var Ok,nw=at(()=>{"use strict";Be();ma();Jm();Xm();ew();Ok=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});oe();pn();var Su=$("acp-installer-warmup"),k_=["claude-code","codex"];async function Iu(t={}){let e=t.ensure??wr,i=(await Promise.allSettled(k_.map(async s=>{let a=await e(s);Su.info("acp wrapper warmup ok",{framework:s,path:a})}))).filter(s=>s.status==="rejected");i.length>0&&Su.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))})}wn();oe();import{readdir as j_}from"node:fs/promises";import{mkdir as ku,readFile as H_,writeFile as Cu}from"node:fs/promises";import{join as ac}from"node:path";var $_={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Er(t,e,n){await ku(t,{recursive:!0});let i=$_[e],s=ac(t,i);return await Cu(s,n??"","utf8"),s}async function cc(t,e,n){let i=ac(t,".claude");await ku(i,{recursive:!0});let s=ac(i,"settings.local.json"),a={};try{let u=await H_(s,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(a=f)}catch{}let l=typeof a.permissions=="object"&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{};if(e==="cloud")l.defaultMode="bypassPermissions",a.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");l.defaultMode===void 0&&(l.defaultMode=n)}return a.permissions=l,await Cu(s,JSON.stringify(a,null,2),"utf8"),s}var rt=$("agent-detail-sync"),W_=6e4,K_=5*6e4,Ns=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await j_(n)}catch(s){rt.info("agents dir not found, skip detail sync",{root:n,err:String(s)});return}rt.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async s=>{let a=await De(s,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){rt.debug("detail sync: skip disconnected agent",{agentId:s});return}try{await this.syncOne(s,a)}catch(l){rt.warn("detail sync failed for agent, skipping",{agentId:s,err:String(l)})}}})),rt.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){rt.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(s){rt.debug("detail sync retry still failing, will try again",{agentId:i,err:String(s)})}}}async syncOne(e,n){let i=n??await De(e,this.opts.paths);if(!i){rt.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(f){rt.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),m=x?Math.min(x.currentDelay*2,K_):W_;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(s.agentId&&s.agentId!==e){rt.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:s.agentId});return}let a=!1,l=!1;s.agentName&&s.agentName!==i.agentName&&(i.agentName=s.agentName,a=!0),s.description!==void 0&&s.description!==i.description&&(i.description=s.description,a=!0),s.cozeIdentity&&s.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=s.cozeIdentity,a=!0,l=!0);let u=!1;if(s.deployType==="cloud"&&i.deployType!=="cloud"?(rt.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):s.deployType&&rt.info("detail.deployType",{agentId:e,deployType:s.deployType}),!a){rt.debug("detail sync: no diff",{agentId:e});return}await qe(i,this.opts.paths),rt.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}),rt.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await Er(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var kl=Nt(df(),1);import{createHash as Ab}from"node:crypto";import{lstat as bl,mkdir as vl,readFile as Ro,readdir as V0,rm as Sl,stat as Z0,writeFile as Il}from"node:fs/promises";import{homedir as Tb}from"node:os";import{dirname as Rb,join as Ee,normalize as kb,relative as Rl,resolve as Al,sep as J0}from"node:path";import{Readable as Y0}from"node:stream";import{pipeline as X0}from"node:stream/promises";import py from"events";import ct from"fs";import{EventEmitter as al}from"node:events";import jf from"node:stream";import{StringDecoder as gy}from"node:string_decoder";import Vf from"node:path";import Lr from"node:fs";import{dirname as ky,parse as Cy}from"path";import{EventEmitter as Fy}from"events";import qc from"assert";import{Buffer as Qn}from"buffer";import*as pf from"zlib";import zy from"zlib";import{posix as Ar}from"node:path";import{basename as fE}from"node:path";import xo from"fs";import Ut from"fs";import bf from"path";import{win32 as vE}from"node:path";import kf from"path";import l0 from"node:fs";import UE from"node:assert";import{randomBytes as d0}from"node:crypto";import ce from"node:fs";import ze from"node:path";import u0 from"fs";import vo from"node:fs";import Bi from"node:path";import ht from"node:fs";import KE from"node:fs/promises";import mo from"node:path";import{join as b0}from"node:path";import ft from"node:fs";import I0 from"node:path";var hy=Object.defineProperty,xy=(t,e)=>{for(var n in e)hy(t,n,{get:e[n],enumerable:!0})},uf=typeof process=="object"&&process?process:{stdout:null,stderr:null},my=t=>!!t&&typeof t=="object"&&(t instanceof nr||t instanceof jf||wy(t)||_y(t)),wy=t=>!!t&&typeof t=="object"&&t instanceof al&&typeof t.pipe=="function"&&t.pipe!==jf.Writable.prototype.pipe,_y=t=>!!t&&typeof t=="object"&&t instanceof al&&typeof t.write=="function"&&typeof t.end=="function",Yt=Symbol("EOF"),Xt=Symbol("maybeEmitEnd"),yn=Symbol("emittedEnd"),Us=Symbol("emittingEnd"),yi=Symbol("emittedError"),Gs=Symbol("closed"),ff=Symbol("read"),qs=Symbol("flush"),hf=Symbol("flushChunk"),At=Symbol("encoding"),Ir=Symbol("decoder"),He=Symbol("flowing"),Ei=Symbol("paused"),Cr=Symbol("resume"),$e=Symbol("buffer"),it=Symbol("pipes"),je=Symbol("bufferLength"),xc=Symbol("bufferPush"),Hs=Symbol("bufferShift"),nt=Symbol("objectMode"),ke=Symbol("destroyed"),pc=Symbol("error"),gc=Symbol("emitData"),xf=Symbol("emitEnd"),mc=Symbol("emitEnd2"),Bt=Symbol("async"),wc=Symbol("abort"),$s=Symbol("aborted"),bi=Symbol("signal"),$n=Symbol("dataListeners"),ut=Symbol("discarded"),vi=t=>Promise.resolve().then(t),yy=t=>t(),Ey=t=>t==="end"||t==="finish"||t==="prefinish",by=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,vy=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Wf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Cr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Sy=class extends Wf{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)}},Iy=t=>!!t.objectMode,Ay=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",nr=class extends al{[He]=!1;[Ei]=!1;[it]=[];[$e]=[];[nt];[At];[Bt];[Ir];[Yt]=!1;[yn]=!1;[Us]=!1;[Gs]=!1;[yi]=null;[je]=0;[ke]=!1;[bi];[$s]=!1;[$n]=0;[ut]=!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");Iy(e)?(this[nt]=!0,this[At]=null):Ay(e)?(this[At]=e.encoding,this[nt]=!1):(this[nt]=!1,this[At]=null),this[Bt]=!!e.async,this[Ir]=this[At]?new gy(this[At]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[$e]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[it]});let{signal:n}=e;n&&(this[bi]=n,n.aborted?this[wc]():n.addEventListener("abort",()=>this[wc]()))}get bufferLength(){return this[je]}get encoding(){return this[At]}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[nt]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Bt]}set async(t){this[Bt]=this[Bt]||!!t}[wc](){this[$s]=!0,this.emit("abort",this[bi]?.reason),this.destroy(this[bi]?.reason)}get aborted(){return this[$s]}set aborted(t){}write(t,e,n){if(this[$s])return!1;if(this[Yt])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[Bt]?vi:yy;if(!this[nt]&&!Buffer.isBuffer(t)){if(vy(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(by(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[nt]?(this[He]&&this[je]!==0&&this[qs](!0),this[He]?this.emit("data",t):this[xc](t),this[je]!==0&&this.emit("readable"),n&&i(n),this[He]):t.length?(typeof t=="string"&&!(e===this[At]&&!this[Ir]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[At]&&(t=this[Ir].write(t)),this[He]&&this[je]!==0&&this[qs](!0),this[He]?this.emit("data",t):this[xc](t),this[je]!==0&&this.emit("readable"),n&&i(n),this[He]):(this[je]!==0&&this.emit("readable"),n&&i(n),this[He])}read(t){if(this[ke])return null;if(this[ut]=!1,this[je]===0||t===0||t&&t>this[je])return this[Xt](),null;this[nt]&&(t=null),this[$e].length>1&&!this[nt]&&(this[$e]=[this[At]?this[$e].join(""):Buffer.concat(this[$e],this[je])]);let e=this[ff](t||null,this[$e][0]);return this[Xt](),e}[ff](t,e){if(this[nt])this[Hs]();else{let n=e;t===n.length||t===null?this[Hs]():typeof n=="string"?(this[$e][0]=n.slice(t),e=n.slice(0,t),this[je]-=t):(this[$e][0]=n.subarray(t),e=n.subarray(0,t),this[je]-=t)}return this.emit("data",e),!this[$e].length&&!this[Yt]&&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[Yt]=!0,this.writable=!1,(this[He]||!this[Ei])&&this[Xt](),this}[Cr](){this[ke]||(!this[$n]&&!this[it].length&&(this[ut]=!0),this[Ei]=!1,this[He]=!0,this.emit("resume"),this[$e].length?this[qs]():this[Yt]?this[Xt]():this.emit("drain"))}resume(){return this[Cr]()}pause(){this[He]=!1,this[Ei]=!0,this[ut]=!1}get destroyed(){return this[ke]}get flowing(){return this[He]}get paused(){return this[Ei]}[xc](t){this[nt]?this[je]+=1:this[je]+=t.length,this[$e].push(t)}[Hs](){return this[nt]?this[je]-=1:this[je]-=this[$e][0].length,this[$e].shift()}[qs](t=!1){do;while(this[hf](this[Hs]())&&this[$e].length);!t&&!this[$e].length&&!this[Yt]&&this.emit("drain")}[hf](t){return this.emit("data",t),this[He]}pipe(t,e){if(this[ke])return t;this[ut]=!1;let n=this[yn];return e=e||{},t===uf.stdout||t===uf.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[it].push(e.proxyErrors?new Sy(this,t,e):new Wf(this,t,e)),this[Bt]?vi(()=>this[Cr]()):this[Cr]()),t}unpipe(t){let e=this[it].find(n=>n.dest===t);e&&(this[it].length===1?(this[He]&&this[$n]===0&&(this[He]=!1),this[it]=[]):this[it].splice(this[it].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[ut]=!1,this[$n]++,!this[it].length&&!this[He]&&this[Cr]();else if(t==="readable"&&this[je]!==0)super.emit("readable");else if(Ey(t)&&this[yn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[yi]){let i=e;this[Bt]?vi(()=>i.call(this,this[yi])):i.call(this,this[yi])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[$n]=this.listeners("data").length,this[$n]===0&&!this[ut]&&!this[it].length&&(this[He]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[$n]=0,!this[ut]&&!this[it].length&&(this[He]=!1)),e}get emittedEnd(){return this[yn]}[Xt](){!this[Us]&&!this[yn]&&!this[ke]&&this[$e].length===0&&this[Yt]&&(this[Us]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Gs]&&this.emit("close"),this[Us]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==ke&&this[ke])return!1;if(t==="data")return!this[nt]&&!n?!1:this[Bt]?(vi(()=>this[gc](n)),!0):this[gc](n);if(t==="end")return this[xf]();if(t==="close"){if(this[Gs]=!0,!this[yn]&&!this[ke])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(t==="error"){this[yi]=n,super.emit(pc,n);let s=!this[bi]||this.listeners("error").length?super.emit("error",n):!1;return this[Xt](),s}else if(t==="resume"){let s=super.emit("resume");return this[Xt](),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[Xt](),i}[gc](t){for(let n of this[it])n.dest.write(t)===!1&&this.pause();let e=this[ut]?!1:super.emit("data",t);return this[Xt](),e}[xf](){return this[yn]?!1:(this[yn]=!0,this.readable=!1,this[Bt]?(vi(()=>this[mc]()),!0):this[mc]())}[mc](){if(this[Ir]){let e=this[Ir].end();if(e){for(let n of this[it])n.dest.write(e);this[ut]||super.emit("data",e)}}for(let e of this[it])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[nt]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[nt]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[nt])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[At]?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[ut]=!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[Yt])return e();let i,s,a=x=>{this.off("data",l),this.off("end",u),this.off(ke,f),e(),s(x)},l=x=>{this.off("error",a),this.off("end",u),this.off(ke,f),this.pause(),i({value:x,done:!!this[Yt]})},u=()=>{this.off("error",a),this.off("data",l),this.off(ke,f),e(),i({done:!0,value:void 0})},f=()=>a(new Error("stream destroyed"));return new Promise((x,m)=>{s=m,i=x,this.once(ke,f),this.once("error",a),this.once("end",u),this.once("data",l)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ut]=!1;let t=!1,e=()=>(this.pause(),this.off(pc,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(pc,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[ut]=!0,this[$e].length=0,this[je]=0;let e=this;return typeof e.close=="function"&&!this[Gs]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return my}},Ty=ct.writev,Cn=Symbol("_autoClose"),Ct=Symbol("_close"),Si=Symbol("_ended"),fe=Symbol("_fd"),_c=Symbol("_finished"),nn=Symbol("_flags"),yc=Symbol("_flush"),Uc=Symbol("_handleChunk"),Gc=Symbol("_makeBuf"),Ni=Symbol("_mode"),js=Symbol("_needDrain"),Nr=Symbol("_onerror"),Mr=Symbol("_onopen"),Ec=Symbol("_onread"),Pr=Symbol("_onwrite"),Pn=Symbol("_open"),kt=Symbol("_path"),In=Symbol("_pos"),Ft=Symbol("_queue"),Dr=Symbol("_read"),bc=Symbol("_readSize"),tn=Symbol("_reading"),Ii=Symbol("_remain"),vc=Symbol("_size"),to=Symbol("_write"),jn=Symbol("_writing"),no=Symbol("_defaultFlag"),Xn=Symbol("_errored"),cl=class extends nr{[Xn]=!1;[fe];[kt];[bc];[tn]=!1;[vc];[Ii];[Cn];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[Xn]=!1,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[kt]=t,this[bc]=e.readSize||16*1024*1024,this[tn]=!1,this[vc]=typeof e.size=="number"?e.size:1/0,this[Ii]=this[vc],this[Cn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[fe]=="number"?this[Dr]():this[Pn]()}get fd(){return this[fe]}get path(){return this[kt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Pn](){ct.open(this[kt],"r",(t,e)=>this[Mr](t,e))}[Mr](t,e){t?this[Nr](t):(this[fe]=e,this.emit("open",e),this[Dr]())}[Gc](){return Buffer.allocUnsafe(Math.min(this[bc],this[Ii]))}[Dr](){if(!this[tn]){this[tn]=!0;let t=this[Gc]();if(t.length===0)return process.nextTick(()=>this[Ec](null,0,t));ct.read(this[fe],t,0,t.length,null,(e,n,i)=>this[Ec](e,n,i))}}[Ec](t,e,n){this[tn]=!1,t?this[Nr](t):this[Uc](e,n)&&this[Dr]()}[Ct](){if(this[Cn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ct.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Nr](t){this[tn]=!0,this[Ct](),this.emit("error",t)}[Uc](t,e){let n=!1;return this[Ii]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[Ii]<=0)&&(n=!1,this[Ct](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[fe]=="number"&&this[Dr](),!1;case"error":return this[Xn]?!1:(this[Xn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Ry=class extends cl{[Pn](){let t=!0;try{this[Mr](null,ct.openSync(this[kt],"r")),t=!1}finally{t&&this[Ct]()}}[Dr](){let t=!0;try{if(!this[tn]){this[tn]=!0;do{let e=this[Gc](),n=e.length===0?0:ct.readSync(this[fe],e,0,e.length,null);if(!this[Uc](n,e))break}while(!0);this[tn]=!1}t=!1}finally{t&&this[Ct]()}}[Ct](){if(this[Cn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ct.closeSync(t),this.emit("close")}}},wo=class extends py{readable=!1;writable=!0;[Xn]=!1;[jn]=!1;[Si]=!1;[Ft]=[];[js]=!1;[kt];[Ni];[Cn];[fe];[no];[nn];[_c]=!1;[In];constructor(t,e){e=e||{},super(e),this[kt]=t,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[Ni]=e.mode===void 0?438:e.mode,this[In]=typeof e.start=="number"?e.start:void 0,this[Cn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[In]!==void 0?"r+":"w";this[no]=e.flags===void 0,this[nn]=e.flags===void 0?n:e.flags,this[fe]===void 0&&this[Pn]()}emit(t,...e){if(t==="error"){if(this[Xn])return!1;this[Xn]=!0}return super.emit(t,...e)}get fd(){return this[fe]}get path(){return this[kt]}[Nr](t){this[Ct](),this[jn]=!0,this.emit("error",t)}[Pn](){ct.open(this[kt],this[nn],this[Ni],(t,e)=>this[Mr](t,e))}[Mr](t,e){this[no]&&this[nn]==="r+"&&t&&t.code==="ENOENT"?(this[nn]="w",this[Pn]()):t?this[Nr](t):(this[fe]=e,this.emit("open",e),this[jn]||this[yc]())}end(t,e){return t&&this.write(t,e),this[Si]=!0,!this[jn]&&!this[Ft].length&&typeof this[fe]=="number"&&this[Pr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Si]?(this.emit("error",new Error("write() after end()")),!1):this[fe]===void 0||this[jn]||this[Ft].length?(this[Ft].push(t),this[js]=!0,!1):(this[jn]=!0,this[to](t),!0)}[to](t){ct.write(this[fe],t,0,t.length,this[In],(e,n)=>this[Pr](e,n))}[Pr](t,e){t?this[Nr](t):(this[In]!==void 0&&typeof e=="number"&&(this[In]+=e),this[Ft].length?this[yc]():(this[jn]=!1,this[Si]&&!this[_c]?(this[_c]=!0,this[Ct](),this.emit("finish")):this[js]&&(this[js]=!1,this.emit("drain"))))}[yc](){if(this[Ft].length===0)this[Si]&&this[Pr](null,0);else if(this[Ft].length===1)this[to](this[Ft].pop());else{let t=this[Ft];this[Ft]=[],Ty(this[fe],t,this[In],(e,n)=>this[Pr](e,n))}}[Ct](){if(this[Cn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ct.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Kf=class extends wo{[Pn](){let t;if(this[no]&&this[nn]==="r+")try{t=ct.openSync(this[kt],this[nn],this[Ni])}catch(e){if(e?.code==="ENOENT")return this[nn]="w",this[Pn]();throw e}else t=ct.openSync(this[kt],this[nn],this[Ni]);this[Mr](null,t)}[Ct](){if(this[Cn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ct.closeSync(t),this.emit("close")}}[to](t){let e=!0;try{this[Pr](null,ct.writeSync(this[fe],t,0,t.length,this[In])),e=!1}finally{if(e)try{this[Ct]()}catch{}}}},Py=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"]]),Dy=t=>!!t.sync&&!!t.file,Ly=t=>!t.sync&&!!t.file,Oy=t=>!!t.sync&&!t.file,Ny=t=>!t.sync&&!t.file,My=t=>!!t.file,By=t=>Py.get(t)||t,ll=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let s=By(n);e[s]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},$i=(t,e,n,i,s)=>Object.assign((a=[],l,u)=>{Array.isArray(a)&&(l=a,a={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let f=ll(a);if(s?.(f,l),Dy(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,l)}else if(Ly(f)){let x=e(f,l);return u?x.then(()=>u(),u):x}else if(Oy(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(f,l)}else if(Ny(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:n,asyncNoFile:i,validate:s}),Uy=zy.constants||{ZLIB_VERNUM:4736},qt=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},Uy)),Gy=Qn.concat,gf=Object.getOwnPropertyDescriptor(Qn,"concat"),qy=t=>t,Sc=gf?.writable===!0||gf?.set!==void 0?t=>{Qn.concat=t?qy:Gy}:t=>{},er=Symbol("_superWrite"),Ws=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"}},Ic=Symbol("flushFlag"),dl=class extends nr{#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 pf[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new pf[e](t)}catch(n){throw new Ws(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 Ws(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return qc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Qn.alloc(0),{[Ic]: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}[er](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Qn.from(t,e)),this.#e)return;qc(this.#t,"zlib binding closed");let i=this.#t._handle,s=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},Sc(!0);let l;try{let f=typeof t[Ic]=="number"?t[Ic]:this.#r;l=this.#t._processChunk(t,f),Sc(!1)}catch(f){Sc(!1),this.#o(new Ws(f,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=s,this.#t.close=a,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",f=>this.#o(new Ws(f,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let f=l[0];u=this[er](Qn.from(f));for(let x=1;x<l.length;x++)u=this[er](l[x])}else u=this[er](Qn.from(l));return n&&n(),u}},Zf=class extends dl{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||qt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||qt.Z_FINISH,t.fullFlushFlag=qt.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(qt.Z_SYNC_FLUSH),qc(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)}}}},Hy=class extends Zf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[er](t){return this.#e?(this.#e=!1,t[9]=255,super[er](t)):super[er](t)}},$y=class extends Zf{constructor(t){super(t,"Unzip")}},Jf=class extends dl{constructor(t,e){t=t||{},t.flush=t.flush||qt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||qt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=qt.BROTLI_OPERATION_FLUSH,super(t,e)}},jy=class extends Jf{constructor(t){super(t,"BrotliCompress")}},Wy=class extends Jf{constructor(t){super(t,"BrotliDecompress")}},Yf=class extends dl{constructor(t,e){t=t||{},t.flush=t.flush||qt.ZSTD_e_continue,t.finishFlush=t.finishFlush||qt.ZSTD_e_end,t.fullFlushFlag=qt.ZSTD_e_flush,super(t,e)}},Ky=class extends Yf{constructor(t){super(t,"ZstdCompress")}},Vy=class extends Yf{constructor(t){super(t,"ZstdDecompress")}},Zy=(t,e)=>{if(Number.isSafeInteger(t))t<0?Yy(t,e):Jy(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Jy=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},Yy=(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]=Xf(s):s===0?e[i-1]=0:(n=!0,e[i-1]=Qf(s))}},Xy=t=>{let e=t[0],n=e===128?eE(t.subarray(1,t.length)):e===255?Qy(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},Qy=t=>{for(var e=t.length,n=0,i=!1,s=e-1;s>-1;s--){var a=Number(t[s]),l;i?l=Xf(a):a===0?l=a:(i=!0,l=Qf(a)),l!==0&&(n-=l*Math.pow(256,e-s-1))}return n},eE=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},Xf=t=>(255^t)&255,Qf=t=>(255^t)+1&255,tE={};xy(tE,{code:()=>ul,isCode:()=>ro,isName:()=>nE,name:()=>_o});var ro=t=>_o.has(t),nE=t=>ul.has(t),_o=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"]]),ul=new Map(Array.from(_o).map(t=>[t[1],t[0]])),tr=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");this.path=n?.path??Wn(t,e,100),this.mode=n?.mode??i?.mode??An(t,e+100,8),this.uid=n?.uid??i?.uid??An(t,e+108,8),this.gid=n?.gid??i?.gid??An(t,e+116,8),this.size=n?.size??i?.size??An(t,e+124,12),this.mtime=n?.mtime??i?.mtime??Ac(t,e+136,12),this.cksum=An(t,e+148,12),i&&this.#n(i,!0),n&&this.#n(n);let s=Wn(t,e+156,1);if(ro(s)&&(this.#e=s||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Wn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=n?.uname??i?.uname??Wn(t,e+265,32),this.gname=n?.gname??i?.gname??Wn(t,e+297,32),this.devmaj=n?.devmaj??i?.devmaj??An(t,e+329,8)??0,this.devmin=n?.devmin??i?.devmin??An(t,e+337,8)??0,t[e+475]!==0){let l=Wn(t,e+345,155);this.path=l+"/"+this.path}else{let l=Wn(t,e+345,130);l&&(this.path=l+"/"+this.path),this.atime=n?.atime??i?.atime??Ac(t,e+476,12),this.ctime=n?.ctime??i?.ctime??Ac(t,e+488,12)}let a=256;for(let l=e;l<e+148;l++)a+=t[l];for(let l=e+156;l<e+512;l++)a+=t[l];this.cksumValid=a===this.cksum,this.cksum===void 0&&a===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=rE(this.path||"",n),s=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Kn(t,e,100,s)||this.needPax,this.needPax=Tn(t,e+100,8,this.mode)||this.needPax,this.needPax=Tn(t,e+108,8,this.uid)||this.needPax,this.needPax=Tn(t,e+116,8,this.gid)||this.needPax,this.needPax=Tn(t,e+124,12,this.size)||this.needPax,this.needPax=Tc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Kn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Kn(t,e+265,32,this.uname)||this.needPax,this.needPax=Kn(t,e+297,32,this.gname)||this.needPax,this.needPax=Tn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Tn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Kn(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=Kn(t,e+345,155,a)||this.needPax:(this.needPax=Kn(t,e+345,130,a)||this.needPax,this.needPax=Tc(t,e+476,12,this.atime)||this.needPax,this.needPax=Tc(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,Tn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:_o.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(ul.get(t));if(ro(e)||e==="Unsupported")this.#e=e;else if(ro(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},rE=(t,e)=>{let n=t,i="",s,a=Ar.parse(t).root||".";if(Buffer.byteLength(n)<100)s=[n,i,!1];else{i=Ar.dirname(n),n=Ar.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=Ar.join(Ar.basename(i),n),i=Ar.dirname(i));while(i!==a&&s===void 0);s||(s=[t.slice(0,99),"",!0])}return s},Wn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),Ac=(t,e,n)=>iE(An(t,e,n)),iE=t=>t===void 0?void 0:new Date(t*1e3),An=(t,e,n)=>Number(t[e])&128?Xy(t.subarray(e,e+n)):oE(t,e,n),sE=t=>isNaN(t)?void 0:t,oE=(t,e,n)=>sE(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),aE={12:8589934591,8:2097151},Tn=(t,e,n,i)=>i===void 0?!1:i>aE[n]||i<0?(Zy(i,t.subarray(e,e+n)),!0):(cE(t,e,n,i),!1),cE=(t,e,n,i)=>t.write(lE(i,n),e,n,"ascii"),lE=(t,e)=>dE(Math.floor(t).toString(8),e),dE=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Tc=(t,e,n,i)=>i===void 0?!1:Tn(t,e,n,i.getTime()/1e3),uE=new Array(156).join("\0"),Kn=(t,e,n,i)=>i===void 0?!1:(t.write(i+uE,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),ho=class e0{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 a=0;a<512;a++)s[a]=0;new tr({path:("PaxHeader/"+fE(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 a=n+512;a<s.length;a++)s[a]=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
+ `,a=Buffer.byteLength(s),l=Math.floor(Math.log(a)/Math.log(10))+1;return a+l>=Math.pow(10,l)&&(l+=1),l+a+s}static parse(e,n,i=!1){return new e0(hE(xE(e),n),i)}},hE=(t,e)=>e?Object.assign({},e,t):t,xE=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(pE,Object.create(null)),pE=(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 a=s.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),l=i.join("=");return t[a]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(a)?new Date(Number(l)*1e3):/^[0-9]+$/.test(l)?+l:l,t},gE=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ne=gE!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),t0=class extends nr{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=ne(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?ne(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=ne(t.path)),t.linkpath&&(t.linkpath=ne(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},yo=(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))},mE=1024*1024,Hc=Buffer.from([31,139]),$c=Buffer.from([40,181,47,253]),wE=Math.max(Hc.length,$c.length),mt=Symbol("state"),Vn=Symbol("writeEntry"),Qt=Symbol("readEntry"),Rc=Symbol("nextEntry"),mf=Symbol("processEntry"),zt=Symbol("extendedHeader"),Ai=Symbol("globalExtendedHeader"),En=Symbol("meta"),wf=Symbol("emitMeta"),_e=Symbol("buffer"),en=Symbol("queue"),bn=Symbol("ended"),kc=Symbol("emittedEnd"),Zn=Symbol("emit"),Le=Symbol("unzip"),Ks=Symbol("consumeChunk"),Vs=Symbol("consumeChunkSub"),Cc=Symbol("consumeBody"),_f=Symbol("consumeMeta"),yf=Symbol("consumeHeader"),Ti=Symbol("consuming"),Pc=Symbol("bufferConcat"),Zs=Symbol("maybeEnd"),Tr=Symbol("writing"),vn=Symbol("aborted"),Js=Symbol("onDone"),Jn=Symbol("sawValidEntry"),Ys=Symbol("sawNullBlock"),Xs=Symbol("sawEOF"),Ef=Symbol("closeStream"),_E=()=>!0,Hi=class extends Fy{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[en]=[];[_e];[Qt];[Vn];[mt]="begin";[En]="";[zt];[Ai];[bn]=!1;[Le];[vn]=!1;[Jn];[Ys]=!1;[Xs]=!1;[Tr]=!1;[Ti]=!1;[kc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Js,()=>{(this[mt]==="begin"||this[Jn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Js,t.ondone):this.on(Js,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||mE,this.filter=typeof t.filter=="function"?t.filter:_E;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[Ef]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){yo(this,t,e,n)}[yf](t,e){this[Jn]===void 0&&(this[Jn]=!1);let n;try{n=new tr(t,e,this[zt],this[Ai])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Ys]?(this[Xs]=!0,this[mt]==="begin"&&(this[mt]="header"),this[Zn]("eof")):(this[Ys]=!0,this[Zn]("nullBlock"));else if(this[Ys]=!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[Vn]=new t0(n,this[zt],this[Ai]);if(!this[Jn])if(s.remain){let a=()=>{s.invalid||(this[Jn]=!0)};s.on("end",a)}else this[Jn]=!0;s.meta?s.size>this.maxMetaEntrySize?(s.ignore=!0,this[Zn]("ignoredEntry",s),this[mt]="ignore",s.resume()):s.size>0&&(this[En]="",s.on("data",a=>this[En]+=a),this[mt]="meta"):(this[zt]=void 0,s.ignore=s.ignore||!this.filter(s.path,s),s.ignore?(this[Zn]("ignoredEntry",s),this[mt]=s.remain?"ignore":"header",s.resume()):(s.remain?this[mt]="body":(this[mt]="header",s.end()),this[Qt]?this[en].push(s):(this[en].push(s),this[Rc]())))}}}[Ef](){queueMicrotask(()=>this.emit("close"))}[mf](t){let e=!0;if(!t)this[Qt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Qt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Rc]()),e=!1);return e}[Rc](){do;while(this[mf](this[en].shift()));if(this[en].length===0){let t=this[Qt];!t||t.flowing||t.size===t.remain?this[Tr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Cc](t,e){let n=this[Vn];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[mt]="header",this[Vn]=void 0,n.end()),s.length}[_f](t,e){let n=this[Vn],i=this[Cc](t,e);return!this[Vn]&&n&&this[wf](n),i}[Zn](t,e,n){this[en].length===0&&!this[Qt]?this.emit(t,e,n):this[en].push([t,e,n])}[wf](t){switch(this[Zn]("meta",this[En]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[zt]=ho.parse(this[En],this[zt],!1);break;case"GlobalExtendedHeader":this[Ai]=ho.parse(this[En],this[Ai],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[zt]??Object.create(null);this[zt]=e,e.path=this[En].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[zt]||Object.create(null);this[zt]=e,e.linkpath=this[En].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[vn]=!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[vn])return n?.(),!1;if((this[Le]===void 0||this.brotli===void 0&&this[Le]===!1)&&t){if(this[_e]&&(t=Buffer.concat([this[_e],t]),this[_e]=void 0),t.length<wE)return this[_e]=t,n?.(),!0;for(let l=0;this[Le]===void 0&&l<Hc.length;l++)t[l]!==Hc[l]&&(this[Le]=!1);let s=!1;if(this[Le]===!1&&this.zstd!==!1){s=!0;for(let l=0;l<$c.length;l++)if(t[l]!==$c[l]){s=!1;break}}let a=this.brotli===void 0&&!s;if(this[Le]===!1&&a)if(t.length<512)if(this[bn])this.brotli=!0;else return this[_e]=t,n?.(),!0;else try{new tr(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Le]===void 0||this[Le]===!1&&(this.brotli||s)){let l=this[bn];this[bn]=!1,this[Le]=this[Le]===void 0?new $y({}):s?new Vy({}):new Wy({}),this[Le].on("data",f=>this[Ks](f)),this[Le].on("error",f=>this.abort(f)),this[Le].on("end",()=>{this[bn]=!0,this[Ks]()}),this[Tr]=!0;let u=!!this[Le][l?"end":"write"](t);return this[Tr]=!1,n?.(),u}}this[Tr]=!0,this[Le]?this[Le].write(t):this[Ks](t),this[Tr]=!1;let i=this[en].length>0?!1:this[Qt]?this[Qt].flowing:!0;return!i&&this[en].length===0&&this[Qt]?.once("drain",()=>this.emit("drain")),n?.(),i}[Pc](t){t&&!this[vn]&&(this[_e]=this[_e]?Buffer.concat([this[_e],t]):t)}[Zs](){if(this[bn]&&!this[kc]&&!this[vn]&&!this[Ti]){this[kc]=!0;let t=this[Vn];if(t&&t.blockRemain){let e=this[_e]?this[_e].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[_e]&&t.write(this[_e]),t.end()}this[Zn](Js)}}[Ks](t){if(this[Ti]&&t)this[Pc](t);else if(!t&&!this[_e])this[Zs]();else if(t){if(this[Ti]=!0,this[_e]){this[Pc](t);let e=this[_e];this[_e]=void 0,this[Vs](e)}else this[Vs](t);for(;this[_e]&&this[_e]?.length>=512&&!this[vn]&&!this[Xs];){let e=this[_e];this[_e]=void 0,this[Vs](e)}this[Ti]=!1}(!this[_e]||this[bn])&&this[Zs]()}[Vs](t){let e=0,n=t.length;for(;e+512<=n&&!this[vn]&&!this[Xs];)switch(this[mt]){case"begin":case"header":this[yf](t,e),e+=512;break;case"ignore":case"body":e+=this[Cc](t,e);break;case"meta":e+=this[_f](t,e);break;default:throw new Error("invalid state: "+this[mt])}e<n&&(this[_e]=this[_e]?Buffer.concat([t.subarray(e),this[_e]]):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[vn]||(this[Le]?(t&&this[Le].write(t),this[Le].end()):(this[bn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Zs]())),this}},Mi=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)},yE=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},n0=(t,e)=>{let n=new Map(e.map(a=>[Mi(a),!0])),i=t.filter,s=(a,l="")=>{let u=l||Cy(a).root||".",f;if(a===u)f=!1;else{let x=n.get(a);f=x!==void 0?x:s(ky(a),u)}return n.set(a,f),f};t.filter=i?(a,l)=>i(a,l)&&s(Mi(a)):a=>s(Mi(a))},EE=t=>{let e=new Hi(t),n=t.file,i;try{i=Lr.openSync(n,"r");let s=Lr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(s.size<a){let l=Buffer.allocUnsafe(s.size),u=Lr.readSync(i,l,0,s.size,0);e.end(u===l.byteLength?l:l.subarray(0,u))}else{let l=0,u=Buffer.allocUnsafe(a);for(;l<s.size;){let f=Lr.readSync(i,u,0,a,l);if(f===0)break;l+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Lr.closeSync(i)}catch{}}},bE=(t,e)=>{let n=new Hi(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((a,l)=>{n.on("error",l),n.on("end",a),Lr.stat(s,(u,f)=>{if(u)l(u);else{let x=new cl(s,{readSize:i,size:f.size});x.on("error",l),x.pipe(n)}})})},Br=$i(EE,bE,t=>new Hi(t),t=>new Hi(t),(t,e)=>{e?.length&&n0(t,e),t.noResume||yE(t)}),r0=(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:SE,parse:vf}=vE,fl=t=>{let e="",n=vf(t);for(;SE(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=vf(t)}return[e,t]},Eo=["|","<",">","?",":"],hl=Eo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),IE=new Map(Eo.map((t,e)=>[t,hl[e]])),AE=new Map(hl.map((t,e)=>[t,Eo[e]])),Sf=t=>Eo.reduce((e,n)=>e.split(n).join(IE.get(n)),t),TE=t=>hl.reduce((e,n)=>e.split(n).join(AE.get(n)),t),i0=(t,e)=>e?(t=ne(t).replace(/^\.(\/|$)/,""),Mi(e)+"/"+t):ne(t),RE=16*1024*1024,If=Symbol("process"),Af=Symbol("file"),Tf=Symbol("directory"),jc=Symbol("symlink"),Rf=Symbol("hardlink"),Ri=Symbol("header"),io=Symbol("read"),Wc=Symbol("lstat"),so=Symbol("onlstat"),Kc=Symbol("onread"),Vc=Symbol("onreadlink"),Zc=Symbol("openfile"),Jc=Symbol("onopenfile"),Rn=Symbol("close"),po=Symbol("mode"),Yc=Symbol("awaitDrain"),Dc=Symbol("ondrain"),Gt=Symbol("prefix"),s0=class extends nr{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=ll(e);super(),this.path=ne(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||RE,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=ne(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?ne(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[a,l]=fl(this.path);a&&typeof l=="string"&&(this.path=l,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=TE(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ne(n.absolute||bf.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[so](s):this[Wc]()}warn(t,e,n={}){return yo(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Wc](){Ut.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[so](e)})}[so](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=PE(t),this.emit("stat",t),this[If]()}[If](){switch(this.type){case"File":return this[Af]();case"Directory":return this[Tf]();case"SymbolicLink":return this[jc]();default:return this.end()}}[po](t){return r0(t,this.type==="Directory",this.portable)}[Gt](t){return i0(t,this.prefix)}[Ri](){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 tr({path:this[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](this.linkpath):this.linkpath,mode:this[po](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 ho({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[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](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)}[Tf](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ri](),this.end()}[jc](){Ut.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Vc](e)})}[Vc](t){this.linkpath=ne(t),this[Ri](),this.end()}[Rf](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ne(bf.relative(this.cwd,t)),this.stat.size=0,this[Ri](),this.end()}[Af](){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[Rf](e);this.linkCache.set(t,this.absolute)}if(this[Ri](),this.stat.size===0)return this.end();this[Zc]()}[Zc](){Ut.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Jc](e)})}[Jc](t){if(this.fd=t,this.#e)return this[Rn]();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[io]()}[io](){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");Ut.read(t,e,n,i,s,(a,l)=>{if(a)return this[Rn](()=>this.emit("error",a));this[Kc](l)})}[Rn](t=()=>{}){this.fd!==void 0&&Ut.close(this.fd,t)}[Kc](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[Rn](()=>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[Rn](()=>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[Dc]():this[Yc](()=>this[Dc]())}[Yc](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)}[Dc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Rn](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[io]()}},kE=class extends s0{sync=!0;[Wc](){this[so](Ut.lstatSync(this.absolute))}[jc](){this[Vc](Ut.readlinkSync(this.absolute))}[Zc](){this[Jc](Ut.openSync(this.absolute,"r"))}[io](){let t=!0;try{let{fd:e,buf:n,offset:i,length:s,pos:a}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let l=Ut.readSync(e,n,i,s,a);this[Kc](l),t=!1}finally{if(t)try{this[Rn](()=>{})}catch{}}}[Yc](t){t()}[Rn](t=()=>{}){this.fd!==void 0&&Ut.closeSync(this.fd),t()}},CE=class extends nr{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 yo(this,t,e,n)}constructor(t,e={}){let n=ll(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=ne(t.path),this.mode=t.mode!==void 0?this[po](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?ne(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let s=!1;if(!this.preservePaths){let[l,u]=fl(this.path);l&&typeof u=="string"&&(this.path=u,s=l)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new tr({path:this[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](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 ho({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[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](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 a=this.header?.block;if(!a)throw new Error("failed to encode header");super.write(a),t.pipe(this)}[Gt](t){return i0(t,this.prefix)}[po](t){return r0(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}},PE=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",DE=class Or{tail;head;length=0;static create(e=[]){return new Or(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++)OE(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)NE(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 Or;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 Or;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 a=0;s;a++)i=e(i,s.value,a),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 a=this.length-1;s;a--)i=e(i,s.value,a),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 Or;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.head,a=0;for(a=0;s&&a<e;a++)s=s.next;for(;s&&a<n;a++,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 Or;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.length,a=this.tail;for(;a&&s>n;s--)a=a.prev;for(;a&&s>e;s--,a=a.prev)i.push(a.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 l=0;s&&l<e;l++)s=s.next;let a=[];for(let l=0;s&&l<n;l++)a.push(s.value),s=this.removeNode(s);s?s!==this.tail&&(s=s.prev):s=this.tail;for(let l of i)s=LE(this,s,l);return a}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 LE(t,e,n){let i=e,s=e?e.next:t.head,a=new xl(n,i,s,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function OE(t,e){t.tail=new xl(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function NE(t,e){t.head=new xl(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var xl=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}},Cf=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Pf=Buffer.alloc(1024),oo=Symbol("onStat"),ki=Symbol("ended"),Tt=Symbol("queue"),Ci=Symbol("queue"),Sn=Symbol("current"),Yn=Symbol("process"),Pi=Symbol("processing"),Qs=Symbol("processJob"),Rt=Symbol("jobs"),Lc=Symbol("jobDone"),ao=Symbol("addFSEntry"),Df=Symbol("addTarEntry"),Xc=Symbol("stat"),Qc=Symbol("readdir"),co=Symbol("onreaddir"),lo=Symbol("pipe"),Lf=Symbol("entry"),Oc=Symbol("entryOpt"),uo=Symbol("writeEntryClass"),o0=Symbol("write"),Nc=Symbol("ondrain"),bo=class extends nr{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[uo];onWriteEntry;[Tt];[Ci]=new Map;[Rt]=0;[Pi]=!1;[ki]=!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=ne(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[uo]=s0,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 Hy(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new jy(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Ky(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[Nc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Nc]);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[Tt]=new DE,this[Rt]=0,this.jobs=Number(t.jobs)||4,this[Pi]=!1,this[ki]=!1}[o0](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[ki]=!0,this[Yn](),n&&n(),this}write(t){if(this[ki])throw new Error("write after end");return t instanceof t0?this[Df](t):this[ao](t),this.flowing}[Df](t){let e=ne(kf.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new Cf(t.path,e);n.entry=new CE(t,this[Oc](n)),n.entry.on("end",()=>this[Lc](n)),this[Rt]+=1,this[Tt].push(n)}this[Yn]()}[ao](t){let e=ne(kf.resolve(this.cwd,t));this[Tt].push(new Cf(t,e)),this[Yn]()}[Xc](t){t.pending=!0,this[Rt]+=1;let e=this.follow?"stat":"lstat";xo[e](t.absolute,(n,i)=>{t.pending=!1,this[Rt]-=1,n?this.emit("error",n):this[oo](t,i)})}[oo](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[Sn])this[Qs](t);else{let n=`${e.dev}:${e.ino}`,i=this[Ci].get(n);i?i.push(t):this[Ci].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Yn]()}[Qc](t){t.pending=!0,this[Rt]+=1,xo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[Rt]-=1,e)return this.emit("error",e);this[co](t,n)})}[co](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Yn]()}[Yn](){if(!this[Pi]){this[Pi]=!0;for(let t=this[Tt].head;t&&this[Rt]<this.jobs;t=t.next)if(this[Qs](t.value),t.value.ignore){let e=t.next;this[Tt].removeNode(t),t.next=e}this[Pi]=!1,this[ki]&&this[Tt].length===0&&this[Rt]===0&&(this.zip?this.zip.end(Pf):(super.write(Pf),super.end()))}}get[Sn](){return this[Tt]&&this[Tt].head&&this[Tt].head.value}[Lc](t){this[Tt].shift(),this[Rt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Ci].get(n);if(i){this[Ci].delete(n);for(let s of i)s.pending=!1,this[Qs](s)}}this[Yn]()}[Qs](t){if(t.pending&&t.pendingLink&&t===this[Sn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Sn]&&!t.piped&&this[lo](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[oo](t,e):this[Xc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[co](t,e):this[Qc](t),!t.readdir)return}if(t.entry=this[Lf](t),!t.entry){t.ignore=!0;return}t===this[Sn]&&!t.piped&&this[lo](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}}[Lf](t){this[Rt]+=1;try{return new this[uo](t.path,this[Oc](t)).on("end",()=>this[Lc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Nc](){this[Sn]&&this[Sn].entry&&this[Sn].entry.resume()}[lo](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let s=t.path,a=s==="./"?"":s.replace(/\/*$/,"/");this[ao](a+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={}){yo(this,t,e,n)}},pl=class extends bo{sync=!0;constructor(t){super(t),this[uo]=kE}pause(){}resume(){}[Xc](t){let e=this.follow?"statSync":"lstatSync";this[oo](t,xo[e](t.absolute))}[Qc](t){this[co](t,xo.readdirSync(t.absolute))}[lo](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let s=t.path,a=s==="./"?"":s.replace(/\/*$/,"/");this[ao](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[o0](i)})}},ME=(t,e)=>{let n=new pl(t),i=new Kf(t.file,{mode:t.mode||438});n.pipe(i),a0(n,e)},BE=(t,e)=>{let n=new bo(t),i=new wo(t.file,{mode:t.mode||438});n.pipe(i);let s=new Promise((a,l)=>{i.on("error",l),i.on("close",a),n.on("error",l)});return c0(n,e).catch(a=>n.emit("error",a)),s},a0=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Br({file:Vf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},c0=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Br({file:Vf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},FE=(t,e)=>{let n=new pl(t);return a0(n,e),n},zE=(t,e)=>{let n=new bo(t);return c0(n,e).catch(i=>n.emit("error",i)),n},wP=$i(ME,BE,FE,zE,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),GE=process.env.__FAKE_PLATFORM__||process.platform,f0=GE==="win32",{O_CREAT:h0,O_NOFOLLOW:Of,O_TRUNC:x0,O_WRONLY:p0}=u0.constants,g0=Number(process.env.__FAKE_FS_O_FILENAME__)||u0.constants.UV_FS_O_FILEMAP||0,qE=f0&&!!g0,HE=512*1024,$E=g0|x0|h0|p0,Nf=!f0&&typeof Of=="number"?Of|x0|h0|p0:null,m0=Nf!==null?()=>Nf:qE?t=>t<HE?$E:"w":()=>"w",el=(t,e,n)=>{try{return vo.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},go=(t,e,n,i)=>{vo.lchown(t,e,n,s=>{i(s&&s?.code!=="ENOENT"?s:null)})},jE=(t,e,n,i,s)=>{if(e.isDirectory())w0(Bi.resolve(t,e.name),n,i,a=>{if(a)return s(a);let l=Bi.resolve(t,e.name);go(l,n,i,s)});else{let a=Bi.resolve(t,e.name);go(a,n,i,s)}},w0=(t,e,n,i)=>{vo.readdir(t,{withFileTypes:!0},(s,a)=>{if(s){if(s.code==="ENOENT")return i();if(s.code!=="ENOTDIR"&&s.code!=="ENOTSUP")return i(s)}if(s||!a.length)return go(t,e,n,i);let l=a.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--l===0)return go(t,e,n,i)}};for(let x of a)jE(t,x,e,n,f)})},WE=(t,e,n,i)=>{e.isDirectory()&&_0(Bi.resolve(t,e.name),n,i),el(Bi.resolve(t,e.name),n,i)},_0=(t,e,n)=>{let i;try{i=vo.readdirSync(t,{withFileTypes:!0})}catch(s){let a=s;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return el(t,e,n);throw a}for(let s of i)WE(t,s,e,n);return el(t,e,n)},y0=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"}},So=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"}},VE=(t,e)=>{ht.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new y0(t,n?.code||"ENOTDIR")),e(n)})},ZE=(t,e,n)=>{t=ne(t);let i=e.umask??18,s=e.mode|448,a=(s&i)!==0,l=e.uid,u=e.gid,f=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),x=e.preserve,m=e.unlink,g=ne(e.cwd),v=(b,I)=>{b?n(b):I&&f?w0(I,l,u,A=>v(A)):a?ht.chmod(t,s,n):n()};if(t===g)return VE(t,v);if(x)return KE.mkdir(t,{mode:s,recursive:!0}).then(b=>v(null,b??void 0),v);let w=ne(mo.relative(g,t)).split("/");tl(g,w,s,m,g,void 0,v)},tl=(t,e,n,i,s,a,l)=>{if(e.length===0)return l(null,a);let u=e.shift(),f=ne(mo.resolve(t+"/"+u));ht.mkdir(f,n,E0(f,e,n,i,s,a,l))},E0=(t,e,n,i,s,a,l)=>u=>{u?ht.lstat(t,(f,x)=>{if(f)f.path=f.path&&ne(f.path),l(f);else if(x.isDirectory())tl(t,e,n,i,s,a,l);else if(i)ht.unlink(t,m=>{if(m)return l(m);ht.mkdir(t,n,E0(t,e,n,i,s,a,l))});else{if(x.isSymbolicLink())return l(new So(t,t+"/"+e.join("/")));l(u)}}):(a=a||t,tl(t,e,n,i,s,a,l))},JE=t=>{let e=!1,n;try{e=ht.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new y0(t,n??"ENOTDIR")}},YE=(t,e)=>{t=ne(t);let n=e.umask??18,i=e.mode|448,s=(i&n)!==0,a=e.uid,l=e.gid,u=typeof a=="number"&&typeof l=="number"&&(a!==e.processUid||l!==e.processGid),f=e.preserve,x=e.unlink,m=ne(e.cwd),g=b=>{b&&u&&_0(b,a,l),s&&ht.chmodSync(t,i)};if(t===m)return JE(m),g();if(f)return g(ht.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=ne(mo.relative(m,t)).split("/"),w;for(let b=v.shift(),I=m;b&&(I+="/"+b);b=v.shift()){I=ne(mo.resolve(I));try{ht.mkdirSync(I,i),w=w||I}catch{let A=ht.lstatSync(I);if(A.isDirectory())continue;if(x){ht.unlinkSync(I),ht.mkdirSync(I,i),w=w||I;continue}else if(A.isSymbolicLink())return new So(I,I+"/"+v.join("/"))}}return g(w)},Mc=Object.create(null),Mf=1e4,Rr=new Set,XE=t=>{Rr.has(t)?Rr.delete(t):Mc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Rr.add(t);let e=Mc[t],n=Rr.size-Mf;if(n>Mf/10){for(let i of Rr)if(Rr.delete(i),delete Mc[i],--n<=0)break}return e},QE=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,eb=QE==="win32",tb=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=b0(i,n)),e.push(n||"/"),e},[]),nb=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=eb?["win32 parallelization disabled"]:t.map(i=>Mi(b0(XE(i))));let n=new Set(t.map(i=>tb(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 a=s.at(-1);a instanceof Set?a.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 a of n){let l=this.#e.get(a);if(!l||l?.[0]!==t)continue;let u=l[1];if(!u){this.#e.delete(a);continue}if(l.shift(),typeof u=="function")s.add(u);else for(let f of u)s.add(f)}for(let a of i){let l=this.#e.get(a),u=l?.[0];if(!(!l||!(u instanceof Set)))if(u.size===1&&l.length===1){this.#e.delete(a);continue}else if(u.size===1){l.shift();let f=l[0];typeof f=="function"&&s.add(f)}else u.delete(t)}return this.#r.delete(t),s.forEach(a=>this.#i(a)),!0}},rb=()=>process.umask(),Bf=Symbol("onEntry"),nl=Symbol("checkFs"),Ff=Symbol("checkFs2"),rl=Symbol("isReusable"),wt=Symbol("makeFs"),il=Symbol("file"),sl=Symbol("directory"),fo=Symbol("link"),zf=Symbol("symlink"),Uf=Symbol("hardlink"),Oi=Symbol("ensureNoSymlink"),Gf=Symbol("unsupported"),qf=Symbol("checkPath"),Bc=Symbol("stripAbsolutePath"),kn=Symbol("mkdir"),We=Symbol("onError"),eo=Symbol("pending"),Hf=Symbol("pend"),kr=Symbol("unpend"),Fc=Symbol("ended"),zc=Symbol("maybeClose"),ol=Symbol("skip"),Fi=Symbol("doChown"),zi=Symbol("uid"),Ui=Symbol("gid"),Gi=Symbol("checkedCwd"),ib=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,qi=ib==="win32",sb=1024,ob=(t,e)=>{if(!qi)return ce.unlink(t,e);let n=t+".DELETE."+d0(16).toString("hex");ce.rename(t,n,i=>{if(i)return e(i);ce.unlink(n,e)})},ab=t=>{if(!qi)return ce.unlinkSync(t);let e=t+".DELETE."+d0(16).toString("hex");ce.renameSync(t,e),ce.unlinkSync(e)},$f=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,gl=class extends Hi{[Fc]=!1;[Gi]=!1;[eo]=0;reservations=new nb;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[Fc]=!0,this[zc]()},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:sb,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||qi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ne(ze.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:rb():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[Bf](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[zc](){this[Fc]&&this[eo]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Bc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[s,a]=fl(n),l=a.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||qi&&/^[a-z]:\.\.$/i.test(l[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),f=ze.posix.normalize(ze.posix.join(u,l.join("/")));if(f.startsWith("../")||f==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return s&&(t[e]=String(a),this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute ${e}`,{entry:t,[e]:n})),!0}[qf](t){let e=ne(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=ne(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[Bc](t,"path")||!this[Bc](t,"linkpath"))return!1;if(t.absolute=ze.isAbsolute(t.path)?ne(ze.resolve(t.path)):ne(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:ne(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+Sf(String(t.absolute).slice(i.length));let{root:s}=ze.win32.parse(t.path);t.path=s+Sf(t.path.slice(s.length))}return!0}[Bf](t){if(!this[qf](t))return t.resume();switch(UE.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[nl](t);default:return this[Gf](t)}}[We](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[kr](),e.resume())}[kn](t,e,n){ZE(ne(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)}[Fi](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}[zi](t){return $f(this.uid,t.uid,this.processUid)}[Ui](t){return $f(this.gid,t.gid,this.processGid)}[il](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new wo(String(t.absolute),{flags:m0(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&ce.close(i.fd,()=>{}),i.write=()=>!0,this[We](u,t),e()});let s=1,a=u=>{if(u){i.fd&&ce.close(i.fd,()=>{}),this[We](u,t),e();return}--s===0&&i.fd!==void 0&&ce.close(i.fd,f=>{f?this[We](f,t):this[kr](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){s++;let x=t.atime||new Date,m=t.mtime;ce.futimes(f,x,m,g=>g?ce.utimes(u,x,m,v=>a(v&&g)):a())}if(typeof f=="number"&&this[Fi](t)){s++;let x=this[zi](t),m=this[Ui](t);typeof x=="number"&&typeof m=="number"&&ce.fchown(f,x,m,g=>g?ce.chown(u,x,m,v=>a(v&&g)):a())}a()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[We](u,t),e()}),t.pipe(l)),l.pipe(i)}[sl](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[kn](String(t.absolute),n,i=>{if(i){this[We](i,t),e();return}let s=1,a=()=>{--s===0&&(e(),this[kr](),t.resume())};t.mtime&&!this.noMtime&&(s++,ce.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Fi](t)&&(s++,ce.chown(String(t.absolute),Number(this[zi](t)),Number(this[Ui](t)),a)),a()})}[Gf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[zf](t,e){let n=ne(ze.relative(this.cwd,ze.resolve(ze.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Oi](t,this.cwd,n,()=>this[fo](t,String(t.linkpath),"symlink",e),i=>{this[We](i,t),e()})}[Uf](t,e){let n=ne(ze.resolve(this.cwd,String(t.linkpath))),i=ne(String(t.linkpath)).split("/");this[Oi](t,this.cwd,i,()=>this[fo](t,n,"link",e),s=>{this[We](s,t),e()})}[Oi](t,e,n,i,s){let a=n.shift();if(this.preservePaths||a===void 0)return i();let l=ze.resolve(e,a);ce.lstat(l,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return s(new So(l,ze.resolve(l,n.join("/"))));this[Oi](t,l,n,i,s)})}[Hf](){this[eo]++}[kr](){this[eo]--,this[zc]()}[ol](t){this[kr](),t.resume()}[rl](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!qi}[nl](t){this[Hf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[Ff](t,n))}[Ff](t,e){let n=l=>{e(l)},i=()=>{this[kn](this.cwd,this.dmode,l=>{if(l){this[We](l,t),n();return}this[Gi]=!0,s()})},s=()=>{if(t.absolute!==this.cwd){let l=ne(ze.dirname(String(t.absolute)));if(l!==this.cwd)return this[kn](l,this.dmode,u=>{if(u){this[We](u,t),n();return}a()})}a()},a=()=>{ce.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[ol](t),n();return}if(l||this[rl](t,u))return this[wt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=m=>this[wt](m??null,t,n);return f?ce.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ce.rmdir(String(t.absolute),f=>this[wt](f??null,t,n))}if(t.absolute===this.cwd)return this[wt](null,t,n);ob(String(t.absolute),f=>this[wt](f??null,t,n))})};this[Gi]?s():i()}[wt](t,e,n){if(t){this[We](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[il](e,n);case"Link":return this[Uf](e,n);case"SymbolicLink":return this[zf](e,n);case"Directory":case"GNUDumpDir":return this[sl](e,n)}}[fo](t,e,n,i){ce[n](e,String(t.absolute),s=>{s?this[We](s,t):(this[kr](),t.resume()),i()})}},Di=t=>{try{return[null,t()]}catch(e){return[e,null]}},v0=class extends gl{sync=!0;[wt](t,e){return super[wt](t,e,()=>{})}[nl](t){if(!this[Gi]){let s=this[kn](this.cwd,this.dmode);if(s)return this[We](s,t);this[Gi]=!0}if(t.absolute!==this.cwd){let s=ne(ze.dirname(String(t.absolute)));if(s!==this.cwd){let a=this[kn](s,this.dmode);if(a)return this[We](a,t)}}let[e,n]=Di(()=>ce.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[ol](t);if(e||this[rl](t,n))return this[wt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[l]=a?Di(()=>{ce.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[wt](l,t)}let[s]=Di(()=>ce.rmdirSync(String(t.absolute)));this[wt](s,t)}let[i]=t.absolute===this.cwd?[]:Di(()=>ab(String(t.absolute)));this[wt](i,t)}[il](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{ce.closeSync(s)}catch(f){u=f}(l||u)&&this[We](l||u,t),e()},s;try{s=ce.openSync(String(t.absolute),m0(t.size),n)}catch(l){return i(l)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",l=>this[We](l,t)),t.pipe(a)),a.on("data",l=>{try{ce.writeSync(s,l,0,l.length)}catch(u){i(u)}}),a.on("end",()=>{let l=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{ce.futimesSync(s,u,f)}catch(x){try{ce.utimesSync(String(t.absolute),u,f)}catch{l=x}}}if(this[Fi](t)){let u=this[zi](t),f=this[Ui](t);try{ce.fchownSync(s,Number(u),Number(f))}catch(x){try{ce.chownSync(String(t.absolute),Number(u),Number(f))}catch{l=l||x}}}i(l)})}[sl](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[kn](String(t.absolute),n);if(i){this[We](i,t),e();return}if(t.mtime&&!this.noMtime)try{ce.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Fi](t))try{ce.chownSync(String(t.absolute),Number(this[zi](t)),Number(this[Ui](t)))}catch{}e(),t.resume()}[kn](t,e){try{return YE(ne(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}}[Oi](t,e,n,i,s){if(this.preservePaths||n.length===0)return i();let a=e;for(let l of n){a=ze.resolve(a,l);let[u,f]=Di(()=>ce.lstatSync(a));if(u)return i();if(f.isSymbolicLink())return s(new So(a,ze.resolve(e,n.join("/"))))}i()}[fo](t,e,n,i){let s=`${n}Sync`;try{ce[s](e,String(t.absolute)),i(),t.resume()}catch(a){return this[We](a,t)}}},cb=t=>{let e=new v0(t),n=t.file,i=l0.statSync(n),s=t.maxReadSize||16*1024*1024;new Ry(n,{readSize:s,size:i.size}).pipe(e)},lb=(t,e)=>{let n=new gl(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((a,l)=>{n.on("error",l),n.on("close",a),l0.stat(s,(u,f)=>{if(u)l(u);else{let x=new cl(s,{readSize:i,size:f.size});x.on("error",l),x.pipe(n)}})})},S0=$i(cb,lb,t=>new v0(t),t=>new gl(t),(t,e)=>{e?.length&&n0(t,e)}),db=(t,e)=>{let n=new pl(t),i=!0,s,a;try{try{s=ft.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")s=ft.openSync(t.file,"w+");else throw f}let l=ft.fstatSync(s),u=Buffer.alloc(512);e:for(a=0;a<l.size;a+=512){for(let m=0,g=0;m<512;m+=g){if(g=ft.readSync(s,u,m,u.length-m,a+m),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!g)break e}let f=new tr(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(a+x+512>l.size)break;a+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,ub(t,n,a,s,e)}finally{if(i)try{ft.closeSync(s)}catch{}}},ub=(t,e,n,i,s)=>{let a=new Kf(t.file,{fd:i,start:n});e.pipe(a),hb(e,s)},fb=(t,e)=>{e=Array.from(e);let n=new bo(t),i=(s,a,l)=>{let u=(v,w)=>{v?ft.close(s,b=>l(v)):l(null,w)},f=0;if(a===0)return u(null,0);let x=0,m=Buffer.alloc(512),g=(v,w)=>{if(v||w===void 0)return u(v);if(x+=w,x<512&&w)return ft.read(s,m,x,m.length-x,f+x,g);if(f===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let b=new tr(m);if(!b.cksumValid)return u(null,f);let I=512*Math.ceil((b.size??0)/512);if(f+I+512>a||(f+=I+512,f>=a))return u(null,f);t.mtimeCache&&b.mtime&&t.mtimeCache.set(String(b.path),b.mtime),x=0,ft.read(s,m,0,512,f,g)};ft.read(s,m,0,512,f,g)};return new Promise((s,a)=>{n.on("error",a);let l="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&l==="r+")return l="w+",ft.open(t.file,l,u);if(f||!x)return a(f);ft.fstat(x,(m,g)=>{if(m)return ft.close(x,()=>a(m));i(x,g.size,(v,w)=>{if(v)return a(v);let b=new wo(t.file,{fd:x,start:w});n.pipe(b),b.on("error",a),b.on("close",s),xb(n,e)})})};ft.open(t.file,l,u)})},hb=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Br({file:I0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},xb=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Br({file:I0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Li=$i(db,fb,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!My(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")}),LP=$i(Li.syncFile,Li.asyncFile,Li.syncNoFile,Li.asyncNoFile,(t,e=[])=>{Li.validate?.(t,e),pb(t)}),pb=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))};wn();var _t={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function Io(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function A0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function Ao(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function T0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function R0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function rr(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}rn();Ze();oe();Be();Ze();function Fr(t,e){if(Io(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function ji(t){return t.startsWith("http://")||t.startsWith("https://")}function zr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as SD}from"node:fs";import{dirname as AD,join as TD}from"node:path";import{fileURLToPath as kD}from"node:url";var Ht="0.2.1-beta.2";Ze();oe();var To="1008033",D0="1289";var L0="pbbp2",O0="https://www.coze.cn",N0="/api/coze_claw/resource/get_frontier_key",vb="https://www.coze.cn",Sb="wss://frontier.coze.cn";function Ur(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??vb}function M0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Sb}function Dn(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 Ki(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Wi=$("handshake");async function ml(t){let e=Ur(t.endpoint),n=t.timeoutMs??1e4,i=`${zr(e)}${N0}?aid=${encodeURIComponent(To)}`,s={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Dn(t.ppeOverride)},a=new AbortController,l=setTimeout(()=>a.abort(),n);Wi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:s,signal:a.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 T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${b.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=${f}`);let g=m.data??{},v=typeof g.access_key=="string"&&g.access_key||typeof g.accessKey=="string"&&g.accessKey||void 0,w=typeof g.device_id=="string"&&g.device_id||typeof g.deviceId=="string"&&g.deviceId||void 0;if(!v||!w){let b=JSON.stringify(m).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${b}`)}return Wi.info("handshake ok",{remoteDeviceId:w,logid:f,traceId:x}),{accessKey:v,deviceId:w}}catch(u){if(u instanceof T)throw Wi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Wi.warn("handshake timeout",{base:e,timeoutMs:n}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let f=u.cause;throw Wi.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 T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}var wl=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Pt="auto",B0=15e4;function F0(t){return{model:_l(t.model)??Pt,...t.modelToken?{modelToken:t.modelToken}:{}}}function z0(t){return!t||t===Pt}var Ib=new Set(["auto","\u81EA\u52A8"]);function _l(t){let e=t?.trim();if(e)return Ib.has(e.toLowerCase())?Pt:e}function U0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=wl,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Pt;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 z0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function G0(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Pt}"`):z0(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="${wl}/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??B0;e.push("-c",`model_context_window=${n}`)}return e}function q0(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function yl(t,e){let{ttEnv:n,usePpe:i}=Ki(t),s={};return n&&(s["x-tt-env"]=n),i&&(s["x-use-ppe"]=i),e&&(s["x-mock-scenario"]=e),s}function H0(t,e,n){if(!t.modelToken)return{};let i=yl(e,n);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([a,l])=>`${a}:${l}`).join(`
92
+ `)}}function El(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function $0(t,e,n){if(!t.modelToken)return null;let i=t.model||Pt,s=yl(e,n),a=["text"];t.modelInfo?.capabilities?.image===!0&&a.push("image");let l={baseUrl:`${wl}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:i,name:i,reasoning:!1,input:a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??B0,maxTokens:8192,api:"openai-completions"}]};return Object.keys(s).length>0&&(l.headers=s),l}function j0(t,e,n){if(!t.modelToken)return[];let i=yl(e,n),s=[];for(let[a,l]of Object.entries(i))s.push("-c",`model_providers.coze.http_headers.${a}="${l}"`);return s}var ge=$("agent-handlers"),W0=5*1024*1024,Cb=1,Pb=6,Db=new Set(["node_modules",".git",".coze","dist","build",".next"]),Lb=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ob=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Nb=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Mb(t){let e=t?.trim();return e?Nb.test(e)||Ob.test(e)?e:(ge.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Bb(t){return new Promise((e,n)=>{let i=lt("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),s=!1,a=l=>{s||(s=!0,l?n(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),a()}),i.once("error",l=>a(l))})}var ko=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let n=rr(e._meta),i=await this.loadAgentCfg(n),s=i?.workspace??et(n).workspace,a=i?.skills??[],l=[],u=new Set;for(let f of a){let x=Ee(s,f.relPath,"SKILL.md");await Z0(x).then(g=>g.isFile()).catch(()=>!1)&&(l.push(Hb(f)),u.add(f.relPath))}if(e.scanLocal){let f=i?.framework??"claude-code",x=await zb(n,s,f),m=await Ub(n,f);for(let g of[...x,...m])u.has(g.relPath)||(u.add(g.relPath),l.push(g.skill))}return{skills:l}}async addSkills(e){e._meta;let n=rr(e._meta),i=await this.requireAgentCfg(n),s=e.skills??[],a=[...i.skills??[]],l=new Map(a.map((f,x)=>[f.skillId,x])),u=[];for(let f of s){let x=await Co({agentId:n,workspace:i.workspace,framework:i.framework,skill:f});Po(a,l,x),u.push(f)}return await wi(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=rr(e._meta),i=await this.requireAgentCfg(n),s=new Set(e.skillIds??[]),a=i.skills??[],l=[];for(let u of a){if(!s.has(u.skillId)){l.push(u);continue}let f=Ee(i.workspace,u.relPath);await Sl(f,{recursive:!0,force:!0}),ge.info("skill removed",{agentId:n,skillId:u.skillId,relPath:u.relPath})}return await wi(n,l),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=rr(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??et(n).workspace,a=i?.framework??"claude-code",l=e.isGlobal??!1,u=Q0(e.skillName),f=await Fb(s,a,u,l);if(!f){let P=l?"global":"workspace";throw new T("SKILL_NOT_FOUND",`skill not found in ${P}: ${e.skillName} (${u})`)}let{absDir:x,relPath:m}=f,g=Ee(x,"SKILL.md"),v=new kl.default;v.addLocalFolder(x,u);let w=v.toBuffer();if(w.length>K0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${w.length} bytes exceeds limit ${K0}`);let b=await Ro(g,{encoding:"utf8"}).then(P=>nh(P).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:w,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...b?{description:b}:{},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 A=I.version??"v1.0",R=I.skillId??e.skillId??th(n,m);if(i&&!l){let P=i.skills??[],E=P.find(k=>k.relPath===m);E?(E.version=A,E.skillId=R):P.push({skillId:R,skillName:e.skillName,relPath:m,version:A,installedAt:Date.now(),...b?{description:b}:{}}),await wi(n,P)}return ge.info("skill published",{agentId:n,skillName:e.skillName,relPath:m,zipBytes:w.length,skillId:R,version:A}),{ok:!0,skillId:R,version:A}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[s,a]of i.sessions){if(!a.downstream)continue;let l=a.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(a)){a.reloadAfterTurn=!0,ge.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:l});continue}let f=a.downstream;a.downstream=void 0,ge.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:l}),f.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 De(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 Er(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 qe(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 De(n))throw new T("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=["-y"];e.registry&&ji(e.registry)&&s.push(`--registry=${e.registry}`);let a=Mb(e.targetVersion);s.push("--ignore-existing",`coze-bridge@${a}`,"connect");let l=e._meta?.cozeEnv;l&&Lb.test(l)&&s.push("--env",l);let u=await Bb(s);return ge.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:u,targetVersion:a,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 De(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await qe(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",`${_t.DELETE}: missing agentId`);let i=await De(n),s=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,a=e.deployType??s??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let l=et(n);return a==="cloud"?await Sl(l.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await qe(i)),ge.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(Fr(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=_l(e.model)??Pt,i=await De(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 qe(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};s.model=n,e.modelInfo&&s.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(s).catch(l=>ge.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(l)}));let a=[];for(let[l,u]of s.allSessionQueues())a.push(u.enqueue(async()=>{let f=s.sessions.get(l);f?.downstream&&(await f.downstream.stop(`switchModel: ${n}`).catch(()=>{}),f.downstream=void 0)}));return await Promise.all(a),ge.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:a.length}),{ok:!0}}async resetAgent(e){if(Fr(e._meta,_t.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${_t.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,_t.RESET),await this.runDetailSync(e.agentId,_t.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 a of i.sessions.values())a.acpSessionId=void 0,a.replySeq=0,a.loadingSession=!1,a.spawnFailCount=void 0,a.spawnFailedAt=void 0;let s=new Map;for(let[a,l]of i.sessions)s.set(a,{modelToken:l.modelToken,tokenGeneratedAt:l.tokenGeneratedAt});await mi(e,s)}async clearPersistedAcpSessionIds(e){let n=await De(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 qe(n)}async repairAgent(e){if(Fr(e._meta,_t.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${_t.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${_t.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,_t.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){Fr(e._meta,"_agent/getFileTree");let n=e._meta,i=rr(n),s=await this.resolveWorkspace(i),a=e.filePath??"",l=this.safeJoin(s,a),u=await bl(l).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${a}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${a}`);if(!await gi(l,s))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let f=tv(e.depth);return u.isDirectory()?{tree:await ev(s,l,a,f)}:{tree:[{name:nv(a),path:oh(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Fr(e._meta,"_agent/getFileContent");let n=rr(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),a=await bl(s).catch(()=>null);if(!a||!a.isFile())throw new T("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(a.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await gi(s,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>W0)throw new T("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${W0})`);let l=await Ro(s);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:a.size}:{content:l.toString("utf8"),encoding:"utf-8",size:a.size}}async resolveWorkspace(e){let n=this.opts.agents.get(e);return n?n.workspace:(await De(e).catch(()=>null))?.workspace??et(e).workspace}safeJoin(e,n){let i=Al(e,n||"."),s=Rl(e,i);if(s.startsWith("..")||s===".."||s.startsWith(`..${J0}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return De(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 Q0(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 Cl(t){return t==="claude-code"?Ee(".claude","skills"):Ee(".agents","skills")}function eh(t){let e=Tb();return t==="claude-code"?[Ee(e,".claude","skills")]:t==="codex"?[Ee(e,".agents","skills"),Ee(e,".codex","skills")]:[Ee(e,".agents","skills"),Ee(e,".openclaw","skills")]}async function Fb(t,e,n,i){let s=async a=>Z0(Ee(a,"SKILL.md")).then(l=>l.isFile()).catch(()=>!1);if(!i){let a=Ee(Cl(e),n),l=Ee(t,a);return await s(l)?{absDir:l,relPath:a}:null}for(let a of eh(e)){let l=Ee(a,n);if(await s(l))return{absDir:l,relPath:l}}return null}function th(t,e){return(Ab("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function nh(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 a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(s);if(!a||!a[2])continue;let l=a[1],u=a[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[l]=u)}return i}async function rh(t,e,n,i){let s=await V0(e,{withFileTypes:!0}).catch(()=>null);if(!s)return[];let a=[];for(let l of s){if(!l.isDirectory())continue;let u=l.name,f=Ee(n,u),x=Ee(e,u,"SKILL.md"),m=await Ro(x,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let g=nh(m);a.push({relPath:f,skill:{skillId:th(t,f),skillName:g.name||u,...g.description?{description:g.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function zb(t,e,n){let i=Cl(n);return rh(t,Ee(e,i),i,!1)}async function Ub(t,e){let n=[],i=new Set;for(let s of eh(e)){let a=await rh(t,s,s,!0);for(let l of a)i.has(l.relPath)||(i.add(l.relPath),n.push(l))}return n}var Gb=3e4,qb=50*1024*1024,K0=10*1024*1024,Gr=3e4;async function Co(t){let{agentId:e,workspace:n,framework:i,skill:s}=t;if(!s.skillName)throw new T("IPC_BAD_REQUEST","skill missing skillName");let a=typeof s.content=="string"&&s.content.length>0,l=typeof s.downloadUrl=="string"&&s.downloadUrl.length>0;if(!a&&!l)throw new T("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let u=Q0(s.skillName),f=Cl(i),x=Ee(f,u),m=Ee(n,x);if(await vl(m,{recursive:!0}),a){let v=Buffer.from(s.content,"utf8");Vi(v.length),await Il(Ee(m,"SKILL.md"),v,"utf8")}else{let v=await jb(s.downloadUrl);Kb(v)?await Yb(v,m):Vb(v)?await Zb(v,m):await Il(Ee(m,"SKILL.md"),v.toString("utf8"),"utf8")}let g={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:a?"content":"downloadUrl"}),g}function Po(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 Hb(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 $b(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 ih(t,e){let n=await De(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Ht,s=n.skillsRefreshedForVersion;if(s===i)return{status:"noop",count:0};if(!s)return n.skillsRefreshedForVersion=i,await qe(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],l=new Map(a.map((m,g)=>[m.skillId,g])),u=a.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await qe(n,e),{status:"noop",count:0};let f=0,x=0;for(let m of u)try{await Sl(Ee(n.workspace,m.relPath),{recursive:!0,force:!0});let g=await Co({agentId:t,workspace:n.workspace,framework:n.framework,skill:$b(m)});Po(a,l,g),f+=1}catch(g){x+=1,ge.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(g)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await qe(n,e),ge.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:s,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function jb(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Vi(e);let n=Wb(t);return Vi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Ro(e);return Vi(n.length),n}if(ji(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),Gb);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 Vi(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 Vi(t){if(t>qb)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Wb(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 Kb(t){return t.length>=2&&t[0]===31&&t[1]===139}function Vb(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 Tl(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Zb(t,e){let n,i;try{n=new kl.default(t),i=n.getEntries()}catch(l){throw new T("IPC_BAD_REQUEST",`zip parse failed: ${l.message}`,{cause:l})}for(let l of i){let u=l.entryName;if(!u||Tl(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 f=l.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let s=Jb(i),a=Al(e);for(let l of i){if(Tl(l.entryName))continue;let u=l.entryName;if(s&&u.startsWith(s)&&(u=u.slice(s.length)),!u)continue;let f=Al(e,u),x=Rl(a,f);if(x.startsWith("..")||x==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await vl(f,{recursive:!0});continue}await vl(Rb(f),{recursive:!0});let m;try{m=l.getData()}catch(g){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${g.message}`,{cause:g})}await Il(f,m)}}function Jb(t){let e;for(let n of t){let i=n.entryName;if(!i||Tl(i))continue;let s=i.indexOf("/");if(s<=0)return;let a=i.slice(0,s+1);if(e===void 0)e=a;else if(e!==a)return}return e}async function Yb(t,e){await Xb(t);let n=S0({cwd:e,strip:1}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Gr}ms)`))},Gr);try{await X0(Y0.from(t),n)}catch(a){throw a instanceof T?a:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Gr}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(s)}}async function Xb(t){let e=[],n=Br({onReadEntry:a=>{let l=a.path,u=a.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,s=setTimeout(()=>{i=!0,n.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Gr}ms)`))},Gr);try{await X0(Y0.from(t),n)}catch(a){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Gr}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(s)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Qb=5e3;async function ev(t,e,n,i){return sh(t,e,n,i,{count:0})}async function sh(t,e,n,i,s){if(i<=0)return[];let a;try{a=await V0(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of a){if(Db.has(u.name)||u.isSymbolicLink())continue;if(s.count>=Qb){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=Ee(e,u.name),x=kb(Ee(n,u.name)),m=null;try{m=await bl(f)}catch{continue}if(m.isSymbolicLink())continue;s.count++;let g={name:u.name,path:oh(Rl(t,f)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(g.children=await sh(t,f,x,i-1,s)),l.push(g)}return l.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),l}function tv(t){return!t||t<=0?Cb:Math.min(t,Pb)}function nv(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function oh(t){return t.split(J0).join("/")}oe();var Ln=$("agent-health-reporter"),rv=1e4,iv=3,Zi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??rv,this.livenessFailureThreshold=e.livenessFailureThreshold??iv}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()}),Ln.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Ln.info("heartbeat stopped"))}async tick(){if(this.inFlight){Ln.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Ln.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let l of this.opts.core.agents.values()){let u=sv(l);if(!u)continue;let f={agentId:l.agentId,status:u};l.patToken&&(f.patToken=l.patToken),l.accountId&&(f.accountId=l.accountId),n.push(f)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Ht,_meta:{cozeDeviceId:e}},s;try{s=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(l){this.consecutiveFailures+=1,Ln.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let a=s?.authFailures;if(a&&a.length>0&&(Ln.warn("heartbeat received authFailures from cloud",{count:a.length,agentIds:a.map(l=>l.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(a)}catch(l){Ln.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Ln.warn("onTickEnd hook failed",{err:String(n)})}}};function sv(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}wn();import{mkdir as Ml,rm as Jv,stat as Yv}from"node:fs/promises";import{homedir as Xv}from"node:os";import{join as Oh}from"node:path";pn();import{existsSync as wv}from"node:fs";import{release as _v}from"node:os";import{basename as yv,isAbsolute as Ev}from"node:path";function Ji(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function qr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Hr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function On(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ze();var Do=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},ee={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function ah(t){return"method"in t&&"id"in t&&t.id!==void 0}function ch(t){return"method"in t&&!("id"in t)}function Lo(t){return!("method"in t)&&"id"in t}var ov={AGENT_NOT_FOUND:ee.AGENT_NOT_FOUND,AGENT_BUSY:ee.AGENT_BUSY,AGENT_DISCONNECTED:ee.AGENT_DISCONNECTED,AGENT_TIMEOUT:ee.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:ee.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:ee.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:ee.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:ee.INTERNAL_ERROR,BRIDGE_INTERNAL:ee.INTERNAL_ERROR,IPC_AUTH_FAILED:ee.INTERNAL_ERROR,IPC_BAD_REQUEST:ee.INVALID_REQUEST,METHOD_NOT_FOUND:ee.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:ee.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:ee.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:ee.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:ee.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:ee.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:ee.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:ee.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:ee.FILE_TOO_LARGE,UNSUPPORTED_MIME:ee.UNSUPPORTED_MIME,UPLOAD_FAILED:ee.UPLOAD_FAILED,UPSTREAM_NOT_READY:ee.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:ee.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:ee.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:ee.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:ee.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:ee.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:ee.SKILL_ZIP_TOO_LARGE};function av(t){if(t!=null)return t instanceof Error?{name:t.name,message:Yi(t.message)}:typeof t=="string"?Yi(t):typeof t=="object"?lv(t):t}var cv=[[/\/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 Yi(t){let e=t;for(let[n,i]of cv)e=e.replace(n,i);return e}function lv(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Yi(i):e[n]=i;return e}function Xi(t){if(t instanceof T){let e=av(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:ov[t.code]??ee.INTERNAL_ERROR,message:Yi(t.message),data:n}}return{code:ee.INTERNAL_ERROR,message:Yi(t instanceof Error?t.message:String(t))}}function lh(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,a=t.data;if(i&&e){let{message:l,...u}=e;a=u}return new T(n,s,{retriable:e?.retriable??!1,cause:a})}function uh(t){return`${JSON.stringify(t)}
95
+ `}var dh=10*1024*1024,Oo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>dh){let s=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${s} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${dh} bytes`)}),[]}let n=this.buffer.split(`
96
+ `);this.buffer=n.pop()??"";let i=[];for(let s of n){let a=s.replace(/\r$/,"").trim();if(a)try{i.push(JSON.parse(a))}catch(l){this.onError?.({line:a,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(n){return this.onError?.({line:e,error:n}),[]}}};var hh={"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"},xL=Object.fromEntries(Object.entries(hh).map(([t,e])=>[e,t])),dv={"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:[]},$r=class{seq=0;next(e,n){this.seq+=1;let i=hh[e]??uv(e),s=dv[i]??[],a=[i,String(this.seq)];if(s.length>0){let l=s.map(f=>fh(n?.[f]??"")),u=fv(l).join(":");u&&a.push(u)}else n&&Object.values(n).some(l=>l)&&a.push(Object.values(n).filter(Boolean).map(l=>fh(String(l))).join(":"));return a.join("_")}reset(){this.seq=0}};function uv(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function fh(t){return t.replace(/[:_\s]+/g,"-")}function fv(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}mn();import{readFileSync as hv}from"node:fs";var xv=384;async function Pl(t,e=process.env){let n={};for(let[i,s]of Object.entries(e))typeof s=="string"&&(n[i]=s);await yr(t.agentEnvFile,n,{mode:xv})}function Dl(t){try{let e=JSON.parse(hv(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function xh(t,e,n={},i=s=>s){return{...i({...t,...Dl(e)}),...n}}rn();pr();Ze();oe();Be();import{execFileSync as pv,spawnSync as gv}from"node:child_process";function Qi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function es(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),gv("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var Ll=new Set;function ph(t){typeof t=="number"&&t>0&&Ll.add(t)}function gh(t){typeof t=="number"&&Ll.delete(t)}function mh(){for(let t of Ll)es(t,"SIGKILL")}var jr="coze-bridge-daemon";function wh(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let s=process.getuid?.()??0;return pv("pgrep",["-U",String(s),"-f",jr],{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 _h(t,e){if(t.length===0)return;let n=e?.killFn??es,i=e?.isAliveFn??Qi,s=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),a=e?.graceMs??3e3,l=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<a&&t.some(f=>i(f));u+=l)await s(Math.min(l,a-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var mv=[{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\/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|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 yh(t,e){if(!e)return null;for(let n of mv)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function Eh(t,e){return yh(t,e)}function bh(t,e){return yh(t,e)}function Wr(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 vh(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:Wr(m,t.firstFrameSeen,e)}}let a=n-t.startedAt-t.suspendedMs,l=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return a>=l?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?a<e.phase2GateMs?{action:"continue",rearmMs:Wr(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Wr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Wr(a,!1,e)}}var Sh=Qe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),bv=200,vv=40,Sv=Qe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Iv=Qe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Av=Qe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Tv=Qe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Rv=Qe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),kv=Qe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Ih=500;function Cv(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Ih?t:`${e.slice(0,Ih)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Pv(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 Ah(t){try{return wv(t)}catch{return}}function Dv(t,e){return{platform:process.platform,osRelease:_v(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Ev(e.command)?Ah(e.command):void 0,cwd:e.cwd,cwdExists:Ah(e.cwd),envKeys:e.envKeys}}function Lv(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${yv(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var $t=class{constructor(e){this.opts=e;this.log=$(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Oo({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new $r;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=xh(process.env,this.opts.agentEnvFile??ie().agentEnvFile,this.opts.env,s=>this.sanitizeEnv(s)),i=lt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,ph(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",s=>{try{for(let a of this.decoder.push(s))this.dispatch(a)}catch(a){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(a)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",s=>{let a=s.trimEnd();this.stderrRing.push(a),this.stderrRing.length>bv&&this.stderrRing.shift(),this.log.debug("stderr",{text:a})}),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,a)=>{this.stopped=!0,gh(i.pid),(s!==0||a!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:s,signal:a,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,a));for(let u of this.exitHandlers)u(s,a)}),i.on("error",s=>{let a=s,l=Dv(a,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(s),diag:l}),this.failAllPending(new T("AGENT_SPAWN_FAILED",Lv(a,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 n=this.child,i=new Promise(a=>n.once("exit",()=>a()));es(n.pid,"SIGTERM");let s=setTimeout(()=>{n.killed||es(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:Rv,phase2GateMs:Sv,livenessWindowMs:Iv,absoluteMaxMs:Av,approvalMaxMs:kv,suspendThresholdMs:Tv,...n};return this.call("session/prompt",e,Sh,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(qr("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(Hr(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(On(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=Sh,s){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),l=Ji(a,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let f=n.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,x)=>{let m={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(s){let g=this.now(),v={cfg:s,startedAt:g,lastActivityAt:g,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:g,expectedIntervalMs:Wr(0,!1,s),sessionId:u};m.promptTimeout=v;let w=()=>{let b={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},I=this.now(),A=vh(b,v.cfg,I),R=P=>{v.armedAt=I,v.expectedIntervalMs=P,m.timer=setTimeout(w,P)};if(A.action==="suspend"){v.suspendedMs+=A.suspendedDeltaMs,v.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),R(A.rearmMs);return}if(A.action==="continue"){R(A.rearmMs);return}this.pending.delete(a),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:A.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),x(A.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(w,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),x(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,m);try{this.writeFrame(l)}catch(g){m.timer&&clearTimeout(m.timer),this.pending.delete(a),x(g)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(uh(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(Lo(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:Cv(e.result)}),n.resolve(e.result));return}if(ch(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(ah(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 a=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!a)return;let l=typeof i.status=="string"?i.status:void 0,u=l==="completed"||l==="failed"||l==="cancelled";s==="tool_call"&&!u?e.activeToolCalls.add(a):u&&e.activeToolCalls.delete(a)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(On(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(On(e.id,Xi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=lh(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=bh(this.framework,Pv(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(vv).join(`
98
+ `),s=Eh(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 Ov(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 No=class extends $t{framework="claude-code";constructor(e){let{command:n,args:i}=pi("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 Ov(e)}};pn();import{mkdtempSync as Nv,rmSync as Mv}from"node:fs";import{tmpdir as Bv}from"node:os";import{join as Fv}from"node:path";var Mo=class extends $t{framework="codex";authMethodId;codexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:s,args:a}=pi("codex",e.command,i),l=e.isolateCodexHome?Nv(Fv(Bv(),"coze-bridge-codex-home-")):void 0,u=l?{...e.env??{},CODEX_HOME:l}:e.env,f={command:s,args:a,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(f),this.authMethodId=e.authMethodId,this.codexHomeDir=l}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{Mv(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};Ze();var zv=3e4,Kr=class extends $t{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}`}]},zv))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var Th=["default","acceptEdits","plan","auto","bypassPermissions"],Rh=["read-only","auto","full-access"];function Nn(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return Th.includes(e);case"codex":return Rh.includes(e);case"openclaw":return!1}}function Ol(t){switch(t){case"claude-code":return Th.join("/");case"codex":return Rh.join("/");case"openclaw":return""}}mn();Ze();oe();Be();function Nl(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}pn();var Mn=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 Bo=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 Mn,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)ts(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 ts(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function sn(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}rn();oe();import{constants as kh}from"node:fs";import{access as Uv}from"node:fs/promises";import{delimiter as Gv,join as qv}from"node:path";var Dt=$("framework-detector"),Ch={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},Hv=[".exe",".cmd",".bat",".ps1"],ir=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??lt,access:e.access??Uv}}async detect(e){let n=Ch[e],i=await this.which(n);if(!i)return Dt.debug("framework binary not found",{framework:e,bin:n}),null;let s=e==="openclaw"?["--log-level","silent"]:[],[a,l]=await Promise.all([this.probeVersion(i,s),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:a};return l&&(u.defaultAgent=l),u}async detectAll(){let e=await Promise.all(Object.keys(Ch).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(Gv).filter(Boolean),i=this.env.platform==="win32"?["",...Hv]:[""];for(let s of n)for(let a of i){let l=qv(s,e+a);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?kh.F_OK:kh.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 Dt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return Dt.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 Dt.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 Dt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let a=s.find(l=>l?.isDefault===!0);return a?!a.id||!a.workspace?(Dt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!a.id,hasWorkspace:!!a.workspace}),null):{id:a.id,workspace:a.workspace}:(Dt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:s.length}),null)}catch(s){return Dt.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 Dt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||Dt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let s={reachable:i},a=n.stdout.match(/\{[\s\S]*\}/);if(a)try{let l=JSON.parse(a[0]);typeof l.gateway?.port=="number"&&(s.port=l.gateway.port),typeof l.service?.runtime?.status=="string"&&(s.runtime=l.service.runtime.status),!i&&typeof l.rpc?.error=="string"&&(s.detail=l.rpc.error)}catch(l){Dt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(l)})}return s}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(jv(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let s="",a=!1,l,u=f=>{a||(a=!0,l&&clearTimeout(l),i(f))};try{let f=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});l=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{s+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:s}))}catch{u(null)}})}},$v=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function jv(t){return t.replace($v,"")}import{homedir as Wv}from"node:os";import{join as Kv}from"node:path";mn();rn();pr();Ze();oe();async function Lh(){let t=Kv(Wv(),".openclaw/openclaw.json");return(await _r(t))?.gateway?.auth?.token??""}var Ph=$("openclaw.config"),Vv=[0,5e3,5e3],Zv=Qe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),Dh="models.providers.",Fo="agents.defaults.models",zo=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new Mn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Vv,this.cliTimeoutMs=e.cliTimeoutMs??Zv}async withRetry(e,n){let i;for(let s=0;s<this.retryDelaysMs.length;s++){let a=this.retryDelaysMs[s]??0;a>0&&await new Promise(l=>setTimeout(l,a));try{return await n()}catch(l){i=l,Ph.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(l)})}}throw new T("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let s=lt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",l=!1,u=x=>{l||(l=!0,clearTimeout(f),x())};s.stderr?.on("data",x=>{a+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),s.on("error",x=>u(()=>i(x))),s.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${a.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let s=String(i);if(n.some(a=>s.includes(a)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",n])))}catch(i){Ph.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",`${Dh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Dh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Fo}[${e}]`,()=>this.runCli(["config","set",Fo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Fo}[${e}]`,`${Fo}.${e}`)}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 he=$("agent-manager"),Fl="acceptEdits",Bh="full-access",Fh="read-only";function Qv(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 eS=(t,e,n,i,s,a,l,u,f,x)=>{switch(t){case"claude-code":{let m={...s?{...U0(s),...H0(s,l,u)}:{},...f??{},IS_SANDBOX:"1"};return new No({cwd:n,env:m,agentId:i})}case"codex":{let m=s?[...G0(s),...j0(s,l,u)]:[],g=Bh;x!==void 0&&(Nn("codex",x)?g=x:he.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let v=[...m,...Qv(g)],w={...s?q0(s):{},...f??{}},b=!!s;return new Mo({cwd:n,agentId:i,...v.length>0?{extraArgs:v}:{},...Object.keys(w).length>0?{env:w}:{},...b?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Kr({command:e,cwd:n,agentId:i,...a?{sessionName:Nl(a)}:{}})}};function Bl(t){return t==="claude-code"||t==="codex"}function tS(t){let e=[],n=Object.keys(t).sort();for(let i of n){let s=t[i];s!==void 0&&(nS(s)||e.push(`${i}=${s}`))}return e.length===0?"":`${e.join(`
100
99
  `)}
101
- `}function NE(t){if(t.includes(`
102
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var ME={path:"",version:"cloud-deployed"},K0="openclaw_gateway_unavailable",BE="openclaw_default_agent_missing";function W0(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 FE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},zE=6e4,ko=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??OE,this.createTimeoutMs=e.createTimeoutMs??zE,this.detectorFactory=e.detectorFactory??(()=>new Zn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Ao({command:r,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??j0(DE(),".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=>{ue.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=j0(e,".env");if(await RE(r).then(c=>c.isFile()).catch(()=>!1)){ue.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=LE({...process.env,...Gi(this.paths.agentEnvFile)});await cn(r,o,{mode:384}),ue.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ue.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 De(e.agentId,this.paths).catch(()=>null),o=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 k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")ue.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>ue.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")ue.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>ue.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){ue.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await De(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await ze(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ue.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await De(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await ze(T,this.paths))}return ue.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=Ze(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 y=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??y??u.workspace,_=new AbortController,v=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&xd(e.framework)&&await fr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await hd(u.root,{recursive:!0}),await hd(S,{recursive:!0}),await hd(u.logs,{recursive:!0}),T(),x||await hr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Ba(S,"cloud"):await Ba(S,"local",pd)),T();let D=i,E=Vf({model:e.model??D?.model}),C=Mf(e._meta)??D?.accountId,O=e.patToken??D?.patToken,F=f==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new vo({agentId:e.agentId,framework:e.framework,workspace:S,model:E.model??bt,deployType:f,...C?{accountId:C}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",D?.sessions){let $=f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Q,se]of Object.entries(D.sessions)){let oe={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};$?se.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",ue.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Q,framework:e.framework,fallback:oe.permissionMode})):Tn(e.framework,se.permissionMode)?oe.permissionMode=se.permissionMode:ue.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Q,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&ue.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Q,framework:e.framework,deployType:f}),se.cozeGroupId&&(oe.cozeGroupId=se.cozeGroupId),I.sessions.set(Q,oe)}let re=Object.keys(D.sessions).length;re>0&&ue.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(I),A=!0;let B={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:E.model};f==="cloud"&&(B.deployType="cloud"),C&&(B.accountId=C),O&&(B.patToken=O),F&&(B.modelInfo=F),D?.skills&&(B.skills=D.skills),D?.agentName&&(B.agentName=D.agentName),D?.description&&(B.description=D.description),B.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):ue.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 $=[...B.skills??[]],re=new Map($.map((oe,R)=>[oe.skillId,R])),Q=await Promise.allSettled(V.map(oe=>po({agentId:e.agentId,workspace:S,framework:e.framework,skill:oe}))),se=0;for(let[oe,R]of Q.entries()){let U=V[oe];U&&(R.status==="fulfilled"?(go($,re,R.value),se++):ue.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(R.reason)}))}se>0&&(B.skills=$,ue.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:V.length}))}return await ze(B,this.paths),ue.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 ue.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 CE(u.root,{recursive:!0,force:!0}).catch(D=>ue.warn("rm agent dir failed (ignored)",{err:String(D)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&xd(e.framework))u=ME;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);xd(e.framework)&&!gs(e.framework)&&(ue.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await fr(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),y=Jt(e)?g?.permissionMode??$0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,this.buildBinShimPathEnv(),y)}try{return await x.start(),await x.initialize(FE),x}catch(g){let y=x instanceof Nt?x.getStderrTail():[];throw y.length>0&&ue.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof k?g.code:"unknown",recentStderr:y}),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",W0(o),{cause:{reason:K0}})}catch(o){ue.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};ue.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 ue.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:BE}})}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",W0(r),{cause:{reason:K0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:l,command:u}=e,f=ud(o);if(r.deployType==="local"){let S=await this.ensureOpenclawDefaultAgent();return new zr({command:u,cwd:S.workspace,agentId:S.id,sessionName:f})}let x=await q0();try{await this.getOpenclawConfig().ensureAcpDeviceScopes()}catch(S){ue.warn("acp device scope ensure failed (ignored)",{err:String(S)})}let g=i?e0(i,c,l):null,y;if(g){let S=Zc(o),v=g.models[0]?.id??bt,I=`${S}/${v}`;if(!this.ensuredProviders.has(I)){let A=this.getOpenclawConfig();await A.ensureProvider(S,g),await A.addModelToAllowlist(I),this.ensuredProviders.add(I)}y=I}return new zr({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:f,...x?{gatewayToken:x}:{},...y?{slashModelOnStart:y}:{}})}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=Zc(i),c=`${o}/${e.model}`,l=!0;try{await r.removeProvider(o)}catch(u){l=!1,ue.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:o,err:String(u)})}try{await r.removeModelFromAllowlist(c)}catch(u){l=!1,ue.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:c,err:String(u)})}l&&this.ensuredProviders.delete(c)}}};import{randomUUID as Q0}from"node:crypto";import{promises as WE}from"node:fs";import{basename as eh}from"node:path";We();ne();import{promises as UE}from"node:fs";import{basename as HE}from"node:path";var J0=H("file-upload"),GE="/api/coze_claw/file/agent_upload",qE=6e4;async function Z0(t,e={}){let i=`${Dr(Pr(e.handshakeBase))}${GE}`,o=e.timeoutMs??qE,c=await UE.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",...In(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);J0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let g=await fetch(i,{method:"POST",headers:u,body:l,signal:f.signal}),y=g.headers.get("x-tt-logid")??"";if(!g.ok){let v=await g.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${y}: ${v.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=${y}`);let _=S.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${y}: ${JSON.stringify(S).slice(0,200)}`);return J0.info("file upload ok",{uri:_,logid:y}),{uri:_}}catch(g){throw g instanceof k?g:g.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${HE(t.path)}`):new k("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}We();ne();import{extname as jE}from"node:path";var KE={".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 Y0(t){let e=jE(t).toLowerCase();return KE[e]??"application/octet-stream"}Re();var To=H("agent-send"),X0=50*1024*1024;function th(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 nh(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&&(To.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 rh(t,e){let{session:r,runtime:i}=th(e.core,t.agentId,t.sessionId);if(!await si(t.path,r.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await WE.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>X0)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${X0}`);let c=await Y0(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??eh(t.path),u;try{u=await Z0({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 To.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:Q0(),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 nh(e,r,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),To.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 ih(t,e){let{session:r,runtime:i}=th(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??eh(t.path),c={sessionUpdate:"group_file",messageId:Q0(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await nh(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),To.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 sh(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}on();Vt();ne();var Mt=H("coze-cli-installer"),oh="@coze/cli@latest",$E="coze",ah="0.1.8",VE=5e3,JE=5e3,ZE=9e4,ch=1e4,$i=null,Co=!1;async function md(t,e={}){if(Co)return;if($i)return $i;let r=e.exec??Hf;return $i=(async()=>{try{let i=await YE($E,r),o=!1;if(i){let l=await XE(r);if(l===void 0)Mt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(sh(l,ah))Mt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:ah}),o=!0;else{Mt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),Co=!0;return}}let c=o?"upgrade-only":"full";Mt.info("coze-cli install start",{package:oh,mode:c});try{await r("npm",["i","-g","--prefer-online",oh],{timeout:ZE,maxBuffer:10*1024*1024}),Mt.info("coze-cli install ok")}catch(l){Mt.warn("coze-cli install failed (skip subsequent steps)",{err:String(l)});return}if(o){Co=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:ch}),Mt.info("coze config set xTTEnv ok",{env:t.env})}catch(l){Mt.warn("coze config set failed (continue to auth login)",{err:String(l)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:ch}),Mt.info("coze auth login ok")}catch(l){Mt.warn("coze auth login failed",{err:String(l)});return}Co=!0}finally{$i=null}})(),$i}async function YE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:VE});return Na(i)}catch{return}}async function XE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:JE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}ln();Re();var QE=10*6e4;function dh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?QE:e}function Ro(t){return an(t??Y().configFile)}function Vi(t,e){return dn(e??Y().configFile,t)}import{randomBytes as _b}from"node:crypto";cr();We();ne();import{createReadStream as eb}from"node:fs";import{mkdir as tb,readFile as nb,realpath as rb,stat as ib,writeFile as sb}from"node:fs/promises";import{basename as ob,dirname as wd,isAbsolute as ab,join as cb,relative as db,resolve as lh,sep as lb}from"node:path";import{createInterface as ub}from"node:readline";var fh=H("fs-rpc"),Ji=Je("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function hh(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Ji)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Ji} bytes`);let i=await ph(t.path,e);return await tb(wd(i),{recursive:!0}),await sb(i,t.content,"utf8"),fh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function xh(t,e){let r=await ph(t.path,e),i=await ib(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Ji&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Ji} bytes`);let c;if(o&&i.size>Ji)c=await fb(r,t.line??1,t.limit);else{let l=await nb(r,"utf8");if(o){let u=l.split(`
103
- `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;c=u.slice(f,x).join(`
104
- `)}else c=l}return fh.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function fb(t,e,r){let i=ub({input:eb(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(`
105
- `)}async function ph(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([uh(lh(e)),uh(lh(t))]),o=db(r,i);if(hb(o,lb,ab(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function hb(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function uh(t){let e=[],r=t;for(;r!==wd(r);)try{let i=await rb(r);return e.length?cb(i,...e.reverse()):i}catch{e.push(ob(r)),r=wd(r)}return t}ne();var gh=H("prompt-multimodal"),mh=10*1024*1024,xb=15e3,pb=6;async function wh(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 gb(l))}}let o=Array.from({length:Math.min(pb,t.length)},()=>i());return await Promise.all(o),e}function _h(t){return t.some(e=>e.type==="image")}async function gb(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Li(e.uri))return t;try{let{buf:r,contentType:i}=await wb(e.uri),o=e.mimeType||mb(i)||"application/octet-stream";return gh.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 gh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function mb(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function wb(t){let e=new AbortController,r=setTimeout(()=>e.abort(),xb);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>mh)throw new Error(`image too large: ${o.byteLength} bytes (max ${mh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}un();We();ne();var W=H("core"),yb=3e4,Eb=/^(boe|ppe)_[A-Za-z0-9_-]+$/,bb="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",vb="\u5BA1\u6279\u5DF2\u8D85\u65F6",Sb=3e4,Do=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=dh(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,l)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:l}),Wi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(kn(o,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(l=>W.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:X.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:X.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(wo(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&&Eb.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Nr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Nr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Nr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(o){W.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(kn(r,Hi(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=uo(r._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,bb,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{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-l,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Ff(i);switch(r){case"session/new":{let c=Ib();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,l=c.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Jt(e)?Bf(i._meta):void 0;if(u!==void 0&&!Tn(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${ld(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=uo(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&&_h(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let y=await wh(c.prompt);try{let S=await f.downstream.sessionPrompt({...c,sessionId:f.acpSessionId,prompt:y});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 v=f.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:l}),await this.synthesizePromptReply(e,f,l,vb,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,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:f.acpSessionId}),S.stop("reload-after-turn").catch(_=>W.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&&(W.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=uo(i._meta);if(!l)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Jt(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(!Tn(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${ld(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(y){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),y}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:l,modeId:u});return{}}default:throw new 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 W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let l of o)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let l of o){let u=l.runtime.downstream,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 Jt(e)&&(c.permissionMode=e.framework==="claude-code"?pd:V0),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(ft.GEN_MODEL_TOKEN,i,Sb);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(Wi(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&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let 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 W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),Jt(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,r,i){if(Wi(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let l=e.activeTriggers.get(r.acpSessionId);l&&(c.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Lr("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(Lr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(Tb(r)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=r.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&Jt(e)){let g=l.currentModeId;Tn(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(y=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(y)}))):typeof g=="string"&&!Tn(e.framework,g)&&W.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(Lr("session/update",{...r,sessionId:o,_meta:u})).catch(g=>W.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}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:X.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 hh(c,o);r.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await xh(c,o);r.respondAgentRequest(i.id,l)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Hi(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 y=u?this.reverseSessionId(e,u):void 0,S=y?e.sessions.get(y):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let _={...c,...y?{sessionId:y}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:y}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:y,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(zi(o,"session/request_permission",_)).catch(v=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),r.respondAgentRequestError(i.id,{code:X.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&Ab(e.result,o),W.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new mo(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),l=e.get(c);if(l)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:l,key:c}}}sendRequest(e,r,i=yb){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(zi(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&&Jt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await oi(e.agentId,r,this.paths)}catch(r){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(kn(e,{code:r,message:i,data:{bridgeVersion:Lt}}))}};function Ib(){return _b(16).toString("hex")}function Ab(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){W.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var kb=["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 Tb(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 kb.some(c=>o.startsWith(c))}ln();ne();Re();import{randomBytes as Cb}from"node:crypto";import{createServer as Rb}from"node:http";var Db=1e6,yh=H("ipc"),Po=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??Y()}async start(){this.token=Cb(32).toString("hex");let e=Rb((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(),yh.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 cn(this.paths.portFile,String(this.port)),await cn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Zi(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Zi(r,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await Pb(e)}catch(u){Zi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);Zi(r,200,u??{ok:!0})}catch(u){yh.error("IPC handler failed",{key:o,err:String(u)}),Zi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Zi(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>Db)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 Xv=Ht(px(),1),Qv=Ht(Ho(),1),eS=Ht(Gr(),1),tS=Ht(Cd(),1),nS=Ht(Pd(),1),rS=Ht(Fd(),1),Ix=Ht(Ko(),1),iS=Ht(Sx(),1);var Ax=Ix.default;We();ne();var{FWS:yS}=Bx(),Le=H("upstream.frontier"),zx="application/json",Ux="none",ES=15e3;function bS(t){class e extends Ax{constructor(i){super(i,qf,{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,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(kl("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");Le.debug("WS raw frame out",{bytes:c.byteLength,headHex:l})}catch(c){Le.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var ss=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:jf,...In(this.opts.ppeOverride)},r=bS(e),i=Wf(this.opts.urlOverride),o={url:i,ws:r,fpID:Gf,aID:fo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:zx,force:!0},payloadEncoding:{encoding:Ux,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new yS(o),l=!1,u=null,f,x,g=new Promise((_,v)=>{f=_,x=v}),y=_=>{l||(l=!0,u&&(clearTimeout(u),u=null),_?x(_):f())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Le.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&y();for(let v of this.connectHandlers)Promise.resolve(v({initial:_})).catch(I=>Le.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=_=>{this.opened=!1,Le.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{Le.warn("frontier error",{code:_.code,msg:_.message}),y(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??ES;u=setTimeout(()=>{y(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(v){Le.warn("fws close during start failure threw (ignored)",{err:String(v)})}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){Le.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Le.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?(Le.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;Hx(c)||Le.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:zx,payloadEncoding:Ux})}catch(u){throw Le.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){Le.debug("drop non-adapter frontier frame",{service:r});return}let i=IS(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 o;try{o=JSON.parse(i)}catch(l){Le.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let c=o;Hx(c)||Le.info("frontier frame in",{logid:SS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:vS(i)}),Promise.resolve(this.handler(o)).catch(l=>Le.warn("frontier frame handler threw",{err:String(l)}))}};function Hx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Gx=2e3;function vS(t){return t.length<=Gx?t:`${t.slice(0,Gx)}...<truncated, total ${t.length} chars>`}function SS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function IS(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}}We();ne();var Gd=H("skill-publish"),AS="/api/marketplace/product/skill/publish_with_assets",kS=15e4;async function qx(t,e={}){let i=`${Dr(Pr(e.handshakeBase))}${AS}`,o=e.timeoutMs??kS,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",...In(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);Gd.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 y=await x.json();if(Gd.info("skill publish response",{logid:g,httpStatus:x.status,code:y.code,msg:y.msg,dataSkillId:y.data?.skill_id??"",dataVersion:y.data?.version??""}),y.code!==void 0&&y.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${y.code} msg=${y.msg??"-"} logid=${g}`);let S={};return y.data?.skill_id!==void 0&&y.data.skill_id!==""&&(S.skillId=String(y.data.skill_id)),y.data?.version&&(S.version=y.data.version),Gd.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 qd=H("upstream.switchable"),ea=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;qd.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 qd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>qd.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 jd=H("upstream"),Vr=class{handler=null;async start(){jd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){jd.info("NoopUpstream stopped",{reason:e})}async send(e){jd.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)}};We();ne();ln();ne();Re();import{promises as TS}from"node:fs";var jx=H("pat-token-store");async function ta(t=Y()){try{let r=(await TS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(jx.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"&&jx.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function os(t,e=Y()){if(!t)throw new Error("writePatToken: empty patToken");await cn(e.patTokenFile,t,{mode:384})}Re();Re();import{promises as na}from"node:fs";import{join as CS}from"node:path";function RS(t,e){return`#!/bin/sh
100
+ `}function nS(t){if(t.includes(`
101
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var rS={path:"",version:"cloud-deployed"},Nh="openclaw_gateway_unavailable",iS="openclaw_default_agent_missing";function Mh(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 sS={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},oS=6e4,Uo=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??eS,this.createTimeoutMs=e.createTimeoutMs??oS,this.detectorFactory=e.detectorFactory??(()=>new ir),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new zo({command:n})),this.openclawConfigDir=e.openclawConfigDir??Oh(Xv(),".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=>{he.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=Oh(e,".env");if(await Yv(n).then(a=>a.isFile()).catch(()=>!1)){he.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let s=tS({...process.env,...Dl(this.paths.agentEnvFile)});await gn(n,s,{mode:384}),he.info("openclaw .env bootstrapped",{envFile:n,bytes:s.length}),await this.getOpenclawConfig().restartGateway(),he.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 De(e.agentId,this.paths).catch(()=>null),s=Io(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new T("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")he.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(R=>he.warn("dispose stale agent failed (ignored)",{err:String(R)})),this.registry.unregister(e.agentId);else if(s&&a.deployType!=="cloud")he.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(R=>he.warn("dispose drifted agent failed (ignored)",{err:String(R)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){he.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let R=await De(e.agentId,this.paths).catch(()=>null);R&&(R.patToken=e.patToken,await qe(R,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){he.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let R=await De(e.agentId,this.paths).catch(()=>null);R&&(R.modelInfo=e.modelInfo,await qe(R,this.paths))}return he.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.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=et(e.agentId,this.paths),f=s?"cloud":"local",x=e.framework==="openclaw"&&f==="local",m;x&&!n?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let g=m??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??g??u.workspace,w=new AbortController,b=setTimeout(()=>w.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{s&&Bl(e.framework)&&await wr(e.framework,w.signal);let R=()=>{if(w.signal.aborted)throw w.signal.reason instanceof Error?w.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await Ml(u.root,{recursive:!0}),await Ml(v,{recursive:!0}),await Ml(u.logs,{recursive:!0}),R(),x||await Er(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await cc(v,"cloud"):await cc(v,"local",Fl)),R();let P=i,E=F0({model:e.model??P?.model}),k=A0(e._meta)??P?.accountId,L=e.patToken??P?.patToken,B=f==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new Bo({agentId:e.agentId,framework:e.framework,workspace:v,model:E.model??Pt,deployType:f,...k?{accountId:k}:{},...L?{patToken:L}:{},...B?{modelInfo:B}:{}}),I.status="ok",P?.sessions){let Z=f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[te,le]of Object.entries(P.sessions)){let de={acpSessionId:le.acpSessionId,modelToken:le.modelToken,tokenGeneratedAt:le.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};Z?le.permissionMode===void 0?(de.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",he.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:te,framework:e.framework,fallback:de.permissionMode})):Nn(e.framework,le.permissionMode)?de.permissionMode=le.permissionMode:he.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:te,framework:e.framework,value:le.permissionMode}):le.permissionMode!==void 0&&he.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:te,framework:e.framework,deployType:f}),le.cozeGroupId&&(de.cozeGroupId=le.cozeGroupId),I.sessions.set(te,de)}let ae=Object.keys(P.sessions).length;ae>0&&he.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ae})}this.registry.register(I),A=!0;let M={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:E.model};f==="cloud"&&(M.deployType="cloud"),k&&(M.accountId=k),L&&(M.patToken=L),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??Ht,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):he.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let X=e.initialSkills??[];if(X.length>0){let Z=[...M.skills??[]],ae=new Map(Z.map((de,C)=>[de.skillId,C])),te=await Promise.allSettled(X.map(de=>Co({agentId:e.agentId,workspace:v,framework:e.framework,skill:de}))),le=0;for(let[de,C]of te.entries()){let G=X[de];G&&(C.status==="fulfilled"?(Po(Z,ae,C.value),le++):he.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:G.skillId,skillName:G.skillName,err:String(C.reason)}))}le>0&&(M.skills=Z,he.info("initialSkills installed",{agentId:e.agentId,installed:le,requested:X.length}))}return await qe(M,this.paths),he.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(R){throw he.error("agent create failed, rolling back",{agentId:e.agentId,err:String(R)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Jv(u.root,{recursive:!0,force:!0}).catch(P=>he.warn("rm agent dir failed (ignored)",{err:String(P)})),R instanceof T?R:new T("AGENT_SPAWN_FAILED",String(R),{cause:R})}finally{clearTimeout(b)}}async spawnSessionDownstream(e,n,i,s,a){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&Bl(e.framework))u=rS;else throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Bl(e.framework)&&!Ps(e.framework)&&(he.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await wr(e.framework));let f=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:f,cloudSessionId:i,cozeEnv:s,mockScenario:a,command:u.path});else{let m=e.sessions.get(i),g=sn(e)?m?.permissionMode??Bh:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,s,a,this.buildBinShimPathEnv(),g)}try{return await x.start(),await x.initialize(sS),x}catch(m){let g=x instanceof $t?x.getStderrTail():[];throw g.length>0&&he.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof T?m.code:"unknown",recentStderr:g}),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",Mh(s),{cause:{reason:Nh}})}catch(s){he.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};he.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 he.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:iS}})}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",Mh(n),{cause:{reason:Nh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:s,cozeEnv:a,mockScenario:l,command:u}=e,f=Nl(s);if(n.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new Kr({command:u,cwd:v.workspace,agentId:v.id,sessionName:f})}let x=await Lh(),m=i?$0(i,a,l):null,g;if(m){let v=El(s),b=m.models[0]?.id??Pt,I=`${v}/${b}`;if(!this.ensuredProviders.has(I)){let A=this.getOpenclawConfig();await A.ensureProvider(v,m),await A.addModelToAllowlist(I),this.ensuredProviders.add(I)}g=I}return new Kr({command:u,cwd:n.workspace,agentId:n.agentId,sessionName:f,...x?{gatewayToken:x}:{},...g?{slashModelOnStart:g}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let n=this.openclawConfigCache;for(let i of e.sessions.keys()){let s=El(i),a=`${s}/${e.model}`,l=!0;try{await n.removeProvider(s)}catch(u){l=!1,he.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:s,err:String(u)})}try{await n.removeModelFromAllowlist(a)}catch(u){l=!1,he.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:a,err:String(u)})}l&&this.ensuredProviders.delete(a)}}};import{randomUUID as Hh}from"node:crypto";import{promises as hS}from"node:fs";import{basename as $h}from"node:path";Ze();oe();import{promises as aS}from"node:fs";import{basename as cS}from"node:path";var zh=$("file-upload"),lS="/api/coze_claw/file/agent_upload",dS=6e4;async function Uh(t,e={}){let i=`${zr(Ur(e.handshakeBase))}${lS}`,s=e.timeoutMs??dS,a=await aS.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([a],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Dn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),s);zh.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:l,signal:f.signal}),g=m.headers.get("x-tt-logid")??"";if(!m.ok){let b=await m.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${g}: ${b.slice(0,200)}`)}let v=await m.json();if(v.code!==void 0&&v.code!==0)throw new T("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${g}`);let w=v.data?.file?.file_url;if(!w)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${g}: ${JSON.stringify(v).slice(0,200)}`);return zh.info("file upload ok",{uri:w,logid:g}),{uri:w}}catch(m){throw m instanceof T?m:m.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${s}ms) for ${cS(t.path)}`):new T("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(x)}}Ze();oe();import{extname as uS}from"node:path";var fS={".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 Gh(t){let e=uS(t).toLowerCase();return fS[e]??"application/octet-stream"}Be();var Go=$("agent-send"),qh=50*1024*1024;function jh(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 Wh(t,e,n,i,s,a){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,n,i,s);return}catch(x){u=x,f<2&&(Go.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(m=>setTimeout(m,5e3)))}throw new T("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function Kh(t,e){let{session:n,runtime:i}=jh(e.core,t.agentId,t.sessionId);if(!await gi(t.path,n.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let s=await hS.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>qh)throw new T("FILE_TOO_LARGE",`${s.size} bytes > limit ${qh}`);let a=await Gh(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new T("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let l=t.name??$h(t.path),u;try{u=await Uh({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:a,name:l,sizeBytes:s.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Go.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:s.size,mime:a,code:x instanceof T?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let f={sessionUpdate:"agent_file",messageId:Hh(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:a,name:l,sizeBytes:s.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Wh(e,n,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Go.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:l,bytes:s.size,mime:a,uri:u.uri}),{ok:!0,uri:u.uri,bytes:s.size,mimeType:a,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Vh(t,e){let{session:n,runtime:i}=jh(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??$h(t.path),a={sessionUpdate:"group_file",messageId:Hh(),content:{uri:t.path,name:s,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Wh(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),Go.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 Zh(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),s=Math.max(n.length,i.length);for(let a=0;a<s;a++){let l=n[a]??0,u=i[a]??0;if(l<u)return!0;if(l>u)return!1}return!1}pn();rn();oe();var jt=$("coze-cli-installer"),Jh="@coze/cli@latest",xS="coze",Yh="0.1.8",pS=5e3,gS=5e3,mS=9e4,Xh=1e4,ns=null,qo=!1;async function Ul(t,e={}){if(qo)return;if(ns)return ns;let n=e.exec??P0;return ns=(async()=>{try{let i=await wS(xS,n),s=!1;if(i){let l=await _S(n);if(l===void 0)jt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Zh(l,Yh))jt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:Yh}),s=!0;else{jt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),qo=!0;return}}let a=s?"upgrade-only":"full";jt.info("coze-cli install start",{package:Jh,mode:a});try{await n("npm",["i","-g","--prefer-online",Jh],{timeout:mS,maxBuffer:10*1024*1024}),jt.info("coze-cli install ok")}catch(l){jt.warn("coze-cli install failed (skip subsequent steps)",{err:String(l)});return}if(s){qo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:Xh}),jt.info("coze config set xTTEnv ok",{env:t.env})}catch(l){jt.warn("coze config set failed (continue to auth login)",{err:String(l)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:Xh}),jt.info("coze auth login ok")}catch(l){jt.warn("coze auth login failed",{err:String(l)});return}qo=!0}finally{ns=null}})(),ns}async function wS(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:pS});return oc(i)}catch{return}}async function _S(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:gS});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}mn();Be();var yS=10*6e4;function Qh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?yS:e}function Ho(t){return _r(t??ie().configFile)}function rs(t,e){return yr(e??ie().configFile,t)}import{randomBytes as US}from"node:crypto";pr();Ze();oe();import{createReadStream as ES}from"node:fs";import{mkdir as bS,readFile as vS,realpath as SS,stat as IS,writeFile as AS}from"node:fs/promises";import{basename as TS,dirname as Gl,isAbsolute as RS,join as kS,relative as CS,resolve as ex,sep as PS}from"node:path";import{createInterface as DS}from"node:readline";var nx=$("fs-rpc"),is=Qe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function rx(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>is)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${is} bytes`);let i=await sx(t.path,e);return await bS(Gl(i),{recursive:!0}),await AS(i,t.content,"utf8"),nx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function ix(t,e){let n=await sx(t.path,e),i=await IS(n),s=typeof t.line=="number"||typeof t.limit=="number";if(i.size>is&&!s)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${is} bytes`);let a;if(s&&i.size>is)a=await LS(n,t.line??1,t.limit);else{let l=await vS(n,"utf8");if(s){let u=l.split(`
102
+ `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;a=u.slice(f,x).join(`
103
+ `)}else a=l}return nx.info("fs/read_text_file ok",{path:n,size:a.length}),{content:a}}async function LS(t,e,n){let i=DS({input:ES(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),s=Math.max(0,e-1),a=typeof n=="number"?s+n:Number.POSITIVE_INFINITY,l=[],u=0;try{for await(let f of i)if(u>=s&&u<a&&l.push(f),u++,u>=a)break}finally{i.close()}return l.join(`
104
+ `)}async function sx(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([tx(ex(e)),tx(ex(t))]),s=CS(n,i);if(OS(s,PS,RS(s)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function OS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function tx(t){let e=[],n=t;for(;n!==Gl(n);)try{let i=await SS(n);return e.length?kS(i,...e.reverse()):i}catch{e.push(TS(n)),n=Gl(n)}return t}oe();var ox=$("prompt-multimodal"),ax=10*1024*1024,NS=15e3,MS=6;async function cx(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let a=n++,l=t[a];l!==void 0&&(e[a]=await BS(l))}}let s=Array.from({length:Math.min(MS,t.length)},()=>i());return await Promise.all(s),e}function lx(t){return t.some(e=>e.type==="image")}async function BS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!ji(e.uri))return t;try{let{buf:n,contentType:i}=await zS(e.uri),s=e.mimeType||FS(i)||"application/octet-stream";return ox.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 ox.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function FS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function zS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),NS);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>ax)throw new Error(`image too large: ${s.byteLength} bytes (max ${ax})`);return{buf:Buffer.from(s),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}wn();Ze();oe();var K=$("core"),GS=3e4,qS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,HS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",$S="\u5BA1\u6279\u5DF2\u8D85\u65F6",jS=3e4,$o=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new $r;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=Qh(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(),K.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){K.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),K.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){K.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)&&K.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,i){let s=i.downstream;s&&(s.onUpdate(a=>{i.loadingSession||this.forwardUpdate(e,a)}),s.onAgentRequest(a=>{this.handleAgentRequest(e,s,a)}),s.onExit((a,l)=>{K.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:l}),ts(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,a]of this.pendingUpstream)a.downstream===e&&i.push(s);if(i.length!==0){K.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let s of i){let a=this.pendingUpstream.get(s);if(a){this.pendingUpstream.delete(s),this.upstream.send(On(s,{code:ee.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(l=>K.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:ee.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){K.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:ee.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Lo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&qS.test(i)?this.currentCozeEnv=i:i&&K.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,ee.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):K.warn("drop notification: extension not registered",{method:e.method});return}let a=await s(e,this);n!==null&&await this.upstream.send(Hr(n,a));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Hr(n,s));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Hr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,ee.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):K.warn("drop unknown notification",{method:e.method})}catch(s){K.error("handleFrame failed",{method:e.method,err:String(s)}),n!==null&&await this.upstream.send(On(n,Xi(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 a=typeof n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!a)return this.dispatchSessionCall(s,e.method,n);if(e.method==="session/prompt"){let f=s.sessions.get(a);if(f?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,m=Ao(n._meta);return K.info("session in pendingPermission, bouncing new prompt",{agentId:s.agentId,cloudSessionId:a}),this.synthesizePromptReply(s,f,a,HS,x,m)}}let l=Date.now(),u=!1;try{let f=await s.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(s,e.method,n));return u=!0,f}finally{K.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-l,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:s}=R0(i);switch(n){case"session/new":{let a=WS();return K.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=s;return K.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:a.sessionId}),{}}case"session/prompt":{let a=s,l=a.sessionId;if(!l)throw new T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=sn(e)?T0(i._meta):void 0;if(u!==void 0&&!Nn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Ol(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 T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&f.permissionMode!==void 0&&f.permissionMode!==u){let v=f.permissionMode;f.permissionMode=u,await this.persistSessionMapping(e);try{await f.downstream.setSessionMode({sessionId:f.acpSessionId,modeId:u})}catch(w){throw f.permissionMode=v,await this.persistSessionMapping(e).catch(()=>{}),w}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(f.acpSessionId,x):e.activeTriggers.delete(f.acpSessionId);let m=Ao(i._meta);if(m?e.activeGroupIds.set(f.acpSessionId,m):e.activeGroupIds.delete(f.acpSessionId),m&&f.cozeGroupId!==m&&(f.cozeGroupId=m,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&lx(a.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let g=await cx(a.prompt);try{let v=await f.downstream.sessionPrompt({...a,sessionId:f.acpSessionId,prompt:g});return f.lastActiveAt=Date.now(),v}catch(v){if(v instanceof T&&v.code==="AGENT_APPROVAL_TIMEOUT"){let w=f.pendingPermission;w&&(w.downstream.respondAgentRequest(w.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(w.upstreamId),f.pendingPermission=void 0);let b=f.acpSessionId,I=b?e.activeTriggers.get(b):void 0,A=b?e.activeGroupIds.get(b):void 0;return K.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:l}),await this.synthesizePromptReply(e,f,l,$S,I,A)}throw v}finally{if(e.activeTriggers.delete(f.acpSessionId),e.activeGroupIds.delete(f.acpSessionId),f.pendingPermission=void 0,f.reloadAfterTurn){f.reloadAfterTurn=!1;let v=f.downstream;v&&(f.downstream=void 0,K.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:f.acpSessionId}),v.stop("reload-after-turn").catch(w=>K.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(w)})))}else f.downstream?.isAlive()&&this.armIdleTimer(e,l,f)}}case"session/cancel":{let l=s.sessionId;if(!l)throw new T("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&&(K.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:f.size}),f.dispose(new T("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${l}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=s,l=a.sessionId,u=a.modeId,f=Ao(i._meta);if(!l)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!sn(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(!Nn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Ol(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 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(g){throw x.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),g}else K.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:l,modeId:u});return{}}default:throw new T("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let s=[];for(let[l,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&s.push({cloudId:l,runtime:u,oldMode:u.permissionMode});if(s.length===0)return K.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};K.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:s.length});for(let l of s)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let l of s){let u=l.runtime.downstream,f=l.runtime.acpSessionId;u?.isAlive()&&f&&a.push({downstream:u,acpSessionId:f,oldMode:l.oldMode,runtime:l.runtime})}for(let l of a)try{await l.downstream.setSessionMode({sessionId:l.acpSessionId,modeId:i})}catch(u){for(let f of s)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n){let i=e.sessions.get(n);if(i)return i;let a={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return sn(e)&&(a.permissionMode=e.framework==="claude-code"?Fl:Fh),e.sessions.set(n,a),await this.persistSessionMapping(e),a}async requestSessionToken(e,n){let i={sessionId:n,_meta:{cozeAgentId:e}};try{let s=await this.sendRequest(_t.GEN_MODEL_TOKEN,i,jS);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(ts(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,a=3e4,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=s&&Date.now()-u<a)throw new T("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${l} times in a row; please check framework binary / network and retry after ${Math.ceil((a-(Date.now()-u))/1e3)}s`);let f;try{f=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=l+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=s&&i.acpSessionId&&(K.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=f,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),K.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){K.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 f.sessionNew({cwd:e.workspace});i.acpSessionId=m.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 K.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,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),sn(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){K.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(ts(i),this.isRuntimeBusy(e,i)){K.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)){K.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}K.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(a=>K.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(a)}))},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 a={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let l=e.activeTriggers.get(n.acpSessionId);l&&(a.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(n.acpSessionId);u&&(a.cozeGroupId=u)}await this.upstream.send(qr("session/update",{sessionId:i,update:s,_meta:a}))}async synthesizePromptReply(e,n,i,s,a,l){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return a&&(u.cozeTriggerMsgId=a),l&&(u.cozeGroupId=l),await this.upstream.send(qr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}},_meta:u})).catch(f=>K.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,s=this.reverseSessionId(e,i);if(!s){K.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(s);if(!a){K.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(ZS(n)){K.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=n.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&sn(e)){let m=l.currentModeId;Nn(e.framework,m)&&a.permissionMode!==m?(a.permissionMode=m,this.persistSessionMapping(e).catch(g=>K.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(g)}))):typeof m=="string"&&!Nn(e.framework,m)&&K.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:++a.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(qr("session/update",{...n,sessionId:s,_meta:u})).catch(m=>K.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}K.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:ee.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 a=i.params??{},l=await rx(a,s);n.respondAgentRequest(i.id,l)}else{let a=i.params??{},l=await ix(a,s);n.respondAgentRequest(i.id,l)}}catch(s){K.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(s)}),n.respondAgentRequestError(i.id,Xi(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"),a=i.params??{},u=a.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let m=u?e.activeGroupIds.get(u):void 0;m&&(x.cozeGroupId=m);let g=u?this.reverseSessionId(e,u):void 0,v=g?e.sessions.get(g):void 0;v&&(v.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:s});let w={...a,...g?{sessionId:g}:{},_meta:x};this.pendingUpstream.set(s,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:g}),K.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:s,acpSessionId:u,cloudSessionId:g,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(b=>({optionId:b.optionId,kind:b.kind,name:b.name}))}),this.upstream.send(Ji(s,"session/request_permission",w)).catch(b=>{this.pendingUpstream.delete(s),K.error("forward permission request failed",{agentId:e.agentId,err:String(b)}),n.respondAgentRequestError(i.id,{code:ee.INTERNAL_ERROR,message:`upstream send failed: ${String(b)}`})})}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?(K.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"&&KS(e.result,s),K.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 Do(e.error)):i.value.resolve(e.result);return}K.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 a=String(n),l=e.get(a);if(l)return K.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:l,key:a}}}sendRequest(e,n,i=GS){let s=this.upstreamIds.next(e);return new Promise((a,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(s),l(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(s,{method:e,resolve:a,reject:l,timer:u}),this.upstream.send(Ji(s,e,n)).catch(f=>{let x=this.pendingBridge.get(s);x&&(clearTimeout(x.timer),this.pendingBridge.delete(s)),l(f)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,s]of e.sessions){let a={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(a.acpSessionId=s.acpSessionId),s.permissionMode&&sn(e)&&(a.permissionMode=s.permissionMode),s.cozeGroupId&&(a.cozeGroupId=s.cozeGroupId),n.set(i,a)}await mi(e.agentId,n,this.paths)}catch(n){K.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(On(e,{code:n,message:i,data:{bridgeVersion:Ht}}))}};function WS(){return US(16).toString("hex")}function KS(t,e){if(!t||typeof t!="object"){K.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){K.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"){K.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let a=i.outcome;(typeof a!="string"||a!=="selected"&&a!=="cancelled")&&K.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var VS=["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 ZS(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 VS.some(a=>s.startsWith(a))}mn();oe();Be();import{randomBytes as JS}from"node:crypto";import{createServer as YS}from"node:http";var XS=1e6,dx=$("ipc"),jo=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??ie()}async start(){this.token=JS(32).toString("hex");let e=YS((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(),dx.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 gn(this.paths.portFile,String(this.port)),await gn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){ss(n,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(s);if(!a){ss(n,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await QS(e)}catch(u){ss(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(l,e);ss(n,200,u??{ok:!0})}catch(u){dx.error("IPC handler failed",{key:s,err:String(u)}),ss(n,500,{error:u instanceof Error?u.message:String(u)})}}};function ss(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function QS(t){let e=[],n=0;for await(let s of t){let a=s;if(n+=a.length,n>XS)throw new Error("body too large");e.push(a)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var _I=Nt(op(),1),yI=Nt(ea(),1),EI=Nt(Jr(),1),bI=Nt(Xl(),1),vI=Nt(td(),1),SI=Nt(ad(),1),pp=Nt(ia(),1),II=Nt(xp(),1);var gp=pp.default;Ze();oe();var{FWS:GI}=Tp(),Ne=$("upstream.frontier"),kp="application/json",Cp="none",qI=15e3;function HI(t){class e extends gp{constructor(i){super(i,L0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Ne.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(mu("debug"))try{let a;typeof i=="string"?a=Buffer.from(i,"utf8"):i instanceof Buffer?a=i:i instanceof ArrayBuffer?a=new Uint8Array(i):ArrayBuffer.isView(i)?a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):a=new Uint8Array(0);let l=Buffer.from(a.slice(0,128)).toString("hex");Ne.debug("WS raw frame out",{bytes:a.byteLength,headHex:l})}catch(a){Ne.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...s)}}return e}var xs=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){Ne.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:O0,...Dn(this.opts.ppeOverride)},n=HI(e),i=M0(this.opts.urlOverride),s={url:i,ws:n,fpID:D0,aID:To,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:kp,force:!0},payloadEncoding:{encoding:Cp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new GI(s),l=!1,u=null,f,x,m=new Promise((w,b)=>{f=w,x=b}),g=w=>{l||(l=!0,u&&(clearTimeout(u),u=null),w?x(w):f())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let w=this.openCount===1;Ne.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:w,openCount:this.openCount}),w&&g();for(let b of this.connectHandlers)Promise.resolve(b({initial:w})).catch(I=>Ne.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=w=>{this.opened=!1,Ne.info("frontier closed",{code:w.code,reason:w.reason,willReconnect:w.willReconnect})},a.onerror=w=>{Ne.warn("frontier error",{code:w.code,msg:w.message}),g(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${w.code} msg=${w.message??""}`))},a.onmessage=w=>this.handleMessage(w),this.fws=a;let v=this.opts.openTimeoutMs??qI;u=setTimeout(()=>{g(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await a.connect();try{await m}catch(w){try{a.close(1e3,"open failed")}catch(b){Ne.warn("fws close during start failure threw (ignored)",{err:String(b)})}throw this.fws=null,this.opened=!1,w}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Ne.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Ne.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?(Ne.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),a=e;Pp(a)||Ne.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:s.length});try{await n.send(s,{service:33555712,method:1,payloadType:kp,payloadEncoding:Cp})}catch(u){throw Ne.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.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){Ne.debug("drop non-adapter frontier frame",{service:n});return}let i=WI(e);if(!i){Ne.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Ne.debug("frame received but no onFrame handler",{size:i.length});return}let s;try{s=JSON.parse(i)}catch(l){Ne.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let a=s;Pp(a)||Ne.info("frontier frame in",{logid:jI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:$I(i)}),Promise.resolve(this.handler(s)).catch(l=>Ne.warn("frontier frame handler threw",{err:String(l)}))}};function Pp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Dp=2e3;function $I(t){return t.length<=Dp?t:`${t.slice(0,Dp)}...<truncated, total ${t.length} chars>`}function jI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function WI(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}}Ze();oe();var ud=$("skill-publish"),KI="/api/marketplace/product/skill/publish_with_assets",VI=15e4;async function Lp(t,e={}){let i=`${zr(Ur(e.handshakeBase))}${KI}`,s=e.timeoutMs??VI,a=new FormData;a.append("skill_id",t.skillId??""),a.append("skill_name",t.skillName),a.append("skill_description",t.description??""),a.append("agent_id",t.agentId),a.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",...Dn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),s);ud.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:a,signal:u.signal}),m=x.headers.get("x-tt-logid")??"";if(!x.ok){let w=await x.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${m}: ${w.slice(0,200)}`)}let g=await x.json();if(ud.info("skill publish response",{logid:m,httpStatus:x.status,code:g.code,msg:g.msg,dataSkillId:g.data?.skill_id??"",dataVersion:g.data?.version??""}),g.code!==void 0&&g.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${g.code} msg=${g.msg??"-"} logid=${m}`);let v={};return g.data?.skill_id!==void 0&&g.data.skill_id!==""&&(v.skillId=String(g.data.skill_id)),g.data?.version&&(v.version=g.data.version),ud.info("skill publish ok",{logid:m,skillId:v.skillId??"",version:v.version??""}),v}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(f)}}oe();var fd=$("upstream.switchable"),ha=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;fd.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 fd.error("swap target start failed, reverting",{err:String(s)}),this.inner=i,s}await i.stop(n??"swapped").catch(s=>fd.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()}};oe();var hd=$("upstream"),ni=class{handler=null;async start(){hd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){hd.info("NoopUpstream stopped",{reason:e})}async send(e){hd.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)}};Ze();oe();mn();oe();Be();import{promises as ZI}from"node:fs";var Op=$("pat-token-store");async function xa(t=ie()){try{let n=(await ZI.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Op.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"&&Op.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ps(t,e=ie()){if(!t)throw new Error("writePatToken: empty patToken");await gn(e.patTokenFile,t,{mode:384})}Be();Be();import{promises as pa}from"node:fs";import{join as JI}from"node:path";function YI(t,e){return`#!/bin/sh
106
105
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
107
- `}function DS(t,e){return`@echo off\r
106
+ `}function XI(t,e){return`@echo off\r
108
107
  "${e}" "${t}" %*\r
109
- `}async function Kx(t,e=Y()){let r=e.binDir;await na.mkdir(r,{recursive:!0});let i=CS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?DS(t,o):RS(t,o);return await na.readFile(i,"utf8").catch(()=>null)===c||(await na.writeFile(i,c,"utf8"),process.platform!=="win32"&&await na.chmod(i,493)),r}ne();Re();import{execSync as Wx}from"node:child_process";import{readFileSync as $x,unlinkSync as PS}from"node:fs";import{mkdir as OS,open as LS,readFile as Vx,unlink as Kd,writeFile as NS}from"node:fs/promises";import{dirname as MS}from"node:path";var BS=H("single-instance"),FS=t=>new Promise(e=>setTimeout(e,t)),ra=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Y().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>qi(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&BS.warn("removing stale pid file",{stalePid:i}),await NS(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 Vx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Kd(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 Vx(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 OS(MS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await LS(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 FS(this.claimLockIntervalMs);continue}await Kd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Kd(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=$x(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Br)||r.includes("lib/index.js"))}catch{}try{let r=Wx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Br)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Wx(`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{$x(this.pidFile,"utf8").trim()===String(this.selfPid)&&PS(this.pidFile)}catch{}})}};ia();ne();var rr=H("daemon.upstream-watchdog"),WS=12e4,$S=9e5,VS=3e4;function $d(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var sa=class{constructor(e){this.opts=e;this.softMs=e.softMs??$d("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",WS),this.hardMs=e.hardMs??$d("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",$S),this.intervalMs=e.intervalMs??$d("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",VS),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?.(),rr.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&&rr.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&&rr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,rr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){rr.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,rr.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>rr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var j=H("daemon");async function Yx(){let t=Y();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Il({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:R=>Ze(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
108
+ `}async function Np(t,e=ie()){let n=e.binDir;await pa.mkdir(n,{recursive:!0});let i=JI(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),s=process.execPath,a=process.platform==="win32"?XI(t,s):YI(t,s);return await pa.readFile(i,"utf8").catch(()=>null)===a||(await pa.writeFile(i,a,"utf8"),process.platform!=="win32"&&await pa.chmod(i,493)),n}oe();Be();import{execSync as Mp}from"node:child_process";import{readFileSync as Bp,unlinkSync as QI}from"node:fs";import{mkdir as eA,open as tA,readFile as Fp,unlink as xd,writeFile as nA}from"node:fs/promises";import{dirname as rA}from"node:path";var iA=$("single-instance"),sA=t=>new Promise(e=>setTimeout(e,t)),ga=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??ie().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Qi(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&&iA.warn("removing stale pid file",{stalePid:i}),await nA(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 Fp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await xd(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 Fp(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 eA(rA(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let s;try{s=await tA(n,"wx")}catch(a){if(a.code!=="EEXIST")throw a;let l=await this.readPidFrom(n);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await sA(this.claimLockIntervalMs);continue}await xd(n).catch(()=>{});continue}try{return await s.writeFile(String(this.selfPid)),await e()}finally{await s.close().catch(()=>{}),await xd(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=Bp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(jr)||n.includes("lib/index.js"))}catch{}try{let n=Mp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(jr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Mp(`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{Bp(this.pidFile,"utf8").trim()===String(this.selfPid)&&QI(this.pidFile)}catch{}})}};ma();oe();var dr=$("daemon.upstream-watchdog"),hA=12e4,xA=9e5,pA=3e4;function gd(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var wa=class{constructor(e){this.opts=e;this.softMs=e.softMs??gd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",hA),this.hardMs=e.hardMs??gd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",xA),this.intervalMs=e.intervalMs??gd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",pA),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?.(),dr.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&&dr.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&&dr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,dr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){dr.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,dr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>dr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var j=$("daemon");async function Gp(){let t=ie();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){pu({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>et(C,t).logs,listAgentIds:()=>Ds(t)});try{let{writeFileSync:C}=await import("node:fs");C(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
110
109
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
111
110
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
112
- `)}catch{}}let e=new ra({processTitle:Br}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Ro(),o=i??{};xs({pid:process.pid}),j.info(i?"loaded bridge config":"initialized bridge config");let c=new ea(new Vr),l=null,u=new Do({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(R,U,K,te)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(R,U,K,te)}}),f=new ko({paths:t,config:o,registry:u});l=f;let x,g,y=null,S={},_,v=null,I=null,A=null,T=new Cn;function D(R,U){return T.enqueue(()=>C(R,U))}function E(){I||(I=new sa({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:R=>{if(process.env[as]==="1"){j.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:R});return}j.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:R}),process.exit(1)}})),I.start()}async function C(R,U){let K=R,te=K?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let et=Mi(K.env),ge=K.handshake_url,me=K.frontier_url,It=Zx(K.env,ge,me);if(A=K,!U?.force&&x===te&&g===It){let Ee=await JS(t);return u.agents.size===0&&Ee?(j.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),aa(t,f).catch(Te=>j.warn("connect-noop auto-revive error (ignored)",{err:String(Te)}))):j.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let pt=!!x&&x!==te,tn=g!==void 0&&g!==It,Ut=pt||tn,nn=await Wc({privatecode:te,...ge?{endpoint:ge}:{},ppeOverride:et});if(Ut){j.warn("connect config switched, resetting agents",{pcChanged:pt,envChanged:tn,previousPc:x?oa(x):"",nextPc:oa(te)});for(let Ee of[...u.agents.values()])await Ee.dispose("connect config switch").catch(()=>{}),u.agents.delete(Ee.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Vr,"connect switch").catch(()=>{})}y=nn.deviceId,xs({deviceId:y,pid:process.pid}),md({patToken:te,env:K.env}).catch(Ee=>j.warn("coze-cli setup error (ignored)",{err:String(Ee)}));let Qr=new ss({handshake:nn,privatecode:te,...me?{urlOverride:me}:{},ppeOverride:et,getPatTokenForAgent:Ee=>u.agents.get(Ee)?.patToken});return await c.swap(Qr,"connect"),x=te,g=It,S=et,_=ge,K.mock_scenario!==void 0&&(u.setMockScenario(K.mock_scenario),j.info("mock scenario set",{scenario:K.mock_scenario})),v||(v=new Fi({core:u,getDeviceId:()=>y??"",onTickEnd:()=>B.retryPending().catch(Ee=>j.warn("detailSync.retryPending failed (ignored)",{err:String(Ee)})),onAuthFailures:V})),v.start(),E(),Ut&&aa(t,f).catch(Ee=>j.warn("post-connect-switch auto-revive error (ignored)",{err:String(Ee)})),os(te,t).catch(Ee=>j.warn("writePatToken after /connect failed (ignored)",{err:String(Ee)})),j.info("/connect: WS established",{deviceId:y}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async R=>f.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 k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return qx({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:_,ppeOverride:S})},disposeAndMarkDisconnected:async(R,U)=>{let K=u.agents.get(R);if(K){await f.cleanupOpenclawSessionProviders(K).catch(et=>j.warn("cleanup openclaw providers failed (ignored)",{agentId:R,err:String(et)}));let te=!0;try{await K.dispose(`disconnect: ${U}`)}catch(et){te=!1,j.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:R,err:String(et)}),K.status="error"}te&&(K.status="disconnected",u.unregister(R),u.disconnectedAgents.add(R))}else u.disconnectedAgents.add(R)},disposeForDelete:async(R,U)=>{let K=u.agents.get(R);K&&(await f.cleanupOpenclawSessionProviders(K).catch(te=>j.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:R,err:String(te)})),await K.dispose(`delete: ${U}`).catch(te=>j.warn("dispose during delete failed (ignored)",{agentId:R,err:String(te)})),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=>{await f.cleanupOpenclawSessionProviders(R)},openclawRepair:async(R,U)=>{await f.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:f,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}`}),j.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(K){j.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(K)})}}))};c.onConnect(({initial:R})=>{j.info("frontier upstream connected, triggering detail sync",{initial:R}),B.syncAll(R?"initial-connect":"reconnect").catch(U=>j.warn("detail sync top-level error (ignored)",{err:String(U)}))});let $=new Po({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let R=u.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[as]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:y??"",frameworksCache:o.frameworksCache??{},...R?{mockScenario:R}:{}}}},{method:"POST",path:"/pair",handler:async R=>{let U=R,K=U?.privatecode,te=U?.pairing_code;if(!K||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let et=Mi(U.env),ge=U.handshake_url,me=U.frontier_url,It=Zx(U.env,ge,me),pt=!!x&&x!==K,tn=g!==void 0&&g!==It,Ut=pt||tn,nn=await Wc({privatecode:K,...ge?{endpoint:ge}:{},ppeOverride:et});if(Ut){j.warn("pair config switched, resetting agents",{pcChanged:pt,envChanged:tn,previousPc:x?oa(x):"",nextPc:oa(K),previousEnvKey:g??"",nextEnvKey:It});for(let Te of[...u.agents.values()])await Te.dispose("pair config switch").catch(()=>{}),u.agents.delete(Te.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Vr,"pair switch").catch(()=>{})}y=nn.deviceId,xs({deviceId:y,pid:process.pid}),md({patToken:K,env:U.env}).catch(Te=>j.warn("coze-cli setup error (ignored)",{err:String(Te)}));let Qr=new ss({handshake:nn,privatecode:K,...me?{urlOverride:me}:{},ppeOverride:et,getPatTokenForAgent:Te=>u.agents.get(Te)?.patToken});await c.swap(Qr,"pair");try{let Te=new Zn;o.frameworksCache=await Te.detectAll(),await Vi(o),j.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Te){j.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Te)})}let Ee=Object.keys(o.frameworksCache??{});try{let Te=await u.sendRequest("_agent/pair",{pairCode:te,patToken:K,frameworks:Ee,_meta:{cozeDeviceId:y}});j.info("_agent/pair ok",{pairResult:Te}),x=K,g=It,S=et,_=ge,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),j.info("mock scenario set",{scenario:U.mock_scenario})),os(K,t).catch(Ne=>j.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),v||(v=new Fi({core:u,getDeviceId:()=>y??"",onTickEnd:()=>B.retryPending().catch(Ne=>j.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:V})),v.start(),E(),Ut&&aa(t,f).catch(Ne=>j.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let ir;return U.agent_id&&(ir=await YS(U.agent_id,t,f,Ne=>u.sendRequest("_agent/detail",Ne),K).catch(Ne=>(j.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",...ir?{agent:ir}:{}}}catch(Te){return j.error("_agent/pair failed",{err:String(Te)}),{ok:!1,note:`pair failed: ${String(Te)}`}}}},{method:"POST",path:"/connect",handler:R=>D(R)},{method:"POST",path:"/_agent/create",handler:async R=>{let U=R;return{ok:!0,result:await f.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async R=>{let U=R;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let K=U;return await(K.groupFile?ih:rh)(K,{core:u,patToken:x,handshakeBase:_,ppeOverride:S})}catch(K){if(K instanceof k)return{ok:!1,code:K.code,message:K.message};throw K}}},{method:"POST",path:"/reload",handler:async R=>{let U=R?.agent_id,K=await u.reloadAgents(U);return j.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:K}),{ok:!0,recycled:K}}},{method:"POST",path:"/shutdown",handler:async()=>(j.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:Q}=await $.start();try{await Kx(t.libEntry,t)}catch(R){j.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(R)})}await u.start(),XS({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new Zn().detectAll(),await Vi(o),o.frameworksCache)}).catch(R=>j.warn("startup warmup error (ignored)",{err:String(R)})),Nl().then(async()=>{let{probeAcpVersion:R}=await Promise.resolve().then(()=>(on(),Ol));for(let U of["claude-code","codex"]){let K=await R(U);K&&j.info("acp wrapper version",{framework:U,version:K})}}).catch(R=>j.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(R)}));let se=null,oe={port:re,token:Q,core:u,ipc:$,shutdown(R){return se||(j.info("daemon shutdown",{reason:R}),se=(async()=>{v?.stop(),I?.stop(),await u.stop(R),await $.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",()=>S0()),process.on("unhandledRejection",R=>{j.error("unhandledRejection",{reason:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0})}),process.on("uncaughtException",R=>{j.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}
113
- `)}catch{}process.exit(1)}),j.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),e1({cliSpawned:process.env[as]==="1",readPatToken:()=>ta(t),connect:D}).catch(R=>j.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(R)})),oe}async function JS(t){return ms(t).length>0}function oa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Zx(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function ZS(t,e){let r=ms(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(un(),_s));for(let c of r){await o(c,t).catch(l=>j.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.deletedAt?(e.disconnectedAgents.add(c),j.info("agent marked deleted on startup",{agentId:c,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(c),j.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){j.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function YS(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(un(),_s)),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`);j.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let g=Xx(l),y={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(y),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}j.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new 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 XS(t){let e=t.logger??j;try{let r=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(r??{})})}catch(r){e.warn("framework detection failed (using cached)",{err:String(r)})}await ZS(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await aa(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await QS(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function aa(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(()=>(un(),_s));j.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){j.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),l+=1;continue}if(!f){l+=1;continue}if(f.deletedAt){j.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),l+=1;continue}if(f.disconnectedAt){j.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),l+=1;continue}try{j.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=Xx(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){j.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),l+=1}}return j.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,total:i.length}}async function QS(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 f0(o,t)).status==="refreshed"&&(i+=1)}catch(c){j.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&j.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function e1(t){let e=t.logger??j;if(t.cliSpawned)return"skipped-cli";let r=await t.readPatToken();return r?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:r}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function Xx(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ia();Re();import{readFile as Qx}from"node:fs/promises";var en=class{paths;constructor(e){this.paths=e??Y()}async probe(e=1e3){let r=await ca(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:n1(i)}}}async request(e){let r=await ca(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:t1(f)}}finally{clearTimeout(l)}}};async function ca(t){try{let[e,r]=await Promise.all([Qx(t.portFile,"utf8"),Qx(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 t1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function n1(t){return t instanceof Error?t.message:String(t)}Vt();ne();cr();import{spawn as r1}from"node:child_process";import{userInfo as tp}from"node:os";var Vd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",i1=new Set(["bash","zsh","sh","dash","ksh"]),ep=Je("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),s1=2e3;function o1(t,e=Vd){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(`
114
- `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.slice(u+1))}return c}function a1(){let t=(process.env.SHELL??"").trim()||(tp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return i1.has(e)?t:null}function c1(t){return new Promise(e=>{let r=`printf '%s' '${Vd}'; env; printf '%s' '${Vd}'`,i;try{i=r1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??tp().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"),ep),x=setTimeout(()=>{l("SIGKILL"),u(o.length>0?o:null)},ep+s1)})}async function Jd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=a1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??c1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=o1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Re();function Pn(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}}on();import{chmod as d1,copyFile as np,mkdir as ip,readFile as da,rename as rp,rm as Zd,stat as sp,writeFile as l1}from"node:fs/promises";import{homedir as mP}from"node:os";import{dirname as u1,join as Jr,resolve as Yd,sep as cs}from"node:path";import{fileURLToPath as f1}from"node:url";Vt();ne();Re();var Xd=H("dist-install");function h1(t){let e=f1(t),r=u1(e),i=`${cs}src${cs}`;if(r.includes(i)||r.endsWith(`${cs}src${cs}cli`))return null;let o=Yd(r,"index.js"),c=Yd(r,"..","package.json");return{dist:o,pkgJson:c}}async function el(t={}){let e=t.paths??Y(),r=h1(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 da(o,"utf8"));c=S.version??"unknown",l=S.dependencies??{}}catch(S){return Xd.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=ri.map(S=>`${S}@${l[S]??"latest"}`),f=await Ro(e.configFile)??{},x=f.libVersion,g=await da(e.libEntry).then(()=>!0).catch(()=>!1),y=x===c;if(y&&g&&await Qd(e))return{kind:"already-current",libVersion:c};if(!y||!g){await ip(e.libDir,{recursive:!0}),await np(i,e.libEntry),await np(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let S=Yd(e.libDir,"package.json"),_=`${JSON.stringify({type:"module"},null,2)}
115
- `;await da(S,"utf8").catch(()=>null)!==_&&await l1(S,_)}return(!y||!await Qd(e))&&await(t.installWrappers??x1)(e,u),f.libVersion=c,await Vi(f,e.configFile),Xd.info("dist installed",{libEntry:e.libEntry,fromVersion:x,toVersion:c}),y&&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 Qd(t){for(let e of ri){let r=Jr(t.libDir,"node_modules",...e.split("/"),"package.json");if(!await sp(r).then(o=>o.isFile()).catch(()=>!1))return!1}return!0}async function x1(t,e){await m1(t.installLock,async()=>{if(await Qd(t))return;let r=Math.random().toString(36).slice(2,10),i=`${t.libDir}${cs}.staging-${process.pid}-${r}`,o=Jr(i,"node_modules"),c=Jr(t.libDir,"node_modules");try{await ip(i,{recursive:!0}),await p1(e,i),await g1(o);let l=`${c}.trash-${r}`;await rp(c,l).catch(()=>{}),await rp(o,c),await Zd(l,{recursive:!0,force:!0}).catch(()=>{}),Xd.info("wrapper closure installed",{liveNm:c,specs:e})}finally{await Zd(i,{recursive:!0,force:!0}).catch(()=>{})}})}function p1(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=it("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 g1(t){for(let e of ri){let r=Jr(t,...e.split("/")),i=JSON.parse(await da(Jr(r,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let c=Jr(t,".bin",o),l=await sp(c);process.platform!=="win32"&&!(l.mode&73)&&await d1(c,l.mode|73).catch(()=>{})}}async function m1(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 Zd(t,{force:!0}).catch(()=>{})}}Da();ne();Re();import{closeSync as ap,fstatSync as cp,openSync as dp,readFileSync as w1,readSync as _1,readdirSync as y1,statSync as E1}from"node:fs";import{join as la}from"node:path";var b1=new Set(["debug","info","warn","error"]);function lp(t){let e=t,r=Pn(e,"--agent-id");e=r.rest;let i=Pn(e,"--date");e=i.rest;let o=Pn(e,"-n","--lines");e=o.rest;let c=Pn(e,"--level");e=c.rest;let l=Pn(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&&b1.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 v1(t,e){return t.agentId?la(Ze(t.agentId,e).logs,dr("agent",t.date)):la(e.bridgeLogsDir,dr("bridge",t.date))}function S1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function I1(t,e){let r;try{r=y1(t)}catch{return[]}let i=[];for(let o of r){let c=Ra(o,e);if(!c)continue;let l=0;try{l=E1(la(t,o)).size}catch{}i.push({file:la(t,o),date:c,size:l})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function up(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"&&!Tl(r,e.level))return!1}return!0}var op={debug:"90",info:"36",warn:"33",error:"31"},A1=new Set(["ts","level","module","msg"]);function k1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function fp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=k1(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&op[o]&&(c=`\x1B[${op[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])=>!A1.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${l} ${u}${f}`}function T1(t,e,r){let c=w1(t,"utf8").split(`
116
- `).filter(l=>l.length>0).filter(l=>up(l,{level:e.level,grep:e.grep}));for(let l of S1(c,e.lines))process.stdout.write(`${fp(l,{raw:e.raw,color:r})}
117
- `)}async function hp(t,e){let r=e.paths??Y(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?Ze(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=I1(l,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
111
+ `)}catch{}}let e=new ga({processTitle:jr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Ho(),s=i??{};ks({pid:process.pid}),j.info(i?"loaded bridge config":"initialized bridge config");let a=new ha(new ni),l=null,u=new $o({upstream:a,paths:t,bridgeConfig:s,sessionSpawner:async(C,G,W,se)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(C,G,W,se)}}),f=new Uo({paths:t,config:s,registry:u});l=f;let x,m,g=null,v={},w,b=null,I=null,A=null,R=new Mn;function P(C,G){return R.enqueue(()=>k(C,G))}function E(){I||(I=new wa({isConnected:()=>a.isConnected()&&!(b?.isLivenessLost()??!1),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:C=>{if(process.env[gs]==="1"){j.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}j.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),I.start()}async function k(C,G){let W=C,se=W?.privatecode;if(!se)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let ot=Ki(W.env),me=W.handshake_url,we=W.frontier_url,Ot=Up(W.env,me,we);if(A=W,!G?.force&&x===se&&m===Ot){let ve=await gA(t);return u.agents.size===0&&ve?(j.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ya(t,f).catch(Ce=>j.warn("connect-noop auto-revive error (ignored)",{err:String(Ce)}))):j.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let St=!!x&&x!==se,un=m!==void 0&&m!==Ot,Jt=St||un,fn=await ml({privatecode:se,...me?{endpoint:me}:{},ppeOverride:ot});if(Jt){j.warn("connect config switched, resetting agents",{pcChanged:St,envChanged:un,previousPc:x?_a(x):"",nextPc:_a(se)});for(let ve of[...u.agents.values()])await ve.dispose("connect config switch").catch(()=>{}),u.agents.delete(ve.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ni,"connect switch").catch(()=>{})}g=fn.deviceId,ks({deviceId:g,pid:process.pid}),Ul({patToken:se,env:W.env}).catch(ve=>j.warn("coze-cli setup error (ignored)",{err:String(ve)}));let di=new xs({handshake:fn,privatecode:se,...we?{urlOverride:we}:{},ppeOverride:ot,getPatTokenForAgent:ve=>u.agents.get(ve)?.patToken});return await a.swap(di,"connect"),x=se,m=Ot,v=ot,w=me,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),j.info("mock scenario set",{scenario:W.mock_scenario})),b||(b=new Zi({core:u,getDeviceId:()=>g??"",onTickEnd:()=>M.retryPending().catch(ve=>j.warn("detailSync.retryPending failed (ignored)",{err:String(ve)})),onAuthFailures:X})),b.start(),E(),Jt&&ya(t,f).catch(ve=>j.warn("post-connect-switch auto-revive error (ignored)",{err:String(ve)})),ps(se,t).catch(ve=>j.warn("writePatToken after /connect failed (ignored)",{err:String(ve)})),j.info("/connect: WS established",{deviceId:g}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async C=>f.createAgent(C.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let L={},B=new ko({agents:u.agents,publishSkillToMarketplace:async C=>{let G=u.agents.get(C.agentId)?.patToken??x;if(!G)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Lp({patToken:G,zip:C.zip,...C.skillId?{skillId:C.skillId}:{},skillName:C.skillName,...C.description?{description:C.description}:{},agentId:C.agentId,...C.accountId?{accountId:C.accountId}:{}},{handshakeBase:w,ppeOverride:v})},disposeAndMarkDisconnected:async(C,G)=>{let W=u.agents.get(C);if(W){await f.cleanupOpenclawSessionProviders(W).catch(ot=>j.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(ot)}));let se=!0;try{await W.dispose(`disconnect: ${G}`)}catch(ot){se=!1,j.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(ot)}),W.status="error"}se&&(W.status="disconnected",u.unregister(C),u.disconnectedAgents.add(C))}else u.disconnectedAgents.add(C)},disposeForDelete:async(C,G)=>{let W=u.agents.get(C);W&&(await f.cleanupOpenclawSessionProviders(W).catch(se=>j.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(se)})),await W.dispose(`delete: ${G}`).catch(se=>j.warn("dispose during delete failed (ignored)",{agentId:C,err:String(se)})),u.unregister(C)),u.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!L.ref)throw new Error("agent-detail-sync not initialized yet");await L.ref.syncOne(C)},cleanupOpenclawProviders:async C=>{await f.cleanupOpenclawSessionProviders(C)},openclawRepair:async(C,G)=>{await f.openclawRepair(C,G)},isRuntimePendingPermission:C=>u.hasPendingPermissionFor(C)});u.registerExtension("_agent/listSkills",C=>B.listSkills(C.params)),u.registerExtension("_agent/addSkills",C=>B.addSkills(C.params)),u.registerExtension("_agent/removeSkills",C=>B.removeSkills(C.params)),u.registerExtension("_agent/publishSkill",C=>B.publishSkill(C.params)),u.registerExtension("_agent/getFileTree",C=>B.getFileTree(C.params)),u.registerExtension("_agent/getFileContent",C=>B.getFileContent(C.params)),u.registerExtension("_agent/update",C=>B.updateAgent(C.params)),u.registerExtension("_agent/disconnect",C=>B.disconnectAgent(C.params)),u.registerExtension("_agent/switchModel",C=>B.switchModel(C.params)),u.registerExtension("_agent/reset",C=>B.resetAgent(C.params)),u.registerExtension("_agent/repair",C=>B.repairAgent(C.params)),u.registerExtension("_agent/delete",C=>B.deleteAgent(C.params)),u.registerExtension("_agent/upgrade",C=>B.upgradeBridge(C.params));let M=new Ns({paths:t,handlers:B,agentManager:f,sendDetail:C=>u.sendRequest("_agent/detail",C)});L.ref=M;let X=async C=>{await Promise.allSettled(C.map(async G=>{try{await B.disconnectAgent({agentId:G.agentId,reason:`auth_failure: code=${G.code} ${G.message}`}),j.info("agent disconnected due to auth failure from heartbeat response",{agentId:G.agentId,code:G.code,message:G.message})}catch(W){j.warn("disconnect during authFailure handling failed (ignored)",{agentId:G.agentId,err:String(W)})}}))};a.onConnect(({initial:C})=>{j.info("frontier upstream connected, triggering detail sync",{initial:C}),M.syncAll(C?"initial-connect":"reconnect").catch(G=>j.warn("detail sync top-level error (ignored)",{err:String(G)}))});let Z=new jo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=u.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[gs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:g??"",frameworksCache:s.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let G=C,W=G?.privatecode,se=G?.pairing_code;if(!W||!se)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ot=Ki(G.env),me=G.handshake_url,we=G.frontier_url,Ot=Up(G.env,me,we),St=!!x&&x!==W,un=m!==void 0&&m!==Ot,Jt=St||un,fn=await ml({privatecode:W,...me?{endpoint:me}:{},ppeOverride:ot});if(Jt){j.warn("pair config switched, resetting agents",{pcChanged:St,envChanged:un,previousPc:x?_a(x):"",nextPc:_a(W),previousEnvKey:m??"",nextEnvKey:Ot});for(let Ce of[...u.agents.values()])await Ce.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ce.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ni,"pair switch").catch(()=>{})}g=fn.deviceId,ks({deviceId:g,pid:process.pid}),Ul({patToken:W,env:G.env}).catch(Ce=>j.warn("coze-cli setup error (ignored)",{err:String(Ce)}));let di=new xs({handshake:fn,privatecode:W,...we?{urlOverride:we}:{},ppeOverride:ot,getPatTokenForAgent:Ce=>u.agents.get(Ce)?.patToken});await a.swap(di,"pair");try{let Ce=new ir;s.frameworksCache=await Ce.detectAll(),await rs(s),j.info("frameworks_cache refreshed before pair",{detected:Object.keys(s.frameworksCache)})}catch(Ce){j.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ce)})}let ve=Object.keys(s.frameworksCache??{});try{let Ce=await u.sendRequest("_agent/pair",{pairCode:se,patToken:W,frameworks:ve,_meta:{cozeDeviceId:g}});j.info("_agent/pair ok",{pairResult:Ce}),x=W,m=Ot,v=ot,w=me,G.mock_scenario!==void 0&&(u.setMockScenario(G.mock_scenario),j.info("mock scenario set",{scenario:G.mock_scenario})),ps(W,t).catch(Me=>j.warn("writePatToken after /pair failed (ignored)",{err:String(Me)})),b||(b=new Zi({core:u,getDeviceId:()=>g??"",onTickEnd:()=>M.retryPending().catch(Me=>j.warn("detailSync.retryPending failed (ignored)",{err:String(Me)})),onAuthFailures:X})),b.start(),E(),Jt&&ya(t,f).catch(Me=>j.warn("post-pair-switch auto-revive error (ignored)",{err:String(Me)}));let ur;return G.agent_id&&(ur=await wA(G.agent_id,t,f,Me=>u.sendRequest("_agent/detail",Me),W).catch(Me=>(j.error("--agent-id ensureAgent failed",{agentId:G.agent_id,err:String(Me)}),{ok:!1,agentId:G.agent_id??"",note:String(Me)}))),{ok:!0,note:"paired with cloud",...ur?{agent:ur}:{}}}catch(Ce){return j.error("_agent/pair failed",{err:String(Ce)}),{ok:!1,note:`pair failed: ${String(Ce)}`}}}},{method:"POST",path:"/connect",handler:C=>P(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let G=C;return{ok:!0,result:await f.createAgent(G)}}},{method:"POST",path:"/agent/send",handler:async C=>{let G=C;if(!G?.agentId||!G?.sessionId||!G?.kind||!G?.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 W=G;return await(W.groupFile?Vh:Kh)(W,{core:u,patToken:x,handshakeBase:w,ppeOverride:v})}catch(W){if(W instanceof T)return{ok:!1,code:W.code,message:W.message};throw W}}},{method:"POST",path:"/reload",handler:async C=>{let G=C?.agent_id,W=await u.reloadAgents(G);return j.info("IPC /reload: recycled agent subprocesses",{agentId:G??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>(j.info("IPC /shutdown received"),setImmediate(()=>{de.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ae,token:te}=await Z.start();try{await Np(t.libEntry,t)}catch(C){j.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await u.start(),_A({paths:t,core:u,agentManager:f,detectAll:async()=>(s.frameworksCache=await new ir().detectAll(),await rs(s),s.frameworksCache)}).catch(C=>j.warn("startup warmup error (ignored)",{err:String(C)})),Iu().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(pn(),vu));for(let G of["claude-code","codex"]){let W=await C(G);W&&j.info("acp wrapper version",{framework:G,version:W})}}).catch(C=>j.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let le=null,de={port:ae,token:te,core:u,ipc:Z,shutdown(C){return le||(j.info("daemon shutdown",{reason:C}),le=(async()=>{b?.stop(),I?.stop(),await u.stop(C),await Z.stop(),await e.release()})(),le)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{de.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>mh()),process.on("unhandledRejection",C=>{j.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{j.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
112
+ `)}catch{}process.exit(1)}),j.info("daemon ready",{port:ae,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(s.frameworksCache??{}),libVersion:s.libVersion??"dev"}),EA({cliSpawned:process.env[gs]==="1",readPatToken:()=>xa(t),connect:P}).catch(C=>j.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),de}async function gA(t){return Ds(t).length>0}function _a(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Up(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function mA(t,e){let n=Ds(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(wn(),Os));for(let a of n){await s(a,t).catch(l=>j.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(l)}));try{let l=await i(a,t);l?.deletedAt?(e.disconnectedAgents.add(a),j.info("agent marked deleted on startup",{agentId:a,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(a),j.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){j.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(l)})}}}async function wA(t,e,n,i,s){let{loadAgentConfig:a}=await Promise.resolve().then(()=>(wn(),Os)),l=await a(t,e);if(l){if(l.deletedAt)throw new T("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${l.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);j.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let m=qp(l),g={agentId:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...s?{patToken:s}:{},...m?{_meta:m}:{}};return await n.createAgent(g),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}j.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new T("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={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(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 _A(t){let e=t.logger??j;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 mA(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await ya(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await yA(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function ya(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(()=>(wn(),Os));j.info("auto-revive: scanning local agents on startup",{count:i.length});let a=0,l=0;for(let u of i){let f;try{f=await s(u,t)}catch(x){j.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),l+=1;continue}if(!f){l+=1;continue}if(f.deletedAt){j.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),l+=1;continue}if(f.disconnectedAt){j.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),l+=1;continue}try{j.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=qp(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}),a+=1}catch(x){j.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),l+=1}}return j.info("auto-revive: done",{revived:a,skipped:l,total:i.length}),{revived:a,skipped:l,total:i.length}}async function yA(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 ih(s,t)).status==="refreshed"&&(i+=1)}catch(a){j.warn("refresh builtin skills failed (skipping agent)",{agentId:s,err:String(a)})}return i>0&&j.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function EA(t){let e=t.logger??j;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 qp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ma();Be();import{readFile as Hp}from"node:fs/promises";var dn=class{paths;constructor(e){this.paths=e??ie()}async probe(e=1e3){let n=await Ea(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}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:vA(i)}}}async request(e){let n=await Ea(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 a=new AbortController,l=setTimeout(()=>a.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:a.signal}),f=await u.text();return{status:u.status,body:bA(f)}}finally{clearTimeout(l)}}};async function Ea(t){try{let[e,n]=await Promise.all([Hp(t.portFile,"utf8"),Hp(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 bA(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function vA(t){return t instanceof Error?t.message:String(t)}rn();oe();pr();import{spawn as SA}from"node:child_process";import{userInfo as jp}from"node:os";var md="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",IA=new Set(["bash","zsh","sh","dash","ksh"]),$p=Qe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),AA=2e3;function TA(t,e=md){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),a={};for(let l of s.split(`
113
+ `)){let u=l.indexOf("=");u<=0||(a[l.slice(0,u)]=l.slice(u+1))}return a}function RA(){let t=(process.env.SHELL??"").trim()||(jp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return IA.has(e)?t:null}function kA(t){return new Promise(e=>{let n=`printf '%s' '${md}'; env; printf '%s' '${md}'`,i;try{i=SA(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??jp().homedir}})}catch{e(null);return}let s="",a=!1,l=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{a||(a=!0,clearTimeout(f),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 f=setTimeout(()=>l("SIGTERM"),$p),x=setTimeout(()=>{l("SIGKILL"),u(s.length>0?s:null)},$p+AA)})}async function wd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=RA();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??kA)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let s=TA(i);return s==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:s}}Be();function zn(t,...e){let n=[],i;for(let s=0;s<t.length;s++){let a=t[s],l=!1;for(let u of e){if(a===u){i=t[s+1],s+=1,l=!0;break}if(a.startsWith(`${u}=`)){i=a.slice(u.length+1),l=!0;break}}l||n.push(a)}return{value:i,rest:n}}var Gd=Nt(Mm(),1);pn();import{chmod as BR,copyFile as Bm,mkdir as zm,readFile as vs,rename as Fm,rm as zd,stat as FR,writeFile as zR}from"node:fs/promises";import{homedir as NM}from"node:os";import{dirname as UR,join as si,resolve as Ud,sep as bs}from"node:path";import{fileURLToPath as GR}from"node:url";rn();oe();Be();var oi=$("dist-install");function qR(t){let e=GR(t),n=UR(e),i=`${bs}src${bs}`;if(n.includes(i)||n.endsWith(`${bs}src${bs}cli`))return null;let s=Ud(n,"index.js"),a=Ud(n,"..","package.json");return{dist:s,pkgJson:a}}async function qd(t={}){let e=t.paths??ie(),n=qR(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 a,l;try{let b=JSON.parse(await vs(s,"utf8"));a=b.version??"unknown",l=b.dependencies??{}}catch(b){return oi.warn("cannot read source package.json,skip dist install",{err:String(b)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(b)}`}}let u=Cs.map(b=>({name:b,spec:l[b]??"latest"})),f=u.map(({name:b,spec:I})=>`${b}@${I}`),x=await Ho(e.configFile)??{},m=x.libVersion,g=await vs(e.libEntry).then(()=>!0).catch(()=>!1),v=m===a,w=await Um(e,u);if(v&&g&&w)return{kind:"already-current",libVersion:a};if(!v||!g){await zm(e.libDir,{recursive:!0}),await Bm(i,e.libEntry),await Bm(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let b=Ud(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
114
+ `;await vs(b,"utf8").catch(()=>null)!==I&&await zR(b,I)}return w||(t.installWrappers?await t.installWrappers(e,f):await HR(e,f,u)),x.libVersion=a,await rs(x,e.configFile),oi.info("dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:a}),v&&g?{kind:"already-current",libVersion:a}:m?{kind:"version-changed",fromVersion:m,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function Um(t,e){for(let n of e){let i=si(t.libDir,"node_modules",...n.name.split("/"),"package.json"),s;try{s=JSON.parse(await vs(i,"utf8"))}catch(u){return oi.warn("wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(u)}),!1}let a=s.version;if(!a)return oi.warn("wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;let l=Gd.default.validRange(n.spec);if(l&&!Gd.default.satisfies(a,l))return oi.warn("wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!0}async function HR(t,e,n){await WR(t.installLock,async()=>{if(await Um(t,n))return;let i=Math.random().toString(36).slice(2,10),s=`${t.libDir}${bs}.staging-${process.pid}-${i}`,a=si(s,"node_modules"),l=si(t.libDir,"node_modules");try{await zm(s,{recursive:!0}),await $R(e,s),await jR(a);let u=`${l}.trash-${i}`;await Fm(l,u).catch(()=>{}),await Fm(a,l),await zd(u,{recursive:!0,force:!0}).catch(()=>{}),oi.info("wrapper closure installed",{liveNm:l,specs:e})}finally{await zd(s,{recursive:!0,force:!0}).catch(()=>{})}})}function $R(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,s)=>{let a=lt("npm",n,{stdio:["ignore","pipe","pipe"]}),l="";a.stderr?.on("data",f=>{l.length<8192&&(l+=f.toString("utf8"))});let u=setTimeout(()=>a.kill("SIGKILL"),18e4);a.once("error",f=>{clearTimeout(u),s(new Error(`spawn npm failed: ${String(f)}`))}),a.once("close",f=>{clearTimeout(u),f===0?i():s(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${l.trim().slice(0,2e3)}`))})})}async function jR(t){for(let e of Cs){let n=si(t,...e.split("/")),i=JSON.parse(await vs(si(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 a=si(t,".bin",s),l=await FR(a);process.platform!=="win32"&&!(l.mode&73)&&await BR(a,l.mode|73).catch(()=>{})}}async function WR(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(a=>setTimeout(a,500))}try{return await e()}finally{i&&await zd(t,{force:!0}).catch(()=>{})}}nc();oe();Be();import{closeSync as qm,fstatSync as Hm,openSync as $m,readFileSync as KR,readSync as VR,readdirSync as ZR,statSync as JR}from"node:fs";import{join as Oa}from"node:path";var YR=new Set(["debug","info","warn","error"]);function jm(t){let e=t,n=zn(e,"--agent-id");e=n.rest;let i=zn(e,"--date");e=i.rest;let s=zn(e,"-n","--lines");e=s.rest;let a=zn(e,"--level");e=a.rest;let l=zn(e,"--grep");e=l.rest;let u=s.value===void 0?200:Number(s.value),f=Number.isInteger(u)&&u>=0?u:200,x=a.value&&YR.has(a.value)?a.value:void 0,m={lines:f,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),l.value&&(m.grep=l.value),m}function XR(t,e){return t.agentId?Oa(et(t.agentId,e).logs,gr("agent",t.date)):Oa(e.bridgeLogsDir,gr("bridge",t.date))}function QR(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function ek(t,e){let n;try{n=ZR(t)}catch{return[]}let i=[];for(let s of n){let a=tc(s,e);if(!a)continue;let l=0;try{l=JR(Oa(t,s)).size}catch{}i.push({file:Oa(t,s),date:a,size:l})}return i.sort((s,a)=>a.date.localeCompare(s.date)),i}function Wm(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"&&!wu(n,e.level))return!1}return!0}var Gm={debug:"90",info:"36",warn:"33",error:"31"},tk=new Set(["ts","level","module","msg"]);function nk(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Km(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=nk(n.ts),s=typeof n.level=="string"?n.level:"",a=s.toUpperCase().padEnd(5);e.color&&Gm[s]&&(a=`\x1B[${Gm[s]}m${a}\x1B[0m`);let l=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",f=Object.entries(n).filter(([x])=>!tk.has(x)).map(([x,m])=>` ${x}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${a} ${l} ${u}${f}`}function rk(t,e,n){let a=KR(t,"utf8").split(`
115
+ `).filter(l=>l.length>0).filter(l=>Wm(l,{level:e.level,grep:e.grep}));for(let l of QR(a,e.lines))process.stdout.write(`${Km(l,{raw:e.raw,color:n})}
116
+ `)}async function Vm(t,e){let n=e.paths??ie(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?et(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=ek(l,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
118
117
  `),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
119
- `);return 0}let o=t.date??Ln(new Date),c=v1({agentId:t.agentId,date:o},r);try{T1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
118
+ `);return 0}let s=t.date??qn(new Date),a=XR({agentId:t.agentId,date:s},n);try{rk(a,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${a}
120
119
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
121
- (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
122
- `),1}return t.follow&&await D1(c,t,i),0}var C1=500;function R1(t){try{let e=dp(t,"r");try{return cp(e).size}finally{ap(e)}}catch{return 0}}async function D1(t,e,r){let i=R1(t),o="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let f=dp(t,"r");try{let x=cp(f).size;if(x>i){let g=Buffer.allocUnsafe(x-i),y=_1(f,g,0,g.length,i);u=g.subarray(0,y).toString("utf8"),i+=y}}finally{ap(f)}}catch{}if(u){let f=(o+u).split(`
123
- `);o=f.pop()??"";for(let x of f)x.length>0&&up(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${fp(x,{raw:e.raw,color:r})}
124
- `)}await new Promise(f=>setTimeout(f,C1))}}finally{process.off("SIGINT",l)}}import{basename as P1,resolve as O1}from"node:path";Re();var L1=9e4,N1={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 M1(t){return N1[t]??1}async function xp(t,e={}){let r=e.paths??Y();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 ok(a,t,i),0}var ik=500;function sk(t){try{let e=$m(t,"r");try{return Hm(e).size}finally{qm(e)}}catch{return 0}}async function ok(t,e,n){let i=sk(t),s="",a=!1,l=()=>{a=!0};process.on("SIGINT",l);try{for(;!a;){let u="";try{let f=$m(t,"r");try{let x=Hm(f).size;if(x>i){let m=Buffer.allocUnsafe(x-i),g=VR(f,m,0,m.length,i);u=m.subarray(0,g).toString("utf8"),i+=g}}finally{qm(f)}}catch{}if(u){let f=(s+u).split(`
122
+ `);s=f.pop()??"";for(let x of f)x.length>0&&Wm(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Km(x,{raw:e.raw,color:n})}
123
+ `)}await new Promise(f=>setTimeout(f,ik))}}finally{process.off("SIGINT",l)}}import{basename as ak,resolve as ck}from"node:path";Be();var lk=9e4,dk={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 uk(t){return dk[t]??1}async function Zm(t,e={}){let n=e.paths??ie();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>
125
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.
126
- `),3;let i=await ca(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.
127
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:O1(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},c;try{c=await B1(i,"/agent/send",o,L1)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
128
- `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
129
- `),M1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
130
- `);else{let l=t.name??P1(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})
131
- `)}else process.stdout.write(`Sent ${t.kind} ${l} (${F1(c.bytes)})
132
- `)}return 0}async function B1(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 F1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var vp=H("cli");function Ke(t,e){let{value:r,rest:i}=Pn(t,e);return{value:r,rest:i}}function ga(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
133
- `)}function cI(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:D}=Ke(e.slice(1),"--agent-id");return D?{mode:"reload",agentId:D}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return dI(e.slice(1));if(e[0]==="log")return{mode:"log",...lp(e.slice(1))};if(e[0]==="connect")return lI(e.slice(1));if(e.includes("--status"))return ga("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ga("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ga("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ga("--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}=Ke(r,"--pat-token");r=o;let{value:c,rest:l}=Ke(r,"--pair-code");r=l;let{value:u,rest:f}=Ke(r,"--env");r=f;let{value:x,rest:g}=Ke(r,"--handshake-url");r=g;let{value:y,rest:S}=Ke(r,"--frontier-url");r=S;let{value:_,rest:v}=Ke(r,"--mock-scenario");r=v;let{value:I}=Ke(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),y&&(T.frontierUrl=y),_&&(T.mockScenario=_),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function dI(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}=Ke(i,"--caption");i=c;let{value:l,rest:u}=Ke(i,"--name");i=u;let{value:f,rest:x}=Ke(i,"--agent-id");i=x;let{value:g,rest:y}=Ke(i,"--session-id");i=y;let{value:S,rest:_}=Ke(i,"--mime");i=_;let v=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),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function lI(t){let e=t,{value:r,rest:i}=Ke(e,"--pat-token");e=i;let{value:o,rest:c}=Ke(e,"--env");e=c;let{value:l,rest:u}=Ke(e,"--handshake-url");e=u;let{value:f,rest:x}=Ke(e,"--frontier-url");e=x;let{value:g,rest:y}=Ke(e,"--mock-scenario");e=y;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 uI=`
125
+ `),3;let i=await Ea(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:ck(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},a;try{a=await fk(i,"/agent/send",s,lk)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
127
+ `),4}if(!a.ok)return process.stderr.write(`Error: ${a.code}: ${a.message}
128
+ `),uk(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
129
+ `);else{let l=t.name??ak(s.path);if(t.groupFile){let u=a.uri.length>60?`${a.uri.slice(0,57)}...`:a.uri;process.stdout.write(`Sent group file ${l} (uri=${u})
130
+ `)}else process.stdout.write(`Sent ${t.kind} ${l} (${hk(a.bytes)})
131
+ `)}return 0}async function fk(t,e,n,i){let s=new AbortController,a=setTimeout(()=>s.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(n),signal:s.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(a)}}function hk(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var iw=$("cli");function Ve(t,e){let{value:n,rest:i}=zn(t,e);return{value:n,rest:i}}function Ua(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
132
+ `)}function Bk(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}=Ve(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 Fk(e.slice(1));if(e[0]==="log")return{mode:"log",...jm(e.slice(1))};if(e[0]==="connect")return zk(e.slice(1));if(e.includes("--status"))return Ua("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ua("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ua("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ua("--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}=Ve(n,"--pat-token");n=s;let{value:a,rest:l}=Ve(n,"--pair-code");n=l;let{value:u,rest:f}=Ve(n,"--env");n=f;let{value:x,rest:m}=Ve(n,"--handshake-url");n=m;let{value:g,rest:v}=Ve(n,"--frontier-url");n=v;let{value:w,rest:b}=Ve(n,"--mock-scenario");n=b;let{value:I}=Ve(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!a)return{mode:"help"};let R={mode:"pair",privatecode:i,pairingCode:a};return u&&(R.env=u),x&&(R.handshakeUrl=x),g&&(R.frontierUrl=g),w&&(R.mockScenario=w),I&&(R.agentId=I),A&&(R.skipRebuildEnv=!0),R}function Fk(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:a}=Ve(i,"--caption");i=a;let{value:l,rest:u}=Ve(i,"--name");i=u;let{value:f,rest:x}=Ve(i,"--agent-id");i=x;let{value:m,rest:g}=Ve(i,"--session-id");i=g;let{value:v,rest:w}=Ve(i,"--mime");i=w;let b=i.includes("--group-file");i=i.filter(R=>R!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return s&&(A.caption=s),l&&(A.name=l),f&&(A.agentId=f),m&&(A.sessionId=m),b&&(A.groupFile=!0),v&&(A.mimeType=v),A}function zk(t){let e=t,{value:n,rest:i}=Ve(e,"--pat-token");e=i;let{value:s,rest:a}=Ve(e,"--env");e=a;let{value:l,rest:u}=Ve(e,"--handshake-url");e=u;let{value:f,rest:x}=Ve(e,"--frontier-url");e=x;let{value:m,rest:g}=Ve(e,"--mock-scenario");e=g;let v=e.includes("--skip-rebuild-env"),w={mode:"connect"};return n&&(w.privatecode=n),s&&(w.env=s),l&&(w.handshakeUrl=l),f&&(w.frontierUrl=f),m&&(w.mockScenario=m),v&&(w.skipRebuildEnv=!0),w}var Uk=`
134
133
  coze-bridge - local bridge daemon for cloud Agent Service
135
134
 
136
135
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -211,57 +210,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
211
210
 
212
211
  Internal:
213
212
  <node> <entry> --daemon daemon mode (OS supervisor only)
214
- `.trimStart();async function Sp(t=process.argv,e={}){let r=cI(t);switch(r.mode){case"help":return process.stdout.write(uI),0;case"version":return process.stdout.write(`${Lt}
215
- `),0;case"daemon":{try{await Yx()}catch(i){return vp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return fI(e);case"stop":return Ap(e);case"reload":return pI(r.agentId,e);case"log":return hp(r,e);case"update":return hI(e);case"purge":return gI(e);case"service-install":return mI(e);case"service-uninstall":return wI(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),_I(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),yI(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return xp({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 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 fI(t){let e=t.paths??Y(),r=new en(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
216
- `),1;if(i.kind==="stale")return await Ip(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
217
- `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
218
- ${JSON.stringify(o.body,null,2)}
219
- `),0}async function Ap(t){let e=t.paths??Y(),r=new en(e),i=t.daemonSweep??(async()=>{let f=I0();return await A0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await ls(t),l=!1;if(c)try{await c.uninstall(),l=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
220
- `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(l?`coze-bridge: stopped
213
+ `.trimStart();async function sw(t=process.argv,e={}){let n=Bk(t);switch(n.mode){case"help":return process.stdout.write(Uk),0;case"version":return process.stdout.write(`${Ht}
214
+ `),0;case"daemon":{try{await Gp()}catch(i){return iw.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return Gk(e);case"stop":return aw(e);case"reload":return $k(n.agentId,e);case"log":return Vm(n,e);case"update":return qk(e);case"purge":return jk(e);case"service-install":return Wk(e);case"service-uninstall":return Kk(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),Vk(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),Zk(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return Zm({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 ow(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 Gk(t){let e=t.paths??ie(),n=new dn(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 ow(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 aw(t){let e=t.paths??ie(),n=new dn(e),i=t.daemonSweep??(async()=>{let f=wh();return await _h(f),f}),s=async()=>{t.skipProcessKill||await i(e)},a=await Is(t),l=!1;if(a)try{await a.uninstall(),l=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
219
+ `)}let u=await n.probe();if(u.kind==="not-running")return await s(),process.stdout.write(l?`coze-bridge: stopped
221
220
  `:`coze-bridge: not running
222
- `),0;if(u.kind==="stale")return await Ip(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
223
- `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
224
- `),0}catch(f){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
225
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
226
- `),1)}}async function hI(t){return await Ap(t),(t.spawnNpx??xI)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function xI(t){return new Promise(e=>{let r=it("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)}
227
- `),e(1)})})}async function pI(t,e){let r=new en(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
228
- `),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)
229
- `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
230
- `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
231
- `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
232
- `),1}}async function ls(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(()=>(Ep(),yp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function kp(t,e){let r=await e.probe();if(r.kind==="connected")return r;let i=t.spawnDaemon??Jx,o=t.waitTimeoutMs??15e3,c=t.sleep??bI,l=t.paths??Y(),u=await ls(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await bp(e,o,c);if(f.kind==="connected")return f;kt(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){kt(l.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}kt(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 EI(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)}
221
+ `),0;if(u.kind==="stale")return await ow(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(f){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(f)}
225
+ `),1)}}async function qk(t){return await aw(t),(t.spawnNpx??Hk)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function Hk(t){return new Promise(e=>{let n=lt("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 $k(t,e){let n=new dn(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 a=s.body.recycled??[];return t&&a.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
+ `):process.stdout.write(`coze-bridge: reloaded ${a.length} agent(s): ${a.join(", ")||"(none)"}
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 Is(t){if(t.supervisor){let a=t.supervisor,l={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:a.platform,install:u=>a.install(l,u),uninstall:()=>a.uninstall(l)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(nw(),tw)),i=e(),s=n();return{platform:i.platform,install:a=>i.install(s,a),uninstall:()=>i.uninstall(s)}}async function cw(t,e){let n=await e.probe();if(n.kind==="connected")return n;let i=t.spawnDaemon??zp,s=t.waitTimeoutMs??15e3,a=t.sleep??Yk,l=t.paths??ie(),u=await Is(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await rw(e,s,a);if(f.kind==="connected")return f;Mt(l.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:s})}catch(f){Mt(l.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}Mt(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 Jk(l.pidFile,a)}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)}
233
232
  `));return process.stdout.write(`coze-bridge: starting daemon...
234
- `),await i({paths:t.paths}),bp(e,o,c)}async function gI(t){let e=new en(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
233
+ `),await i({paths:t.paths}),rw(e,s,a)}async function jk(t){let e=new dn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
235
234
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
236
- `)}await new Promise(l=>setTimeout(l,500))}let i=await ls(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
235
+ `)}await new Promise(l=>setTimeout(l,500))}let i=await Is(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
237
236
  `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
238
- `)}let o=t.paths??Y(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
237
+ `)}let s=t.paths??ie(),{rm:a}=await import("node:fs/promises");try{await a(s.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${s.bridgeRoot}
239
238
  `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
240
239
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
241
- `),0}async function mI(t){let e=await ls(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
240
+ `),0}async function Wk(t){let e=await Is(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
242
241
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
243
- `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
244
- `),1}}async function wI(t){let e=await ls(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
245
- `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
246
- `),1}}async function Tp(t,e,r){if(e)return kt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(kt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(kt(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)
247
- `),kt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function _I(t,e,r,i={},o,c){let l=new en(r.paths),u=r.paths??Y(),f=await Tp(u,c,r.reconstructEnv??Jd);if(await od(u,f).catch(y=>kt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(y)})),!r.skipDistInstall){let y=await el({paths:r.paths});y.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${y.fromVersion} \u2192 ${y.toVersion}
248
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):y.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${y.libVersion}
249
- `)}let x=await kp(r,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
250
- `),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 y=await l.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(y.status===200&&y.body?.ok){let S=y.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 Kk(t){let e=await Is(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 lw(t,e,n){if(e)return Mt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(Mt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(Mt(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
+ `),Mt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function Vk(t,e,n,i={},s,a){let l=new dn(n.paths),u=n.paths??ie(),f=await lw(u,a,n.reconstructEnv??wd);if(await Pl(u,f).catch(g=>Mt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!n.skipDistInstall){let g=await qd({paths:n.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
247
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(w=>setTimeout(w,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
248
+ `)}let x=await cw(n,l);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 g=await l.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(g.status===200&&g.body?.ok){let v=g.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
251
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"
252
- `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(y.body)}
253
- `),1}catch(y){return process.stderr.write(`coze-bridge: pair failed: ${String(y)}
254
- `),1}}async function yI(t,e,r={},i){let o=e.paths??Y(),c=t??await ta(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 en(e.paths),u=await Tp(o,i,e.reconstructEnv??Jd);if(await od(o,u).catch(g=>kt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await el({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
255
- `),(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}
256
- `)}let f=await kp(e,l);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
257
- `),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"})
258
- `),t!==void 0&&await os(c,o).catch(y=>vp.warn("writePatToken after connect failed (ignored)",{err:String(y)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
259
- `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
260
- `),1}}async function bp(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 EI(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||!qi(u))return;await e(i)}}function bI(t){return new Promise(e=>setTimeout(e,t))}ne();function vI(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 Cp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=vI(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
261
- `),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(g.body)}
252
+ `),1}catch(g){return process.stderr.write(`coze-bridge: pair failed: ${String(g)}
253
+ `),1}}async function Zk(t,e,n={},i){let s=e.paths??ie(),a=t??await xa(s);if(!a)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 dn(e.paths),u=await lw(s,i,e.reconstructEnv??wd);if(await Pl(s,u).catch(m=>Mt(s.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await qd({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
254
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
255
+ `)}let f=await cw(e,l);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
256
+ `),1;let x={privatecode:a};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 l.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 ps(a,s).catch(g=>iw.warn("writePatToken after connect failed (ignored)",{err:String(g)})),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 rw(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 Jk(t,e,n=60,i=200){let{readFile:s}=await import("node:fs/promises");for(let a=0;a<n;a++){let l;try{l=await s(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!Qi(u))return;await e(i)}}function Yk(t){return new Promise(e=>setTimeout(e,t))}oe();function Xk(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 dw(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){let i=Xk(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
262
261
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
263
262
  npx -y coze-bridge@latest stop
264
263
  npx -y coze-bridge@latest connect
265
264
 
266
- `)}Cp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Al("warn");Sp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
265
+ `)}dw();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&gu("warn");sw(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
267
266
  `),process.exit(1)});