coze-bridge 0.2.7-alpha.13 → 0.2.7-alpha.15

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 +95 -94
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var Gg=Object.create;var Ra=Object.defineProperty;var jg=Object.getOwnPropertyDescriptor;var Wg=Object.getOwnPropertyNames;var Kg=Object.getPrototypeOf,$g=Object.prototype.hasOwnProperty;var fe=(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 et=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Da=(t,e)=>{for(var r in e)Ra(t,r,{get:e[r],enumerable:!0})},Vg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wg(e))!$g.call(t,o)&&o!==r&&Ra(t,o,{get:()=>e[o],enumerable:!(i=jg(e,o))||i.enumerable});return t};var Gt=(t,e,r)=>(r=t!=null?Gg(Kg(t)):{},Vg(e||!t||!t.__esModule?Ra(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=et(()=>{"use strict"});import{createWriteStream as Zg,mkdirSync as Jg,readdirSync as Yg,unlinkSync as Xg}from"node:fs";import{join as Pl}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 Pa(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function Qg(t,e,r){let i=c=>{let[d,u,h]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>r}function fs(t,e,r,i){let o;try{o=Yg(t)}catch{return}for(let c of o){let d=Pa(c,e);if(d&&Qg(d,r,i))try{Xg(Pl(t,c))}catch{}}}var ii,Oa=et(()=>{"use strict";ii=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{Jg(this.dir,{recursive:!0});let r=Zg(Pl(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&&fs(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 em,mkdirSync as tm}from"node:fs";import{join as nm}from"node:path";function Ll(t){let e=t.retentionDays??sm,r=t.clock??(()=>Ln(new Date));xs={bridgeSink:new ii(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ii(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();fs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])fs(t.agentLogsDir(o),"agent",i,e)}function om(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Nl(t){La=t}function Ml(t){return lr[La]<=lr[t]}function Bl(t,e){let r=lr[t];return r===void 0?!0:r>=lr[e]}function ps(t){Ol={...t}}function Fl(t){let e=(u,h=2)=>String(u).padStart(h,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),d=e(o%60);return`${Ln(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function nt(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Fl(new Date),level:e,module:r,msg:i,...o})}
11
- `;tm(t,{recursive:!0}),em(nm(t,dr("bridge",Ln(new Date))),c)}catch{}}function am(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function hs(t,e,r,i,o){if(lr[t]<lr[La])return;let c=`${JSON.stringify({ts:Fl(new Date),level:t,module:e,msg:r,...Ol,...i})}
12
- `;if(xs){let d=am(o,i),u=d?om(xs,d):xs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?im.write(c):rm.write(c)}function H(t,e){return{debug:(r,i)=>hs("debug",t,r,i,e),info:(r,i)=>hs("info",t,r,i,e),warn:(r,i)=>hs("warn",t,r,i,e),error:(r,i)=>hs("error",t,r,i,e),child:r=>H(`${t}.${r}`,e),forAgent:r=>H(t,r)}}var lr,La,rm,im,Ol,sm,xs,ne=et(()=>{"use strict";cr();Oa();lr={debug:10,info:20,warn:30,error:40},La=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),rm=process.stdout,im=process.stderr,Ol={},sm=Je("COZE_BRIDGE_LOG_RETENTION_DAYS",30),xs=null});var T,Ke=et(()=>{"use strict";T=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Hl={};Da(Hl,{ACP_WRAPPER_NPM_PACKAGES:()=>ms,_resetAcpInstallerForTests:()=>hm,_setBinaryPathCacheForTests:()=>xm,buildAcpSpawn:()=>si,ensureAcpInstalled:()=>fr,getAcpBinaryPath:()=>ws,pickWhichLine:()=>Ba,probeAcpVersion:()=>fm,resolveAcpCommand:()=>ql});import{readFileSync as zl}from"node:fs";import{createRequire as cm}from"node:module";import{dirname as dm,resolve as lm}from"node:path";function Ma(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Ba(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 um(t){let e=Ul.resolve(`${t.npmPackage}/package.json`),r=dm(e),i=JSON.parse(zl(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 lm(r,o)}async function fr(t,e){let r=Na[t];if(!r)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ur.get(t);if(i)return i;let o=Ma(t);if(o)return ur.set(t,o),gs.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let c=um(r);return ur.set(t,c),gs.info("acp wrapper resolved",{framework:t,binary:r.binary,path:c}),c}catch(c){throw gs.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 T("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
- `),{cause:c})}}async function fm(t){let e=Na[t];if(e)try{let r=Ul.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(zl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){gs.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function ws(t){return ur.get(t)}function ql(t,e){if(e)return e;let r=Ma(t);if(r)return r;let i=ws(t);if(!i)throw new T("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function si(t,e,r){if(e)return{command:e,args:[...r]};let i=Ma(t);if(i)return{command:i,args:[...r]};let o=ql(t);return{command:process.execPath,args:[o,...r]}}function hm(){ur.clear()}function xm(t,e){ur.set(t,e)}var gs,Na,ms,Ul,ur,cn=et(()=>{"use strict";Ke();ne();gs=H("agents.acp-installer"),Na={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ms=Object.values(Na).filter(t=>t!==void 0).map(t=>t.npmPackage),Ul=cm(import.meta.url),ur=new Map});import{chmod as gm,mkdir as mm,readFile as wm,rename as _m,rm as ym,writeFile as bm}from"node:fs/promises";import{dirname as Em}from"node:path";async function dn(t){try{let e=await wm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ln(t,e,r){await mm(Em(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await bm(i,e,{encoding:"utf8",mode:r?.mode}),await _m(i,t),r?.mode!==void 0&&await gm(t,r.mode)}catch(o){throw await ym(i,{force:!0}).catch(()=>{}),o}}async function un(t,e,r){await ln(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var fn=et(()=>{"use strict"});import{promises as Wl,readdirSync as vm}from"node:fs";import{homedir as Sm}from"node:os";import{sep as Im,join as Ce,resolve as Kl}from"node:path";function J(t){let e=t??Sm(),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 $e(t,e=J()){let r=Ce(e.agentsRoot,t);return{root:r,config:Ce(r,"config.json"),workspace:Ce(r,"workspace"),logs:Ce(r,"logs")}}function _s(t=J()){try{return vm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function oi(t,e){let r=await Wl.realpath(Kl(t)).catch(()=>null);if(!r)return!1;let i=await Wl.realpath(Kl(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=et(()=>{"use strict"});var bs={};Da(bs,{AGENT_CONFIG_FILE_MODE:()=>ys,enforceAgentConfigMode:()=>Tm,loadAgentConfig:()=>De,persistAgentSessions:()=>ai,persistAgentSkills:()=>ci,saveAgentConfig:()=>Fe});import{chmod as Am,stat as km}from"node:fs/promises";function De(t,e){return dn($e(t,e).config)}function Fe(t,e){return un($e(t.agentId,e).config,t,{mode:ys})}async function Tm(t,e){if(process.platform==="win32")return;let r=$e(t,e).config;try{let i=await km(r);if(!i.isFile())return;let o=i.mode&511;o!==ys&&(await Am(r,ys),$l.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;$l.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ai(t,e,r){let i=await De(t,r);i&&(i.sessions=Object.fromEntries(e),await Fe(i,r))}async function ci(t,e,r){let i=await De(t,r);i&&(i.skills=e,await Fe(i,r))}var $l,ys,hn=et(()=>{"use strict";fn();ne();Re();$l=H("agent-config"),ys=384});var Ua=ae((KI,Jl)=>{Jl.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 vs=ae(Xl=>{var Yl={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 Lm(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(Yl))Xl[t]=Lm(Yl[t])});var ru=ae((VI,nu)=>{var Nm=fe("fs"),Me=fe("path"),Ql=Ua(),Mm=vs(),Bm=typeof process=="object"&&process.platform==="win32",eu=t=>typeof t=="object"&&t!==null,tu=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 Se(t){this.sep=Me.sep,this.fs=Nm,eu(t)&&eu(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}nu.exports=Se;Se.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw Mm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Se.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var d=Me.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Se.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!r)return o(!1);c.fs.stat(t,function(u,h){if(d&&h.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(w,S){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):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)})})})})})};Se.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let h=Me.join(i,u),x=e.fs.statSync(h);(!o||o.test(h))&&d.push(Me.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(r(h,o,c)))}),d}return r(t,void 0,!0)};Se.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Me.join(t,u),r.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Me.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(g,w){if(g)return e(g);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};Se.prototype.getAttributes=function(){};Se.prototype.setAttributes=function(){};Se.crc32update=function(t,e){return tu[(t^e)&255]^t>>>8};Se.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Se.crc32update(r,t[i++]);return~r>>>0};Se.methodToString=function(t){switch(t){case Ql.STORED:return"STORED ("+t+")";case Ql.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Se.canonical=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.join(".",e)};Se.zipnamefix=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.posix.join(".",e)};Se.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]};Se.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)))};Se.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Se.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Se.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)};Se.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};Se.isWin=Bm;Se.crcTable=tu});var su=ae((ZI,iu)=>{var Fm=fe("path");iu.exports=function(t,{fs:e}){var r=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(o=e.statSync(r),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=Fm.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:r,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var au=ae((JI,ou)=>{ou.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=ae((YI,xr)=>{xr.exports=ru();xr.exports.Constants=Ua();xr.exports.Errors=vs();xr.exports.FileAttr=su();xr.exports.decoder=au()});var du=ae((XI,cu)=>{var xn=pr(),z=xn.Constants;cu.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,h=0,x=0,g=0,w=0,S=0,_=0,E=0;t|=xn.isWin?2560:768,r|=z.FLG_EFS;let I={extraLen:0},k=b=>Math.max(0,b)>>>0,C=b=>Math.max(0,b)&65535,P=b=>Math.max(0,b)&255;return o=xn.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return r},set flags(b){r=b},get flags_efs(){return(r&z.FLG_EFS)>0},set flags_efs(b){b?r|=z.FLG_EFS:r&=~z.FLG_EFS},get flags_desc(){return(r&z.FLG_DESC)>0},set flags_desc(b){b?r|=z.FLG_DESC:r&=~z.FLG_DESC},get method(){return i},set method(b){switch(b){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=b},get time(){return xn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=xn.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=k(b)},get timeHighByte(){return P(o>>>8)},get crc(){return c},set crc(b){c=k(b)},get compressedSize(){return d},set compressedSize(b){d=k(b)},get size(){return u},set size(b){u=k(b)},get fileNameLength(){return h},set fileNameLength(b){h=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return g},set commentLength(b){g=b},get diskNumStart(){return w},set diskNumStart(b){w=k(b)},get inAttr(){return S},set inAttr(b){S=k(b)},get attr(){return _},set attr(b){_=k(b)},get fileAttr(){return(_||0)>>16&4095},get offset(){return E},set offset(b){E=k(b)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+x+g},get realDataOffset(){return E+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var R=b.slice(E,E+z.LOCHDR);if(R.readUInt32LE(0)!==z.LOCSIG)throw xn.Errors.INVALID_LOC();I.version=R.readUInt16LE(z.LOCVER),I.flags=R.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=R.readUInt16LE(z.LOCHOW),I.time=R.readUInt32LE(z.LOCTIM),I.crc=R.readUInt32LE(z.LOCCRC),I.compressedSize=R.readUInt32LE(z.LOCSIZ),I.size=R.readUInt32LE(z.LOCLEN),I.fnameLen=R.readUInt16LE(z.LOCNAM),I.extraLen=R.readUInt16LE(z.LOCEXT);let O=E+z.LOCHDR+I.fnameLen,B=O+I.extraLen;return b.slice(O,B)},loadFromBinary:function(b){if(b.length!==z.CENHDR||b.readUInt32LE(0)!==z.CENSIG)throw xn.Errors.INVALID_CEN();t=b.readUInt16LE(z.CENVEM),e=b.readUInt16LE(z.CENVER),r=b.readUInt16LE(z.CENFLG),i=b.readUInt16LE(z.CENHOW),o=b.readUInt32LE(z.CENTIM),c=b.readUInt32LE(z.CENCRC),d=b.readUInt32LE(z.CENSIZ),u=b.readUInt32LE(z.CENLEN),h=b.readUInt16LE(z.CENNAM),x=b.readUInt16LE(z.CENEXT),g=b.readUInt16LE(z.CENCOM),w=b.readUInt16LE(z.CENDSK),S=b.readUInt16LE(z.CENATT),_=b.readUInt32LE(z.CENATX),E=b.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(z.LOCHDR);return b.writeUInt32LE(z.LOCSIG,0),b.writeUInt16LE(e,z.LOCVER),b.writeUInt16LE(r,z.LOCFLG),b.writeUInt16LE(i,z.LOCHOW),b.writeUInt32LE(o,z.LOCTIM),b.writeUInt32LE(c,z.LOCCRC),b.writeUInt32LE(d,z.LOCSIZ),b.writeUInt32LE(u,z.LOCLEN),b.writeUInt16LE(h,z.LOCNAM),b.writeUInt16LE(I.extraLen,z.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(z.CENHDR+h+x+g);return b.writeUInt32LE(z.CENSIG,0),b.writeUInt16LE(t,z.CENVEM),b.writeUInt16LE(e,z.CENVER),b.writeUInt16LE(r,z.CENFLG),b.writeUInt16LE(i,z.CENHOW),b.writeUInt32LE(o,z.CENTIM),b.writeUInt32LE(c,z.CENCRC),b.writeUInt32LE(d,z.CENSIZ),b.writeUInt32LE(u,z.CENLEN),b.writeUInt16LE(h,z.CENNAM),b.writeUInt16LE(x,z.CENEXT),b.writeUInt16LE(g,z.CENCOM),b.writeUInt16LE(w,z.CENDSK),b.writeUInt16LE(S,z.CENATT),b.writeUInt32LE(_,z.CENATX),b.writeUInt32LE(E,z.CENOFF),b},toJSON:function(){let b=function(R){return R+" bytes"};return{made:t,version:e,flags:r,method:xn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(g),diskNumStart:w,inAttr:S,attr:_,offset:E,centralHeaderSize:b(z.CENHDR+h+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var uu=ae((QI,lu)=>{var gr=pr(),be=gr.Constants;lu.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(d,u){let h=d.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ha=ae(qa=>{qa.EntryHeader=du();qa.MainHeader=uu()});var hu=ae((tA,fu)=>{fu.exports=function(t){var e=fe("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],d=0;o.on("data",function(u){c.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),h=0;u.fill(0);for(var x=0;x<c.length;x++){var g=c[x];g.copy(u,h),h+=g.length}i&&i(u)}),o.end(t)}}}});var pu=ae((nA,xu)=>{var zm=+(process.versions?process.versions.node:"").split(".")[0]||0;xu.exports=function(t,e){var r=fe("zlib");let i=zm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),d=[],u=0;c.on("data",function(h){d.push(h),u+=h.length}),c.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var g=0;g<d.length;g++){var w=d[g];w.copy(h,x),x+=w.length}o&&o(h)}),c.end(t)}}}});var yu=ae((rA,_u)=>{"use strict";var{randomFillSync:gu}=fe("crypto"),Um=vs(),qm=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}),wu=(t,e)=>Math.imul(t,e)>>>0,mu=(t,e)=>qm[(t^e)&255]^t>>>8,di=()=>typeof gu=="function"?gu(Buffer.alloc(12)):di.node();di.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 Ss={genSalt:di};function Is(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])}Is.prototype.updateKeys=function(t){let e=this.keys;return e[0]=mu(e[0],t),e[1]+=e[0]&255,e[1]=wu(e[1],134775813)+1,e[2]=mu(e[2],e[1]>>>24),t};Is.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return wu(t,t^1)>>8&255};function Hm(t){let e=new Is(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 Gm(t){let e=new Is(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let d=e.next();i[o++]=c^d,e.updateKeys(c)}return i}}function jm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Hm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Um.WRONG_PASSWORD();return i(t.slice(12))}function Wm(t){Buffer.isBuffer(t)&&t.length>=12?Ss.genSalt=function(){return t.slice(0,12)}:t==="node"?Ss.genSalt=di.node:Ss.genSalt=di}function Km(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Gm(r),c=Ss.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(c,d),o(t,d,12)}_u.exports={decrypt:jm,encrypt:Km,_salter:Wm}});var bu=ae(As=>{As.Deflater=hu();As.Inflater=pu();As.ZipCrypto=yu()});var ja=ae((sA,Eu)=>{var ce=pr(),$m=Ha(),Ie=ce.Constants,Ga=bu();Eu.exports=function(t,e){var r=new $m.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let g=t,w=typeof g.decoder=="object"?g.decoder:ce.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function _(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(b)!==r.localHeader.crc)return!1}else{let R={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==Ie.LOCSIG||e.readUInt32LE(O)==Ie.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Ie.EXTSIG)R.crc=e.readUInt32LE(O+Ie.EXTCRC),R.compressedSize=e.readUInt32LE(O+Ie.EXTSIZ),R.size=e.readUInt32LE(O+Ie.EXTLEN);else if(e.readUInt16LE(O+12)===19280)R.crc=e.readUInt32LE(O+Ie.EXTCRC-4),R.compressedSize=e.readUInt32LE(O+Ie.EXTSIZ-4),R.size=e.readUInt32LE(O+Ie.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==r.compressedSize||R.size!==r.size||R.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(b)!==R.crc)return!1}return!0}function E(b,R,O){if(typeof R>"u"&&typeof b=="string"&&(O=b,b=void 0),c)return b&&R&&R(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var B=S();if(B.length===0)return b&&R&&R(B),B;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ce.Errors.INVALID_PASS_PARAM();B=Ga.ZipCrypto.decrypt(B,r,O)}var M=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(B.copy(M),_(M))return b&&R&&R(M),M;throw b&&R&&R(M,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var Z=new Ga.Inflater(B,r.size);if(b)Z.inflateAsync(function(V){V.copy(V,0),R&&(_(V)?R(V):R(V,ce.Errors.BAD_CRC()))});else{if(Z.inflate(M).copy(M,0),!_(M))throw ce.Errors.BAD_CRC(`"${w.decode(i)}"`);return M}break;default:throw b&&R&&R(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(b,R){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&R&&R(S()),S();if(d.length&&!c){var O;switch(r.method){case ce.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(d.length),d.copy(O),b&&R&&R(O),O;default:case ce.Constants.DEFLATED:var B=new Ga.Deflater(d);if(b)B.deflateAsync(function(Z){O=Buffer.alloc(Z.length),r.compressedSize=Z.length,Z.copy(O),R&&R(O)});else{var M=B.deflate();return r.compressedSize=M.length,M}B=null;break}}else if(b&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function k(b,R){return ce.readBigUInt64LE(b,R)}function C(b){try{for(var R=0,O,B,M;R+4<b.length;)O=b.readUInt16LE(R),R+=2,B=b.readUInt16LE(R),R+=2,M=b.slice(R,R+B),R+=B,Ie.ID_ZIP64===O&&P(M)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(b){var R,O,B,M;b.length>=Ie.EF_ZIP64_SCOMP&&(R=k(b,Ie.EF_ZIP64_SUNCOMP),r.size===Ie.EF_ZIP64_OR_32&&(r.size=R)),b.length>=Ie.EF_ZIP64_RHO&&(O=k(b,Ie.EF_ZIP64_SCOMP),r.compressedSize===Ie.EF_ZIP64_OR_32&&(r.compressedSize=O)),b.length>=Ie.EF_ZIP64_DSN&&(B=k(b,Ie.EF_ZIP64_RHO),r.offset===Ie.EF_ZIP64_OR_32&&(r.offset=B)),b.length>=Ie.EF_ZIP64_DSN+4&&(M=b.readUInt32LE(Ie.EF_ZIP64_DSN),r.diskNumStart===Ie.EF_ZIP64_OR_16&&(r.diskNumStart=M))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=ce.toBuffer(b,w.encode);var R=i[i.length-1];c=R===47||R===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,C(b)},get comment(){return w.decode(o)},set comment(b){if(o=ce.toBuffer(b,w.encode),r.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var b=w.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){d=ce.toBuffer(b,ce.decoder.encode),!c&&d.length?(r.size=d.length,r.method=ce.Constants.DEFLATED,r.crc=ce.crc32(b),r.changed=!0):r.method=ce.Constants.STORED},getData:function(b){return r.changed?d:E(!1,null,b)},getDataAsync:function(b,R){r.changed?b(d):E(!0,b,R)},set attr(b){r.attr=b},get attr(){return r.attr},set header(b){r.loadFromBinary(b)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var b=r.centralHeaderToBinary(),R=ce.Constants.CENHDR;return i.copy(b,R),R+=i.length,u.copy(b,R),R+=r.extraLength,o.copy(b,R),b},packLocalHeader:function(){let b=0;r.flags_efs=this.efs,r.extraLocalLength=h.length;let R=r.localHeaderToBinary(),O=Buffer.alloc(R.length+i.length+r.extraLocalLength);return R.copy(O,b),b+=R.length,i.copy(O,b),b+=i.length,h.copy(O,b),b+=h.length,O},toJSON:function(){let b=function(R){return"<"+(R&&R.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:b(e),data:b(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Iu=ae((oA,Su)=>{var vu=ja(),Vm=Ha(),Ve=pr();Su.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Vm.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:g,decoder:w}=x;t?E(x.readEntries):d=!0;function S(){let k=new Set;for(let C of Object.keys(i)){let P=C.split("/");if(P.pop(),!!P.length)for(let b=0;b<P.length;b++){let R=P.slice(0,b+1).join("/")+"/";k.add(R)}}for(let C of k)if(!(C in i)){let P=new vu(x);P.entryName=C,P.attr=16,P.temporary=!0,r.push(P),i[P.entryName]=P,h.add(P)}}function _(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/Ve.Constants.CENHDR)throw Ve.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var k=c.offset,C=0;C<r.length;C++){var P=k,b=new vu(x,t);b.header=t.slice(P,P+=Ve.Constants.CENHDR),b.entryName=t.slice(P,P+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(P,P+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(P,P+b.header.commentLength)),k+=b.header.centralHeaderSize,r[C]=b,i[b.entryName]=b}h.clear(),S()}function E(k){var C=t.length-Ve.Constants.ENDHDR,P=Math.max(0,C-65535),b=P,R=t.length,O=-1,B=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),C;C>=b;C--)if(t[C]===80){if(t.readUInt32LE(C)===Ve.Constants.ENDSIG){O=C,B=C,R=C+Ve.Constants.ENDHDR,b=C-Ve.Constants.END64HDR;continue}if(t.readUInt32LE(C)===Ve.Constants.END64SIG){b=P;continue}if(t.readUInt32LE(C)===Ve.Constants.ZIP64SIG){O=C,R=C+Ve.readBigUInt64LE(t,C+Ve.Constants.ZIP64SIZE)+Ve.Constants.ZIP64LEAD;break}}if(O==-1)throw Ve.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,R)),c.commentLength&&(o=t.slice(B+Ve.Constants.ENDHDR)),k&&_()}function I(){r.length>1&&!g&&r.sort((k,C)=>k.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return d||_(),r.filter(k=>!h.has(k))},get comment(){return w.decode(o)},set comment(k){o=Ve.toBuffer(k,w.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(k){this.entries.forEach(k)},getEntry:function(k){return d||_(),i[k]||null},setEntry:function(k){d||_(),r.push(k),i[k.entryName]=k,c.totalEntries=r.length},deleteFile:function(k,C=!0){d||_();let P=i[k];this.getEntryChildren(P,C).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(k){d||_();let C=i[k],P=r.indexOf(C);P>=0&&(r.splice(P,1),delete i[k],c.totalEntries=r.length)},getEntryChildren:function(k,C=!0){if(d||_(),typeof k=="object")if(k.isDirectory&&C){let P=[],b=k.entryName;for(let R of r)R.entryName.startsWith(b)&&P.push(R);return P}else return[k];return[]},getChildCount:function(k){if(k&&k.isDirectory){let C=this.getEntryChildren(k);return C.includes(k)?C.length-1:C.length}return 0},compressToBuffer:function(){d||_(),I();let k=[],C=[],P=0,b=0;c.size=0,c.offset=0;let R=0;for(let M of this.entries){let Z=M.getCompressedData();M.header.offset=b;let V=M.packLocalHeader(),re=V.length+Z.length;b+=re,k.push(V),k.push(Z);let X=M.packCentralHeader();C.push(X),c.size+=X.length,P+=re+X.length,R++}P+=c.mainHeaderSize,c.offset=b,c.totalEntries=R,b=0;let O=Buffer.alloc(P);for(let M of k)M.copy(O,b),b+=M.length;for(let M of C)M.copy(O,b),b+=M.length;let B=c.toBinary();return o&&o.copy(B,Ve.Constants.ENDHDR),B.copy(O,b),t=O,d=!1,O},toAsyncBuffer:function(k,C,P,b){try{d||_(),I();let R=[],O=[],B=0,M=0,Z=0;c.size=0,c.offset=0;let V=function(re){if(re.length>0){let X=re.shift(),ee=X.entryName+X.extra.toString();P&&P(ee),X.getCompressedDataAsync(function(se){b&&b(ee),X.header.offset=M;let D=X.packLocalHeader(),U=D.length+se.length;M+=U,R.push(D),R.push(se);let W=X.packCentralHeader();O.push(W),c.size+=W.length,B+=U+W.length,Z++,V(re)})}else{B+=c.mainHeaderSize,c.offset=M,c.totalEntries=Z,M=0;let X=Buffer.alloc(B);R.forEach(function(se){se.copy(X,M),M+=se.length}),O.forEach(function(se){se.copy(X,M),M+=se.length});let ee=c.toBinary();o&&o.copy(ee,Ve.Constants.ENDHDR),ee.copy(X,M),t=X,d=!1,k(X)}};V(Array.from(this.entries))}catch(R){C(R)}}}}});var Tu=ae((aA,ku)=>{var ve=pr(),Ee=fe("path"),Zm=ja(),Jm=Iu(),Nn=(...t)=>ve.findLast(t,e=>typeof e=="boolean"),Au=(...t)=>ve.findLast(t,e=>typeof e=="string"),Ym=(...t)=>ve.findLast(t,e=>typeof e=="function"),Xm={noSort:!1,readEntries:!1,method:ve.Constants.NONE,fs:null};ku.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Xm);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=ve.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new ve(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=ve.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=ve.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw ve.Errors.INVALID_FILENAME();let c=new Jm(r,i),{canonical:d,sanitize:u,zipnamefix:h}=ve;function x(_){if(_&&c){var E;if(typeof _=="string"&&(E=c.getEntry(Ee.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(E=c.getEntry(_.entryName)),E)return E}return null}function g(_){let{join:E,normalize:I,sep:k}=Ee.posix;return E(Ee.isAbsolute(_)?"/":".",I(k+_.split("\\").join(k)+k))}function w(_){return _ instanceof RegExp?(function(E){return function(I){return E.test(I)}})(_):typeof _!="function"?()=>!0:_}let S=(_,E)=>{let I=E.slice(-1);return I=I===o.sep?o.sep:"",Ee.relative(_,E)+I};return{readFile:function(_,E){var I=x(_);return I&&I.getData(E)||null},childCount:function(_){let E=x(_);if(E)return c.getChildCount(E)},readFileAsync:function(_,E){var I=x(_);I?I.getDataAsync(E):E(null,"getEntry failed for:"+_)},readAsText:function(_,E){var I=x(_);if(I){var k=I.getData();if(k&&k.length)return k.toString(E||"utf8")}return""},readAsTextAsync:function(_,E,I){var k=x(_);k?k.getDataAsync(function(C,P){if(P){E(C,P);return}C&&C.length?E(C.toString(I||"utf8")):E("")}):E("")},deleteFile:function(_,E=!0){var I=x(_);I&&c.deleteFile(I.entryName,E)},deleteEntry:function(_){var E=x(_);E&&c.deleteEntry(E.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,E){var I=x(_);I&&(I.comment=E)},getZipEntryComment:function(_){var E=x(_);return E&&E.comment||""},updateFile:function(_,E){var I=x(_);I&&I.setData(E)},addLocalFile:function(_,E,I,k){if(o.fs.existsSync(_)){E=E?g(E):"";let C=Ee.win32.basename(Ee.win32.normalize(_));E+=I||C;let P=o.fs.statSync(_),b=P.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);P.isDirectory()&&(E+=o.sep),this.addFile(E,b,k,P)}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,E){_=typeof _=="object"?_:{localPath:_};let I=Ee.resolve(_.localPath),{comment:k}=_,{zipPath:C,zipName:P}=_,b=this;o.fs.stat(I,function(R,O){if(R)return E(R,!1);C=C?g(C):"";let B=Ee.win32.basename(Ee.win32.normalize(I));if(C+=P||B,O.isFile())o.fs.readFile(I,function(M,Z){return M?E(M,!1):(b.addFile(C,Z,k,O),setImmediate(E,void 0,!0))});else if(O.isDirectory())return C+=o.sep,b.addFile(C,Buffer.alloc(0),k,O),setImmediate(E,void 0,!0)})},addLocalFolder:function(_,E,I){if(I=w(I),E=E?g(E):"",_=Ee.normalize(_),o.fs.existsSync(_)){let k=o.findFiles(_),C=this;if(k.length)for(let P of k){let b=Ee.join(E,S(_,P));I(b)&&C.addLocalFile(P,Ee.dirname(b))}}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,E,I,k){k=w(k),I=I?g(I):"",_=Ee.normalize(_);var C=this;o.fs.open(_,"r",function(P){if(P&&P.code==="ENOENT")E(void 0,ve.Errors.FILE_NOT_FOUND(_));else if(P)E(void 0,P);else{var b=o.findFiles(_),R=-1,O=function(){if(R+=1,R<b.length){var B=b[R],M=S(_,B).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),k(M)?o.fs.stat(B,function(Z,V){Z&&E(void 0,Z),V.isFile()?o.fs.readFile(B,function(re,X){re?E(void 0,re):(C.addFile(I+M,X,"",V),O())}):(C.addFile(I+M+"/",Buffer.alloc(0),"",V),O())}):process.nextTick(()=>{O()})}else E(!0,void 0)};O()}})},addLocalFolderAsync2:function(_,E){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=Ee.resolve(g(_.localPath));let{zipPath:k,filter:C,namefix:P}=_;C instanceof RegExp?C=(function(O){return function(B){return O.test(B)}})(C):typeof C!="function"&&(C=function(){return!0}),k=k?g(k):"",P=="latin1"&&(P=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=O=>O);let b=O=>Ee.join(k,P(S(localPath,O))),R=O=>Ee.win32.basename(Ee.win32.normalize(P(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?E(void 0,ve.Errors.FILE_NOT_FOUND(localPath)):O?E(void 0,O):o.findFilesAsync(localPath,function(B,M){if(B)return E(B);M=M.filter(Z=>C(b(Z))),M.length||E(void 0,!1),setImmediate(M.reverse().reduce(function(Z,V){return function(re,X){if(re||X===!1)return setImmediate(Z,re,!1);I.addLocalFileAsync({localPath:V,zipPath:Ee.dirname(b(V)),zipName:R(V)},Z)}},E))})})},addLocalFolderPromise:function(_,E){return new Promise((I,k)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},E),(C,P)=>{C&&k(C),P&&I(this)})})},addFile:function(_,E,I,k){_=h(_);let C=x(_),P=C!=null;P||(C=new Zm(i),C.entryName=_),C.comment=I||"";let b=typeof k=="object"&&k instanceof o.fs.Stats;b&&(C.header.time=k.mtime);var R=C.isDirectory?16:0;let O=C.isDirectory?16384:32768;return b?O|=4095&k.mode:typeof k=="number"?O|=4095&k:O|=C.isDirectory?493:420,R=(R|O<<16)>>>0,C.attr=R,C.setData(E),P||c.setEntry(C),C},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,E,I,k,C,P){k=Nn(!1,k),C=Nn(!1,C),I=Nn(!0,I),P=Au(C,P);var b=x(_);if(!b)throw ve.Errors.NO_ENTRY();var R=d(b.entryName),O=u(E,P&&!b.isDirectory?P:I?R:Ee.basename(R));if(b.isDirectory){var B=c.getEntryChildren(b);return B.forEach(function(V){if(V.isDirectory)return;var re=V.getData();if(!re)throw ve.Errors.CANT_EXTRACT_FILE();var X=d(V.entryName),ee=u(E,I?X:Ee.basename(X));let se=C?V.header.fileAttr:void 0;o.writeFileTo(ee,re,k,se)}),!0}var M=b.getData(c.password);if(!M)throw ve.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!k)throw ve.Errors.CANT_OVERRIDE();let Z=C?_.header.fileAttr:void 0;return o.writeFileTo(O,M,k,Z),!0},test:function(_){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var I=c.entries[E].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,E,I,k){if(I=Nn(!1,I),k=Au(I,k),E=Nn(!1,E),!c)throw ve.Errors.NO_ZIP();c.entries.forEach(function(C){var P=u(_,d(C.entryName));if(C.isDirectory){o.makeDir(P);return}var b=C.getData(k);if(!b)throw ve.Errors.CANT_EXTRACT_FILE();let R=I?C.header.fileAttr:void 0;o.writeFileTo(P,b,E,R);try{o.fs.utimesSync(P,C.header.time,C.header.time)}catch{throw ve.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,E,I,k){if(k=Ym(E,I,k),I=Nn(!1,I),E=Nn(!1,E),!k)return new Promise((O,B)=>{this.extractAllToAsync(_,E,I,function(M){M?B(M):O(this)})});if(!c){k(ve.Errors.NO_ZIP());return}_=Ee.resolve(_);let C=O=>u(_,Ee.normalize(d(O.entryName))),P=(O,B)=>new Error(O+': "'+B+'"'),b=[],R=[];c.entries.forEach(O=>{O.isDirectory?b.push(O):R.push(O)});for(let O of b){let B=C(O),M=I?O.header.fileAttr:void 0;try{o.makeDir(B),M&&o.fs.chmodSync(B,M),o.fs.utimesSync(B,O.header.time,O.header.time)}catch{k(P("Unable to create folder",B))}}R.reverse().reduce(function(O,B){return function(M){if(M)O(M);else{let Z=Ee.normalize(d(B.entryName)),V=u(_,Z);B.getDataAsync(function(re,X){if(X)O(X);else if(!re)O(ve.Errors.CANT_EXTRACT_FILE());else{let ee=I?B.header.fileAttr:void 0;o.writeFileToAsync(V,re,E,ee,function(se){se||O(P("Unable to write file",V)),o.fs.utimes(V,B.header.time,B.header.time,function(D){D?O(P("Unable to set times",V)):O()})})}})}}},k)()},writeZip:function(_,E){if(arguments.length===1&&typeof _=="function"&&(E=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var k=o.writeFileTo(_,I,!0);typeof E=="function"&&E(k?null:new Error("failed"),"")}}},writeZipPromise:function(_,E){let{overwrite:I,perm:k}=Object.assign({overwrite:!0},E);return new Promise((C,P)=>{!_&&i.filename&&(_=i.filename),_||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let R=O=>O?C(O):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,b,I,k,R)},P)})},toBufferPromise:function(){return new Promise((_,E)=>{c.toAsyncBuffer(_,E)})},toBuffer:function(_,E,I,k){return typeof _=="function"?(c.toAsyncBuffer(_,E,I,k),null):c.compressToBuffer()}}}});import{execFile as oy,spawn as ay,spawnSync as Ik}from"node:child_process";import{promisify as cy}from"node:util";function ly(t){if(process.platform!=="win32")return!1;if(Jf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Jf,"").toLowerCase();return dy.has(r)}function Yf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return ly(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function it(t,e=[],r={}){return ay(t,e,Yf(t,r))}function Xf(t,e=[],r={}){return uy(t,e,Yf(t,r))}var dy,Jf,uy,Jt=et(()=>{"use strict";dy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Jf=/\.(cmd|bat|ps1)$/i;uy=cy(oy)});var Xt=ae((pD,Uh)=>{"use strict";var Fh=["nodebuffer","arraybuffer","fragments"],zh=typeof Blob<"u";zh&&Fh.push("blob");Uh.exports={BINARY_TYPES:Fh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:zh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Yi=ae((gD,Mo)=>{"use strict";var{EMPTY_BUFFER:xv}=Xt(),kd=Buffer[Symbol.species];function pv(t,e){if(t.length===0)return xv;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 kd(r.buffer,r.byteOffset,i):r}function qh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Hh(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function gv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Td(t){if(Td.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new kd(t):ArrayBuffer.isView(t)?e=new kd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Td.readOnly=!1),e}Mo.exports={concat:pv,mask:qh,toArrayBuffer:gv,toBuffer:Td,unmask:Hh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=fe("bufferutil");Mo.exports.mask=function(e,r,i,o,c){c<48?qh(e,r,i,o,c):t.mask(e,r,i,o,c)},Mo.exports.unmask=function(e,r){e.length<32?Hh(e,r):t.unmask(e,r)}}catch{}});var Wh=ae((mD,jh)=>{"use strict";var Gh=Symbol("kDone"),Cd=Symbol("kRun"),Rd=class{constructor(e){this[Gh]=()=>{this.pending--,this[Cd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Cd]()}[Cd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Gh])}}};jh.exports=Rd});var jr=ae((wD,Zh)=>{"use strict";var Xi=fe("zlib"),Kh=Yi(),mv=Wh(),{kStatusCode:$h}=Xt(),wv=Buffer[Symbol.species],_v=Buffer.from([0,0,255,255]),Fo=Symbol("permessage-deflate"),Qt=Symbol("total-length"),Hr=Symbol("callback"),Rn=Symbol("buffers"),Gr=Symbol("error"),Bo,Dd=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,!Bo){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Bo=new mv(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[Hr];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){Bo.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){Bo.add(o=>{this._compress(e,r,(c,d)=>{o(),i(c,d)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Xi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Xi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Fo]=this,this._inflate[Qt]=0,this._inflate[Rn]=[],this._inflate.on("error",bv),this._inflate.on("data",Vh)}this._inflate[Hr]=i,this._inflate.write(e),r&&this._inflate.write(_v),this._inflate.flush(()=>{let c=this._inflate[Gr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Kh.concat(this._inflate[Rn],this._inflate[Qt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Qt]=0,this._inflate[Rn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Xi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Xi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Qt]=0,this._deflate[Rn]=[],this._deflate.on("data",yv)}this._deflate[Hr]=i,this._deflate.write(e),this._deflate.flush(Xi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Kh.concat(this._deflate[Rn],this._deflate[Qt]);r&&(c=new wv(c.buffer,c.byteOffset,c.length-4)),this._deflate[Hr]=null,this._deflate[Qt]=0,this._deflate[Rn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Zh.exports=Dd;function yv(t){this[Rn].push(t),this[Qt]+=t.length}function Vh(t){if(this[Qt]+=t.length,this[Fo]._maxPayload<1||this[Qt]<=this[Fo]._maxPayload){this[Rn].push(t);return}this[Gr]=new RangeError("Max payload size exceeded"),this[Gr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Gr][$h]=1009,this.removeListener("data",Vh),this.reset()}function bv(t){if(this[Fo]._inflate=null,this[Gr]){this[Hr](this[Gr]);return}t[$h]=1007,this[Hr](t)}});var Wr=ae((_D,zo)=>{"use strict";var{isUtf8:Jh}=fe("buffer"),{hasBlob:Ev}=Xt(),vv=[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 Sv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Pd(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 Iv(t){return Ev&&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:Iv,isValidStatusCode:Sv,isValidUTF8:Pd,tokenChars:vv};if(Jh)zo.exports.isValidUTF8=function(t){return t.length<24?Pd(t):Jh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=fe("utf-8-validate");zo.exports.isValidUTF8=function(e){return e.length<32?Pd(e):t(e)}}catch{}});var Bd=ae((yD,rx)=>{"use strict";var{Writable:Av}=fe("stream"),Yh=jr(),{BINARY_TYPES:kv,EMPTY_BUFFER:Xh,kStatusCode:Tv,kWebSocket:Cv}=Xt(),{concat:Od,toArrayBuffer:Rv,unmask:Dv}=Yi(),{isValidStatusCode:Pv,isValidUTF8:Qh}=Wr(),Uo=Buffer[Symbol.species],ht=0,ex=1,tx=2,nx=3,Ld=4,Nd=5,qo=6,Md=class extends Av{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||kv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Cv]=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 Uo(i.buffer,i.byteOffset+e,i.length-e),new Uo(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 Uo(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 ex:this.getPayloadLength16(e);break;case tx:this.getPayloadLength64(e);break;case nx:this.getMask();break;case Ld:this.getData(e);break;case Nd:case qo: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[Yh.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=ex:this._payloadLength===127?this._state=tx: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=nx:this._state=Ld}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ld}getData(e){let r=Xh;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&&Dv(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Nd,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Yh.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return r(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(d);return}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=Od(i,r):this._binaryType==="arraybuffer"?o=Rv(Od(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=ht):(this._state=qo,setImmediate(()=>{this.emit("message",o,!0),this._state=ht,this.startLoop(e)}))}else{let o=Od(i,r);if(!this._skipUTF8Validation&&!Qh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Nd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=ht):(this._state=qo,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,Xh),this.end();else{let i=e.readUInt16BE(0);if(!Pv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Uo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Qh(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=qo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ht,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(d,this.createError),d.code=c,d[Tv]=o,d}};rx.exports=Md});var Ud=ae((ED,ox)=>{"use strict";var{Duplex:bD}=fe("stream"),{randomFillSync:Ov}=fe("crypto"),ix=jr(),{EMPTY_BUFFER:Lv,kWebSocket:Nv,NOOP:Mv}=Xt(),{isBlob:Kr,isValidStatusCode:Bv}=Wr(),{mask:sx,toBuffer:Xn}=Yi(),xt=Symbol("kByteLength"),Fv=Buffer.alloc(4),Ho=8*1024,Qn,$r=Ho,vt=0,zv=1,Uv=2,Fd=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=vt,this.onerror=Mv,this[Nv]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||Fv,r.generateMask?r.generateMask(i):($r===Ho&&(Qn===void 0&&(Qn=Buffer.alloc(Ho)),Ov(Qn,0,Ho),$r=0),i[0]=Qn[$r++],i[1]=Qn[$r++],i[2]=Qn[$r++],i[3]=Qn[$r++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[xt]!==void 0?u=r[xt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let h=u;u>=65536?(c+=8,h=127):u>125&&(c+=2,h=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]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),r.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],d?[x,e]:o?(sx(e,i,x,c,u),[x]):(sx(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=Lv;else{if(typeof e!="number"||!Bv(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 d={[xt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==vt?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Kr(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 d={[xt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Kr(e)?this._state!==vt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==vt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Kr(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 d={[xt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Kr(e)?this._state!==vt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==vt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[ix.extensionName],c=r.binary?2:1,d=r.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):Kr(e)?(u=e.size,h=!1):(e=Xn(e),u=e.length,h=Xn.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,c=0),r.fin&&(this._firstFragment=!0);let x={[xt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:d};Kr(e)?this._state!==vt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==vt?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=Uv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(zd,this,u,o);return}this._bufferedBytes-=i[xt];let d=Xn(c);r?this.dispatch(d,r,i,o):(this._state=vt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(qv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[ix.extensionName];this._bufferedBytes+=i[xt],this._state=zv,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");zd(this,h,o);return}this._bufferedBytes-=i[xt],this._state=vt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===vt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][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)}};ox.exports=Fd;function zd(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 qv(t,e,r){zd(t,e,r),t.onerror(e)}});var px=ae((vD,xx)=>{"use strict";var{kForOnEventAttribute:Qi,kListener:qd}=Xt(),ax=Symbol("kCode"),cx=Symbol("kData"),dx=Symbol("kError"),lx=Symbol("kMessage"),ux=Symbol("kReason"),Vr=Symbol("kTarget"),fx=Symbol("kType"),hx=Symbol("kWasClean"),en=class{constructor(e){this[Vr]=null,this[fx]=e}get target(){return this[Vr]}get type(){return this[fx]}};Object.defineProperty(en.prototype,"target",{enumerable:!0});Object.defineProperty(en.prototype,"type",{enumerable:!0});var er=class extends en{constructor(e,r={}){super(e),this[ax]=r.code===void 0?0:r.code,this[ux]=r.reason===void 0?"":r.reason,this[hx]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[ax]}get reason(){return this[ux]}get wasClean(){return this[hx]}};Object.defineProperty(er.prototype,"code",{enumerable:!0});Object.defineProperty(er.prototype,"reason",{enumerable:!0});Object.defineProperty(er.prototype,"wasClean",{enumerable:!0});var Zr=class extends en{constructor(e,r={}){super(e),this[dx]=r.error===void 0?null:r.error,this[lx]=r.message===void 0?"":r.message}get error(){return this[dx]}get message(){return this[lx]}};Object.defineProperty(Zr.prototype,"error",{enumerable:!0});Object.defineProperty(Zr.prototype,"message",{enumerable:!0});var es=class extends en{constructor(e,r={}){super(e),this[cx]=r.data===void 0?null:r.data}get data(){return this[cx]}};Object.defineProperty(es.prototype,"data",{enumerable:!0});var Hv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Qi]&&o[qd]===e&&!o[Qi])return;let i;if(t==="message")i=function(c,d){let u=new es("message",{data:d?c:c.toString()});u[Vr]=this,Go(e,this,u)};else if(t==="close")i=function(c,d){let u=new er("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Vr]=this,Go(e,this,u)};else if(t==="error")i=function(c){let d=new Zr("error",{error:c,message:c.message});d[Vr]=this,Go(e,this,d)};else if(t==="open")i=function(){let c=new en("open");c[Vr]=this,Go(e,this,c)};else return;i[Qi]=!!r[Qi],i[qd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[qd]===e&&!r[Qi]){this.removeListener(t,r);break}}};xx.exports={CloseEvent:er,ErrorEvent:Zr,Event:en,EventTarget:Hv,MessageEvent:es};function Go(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var jo=ae((SD,gx)=>{"use strict";var{tokenChars:ts}=Wr();function Ft(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Gv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,h=-1,x=-1,g=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(g===-1&&ts[x]===1)h===-1&&(h=w);else if(w!==0&&(x===32||x===9))g===-1&&h!==-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let _=t.slice(h,g);x===44?(Ft(e,_,r),r=Object.create(null)):d=_,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(g===-1&&ts[x]===1)h===-1&&(h=w);else if(x===32||x===9)g===-1&&h!==-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w),Ft(r,t.slice(h,g),!0),x===44&&(Ft(e,d,r),r=Object.create(null),d=void 0),h=g=-1}else if(x===61&&h!==-1&&g===-1)u=t.slice(h,w),h=g=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(ts[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);h===-1?h=w:i||(i=!0),o=!1}else if(c)if(ts[x]===1)h===-1&&(h=w);else if(x===34&&h!==-1)c=!1,g=w;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)c=!0;else if(g===-1&&ts[x]===1)h===-1&&(h=w);else if(h!==-1&&(x===32||x===9))g===-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let _=t.slice(h,g);i&&(_=_.replace(/\\/g,""),i=!1),Ft(r,u,_),x===44&&(Ft(e,d,r),r=Object.create(null),d=void 0),u=void 0,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=w);let S=t.slice(h,g);return d===void 0?Ft(e,S,r):(u===void 0?Ft(r,S,!0):i?Ft(r,u,S.replace(/\\/g,"")):Ft(r,u,S),Ft(e,d,r)),e}function jv(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}gx.exports={format:jv,parse:Gv}});var Vo=ae((kD,Cx)=>{"use strict";var Wv=fe("events"),Kv=fe("https"),$v=fe("http"),yx=fe("net"),Vv=fe("tls"),{randomBytes:Zv,createHash:Jv}=fe("crypto"),{Duplex:ID,Readable:AD}=fe("stream"),{URL:Hd}=fe("url"),Dn=jr(),Yv=Bd(),Xv=Ud(),{isBlob:Qv}=Wr(),{BINARY_TYPES:mx,CLOSE_TIMEOUT:eS,EMPTY_BUFFER:Wo,GUID:tS,kForOnEventAttribute:Gd,kListener:nS,kStatusCode:rS,kWebSocket:Ge,NOOP:bx}=Xt(),{EventTarget:{addEventListener:iS,removeEventListener:sS}}=px(),{format:oS,parse:aS}=jo(),{toBuffer:cS}=Yi(),Ex=Symbol("kAborted"),jd=[8,13],tn=["CONNECTING","OPEN","CLOSING","CLOSED"],dS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends Wv{constructor(e,r,i){super(),this._binaryType=mx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Wo,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]),vx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){mx.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 Yv({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new Xv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[Ge]=this,c[Ge]=this,e[Ge]=this,o.on("conclude",fS),o.on("drain",hS),o.on("error",xS),o.on("message",pS),o.on("ping",gS),o.on("pong",mS),c.onerror=wS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Ax),e.on("data",$o),e.on("end",kx),e.on("error",Tx),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())}),Ix(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){Wd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Wo,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){Wd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Wo,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){Wd(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||Wo,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(we,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(we.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(we.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Gd])return e[nS];return null},set(e){for(let r of this.listeners(t))if(r[Gd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Gd]:!0})}})});we.prototype.addEventListener=iS;we.prototype.removeEventListener=sS;Cx.exports=we;function vx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:eS,protocolVersion:jd[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,!jd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${jd.join(", ")})`);let c;if(e instanceof Hd)c=e;else try{c=new Hd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let d=c.protocol==="wss:",u=c.protocol==="ws+unix:",h;if(c.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?h="The URL's pathname is empty":c.hash&&(h="The URL contains a fragment identifier"),h){let I=new SyntaxError(h);if(t._redirects===0)throw I;Ko(t,I);return}let x=d?443:80,g=Zv(16).toString("base64"),w=d?Kv.request:$v.request,S=new Set,_;if(o.createConnection=o.createConnection||(d?uS:lS),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"]=oS({[Dn.extensionName]:_.offer()})),r.length){for(let I of r){if(typeof I!="string"||!dS.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 E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[k,C]of Object.entries(I))i.headers[k.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=w(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=w(o);o.timeout&&E.on("timeout",()=>{ct(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[Ex]||(E=t._req=null,Ko(t,I))}),E.on("response",I=>{let k=I.headers.location,C=I.statusCode;if(k&&o.followRedirects&&C>=300&&C<400){if(++t._redirects>o.maxRedirects){ct(t,E,"Maximum redirects exceeded");return}E.abort();let P;try{P=new Hd(k,e)}catch{let R=new SyntaxError(`Invalid URL: ${k}`);Ko(t,R);return}vx(t,P,r,i)}else t.emit("unexpected-response",E,I)||ct(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,k,C)=>{if(t.emit("upgrade",I),t.readyState!==we.CONNECTING)return;E=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){ct(t,k,"Invalid Upgrade header");return}let b=Jv("sha1").update(g+tS).digest("base64");if(I.headers["sec-websocket-accept"]!==b){ct(t,k,"Invalid Sec-WebSocket-Accept header");return}let R=I.headers["sec-websocket-protocol"],O;if(R!==void 0?S.size?S.has(R)||(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,k,O);return}R&&(t._protocol=R);let B=I.headers["sec-websocket-extensions"];if(B!==void 0){if(!_){ct(t,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=aS(B)}catch{ct(t,k,"Invalid Sec-WebSocket-Extensions header");return}let Z=Object.keys(M);if(Z.length!==1||Z[0]!==Dn.extensionName){ct(t,k,"Server indicated an extension that was not requested");return}try{_.accept(M[Dn.extensionName])}catch{ct(t,k,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Dn.extensionName]=_}t.setSocket(k,C,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,t):E.end()}function Ko(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function lS(t){return t.path=t.socketPath,yx.connect(t)}function uS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=yx.isIP(t.host)?"":t.host),Vv.connect(t)}function ct(t,e,r){t._readyState=we.CLOSING;let i=new Error(r);Error.captureStackTrace(i,ct),e.setHeader?(e[Ex]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ko,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Wd(t,e,r){if(e){let i=Qv(e)?e.size:cS(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${tn[t.readyState]})`);process.nextTick(r,i)}}function fS(t,e){let r=this[Ge];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Ge]!==void 0&&(r._socket.removeListener("data",$o),process.nextTick(Sx,r._socket),t===1005?r.close():r.close(t,e))}function hS(){let t=this[Ge];t.isPaused||t._socket.resume()}function xS(t){let e=this[Ge];e._socket[Ge]!==void 0&&(e._socket.removeListener("data",$o),process.nextTick(Sx,e._socket),e.close(t[rS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function _x(){this[Ge].emitClose()}function pS(t,e){this[Ge].emit("message",t,e)}function gS(t){let e=this[Ge];e._autoPong&&e.pong(t,!this._isServer,bx),e.emit("ping",t)}function mS(t){this[Ge].emit("pong",t)}function Sx(t){t.resume()}function wS(t){let e=this[Ge];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,Ix(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ix(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ax(){let t=this[Ge];if(this.removeListener("close",Ax),this.removeListener("data",$o),this.removeListener("end",kx),t._readyState=we.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Ge]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",_x),t._receiver.on("finish",_x))}function $o(t){this[Ge]._receiver.write(t)||this.pause()}function kx(){let t=this[Ge];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function Tx(){let t=this[Ge];this.removeListener("error",Tx),this.on("error",bx),t&&(t._readyState=we.CLOSING,this.destroy())}});var Ox=ae((CD,Px)=>{"use strict";var TD=Vo(),{Duplex:_S}=fe("stream");function Rx(t){t.emit("close")}function yS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Dx(t){this.removeListener("error",Dx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function bS(t,e){let r=!0,i=new _S({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,d){let u=!d&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(Rx,i);return}let d=!1;t.once("error",function(h){d=!0,c(h)}),t.once("close",function(){d||c(o),process.nextTick(Rx,i)}),r&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,d)});return}t.send(o,d)},i.on("end",yS),i.on("error",Dx),i}Px.exports=bS});var Kd=ae((RD,Lx)=>{"use strict";var{tokenChars:ES}=Wr();function vS(t){let e=new Set,r=-1,i=-1,o=0;for(o;o<t.length;o++){let d=t.charCodeAt(o);if(i===-1&&ES[d]===1)r===-1&&(r=o);else if(o!==0&&(d===32||d===9))i===-1&&r!==-1&&(i=o);else if(d===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(r,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(r,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}Lx.exports={parse:vS}});var qx=ae((PD,Ux)=>{"use strict";var SS=fe("events"),Zo=fe("http"),{Duplex:DD}=fe("stream"),{createHash:IS}=fe("crypto"),Nx=jo(),tr=jr(),AS=Kd(),kS=Vo(),{CLOSE_TIMEOUT:TS,GUID:CS,kWebSocket:RS}=Xt(),DS=/^[+/0-9A-Za-z]{22}==$/,Mx=0,Bx=1,zx=2,$d=class extends SS{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:TS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:kS,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Zo.createServer((i,o)=>{let c=Zo.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=PS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,d)=>{this.handleUpgrade(o,c,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Mx}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===zx){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!==Bx)if(this._state=Bx,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",Fx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){nr(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){nr(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!DS.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 h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=AS.parse(h)}catch{nr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&g!==void 0){let S=new tr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Nx.parse(g);_[tr.extensionName]&&(S.accept(_[tr.extensionName]),w[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,(_,E,I,k)=>{if(!_)return rs(r,E||401,I,k);this.completeUpgrade(w,c,x,e,r,i,o)});return}if(!this.options.verifyClient(S))return rs(r,401)}this.completeUpgrade(w,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[RS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Mx)return rs(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${IS("sha1").update(r+CS).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),g._protocol=w)}if(e[tr.extensionName]){let w=e[tr.extensionName].params,S=Nx.format({[tr.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
8
+ var Vg=Object.create;var Na=Object.defineProperty;var Zg=Object.getOwnPropertyDescriptor;var Yg=Object.getOwnPropertyNames;var Jg=Object.getPrototypeOf,Xg=Object.prototype.hasOwnProperty;var xe=(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 nt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ma=(t,e)=>{for(var n in e)Na(t,n,{get:e[n],enumerable:!0})},Qg=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Yg(e))!Xg.call(t,o)&&o!==n&&Na(t,o,{get:()=>e[o],enumerable:!(i=Zg(e,o))||i.enumerable});return t};var qt=(t,e,n)=>(n=t!=null?Vg(Jg(t)):{},Qg(e||!t||!t.__esModule?Na(n,"default",{value:t,enumerable:!0}):n,t));function Je(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ur=nt(()=>{"use strict"});import{createWriteStream as em,mkdirSync as tm,readdirSync as nm,unlinkSync as rm}from"node:fs";import{join as Nl}from"node:path";function Bn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function fr(t,e){return`${t}-${e}.log`}function Ba(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function im(t,e,n){let i=c=>{let[d,u,f]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>n}function ws(t,e,n,i){let o;try{o=nm(t)}catch{return}for(let c of o){let d=Ba(c,e);if(d&&im(d,n,i))try{rm(Nl(t,c))}catch{}}}var ci,Fa=nt(()=>{"use strict";ci=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Bn(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{tm(this.dir,{recursive:!0});let n=em(Nl(this.dir,fr(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&&ws(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 sm,mkdirSync as om}from"node:fs";import{join as am}from"node:path";function Bl(t){let e=t.retentionDays??lm,n=t.clock??(()=>Bn(new Date));ys={bridgeSink:new ci(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new ci(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();ws(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])ws(t.agentLogsDir(o),"agent",i,e)}function um(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Fl(t){za=t}function zl(t){return hr[za]<=hr[t]}function Ul(t,e){let n=hr[t];return n===void 0?!0:n>=hr[e]}function bs(t){Ml={...t}}function Gl(t){let e=(u,f=2)=>String(u).padStart(f,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",o=Math.abs(n),c=e(Math.floor(o/60)),d=e(o%60);return`${Bn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function rt(t,e,n,i,o){try{let c=`${JSON.stringify({ts:Gl(new Date),level:e,module:n,msg:i,...o})}
11
+ `;om(t,{recursive:!0}),sm(am(t,fr("bridge",Bn(new Date))),c)}catch{}}function fm(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function _s(t,e,n,i,o){if(hr[t]<hr[za])return;let c=`${JSON.stringify({ts:Gl(new Date),level:t,module:e,msg:n,...Ml,...i})}
12
+ `;if(ys){let d=fm(o,i),u=d?um(ys,d):ys.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?dm.write(c):cm.write(c)}function H(t,e){return{debug:(n,i)=>_s("debug",t,n,i,e),info:(n,i)=>_s("info",t,n,i,e),warn:(n,i)=>_s("warn",t,n,i,e),error:(n,i)=>_s("error",t,n,i,e),child:n=>H(`${t}.${n}`,e),forAgent:n=>H(t,n)}}var hr,za,cm,dm,Ml,lm,ys,ie=nt(()=>{"use strict";ur();Fa();hr={debug:10,info:20,warn:30,error:40},za=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),cm=process.stdout,dm=process.stderr,Ml={},lm=Je("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ys=null});var k,Ve=nt(()=>{"use strict";k=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 Wl={};Ma(Wl,{ACP_WRAPPER_NPM_PACKAGES:()=>vs,_resetAcpInstallerForTests:()=>wm,_setBinaryPathCacheForTests:()=>_m,buildAcpSpawn:()=>di,ensureAcpInstalled:()=>pr,getAcpBinaryPath:()=>Ss,pickWhichLine:()=>Ha,probeAcpVersion:()=>mm,resolveAcpCommand:()=>jl});import{readFileSync as Hl}from"node:fs";import{createRequire as hm}from"node:module";import{dirname as xm,resolve as pm}from"node:path";function Ga(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Ha(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(o=>o.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function gm(t){let e=ql.resolve(`${t.npmPackage}/package.json`),n=xm(e),i=JSON.parse(Hl(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 pm(n,o)}async function pr(t,e){let n=Ua[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=xr.get(t);if(i)return i;let o=Ga(t);if(o)return xr.set(t,o),Es.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let c=gm(n);return xr.set(t,c),Es.info("acp wrapper resolved",{framework:t,binary:n.binary,path:c}),c}catch(c){throw Es.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(c)}),new k("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:c})}}async function mm(t){let e=Ua[t];if(e)try{let n=ql.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Hl(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Es.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function Ss(t){return xr.get(t)}function jl(t,e){if(e)return e;let n=Ga(t);if(n)return n;let i=Ss(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 di(t,e,n){if(e)return{command:e,args:[...n]};let i=Ga(t);if(i)return{command:i,args:[...n]};let o=jl(t);return{command:process.execPath,args:[o,...n]}}function wm(){xr.clear()}function _m(t,e){xr.set(t,e)}var Es,Ua,vs,ql,xr,ln=nt(()=>{"use strict";Ve();ie();Es=H("agents.acp-installer"),Ua={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},vs=Object.values(Ua).filter(t=>t!==void 0).map(t=>t.npmPackage),ql=hm(import.meta.url),xr=new Map});import{chmod as bm,mkdir as Em,readFile as vm,rename as Sm,rm as Im,writeFile as Am}from"node:fs/promises";import{dirname as km}from"node:path";async function un(t){try{let e=await vm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function fn(t,e,n){await Em(km(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Am(i,e,{encoding:"utf8",mode:n?.mode}),await Sm(i,t),n?.mode!==void 0&&await bm(t,n.mode)}catch(o){throw await Im(i,{force:!0}).catch(()=>{}),o}}async function hn(t,e,n){await fn(t,`${JSON.stringify(e,null,2)}
14
+ `,n)}var xn=nt(()=>{"use strict"});import{promises as Vl,readdirSync as Tm}from"node:fs";import{homedir as Cm}from"node:os";import{sep as Rm,join as Re,resolve as Zl}from"node:path";function J(t){let e=t??Cm(),n=Re(e,".coze"),i=Re(n,"bridge"),o=Re(i,"lib"),c=Re(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:Re(o,"index.js"),binDir:Re(i,"bin"),pidFile:Re(i,"bridge.pid"),portFile:Re(i,"bridge.port"),tokenFile:Re(i,"bridge.token"),patTokenFile:Re(i,"pat-token"),agentEnvFile:Re(i,"agent-env.json"),logFile:Re(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Re(c,"daemon-stdio.log"),installLock:Re(i,"install.lock"),configFile:Re(i,"config.json"),agentsRoot:Re(n,"agents")}}function Ue(t,e=J()){let n=Re(e.agentsRoot,t);return{root:n,config:Re(n,"config.json"),workspace:Re(n,"workspace"),logs:Re(n,"logs")}}function Is(t=J()){try{return Tm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function li(t,e){let n=await Vl.realpath(Zl(t)).catch(()=>null);if(!n)return!1;let i=await Vl.realpath(Zl(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?n.toLowerCase():n,c=process.platform==="win32"?i.toLowerCase():i;return o===c||o.startsWith(c+Rm)}var De=nt(()=>{"use strict"});var ks={};Ma(ks,{AGENT_CONFIG_FILE_MODE:()=>As,enforceAgentConfigMode:()=>Om,loadAgentConfig:()=>Pe,persistAgentSessions:()=>ui,persistAgentSkills:()=>fi,saveAgentConfig:()=>Ge});import{chmod as Dm,stat as Pm}from"node:fs/promises";function Pe(t,e){return un(Ue(t,e).config)}function Ge(t,e){return hn(Ue(t.agentId,e).config,t,{mode:As})}async function Om(t,e){if(process.platform==="win32")return;let n=Ue(t,e).config;try{let i=await Pm(n);if(!i.isFile())return;let o=i.mode&511;o!==As&&(await Dm(n,As),Yl.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Yl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function ui(t,e,n){let i=await Pe(t,n);i&&(i.sessions=Object.fromEntries(e),await Ge(i,n))}async function fi(t,e,n){let i=await Pe(t,n);i&&(i.skills=e,await Ge(i,n))}var Yl,As,pn=nt(()=>{"use strict";xn();ie();De();Yl=H("agent-config"),As=384});var Wa=ce((iA,Ql)=>{Ql.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 Cs=ce(tu=>{var eu={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 zm(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(eu))tu[t]=zm(eu[t])});var ou=ce((oA,su)=>{var Um=xe("fs"),Be=xe("path"),nu=Wa(),Gm=Cs(),Hm=typeof process=="object"&&process.platform==="win32",ru=t=>typeof t=="object"&&t!==null,iu=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 Ie(t){this.sep=Be.sep,this.fs=Um,ru(t)&&ru(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}su.exports=Ie;Ie.prototype.makeDir=function(t){let e=this;function n(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw Gm.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};Ie.prototype.writeFileTo=function(t,e,n,i){let o=this;if(o.fs.existsSync(t)){if(!n)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var d=Be.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ie.prototype.writeFileToAsync=function(t,e,n,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!n)return o(!1);c.fs.stat(t,function(u,f){if(d&&f.isDirectory())return o(!1);var x=Be.dirname(t);c.fs.exists(x,function(p){p||c.makeDir(x),c.fs.open(t,"w",438,function(w,S){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):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 n(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let f=Be.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&d.push(Be.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(n(f,o,c)))}),d}return n(t,void 0,!0)};Ie.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(o,c){if(o)return e(o);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Be.join(t,u),n.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Be.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(p,w){if(p)return e(p);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};Ie.prototype.getAttributes=function(){};Ie.prototype.setAttributes=function(){};Ie.crc32update=function(t,e){return iu[(t^e)&255]^t>>>8};Ie.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Ie.crc32update(n,t[i++]);return~n>>>0};Ie.methodToString=function(t){switch(t){case nu.STORED:return"STORED ("+t+")";case nu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ie.canonical=function(t){if(!t)return"";let e=Be.posix.normalize("/"+t.split("\\").join("/"));return Be.join(".",e)};Ie.zipnamefix=function(t){if(!t)return"";let e=Be.posix.normalize("/"+t.split("\\").join("/"));return Be.posix.join(".",e)};Ie.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]};Ie.sanitize=function(t,e){t=Be.resolve(Be.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var c=Be.normalize(Be.join(t,n.slice(i,o).join(Be.sep)));if(c.indexOf(t)===0)return c}return Be.normalize(Be.join(t,Be.basename(e)))};Ie.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Ie.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};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,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};Ie.isWin=Hm;Ie.crcTable=iu});var cu=ce((aA,au)=>{var qm=xe("path");au.exports=function(t,{fs:e}){var n=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(o=e.statSync(n),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=qm.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 lu=ce((cA,du)=>{du.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var wr=ce((dA,mr)=>{mr.exports=ou();mr.exports.Constants=Wa();mr.exports.Errors=Cs();mr.exports.FileAttr=cu();mr.exports.decoder=lu()});var fu=ce((lA,uu)=>{var gn=wr(),z=gn.Constants;uu.exports=function(){var t=20,e=10,n=0,i=0,o=0,c=0,d=0,u=0,f=0,x=0,p=0,w=0,S=0,_=0,E=0;t|=gn.isWin?2560:768,n|=z.FLG_EFS;let I={extraLen:0},A=y=>Math.max(0,y)>>>0,T=y=>Math.max(0,y)&65535,P=y=>Math.max(0,y)&255;return o=gn.fromDate2DOS(new Date),{get made(){return t},set made(y){t=y},get version(){return e},set version(y){e=y},get flags(){return n},set flags(y){n=y},get flags_efs(){return(n&z.FLG_EFS)>0},set flags_efs(y){y?n|=z.FLG_EFS:n&=~z.FLG_EFS},get flags_desc(){return(n&z.FLG_DESC)>0},set flags_desc(y){y?n|=z.FLG_DESC:n&=~z.FLG_DESC},get method(){return i},set method(y){switch(y){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=y},get time(){return gn.fromDOS2Date(this.timeval)},set time(y){y=new Date(y),this.timeval=gn.fromDate2DOS(y)},get timeval(){return o},set timeval(y){o=A(y)},get timeHighByte(){return P(o>>>8)},get crc(){return c},set crc(y){c=A(y)},get compressedSize(){return d},set compressedSize(y){d=A(y)},get size(){return u},set size(y){u=A(y)},get fileNameLength(){return f},set fileNameLength(y){f=y},get extraLength(){return x},set extraLength(y){x=y},get extraLocalLength(){return I.extraLen},set extraLocalLength(y){I.extraLen=y},get commentLength(){return p},set commentLength(y){p=y},get diskNumStart(){return w},set diskNumStart(y){w=A(y)},get inAttr(){return S},set inAttr(y){S=A(y)},get attr(){return _},set attr(y){_=A(y)},get fileAttr(){return(_||0)>>16&4095},get offset(){return E},set offset(y){E=A(y)},get encrypted(){return(n&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+f+x+p},get realDataOffset(){return E+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(y){var R=y.slice(E,E+z.LOCHDR);if(R.readUInt32LE(0)!==z.LOCSIG)throw gn.Errors.INVALID_LOC();I.version=R.readUInt16LE(z.LOCVER),I.flags=R.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=R.readUInt16LE(z.LOCHOW),I.time=R.readUInt32LE(z.LOCTIM),I.crc=R.readUInt32LE(z.LOCCRC),I.compressedSize=R.readUInt32LE(z.LOCSIZ),I.size=R.readUInt32LE(z.LOCLEN),I.fnameLen=R.readUInt16LE(z.LOCNAM),I.extraLen=R.readUInt16LE(z.LOCEXT);let O=E+z.LOCHDR+I.fnameLen,F=O+I.extraLen;return y.slice(O,F)},loadFromBinary:function(y){if(y.length!==z.CENHDR||y.readUInt32LE(0)!==z.CENSIG)throw gn.Errors.INVALID_CEN();t=y.readUInt16LE(z.CENVEM),e=y.readUInt16LE(z.CENVER),n=y.readUInt16LE(z.CENFLG),i=y.readUInt16LE(z.CENHOW),o=y.readUInt32LE(z.CENTIM),c=y.readUInt32LE(z.CENCRC),d=y.readUInt32LE(z.CENSIZ),u=y.readUInt32LE(z.CENLEN),f=y.readUInt16LE(z.CENNAM),x=y.readUInt16LE(z.CENEXT),p=y.readUInt16LE(z.CENCOM),w=y.readUInt16LE(z.CENDSK),S=y.readUInt16LE(z.CENATT),_=y.readUInt32LE(z.CENATX),E=y.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var y=Buffer.alloc(z.LOCHDR);return y.writeUInt32LE(z.LOCSIG,0),y.writeUInt16LE(e,z.LOCVER),y.writeUInt16LE(n,z.LOCFLG),y.writeUInt16LE(i,z.LOCHOW),y.writeUInt32LE(o,z.LOCTIM),y.writeUInt32LE(c,z.LOCCRC),y.writeUInt32LE(d,z.LOCSIZ),y.writeUInt32LE(u,z.LOCLEN),y.writeUInt16LE(f,z.LOCNAM),y.writeUInt16LE(I.extraLen,z.LOCEXT),y},centralHeaderToBinary:function(){var y=Buffer.alloc(z.CENHDR+f+x+p);return y.writeUInt32LE(z.CENSIG,0),y.writeUInt16LE(t,z.CENVEM),y.writeUInt16LE(e,z.CENVER),y.writeUInt16LE(n,z.CENFLG),y.writeUInt16LE(i,z.CENHOW),y.writeUInt32LE(o,z.CENTIM),y.writeUInt32LE(c,z.CENCRC),y.writeUInt32LE(d,z.CENSIZ),y.writeUInt32LE(u,z.CENLEN),y.writeUInt16LE(f,z.CENNAM),y.writeUInt16LE(x,z.CENEXT),y.writeUInt16LE(p,z.CENCOM),y.writeUInt16LE(w,z.CENDSK),y.writeUInt16LE(S,z.CENATT),y.writeUInt32LE(_,z.CENATX),y.writeUInt32LE(E,z.CENOFF),y},toJSON:function(){let y=function(R){return R+" bytes"};return{made:t,version:e,flags:n,method:gn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:y(d),size:y(u),fileNameLength:y(f),extraLength:y(x),commentLength:y(p),diskNumStart:w,inAttr:S,attr:_,offset:E,centralHeaderSize:y(z.CENHDR+f+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var xu=ce((uA,hu)=>{var _r=wr(),Ee=_r.Constants;hu.exports=function(){var t=0,e=0,n=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 n},set size(c){n=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return Ee.ENDHDR+o},loadFromBinary:function(c){if((c.length!==Ee.ENDHDR||c.readUInt32LE(0)!==Ee.ENDSIG)&&(c.length<Ee.ZIP64HDR||c.readUInt32LE(0)!==Ee.ZIP64SIG))throw _r.Errors.INVALID_END();c.readUInt32LE(0)===Ee.ENDSIG?(t=c.readUInt16LE(Ee.ENDSUB),e=c.readUInt16LE(Ee.ENDTOT),n=c.readUInt32LE(Ee.ENDSIZ),i=c.readUInt32LE(Ee.ENDOFF),o=c.readUInt16LE(Ee.ENDCOM)):(t=_r.readBigUInt64LE(c,Ee.ZIP64SUB),e=_r.readBigUInt64LE(c,Ee.ZIP64TOT),n=_r.readBigUInt64LE(c,Ee.ZIP64SIZE),i=_r.readBigUInt64LE(c,Ee.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(Ee.ENDHDR+o);return c.writeUInt32LE(Ee.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,Ee.ENDSUB),c.writeUInt16LE(e,Ee.ENDTOT),c.writeUInt32LE(n,Ee.ENDSIZ),c.writeUInt32LE(i,Ee.ENDOFF),c.writeUInt16LE(o,Ee.ENDCOM),c.fill(" ",Ee.ENDHDR),c},toJSON:function(){let c=function(d,u){let f=d.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var $a=ce(Ka=>{Ka.EntryHeader=fu();Ka.MainHeader=xu()});var gu=ce((hA,pu)=>{pu.exports=function(t){var e=xe("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var o=e.createDeflateRaw(n),c=[],d=0;o.on("data",function(u){c.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),f=0;u.fill(0);for(var x=0;x<c.length;x++){var p=c[x];p.copy(u,f),f+=p.length}i&&i(u)}),o.end(t)}}}});var wu=ce((xA,mu)=>{var jm=+(process.versions?process.versions.node:"").split(".")[0]||0;mu.exports=function(t,e){var n=xe("zlib");let i=jm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var c=n.createInflateRaw(i),d=[],u=0;c.on("data",function(f){d.push(f),u+=f.length}),c.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var p=0;p<d.length;p++){var w=d[p];w.copy(f,x),x+=w.length}o&&o(f)}),c.end(t)}}}});var vu=ce((pA,Eu)=>{"use strict";var{randomFillSync:_u}=xe("crypto"),Wm=Cs(),Km=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}),bu=(t,e)=>Math.imul(t,e)>>>0,yu=(t,e)=>Km[(t^e)&255]^t>>>8,hi=()=>typeof _u=="function"?_u(Buffer.alloc(12)):hi.node();hi.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 Rs={genSalt:hi};function Ds(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])}Ds.prototype.updateKeys=function(t){let e=this.keys;return e[0]=yu(e[0],t),e[1]+=e[0]&255,e[1]=bu(e[1],134775813)+1,e[2]=yu(e[2],e[1]>>>24),t};Ds.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return bu(t,t^1)>>8&255};function $m(t){let e=new Ds(t);return function(n){let i=Buffer.alloc(n.length),o=0;for(let c of n)i[o++]=e.updateKeys(c^e.next());return i}}function Vm(t){let e=new Ds(t);return function(n,i,o=0){i||(i=Buffer.alloc(n.length));for(let c of n){let d=e.next();i[o++]=c^d,e.updateKeys(c)}return i}}function Zm(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=$m(n),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Wm.WRONG_PASSWORD();return i(t.slice(12))}function Ym(t){Buffer.isBuffer(t)&&t.length>=12?Rs.genSalt=function(){return t.slice(0,12)}:t==="node"?Rs.genSalt=hi.node:Rs.genSalt=hi}function Jm(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Vm(n),c=Rs.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(c,d),o(t,d,12)}Eu.exports={decrypt:Zm,encrypt:Jm,_salter:Ym}});var Su=ce(Ps=>{Ps.Deflater=gu();Ps.Inflater=wu();Ps.ZipCrypto=vu()});var Za=ce((mA,Iu)=>{var de=wr(),Xm=$a(),Ae=de.Constants,Va=Su();Iu.exports=function(t,e){var n=new Xm.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let p=t,w=typeof p.decoder=="object"?p.decoder:de.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(y){if(!n.flags_desc&&!n.localHeader.flags_desc){if(de.crc32(y)!==n.localHeader.crc)return!1}else{let R={},O=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(O)==Ae.LOCSIG||e.readUInt32LE(O)==Ae.CENSIG)throw de.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Ae.EXTSIG)R.crc=e.readUInt32LE(O+Ae.EXTCRC),R.compressedSize=e.readUInt32LE(O+Ae.EXTSIZ),R.size=e.readUInt32LE(O+Ae.EXTLEN);else if(e.readUInt16LE(O+12)===19280)R.crc=e.readUInt32LE(O+Ae.EXTCRC-4),R.compressedSize=e.readUInt32LE(O+Ae.EXTSIZ-4),R.size=e.readUInt32LE(O+Ae.EXTLEN-4);else throw de.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==n.compressedSize||R.size!==n.size||R.crc!==n.crc)throw de.Errors.DESCRIPTOR_FAULTY();if(de.crc32(y)!==R.crc)return!1}return!0}function E(y,R,O){if(typeof R>"u"&&typeof y=="string"&&(O=y,y=void 0),c)return y&&R&&R(Buffer.alloc(0),de.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return y&&R&&R(F),F;if(n.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw de.Errors.INVALID_PASS_PARAM();F=Va.ZipCrypto.decrypt(F,n,O)}var M=Buffer.alloc(n.size);switch(n.method){case de.Constants.STORED:if(F.copy(M),_(M))return y&&R&&R(M),M;throw y&&R&&R(M,de.Errors.BAD_CRC()),de.Errors.BAD_CRC();case de.Constants.DEFLATED:var Y=new Va.Inflater(F,n.size);if(y)Y.inflateAsync(function(V){V.copy(V,0),R&&(_(V)?R(V):R(V,de.Errors.BAD_CRC()))});else{if(Y.inflate(M).copy(M,0),!_(M))throw de.Errors.BAD_CRC(`"${w.decode(i)}"`);return M}break;default:throw y&&R&&R(Buffer.alloc(0),de.Errors.UNKNOWN_METHOD()),de.Errors.UNKNOWN_METHOD()}}function I(y,R){if((!d||!d.length)&&Buffer.isBuffer(e))return y&&R&&R(S()),S();if(d.length&&!c){var O;switch(n.method){case de.Constants.STORED:return n.compressedSize=n.size,O=Buffer.alloc(d.length),d.copy(O),y&&R&&R(O),O;default:case de.Constants.DEFLATED:var F=new Va.Deflater(d);if(y)F.deflateAsync(function(Y){O=Buffer.alloc(Y.length),n.compressedSize=Y.length,Y.copy(O),R&&R(O)});else{var M=F.deflate();return n.compressedSize=M.length,M}F=null;break}}else if(y&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(y,R){return de.readBigUInt64LE(y,R)}function T(y){try{for(var R=0,O,F,M;R+4<y.length;)O=y.readUInt16LE(R),R+=2,F=y.readUInt16LE(R),R+=2,M=y.slice(R,R+F),R+=F,Ae.ID_ZIP64===O&&P(M)}catch{throw de.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(y){var R,O,F,M;y.length>=Ae.EF_ZIP64_SCOMP&&(R=A(y,Ae.EF_ZIP64_SUNCOMP),n.size===Ae.EF_ZIP64_OR_32&&(n.size=R)),y.length>=Ae.EF_ZIP64_RHO&&(O=A(y,Ae.EF_ZIP64_SCOMP),n.compressedSize===Ae.EF_ZIP64_OR_32&&(n.compressedSize=O)),y.length>=Ae.EF_ZIP64_DSN&&(F=A(y,Ae.EF_ZIP64_RHO),n.offset===Ae.EF_ZIP64_OR_32&&(n.offset=F)),y.length>=Ae.EF_ZIP64_DSN+4&&(M=y.readUInt32LE(Ae.EF_ZIP64_DSN),n.diskNumStart===Ae.EF_ZIP64_OR_16&&(n.diskNumStart=M))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(y){i=de.toBuffer(y,w.encode);var R=i[i.length-1];c=R===47||R===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(y){u=y,n.extraLength=y.length,T(y)},get comment(){return w.decode(o)},set comment(y){if(o=de.toBuffer(y,w.encode),n.commentLength=o.length,o.length>65535)throw de.Errors.COMMENT_TOO_LONG()},get name(){var y=w.decode(i);return c?y.substr(y.length-1).split("/").pop():y.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(y){I(!0,y)},setData:function(y){d=de.toBuffer(y,de.decoder.encode),!c&&d.length?(n.size=d.length,n.method=de.Constants.DEFLATED,n.crc=de.crc32(y),n.changed=!0):n.method=de.Constants.STORED},getData:function(y){return n.changed?d:E(!1,null,y)},getDataAsync:function(y,R){n.changed?y(d):E(!0,y,R)},set attr(y){n.attr=y},get attr(){return n.attr},set header(y){n.loadFromBinary(y)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var y=n.centralHeaderToBinary(),R=de.Constants.CENHDR;return i.copy(y,R),R+=i.length,u.copy(y,R),R+=n.extraLength,o.copy(y,R),y},packLocalHeader:function(){let y=0;n.flags_efs=this.efs,n.extraLocalLength=f.length;let R=n.localHeaderToBinary(),O=Buffer.alloc(R.length+i.length+n.extraLocalLength);return R.copy(O,y),y+=R.length,i.copy(O,y),y+=i.length,f.copy(O,y),y+=f.length,O},toJSON:function(){let y=function(R){return"<"+(R&&R.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:y(e),data:y(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Tu=ce((wA,ku)=>{var Au=Za(),Qm=$a(),Ze=wr();ku.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),c=new Qm.MainHeader,d=!1,u=null;let f=new Set,x=e,{noSort:p,decoder:w}=x;t?E(x.readEntries):d=!0;function S(){let A=new Set;for(let T of Object.keys(i)){let P=T.split("/");if(P.pop(),!!P.length)for(let y=0;y<P.length;y++){let R=P.slice(0,y+1).join("/")+"/";A.add(R)}}for(let T of A)if(!(T in i)){let P=new Au(x);P.entryName=T,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,f.add(P)}}function _(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/Ze.Constants.CENHDR)throw Ze.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(c.diskEntries);for(var A=c.offset,T=0;T<n.length;T++){var P=A,y=new Au(x,t);y.header=t.slice(P,P+=Ze.Constants.CENHDR),y.entryName=t.slice(P,P+=y.header.fileNameLength),y.header.extraLength&&(y.extra=t.slice(P,P+=y.header.extraLength)),y.header.commentLength&&(y.comment=t.slice(P,P+y.header.commentLength)),A+=y.header.centralHeaderSize,n[T]=y,i[y.entryName]=y}f.clear(),S()}function E(A){var T=t.length-Ze.Constants.ENDHDR,P=Math.max(0,T-65535),y=P,R=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),T;T>=y;T--)if(t[T]===80){if(t.readUInt32LE(T)===Ze.Constants.ENDSIG){O=T,F=T,R=T+Ze.Constants.ENDHDR,y=T-Ze.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Ze.Constants.END64SIG){y=P;continue}if(t.readUInt32LE(T)===Ze.Constants.ZIP64SIG){O=T,R=T+Ze.readBigUInt64LE(t,T+Ze.Constants.ZIP64SIZE)+Ze.Constants.ZIP64LEAD;break}}if(O==-1)throw Ze.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,R)),c.commentLength&&(o=t.slice(F+Ze.Constants.ENDHDR)),A&&_()}function I(){n.length>1&&!p&&n.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(A=>!f.has(A))},get comment(){return w.decode(o)},set comment(A){o=Ze.toBuffer(A,w.encode),c.commentLength=o.length},getEntryCount:function(){return d?n.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||_(),i[A]||null},setEntry:function(A){d||_(),n.push(A),i[A.entryName]=A,c.totalEntries=n.length},deleteFile:function(A,T=!0){d||_();let P=i[A];this.getEntryChildren(P,T).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||_();let T=i[A],P=n.indexOf(T);P>=0&&(n.splice(P,1),delete i[A],c.totalEntries=n.length)},getEntryChildren:function(A,T=!0){if(d||_(),typeof A=="object")if(A.isDirectory&&T){let P=[],y=A.entryName;for(let R of n)R.entryName.startsWith(y)&&P.push(R);return P}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){d||_(),I();let A=[],T=[],P=0,y=0;c.size=0,c.offset=0;let R=0;for(let M of this.entries){let Y=M.getCompressedData();M.header.offset=y;let V=M.packLocalHeader(),se=V.length+Y.length;y+=se,A.push(V),A.push(Y);let Q=M.packCentralHeader();T.push(Q),c.size+=Q.length,P+=se+Q.length,R++}P+=c.mainHeaderSize,c.offset=y,c.totalEntries=R,y=0;let O=Buffer.alloc(P);for(let M of A)M.copy(O,y),y+=M.length;for(let M of T)M.copy(O,y),y+=M.length;let F=c.toBinary();return o&&o.copy(F,Ze.Constants.ENDHDR),F.copy(O,y),t=O,d=!1,O},toAsyncBuffer:function(A,T,P,y){try{d||_(),I();let R=[],O=[],F=0,M=0,Y=0;c.size=0,c.offset=0;let V=function(se){if(se.length>0){let Q=se.shift(),ne=Q.entryName+Q.extra.toString();P&&P(ne),Q.getCompressedDataAsync(function(ae){y&&y(ne),Q.header.offset=M;let D=Q.packLocalHeader(),U=D.length+ae.length;M+=U,R.push(D),R.push(ae);let j=Q.packCentralHeader();O.push(j),c.size+=j.length,F+=U+j.length,Y++,V(se)})}else{F+=c.mainHeaderSize,c.offset=M,c.totalEntries=Y,M=0;let Q=Buffer.alloc(F);R.forEach(function(ae){ae.copy(Q,M),M+=ae.length}),O.forEach(function(ae){ae.copy(Q,M),M+=ae.length});let ne=c.toBinary();o&&o.copy(ne,Ze.Constants.ENDHDR),ne.copy(Q,M),t=Q,d=!1,A(Q)}};V(Array.from(this.entries))}catch(R){T(R)}}}}});var Du=ce((_A,Ru)=>{var Se=wr(),ve=xe("path"),ew=Za(),tw=Tu(),Fn=(...t)=>Se.findLast(t,e=>typeof e=="boolean"),Cu=(...t)=>Se.findLast(t,e=>typeof e=="string"),nw=(...t)=>Se.findLast(t,e=>typeof e=="function"),rw={noSort:!1,readEntries:!1,method:Se.Constants.NONE,fs:null};Ru.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),rw);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=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,n=o.fs.readFileSync(t);else throw Se.Errors.INVALID_FILENAME();let c=new tw(n,i),{canonical:d,sanitize:u,zipnamefix:f}=Se;function x(_){if(_&&c){var E;if(typeof _=="string"&&(E=c.getEntry(ve.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(E=c.getEntry(_.entryName)),E)return E}return null}function p(_){let{join:E,normalize:I,sep:A}=ve.posix;return E(ve.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function w(_){return _ instanceof RegExp?(function(E){return function(I){return E.test(I)}})(_):typeof _!="function"?()=>!0:_}let S=(_,E)=>{let I=E.slice(-1);return I=I===o.sep?o.sep:"",ve.relative(_,E)+I};return{readFile:function(_,E){var I=x(_);return I&&I.getData(E)||null},childCount:function(_){let E=x(_);if(E)return c.getChildCount(E)},readFileAsync:function(_,E){var I=x(_);I?I.getDataAsync(E):E(null,"getEntry failed for:"+_)},readAsText:function(_,E){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(E||"utf8")}return""},readAsTextAsync:function(_,E,I){var A=x(_);A?A.getDataAsync(function(T,P){if(P){E(T,P);return}T&&T.length?E(T.toString(I||"utf8")):E("")}):E("")},deleteFile:function(_,E=!0){var I=x(_);I&&c.deleteFile(I.entryName,E)},deleteEntry:function(_){var E=x(_);E&&c.deleteEntry(E.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,E){var I=x(_);I&&(I.comment=E)},getZipEntryComment:function(_){var E=x(_);return E&&E.comment||""},updateFile:function(_,E){var I=x(_);I&&I.setData(E)},addLocalFile:function(_,E,I,A){if(o.fs.existsSync(_)){E=E?p(E):"";let T=ve.win32.basename(ve.win32.normalize(_));E+=I||T;let P=o.fs.statSync(_),y=P.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);P.isDirectory()&&(E+=o.sep),this.addFile(E,y,A,P)}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,E){_=typeof _=="object"?_:{localPath:_};let I=ve.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:P}=_,y=this;o.fs.stat(I,function(R,O){if(R)return E(R,!1);T=T?p(T):"";let F=ve.win32.basename(ve.win32.normalize(I));if(T+=P||F,O.isFile())o.fs.readFile(I,function(M,Y){return M?E(M,!1):(y.addFile(T,Y,A,O),setImmediate(E,void 0,!0))});else if(O.isDirectory())return T+=o.sep,y.addFile(T,Buffer.alloc(0),A,O),setImmediate(E,void 0,!0)})},addLocalFolder:function(_,E,I){if(I=w(I),E=E?p(E):"",_=ve.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),T=this;if(A.length)for(let P of A){let y=ve.join(E,S(_,P));I(y)&&T.addLocalFile(P,ve.dirname(y))}}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,E,I,A){A=w(A),I=I?p(I):"",_=ve.normalize(_);var T=this;o.fs.open(_,"r",function(P){if(P&&P.code==="ENOENT")E(void 0,Se.Errors.FILE_NOT_FOUND(_));else if(P)E(void 0,P);else{var y=o.findFiles(_),R=-1,O=function(){if(R+=1,R<y.length){var F=y[R],M=S(_,F).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?o.fs.stat(F,function(Y,V){Y&&E(void 0,Y),V.isFile()?o.fs.readFile(F,function(se,Q){se?E(void 0,se):(T.addFile(I+M,Q,"",V),O())}):(T.addFile(I+M+"/",Buffer.alloc(0),"",V),O())}):process.nextTick(()=>{O()})}else E(!0,void 0)};O()}})},addLocalFolderAsync2:function(_,E){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=ve.resolve(p(_.localPath));let{zipPath:A,filter:T,namefix:P}=_;T instanceof RegExp?T=(function(O){return function(F){return O.test(F)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?p(A):"",P=="latin1"&&(P=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=O=>O);let y=O=>ve.join(A,P(S(localPath,O))),R=O=>ve.win32.basename(ve.win32.normalize(P(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?E(void 0,Se.Errors.FILE_NOT_FOUND(localPath)):O?E(void 0,O):o.findFilesAsync(localPath,function(F,M){if(F)return E(F);M=M.filter(Y=>T(y(Y))),M.length||E(void 0,!1),setImmediate(M.reverse().reduce(function(Y,V){return function(se,Q){if(se||Q===!1)return setImmediate(Y,se,!1);I.addLocalFileAsync({localPath:V,zipPath:ve.dirname(y(V)),zipName:R(V)},Y)}},E))})})},addLocalFolderPromise:function(_,E){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},E),(T,P)=>{T&&A(T),P&&I(this)})})},addFile:function(_,E,I,A){_=f(_);let T=x(_),P=T!=null;P||(T=new ew(i),T.entryName=_),T.comment=I||"";let y=typeof A=="object"&&A instanceof o.fs.Stats;y&&(T.header.time=A.mtime);var R=T.isDirectory?16:0;let O=T.isDirectory?16384:32768;return y?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=T.isDirectory?493:420,R=(R|O<<16)>>>0,T.attr=R,T.setData(E),P||c.setEntry(T),T},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,E,I,A,T,P){A=Fn(!1,A),T=Fn(!1,T),I=Fn(!0,I),P=Cu(T,P);var y=x(_);if(!y)throw Se.Errors.NO_ENTRY();var R=d(y.entryName),O=u(E,P&&!y.isDirectory?P:I?R:ve.basename(R));if(y.isDirectory){var F=c.getEntryChildren(y);return F.forEach(function(V){if(V.isDirectory)return;var se=V.getData();if(!se)throw Se.Errors.CANT_EXTRACT_FILE();var Q=d(V.entryName),ne=u(E,I?Q:ve.basename(Q));let ae=T?V.header.fileAttr:void 0;o.writeFileTo(ne,se,A,ae)}),!0}var M=y.getData(c.password);if(!M)throw Se.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw Se.Errors.CANT_OVERRIDE();let Y=T?_.header.fileAttr:void 0;return o.writeFileTo(O,M,A,Y),!0},test:function(_){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var I=c.entries[E].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,E,I,A){if(I=Fn(!1,I),A=Cu(I,A),E=Fn(!1,E),!c)throw Se.Errors.NO_ZIP();c.entries.forEach(function(T){var P=u(_,d(T.entryName));if(T.isDirectory){o.makeDir(P);return}var y=T.getData(A);if(!y)throw Se.Errors.CANT_EXTRACT_FILE();let R=I?T.header.fileAttr:void 0;o.writeFileTo(P,y,E,R);try{o.fs.utimesSync(P,T.header.time,T.header.time)}catch{throw Se.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,E,I,A){if(A=nw(E,I,A),I=Fn(!1,I),E=Fn(!1,E),!A)return new Promise((O,F)=>{this.extractAllToAsync(_,E,I,function(M){M?F(M):O(this)})});if(!c){A(Se.Errors.NO_ZIP());return}_=ve.resolve(_);let T=O=>u(_,ve.normalize(d(O.entryName))),P=(O,F)=>new Error(O+': "'+F+'"'),y=[],R=[];c.entries.forEach(O=>{O.isDirectory?y.push(O):R.push(O)});for(let O of y){let F=T(O),M=I?O.header.fileAttr:void 0;try{o.makeDir(F),M&&o.fs.chmodSync(F,M),o.fs.utimesSync(F,O.header.time,O.header.time)}catch{A(P("Unable to create folder",F))}}R.reverse().reduce(function(O,F){return function(M){if(M)O(M);else{let Y=ve.normalize(d(F.entryName)),V=u(_,Y);F.getDataAsync(function(se,Q){if(Q)O(Q);else if(!se)O(Se.Errors.CANT_EXTRACT_FILE());else{let ne=I?F.header.fileAttr:void 0;o.writeFileToAsync(V,se,E,ne,function(ae){ae||O(P("Unable to write file",V)),o.fs.utimes(V,F.header.time,F.header.time,function(D){D?O(P("Unable to set times",V)):O()})})}})}}},A)()},writeZip:function(_,E){if(arguments.length===1&&typeof _=="function"&&(E=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof E=="function"&&E(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,E){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},E);return new Promise((T,P)=>{!_&&i.filename&&(_=i.filename),_||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(y=>{let R=O=>O?T(O):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,y,I,A,R)},P)})},toBufferPromise:function(){return new Promise((_,E)=>{c.toAsyncBuffer(_,E)})},toBuffer:function(_,E,I,A){return typeof _=="function"?(c.toAsyncBuffer(_,E,I,A),null):c.compressToBuffer()}}}});import{execFile as uy,spawn as fy,spawnSync as Bk}from"node:child_process";import{promisify as hy}from"node:util";function py(t){if(process.platform!=="win32")return!1;if(Qf.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(Qf,"").toLowerCase();return xy.has(n)}function e0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return py(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function st(t,e=[],n={}){return fy(t,e,e0(t,n))}function t0(t,e=[],n={}){return gy(t,e,e0(t,n))}var xy,Qf,gy,Yt=nt(()=>{"use strict";xy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Qf=/\.(cmd|bat|ps1)$/i;gy=hy(uy)});var Qt=ce((kD,jh)=>{"use strict";var Hh=["nodebuffer","arraybuffer","fragments"],qh=typeof Blob<"u";qh&&Hh.push("blob");jh.exports={BINARY_TYPES:Hh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:qh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ts=ce((TD,qo)=>{"use strict";var{EMPTY_BUFFER:Iv}=Qt(),Dd=Buffer[Symbol.species];function Av(t,e){if(t.length===0)return Iv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let c=t[o];n.set(c,i),i+=c.length}return i<e?new Dd(n.buffer,n.byteOffset,i):n}function Wh(t,e,n,i,o){for(let c=0;c<o;c++)n[i+c]=t[c]^e[c&3]}function Kh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function kv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Pd(t){if(Pd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Dd(t):ArrayBuffer.isView(t)?e=new Dd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Pd.readOnly=!1),e}qo.exports={concat:Av,mask:Wh,toArrayBuffer:kv,toBuffer:Pd,unmask:Kh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");qo.exports.mask=function(e,n,i,o,c){c<48?Wh(e,n,i,o,c):t.mask(e,n,i,o,c)},qo.exports.unmask=function(e,n){e.length<32?Kh(e,n):t.unmask(e,n)}}catch{}});var Zh=ce((CD,Vh)=>{"use strict";var $h=Symbol("kDone"),Od=Symbol("kRun"),Ld=class{constructor(e){this[$h]=()=>{this.pending--,this[Od]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Od]()}[Od](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$h])}}};Vh.exports=Ld});var $r=ce((RD,Qh)=>{"use strict";var ns=xe("zlib"),Yh=ts(),Tv=Zh(),{kStatusCode:Jh}=Qt(),Cv=Buffer[Symbol.species],Rv=Buffer.from([0,0,255,255]),Wo=Symbol("permessage-deflate"),en=Symbol("total-length"),Wr=Symbol("callback"),Pn=Symbol("buffers"),Kr=Symbol("error"),jo,Nd=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,!jo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;jo=new Tv(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[Wr];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(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.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 o=n[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}"`);n[i]=o})}),e}decompress(e,n,i){jo.add(o=>{this._decompress(e,n,(c,d)=>{o(),i(c,d)})})}compress(e,n,i){jo.add(o=>{this._compress(e,n,(c,d)=>{o(),i(c,d)})})}_decompress(e,n,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?ns.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=ns.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Wo]=this,this._inflate[en]=0,this._inflate[Pn]=[],this._inflate.on("error",Pv),this._inflate.on("data",Xh)}this._inflate[Wr]=i,this._inflate.write(e),n&&this._inflate.write(Rv),this._inflate.flush(()=>{let c=this._inflate[Kr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Yh.concat(this._inflate[Pn],this._inflate[en]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[en]=0,this._inflate[Pn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?ns.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=ns.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[en]=0,this._deflate[Pn]=[],this._deflate.on("data",Dv)}this._deflate[Wr]=i,this._deflate.write(e),this._deflate.flush(ns.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Yh.concat(this._deflate[Pn],this._deflate[en]);n&&(c=new Cv(c.buffer,c.byteOffset,c.length-4)),this._deflate[Wr]=null,this._deflate[en]=0,this._deflate[Pn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Qh.exports=Nd;function Dv(t){this[Pn].push(t),this[en]+=t.length}function Xh(t){if(this[en]+=t.length,this[Wo]._maxPayload<1||this[en]<=this[Wo]._maxPayload){this[Pn].push(t);return}this[Kr]=new RangeError("Max payload size exceeded"),this[Kr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Kr][Jh]=1009,this.removeListener("data",Xh),this.reset()}function Pv(t){if(this[Wo]._inflate=null,this[Kr]){this[Wr](this[Kr]);return}t[Jh]=1007,this[Wr](t)}});var Vr=ce((DD,Ko)=>{"use strict";var{isUtf8:ex}=xe("buffer"),{hasBlob:Ov}=Qt(),Lv=[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 Nv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Md(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 Mv(t){return Ov&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ko.exports={isBlob:Mv,isValidStatusCode:Nv,isValidUTF8:Md,tokenChars:Lv};if(ex)Ko.exports.isValidUTF8=function(t){return t.length<24?Md(t):ex(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");Ko.exports.isValidUTF8=function(e){return e.length<32?Md(e):t(e)}}catch{}});var Gd=ce((PD,ax)=>{"use strict";var{Writable:Bv}=xe("stream"),tx=$r(),{BINARY_TYPES:Fv,EMPTY_BUFFER:nx,kStatusCode:zv,kWebSocket:Uv}=Qt(),{concat:Bd,toArrayBuffer:Gv,unmask:Hv}=ts(),{isValidStatusCode:qv,isValidUTF8:rx}=Vr(),$o=Buffer[Symbol.species],pt=0,ix=1,sx=2,ox=3,Fd=4,zd=5,Vo=6,Ud=class extends Bv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Fv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Uv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=pt}_write(e,n,i){if(this._opcode===8&&this._state==pt)return i();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 $o(i.buffer,i.byteOffset+e,i.length-e),new $o(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=n.length-e;e>=i.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new $o(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case pt:this.getInfo(e);break;case ix:this.getPayloadLength16(e);break;case sx:this.getPayloadLength64(e);break;case ox:this.getMask();break;case Fd:this.getData(e);break;case zd:case Vo: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 o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(n[0]&64)===64;if(i&&!this._extensions[tx.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[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=(n[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=ix:this._payloadLength===127?this._state=sx: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 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)+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=ox:this._state=Fd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Fd}getData(e){let n=nx;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&&Hv(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=zd,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[tx.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return n(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(d);return}this._fragments.push(c)}this.dataMessage(n),this._state===pt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=pt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Bd(i,n):this._binaryType==="arraybuffer"?o=Gv(Bd(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=pt):(this._state=Vo,setImmediate(()=>{this.emit("message",o,!0),this._state=pt,this.startLoop(e)}))}else{let o=Bd(i,n);if(!this._skipUTF8Validation&&!rx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===zd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=pt):(this._state=Vo,setImmediate(()=>{this.emit("message",o,!1),this._state=pt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,nx),this.end();else{let i=e.readUInt16BE(0);if(!qv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(c);return}let o=new $o(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!rx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=pt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=pt):(this._state=Vo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=pt,this.startLoop(n)}))}createError(e,n,i,o,c){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=c,d[zv]=o,d}};ax.exports=Ud});var jd=ce((LD,lx)=>{"use strict";var{Duplex:OD}=xe("stream"),{randomFillSync:jv}=xe("crypto"),cx=$r(),{EMPTY_BUFFER:Wv,kWebSocket:Kv,NOOP:$v}=Qt(),{isBlob:Zr,isValidStatusCode:Vv}=Vr(),{mask:dx,toBuffer:tr}=ts(),gt=Symbol("kByteLength"),Zv=Buffer.alloc(4),Zo=8*1024,nr,Yr=Zo,It=0,Yv=1,Jv=2,Hd=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=It,this.onerror=$v,this[Kv]=void 0}static frame(e,n){let i,o=!1,c=2,d=!1;n.mask&&(i=n.maskBuffer||Zv,n.generateMask?n.generateMask(i):(Yr===Zo&&(nr===void 0&&(nr=Buffer.alloc(Zo)),jv(nr,0,Zo),Yr=0),i[0]=nr[Yr++],i[1]=nr[Yr++],i[2]=nr[Yr++],i[3]=nr[Yr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!n.mask||d)&&n[gt]!==void 0?u=n[gt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=n.mask&&n.readOnly&&!d);let f=u;u>=65536?(c+=8,f=127):u>125&&(c+=2,f=126);let x=Buffer.allocUnsafe(o?u+c:c);return x[0]=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[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],d?[x,e]:o?(dx(e,i,x,c,u),[x]):(dx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,o){let c;if(e===void 0)c=Wv;else{if(typeof e!="number"||!Vv(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof n=="string"?c.write(n,2):c.set(n,2)}}let d={[gt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==It?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,n,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Zr(e)?(o=e.size,c=!1):(e=tr(e),o=e.length,c=tr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[gt]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Zr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Zr(e)?(o=e.size,c=!1):(e=tr(e),o=e.length,c=tr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[gt]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Zr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[cx.extensionName],c=n.binary?2:1,d=n.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Zr(e)?(u=e.size,f=!1):(e=tr(e),u=e.length,f=tr.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,c=0),n.fin&&(this._firstFragment=!0);let x={[gt]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:f,rsv1:d};Zr(e)?this._state!==It?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==It?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[gt],this._state=Jv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(qd,this,u,o);return}this._bufferedBytes-=i[gt];let d=tr(c);n?this.dispatch(d,n,i,o):(this._state=It,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(Xv,this,c,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[cx.extensionName];this._bufferedBytes+=i[gt],this._state=Yv,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");qd(this,f,o);return}this._bufferedBytes-=i[gt],this._state=It,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===It&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][gt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][gt],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};lx.exports=Hd;function qd(t,e,n){typeof n=="function"&&n(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 Xv(t,e,n){qd(t,e,n),t.onerror(e)}});var yx=ce((ND,_x)=>{"use strict";var{kForOnEventAttribute:rs,kListener:Wd}=Qt(),ux=Symbol("kCode"),fx=Symbol("kData"),hx=Symbol("kError"),xx=Symbol("kMessage"),px=Symbol("kReason"),Jr=Symbol("kTarget"),gx=Symbol("kType"),mx=Symbol("kWasClean"),tn=class{constructor(e){this[Jr]=null,this[gx]=e}get target(){return this[Jr]}get type(){return this[gx]}};Object.defineProperty(tn.prototype,"target",{enumerable:!0});Object.defineProperty(tn.prototype,"type",{enumerable:!0});var rr=class extends tn{constructor(e,n={}){super(e),this[ux]=n.code===void 0?0:n.code,this[px]=n.reason===void 0?"":n.reason,this[mx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[ux]}get reason(){return this[px]}get wasClean(){return this[mx]}};Object.defineProperty(rr.prototype,"code",{enumerable:!0});Object.defineProperty(rr.prototype,"reason",{enumerable:!0});Object.defineProperty(rr.prototype,"wasClean",{enumerable:!0});var Xr=class extends tn{constructor(e,n={}){super(e),this[hx]=n.error===void 0?null:n.error,this[xx]=n.message===void 0?"":n.message}get error(){return this[hx]}get message(){return this[xx]}};Object.defineProperty(Xr.prototype,"error",{enumerable:!0});Object.defineProperty(Xr.prototype,"message",{enumerable:!0});var is=class extends tn{constructor(e,n={}){super(e),this[fx]=n.data===void 0?null:n.data}get data(){return this[fx]}};Object.defineProperty(is.prototype,"data",{enumerable:!0});var Qv={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[rs]&&o[Wd]===e&&!o[rs])return;let i;if(t==="message")i=function(c,d){let u=new is("message",{data:d?c:c.toString()});u[Jr]=this,Yo(e,this,u)};else if(t==="close")i=function(c,d){let u=new rr("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Jr]=this,Yo(e,this,u)};else if(t==="error")i=function(c){let d=new Xr("error",{error:c,message:c.message});d[Jr]=this,Yo(e,this,d)};else if(t==="open")i=function(){let c=new tn("open");c[Jr]=this,Yo(e,this,c)};else return;i[rs]=!!n[rs],i[Wd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Wd]===e&&!n[rs]){this.removeListener(t,n);break}}};_x.exports={CloseEvent:rr,ErrorEvent:Xr,Event:tn,EventTarget:Qv,MessageEvent:is};function Yo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Jo=ce((MD,bx)=>{"use strict";var{tokenChars:ss}=Vr();function zt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function eS(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,c=!1,d,u,f=-1,x=-1,p=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(p===-1&&ss[x]===1)f===-1&&(f=w);else if(w!==0&&(x===32||x===9))p===-1&&f!==-1&&(p=w);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w);let _=t.slice(f,p);x===44?(zt(e,_,n),n=Object.create(null)):d=_,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(p===-1&&ss[x]===1)f===-1&&(f=w);else if(x===32||x===9)p===-1&&f!==-1&&(p=w);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w),zt(n,t.slice(f,p),!0),x===44&&(zt(e,d,n),n=Object.create(null),d=void 0),f=p=-1}else if(x===61&&f!==-1&&p===-1)u=t.slice(f,w),f=p=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(ss[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);f===-1?f=w:i||(i=!0),o=!1}else if(c)if(ss[x]===1)f===-1&&(f=w);else if(x===34&&f!==-1)c=!1,p=w;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)c=!0;else if(p===-1&&ss[x]===1)f===-1&&(f=w);else if(f!==-1&&(x===32||x===9))p===-1&&(p=w);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w);let _=t.slice(f,p);i&&(_=_.replace(/\\/g,""),i=!1),zt(n,u,_),x===44&&(zt(e,d,n),n=Object.create(null),d=void 0),u=void 0,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(f===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=w);let S=t.slice(f,p);return d===void 0?zt(e,S,n):(u===void 0?zt(n,S,!0):i?zt(n,u,S.replace(/\\/g,"")):zt(n,u,S),zt(e,d,n)),e}function tS(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(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bx.exports={format:tS,parse:eS}});var ta=ce((zD,Ox)=>{"use strict";var nS=xe("events"),rS=xe("https"),iS=xe("http"),Sx=xe("net"),sS=xe("tls"),{randomBytes:oS,createHash:aS}=xe("crypto"),{Duplex:BD,Readable:FD}=xe("stream"),{URL:Kd}=xe("url"),On=$r(),cS=Gd(),dS=jd(),{isBlob:lS}=Vr(),{BINARY_TYPES:Ex,CLOSE_TIMEOUT:uS,EMPTY_BUFFER:Xo,GUID:fS,kForOnEventAttribute:$d,kListener:hS,kStatusCode:xS,kWebSocket:Ke,NOOP:Ix}=Qt(),{EventTarget:{addEventListener:pS,removeEventListener:gS}}=yx(),{format:mS,parse:wS}=Jo(),{toBuffer:_S}=ts(),Ax=Symbol("kAborted"),Vd=[8,13],nn=["CONNECTING","OPEN","CLOSING","CLOSED"],yS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ye=class t extends nS{constructor(e,n,i){super(),this._binaryType=Ex[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xo,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]),kx(this,e,n,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,n,i){let o=new cS({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new dS(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[Ke]=this,c[Ke]=this,e[Ke]=this,o.on("conclude",vS),o.on("drain",SS),o.on("error",IS),o.on("message",AS),o.on("ping",kS),o.on("pong",TS),c.onerror=CS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Rx),e.on("data",ea),e.on("end",Dx),e.on("error",Px),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[On.extensionName]&&this._extensions[On.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Cx(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){Zd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Xo,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){Zd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Xo,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){Zd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[On.extensionName]||(o.compress=!1),this._sender.send(e||Xo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ye,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(ye.prototype,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(ye,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(ye.prototype,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(ye,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(ye.prototype,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(ye,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});Object.defineProperty(ye.prototype,"CLOSED",{enumerable:!0,value:nn.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[$d])return e[hS];return null},set(e){for(let n of this.listeners(t))if(n[$d]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[$d]:!0})}})});ye.prototype.addEventListener=pS;ye.prototype.removeEventListener=gS;Ox.exports=ye;function kx(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:uS,protocolVersion:Vd[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,!Vd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Vd.join(", ")})`);let c;if(e instanceof Kd)c=e;else try{c=new Kd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let d=c.protocol==="wss:",u=c.protocol==="ws+unix:",f;if(c.protocol!=="ws:"&&!d&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?f="The URL's pathname is empty":c.hash&&(f="The URL contains a fragment identifier"),f){let I=new SyntaxError(f);if(t._redirects===0)throw I;Qo(t,I);return}let x=d?443:80,p=oS(16).toString("base64"),w=d?rS.request:iS.request,S=new Set,_;if(o.createConnection=o.createConnection||(d?ES:bS),o.defaultPort=o.defaultPort||x,o.port=c.port||x,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new On({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=mS({[On.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!yS.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,T]of Object.entries(I))i.headers[A.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=w(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=w(o);o.timeout&&E.on("timeout",()=>{dt(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[Ax]||(E=t._req=null,Qo(t,I))}),E.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){dt(t,E,"Maximum redirects exceeded");return}E.abort();let P;try{P=new Kd(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);Qo(t,R);return}kx(t,P,n,i)}else t.emit("unexpected-response",E,I)||dt(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==ye.CONNECTING)return;E=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){dt(t,A,"Invalid Upgrade header");return}let y=aS("sha1").update(p+fS).digest("base64");if(I.headers["sec-websocket-accept"]!==y){dt(t,A,"Invalid Sec-WebSocket-Accept header");return}let R=I.headers["sec-websocket-protocol"],O;if(R!==void 0?S.size?S.has(R)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":S.size&&(O="Server sent no subprotocol"),O){dt(t,A,O);return}R&&(t._protocol=R);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!_){dt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=wS(F)}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Y=Object.keys(M);if(Y.length!==1||Y[0]!==On.extensionName){dt(t,A,"Server indicated an extension that was not requested");return}try{_.accept(M[On.extensionName])}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[On.extensionName]=_}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,t):E.end()}function Qo(t,e){t._readyState=ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function bS(t){return t.path=t.socketPath,Sx.connect(t)}function ES(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Sx.isIP(t.host)?"":t.host),sS.connect(t)}function dt(t,e,n){t._readyState=ye.CLOSING;let i=new Error(n);Error.captureStackTrace(i,dt),e.setHeader?(e[Ax]=!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 Zd(t,e,n){if(e){let i=lS(e)?e.size:_S(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${nn[t.readyState]})`);process.nextTick(n,i)}}function vS(t,e){let n=this[Ke];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Ke]!==void 0&&(n._socket.removeListener("data",ea),process.nextTick(Tx,n._socket),t===1005?n.close():n.close(t,e))}function SS(){let t=this[Ke];t.isPaused||t._socket.resume()}function IS(t){let e=this[Ke];e._socket[Ke]!==void 0&&(e._socket.removeListener("data",ea),process.nextTick(Tx,e._socket),e.close(t[xS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function vx(){this[Ke].emitClose()}function AS(t,e){this[Ke].emit("message",t,e)}function kS(t){let e=this[Ke];e._autoPong&&e.pong(t,!this._isServer,Ix),e.emit("ping",t)}function TS(t){this[Ke].emit("pong",t)}function Tx(t){t.resume()}function CS(t){let e=this[Ke];e.readyState!==ye.CLOSED&&(e.readyState===ye.OPEN&&(e._readyState=ye.CLOSING,Cx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Cx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Rx(){let t=this[Ke];if(this.removeListener("close",Rx),this.removeListener("data",ea),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[Ke]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",vx),t._receiver.on("finish",vx))}function ea(t){this[Ke]._receiver.write(t)||this.pause()}function Dx(){let t=this[Ke];t._readyState=ye.CLOSING,t._receiver.end(),this.end()}function Px(){let t=this[Ke];this.removeListener("error",Px),this.on("error",Ix),t&&(t._readyState=ye.CLOSING,this.destroy())}});var Bx=ce((GD,Mx)=>{"use strict";var UD=ta(),{Duplex:RS}=xe("stream");function Lx(t){t.emit("close")}function DS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Nx(t){this.removeListener("error",Nx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function PS(t,e){let n=!0,i=new RS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,d){let u=!d&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(n=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(Lx,i);return}let d=!1;t.once("error",function(f){d=!0,c(f)}),t.once("close",function(){d||c(o),process.nextTick(Lx,i)}),n&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,d)});return}t.send(o,d)},i.on("end",DS),i.on("error",Nx),i}Mx.exports=PS});var Yd=ce((HD,Fx)=>{"use strict";var{tokenChars:OS}=Vr();function LS(t){let e=new Set,n=-1,i=-1,o=0;for(o;o<t.length;o++){let d=t.charCodeAt(o);if(i===-1&&OS[d]===1)n===-1&&(n=o);else if(o!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=o);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);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 ${o}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(n,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}Fx.exports={parse:LS}});var Wx=ce((jD,jx)=>{"use strict";var NS=xe("events"),na=xe("http"),{Duplex:qD}=xe("stream"),{createHash:MS}=xe("crypto"),zx=Jo(),ir=$r(),BS=Yd(),FS=ta(),{CLOSE_TIMEOUT:zS,GUID:US,kWebSocket:GS}=Qt(),HS=/^[+/0-9A-Za-z]{22}==$/,Ux=0,Gx=1,qx=2,Jd=class extends NS{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:zS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:FS,...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=na.createServer((i,o)=>{let c=na.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,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=qS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,d)=>{this.handleUpgrade(o,c,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ux}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===qx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(os,this);return}if(e&&this.once("close",e),this._state!==Gx)if(this._state=Gx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(os,this):process.nextTick(os,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{os(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,o){n.on("error",Hx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){sr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){sr(this,e,n,400,"Invalid Upgrade header");return}if(c===void 0||!HS.test(c)){sr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){sr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){as(n,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=BS.parse(f)}catch{sr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&p!==void 0){let S=new ir({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=zx.parse(p);_[ir.extensionName]&&(S.accept(_[ir.extensionName]),w[ir.extensionName]=S)}catch{sr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(S,(_,E,I,A)=>{if(!_)return as(n,E||401,I,A);this.completeUpgrade(w,c,x,e,n,i,o)});return}if(!this.options.verifyClient(S))return as(n,401)}this.completeUpgrade(w,c,x,e,n,i,o)}completeUpgrade(e,n,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[GS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ux)return as(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${MS("sha1").update(n+US).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),p._protocol=w)}if(e[ir.extensionName]){let w=e[ir.extensionName].params,S=zx.format({[ir.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${S}`),p._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",Fx),g.setSocket(c,d,{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)}};Ux.exports=$d;function PS(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=zx,t.emit("close")}function Fx(){this.destroy()}function rs(t,e,r,i){r=r||Zo.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Zo.STATUS_CODES[e]}\r
16
+ `)),c.removeListener("error",Hx),p.setSocket(c,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(os,this)})),u(p,o)}};jx.exports=Jd;function qS(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 os(t){t._state=qx,t.emit("close")}function Hx(){this.destroy()}function as(t,e,n,i){n=n||na.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} ${na.STATUS_CODES[e]}\r
17
17
  `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+r)}function nr(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,nr),t.emit("wsClientError",d,r,e)}else rs(r,i,o,c)}});var ep=ae(_e=>{"use strict";var N=j;(function(t,e){let r=j,i=t();for(;;)try{if(-parseInt(r(429))/1+parseInt(r(1577))/2*(-parseInt(r(1286))/3)+parseInt(r(1260))/4*(parseInt(r(1888))/5)+parseInt(r(1047))/6*(parseInt(r(1110))/7)+-parseInt(r(519))/8*(parseInt(r(1159))/9)+parseInt(r(1255))/10*(-parseInt(r(1052))/11)+parseInt(r(408))/12===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(na,307505);var US=Object[N(1625)+N(1342)],qS=Object["getOwnPr"+N(666)+"mes"],Zx=(t,e)=>function(){return t&&(e=(0,t[{NNTBw:function(c,d){return c(d)}}[N(1907)](qS,t)[0]])(t=0)),e},HS=(t,e)=>{let r=N,i={rTvTc:function(c,d,u,h){return c(d,u,h)}};for(var o in e)i[r(1382)](US,t,o,{get:e[o],enumerable:!0})};function GS(){return jx||(jx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function jS(){let t=N;return Wx||(Wx=[IDBCursor[t(501)+"e"][t(1391)],IDBCursor[t(501)+"e"].continue,IDBCursor[t(501)+"e"][t(740)+t(856)+"ey"]])}function WS(t){let e=N,r={MDzsD:"error",KMCxc:function(o){return o()},ZxcoY:e(428),nlXRp:function(o,c){return o<c},dRaYW:function(o,c){return o===c},vIBnb:function(o,c){return o&c},CvMHY:function(o,c){return o!==c}},i=new Promise((o,c)=>{let d=e,u={qwZEy:d(428),mdtNl:r[d(1635)],CVRcA:function(w,S){return w(S)},ZTdXV:function(w){return r[d(641)](w)}},h=()=>{let w=d;t["removeEventListe"+w(1486)](u[w(705)],x),t[w(767)+w(921)+w(1486)](u[w(608)],g)},x=()=>{o(Ut(t[d(1774)])),h()},g=()=>{let w=d;u.CVRcA(c,t[w(935)]),u[w(523)](h)};t["addEvent"+d(958)](r.ZxcoY,x),t[d(1821)+"Listener"](r[d(1635)],g)});return i[e(818)](o=>{let c=e;o instanceof IDBCursor&&(r[c(1254)](c(1330),c(1849))?Zd[c(1892)](o,t):(_0x375b21=_0x52e35a[c(1384)+"At"](_0x56c631),r.nlXRp(_0x2b5d33,128)?_0x5315ac+=1:_0x3c1a1c<2048?_0x55d754+=2:r.dRaYW(r.vIBnb(64512,_0x400ae7),55296)&&r.dRaYW(64512&_0x515777[c(1384)+"At"](_0x12db3e+1),56320)?(++_0x487c65,_0x530aab+=4):_0x5edf93+=3))}).catch(()=>{}),ea[e(1892)](i,t),i}function KS(t){let e=N,r={mISLu:e(1775),DZAqY:e(935),aaJHE:e(601),hDrXz:function(o,c){return o(c)},SfeRl:e(1531)+"or",aRcjg:function(o){return o()}};if(Qo[e(1488)](t))return;let i=new Promise((o,c)=>{let d=e,u={oAqRh:function(w){return w()}},h=()=>{let w=j;t[w(767)+"entListe"+w(1486)](r.mISLu,x),t[w(767)+w(921)+"ner"](r.DZAqY,g),t[w(767)+w(921)+w(1486)](r[w(684)],g)},x=()=>{let w=j;u[w(662)](o),u[w(662)](h)},g=()=>{let w=j;r[w(1149)](c,t[w(935)]||new DOMException(w(1531)+"or",r[w(1845)])),r.aRcjg(h)};t[d(1821)+d(958)](d(1775),x),t[d(1821)+"Listener"](r[d(946)],g),t["addEvent"+d(958)](r[d(684)],g)});Qo[e(1892)](t,i)}function $S(t){ta={xxXXl:function(i,o){return i(o)}}[N(1824)](t,ta)}function VS(t){let e=N,r={sduJY:function(i,o){return i===o},vuPqA:e(1863),Nzrmf:e(404),FESXn:function(i,o){return i(o)},VRnvU:function(i,o){return i(o)},cmJBb:function(i,o){return i(o)},niBNP:function(i,o){return i in o},mgVre:e(443)+e(558),yxPho:function(i){return i()}};return t===IDBDatabase.prototype[e(1499)+e(1169)]&&!r[e(1351)](r[e(1525)],IDBTransaction[e(501)+"e"])?function(i,...o){let c=e,d={ipFoN:function(u,h,x,g,w){return u(h,x,g,w)}};if(r.sduJY(r.vuPqA,r[c(1765)]))d[c(1294)](_0x403ea3,_0x11f377(_0x4ecdc5.result),_0x534d96[c(925)+"on"],_0x289d9d[c(1403)+"on"],_0x4199da(_0x471e24["transact"+c(1169)]));else{let u=t.call(r[c(989)](is,this),i,...o);return Vd.set(u,i[c(424)]?i[c(424)]():[i]),r.FESXn(Ut,u)}}:r[e(592)](jS)[e(1212)](t)?function(...i){let o=e;return t.apply(r[o(670)](is,this),i),Ut(Zd[o(1935)](this))}:function(...i){let o=e;return Ut(t[o(1850)](r[o(1428)](is,this),i))}}function ZS(t){let e=N,r={cKhKX:function(i,o){return i===o},BVoWK:e(978),gNqqx:function(i,o){return i(o)},orXNH:function(i,o){return i instanceof o},QEwyP:function(i,o){return i(o)},sDdVo:function(i,o,c){return i(o,c)},piYdg:function(i){return i()}};return r[e(1601)](typeof t,r[e(812)])?r[e(1705)](VS,t):(r.orXNH(t,IDBTransaction)&&r[e(1137)](KS,t),r.sDdVo(Jx,t,r[e(723)](GS))?new Proxy(t,ta):t)}function Ut(t){let e=N,r={qKUXT:function(o,c){return o(c)},pUhsg:function(o,c){return o!==c}};if(t instanceof IDBRequest)return r[e(1079)](WS,t);if(Yo.has(t))return Yo[e(1935)](t);let i=r.qKUXT(ZS,t);return r[e(1945)](i,t)&&(Yo[e(1892)](t,i),ea[e(1892)](i,t)),i}var Jx,jx,Wx,Zd,Qo,Vd,Yo,ea,ta,is,Kx=Zx({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={QlGmk:function(r,i){return r||i},PMIZa:function(r,i){return r instanceof i},ZdifG:t(1716),OLzCZ:function(r,i){return r===i},uzzXe:t(1915),jEzAO:t(443)+t(558),xAUnL:function(r,i){return r(i)},cfGWJ:function(r,i){return r in i}};Jx=(r,i)=>i[t(1700)](o=>r instanceof o),Zd=new WeakMap,Qo=new WeakMap,Vd=new WeakMap,Yo=new WeakMap,ea=new WeakMap,ta={get(r,i,o){let c=t,d={pDIrz:function(u,h){return e.QlGmk(u,h)}};if(e.PMIZa(r,IDBTransaction))if(e.ZdifG!=="KzdST"){let u=this[c(1062)][c(953)+c(638)+"nc"](this._prefix),h=_0x67c39c[c(1004)](d.pDIrz(u,"{}"));return _0x3c8634[c(1139)](h)}else{if(e[c(834)](i,e[c(1811)]))return Qo.get(r);if(i===e[c(1431)])return r[c(443)+c(558)]||Vd[c(1935)](r);if(i===c(1587))return o["objectSt"+c(558)][1]?void 0:o[c(443)+c(1148)](o[c(443)+c(558)][0])}return e[c(1784)](Ut,r[i])},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return r instanceof IDBTransaction&&(i===e[o(1811)]||e[o(834)](i,o(1587)))?!0:e.cfGWJ(i,r)}},is=r=>ea[t(1935)](r)}}),Yx={};HS(Yx,{deleteDB:()=>YS,openDB:()=>JS,unwrap:()=>is,wrap:()=>Ut});function JS(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=N,u={LYXLX:function(g,w,S,_,E){return g(w,S,_,E)},tZNon:function(g,w){return g(w)},PdmCc:d(737),lLFPY:function(g,w){return g(w)},EpdkB:d(1223)+d(980),brTOB:d(1599)},h=indexedDB.open(t,e),x=u[d(726)](Ut,h);return i&&h[d(1821)+d(958)](u[d(694)],g=>{let w=d;u[w(669)](i,u.tZNon(Ut,h[w(1774)]),g[w(925)+"on"],g[w(1403)+"on"],Ut(h[w(1499)+"ion"]))}),r&&h["addEvent"+d(958)](u[d(1283)],()=>r()),x[d(818)](g=>{let w=d;c&&g[w(1821)+w(958)](u[w(1031)],()=>c()),o&&g[w(1821)+"Listener"]("versionc"+w(1086),()=>o())})[d(1585)](()=>{}),x}function YS(t,{blocked:e}={}){let r=N,i={WGOIf:r(1599)},o=indexedDB[r(1036)+r(1507)](t);return e&&o[r(1821)+r(958)](i[r(650)],()=>e()),Ut(o).then(()=>{})}function $x(t,e){let r=N,i={fPxjp:r(588),iOVPP:function(h,x){return h instanceof x},hTJbm:function(h,x){return h===x},DAhmV:r(1357),UsiAu:function(h,x){return h!==x}};if(!(i[r(966)](t,IDBDatabase)&&!(e in t)&&i[r(1112)](typeof e,i[r(1687)])))return;if(Xo.get(e))return Xo[r(1935)](e);let o=e[r(1120)](/FromIndex$/,""),c=i[r(1840)](e,o),d=Qx[r(1212)](o);if(!(o in(c?IDBIndex:IDBObjectStore)[r(501)+"e"])||!(d||Xx[r(1212)](o)))return;let u=async function(h,...x){let g=r,w=this.transaction(h,d?g(1437)+"e":i[g(1045)]),S=w[g(1587)];return c&&(S=S[g(537)](x.shift())),(await Promise.all([S[o](...x),d&&w[g(1915)]]))[0]};return Xo[r(1892)](e,u),u}var Xx,Qx,Xo,XS=Zx({"node_modules/idb/build/index.js"(){let t=N,e={BaFVD:function(r){return r()},SWWpe:t(1935),TNmuh:t(1037),WsDwY:"getAll",ZSbjx:t(602)+"ys",FLxLA:"add",WHqiH:t(445),uWAQe:function(r,i){return r(i)}};Kx(),e[t(1307)](Kx),Xx=[e[t(757)],e[t(1396)],e[t(992)],e[t(1103)],"count"],Qx=[t(1313),e[t(1630)],e[t(1398)],t(1134)],Xo=new Map,e[t(1265)]($S,r=>({...r,get:(i,o,c)=>$x(i,o)||r[t(1935)](i,o,c),has:(i,o)=>!!$x(i,o)||r.has(i,o)}))}}),QS={idb:function(t){let e=N;t[e(1147)]=Promise[e(826)]()[e(818)](()=>(XS(),Yx))[e(818)](function(r){return r})}},Vx={};function zt(t){let e=N,r={XmYRd:e(774)+"1"},i=r.XmYRd[e(654)]("|"),o=0;for(;;){switch(i[o++]){case"0":var c=Vx[t];continue;case"1":return d[e(1147)];case"2":QS[t](d,d.exports,zt);continue;case"3":var d=Vx[t]={exports:{}};continue;case"4":if(c!==void 0)return c[e(1147)];continue}break}}function na(){let t=["yw5ZzM9YBvq","C21KBwm","BMvY","uMvHzcbWyxm","AgfZ","D3jPDgvvAw4","y29Uy2f0","B2zMBgLUzq","vg1mCKC","EeXgD3G","Bwf4twvZC2e","zw5JB2rLrNi","DhDVCMTdAge","Ahr0Dfi","y29UBMvJDfm","DhjHBNnHy3q","BMv4DcGPigm","Dgz6sxy","vvDrzxa","y3vZDg9Tshq","CffgBfO","u2j2zxO","B2j1zvG","DgfIyxnL","qxjlBfC","DeLK","C2v0u3rVCMe","CxnqvKy","DwL1y1C","B3bLBG","BMrLEa","yvLeru0","AKfgA04","y3bmtxu","tLHyt2e","y29UC3rYDwm","BwvY","qvHWuLy","wKn6Bwi","vePJrMu","u0r2Cvu","BwDwCMu","BvHdrNm","r1fYD0i","seXlvLq","BhD4uNq","Cez4DKm","qwjVCNrfCNi","AgLNAa","D2vI","x29Ut3bLBG","zLLAwhi","EfHhy3O","AxjLza","A2neEvK","EwHvvgK","wLfsv0y","AM9PBG","AwXK","zNjVBuHHC2G","Cuv3qum","x2n1CNnVCK4","zNjVBNrPzxi","x3nLBMrby2S","AuPTtNC","t1PSEfa","lcbTyxGGCMu","x2jPBMfYEvq","y3r4","A2v5","D0vwvwO","CgfNzwHPzgu","shbst2S","turSB3e","yuTLqKC","yM1Iq1m","EvD2qvK","AKLoDw0","C2fNzq","zvfPALy","EvbSyui","A2v5CW","q0Xpu0LorW","x2rLyNvN","s2P5rK8","CKzLz0u","EMfSrLu","u3jurvi","whP1Afe","wePjs0u","qMnvB1O","q1fSCwS","u3zTDxK","nZy5ohHoy21nDG","v2PxshO","DgHHBIbSB2m","wfDJD0K","ywDLsgLKzq","BwLUAvbYB2C","zfzovfO","A25XqNq","y2f0y2G","AxmGDw5Kzwy","C3rVCMu","DcbVzIbYyw4","jMPZy2fSBgi","qNP4DMi","vxzssxm","svj3A3C","BwfW","tMv6Cuy","yxnZAwDU","ChPjAwC","BMvJDa","AvvHswu","yMXVy2TLza","uufMwem","y0TOs1G","rwXruK4","zNjVBujPDhm","vfDlsLy","zxjFywnRx20","DwjpEKm","vLDuyMW","q0reDvq","zMTrv1C","x2LZqNjVD3m","rgTcvKe","uLjpuG","tMfTzq","swvhExG","y2fSBa","DevtzMq","D2nctva","v1vzD0K","t3HTwMu","Ef9MCM9UDgK","qxfjAhu","D3nZoI8V","t2vkugu","q2PNAwy","zgvMAw5Luhi","x3DHAxq","q3Pzu2i","wKD0yu8","x21PBMLoyxy","rKX4tee","vgfN","C0Xf","B3bLBKrc","AKHlyLG","tur6C0q","AMvJDfn0B3i","vw9fuhG","y0LxEhO","x0rctMfTzq","CMvQzwn0","zvvYBa","zcWGDw5RBM8","vKfWr0C","Dg9cExrLC0W","u2vYDMLJzvC","tu51DfO","whDrwu4","z1rPBwvVDxq","q25Iyui","x3bHDgHlzxK","zwnVBM5Ly3q","CNDqsKO","z3zwqvy","CND0ruG","C0vuBNm","qvzZBMS","vu1UrK8","A2L2B3y","BhPSCfu","BwvZC2fNzq","qunUD0K","rKfXsNK","q2Hizxe","CgvYC2LZDgu","yw1Lu3bHy2u","u0zQtgu","zhnyCg0","x2n1CNnVCK0","CLzHBhvLCW","uvzMr08","r2Tvr28","wwrirLa","yxb6s04","vNPgt0m","thPIy2C","x29UvgLTzw8","EgL5yKm","y3vYCMvUDeK","twjuEwm","vefHv3e","s3PqywO","zNjVBu51Bwi","y3jLyxrLrxi","B1LWDKG","rxr4t3K","qKDIrLa","refOBvy","D2fbyu8","vNvyy0K","y0HdD20","t0HjEMm","y2T5v2u","q0LTv2m","B2LozMm","DKrpvfe","B3jpBMXPBMu","z2vY","Dg9Y","zhPnBMi","C29Tzq","u0PeAK0","Eg1kyvG","AxPnBvi","sMrItfK","z05XCxG","B1jiu0y","rvjbwwS","AxnAzxjV","A2f4y3m","tNPLDva","yvvtwwK","yNLL","zMLSDgvY","AgvKtwf4uMu","txfpsKW","s3PKu1q","C2vYDMvYvgK","ihzHBgLKigq","y2vZC0HHBMq","Cw9Z","CNHACee","BwfUDwfSihi","DMvUDa","BM5Ly3q","A1D1t28","C2XPy2u","s0nVwLK","x2nVBM5Ly3q","rvvUtvu","uK9fv28","Dhj1y3rVCIa","A1n0yxr1C0m","vw5Oyw5KBgu","u2XwC2e","x25HDMLNyxq","r0j6ueq","x29UugfNzu4","zfvKwha","AgvHzgvYCW","tLz6A3O","CNjVCK1LC3m","wxHqCwG","u3j3t3i","weH3sha","A0XXDfm","D0zuCfq","EwDUsKu","z0jrDLm","Dfrzsva","ENfwqKq","wfvMuwm","ALvcDeu","vhjRuLm","BwvZC2fNzv8","DuryCMy","qM1MvuO","yKXrr3q","q3vZDg9Tq2W","EwXPtum","CfzHDxG","C3rVCcbPBw0","A0zczeK","qK1yv0O","tNv0vgS","tNPYBwy","CMvHC29U","A0Dpqum","DhzjsM0","sKfjzui","qMnWt3C","wwHVz0C","AfnRsLG","zNjVBunOyxi","CMvZDwX0","y29TCgXLDgu","zufJAW","DgvmB2Djre4","x2zVCM1HDeu","B3nLrxzLBNq","uNzqzKC","AvzuCNe","u0D4uvC","CMfUzg9T","EefvBKW","z29Py0W","CK9Xy08","DMr6wKq","ENzjBgS","y2XVC2veqG","AwrI","C293veG","q3zJrhG","x2TLEvbHDgG","z0nnswK","reXNEvm","svfirwK","CM92AwrLihC","DxnLCKLW","qLL2u2C","ru9XBgm","B25LCNjVCG","BxPqs1a","uNzYywS","AwvUwxi","zw5HyMXLuw8","qLzHtw0","Ec1TC2CTCw8","BKvirfm","wNvNBKy","tK1qEM8","DxP6wgu","CNzHBfzHBhu","ANPizLm","ugXsr3e","s3vHBLK","CxHwAhm","ueDTBNO","t0Puy3u","t1bftG","Bfrnug0","ywrKrxzLBNq","sfbmrgy","B29UEgO","EhHywgW","ufnbshO","DLLvzNC","vePet1u","wLL3q2m","uKrbvhm","D0f3z2C","r0DNte8","vMDzDwS","yLzot0O","BfrywK8","BNn4ufi","wuf0A0m","DejNC0i","thjfDee","x2rPC3bHDgm","vxnPqxu","ChrVCG","tLnYreS","B3bLBIa","vKrKv2W","u2zLuMW","BMCGzMfPBgu","B3v0sw50zxi","AgPHt2y","yKLREK4","yxbWBhK","BxHjCMK","ihrVihjLDhi","tvDRAKe","uMnjuLi","B25VCgvU","CLr3rMS","mhW0Fdf8m3W","u3HIrvC","yxKSig5LDhC","Dw5KzwzPBMu","zNjVBuj5Dgu","ignVzgu6ia","DwvMzxq","zw5fDMvUDa","y3vYC29YlNm","DwvIrLq","x29Uq2XVC2u","DeX5zvi","CMvJzwL2zwq","Bg9N","v3rbyM0","thD0C24","DfPQuuC","x2LUAxq","rw5QrNm","sgTYr2K","svnNExO","C3rYAw5NAwy","B2nRzxq","wvLUDgi","D29fshG","y2Prqwi","qLrowKS","ywrRu04","CgLUz09Uy2u","Cg9TuLu","EgPfDMW","ntmWwgretfvx","BMCGB3iGyw4","yMLUyxj5","tMXOuu0","C2v0","zxj2AwnL","thrjq1i","svPlDxi","B3jRig9MzMW","D2fZq2XLyw4","rxzLBNq","ywDL","rhjMv20","yvnSs0O","ANvjuMG","z2v0sxrLBq","zNjHBwvuExa","tg9Nsuq","yxrLq291BNq","tK5uqNC","te1LCgu","Aw50zwDLCIa","C0TREwy","zKzjwfm","ALDKyKO","u2TPCcbWyxm","rxDUvfi","zg9Uzq","zw50","De1HBMfNzxi","x2LUAxrqCM8","svDvrve","AfDRzvy","yNrlAuC","twPSzhK","u2XWtgW","Dg9cExrLCW","zgHyq2S","sNzYCgS","t0HpCgS","Ce9rr3u","B2zMC2v0","tu9TyLi","zxjYtM8","Bu9Zy1K","vg5NBgC","u1Lkq2S","z2v0","tunRChi","sfrpB2m","B25ozxr3B3i","x1fVu01HBMe","x3bYB3rVy28","tffWCfe","BfjAzem","EwnArKu","rLDQue8","CfvOC2C","BeHHBMrSzxi","v0Dhsum","z0HXuxe","yxv0BW","C3Pnu3O","BvDsAw8","CuzXvKe","yw1LoIa","zwf5vK8","turez2u","v1ruvM8","y09Wzw4","CNnVCL92ywW","DcbSAw1PDa","zxrxB3jRq2G","EwnTrve","Dg9ks2i","C2vYDMLJzs0","uMPkuMO","q3vZDg9Trxi","mtG3ody0ntzeEw1SB1i","vxryq0S","vhHTCeO","DhjPzxmGCMu","yNL0zuXLBMC","rxPNEve","zLrKA1K","zNDUwuW","z2vtEw5J","y29SBM8","CIb0DhDjra","r3bpu3e","Ag1QzNC","EvHktvK","BgvY","DezcCvu","C29YDa","rfzMvhK","C3zwC3e","sfHMBwe","C3vJy2vZCW","nda0ntq1svz1yLvc","tKTVAui","DKfer1m","DMfS","y3DVr1C","tKDFrvjst1i","CLzKAhy","DMDRtgC","AMP1AhK","AenSB3nLrxy","CLDtr1m","uvHWrNu","BgHOzxi","B1fJrKC","B2jQzwn0u3q","sgj3sM4","zgvSzxrL","uK5ltha","zw5HyMXLvhi","Dhr3Awq","zw1PDa","zgvJB2rLzey","zMH0u0K","Bg93","y2XLyxjtDg8","wefNAvK","Dxrjza","BezSDxnO","AxHdCey","AwDHDg9Yt24","x2LUDgvYDMe","y3vYCMvUDeu","vxLYB0m","AxnbCNjHEq","mNW0","whb6EMW","DuzgweW","CvroBfK","mxW5Fdz8n3W","Ag9vuKS","ANbHvwC","rurswei","whvPrxi","zgDPCLO","z3fOyNq","D2n2wxa","AefJA01LC3m","zxH0zw5ZAw8","zgv2AwnLx2K","EKnMvwq","AxbpuLO","x3bPBMDqB24","Auv2rwO","vLbuz04","DhbizwfKzxi","sM5Qwg4","DhLACM8","BMnLq2XVC2u","zunADfK","CfP4A0m","AevYCM9Yrxy","wLz1vMC","BMrWB2LUDca","y2XVC2uSihC","Fdv8nhWY","ywXty29Wzq","y29UBMvJDca","rwHmy1q","z01xEeq","C1Litvq","AwXLtMfTzq","zLHuveG","ChjVDg90Exa","BIWGAg9ZDg4","zw5JB2rPBMC","lcbxzwjtB2m","y3ruAw1LB3u","C2XQCg0","Cu5WEKi","B2nRzxrtDwm","ueLWuvK","vuLgCfm","CgXLyxnLiha","BLj2tum","Eg1ftKu","B254B2C","AgLAu0m","zsbHihn0CMK","BvLuCLG","x2nSzwfYugK","mJrXwevPqKi","x19LC01Vzhu","uNLjq20","tfbAA0G","wLrKwfy","y0LcCue","uNrWvKG","vxj4s04","se1qyK8","tw5QDNq","EgvnDwW","qwvZzfq","yMfSrxzLBNq","zMLN","y3jLyxrLtwu","t0HLugC","rKLmrv9ot1q","q291BNq","Aw5KzxG","Dgjbvfm","su5tvefova","rMXNreG","y3vYDMfSDwu","r0fbshK","se5uCxu","ig1LC3nHz2u","CMvHzhLtDge","x3nVy2TLDa","zwDcD2e","BMDuAw1LCG","vNLRB2q","AxnrB1nnzxm","uhrhr1m","AKDStxm","x3jLywr5q2W","tM9luLK","C3bSAwnL","tgfvEvm","sfrArxO","B3jLtMfTzxm","s0zNugO","z2nqDuu","zeP1sva","AgfZt3DUuhi","CeTPuxa","sxn1rNC","D29yzvq","shzMuee","C2HqswW","yNvMzMvYzwq","wfrrB1u","AgvHzgvY","BgvUz3rO","CgLUz19VBMm","B2nRzxrgywK","ChbL","EfzMuve","vwPnsLm","vuDjBw4","Cuftzfq","DxrMofDYAxq","v2LUzg93","ruf5BLe","CgP1tuS","uezZvMy","yxnL","A1bqqKq","Auvzr3m","zv90Aw1LB3u","CMvHzg9UBhK","EKzhzxK","qNjuuM4","BgjpqvK","ExHqAg8","DgfYz2v0","q1LdC04","vvnnBuO","y2HLy2TdDxi","uMLdseS","wg1HtMe","AvjVDNq","ELLMr00","ywjVCNq","z2v0qwXSs2u","Cgf5Bg9Hza","Ee1XvgG","mxWYFdv8m3W","Bhm6ia","A2fotfi","Bwr0tMW","y3jLyxrLuMu","u0DmBfO","AuTfDwG","wgfQzui","ExnUt2G","C3zdquq","EeHjEwK","vvLvB1y","AujJu2C","BxnNsuq","C3vIC3rYAw4","t2z3wu0","ELfrswC","Evz0ueS","u3bbsge","wMPes00","Dgv4DfbHEwW","wLnfq1G","A3HIA0K","AMPxANi","sxrjCeW","qxbLC2S","Aw9Ul2PZB24","vwTJwKG","q2fmCLm","wfz2BNu","zw5KCg9PBNq","CwLjshO","sLbNufO","z2vjBMzVu3K","sMjZuu4","Eezsu2G","s01dEgm","EMTRv2e","CMvKDwnL","m3WXFdj8nhW","CfzJCNG","Du16ufO","CfDfvuK","y3jLyxrLt2i","zxjYtxnN","v0Dpswy","r3Lbs2y","y3vYC29Yx24","yxbWzw5Kq2G","C3bSAxq","u1HQswS","zM9Yy2u","x29UrxjYB3i","DLLNC3q","ywnRtxnNswq","BfrPBwvVDxq","AgHxs0y","B0fXuMG","DwjpAhq","wwrxu1a","uuzXD1O","B3bLCNr5tMe","rhHtBem","x2rItMfTzq","tfLytfG","vLjUDLu","rNjVBNrPzxi","Dg9tDhjPBMC","vKLXtfa","DxLRtNC","BMrWB2LUDfq","x21LC3nHz2u","wgT6sg8","z2vrDwv1zuW","x2DLBMvYyxq","CMfTzq","x3vYBa","rwLhzMC","z05TC0W","ywfkseu","DLDUq3e","y29UBMvJDgK","rufnExu","C2nYAxb0","tvrPAKu","x29WDgLVBNm","BuXKruq","zMzLCG","zNPKt1C","rxbKA0i","Evrwq3u","BxHKv1G","Den2wMy","AxnFywnR","uhLQsg4","CYbWyxjHBxm","Du5WyvO","ALjgz28","Cgf5Bg9Hzfq","zePAC3C","CxDArxK","BNrLCG","C2v0q3vYC28","ihn1y2nLC3m","CMvJB25Uzwm","vgThvxy","yvrKDKy","teXRvKq","vK1uwMK","CufmsM0","uwX4uMS","rNDbq0C","CuH3Bwq","r2nZAu8","BNruCMLLC0m","twXStxe","Egnbwgm","zxq9DxrMltG","CgLzzgC","yM93uvG","zgvS","BeXgufK","r0zZzw4","Au1YD1q","zgLZCgf0y2G","qujwv2m","q0jxr2K","wwH1Bfe","vvPxrgC","BwzKA1C","y3jLyxrLq2W","qMPQAw4","y2XVC2u","B25SAw5L","EvP2tgW","y29UDgLUDwu","nhWW","BxngEwm","vwjkD1q","sK1pEMO","vNfqzu8","rgvmzLa","tKfusvzfx0u","AxnszwfKEq","sNreBNa","t1HtsxK","ExnfC28","wwrRCKu","v2TwDxG","EfD0rNO","DK5dqMu","B3rey2O","u1DxCgu","DLnovM8","x2rYB3bhBg8","q29Qs3K","reLtEvK","C0jf","EuHVEei","yxDdCey","CgfRwxa","Dw5ZAwDUzwq","CMvTB3zLrxy","tKLyv0q","x3jLy29UBMu","ywWGy3vYC28","Dg5by0G","q2nYBgi","zNDZxZeUmc4","mhW0Fdn8mNW","x3DZ","C0nVDw50zxi","rgD5D3m","AePhuuq","CM9YrxzLBNq","BuLlDMi","rLLws0C","DgvZDa","q0TOrgC","DKX1zLa","s0fRshG","sM5srvy","wfLiAhK","y3jLyxrLt3a","qKnNqu4","BgLUzw5V","BMz1sxu","y29Kzq","wwrbrgK","uMDTzxe","BKvswKG","qwf1Eha","CgLUz0XVC3m","uwDNs3q","zxjFCw9Z","DxrVuMvJB24","B25Uzwn0Aw4","DMvY","ChvZAa","Aw9UvgLTzw8","y3vYC29Y","x2HHBMrSzvi","mhWXmhW4Fde","uNfRzwG","B25fCNjVCG","wevtExC","Aw5N","qLzVv0S","EhfiD3u","BgLZDgvUtMu","CvvyAwW","zxjFAxnFywm","wePpuMS","DgHLBG","CvjkquO","thPxBNK","uuToEhq","wMnIDvG","C3rZEuW","v2vIu29JA2u","DgLTzw91DcW","CMvZB2X2zq","r1vTzvu","zfDNBNu","t0L0DMW","y09cyMe","BNrbBMrvCgq","qMnevxa","mNWXFdr8m3W","t0X6q1O","C3jJ","igXHCMDLCIa","DwHNsMS","mdaWmdaWmda","rw9PEKC","CgLUz0LUDgu","wgjQwhi","C2vUza","r3vzueC","whv5Aw8","s3PSDwe","q2zvAKi","weHYzMG","Dg9oDw1Izxi","v0rrq0m","CM92AwrLige","twvZC2fNzuu","BenZuui","D3rACNC","yxjRrha","x2rPC2nVBM4","uhjPBwfYEuS","zuzpve0","rKncv2C","l3DZl3yY","ChjVDg9JB2W","BwvKAwf0zwW","C2DPza","ugzvAem","ywzL","Bw1ds3q","CxD5BKq","vvjTse8","reiGzMfPBgu","CvHcALC","C2vUzf9Hy2S","z1jSz0y","zhr0qLa","Dw5RBM93BIa","D1jir2S","rvLgswW","thnhsha","r2PqzeW","x0vysvnu","wNPNtxa","C2rntM8","yMLUyxj5vhK","EMjUAgq","C3vyqxe","EMLjB3q","A2frtwe","EMLJtfm","zw50zwqGDhK","DgLUzYbZzxi","D2LJvge","x29UtwvZC2e","B25dBg9Zzq","u0TMq3u","BgLTAxq","rLDt","C2HPzNq","zND2zeS","Cgu6ia","B25nzxnZywC","Dg9VigXHCMC","rMj6s3i","Ag1Wuu4","D1zsCg4","igzHAwWSig0","rLLqteS","qvvPEKi","B25TzxnZywC","DgHwseO","A1DZweK","u0Hewxu","DePRsvy","ywXSzwqGBxu","BwLZzq","uNb6zuO","te1fDgS","qLj3rNC","ChbLwxG","rMXWswC","tw9KDwXL","zeLry3K","Cg9PBNrbBMq","zw50tgLZDgu","D0jWBgy","igfYCMf5yNu","Axnby2TdBgu","B2XKvMvYC2K","rLjptLrjrvi","ELPLtM0","vwzUBfm","zxmGCMvHy2G","svLuA1C","wwfIugm","surTAwG","C3rHCNq","ywrK","zxjYB3i","ru9KtvC","BM9Uzv9UB24","ywrKt25L","D2LSBfjLy28","zfzprKK","CMvZzxrfBMq","z2v0qwXS","Dev2zw50","AxnrB1nby2S","DgLLC2i","rfPbCvK","uKv0yva","twLZC2LUzYa","ruzTqwW","v3Doyvm","u0H2Aw0","uuzmue4","z2v0u3rVCMe","rNLwq1a","yw1L","Bu9wugS","zvzbr1K","tgLZDgvUzxi","sur5tNm","q29RyLe","Bg9NsurozxC","DwL5ALm","ANPJtuy","Aw1LCYbPBIa","qujQveC","Au9wufa","ve5qthG","EhzNr0q","tg9JAW","Ae1LC3nHz2u","v1bdA2m","lcbOB3n0BMe","zev5quy","ihzHBgLKihm","C2zuAhK","igzPzwXKoIa","ywnOzwqSihC","zNvUy3rPB24","zgf0yq","zwvKzwq","BujrAMe","x3bPBMC","x2LZtwLUAvq","x2LUAxrhBg8","Ce9jCM4","BMCGDxjSoIa","x2nSzwfYvgK","Ag1jCNG","rKvtwg4","BxfWqLe","A2v0ignVBNm","v3neD1K","m3W0Fdv8nNW","y0LrseC","r2DewNu","CgDvDfi","D0rJD0K","y2v4EK0","r25gy3m","yMXfuwC","BNrfBMrWB2K","D3DwEvK","B3nLza","CgfYC2u","EvzxvfC","y2TAz0W","swrKBK0","BhrPCgXLihq","zw1LBNq","zg9Uy1G","uxDoquq","v1vtq20","EsbJBg9Zzwq","C2j0svm","q21Oy1u","zxjFCw9Zx2e","uejuEhC","uKjHCeO","DKHiruS","CMvZzxruCMK","DKrREhK","C1PNtu4","CMvUDevUzha","ihrPBwvVDxq","sK5Rtfq","Bg9IywXty28","BLjmzvu","q0Xpu0ve","rvjst1i","vw5PBxbSzw0","ugrTq2m","EvfJBLi","vgHRBfK","zfDVCMTLCKC","rNjZrfa","zgvSzxrLrge","z2v0s2v5","EvLvrvG","DxbKyxrLq3u","yNL0zu9MzNm","Bwv0Ag9K","Ag92r0m","CMfTugfYyw0","CMLLC0nVDw4","zLb4ANa","C2vUDa","nMTNzuL3wq","CeDeA3O","ywnOzwq","v0vgsMi","DKTsyMC","nta2BKzwsM9s","B05ZD04","qxHlqwe","CNzHBa","uw5wyLi","yw5Hz2vY","Bvf6y0y","vgLTzw91Da","zw5HyMXLqxu","x3nLCuLK","x3fVC0rc","ywXSB2nvBNm","BhDcBhG","DxDxu24","yuHeAuC","C2v0sxrLBq","suPPzei","q09otKvdveK","DeLUDgvYy2u","wK9zCLG","BKn3tKO","BMnVzgLUzW","y2HLy2Tszwe","D3jPDgu","CNDmyMe","rwjWDMi","B25szwnLAxy","CuTvwfq","DvDquKG","ANzXDgC","BMfTzq","CgjICdi","suT1v0O","D3L2CMm","AgfUz2u","s2zSCNm","DhLWzq","tMTZBK0","BuTOBNe","wej0rMC","BwLUzW","zwn0","q29Kzq","shPWu2q","s3jhEui","Dw50","s01wt3y","qNnMy20","BxDMCw8","z2u6ia","BNvus2y","wLnIANG","B25mAw5L","Dg9cExrLC0i","su1wtfm","CNDqr0u","B25tDg9Wsw0","CMvZzxrdB3u","ndi3odiXohLsq0XXwa","uhfhz0W","AfrkyM0","u3rYyxrLz3K","Ce5AugO","EvjLy29UBMu","B2zM","D2H4r1m","EufpExG","AKn0sMC","CMvWBgfJzq","twXsyvK","CMvWBgfJzui","swr3D1K","uhzxweC","tvHutvm","z0zKzNu","AxnmB25N","B1jsC2G","D3m6lY8","rersu08","DMLJzuLeig8","BwnQBxK","tuvtu0fhrv8","y2XLyxi","y29UBMvJDa","yxnJCMLWDa","uuv3Eva","uxvLDwu","DMfSDwvZ","B3b4EMu","ihjLy29UBMu","Dgv4Dc9Qyxy","Cw9Zx18","vev4t2m","wLzky24","Cgf5Bg9Hzeu","zxHWB3j0CW","B3jL","AerYwhO","Ahr0Ca","yMfSu2nVCgu","C0TurNa","C2v0zgi","yunxrxK","DxjS","wLftyw0","zMvY","tKDVtLe","mtC4nJi1n1npDNHeqW","vhzAswq","vxnAzK0","uKjlzeq","B3vUDa","B3nYs3C","Cg93","u2rmuMC","z3DervO","yxbWBgLJyxq","Aw9U","rhj4Bhe","vfzgr0W","uuzTsxO","DxbOBLi","zM9YrwfJAa","wuH4sgu","v3Pyrhy","DvPSq0S","CKzss0C","Ee9Ksfi","DgLTzw91Da","qwPHu0e","B25pCgvU","t1bftL9fuLi","vNbAqMm","zKrUsNe","tvPeseO","BgrZzfG","BNDitxq","C3rLBMvYCW","u2vXsuq","CgfNzxnOB3C","DKrHrxi","Bwf4uMv0CMK","shj0sNK","sLnptLa","sxLZugC","vxj4yuq","tufuuwq","DhjPzxm","uKvhweu","tvjIEMy","ywnRpwzYB24","AMnpA0i","yuDNAve","sgnKrei","x2HHBMrSzva","vuHYzMq","DefoBvm","rLPWwwm","qND3qKW","rff0vhe","Aw5JBhvKzxm","D0L5Afu","CMvHzfvjBNq","CxjLExi","tgjVB0q","veTUCxK","DvL0Eee","AgHxvMe","ue9bBgW","EM9RqM4","EvPODhe","DxbNCMfKzw4","wejcrMC","vMDxrM8","nhWXFdb8mNW","tvrUBwG","uNL1q0C","yxv0B21HDgK","EKLYuKO","quXm","seTJANu","t2jQzwn0","AuX0ze0","EgXsswK","Ewz6z08","CMvTB3zLq2G","BeD1y0K","CNnVCKzPBgu","BM93","yNL0zxm","wLf2zhC","Bwu6ia","CenWwKu","uhL4r24","B2LUDfjLywm","zMPYrey","Cg9PBNrdB24","x2rLC3rYB3K","B0DTz0u","uw1QExe","seLiuem","x3DZsw5ZDge","q3znsfK","mte5otuWDurKweHx","EhfeEwu","q29wzKS","B25JBg9Zzq","rhHdyw8","nZyYoe9uCufLAq","B3rnEgG","x2LZv29YA2u","yMLUza","BxnN","DvDbuwu","zKzVBgO","C2vYDMLJzq","DgXMyuO","x2nYzwf0zvm","yM9KEq","ign1CNnVCIa","AwXLx25HBwu","C3vIyxjYyxK","Dfrmz2G","qKD2Dw8","qMT3yMi","y1jSDMy","y3vYC29Yx2y","DMfSDwu","tKHqAKC","x2fKzfDZtgK","s09lyKq","yNjut0i","C0XPC3rLBMu","rxjYB3jdB2q","nda1CLf1se1o","vuDUDMi","vwTyEKi","qvrzAvq","DxnIsgm","x2n1CNnVCKy","tvjrt04","BefetvG","AxbgB04","DuTAwuy","vxbKyxrLq28","DgLLCKPtt04","zMLSzw5HBwu","qxzLCNq","wg5qqMG","zxf1ywXZ","wvbIuwO","shj4uuu","D2niyvi","Dgv4Dc9WBge","zw5XDwv1zq","qMfgvKq","BMDLza","zMzmAw5L","vM11rLm","BML0AwfSAxO","CgLUz1rPBwu","Chv0","yxGGCMv0CMK","CKnPre4","AvnAuwC","C3zXzxe","tKnYv1m","Agzgq28","uhzPufa","ihbYB3rVy28","Ae9Wzw5fDMu","Dhr3Awu","wvjvBMq","A1b4ueq","txjAEKy","v0nNt2G","x3bPBMDmB3m","tvnzA3m","vNnjshC","qNj2wMS","v2riCxa","yxKSihrYEsa","ywnRDxbfBMq","zw5NDgG","vKPMyuG","uMvJB25Uzwm","ywrKq291BNq","rMLXAu4","D092Cvy","Cw9jEu0","B3bLCNr5","ELjUDLO","EwP0Dxy","u1PJuMy","rhnkru8","Ec1TC2CTy3u","zxfmAKK","zxjFBxnNAwq","sKLYvwq","BMLctLa","D24GCMvHC28","y2HnyxHdB3u","x2XPC3rLBMu","uNneEwG","vxHrug8","C3rYAw5N","Ce16BNq","ENHcr1m","EMnvEgC","rhfvsLu","D0HWtgi","BfbivwW","ug9Szwy","vNLKB2u","zxjHDg9Y","y29UBMvJDeu","EfDwy1C","x3bYzwzPEa","q29UzMLN","qw1VDw50","BNvTyMvY","Dg9hzw5LCMe","z0jutNa","B2fK","zw5rA2G","yMrFzgLK","y2uGBM90igK","AezxCva","zxDmCfa","zcbLCNjVCI4","CLr2vgm","v3vgwKe","y2HHCKnVzgu","yuDjCMO","v3HmtNa","wwX1BMS","qxrMDMS","q1HLz2S","sePwz0K","ywr2yw5Jzq","yuzgrNq","Dg9iyxnO","uuDtB28","qNnICwC","ve5TDwG","y3jLyxrLrwW","v0HXAuG","Aw5PDcbrB1m","sfjHCLm","vM1JA2S","suvtx0vsuK8","BMv3vMvYC2K","y291BNq","yMfJA3vWigu","swHqs28","CMvXDwLYzwq","ExbL","x2DLDeLUDgu","v2LkvMe","Bwf4tg9ZC0m","yNvMzMvY","CK1YqvK","uwvWvLy","BuzWvfe","EfvZzuvUDG","Afbltvq","DNrvBey","u2nYDxy","u2nirwO","v1Lhzuy","icSG","tu1Qrg0","ywDLu2HVDW","C0vjCwi","tgLTv2y","Dg9mB3DLCKm","y21kqMi","CMv0CNLdB3u","CLjtDfO","AKv6qu8","zgrjrcWGzgu","B25tDgfYDfi","uMvXCuG","yLz2rLu","z2v0q3vYCMu","CMvHzhDYAxq","x2HHBMrSzu8","CxL4r0y","v2HiDe0","ysbTDxn0igi","sKzKsgq","qvfYwNm","CM92AwrLihy","mdaWma","uMTQsKy","B0TTv2S","DhfssLu","C3fxzvO","shnSv1i","z29PBMCGyxC","sgXNshi","x2LZtwLUAvC","mxWZFdv8mNW","BgLUzq","B3LTrxi","x2LZsw5PDa","ywnR","ChjVy2vZCW","zuLouKS","C3nHz2vfDMu","ywDLrxzLBNq","x2vUzhbVAw4","CYbPBNn0yw4","r0fruNe","t3zXr0e","y2HnyxHuCMK","tufyx1jfvfi","BKXPBMu","y0jHyMK","AM5UrvG","CMfNzvn5BMm","A1rSAvO","vw1IrLK","t3bLBKv2zw4","q01WDhe","DunUwNG","CwDmqKO","B29RDgu","x3jLBw92zvC","C2v0y3vYC28","yw51Ce1LC3m","CYbHBhjLywq"];return na=function(){return t},na()}zt.d=(t,e)=>{let r=j;for(var i in e)zt.o(e,i)&&!zt.o(t,i)&&Object[r(1625)+"operty"](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;zt.o=(e,r)=>Object[t(501)+"e"][t(562)+t(1342)][t(1615)](e,r)})(),(()=>{let t=N,e={QEnEk:function(r,i){return r!=i},mURxk:"undefined",WzXDv:t(918),RvPfG:t(520)+"le"};zt.r=r=>{let i=t;e.QEnEk(e.mURxk,typeof Symbol)&&Symbol["toString"+i(1631)]&&Object.defineProperty(r,Symbol[i(672)+i(1631)],{value:e[i(1176)]}),Object[i(1625)+"operty"](r,e[i(1780)],{value:!0})}})();function j(t,e){t=t-400;let r=na(),i=r[t];if(j.RnobXt===void 0){var o=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",w="";for(let S=0,_,E,I=0;E=h.charAt(I++);~E&&(_=S%4?_*64+E:E,S++%4)?g+=String.fromCharCode(255&_>>(-2*S&6)):0)E=x.indexOf(E);for(let S=0,_=g.length;S<_;S++)w+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(w)};j.HKiJyZ=o,j.wKWNds={},j.RnobXt=!0}let c=r[0],d=t+c,u=j.wKWNds[d];return u?i=u:(i=j.HKiJyZ(i),j.wKWNds[d]=i),i}var Pe={};(()=>{let t=N,e={sKTFp:"close",CnbaB:function(a,n){return a!==n},YyAcv:t(1788),Kflrs:function(a,n){return a(n)},vHHEK:function(a,n){return a+n},XESyw:function(a,n){return a+n},QwNAD:function(a,n){return a+n},wcvYp:function(a,n){return a+n},jnnEX:function(a,n){return a*n},CMptq:function(a,n){return a*n},BCgAN:function(a,n){return a|n},yVWTW:function(a,n){return a&n},fFolj:function(a,n){return a>>n},OeJPe:t(1325),uphnR:function(a,n){return a(n)},hWkeV:function(a,n){return a(n)},mWRio:function(a,n,s){return a(n,s)},EAynQ:function(a,n){return a(n)},qwynD:function(a,n){return a+n},ZOYrX:function(a,n){return a(n)},MDDge:t(1445),SZcRf:"ffff",AQrZs:function(a,n){return a(n)},pMznt:function(a,n){return a===n},oRHSF:function(a,n){return a!==n},MbTyc:function(a,n,s){return a(n,s)},XBtFg:function(a,n){return a>n},BcDUp:function(a,n){return a<n},pOQGu:function(a,n){return a===n},CYCsN:t(488),HJVgI:function(a,n){return a>n},tdNrl:t(1205),obtUy:t(712),doncX:function(a,n){return a-n},REGXE:function(a,n){return a!==n},pakYp:function(a,n){return a<n},uZlCK:"ZfVnb",ArKlW:function(a,n){return a-n},pgUtR:"pjrSc",SdLRg:"duBXf",BRwFw:function(a,n,s){return a(n,s)},QXpFu:function(a,n,s){return a(n,s)},Bzxvb:function(a,n){return a+n},rWSGS:t(1600),HLKVT:function(a,n){return a(n)},IYTkW:function(a,n){return a!==n},PYiBc:"HPLDf",mLdED:function(a,n){return a(n)},GUmeU:function(a,n){return a>>>n},EOqlc:function(a,n,s){return a(n,s)},xVfQQ:function(a,n){return a&n},UZWDg:t(948)+t(1407)+t(976)+"key",jRFgo:t(948)+t(1407)+" field: "+t(1279),EyWif:function(a,n){return a>=n},VuXcI:function(a,n){return a!==n},ZShSh:t(1838),vADGS:function(a){return a()},TkGUv:t(520)+"le",qAbqw:function(a,n){return a(n)},oAXoU:function(a,n){return a!==n},ThklY:t(696),NKoiB:function(a,n){return a!==n},xqHwu:function(a,n,s){return a(n,s)},cIWxz:function(a,n,s){return a(n,s)},VhTfX:function(a){return a()},dWgnu:function(a,n){return a!==n},yZvLl:function(a,n,s){return a(n,s)},hmpQN:function(a,n,s){return a(n,s)},RsDyh:function(a,n,s){return a(n,s)},VApGG:"jCgyO",vDaEr:function(a,n,s){return a(n,s)},bmbCS:function(a,n,s){return a(n,s)},qFqVA:t(1762),awCpF:t(1315),YabPc:function(a,n){return a!==n},fXTTH:function(a,n){return a!==n},fTdkY:function(a,n,s){return a(n,s)},JNkLT:function(a,n){return a(n)},SHvim:function(a,n){return a(n)},sZgMN:function(a,n){return a>>>n},FlpIg:function(a,n,s){return a(n,s)},UGImn:function(a,n){return a(n)},YxPqh:function(a,n,s){return a(n,s)},OJTcu:function(a,n,s){return a(n,s)},AzIEz:function(a,n,s){return a(n,s)},GuYPG:function(a,n,s){return a(n,s)},kxbkI:function(a,n){return a(n)},sqWeZ:function(a,n){return a&n},fYZXr:function(a,n){return a===n},mBQja:function(a,n){return a===n},DkBVA:t(948)+"required field: "+t(1905),mqpBQ:function(a,n){return a===n},xmENE:function(a,n){return a!==n},nRvMC:"OLcvz",HkrGi:function(a,n){return a(n)},OfwYM:function(a,n,s){return a(n,s)},goicL:t(1030)+t(887)+t(897),UxQPo:function(a,n){return a>=n},PGmnz:function(a,n){return a!==n},MMjDm:t(1340),XYHhy:t(1913)+t(401),aHDiG:function(a,n){return a>=n},VzFOC:function(a,n){return a+n},HIHPC:function(a,n){return a+n},CoVfK:t(1487)+t(401),RDATs:function(a,n){return a+n},qXBjW:function(a,n,s){return a(n,s)},DVfTy:function(a,n){return a==n},uwWSn:t(1357),fkQWW:function(a,n){return a(n)},jjWjr:function(a,n,s,l){return a(n,s,l)},NSrDK:function(a,n){return a instanceof n},kTliZ:function(a,n){return a&n},knqBt:function(a,n){return a<<n},IRwkw:t(677),GgDZu:function(a,n,s){return a(n,s)},pFxvC:function(a,n){return a<n},mzPKP:function(a,n){return a&n},wFTpT:function(a,n){return a(n)},BcpOw:function(a,n){return a!==n},ycmEQ:t(1326),HTOoc:function(a,n){return a!==n},WUSCm:function(a,n){return a&n},zQQIg:function(a,n){return a&n},FbzKr:function(a,n){return a(n)},xxBRa:function(a,n){return a|n},ABVWc:function(a,n){return a|n},uCnZx:function(a,n){return a&n},mfdkW:function(a,n){return a<<n},KilAc:function(a,n){return a>=n},Bjjin:function(a,n){return a<=n},bowQX:function(a,n){return a+n},tCvZf:function(a,n){return a+n},rTwFk:function(a,n){return a&n},ysEso:function(a,n){return a|n},mQzcF:function(a,n){return a|n},UMnFO:function(a,n){return a<<n},jGlMs:function(a,n){return a|n},xWtFz:function(a,n){return a|n},bVvFU:function(a,n){return a<<n},SGxQW:function(a,n){return a&n},svVsq:function(a,n){return a<<n},CojKy:function(a,n){return a>n},REtaP:function(a,n){return a===n},EAMyu:t(1485),oonxj:function(a,n){return a+n},WjWHz:function(a,n){return a+n},RcIRR:function(a,n){return a+n},cBabi:function(a,n){return a|n},usbHc:function(a,n){return a<n},CzYSb:function(a,n){return a>=n},WEFJb:function(a,n){return a+n},SGLlZ:function(a,n,s){return a(n,s)},wtZrw:function(a,n){return a-n},iBcSg:function(a,n){return a+n},YdADi:function(a,n){return a<<n},CVvnu:function(a,n){return a!==n},xWVcW:t(554),shPIl:t(742),wAwgg:function(a,n){return a<n},DxCao:function(a,n){return a>>n},cHCwm:function(a,n){return a<n},HTZEz:function(a,n){return a>>n},ATYiT:function(a,n){return a&n},tLyeR:function(a,n){return a|n},NIvnp:function(a,n){return a>>n},ElQRN:function(a,n){return a|n},jcOkB:function(a,n){return a&n},MATQd:function(a,n,s){return a(n,s)},aTdvF:function(a,n,s){return a(n,s)},ixCpF:function(a,n,s,l){return a(n,s,l)},osrKw:function(a,n){return a===n},MlRaY:"ygCip",hqUjI:t(551),IeGyx:function(a,n){return a<n},NutTk:function(a,n){return a<<n},cIQHG:function(a,n){return a&n},MCkpr:function(a,n){return a>=n},dUdXp:function(a,n,s){return a(n,s)},SDvqU:function(a,n){return a|n},GAAHy:function(a,n){return a<<n},sETns:function(a,n){return a!==n},OHOpk:"emJhV",MWGwu:function(a,n){return a(n)},blEQg:function(a,n){return a<<n},NzeuP:function(a,n){return a!==n},oGmgE:t(1035),mxIri:t(521),hSkJX:function(a,n){return a(n)},ZVuVg:function(a,n){return a&n},mcjmy:function(a,n){return a<<n},JPgPZ:function(a,n){return a(n)},qTNlY:function(a,n){return a&n},gBTNp:function(a,n){return a&n},cjQAb:function(a,n){return a<<n},ubOht:function(a,n){return a>>>n},Mnjvt:function(a,n){return a<<n},BYvSg:function(a,n){return a<n},ZSECX:function(a,n){return a<n},rxZpA:function(a,n,s){return a(n,s)},rMrAY:function(a,n){return a!==n},EOdMW:function(a,n){return a|n},SxbEW:function(a,n){return a+n},ItIpL:function(a,n){return a!==n},kcDyY:function(a,n){return a|n},MOmbR:function(a,n){return a&n},nsxPR:function(a,n){return a>>>n},hovGC:function(a,n){return a+n},EYFIl:function(a,n){return a>>>n},sKkyf:function(a,n){return a|n},dVNTZ:function(a,n){return a&n},aCWEy:function(a,n){return a!==n},NHPjG:function(a,n){return a>>>n},MDloq:function(a,n){return a+n},TmLrG:function(a,n){return a|n},CmhcU:function(a,n){return a+n},tbATS:function(a,n){return a!==n},eCZtY:function(a,n){return a>>>n},WhHtM:function(a,n){return a&n},NQLZp:function(a,n){return a(n)},vYgst:function(a,n){return a===n},xacrU:t(1292),MZDHJ:t(1895),qxVhs:function(a,n){return a|n},hfFCo:function(a,n){return a|n},adkSN:function(a,n){return a|n},KjyFO:function(a,n){return a<<n},vSNVo:function(a,n){return a|n},hhWKF:function(a,n){return a|n},UvRIs:function(a,n){return a|n},epcnA:function(a,n){return a|n},szMSz:function(a,n){return a<<n},mIKvb:function(a,n){return a>>>n},qgLBJ:function(a,n){return a|n},kaNLR:function(a,n){return a<<n},btKiG:function(a,n){return a&n},zRnvZ:function(a,n){return a>>>n},RNKLp:function(a,n){return a&n},nwHMt:function(a,n){return a>>>n},LzWny:function(a,n){return a>>>n},wcBMP:function(a,n){return a(n)},DGdIT:function(a,n){return a<=n},NGoNQ:function(a,n){return a|n},lTXZO:function(a,n){return a%n},SlVsa:function(a,n){return a/n},VpZBc:function(a,n){return a>>>n},HlgHr:function(a,n){return a+n},rxfBd:function(a,n){return a*n},ienYr:function(a,n){return a>>>n},Svmuy:function(a,n){return a&n},eayVO:function(a,n){return a>>>n},qHwmd:function(a,n){return a+n},jjBLP:function(a,n){return a>>>n},vYUfw:function(a,n){return a+n},HvfPA:t(935),JFdHd:function(a,n){return a!==n},Aauxp:function(a,n){return a>>>n},HKcju:function(a,n){return a===n},WuFZA:t(1628),lwxRt:function(a,n){return a===n},fhtSI:function(a,n){return a(n)},OXSIy:t(746),tvIJm:function(a,n){return a+n},RUXkk:function(a,n){return a*n},ttwie:function(a,n){return a===n},vJuro:t(437),cwoGW:function(a,n){return a&n},CfUjB:function(a,n){return a&n},HRarS:function(a,n){return a>>>n},tTLgh:function(a,n){return a>>>n},rFegE:function(a,n){return a>>>n},dhXCk:function(a,n){return a>>>n},Ipism:function(a,n){return a&n},kLqtS:function(a,n){return a>>>n},gvVAV:t(833)+"5|0",yjtuv:t(1069)+t(434),PyjHn:t(747)+t(1612),CokbQ:t(1468)+t(1402)+"R",yHoxB:t(1183)+"OR",OvqGA:function(a,n){return a(n)},UoEPx:function(a,n,s,l){return a(n,s,l)},rRslN:t(919),kGOAC:t(1350),hmIrx:t(993)+"2|1|0",XWcwI:function(a,n){return a!==n},vDkxy:function(a,n){return a===n},bLQGt:function(a,n){return a===n},AesdT:function(a,n){return a!==n},hyIfM:"jszqt",TbXNf:"tuIqi",AUizB:t(1064),DsJEO:function(a,n){return a>=n},sbtIS:function(a,n){return a===n},EzgyQ:function(a,n){return a===n},yhUTi:function(a,n){return a==n},PyxGn:function(a,n){return a+n},RyuCG:function(a,n){return a!==n},PSAHz:function(a,n){return a|n},tJkIV:function(a,n){return a<=n},HbwJn:function(a,n){return a(n)},obueX:function(a,n){return a!==n},hjaOf:t(1222),DLgyS:t(1187),SXjIk:function(a,n){return a===n},VPTgN:t(1733)+t(1381),CaLrS:function(a,n){return a===n},Bkwbb:function(a,n){return a<n},whxGS:function(a,n){return a===n},XmaNa:function(a,n){return a(n)},lCsQB:function(a,n){return a+n},ygnJE:function(a,n){return a+n},KCjzP:t(1422),EDRXB:function(a,n){return a||n},xjEvl:" > ",gHqQq:t(1388),iMrwT:t(1660),yxpMT:function(a,n){return a!==n},JnjXn:t(1417),PvWXG:"LxzYw",cOBba:"open",dsXpm:function(a,n){return a<<n},hTMBL:function(a,n){return a&n},dttBP:function(a,n){return a>>n},aBgsE:function(a,n){return a&n},VmuFS:function(a,n,s){return a(n,s)},oKmWk:function(a,n){return a instanceof n},WkVux:function(a,n){return a===n},POAll:t(1902),uMzPZ:"Ihkaa",WTTVo:function(a,n){return a!=n},wyvrc:t(1860)+"d",tjdwn:t(688),ABjTG:t(1142)+t(1136),EhLcT:function(a,n){return a+n},UrxKN:t(1150),egBwa:t(873)+t(1766),dzMnb:t(644)+"0",woXeT:function(a,n){return a(n)},zZeNm:function(a,n){return a===n},mYTrX:function(a,n){return a===n},zIrRJ:t(1512),YdkrE:function(a,n){return a<n},WBvIx:function(a,n){return a<n},RNaAn:function(a,n){return a<n},Cjgif:function(a,n){return a&n},wpQpC:function(a,n){return a&n},iSZQg:function(a,n){return a+n},lCDpS:t(585),MTnmh:function(a,n){return a|n},uiyjS:function(a,n){return a>>n},TRlkj:function(a,n){return a!==n},LMihJ:t(963),MRbzf:function(a,n){return a<n},NVzkz:function(a,n){return a<=n},TAaWq:function(a,n){return a<n},QFLPN:function(a,n){return a<<n},QVfGO:function(a,n){return a&n},FWjPO:function(a,n){return a|n},tBgsB:function(a,n){return a<<n},rwtEH:function(a,n){return a&n},MNutZ:function(a,n){return a>=n},fwnYL:function(a,n){return a|n},TJcFe:function(a,n){return a<<n},RkjJF:function(a,n){return a&n},WxLNp:function(a,n){return a+n},CKhDg:function(a,n){return a===n},AjaSA:function(a,n){return a+n},LaUyS:"0|5|1|3|"+t(463),UYUoV:function(a,n){return a+n},ZVJcn:function(a,n){return a+n},sanzn:function(a,n){return a&n},dJZsw:function(a,n){return a&n},rOqcO:function(a,n){return a|n},pQFlZ:function(a,n){return a&n},FyVCP:function(a,n){return a-n},YPbQj:function(a,n){return a==n},GFsen:function(a,n){return a instanceof n},zxBGS:function(a,n){return a!=n},pNZPj:t(1305)+"in;chars"+t(722),jCtJg:"boe",mwIOd:t(882),SYJCk:"need_ack",SlpLl:"is_ack",svCAD:function(a,n){return a&&n},xmJaX:"ack_id",FHgik:"ack_code",ycZFE:function(a){return a()},ipORZ:function(a,n){return a===n},EFmAl:t(1574),KuanY:function(a,n){return a(n)},XnPBh:t(1180),woEHx:t(572)+"e_success",IdwwY:function(a,n,s){return a(n,s)},qNpzB:"gWhry",DxSlC:t(689),XBBFg:function(a,n){return a!==n},aKeBG:t(485),tlfaJ:t(1880),nRLeU:function(a,n){return a(n)},xHIyi:"online",hoURK:t(1491),gFdfu:t(1555),JMOzj:"SUmgp",PUwtf:t(1790),iXBRY:t(1223)+t(980),WDQCC:t(822),tlTCp:t(1857)+"2",eQijV:function(a,n){return a===n},qiIHz:t(1056),vgkLg:t(932),CPrCA:t(1287),oymEr:"RJjPe",CImWc:function(a,n){return a||n},oNswN:function(a,n){return a|n},FAqJy:t(1144),Drxlq:t(815),arkDp:function(a,n){return a||n},ZzgMp:function(a,n){return a<n},Bsbqg:function(a,n){return a===n},TrkRS:t(743),fFIXS:function(a,n){return a!==n},jvqtg:t(1932),UfnlS:function(a,n){return a||n},wBplf:function(a,n){return a||n},mKhnq:function(a,n){return a!=n},MllMq:function(a,n){return a||n},qASdT:t(1399)+t(868)+"d",IDyNs:t(1720),Avert:t(1754)+"id",rqvCK:t(1235),jWdbJ:t(1620)+t(799),EiGfg:t(1620)+t(1016)+"ck",LrzUj:t(1620)+t(816)+"k",bJudW:function(a,n){return a&&n},GjPdL:t(1288),TxmpJ:function(a){return a()},RZhJT:t(1869),dXXJk:function(a){return a()},EzFuS:function(a,n){return a(n)},DqUJU:t(1168)+"ion/json",PviPP:t(1168)+t(631)+";charset=utf-8",LeakF:t(937)+"e",zcUxg:t(1890),BTNZK:t(647),nWXlP:function(a,n){return a<n},vWLsU:function(a,n){return a>n},EnjFs:function(a,n){return a>n},xqDye:function(a,n){return a+n},HrxQE:t(1197),jUBtE:function(a,n){return a&n},IMVLS:function(a,n){return a+n},UIFpS:function(a,n){return a||n},WwNaS:function(a,n){return a>>>n},bvxDC:function(a,n){return a+n},vNCBe:function(a,n){return a+n},YEpMF:function(a,n){return a+n},roboV:"index ou"+t(1588)+t(1101),rwLba:function(a,n){return a||n},pKiQp:t(1909)+t(899)+"e",vWnCq:function(a,n,s){return a(n,s)},NezqF:function(a,n){return a<<n},mhacH:t(582),ROEWo:"1|2|4|3|0",gNmsL:function(a,n){return a+n},qoIyM:function(a,n,s,l){return a(n,s,l)},hmjfw:function(a,n){return a+n},vDOTQ:function(a,n){return a+n},XUfQc:function(a,n){return a+n},eINRK:function(a,n){return a+n},xywAB:function(a,n){return a|n},gUvPR:function(a,n){return a|n},MrMWQ:function(a,n){return a+n},hSIEK:function(a,n){return a+n},Rqkeh:function(a,n){return a+n},siyxW:function(a,n){return a+n},HslWR:function(a,n){return a>>>n},wRHGk:function(a,n){return a+n},VgWFo:function(a,n){return a>>>n},SqsBC:function(a,n){return a&n},NlhQM:function(a,n){return a>>>n},kXgiR:function(a,n){return a&n},RiCHK:function(a,n){return a>>>n},SJDjM:function(a,n){return a+n},tiesb:function(a,n){return a&n},ZQSam:t(1620)+"er_ack_m"+t(862),yQcnR:function(a,n){return a!==n},RpzeJ:"HTexT",kKCOz:function(a,n){return a+n},MWkjA:function(a,n){return a&n},EBYcZ:function(a,n){return a+n},AxKAa:t(605)+t(807)+t(467)+"4",Lwtsn:function(a,n){return a|n},zCfUd:function(a,n){return a>>>n},nERZH:function(a,n){return a&n},MXTMS:function(a,n){return a<n},mmCKt:function(a,n){return a|n},vtUlF:function(a,n){return a<<n},lPHUl:function(a,n){return a<n},GkUGo:function(a,n,s,l){return a(n,s,l)},wcHaR:function(a,n){return a&n},HzpSd:function(a,n){return a>>>n},gwDEZ:function(a,n){return a<n},DUiit:function(a,n){return a|n},LsGHp:function(a,n){return a!==n},lRZdC:t(701),kaQMa:function(a,n){return a<n},WqQdu:function(a,n){return a!==n},XHwHp:t(837),YHxHe:function(a,n){return a+n},zqVBD:function(a,n,s){return a(n,s)},kUdOp:function(a,n){return a!==n},yVtPK:t(561),SrwOr:t(1865)+t(1893),GBBMv:"service",FYVKG:t(541),IJidB:t(405)+t(1082),BVaMm:"name",mwfqo:function(a,n,s,l){return a(n,s,l)},uYtxA:function(a,n,s,l){return a(n,s,l)},VqPeO:t(570),RukHF:function(a,n){return a(n)},WMXLS:function(a,n){return a(n)},LPZkH:function(a,n,s){return a(n,s)},ckyWe:function(a,n,s){return a(n,s)},DrfWm:t(1278)+"ile_name",LlaQk:function(a,n,s){return a(n,s)},EoizG:"cursor_n"+t(955),uFFXL:function(a,n){return a<=n},yPlaB:t(695),ISgyz:"allCurso"+t(1669),zsgGR:t(1231),Scruv:function(a,n,s,l){return a(n,s,l)},AVsnk:"CONTINUE",iKEuh:function(a,n,s,l){return a(n,s,l)},BHfpD:function(a){return a()},pOIrn:t(1153),XACOL:function(a,n){return a(n)},mXCFs:t(1481)+"r",lzlpU:function(a,n){return a===n},hFWqP:t(1703),fjrDF:function(a,n){return a!==n},uisRp:t(823),ZhOiS:t(792),Apesk:function(a,n,s){return a(n,s)},FwACG:t(1620)+t(1349),OqCkt:function(a,n,s){return a(n,s)},wHpLb:"x_frontier_ttl",sfThy:t(1807)+"s",AlsQu:function(a,n,s){return a(n,s)},wicTa:t(1347)+"rsor_name",uDXrf:function(a,n){return a(n)},eQDpB:t(1347)+t(400)+"ue",sYHMT:function(a,n){return a>n},HBTMG:function(a,n){return a!==n},KrGyB:t(1389),uWPRH:function(a,n){return a<n},JAIeB:function(a){return a()},PIpQY:function(a){return a()},TvZId:function(a){return a()},eFOTM:function(a,n){return a===n},iEvEj:function(a,n){return a===n},XIqXx:function(a,n){return a&&n},IddnM:function(a,n,s){return a(n,s)},pCpZE:function(a){return a()},oYpvH:function(a,n){return a<n},tfzIv:function(a,n,s){return a(n,s)},RBapJ:function(a,n,s){return a(n,s)},URmHO:t(1947),wEVUj:function(a,n){return a===n},CQlqk:t(1949),VMTZi:t(428),XTQoU:t(1128),ZQRWF:t(1894),FZpYc:"tFBqU",dVOFI:function(a,n){return a(n)},suXAq:function(a,n,s){return a(n,s)},Vykod:function(a,n){return a!==n},FiqiN:function(a,n,s){return a(n,s)},NXXOa:"arraybuf"+t(1157),otDcj:t(1083),RFVKy:function(a,n){return a==n},zkkWa:function(a,n){return a===n},cRlvf:"please p"+t(1444)+"alid url",oQcFG:"please p"+t(1797)+t(700)+t(504)+t(991)+t(1731)+t(1586)+"ined",waAaO:function(a,n,s){return a(n,s)},aYDEM:t(709)+"t",JqqWe:t(1761)+"ediately"+t(1141)+"ct",lGucI:t(1191),yAOyx:t(721),BrvZk:t(1596),JbsQN:function(a,n){return a==n},BwwBL:"https:",DDRSO:t(1622),ewLpP:t(1129),XuiEr:t(448),JdbLY:t(477)+"d",GnFcs:function(a,n){return a||n},Sbvez:t(511)+"rovide b"+t(1432)+t(1131)+t(418),HeAUq:"function",fwvdK:t(1533),LOYHq:t(773)+"0",BGvuo:t(933),VJfaH:function(a,n){return a>n},gqhbt:function(a,n,s){return a(n,s)},Rvrak:"mBarH",gBQvS:t(1548),vBWUS:function(a,n){return a(n)},thVHJ:t(926)+">",LOkjv:t(858),PqGgL:function(a,n){return a*n},wrqwL:function(a,n){return a>n},ookte:t(613),Mjldy:t(572)+t(587)+"t",NksnM:t(1493),htttR:t(1571),XcucA:t(1926),ELdme:t(514),TJDOU:function(a,n){return a<<n},Ccrlb:function(a,n){return a&n},Xuyio:t(825)+" try rec"+t(801)+"g",RjJRj:t(870),ERAYk:"4|2|0|3|1",zXHTO:t(1454)+t(741),Kzlua:t(445),BGbFP:t(1134),nuTKf:function(a){return a()},zokBn:t(1935),ACnwI:t(942),ubOzC:t(602)+"ys",KFgPj:t(914),bPgqL:t(1604),xXGcz:t(1522),guipx:function(a,n,s){return a(n,s)},WiJVa:t(1712),KMVOv:function(a,n){return a|n},KCoZY:function(a,n){return a&n},ReqqH:function(a,n){return a<<n},IWUEQ:function(a,n){return a&n},YRUnd:function(a,n){return a>>n},jMcIw:function(a,n){return a&n},ToRAE:function(a,n){return a===n},zFGey:"qWecu",AXpRV:function(a){return a()},GpOSq:function(a,n){return a!==n},fqFKA:t(645),XajeB:"YTjRe",jINum:"bkfcx",sljpm:function(a,n){return a===n},WCgOh:function(a,n){return a!==n},SpAHa:t(632),lhher:t(1808),YIKxg:t(492)+t(1483)+t(1013),OkPps:function(a,n){return a==n},LbooD:t(511)+t(850)+t(1718)+"ata, dat"+t(1441)+t(516)+t(1889)+t(923)+t(692),qZdXM:t(1372),BMXWJ:function(a,n){return a(n)},FlgDH:t(511)+"rovide a"+t(974)+"ervice",GMkKR:function(a,n){return a instanceof n},EUnMU:function(a,n){return a(n)},CBWGi:function(a,n){return a===n},CDDuT:t(1046),HMPbO:function(a,n){return a<n},zYfGM:t(1306),PuFIl:function(a,n){return a!==n},hQYVU:function(a,n,s){return a(n,s)},sowTH:t(714),TNPLx:t(591),egafr:t(904),oiNfc:t(1226)+"3",Polef:function(a,n){return a===n},YdWSP:"qMBDq",pfrhl:function(a,n){return a(n)},Dgyws:function(a,n){return a!==n},mRGdT:t(1172),ziIot:"IoQVr",OAakq:"\0\0\0\0\0\0\0\0",Vydoe:function(a,n){return a*n},cpLMu:function(a,n){return a/n},Vmckk:t(580),wYXYz:function(a,n){return a===n},OxmZe:function(a,n){return a!=n},pGDkz:function(a,n){return a!=n},VgYuk:t(1233),tnAcH:"Dedicate"+t(1034)+t(1026)+"pe",hJGQD:function(a,n){return a!=n},WPCkc:function(a,n){return a==n},tDKpJ:function(a,n){return a!=n},Qmjyq:t(1645)+"orkerGlo"+t(1151),QKNxt:function(a,n){return a!=n},FMPTf:function(a,n){return a!=n},Rgmeq:function(a,n){return a!=n},WUYwI:function(a,n){return a!=n},WdHqp:"__x_msg_"+t(1143)};zt.r(Pe),zt.d(Pe,{FWS:()=>zg,CustomErrorEvent:()=>pl,createCloseEvent:()=>gt,ReconnectEvent:()=>xl,createErrorEvent:()=>dt,decodedFrame:()=>rn,createOpenEvent:()=>bl,CustomCloseEvent:()=>gl,createReconnectEvent:()=>_a,FrontierMessageEvent:()=>wl,encodeFrame:()=>qt,createMessageEvent:()=>yl,OpenEvent:()=>_l,ErrorCode:()=>on,Event:()=>sr,MessageEvent:()=>ml});let r="";function i(a=""){let n=t,s={bnGiD:n(1513),ZYwCc:e[n(1152)]};if(e[n(1649)](n(583),e.YyAcv)){let f=""+Date[n(1240)](),m=r||(r=e[n(1087)](h,a)),v=Math[n(1783)]().toString(16)[n(1726)](-6);return e[n(1019)](e[n(810)](e[n(1011)]("02",f),m),v)}else{let l="2|1|4|0|3"[n(654)]("|"),f=0;for(;;){switch(l[f++]){case"0":this[n(775)][n(1821)+n(958)]("message",this[n(890)+"ge"]);continue;case"1":this._ws[n(1821)+"Listener"](s.bnGiD,this[n(1534)]);continue;case"2":if(!this[n(775)])return;continue;case"3":this[n(775)][n(1821)+n(958)]("error",this[n(657)]);continue;case"4":this[n(775)][n(1821)+n(958)](s[n(1828)],this[n(1867)]);continue}break}}}function o(){let a=t;return e[a(474)](e[a(1471)](1e4,Date.now()),Math.floor(e[a(1476)](1e4,Math[a(1783)]())))}function c(a){let n=t,s={qRJAJ:function(l,f){return e[j(789)](l,f)},GcsiO:function(l,f){return e[j(1005)](l,f)},tPgTZ:function(l,f){return e[j(1266)](l,f)},NIXWD:function(l,f){return e[j(789)](l,f)},uebFT:function(l,f){return e.fFolj(l,f)},DQtTq:function(l,f){return e[j(1266)](l,f)},rwPJJ:function(l,f){return e[j(789)](l,f)}};if(e[n(1623)]!==e[n(1623)])_0x4e4add<65536?_0x15121d[_0x58038c++]=s[n(819)](s[n(718)](s.tPgTZ(_0x453614,12),15),224):(_0x2b92dc[_0x2fdc6++]=s[n(768)](s[n(718)](s[n(1866)](_0x53263e,18),7),240),_0x425c0c[_0x9f8d7e++]=s[n(718)](s[n(1211)](_0x2bde41,12),63)|128),_0x1ce9b6[_0x1aa8f9++]=s[n(1652)](s.DQtTq(_0x17ac1e,6)&63,128);else return(e.uphnR(Array,8).join("0")+parseInt(a,10)[n(672)](2))[n(1726)](-8)}function d(a){let n=t;return(e[n(1920)](Array,4)[n(1541)]("0")+e[n(1951)](parseInt,a,2)[n(672)](16))[n(1726)](-4)}function u(a){let n=t,s=a[n(654)](/\./)[n(1593)](m=>c(m)),l=[];return l[0]=e.EAynQ(d,e[n(866)](s[0],s[1])),l[1]=e[n(1071)](d,s[2]+s[3]),[e.MDDge,e.MDDge,e[n(1955)],e[n(1955)],n(1445),e[n(1345)],l[0],l[1]][n(1541)]("")}function h(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(782)](a),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[n(782)](a);return s?e.AQrZs(u,a):l?e.hWkeV(x,a):n(838)+"00000000"+n(838)+n(838)}function x(a){let n=t,s="",l=[],f=0,m=0,v=!0,y=e[n(1955)];if(e[n(1091)](a.indexOf("::"),-1)){let p=a[n(654)]("::");for(let L=0;e[n(832)](L,p[n(571)]);L++)if(e[n(1928)](e[n(594)],e[n(594)])){let F=p[L];if(e[n(1390)](F.indexOf(":"),0)){let q=F.split(":");v&&(f=q[n(571)]),m+=q[n(571)];for(let $=0;$<q[n(571)];$++)if(e[n(1649)](4,q[$].length)){if(e[n(1358)](e.tdNrl,e.obtUy))return this[n(1463)+n(1917)]?.["getCurre"+n(1001)+n(719)+n(1163)]()||0;{let ge=y[n(619)+"g"](0,e.doncX(4,q[$][n(571)])),We=ge.concat(q[$]);l[n(803)](We)}}else l[n(803)](q[$]);v=!1}else{if(e[n(1200)](4,F.length)){let q=y.substring(0,4-F[n(571)]),$=q[n(1490)](F);l.push($)}else l.push(F);v&&(f+=1),m+=1,v=!1}}else return!0;let A="";for(let L=0;e.BcDUp(L,8-m);L++)A=A[n(1490)](y);for(let L=0;e[n(765)](L,l[n(571)]);L++)e[n(1358)](L,f)&&(s=s[n(1490)](A)),s=s[n(1490)](l[L]);return s}{let p=a[n(654)](":");for(let A=0;e[n(765)](A,p.length);A++){let L=p[A];if(e[n(1200)](4,p[A][n(571)]))if(e[n(1358)](e[n(1177)],e[n(1177)])){let F=y[n(619)+"g"](0,e[n(1508)](4,p[A][n(571)])),q=F[n(1490)](L);s=s.concat(q)}else{if(this[n(775)]&&e.pMznt(this._ws[n(545)+"te"],this.CONNECTING)){this["_clearPi"+n(548)](),this[n(480)+n(1648)+"Id"]=e[n(1951)](_0x3a0128,this[n(982)][n(1263)](this),this._options[n(840)+n(1055)]);return}if(!this[n(775)]||e[n(1706)](this[n(775)][n(545)+"te"],this.OPEN))return void this[n(806)+"econnect"]();this._ws&&this[n(775)][n(842)]("hi"),this["_reconne"+n(505)+n(1509)]=e[n(1679)](_0x2e1ec2,this[n(806)+n(1651)+n(1059)].bind(this),this[n(690)][n(1312)+"outInter"+n(432)])}else s=s.concat(L)}return s}}function g(a,n){let s=t,l=a[s(1553)];if(e.CnbaB(void 0,l))if(e[s(1358)](e[s(996)],e[s(1166)])){let m=_0x4301b0();return e[s(1951)](_0x3a8240,_0x3586ff,m),e.ZOYrX(_0x38451d,m)}else e.mWRio(pe,n,10),e.BRwFw(U,n,l);let f=a.value;e[s(1706)](void 0,f)&&(e[s(440)](pe,n,18),U(n,f))}function w(a){let n=t;if(e.rWSGS!==e[n(439)]){let s=_0x3b4eb1(_0x192557,_0xafcf7c);return _0x263391[n(1241)][n(1273)](s,e[n(1590)](s,_0x250193))}else{let s={};e:for(;!e[n(1528)](V,a);){if(e[n(930)](e.PYiBc,n(1822)))return this._qosDB?.isReady;{let l=e[n(691)](le,a);switch(e.GUmeU(l,3)){case 0:break e;case 1:s.key=e[n(1800)](D,a,le(a));break;case 2:s[n(1279)]=D(a,le(a));break;default:C(a,e[n(575)](7,l))}}}if(e[n(1928)](void 0,s[n(1553)]))throw new Error(e[n(733)]);if(e[n(1928)](void 0,s[n(1279)]))throw new Error(e[n(702)]);return s}}function S(a){let n=t,s={OZlxP:function(l,f){return e.EyWif(l,f)}};if(e[n(1689)](e.ZShSh,n(1196))){let l=e[n(431)](R);return _(a,l),M(l)}else if(s[n(1549)](_0x5c6560,_0x4b42a0))return _0x3da965}function _(a,n){let s=t,l={jHKbX:function(It,Ht){return e.qAbqw(It,Ht)}},f=a[s(1190)];e.IYTkW(void 0,f)&&(e[s(1679)](pe,n,8),pt(n,f));let m=a[s(1905)];e.oAXoU(void 0,m)&&(e.MbTyc(pe,n,16),e[s(1951)](pt,n,m));let v=a[s(1267)];e[s(1200)](void 0,v)&&(e.ThklY!==e[s(1033)]?(this[s(1551)+s(1408)]=_0x38a8ee,this._ws&&(this._ws[s(881)+"pe"]=_0xac56c4)):(e[s(440)](pe,n,24),pt(n,e.ZOYrX(P,v))));let y=a.method;e.NKoiB(void 0,y)&&(e[s(1800)](pe,n,32),e[s(813)](pt,n,e.uphnR(P,y)));let p=a.headers;if(p!==void 0)for(let It of p){e[s(1638)](pe,n,42);let Ht=e.VhTfX(R);g(It,Ht),pe(n,Ht[s(893)]),W(n,Ht),O(Ht)}let A=a[s(1146)+s(1073)];e.dWgnu(void 0,A)&&(e[s(739)](pe,n,50),e[s(901)](U,n,A));let L=a.payloadType;e[s(828)](void 0,L)&&(e[s(1355)](pe,n,58),U(n,L));let F=a[s(603)];if(e[s(930)](void 0,F))if(e[s(1643)]==="jCgyO")e[s(739)](pe,n,66),e.vDaEr(pe,n,F[s(571)]),e[s(1638)](se,n,F);else return l[s(1634)](_0x35a6cc,_0xbf25dd);let q=a.LogIDNew;e[s(930)](void 0,q)&&(e[s(1192)](pe,n,74),e[s(1559)](U,n,q));let $=a.serverTiming;e[s(1649)](void 0,$)&&(e[s(1952)]===e[s(764)]?(typeof _0x19d401<"u"&&_0x57d157[s(672)+s(1631)]&&_0x42cce7["definePr"+s(1342)](_0x27e564,_0x45ab98[s(672)+"Tag"],{value:s(918)}),_0x40f47c.defineProperty(_0xe356b7,ScJSEe[s(710)],{value:!0})):(e[s(739)](pe,n,82),e[s(1355)](U,n,$)));let ge=a.msgID;e[s(931)](void 0,ge)&&(e[s(1638)](pe,n,90),e[s(1559)](U,n,ge));let We=a[s(1904)+"e"];e[s(500)](void 0,We)&&(e[s(1559)](pe,n,96),e[s(414)](pt,n,P(We)))}function E(a){return e[t(1025)](I,B(a))}function I(a){let n=t,s={};e:for(;!V(a);){let l=e.SHvim(le,a);switch(e[n(1022)](l,3)){case 0:break e;case 1:s[n(1190)]=e.FlpIg(St,a,!0);break;case 2:s.LogID=St(a,!0);break;case 3:s[n(1267)]=e.UGImn(le,a);break;case 4:s[n(1041)]=le(a);break;case 5:{let f=e[n(1920)](k,a);(s[n(1739)]||(s[n(1739)]=[]))[n(803)](e[n(577)](w,a)),a[n(893)]=f;break}case 6:s[n(1146)+n(1073)]=e[n(1355)](D,a,le(a));break;case 7:s[n(703)+n(1408)]=e[n(1742)](D,a,e[n(951)](le,a));break;case 8:s[n(603)]=e[n(1818)](ee,a,le(a));break;case 9:s.LogIDNew=e.AzIEz(D,a,le(a));break;case 10:s[n(1717)+n(1092)]=e[n(843)](D,a,e[n(577)](le,a));break;case 11:s[n(618)]=D(a,e.hWkeV(le,a));break;case 12:s.frameType=e[n(627)](le,a);break;default:e.MbTyc(C,a,e[n(1449)](7,l))}}if(e[n(1535)](void 0,s[n(1190)]))throw new Error("Missing required"+n(976)+"SeqID");if(e.mBQja(void 0,s[n(1905)]))throw new Error(e[n(1611)]);if(s[n(1267)]===void 0)throw new Error(n(948)+n(1407)+" field: "+n(1267));if(e[n(990)](void 0,s.method))throw new Error(n(948)+n(1407)+n(976)+n(1041));return s}function k(a){let n=t,s=e[n(581)](le,a),l=a[n(893)];return a.limit=a.offset+s,l}function C(a,n){let s=t;if(e[s(513)](e[s(512)],"qHCWe"))switch(n){case 0:for(;128&e[s(1876)](te,a););break;case 2:e[s(620)](Z,a,le(a));break;case 5:e[s(901)](Z,a,4);break;case 1:Z(a,8);break;default:throw new Error(e[s(1785)]+n)}else{if(this._options["disableA"+s(800)+s(1597)]||this[s(553)+"osed"])return;this[s(806)+s(1651)]()}}function P(a){let n=t;return a|=0,{low:a,high:e[n(1266)](a,31),unsigned:e.UxQPo(a,0)}}let b=[];function R(){let a=t;if(e[a(1817)](a(1340),e[a(1423)]))throw this[a(1728)+"Lock"]=!1,_0x76cf5e;{let n=b.pop();return n?(n[a(1929)]=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}}function O(a){b[t(803)](a)}function B(a){return{bytes:a,offset:0,limit:a[t(571)]}}function M(a){let n=t,s=a[n(1241)],l=a[n(893)];return e[n(981)](s.length,l)?s:s.subarray(0,l)}function Z(a,n){let s=t;if(e[s(1390)](e[s(866)](a[s(1929)],n),a[s(893)]))throw new Error(e[s(787)]);a.offset+=n}function V(a){let n=t;return e[n(1066)](a[n(1929)],a.limit)}function re(a,n){let s=t,l=a.bytes,f=a[s(1929)],m=a.limit,v=e.VzFOC(f,n);if(e[s(1390)](v,l[s(571)])){let y=new Uint8Array(e[s(1476)](2,v));y[s(1892)](l),a[s(1241)]=y}return a[s(1929)]=v,e[s(1091)](v,m)&&(a[s(893)]=v),f}function X(a,n){let s=t,l=a.offset;if(e[s(1091)](e[s(1252)](l,n),a[s(893)]))throw new Error(e[s(1257)]);return a[s(1929)]+=n,l}function ee(a,n){let s=t,l=e[s(917)](X,a,n);return a[s(1241)][s(1273)](l,e[s(1829)](l,n))}function se(a,n){let s=t,l=e[s(869)](re,a,n[s(571)]);a[s(1241)][s(1892)](n,l)}function D(a,n){let s=t;if(e[s(1592)]===e[s(1592)]){let l=e[s(995)](X,a,n),f=String[s(1773)+s(1094)],m=a[s(1241)],v="\uFFFD",y="";for(let p=0;e[s(1530)](p,n);p++){let A=m[e[s(1829)](p,l)],L,F,q,$;if(e[s(981)](e[s(1802)](128,A),0))y+=e.wFTpT(f,A);else if(e[s(1928)](e[s(1449)](224,A),192))if(e.EyWif(p+1,n))y+=v;else if(e[s(1770)](e[s(403)],"MrZzF")){if(e.DVfTy(e.uwWSn,typeof _0x498495)){let ge=new _0x40f17f(e[s(1609)](_0x156f41,_0x15eb6a));return e[s(628)](_0x390adf,_0x3a4dfe,ge,0),ge}return e[s(1842)](_0x5dc5f9,_0x3672a6)?new _0x698314(_0x4a5511):new _0x2c013a(_0x2bde31[s(1412)],_0x4a2ad9[s(1040)+"et"],_0x22c272.byteLength)}else L=m[e[s(1252)](e[s(1829)](p,l),1)],e[s(1937)](e[s(1012)](192,L),128)?y+=v:($=e[s(1584)](e[s(621)](31,A),6)|e[s(1473)](63,L),e[s(1530)]($,128)?y+=v:(y+=e.FbzKr(f,$),p++));else if(e[s(425)](e.mzPKP(240,A),224))e[s(1356)](p+2,n)?y+=v:(L=m[e.QwNAD(p,l)+1],F=m[e[s(474)](e[s(1674)](p,l),2)],(e.xxBRa(L,F<<8)&49344)!==32896?y+=v:($=e[s(789)](e[s(730)](e[s(1477)](15,A)<<12,e[s(734)](63&L,6)),63&F),e.BcDUp($,2048)||e.KilAc($,55296)&&e[s(736)]($,57343)?y+=v:(y+=e[s(691)](f,$),p+=2)));else if(e[s(1473)](248,A)==240)if(e[s(1019)](p,3)>=n)y+=v;else if(L=m[e[s(724)](p,l)+1],F=m[e[s(697)](p,l)+2],q=m[e.tCvZf(e.tCvZf(p,l),3)],e.CnbaB(e[s(1856)](e[s(751)](e[s(1058)](L,e[s(1657)](F,8)),e[s(1657)](q,16)),12632256),8421504))y+=v;else if($=e[s(751)](e.jGlMs(e[s(754)](e[s(1435)](e[s(1782)](7,A),18),(63&L)<<12),e[s(426)](e[s(1856)](63,F),6)),63&q),e[s(765)]($,65536)||e[s(760)]($,1114111))y+=v;else{if(e[s(947)](e[s(687)],"rdBXm"))return _0x4dbe69;$-=65536,y+=f(e[s(1823)](e[s(1266)]($,10),55296),e[s(1449)](1023,$)+56320),p+=3}else y+=v}return y}else _0x5b6b96=e[s(1071)](_0x29c7b5,_0x323e55),_0x18096a=127&_0x27837b,e[s(1473)](128,_0x3f49ae)&&(_0x53fdef=_0x212aff(_0x6b09b0),_0x5a1823|=e[s(1584)](127&_0x2cf724,7))}function U(a,n){let s=t,l=n[s(571)],f=0;for(let y=0;e[s(1290)](y,l);y++){let p=n[s(1384)+"At"](y);e[s(1627)](p,55296)&&e[s(736)](p,56319)&&e[s(765)](y+1,l)&&(p=e[s(1050)](p<<10,n[s(1384)+"At"](++y))-56613888),f+=p<128?1:e[s(832)](p,2048)?2:e[s(1290)](p,65536)?3:4}pe(a,f);let m=e[s(610)](re,a,f),v=a[s(1241)];for(let y=0;y<l;y++){let p=n[s(1384)+"At"](y);if(e[s(1066)](p,55296)&&e[s(736)](p,56319)&&e[s(832)](e[s(474)](y,1),l)&&(p=e[s(853)](e.iBcSg(e.YdADi(p,10),n.charCodeAt(++y)),56613888)),e[s(765)](p,128))v[m++]=p;else if(e.CVvnu(e[s(1368)],e[s(567)]))e.wAwgg(p,2048)?v[m++]=e[s(730)](e[s(1259)](p,6)&31,192):(e[s(1690)](p,65536)?v[m++]=e[s(1470)](e[s(557)](p,12)&15,224):(v[m++]=e[s(1058)](e.ATYiT(e[s(1266)](p,18),7),240),v[m++]=e[s(789)](e[s(1259)](p,12)&63,128)),v[m++]=e[s(1868)](e.kTliZ(e.NIvnp(p,6),63),128)),v[m++]=e.ElQRN(e[s(1203)](63,p),128);else{if(e[s(832)](_0x1eb8f3,1)||_0x193a09>_0x6ba39e)return e.JNkLT(_0x1443ac,_0x52768d);e[s(1578)](_0x441a74,_0x362c23)>_0xf76aa0&&(_0x4cdbc1=e[s(1443)](_0x50d7b1,_0x1cec69),_0x52a317=0);let A=_0x4ebfd6[s(1615)](_0x4c80dc,_0x34d3d3,_0x1b6fec+=_0x16e371);return 7&_0x239f7c&&(_0x1af7d3=e[s(1854)](e[s(1470)](7,_0x324d50),1)),A}}}function W(a,n){let s=t,l=e[s(1198)](re,a,n[s(893)]),f=a[s(1241)],m=n[s(1241)];for(let v=0,y=n.limit;e[s(1290)](v,y);v++)f[e[s(1590)](v,l)]=m[v]}function te(a){let n=t;return a.bytes[e[n(711)](X,a,1)]}function Ze(a,n){let s=t;if(e[s(1164)](e[s(1121)],e.hqUjI))e[s(457)](_0x251afe,this,_0xfb1b05,[_0x4a374f,_0x2447df,_0x1184b5]);else{let l=e.RsDyh(re,a,1);a[s(1241)][l]=n}}function le(a){let n=t,s=0,l=0,f;do f=te(a),e[n(1614)](s,32)&&(l|=e.NutTk(e.cIQHG(127,f),s)),s+=7;while(128&f);return l}function pe(a,n){let s=t;for(n>>>=0;e[s(1936)](n,128);)e[s(1738)](Ze,a,e[s(1524)](e.xVfQQ(127,n),128)),n>>>=7;e[s(610)](Ze,a,n)}function St(a,n){let s=t,l={DISyY:function(p,A){return e.ABVWc(p,A)},HpROk:function(p,A){return e[j(1435)](p,A)},xFRSh:function(p,A){return e[j(542)](p,A)},xiybC:function(p,A){return e[j(1657)](p,A)}},f=0,m=0,v=0,y;if(y=te(a),f=127&y,e.jcOkB(128,y)&&(y=e.fkQWW(te,a),f|=e[s(542)](127&y,7),e.jcOkB(128,y))){if(e[s(1655)](e[s(1927)],e[s(1927)]))return _0x245922[s(443)+s(558)][1]?void 0:_0x2f9d23[s(443)+"ore"](_0x318da4[s(443)+"oreNames"][0]);if(y=e.MWGwu(te,a),f|=e[s(1e3)](e[s(1203)](127,y),14),128&y)if(e[s(1710)](e[s(1250)],e[s(1851)]))y=e[s(1772)](te,a),f|=e.ZVuVg(127,y)<<21,e[s(1005)](128,y)&&(y=te(a),m=127&y,e[s(1012)](128,y)&&(y=e[s(1528)](te,a),m|=e[s(1764)](e.mzPKP(127,y),7),128&y&&(y=e[s(1746)](te,a),m|=e[s(1132)](e.xVfQQ(127,y),14),e[s(1473)](128,y)&&(y=te(a),m|=(127&y)<<21,e.mzPKP(128,y)&&(y=e[s(637)](te,a),v=e[s(466)](127,y),e.gBTNp(128,y)&&(y=e[s(581)](te,a),v|=e[s(1882)](127&y,7)))))));else return new _0x34b564(l[s(761)](l[s(761)](l[s(761)](_0x15ff63[0],l[s(1556)](_0x35f9fd[1],8)),l[s(640)](_0x459f7a[2],16)),_0x5e51ec[3]<<24),l.DISyY(l[s(761)](_0x4baa58[4],l[s(1677)](_0x28146e[5],8))|l[s(1677)](_0x331bca[6],16),_0x111442[7]<<24),_0x2f5b92)}return{low:e.xxBRa(f,e[s(1657)](m,28)),high:m>>>4|e.UMnFO(v,24),unsigned:n}}function pt(a,n){let s=t,l=e[s(827)](n[s(452)],0),f=e[s(827)](e[s(1058)](e[s(663)](n[s(452)],28),e[s(528)](n[s(1532)],4)),0),m=n[s(1532)]>>>24,v=m===0?e[s(1928)](0,f)?e[s(1830)](l,16384)?e[s(1799)](l,128)?1:2:l<2097152?3:4:e[s(626)](f,16384)?e.ZSECX(f,128)?5:6:f<2097152?7:8:m<128?9:10,y=e[s(1721)](re,a,v),p=a[s(1241)];switch(v){case 10:p[y+9]=e[s(1477)](e[s(663)](m,7),1);case 9:p[e[s(1674)](y,8)]=e[s(1413)](9,v)?e[s(936)](128,m):127&m;case 8:p[e[s(1858)](y,7)]=e.ItIpL(8,v)?e[s(1538)](e.ubOht(f,21),128):e[s(1930)](e[s(1835)](f,21),127);case 7:p[e[s(1042)](y,6)]=v!==7?e[s(663)](f,14)|128:e[s(1802)](e[s(663)](f,14),127);case 6:p[e[s(697)](y,5)]=v!==6?e.EYFIl(f,7)|128:e[s(490)](f>>>7,127);case 5:p[e[s(617)](y,4)]=v!==5?e[s(1910)](128,f):e.dVNTZ(127,f);case 4:p[e[s(1011)](y,3)]=e[s(1154)](4,v)?e[s(754)](e[s(1280)](l,21),128):e[s(1005)](l>>>21,127);case 3:p[e[s(1557)](y,2)]=v!==3?e[s(1492)](e[s(1022)](l,14),128):e[s(663)](l,14)&127;case 2:p[e[s(1015)](y,1)]=e[s(538)](2,v)?l>>>7|128:e[s(1005)](e[s(487)](l,7),127);case 1:p[y]=e[s(1154)](1,v)?128|l:e[s(1440)](127,l)}}function rn(a){return e.NQLZp(E,a)}function qt(a){return e.AQrZs(S,a)}let sn=65536,ti=e.OAakq,ye=e[t(1365)](sn,sn),Te=e.jnnEX(ye,ye),ir=e[t(1517)](Te,2),Ne=String[t(501)+"e"][t(1384)+"At"];class ue{constructor(n,s,l){let f=t;this[f(1127)]=!0,this[f(452)]=e[f(1524)](0,n),this[f(1532)]=e[f(1058)](0,s),this[f(766)]=!!l}static isLong(n){let s=t;return n&&e[s(990)](!0,n[s(1127)])}static[t(1603)](n,s,l){return new ue(n,s,l)}static[t(1861)+"s"](n,s,l){let f=t;return l?ue["fromByte"+f(1632)](n,s):ue[f(1861)+f(762)](n,s)}static[t(1861)+t(1632)](n,s){let l=t;if(e[l(658)](e.xacrU,e[l(1186)]))_0x3e0b6f[l(1892)](_0x5ac53d,_0x4eee86);else return new ue(e[l(1816)](n[0],e.blEQg(n[1],8))|e[l(1e3)](n[2],16)|n[3]<<24,e[l(751)](e[l(1319)](e.TmLrG(n[4],e[l(528)](n[5],8)),e[l(1435)](n[6],16)),e[l(528)](n[7],24)),s)}static[t(1861)+t(762)](n,s){let l=t;return new ue(e[l(1492)](e[l(1884)](e[l(1868)](e[l(1568)](n[4],24),e.blEQg(n[5],16)),n[6]<<8),n[7]),e[l(758)](e[l(1602)](e.UMnFO(n[0],24),n[1]<<16)|e.UMnFO(n[2],8),n[3]),s)}static[t(1543)](n){let s=t;return n===ti?hl:new ue(e[s(1022)](e[s(661)](e[s(1591)](e.epcnA(Ne.call(n,0),e[s(1950)](Ne.call(n,1),8)),e[s(542)](Ne[s(1615)](n,2),16)),e[s(793)](Ne[s(1615)](n,3),24)),0),e.mIKvb(e[s(1470)](e.qgLBJ(e[s(1538)](Ne[s(1615)](n,4),e.szMSz(Ne[s(1615)](n,5),8)),e.mfdkW(Ne[s(1615)](n,6),16)),e[s(607)](Ne[s(1615)](n,7),24)),0),!0)}[t(1393)](){let n=t;return String[n(1773)+"Code"](e[n(1921)](255,this[n(452)]),e.WhHtM(e[n(1343)](this[n(452)],8),255),e[n(575)](e[n(1022)](this[n(452)],16),255),this.low>>>24,e[n(1440)](255,this[n(1532)]),e[n(446)](e[n(875)](this.high,8),255),e[n(1188)](this[n(1532)],16)&255,e[n(820)](this.high,24))}static[t(1682)+"er"](n,s=!0){let l=t;if(e[l(1617)](isNaN,n))return s?Yp:hl;if(s){if(e[l(1627)](n,Te))return Qp}else{if(e.DGdIT(n,-ir))return eg;if(e.MCkpr(n+1,ir))return Xp}return ue[l(1603)](e[l(1158)](e[l(1834)](n,ye),0),e[l(1524)](e[l(1734)](n,ye),0),s)}[t(848)](){let n=t;return this.unsigned?e.jnnEX(this[n(1532)]>>>0,ye)+e[n(1184)](this.low,0):e[n(1452)](e.rxfBd(this[n(1532)],ye),this[n(452)]>>>0)}[t(1708)](){let n=t;return this[n(1532)]===0&&e[n(658)](0,this.low)}[t(934)](n){let s=t;ue[s(1127)](n)||(n=ue[s(1682)+"er"](n));let l=e.NHPjG(this[s(1532)],16),f=e.jcOkB(65535,this[s(1532)]),m=e[s(1804)](this[s(452)],16),v=e.SGxQW(65535,this[s(452)]),y=e.NHPjG(n.high,16),p=e[s(1576)](65535,n.high),A=e[s(1954)](n[s(452)],16),L=e[s(1440)](65535,n.low),F=0,q=0,$=0,ge=0;return ge+=e[s(717)](v,L),$+=e.jjBLP(ge,16),ge&=65535,$+=e.HlgHr(m,A),q+=$>>>16,$&=65535,q+=e[s(1826)](f,p),F+=q>>>16,q&=65535,F+=e[s(1252)](l,y),F&=65535,ue[s(1603)](e.UvRIs(e[s(1132)]($,16),ge),e[s(1492)](F<<16,q),this[s(766)])}[t(1301)](n){let s=t,l={sEIqb:e[s(566)]};if(e[s(990)](s(1084),s(1084)))return ue[s(1127)](n)||(n=ue[s(1682)+"er"](n)),e.JFdHd(this[s(766)],n[s(766)])&&e[s(981)](e[s(796)](this[s(1532)],31),1)&&n[s(1532)]>>>31===1?!1:this[s(1532)]===n[s(1532)]&&e[s(1232)](this[s(452)],n[s(452)]);this[s(449)](l[s(1425)],_0x1c9117),this[s(1801)]&&this[s(1801)](_0x1e886f)}[t(938)](){let n=t;if(!e[n(430)](n(1628),e[n(1383)]))return e[n(1164)](-1,this.low)&&e[n(947)](-1,this[n(1532)])?ue.fromBits(0,0,this.unsigned):e[n(1529)](-1,this[n(452)])?ue.fromBits(0,e[n(697)](this[n(1532)],1),this[n(766)]):ue[n(1603)](this[n(452)]+1,this.high,this[n(766)])}[t(1924)](n){let s=t;if(e[s(513)](s(1814),e[s(750)]))return n?this[s(1644)+"E"]():this.toBytesBE();{let l=_0x163024[s(1615)](ScJSEe[s(900)](_0x5d9104,this),_0x538381,..._0x27d270);return _0x27143d.set(l,_0x1f42a8.sort?_0x7262e7[s(424)]():[_0x16face]),ScJSEe.fhtSI(_0x29a93e,l)}}[t(1644)+"E"](){let n=t;if(e[n(1323)]("HTuES",e.vJuro))return this[n(766)]?e[n(1768)](e[n(1471)](e.mIKvb(this[n(1532)],0),_0x181ad0),this[n(452)]>>>0):e[n(724)](e.RUXkk(this.high,_0x1b0b44),e[n(875)](this[n(452)],0));{let s=this[n(1532)],l=this.low;return[e[n(1440)](255,l),e[n(433)](e.jjBLP(l,8),255),e[n(846)](e[n(820)](l,16),255),e[n(780)](l,24),255&s,e.CfUjB(e[n(820)](s,8),255),e[n(1203)](e[n(1343)](s,16),255),e[n(1400)](s,24)]}}[t(1105)+"E"](){let n=t,s=this.high,l=this[n(452)];return[e[n(1835)](s,24),e[n(1274)](s,16)&255,e.uCnZx(e[n(1569)](s,8),255),e[n(1583)](255,s),e.GUmeU(l,24),e[n(466)](e[n(1925)](l,16),255),e.Ipism(e[n(1745)](l,8),255),e[n(1930)](255,l)]}}let hl=new ue(0,0,!1),Yp=new ue(0,0,!0),Xp=ue[t(1603)](-1,2147483647,!1),Qp=ue[t(1603)](-1,-1,!0),eg=ue[t(1603)](0,-2147483648,!1);var on=(function(a){let n=t,s=e[n(1653)][n(654)]("|"),l=0;for(;;){switch(s[l++]){case"0":return a;case"1":a[a[e[n(1344)]]=5002]=e[n(1344)];continue;case"2":a[a[e[n(699)]]=5001]=e[n(699)];continue;case"3":a[a[n(1133)+n(1029)]=5004]=n(1133)+n(1029);continue;case"4":a[a[e[n(960)]]=5003]=e[n(960)];continue;case"5":a[a[e[n(763)]]=5005]=e[n(763)];continue}break}})({});class sr{constructor(n){let s=t;this[s(1088)]=n,this[s(593)]=null}}class xl extends sr{constructor(n,s){let l=t,f={qjXqt:function(m,v){return e[j(1466)](m,v)},nfuIu:function(m,v,y,p){return e.UoEPx(m,v,y,p)}};if(e.rRslN===e[l(1767)]){let m=new _0x3660a5(f.qjXqt(_0x52c148,_0x4bd349));return f[l(791)](_0x36b272,_0x5b0fbc,m,0),m}else super(n),this[l(1660)]=s&&s[l(1660)]||null}}class pl extends sr{constructor(n,s){let l=t,f=e[l(988)][l(654)]("|"),m=0;for(;;){switch(f[m++]){case"0":this.code=s&&s[l(792)]||5001;continue;case"1":this.message=s&&s[l(1660)]||"";continue;case"2":this[l(790)]=s&&s[l(790)]||0;continue;case"3":super(n);continue;case"4":this.error=s&&s[l(935)]||null;continue;case"5":this[l(417)]=s&&s[l(417)]||0;continue;case"6":this[l(1298)]=s&&s[l(1298)]||"";continue}break}}}class gl extends sr{constructor(n,s){let l=t;super(n),this[l(792)]=s&&s[l(792)]||0,this[l(1766)]=s&&s.reason||"",this[l(1897)]=s&&s.wasClean||!1,this[l(939)+l(1724)]=s&&s[l(939)+l(1724)]||!1}}class ml extends sr{constructor(n,s){let l=t;super(n),this[l(979)]=s&&s[l(979)]||null}}class wl extends ml{constructor(n,s){let l=t;super(n),this.data=s&&s[l(979)]||null,this[l(1660)]=s&&s[l(1660)]||null}}class _l extends sr{constructor(n,s){let l=t;super(n),this[l(979)]=s&&s[l(979)]||null}}function dt(a,{message:n,code:s,error:l}){return new pl(a,{message:n,code:s,error:l})}function gt(a,{code:n,reason:s,wasClean:l,willReconnect:f}){return new gl(a,{code:n,reason:s,wasClean:l,willReconnect:f})}function yl(a,{data:n,message:s}){return new wl(a,{data:n,message:s})}function bl(a,{data:n}){return new _l(a,{data:n})}function _a(a,{message:n}){return new xl(a,{message:n})}class El{constructor(n,s){let l=t;if(e[l(530)](e.hyIfM,e.TbXNf))this[l(635)+"s"]=n,this.maxRetries=s,this[l(1678)+"ndex"]=0,this[l(460)+l(675)+l(1044)+"t"]=0;else return _0x54046c.isLong(_0x52181b)||(_0x22db98=_0x10daf5[l(1682)+"er"](_0x1c2550)),e[l(1580)](this[l(766)],_0x5cfaff[l(766)])&&e[l(1021)](e.eayVO(this.high,31),1)&&e[l(1757)](e.tTLgh(_0x19dd0d.high,31),1)?!1:this.high===_0x27c03f.high&&this[l(452)]===_0x141091[l(452)]}[t(941)+t(1248)+t(532)](){let n=t;this[n(1678)+"ndex"]=0,this["currentE"+n(675)+n(1044)+"t"]=0}[t(1020)+"es"](){let n=t;this["currentEndpointT"+n(1044)+"t"]=0}[t(1436)+t(1001)+"nt"](){let n=t;if(e[n(629)](e[n(905)],e[n(905)])){this._clearPingTimer(),this["_pingPon"+n(1648)+"Id"]=_0x43a811(this[n(982)][n(1263)](this),this._options[n(840)+"rval"]);return}else return this[n(635)+"s"][this[n(1678)+n(1514)]]}[t(1436)+t(1001)+t(719)+t(1163)](){let n=t;return this[n(460)+n(675)+n(1044)+"t"]}[t(1074)+"chMaxTries"](){let n=t;return!!(e[n(1346)](this.currentIndex,this[n(635)+"s"][n(571)])||e[n(1014)](this[n(1678)+n(1514)],e[n(1508)](this[n(635)+"s"][n(571)],1))&&e[n(413)](this[n(460)+n(675)+n(1044)+"t"],this[n(1193)+"es"]))}[t(596)+t(1023)+t(1246)+"hedMaxRetries"](){let n=t;return e[n(1539)](this[n(1678)+n(1514)],this[n(635)+"s"][n(571)])?!0:e[n(1091)](this["currentE"+n(675)+"riesCount"],this[n(1193)+"es"])}[t(1122)+t(1334)+t(920)+"UpdateCo"+t(1097)](){let n=t;return this["currentE"+n(675)+"riesCount"]=1,this.currentIndex++,this[n(635)+"s"][this[n(1678)+n(1514)]]}[t(1436)+t(1001)+t(831)+t(1906)](){let n=t,s={nEBMY:function(l,f){return e[j(1245)](l,f)},rVdhv:function(l,f){return e.MDloq(l,f)},LimWf:function(l,f){return e[j(1228)](l,f)},qyxGF:function(l,f){return l&f},jzHfS:function(l,f){return e[j(1950)](l,f)},QepVV:function(l,f){return e[j(1825)](l,f)},SHDYu:function(l,f){return e[j(1657)](l,f)},yfzgO:function(l,f){return l<<f},XJORk:function(l,f){return l<f},Lzbcg:function(l,f){return e[j(1346)](l,f)},tVMHM:function(l,f){return e.tJkIV(l,f)},wIyhU:function(l,f){return e[j(444)](l,f)}};if(e[n(1506)](e[n(1848)],e[n(1795)]))return this[n(460)+n(675)+n(1044)+"t"]++,this[n(1436)+n(1001)+"nt"]();_0x5a2d46=_0x37bd0e[wUyiZR.nEBMY(wUyiZR[n(435)](_0x2d8c65,_0x8a212a),1)],_0x40cf9e=_0x2971c5[_0x553274+_0x2693b4+2],wUyiZR[n(1426)](wUyiZR[n(1439)](_0x906786|wUyiZR[n(1813)](_0x1f465b,8),49344),32896)?_0x475dd7+=_0x530ce7:(_0x146d53=wUyiZR[n(1414)](wUyiZR[n(1414)](wUyiZR[n(909)](wUyiZR[n(1439)](15,_0x186f1e),12),wUyiZR[n(1236)](wUyiZR[n(1439)](63,_0x46e290),6)),wUyiZR[n(1439)](63,_0x4bbd33)),wUyiZR[n(817)](_0xa8f83b,2048)||wUyiZR[n(1675)](_0xfce6e4,55296)&&wUyiZR.tVMHM(_0x11b027,57343)?_0x1ece5b+=_0x3bd090:(_0x5a2a82+=wUyiZR[n(1213)](_0x4d02a9,_0x4d6509),_0x3bc339+=2))}}let or=(e.WTTVo(e[t(1085)],typeof globalThis)&&e.Polef(e.Vmckk,globalThis[t(1519)+t(1698)].name)||e[t(1085)]!=typeof window&&e.wYXYz(e[t(1401)],window[t(1519)+t(1698)][t(1082)]))&&e[t(1619)](e[t(1085)],typeof document),On=e[t(1048)](e[t(1085)],typeof globalThis)&&(e.ToRAE(e[t(1832)],globalThis[t(1519)+t(1698)][t(1082)])||e[t(413)](e.tnAcH,globalThis.constructor[t(1082)]))&&t(1860)+"d"!=typeof tt,ni=(e[t(778)](e[t(1085)],typeof globalThis)&&globalThis["construc"+t(1698)][t(1082)]==="Object"||e[t(971)](e[t(1085)],typeof globalThis)||e.mKhnq(e[t(1085)],typeof globalThis)&&!!globalThis.WeixinJSBridge)&&e.tDKpJ(e.wyvrc,typeof wx),ri=e.wyvrc!=typeof globalThis&&(e[t(1117)](e[t(771)],globalThis.constructor[t(1082)])||"SharedWorkerGlob"+t(494)===globalThis[t(1519)+t(1698)][t(1082)]||e.zZeNm(e[t(1251)],globalThis[t(1519)+t(1698)][t(1082)]))&&e[t(821)](e[t(1085)],typeof self),tg=e.FMPTf(e[t(1085)],typeof globalThis)&&e[t(990)](e[t(1832)],globalThis[t(1519)+t(1698)].name)&&e[t(794)](e[t(1085)],typeof global)&&e[t(731)]("Object",global[t(1519)+t(1698)][t(1082)])&&e.wyvrc!=typeof process&&!!process.version;class ya{constructor(){let n=t;e[n(1757)](n(784),"OjbkT")?(_0x185aae[n(1892)](_0x4524fe,_0x7234a9),_0x4d7259.set(_0x19539b,_0x5e304b)):this._listeners={}}[t(449)](n,...s){let l=t,f=this[l(1354)+"rs"][n];if(f)f[l(1726)]()[l(1174)](m=>m.fn[l(1850)](m[l(1552)],s));else if(e[l(655)](e[l(566)],n)&&!this[l(1801)]){let m=s[l(571)]&&s[0];if(m instanceof Error)throw m;let v=new Error(e[l(482)]+(m?e.SxbEW(e.CmhcU(" (",m[l(1660)]),")"):""));throw v.context=m,m}return this}[t(1116)](n,s){let l=t;if(n===void 0)this[l(1354)+"rs"]={};else if(e[l(633)](void 0,s))this[l(1354)+"rs"][n]=null;else{let f=this[l(1354)+"rs"][n];if(f)for(let m=0;e[l(1276)](m,f[l(571)]);)e[l(1117)](f[m].fn,s)?f[l(555)](m,1):++m}return this}on(n,s,l){let f=t;return(this[f(1354)+"rs"][n]||(this[f(1354)+"rs"][n]=[])).push({fn:s,ctx:l||this}),this}}class ng extends ya{[t(1778)+"rrorMess"+t(1899)](n){let s=t;return n[s(649)]||n.errNo?("message: "+(n[s(649)]||"")+s(1862)+(n[s(1931)]||"")).trim():JSON.stringify(n)}constructor(n,s,l){let f=t;super(),this._socket=null,ni&&wx[f(1498)+f(1879)]&&(this._socket=wx[f(1498)+"ocket"]({url:n,protocols:s,header:l,fail:this[f(1269)+"ocketFai"+f(1946)][f(1263)](this),success:this[f(1269)+"ocketSuccessHand"+f(422)][f(1263)](this)})),On&&tt[f(1498)+f(1879)]&&(this[f(546)]=tt["connectS"+f(1879)]({url:n,protocols:s,header:l,fail:this["_createS"+f(573)+"lHandler"][f(1263)](this),success:this["_createS"+f(508)+"cessHand"+f(422)][f(1263)](this)}))}[t(1269)+"ocketSuc"+t(1719)+t(422)](){let n=t;Promise.resolve()[n(818)](()=>{let s=n;this[s(1281)+s(1189)]()})}["_createS"+t(573)+"lHandler"](n){let s=t,l={EwnTR:function(f,m){return e[j(598)](f,m)},XwQYN:function(f,m){return e[j(852)](f,m)},YdHFP:function(f,m){return e[j(1747)](f,m)},phXdJ:e.KCjzP,mFpTQ:function(f,m){return e.EDRXB(f,m)},KOKbD:e[s(1887)],XbjXr:function(f,m){return f===m},UWQep:e[s(1948)],HXfma:function(f,m,v){return e[s(1355)](f,m,v)},NCrWS:e[s(566)],jpaUg:s(737)};Promise[s(826)]()[s(818)](()=>{let f=s;if(l[f(841)](l[f(1502)],l[f(1502)])){let m=l[f(427)](dt,l[f(1318)],{message:this[f(1778)+f(1741)+f(1899)](n)});this[f(449)](l[f(1318)],m);let v=l.HXfma(gt,f(737),{reason:this[f(1778)+"rrorMess"+f(1899)](n)});this.emit(l[f(469)],v)}else return l[f(1914)](_0x1b4321,l.XwQYN(l[f(1647)](l.XwQYN(l[f(1672)]("index ou"+f(1588)+f(1101),_0x2aa254),l.phXdJ)+l[f(1415)](_0x10233e,1),l[f(1282)]),_0x31d45b))})}[t(1281)+t(1189)](){let n=t,s={gMWxD:e[n(830)],apzKN:function(l,f){return e[n(910)](l,f)},gRlgF:function(l,f){return e[n(1830)](l,f)},kivov:function(l,f){return e.ArKlW(l,f)},GyAKf:function(l,f){return l+f},BrTRn:function(l,f){return e[n(1667)](l,f)},Bsfcm:function(l,f){return e.qgLBJ(l,f)},VIqLP:function(l,f){return e.hTMBL(l,f)},PBTxw:function(l,f){return e.wAwgg(l,f)},UmbFY:function(l,f){return e[n(994)](l,f)},QlxRk:function(l,f){return e[n(872)](l,f)},wDcwI:function(l,f){return l|f},UjMJS:function(l,f){return l>>f},UHrfd:function(l,f){return e.aBgsE(l,f)}};this._socket[n(1182)](l=>{let f=n;this[f(449)]("open",bl(s[f(497)],{...l,data:l[f(649)]||""}))}),this._socket[n(891)](l=>{let f=n;this[f(449)](f(737),gt(e.sKTFp,{...l}))}),this[n(546)][n(898)+"e"](l=>{let f=n;this[f(449)](f(1660),yl(e[f(728)],{...l}))}),this[n(546)][n(809)](l=>{let f=n;if(e.yxpMT(e[f(484)],e[f(1124)]))this[f(449)](e[f(566)],e[f(1679)](dt,e[f(566)],{...l,message:l[f(649)]||""}));else{let m=_0x507358.charCodeAt(_0x214f77);m>=55296&&bDBoig[f(1673)](m,56319)&&bDBoig[f(871)](_0x3ed107+1,_0x3fa97b)&&(m=bDBoig[f(1658)](bDBoig[f(651)](bDBoig[f(590)](m,10),_0x40a2cc[f(1384)+"At"](++_0x2d21d6)),56613888)),m<128?_0xc64a8a[_0x5a8eae++]=m:(bDBoig[f(871)](m,2048)?_0x2a8e2a[_0x501467++]=bDBoig.Bsfcm(bDBoig[f(673)](m>>6,31),192):(bDBoig[f(1017)](m,65536)?_0x407610[_0x1bd976++]=bDBoig.Bsfcm(bDBoig[f(1474)](bDBoig[f(715)](m,12),15),224):(_0x6d521e[_0x1cb6a5++]=bDBoig[f(997)](bDBoig[f(1474)](bDBoig[f(715)](m,18),7),240),_0x33e40d[_0x4f0621++]=bDBoig[f(1474)](bDBoig[f(576)](m,12),63)|128),_0x450b61[_0x4db1b6++]=bDBoig.wDcwI(bDBoig.UHrfd(bDBoig[f(576)](m,6),63),128)),_0x9d921b[_0x5143b5++]=bDBoig[f(1099)](bDBoig[f(1207)](63,m),128))}})}[t(842)](n){let s=t;if(e[s(1447)](n,Uint8Array)){let l=n[s(1412)][s(1726)](n.byteOffset,e[s(866)](n.byteLength,n[s(1040)+"et"]));this[s(546)]&&this[s(546)][s(842)]({data:l,fail:f=>{let m=s;this[m(449)](e[m(566)],dt(e[m(566)],{message:this[m(1778)+"rrorMessage"](f)}))}})}else this[s(546)]&&this._socket.send({data:n,fail:l=>{let f=s;this.emit(e[f(566)],e[f(1310)](dt,e[f(566)],{message:this[f(1778)+f(1741)+f(1899)](l)}))}})}[t(737)](n,s){let l=t;this[l(546)]&&this._socket[l(737)]({code:n,reason:s})}[t(1821)+t(958)](n,s){this.on(n,s)}[t(767)+t(921)+"ner"](n,s){this[t(1116)](n,s)}get readyState(){let n=t;return this[n(546)][n(545)+"te"]}get[t(881)+"pe"](){return this[t(546)].binaryType}set[t(881)+"pe"](n){}get[t(1155)](){let n=t;return this[n(546)][n(1155)]}get protocol(){let n=t,s={PvFOd:function(l,f){return l(f)},kWsXI:function(l,f){return l+f}};if(e[n(753)](e[n(1220)],e[n(1220)]))return this._socket[n(860)];{let f=""+_0x20c5e5[n(1240)](),m=_0x5a60b3||(_0x4f5ccf=WQOUgg.PvFOd(_0x1d5056,_0x162341)),v=_0x35e167[n(1783)]()[n(672)](16)[n(1726)](-6);return WQOUgg[n(908)]("02"+f+m,v)}}get[t(476)+"ns"](){let n=t;return this[n(546)][n(476)+"ns"]}get["buffered"+t(1371)](){let n=t,s={lTMPm:function(l,f){return l instanceof f},kWuOo:function(l,f){return e.CnbaB(l,f)}};if(e.tbATS(e.uMzPZ,e[n(646)])){if(zWjtQt[n(1820)](_0x43f120,_0x338a41))return _0x858648(_0x3d2697);if(_0x52efeb[n(1488)](_0x31bbd2))return _0x1c686f.get(_0x1631f3);let l=_0x337c3e(_0x466dc2);return zWjtQt[n(1725)](l,_0x3e6cb)&&(_0x5076d1.set(_0x4b4a2a,l),_0x470235.set(l,_0x3130b9)),l}else return 0}}function rg(a,n){let s=t;if(n)return new n(a[s(1155)],a[s(860)]);if(e[s(470)](ni,On))return new ng(a[s(1155)],a.protocol,a[s(1739)]);if(e[s(470)](or,ri)&&e[s(1956)](e.wyvrc,typeof WebSocket)&&WebSocket)return new WebSocket(a[s(1155)],a[s(860)+"s"])}function ig(a){let n=t,s={OHIzc:function(l,f){return e[j(900)](l,f)},WtAbm:e[n(547)]};if(e[n(1232)](n(1242),"ZQvdw")){let l=e[n(1699)].split("|"),f=0;for(;;){switch(l[f++]){case"0":return!1;case"1":if(ni&&wx[n(1498)+n(1879)])return!0;continue;case"2":if(On&&tt[n(1498)+"ocket"])return!0;continue;case"3":if(a)return!0;continue;case"4":if(e[n(470)](or,ri)&&e[n(1956)](e[n(1085)],typeof WebSocket)&&WebSocket)return!0;continue}break}}else{let l=_0x3a17e3[n(1397)+n(1009)](e.tjdwn);_0x3fddf7[n(1546)+n(1195)]=f=>{let m=n;_0x42807a[m(1270)]["removeCh"+m(1542)](l),_0x32dd1f[m(1546)+"JSONP"]=void 0,s[m(1691)](_0x20b3b1,f&&f[m(1264)]||s[m(1871)])},l[n(1088)]=e[n(965)],l[n(835)]=e[n(496)](_0x41479a[n(1120)](/^ws/,e[n(526)]),n(1589)+n(1202)+n(1297)+"P");try{_0x52809a[n(1270)][n(653)+n(1542)](l)}catch{_0x4fc319[n(1270)][n(1237)+n(1542)](l)}}}function vl(a,n,s){let l=t,f=-1;async function m(v){let y=j;return e[y(910)](v,f)?Promise[y(1640)](new Error(y(1500)+"alled mu"+y(1008)+y(964)+y(1459))):(f=v,e.mqpBQ(v,s.length)?Promise[y(826)]():s[v][y(1263)](a)(n,m[y(1263)](null,e[y(1823)](v,1))))}e[l(565)](m,0)}function Sl(a){let n=t;if(e[n(517)](e[n(1230)],e[n(1230)])){let s=0,l=0;for(let f=0;e[n(752)](f,a[n(571)]);++f)l=a[n(1384)+"At"](f),e.WBvIx(l,128)?s+=1:e.RNaAn(l,2048)?s+=2:e[n(1624)](64512,l)===55296&&e[n(1757)](e.wpQpC(64512,a[n(1384)+"At"](e[n(1316)](f,1))),56320)?e[n(931)](n(585),e.lCDpS)?ScJSEe[n(1842)](_0x28fe67,_0x25e3d8)&&_0xdb7816[n(1892)](_0x25c0f8,_0x7fd4b):(++f,s+=4):s+=3;return s}else return!!(this[n(1678)+"ndex"]>=this.endpoints[n(571)]||this[n(1678)+n(1514)]===e[n(1010)](this[n(635)+"s"].length,1)&&e[n(927)](this[n(460)+n(675)+n(1044)+"t"],this[n(1193)+"es"]))}function Il(a,n,s){let l=t;if(e.TRlkj(e.LMihJ,"jzcMF"))_0x2752a5[_0x1ef173++]=e[l(1227)](e[l(962)](_0x90ab8,6),192),_0x4768fc[_0x31192d++]=e[l(758)](63&_0x3fa56a,128);else{if(e[l(1201)](e.doncX(s,n),1))return"";let f="";for(let m=n;m<s;){let v=a[m++];if(e[l(1740)](v,127))f+=String[l(1773)+l(1094)](v);else if(v>=192&&e[l(1680)](v,224))f+=String[l(1773)+l(1094)](e[l(1524)](e[l(952)](e[l(466)](31,v),6),e[l(1670)](63,a[m++])));else if(v>=224&&e[l(832)](v,240))f+=String[l(1773)+l(1094)](e.hhWKF(e[l(1944)](e[l(1837)](e[l(1449)](15,v),12),e[l(528)](e[l(1654)](63,a[m++]),6)),e.dVNTZ(63,a[m++])));else if(e[l(1646)](v,240)){let y=e[l(1010)](e[l(789)](e.fwnYL(e.szMSz(e.kTliZ(7,v),18),e[l(528)](e[l(1289)](63,a[m++]),12))|e[l(1523)](e[l(1446)](63,a[m++]),6),e[l(994)](63,a[m++])),65536);f+=String[l(1773)+l(1094)](e.MDloq(55296,e[l(962)](y,10))),f+=String[l(1773)+l(1094)](e[l(1386)](56320,e.qTNlY(1023,y)))}}return f}}function ba(a,n,s){let l=t,f=s,m,v;for(let y=0;y<a[l(571)];++y)if(m=a[l(1384)+"At"](y),e[l(1614)](m,128))n[s++]=m;else if(m<2048)n[s++]=m>>6|192,n[s++]=e.WhHtM(63,m)|128;else if(e[l(783)](e.kTliZ(64512,m),55296)&&(64512&(v=a[l(1384)+"At"](e[l(1181)](y,1))))===56320){let p=e[l(556)][l(654)]("|"),A=0;for(;;){switch(p[A++]){case"0":m=e[l(616)](e[l(1145)](65536,e.sanzn(1023,m)<<10),e[l(704)](1023,v));continue;case"1":n[s++]=m>>18|240;continue;case"2":n[s++]=e.rOqcO(e[l(1504)](m>>6,63),128);continue;case"3":n[s++]=e[l(1524)](e[l(1654)](e[l(962)](m,12),63),128);continue;case"4":n[s++]=e[l(936)](e[l(621)](63,m),128);continue;case"5":++y;continue}break}}else n[s++]=e[l(1266)](m,12)|224,n[s++]=e.rwtEH(e[l(962)](m,6),63)|128,n[s++]=e.UvRIs(e.rwtEH(63,m),128);return e[l(954)](s,f)}async function Al(a){let n=t;if(e[n(1302)](e[n(1065)],typeof a)){let s=new Uint8Array(e[n(451)](Sl,a));return e[n(457)](ba,a,s,0),s}return e.GFsen(a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}function sg(a){let n=t;try{return e[n(1359)](n(1357),typeof a)&&(e[n(1842)](a,ArrayBuffer)||a.buffer&&a[n(1412)]instanceof ArrayBuffer)||e.uwWSn!=typeof a?"":(JSON[n(1004)](a),n(1168)+"ion/json")}catch{return n(1357)==typeof a?e[n(1114)]:""}}let og=(a,n)=>{let s=t;switch(a){case e[s(1119)]:case s(574):return{["x-use-"+a]:1,"x-tt-env":n};default:return{}}};class ag{constructor(n){let s=t;if(e.bLQGt(s(882),e.mwIOd))this["maxLossC"+s(1163)]=n,this[s(1404)]=0;else return s(1546)+"_"+this[s(1639)]}[t(1338)](){let n=t,s={rwPGE:e[n(1934)],XJIKE:e[n(1923)],zalFU:function(l,f){return e[n(614)](l,f)},RtpVH:e[n(1702)],AqIhu:e.FHgik,FRnlM:function(l){return e[n(1943)](l)}};if(e[n(479)](e[n(949)],n(1574)))this[n(1404)]++;else{let{enableAutoAck:l}=this[n(690)],f=_0x1ac0b6(_0x14cbb3[n(1660)][n(1739)],s[n(1107)],"1"),m=_0x4097cf(_0x5b8366[n(1660)][n(1739)],s[n(1573)],"1"),v=_0x3ad811.call(this,_0x213cd1);if(s[n(1570)](l,f)){let{SeqID:y,LogID:p,service:A,LogIDNew:L,method:F}=_0x14608a[n(1660)];this[n(1547)]({SeqID:y,LogID:p,LogIDNew:L,service:A,method:F,headers:[{key:n(698),value:"1"},{key:s[n(525)],value:L||""},{key:s[n(1621)],value:"0"}]})}m&&!v[n(944)]&&this[n(1839)+n(475)+"ageEvent"](_0x87cd7),s.FRnlM(_0x1ee2b7)}}["checkRea"+t(1353)+"nt"](){let n=t;return e[n(1936)](this[n(1404)],this[n(1411)+n(1163)])}[t(1109)+t(706)](n=0){let s=t;this["maxLossC"+s(1163)]=n,this.count=0}}async function cg(a){let n=t,s={ytqVM:function(l,f){return e[j(470)](l,f)},iLtdM:e[n(1268)],aSlKJ:function(l,f){return e[n(1027)](l,f)},GQrwB:e.egBwa};return new Promise(l=>{let f=n,m={XVvnu:f(1306),rRStZ:function(v,y){return e[f(577)](v,y)},IQHEi:"success",Ayhcf:function(v,y){return e[f(1815)](v,y)},eqLjI:e[f(1300)],SFjLe:e[f(1881)],aqzIh:function(v,y,p){return e[f(1123)](v,y,p)}};if(e[f(927)](e[f(507)],e[f(667)])){let v=this[f(1062)].getItem(this[f(1369)]),y=_0x39d235.parse(s.ytqVM(v,"{}"));return _0x2c6271[f(1139)](y)}else{if(!or)return e[f(598)](l,e[f(547)]);try{let v=document[f(1397)+f(1009)](e.tjdwn);window[f(1546)+f(1195)]=y=>{let p=f;s.iLtdM===s[p(1234)]?(document[p(1270)][p(1237)+"ild"](v),window.frontierJSONP=void 0,s[p(1901)](l,y&&y.msg||s[p(1527)])):(this[p(676)+p(1138)].push(_0x265dc9),this[p(1567)](m[p(634)],_0x7afdf4))},v.type=e.ABjTG,v[f(835)]=e[f(1252)](a[f(1120)](/^ws/,f(1150)),f(1589)+f(1202)+f(1297)+"P");try{document.body[f(653)+f(1542)](v)}catch{document[f(1270)][f(1237)+f(1542)](v)}}catch{if(e[f(1224)](e[f(1558)],e[f(1558)]))return new _0x4d7b29((v,y)=>{let p=f,A={aFFFt:function(q,$){return m[j(1430)](q,$)},VWTbl:m[p(1796)],bVNOJ:p(572)+"e_timeout",bzuKp:function(q,$){return m.Ayhcf(q,$)},LoSND:m[p(1348)],VpSpY:m[p(1666)]};this["_clearPi"+p(548)](),this[p(480)+p(1648)+"Id"]=m.aqzIh(_0x163923,this[p(982)][p(1263)](this),this[p(690)][p(840)+p(1055)]);let L=()=>{let q=p;A[q(1392)](v,A[q(1607)]),this[q(1116)]("ping_once_success",L),this[q(1116)](A.bVNOJ,F)},F=()=>{let q=p;A.bzuKp(y,A.LoSND),this[q(1116)](A.VpSpY,L),this.off(A[q(1833)],F)};this.on(m[p(1666)],L),this.on(p(572)+p(587)+"t",F),this[p(982)]()});window[f(1546)+f(1195)]=void 0,e[f(565)](l,e.egBwa)}}})}function an(a,n,s){let l=t;return!!a?.find(f=>f[l(1553)]===n&&f[l(1279)]===s)}function ar(a,n){let s=t;if(e[s(1358)](e[s(744)],"ANgvx"))this[s(1610)+"er"]&&_0x34b654[s(1821)+s(958)](e[s(615)],this["_handleO"+s(1469)]),this[s(1610)+"er"]&&_0x1b0292[s(1821)+"Listener"](e[s(468)],this[s(1438)+"ffLine"]),this[s(1610)+"er"]&&_0x5ab134["addEvent"+s(958)](e[s(1126)],this["_handleP"+s(1581)]),this._isBrowser&&_0x3fa2a3["addEvent"+s(958)](s(1191),this[s(1206)+s(1424)]);else return a?.find(l=>l.key===n)?.[s(1279)]}let Ea=null;async function dg(){let a=t;return Ea||(Ea=Promise[a(826)]()[a(818)](zt.bind(zt,e.PUwtf))),Ea}class lg extends ya{constructor(n,s){let l=t;super(),this._dbName=n,this[l(1793)]=s,this._qosDB=void 0,this["_initPro"+l(912)]=null}async[t(1633)](){await this[t(1874)]()}async _init(){let n=t,s={UyroC:e.tlTCp};if(e[n(1563)](e[n(636)],n(1056))){if(this[n(1062)])return;if(this[n(1918)+n(912)])return this[n(1918)+n(912)];try{let l=this[n(668)],f=this[n(1793)];this["_initPro"+n(912)]=(async()=>{let m=n,v={XzuhQ:function(y,p){return y(p)},qsPVF:e.iXBRY};if(e[m(849)]!==m(1771)){let{openDB:y}=await e[m(431)](dg);this[m(1062)]=await e[m(457)](y,m(1546)+"_"+l,1,{upgrade(p){let A=m;p[A(648)+A(1636)+"e"](l,{keyPath:f})}})}else{let y={IhPKo:function(p,A){let L=m;return jAiPfX[L(1572)](p,A)},otMxh:function(p,A){return p(A)}};_0x4791da[m(1821)+m(958)](jAiPfX[m(1511)],p=>{let A=m;_0x5c6253(y[A(1406)](_0x28c76d,_0x14e0c3[A(1774)]),p.oldVersion,p[A(1403)+"on"],y[A(1261)](_0x2605dc,_0x59d90c[A(1499)+A(1169)]))})}})(),await this[n(1918)+"mise"]}catch(l){console[n(1870)](l)}finally{this["_initPro"+n(912)]=null}}else{let l=s[n(461)][n(654)]("|"),f=0;for(;;){switch(l[f++]){case"0":this["_endpoin"+n(1917)]?.[n(941)+"pointCon"+n(532)]();continue;case"1":this[n(553)+n(1003)]=!1;continue;case"2":this._connect();continue;case"3":this._isInit=!0;continue;case"4":this._pingLossCounter?.[n(1109)+n(706)]();continue}break}}}async[t(1935)](n){let s=t;if(e.SXjIk("IDmih",e[s(436)]))try{return await this[s(1874)](),this[s(1062)]?.[s(1935)](this._dbName,n)}catch(l){console[s(1870)](l)}else return 0}async set(n,s){let l=t;return await this[l(1874)](),this[l(1062)]?.put(this[l(668)],n)}async[t(725)](n){let s=t;try{return await this[s(1874)](),this[s(1062)]?.delete(this[s(668)],n)}catch(l){console.log(l)}}async[t(1134)](){let n=t;try{return await this._init(),this[n(1062)]?.[n(1134)](this[n(668)])}catch(s){console.log(s)}}async[t(1565)](){let n=t;return await this[n(1874)](),this[n(1062)]?.[n(602)+"ys"](this[n(668)])}async[t(942)](){return await this[t(1874)](),this._qosDB?.getAll(this._dbName)}async[t(1789)](){let n=t;if(e[n(1117)](e.CPrCA,n(1287)))try{this[n(1062)]?.[n(737)](),this[n(1062)]=void 0}catch(s){console[n(1870)](s)}else return _0x2f4e15&&_0x5dbc2f.isLong===!0}get[t(748)](){let n=t;if(e.oymEr===e[n(1456)])try{return!!this[n(1062)]}catch(s){return console[n(1870)](s),!1}else _0x3153bc(_0x4a2078,10),_0xf47ed7(_0x2d5421,_0x18da07)}}class ug{constructor(n,s){let l=t;this[l(1639)]=n,this._pathKey=s,this._qosDB=localStorage}async openDB(){}get[t(1369)](){let n=t;return n(1546)+"_"+this[n(1639)]}async get(n){let s=t,l=this[s(1062)][s(1903)](this._prefix);return JSON[s(1004)](e[s(1693)](l,"{}"))[n]}async[t(1892)](n,s){let l=t,f=this._qosDB[l(1903)](this[l(1369)]),m=JSON[l(1004)](e.EDRXB(f,"{}"));return m[s||n[this[l(1650)]]]=n,this[l(1062)][l(1067)](this[l(1369)],JSON[l(1878)+"y"](m)),s||n[this._pathKey]}async del(n){let s=t;if(e[s(1529)](e[s(1662)],e[s(1170)]))this[s(1127)]=!0,this[s(452)]=e[s(1053)](0,_0x37890d),this.high=e[s(1058)](0,_0xbcfe9a),this.unsigned=!!_0x2d1fc8;else{let l=this._qosDB.getItem(this._prefix),f=JSON[s(1004)](e[s(854)](l,"{}"));return f[n]=void 0,this[s(1062)][s(1067)](this[s(1369)],JSON[s(1878)+"y"](f))}}async[t(1134)](){let n=t;return this[n(1062)][n(1134)]()}async keys(){let n=t,s=this[n(1062)][n(1903)](this[n(1369)]),l=JSON.parse(e[n(470)](s,"{}"));return Object.keys(l)}async[t(942)](){let n=t,s=this._qosDB[n(1903)](this[n(1369)]),l=JSON[n(1004)](s||"{}");return Object[n(1139)](l)}[t(1789)](){let n=t,s={tESfd:function(l,f){return e[j(879)](l,f)},iYoMq:function(l,f){return l<f},HNTqu:function(l,f){return l&f},haHCS:function(l,f){return l&f}};if(e[n(1395)](n(743),e[n(1753)]))return Promise[n(826)]();{let l=0,f=0;for(let m=0;UfLKBr.tESfd(m,_0x498eb5[n(571)]);++m)f=_0x342fd1[n(1384)+"At"](m),UfLKBr[n(1616)](f,128)?l+=1:UfLKBr.iYoMq(f,2048)?l+=2:UfLKBr[n(543)](64512,f)===55296&&UfLKBr.haHCS(64512,_0x37c133[n(1384)+"At"](m+1))===56320?(++m,l+=4):l+=3;return l}}get isReady(){let n=t;return e[n(1911)](e[n(1081)],e.jvqtg)?this[n(546)][n(860)]:!!this._qosDB}}class fg{constructor(n,s){let l=t;this[l(1639)]=n,this[l(1650)]=s,this[l(1062)]=On?tt:ni?wx:null}async[t(1633)](){}get[t(1369)](){return"frontier_"+this._DBName}async get(n){let s=t,l=this[s(1062)][s(953)+"geSync"](this[s(1369)]);return JSON[s(1004)](l||"{}")[n]}async[t(1892)](n,s){let l=t,f=this[l(1062)][l(953)+l(416)](this._prefix),m=JSON[l(1004)](e[l(928)](f,"{}"));return m[s||n[this[l(1650)]]]=n,this[l(1062)].setStorageSync(this[l(1369)],JSON[l(1878)+"y"](m)),s||n[this._pathKey]}async del(n){let s=t,l=this[s(1062)][s(953)+s(416)](this[s(1369)]),f=JSON[s(1004)](l||"{}");return f[n]=void 0,this._qosDB[s(1510)+s(416)](this._prefix,JSON.stringify(f))}async[t(1134)](){let n=t;return this[n(1062)][n(453)+n(1472)]()}async[t(1565)](){let n=t,s=this[n(1062)]["getStora"+n(638)+"nc"](this._prefix),l=JSON[n(1004)](e.UfnlS(s,"{}"));return Object[n(1565)](l)}async[t(942)](){let n=t,s=this[n(1062)]["getStora"+n(638)+"nc"](this._prefix),l=JSON[n(1004)](e[n(922)](s,"{}"));return Object[n(1139)](l)}[t(1789)](){return Promise[t(826)]()}get[t(748)](){return!!this._qosDB}}function kl(a,n){let s=t;if(e.wBplf(On,On))return new fg(a,n);if(e[s(470)](or,ri)&&e[s(1090)](e[s(1085)],typeof indexedDB))return new lg(a,n);if(e[s(720)](or,ri)&&e[s(1359)](e.wyvrc,typeof localStorage))return new ug(a,n);throw new Error(e[s(578)])}class hg{constructor(){let n=t;this["_interva"+n(660)+"Id"]=null,this._interval=36e5,this._qosDB=e.rxZpA(kl,e[n(959)],e[n(1299)])}async[t(459)+t(456)](){let n=t;e[n(444)](clearInterval,this["_interva"+n(660)+"Id"]),this["_interva"+n(660)+"Id"]=setInterval(()=>{this["flushExp"+n(1537)]()},this[n(459)+"l"])}async[t(1633)](){let n=t;await this._qosDB.openDB()[n(818)](()=>{let s=n;this[s(459)+s(456)]()})}async flushExpired(){let n=t;(await this[n(1062)]?.getAll()||[])[n(1713)](({timestamp:f})=>f<Date[n(1240)]())[n(1174)](f=>{let m=n;this._qosDB?.[m(725)](f.message_id)})}async[t(725)](n){return this[t(1062)]?.del(n)}async[t(1892)](n,s){let l=t;return this[l(1062)]?.[l(1892)]({message_id:n,timestamp:s})}async get(n){let s=t;return this[s(1062)]?.[s(1935)](n)}async[t(1789)](){let n=t;clearInterval(this[n(459)+n(660)+"Id"]),await this[n(1062)]?.[n(1789)]()}get[t(748)](){let n=t;return this._qosDB?.[n(748)]}}function va(a){let n=t;if(e[n(1442)](n(1908),e.rqvCK)){let s=!!this[n(690)][n(1805)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[n(1637)](an,a[n(1660)][n(1739)],e[n(1912)],"2"),f=l&&e[n(457)](an,a[n(1660)][n(1739)],e[n(682)],"1"),m=l&&e[n(1637)](an,a.message[n(1739)],e.LrzUj,"1"),v=m?ar(a[n(1660)].headers,n(1620)+n(1605)+n(862))?.[n(654)](",")[n(1713)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:m,ackMsgIds:v}}else _0x493412.o=(s,l)=>_0x265286[n(501)+"e"].hasOwnProperty[n(1615)](s,l)}async function Tl(){let a=t;return this[a(1939)+a(1697)]||(this[a(1939)+a(1697)]=new hg),this[a(1939)+a(1697)][a(748)]||await this[a(1939)+a(1697)][a(1633)](),this["_QoSMana"+a(1697)]}async function xg(a,n){let s=t,l={tANmS:function(p,A,L){return e.qXBjW(p,A,L)}},{enableAutoAck:f}=this._options,m=an(a[s(1660)][s(1739)],e[s(1934)],"1"),v=e[s(628)](an,a[s(1660)][s(1739)],e[s(1923)],"1"),y=va.call(this,a);if(e.bJudW(f,m))if(e[s(1014)](e[s(877)],e[s(877)])){let{SeqID:p,LogID:A,service:L,LogIDNew:F,method:q}=a[s(1660)];this[s(1547)]({SeqID:p,LogID:A,LogIDNew:F,service:L,method:q,headers:[{key:e[s(1923)],value:"1"},{key:e[s(1702)],value:e[s(720)](F,"")},{key:"ack_code",value:"0"}]})}else mzDwQb[s(1208)](_0x1bd36c,_0x3fe7c0,127&_0x42167f|128),_0x576132>>>=7;v&&!y[s(944)]&&this[s(1839)+s(475)+s(1462)](a),e[s(410)](n)}async function pg(a,n){let s=t;this._debug(e.RZhJT,a[s(1660)]),e.dXXJk(n)}async function gg(a,n){let s=t,l={WYGeF:function(m,v,y){return e[j(1198)](m,v,y)},yXJMY:s(935)},f=e[s(1617)](rn,await e.EzFuS(Al,a.data));try{if(e[s(1842)](f[s(603)],Uint8Array)){let m=e.oKmWk(this[s(690)][s(1146)+s(1073)],Object)?{force:!!this[s(690)].payloadEncoding.force,encoding:this[s(690)][s(1146)+s(1073)][s(503)]?this._options.payloadEncoding[s(503)][s(1120)](/\s/g,"")[s(1427)+s(584)]():""}:{force:!1,encoding:this[s(690)][s(1146)+s(1073)]?this[s(690)][s(1146)+s(1073)].replace(/\s/g,"")["toLowerC"+s(584)]():""},v=f[s(1146)+s(1073)]?f["payloadE"+s(1073)][s(1120)](/\s/g,"")[s(1427)+"ase"]():"",y=e[s(1842)](this[s(690)]["payloadT"+s(1408)],Object)?{force:!!this[s(690)]["payloadT"+s(1408)][s(656)],type:this[s(690)][s(703)+"ype"][s(1088)]?this[s(690)]["payloadT"+s(1408)].type[s(1120)](/\s/g,"")["toLowerC"+s(584)]():""}:{force:!1,type:this._options[s(703)+s(1408)]?this._options["payloadT"+s(1408)][s(1120)](/\s/g,"")[s(1427)+s(584)]():""},p=f["payloadT"+s(1408)]?f[s(703)+s(1408)].replace(/\s/g,"")[s(1427)+s(584)]():"",A=y[s(656)]?y.type:p||y[s(1088)],L=m[s(656)]?m[s(503)]:v||m[s(503)],F=[e.pNZPj,e[s(1361)],e[s(1320)],e[s(1065)]],q=[e.LeakF,e[s(1360)]];this._options[s(447)+s(1484)+"extPayload"]&&F.includes(A)&&(!L||q[s(1212)](L))?f[s(625)+s(1375)]=e[s(628)](Il,f[s(603)],0,f.payload[s(412)+"th"]):f[s(625)+s(1375)]=""}else f["textPayl"+s(1375)]=""}catch(m){if(e.rMrAY(e.BTNZK,e[s(1883)])){let v=l[s(1421)](_0x18c2b3,l[s(421)],{message:_0x4a5372.message,code:_0x200059[s(1183)+"OR"],error:_0x238b6f});this[s(1839)+s(489)+s(1916)](v)}else f[s(625)+s(1375)]="",console[s(1870)](m)}a[s(1660)]=f,e.TxmpJ(n)}function mg(a,n,s){let l=t,f={IUrss:function(A,L){return e[j(1106)](A,L)},qreyr:function(A,L){return A>L}},m=e[l(510)](s,8192),v=e[l(950)](m,1),y=null,p=m;return function(A){let L=l;if(e.nWXlP(A,1)||e.vWLsU(A,v))return a(A);if(e[L(1875)](e[L(1256)](p,A),m))if(e[L(1303)]===L(1162)){let q=_0x3097b7[L(1241)],$=_0x37b6f5[L(1929)],ge=_0x30fc86[L(893)],We=tnhiSn.IUrss($,_0x16f92c);if(We>q[L(571)]){let It=new _0x4775bb(2*We);It[L(1892)](q),_0xa769d5[L(1241)]=It}return _0x20d0d6[L(1929)]=We,tnhiSn[L(1215)](We,ge)&&(_0x397385[L(893)]=We),$}else y=a(m),p=0;let F=n[L(1615)](y,p,p+=A);return e[L(1752)](7,p)&&(p=e.UvRIs(7,p)+1),F}}let wg=4294967295;function _g(a,n,s){let l=t;return RangeError(e[l(1181)](e.bvxDC(e[l(755)](e.YEpMF(e[l(852)](e.roboV,a),l(1422)),e[l(1076)](n,1)),e[l(1887)]),s))}function yg(a,n,s){let l=t;if(e[l(1390)](s,wg))throw new Error(e[l(563)]);let f=3;for(;e[l(1346)](f,0);){let m=255&s;e[l(1637)](Ia,m,a,n+f),s>>>=8,f--}return e.tvIJm(n,4)}function bg(a,n){let s=t,l=0,f=n,m=e[s(1858)](n,4);for(;f<m;){let{value:v,offset:y}=e[s(685)](Sa,a,f);f=y,l=e[s(1184)](e[s(1594)](l,8),0),l+=v}return{value:l,offset:m}}function Eg(a,n,s){let l=t;if(e[l(658)]("elsGe",e.mhacH))for(var f in _0x11c01a)_0x22c888.o(_0x326885,f)&&!_0x4bb2d4.o(_0x28d6ba,f)&&_0x57d436[l(1625)+l(1342)](_0xf1baa6,f,{enumerable:!0,get:_0x385f5f[f]});else{let m=e[l(1730)][l(654)]("|"),v=0;for(;;){switch(m[v++]){case"0":return e[l(683)](e[l(1341)](ba,a,n,s),s);case"1":if(!a)return s;continue;case"2":if(a.length<40)return e[l(420)](e.UoEPx(ba,a,n,s),s);continue;case"3":if(n[l(1075)])return e[l(1019)](n[l(1075)](a,s),s);continue;case"4":if(n[l(579)+"e"])return e[l(1695)](n[l(579)+"e"](a,s),s);continue}break}}}function vg(a,n){let s=t,l=new ue(e.Mnjvt(a[e[s(810)](n,4)],24)|e[s(1132)](a[e[s(1751)](n,5)],16)|a[e[s(1460)](n,6)]<<8|a[n+7],e.xywAB(e[s(552)](e.gUvPR(e[s(1837)](a[e.MrMWQ(n,0)],24),e.Mnjvt(a[e.hSIEK(n,1)],16)),a[e[s(808)](n,2)]<<8),a[e.siyxW(n,3)]),!0);return n+=8,{value:l,offset:e[s(1256)](n,8)}}function Sg(a,n,s){let l=t,f=a[l(452)],m=a[l(1532)];return n[s]=e[l(1450)](m,24),n[e[l(874)](s,1)]=e[l(1225)](m,16)&255,n[e.tCvZf(s,2)]=e.SqsBC(e[l(1280)](m,8),255),n[s+3]=255&m,n[e.vDOTQ(s,4)]=e[l(1891)](f,24),n[e.siyxW(s,5)]=e.kXgiR(e[l(597)](f,16),255),n[e[l(724)](s,6)]=f>>>8&255,n[e[l(1701)](s,7)]=e[l(945)](255,f),s+=8,s}function Sa(a,n){let s=t,l={SKfCu:function(f,m,v,y){return f(m,v,y)},EtxOy:e[s(1912)],OHePg:e.EiGfg,vEVGz:s(1620)+s(816)+"k",ckZgL:function(f,m,v){return e[s(1559)](f,m,v)},vxRbv:e[s(1156)]};if(e[s(1032)](e[s(913)],e[s(913)])){let f=!!this[s(690)][s(1805)+"S"];if(!f)return{enabled:f,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let m=eriaXg[s(892)](_0x4d1b8b,_0x4e6c8c.message.headers,eriaXg[s(1685)],"2"),v=m&&_0x40f671(_0x54d29c[s(1660)][s(1739)],eriaXg[s(534)],"1"),y=m&&eriaXg[s(892)](_0x5c68af,_0x3b7fd5.message[s(1739)],eriaXg.vEVGz,"1"),p=y?eriaXg[s(1006)](_0x4a12b7,_0x4e86a4[s(1660)][s(1739)],eriaXg.vxRbv)?.[s(654)](",").filter(_0x139e0a)||[]:[];return{enabled:f,isQoSMessage:m,isQoSAck:v,isAckCleanupMessage:y,ackMsgIds:p}}else return a[s(1214)+"8"]?{value:a[s(1214)+"8"](n),offset:e.kKCOz(n,1)}:{value:255&a[n],offset:e.lCsQB(n,1)}}function Ia(a,n,s){let l=t;return n[l(1489)+"t8"]?n[l(1489)+"t8"](a,s):n[s]=e[l(1853)](255,a),e.EBYcZ(s,1)}let Ig=function(a){return new Uint8Array(a)},Ag=e[t(1618)](t(1860)+"d",typeof Buffer)?Buffer[t(1063)+t(864)]:mg(Ig,Uint8Array.prototype[t(1273)]);(()=>{let a=t;if(e[a(876)](e[a(1942)],a(1179))){let n=4294967295;return function(s,l,f=!0){let m=a,v=e[m(1054)][m(654)]("|"),y=0;for(;;){switch(v[y++]){case"0":n=e[m(1400)](e[m(1872)](n,e[m(1882)](e[m(1374)](127,s[l]),14)),0);continue;case"1":n=e[m(478)](e[m(795)](127,s[l]),0);continue;case"2":if(s[l++]<128)return{value:f?n:e[m(1478)](0,n),offset:l};continue;case"3":if(e[m(1125)](s[l++],128))return{value:f?n:e.FWjPO(0,n),offset:l};continue;case"4":return{value:f?n:e[m(1816)](0,n),offset:l};case"5":n=e.jjBLP(e[m(865)](n,e[m(1418)](127&s[l],7)),0);continue;case"6":if(e[m(1363)](s[l++],128))return{value:f?n:e.mQzcF(0,n),offset:l};continue;case"7":if(e[m(1390)](l+=5,s[m(571)]))throw l=s.length,e[m(1671)](_g,l,10,s.length);continue;case"8":n=e.vSNVo(n,e[m(1304)](127,s[l])<<21)>>>0;continue;case"9":n=e[m(1095)](e[m(789)](n,e[m(1802)](15,s[l])<<28),0);continue;case"10":if(s[l++]<128)return{value:f?n:e.FWjPO(0,n),offset:l};continue;case"11":if(e[m(1167)](s[l++],128))return{value:f?n:e.DUiit(0,n),offset:l};continue}break}}}else return _e._ws?_e[a(775)][a(545)+"te"]:_e[a(690)][a(1229)+a(1957)]?_e.CONNECTING:_e[a(1028)]})();let kg=16,Aa=32;function Tg(a){let n=t,s=0,l={};for(let f=0;e[n(885)](f,a.length);f++)e.WqQdu(e[n(1744)],e.XHwHp)?this["_cursorF"+n(499)]=_0x78cbc4:(l[a[f][n(652)+n(955)]]=e[n(1466)](Sl,a[f][n(652)+n(955)]),s+=e[n(1175)](14,l[a[f][n(652)+n(955)]]));return[s,l]}function Cl(a,n,s){let l=t,[f,m]=e.RukHF(Tg,a),v=e.WMXLS(Ag,f),y=0;return a.forEach(p=>{let A=j,L={vKRbg:function(F,q,$){return e[j(1750)](F,q,$)},cIBqA:e[A(1152)]};if(e.kUdOp(e.yVtPK,e[A(622)])){let F=this[A(1463)+A(1917)]?.["getCurre"+A(1001)+"nt"]();this[A(1839)+A(438)+A(1916)](L[A(1051)](_0x86a8da,L[A(524)],{code:_0x57d0b5[A(792)],reason:A(686)+A(1846)+A(1642)+"wn reaso"+A(502)+A(1953)+F})),this[A(1463)+"tManager"]?.[A(941)+"pointConfig"](),this._pingLossCounter?.[A(1109)+A(706)]();return}else{let F=("0|10|9|8|1|7|3|6"+A(493))[A(654)]("|"),q=0;for(;;){switch(F[q++]){case"0":console.log(e[A(1743)],p,p.service);continue;case"1":console.log(e.GBBMv,y);continue;case"2":console[A(1870)](e[A(781)],y);continue;case"3":console.log(e[A(1068)],y);continue;case"4":y=Sg(ue.fromNumber(p.cursor||n),v,y);continue;case"5":console[A(1870)](e[A(1806)],y);continue;case"6":y=e.ixCpF(Eg,p[A(652)+A(955)],v,y);continue;case"7":y=e.mwfqo(Ia,m[p[A(652)+A(955)]],v,y);continue;case"8":y=e[A(1218)](yg,v,y,p[A(1267)]||0);continue;case"9":console.log(e[A(745)],y);continue;case"10":y=e[A(1100)](Ia,0,v,y);continue}break}}}),{frameType:Aa,headers:[{key:l(1278)+l(1272),value:s}],payload:v}}function Cg(a){let n=t,s=0,l=[];for(;s<a[n(412)+"th"];){let{offset:f}=e[n(522)](Sa,a,s);s=f;let m={cursor_name:"",cursor:0,service:0},{value:v,offset:y}=bg(a,s);m[n(1267)]=v,s=y;let{value:p,offset:A}=Sa(a,s);s=A,m.cursor_name=Il(a,s,e[n(717)](s,p)),s+=p;let{value:L,offset:F}=e[n(1692)](vg,a,s);m.cursor=L.toNumber(),s=F,l[n(803)](m)}return l}function Rg(){let a=t;return{frameType:Aa,headers:[{key:e[a(1900)],value:a(535)+a(878)}],payload:void 0}}class Dg{constructor(n,s,l){let f=t;this[f(1545)+f(1665)]=n,this[f(1291)+f(499)]=s,this[f(676)+"Strategy"]=l,this[f(1062)]=e.LlaQk(kl,this[f(1545)+"ameSpace"],e[f(839)])}async[t(1633)](){let n=t;if(e[n(1649)](e[n(1564)],e[n(1564)]))return e[n(465)](_0x1ab135,_0x3e6a34)?_0x38887b.reject(new _0x10ef9d(n(1500)+n(911)+"ltiple t"+n(964)+"process")):(_0x23a5ac=_0x14c858,e[n(633)](_0x305a9c,_0x5ceb7d[n(571)])?_0x49f161[n(826)]():_0x552ff6[_0xa5b508].bind(_0x57c3a5)(_0x3e3943,_0x4e1d2b.bind(null,_0x3ae0b3+1)));await this[n(1062)][n(1633)]()}async getCursors(){let n=t;if(!this._qosDB[n(748)])return;let s=this[n(676)+n(1113)],l=await this._qosDB[n(942)]();switch(console.log(e[n(1877)],l),s){case e.zsgGR:return l&&l[n(571)]?e[n(1419)](Cl,l,0,this._cursorFileName):void 0;case n(539):return;case e[n(1656)]:return l&&l[n(571)]?e[n(611)](Cl,l,0,this["_cursorF"+n(499)]):e.BHfpD(Rg)}}async[t(1892)](n,s,l){let f=t;return console[f(1870)](e[f(985)],n,s,l),this._qosDB[f(1892)]({cursor_name:n,cursor:s,service:l})}async[t(707)+"rs"](n){let s=t,l=e.XACOL(Cg,n);for(let f of l)console[s(1870)](e[s(1526)],l),await this[s(1062)][s(1892)](f)}async[t(1935)](n){let s=t;return(await this[s(1062)][s(1935)](n))?.[s(805)]}async[t(1789)](){let n=t,s={qEwAC:function(l,f){return e[j(465)](l,f)},ScHEj:function(l,f){return l+f}};if(e[n(1659)](e[n(1379)],n(1703)))await this._qosDB.closeDB();else{if(NuIZMJ[n(1544)](_0x1657b4,-_0x12dcbd))return _0xde918d;if(NuIZMJ[n(1420)](_0x5659a8,1)>=_0x28a7c1)return _0x15a594}}[t(1039)+t(1239)+t(1613)](n){let s=t;this[s(1291)+s(499)]=n}get[t(748)](){let n=t;if(n(1317)!=="DrWpz")return this[n(1062)][n(748)];++_0x342188,_0x34eed1+=4}}let Pg=e[t(1332)];async function Rl(a){let n=t,s={sdMNo:n(1790)};if(!this[n(690)].enableQoS)return null;let{aID:l,fpID:f,messageStrategy:m}=this._options,v=a||Pg;try{if(this[n(1668)+n(1057)])if(e[n(1247)](e.uisRp,n(564)))a&&this[n(1668)+n(1057)][n(1039)+"rsorFile"+n(1613)](a);else return _0x40dd8c||(_0x1059bd=_0x4ed6ab[n(826)]().then(_0x1562b0[n(1263)](_0x416763,cjWRlf[n(880)]))),_0x4fd583;else this[n(1668)+n(1057)]=new Dg(f+"_"+l+"_"+v,v,m);return this[n(1668)+"anager"].isReady||await this["_cursorM"+n(1057)][n(1633)](),this[n(1668)+n(1057)]}catch{return null}}async function Og(a,n){let s=t,l=an(a[s(1660)][s(1739)],e.ZhOiS,"-1"),f=e[s(1341)](an,a.message[s(1739)],e[s(1923)],"1"),m=e[s(630)](ar,a[s(1660)].headers,e[s(716)]),v=e[s(581)](Number,e.OqCkt(ar,a[s(1660)][s(1739)],e[s(1362)]))||0,y=va.call(this,a),p=an(a[s(1660)][s(1739)],e[s(975)],"2"),A=e.AlsQu(ar,a[s(1660)][s(1739)],e[s(889)]),L=e[s(1755)](Number,e[s(440)](ar,a.message[s(1739)],e.eQDpB));if(y[s(944)])return n();let F=y[s(550)+"sage"]?await Tl[s(1615)](this):null;if(e[s(498)](a.message[s(1267)],0)&&f&&!l||e.CojKy(a[s(1660)][s(1267)],0)){if(m&&y.isQoSMessage&&F)return e.HBTMG(e[s(1096)],s(1171))?(!!!await F.get(m)&&(this["_dispatc"+s(970)+"Event"](a),await F.set(m,e.wcvYp(Date.now(),v))),e[s(1943)](n)):(_0x2d9064[s(1489)+"t8"]?_0x1c3af8.writeUint8(_0x1e09e5,_0x73dd5d):_0x5bbbab[_0x450955]=e.kXgiR(255,_0x1858ea),_0x1cebd3+1);if(p){let q=await Rl.call(this);if(!q)return this["_dispatc"+s(970)+s(1898)](a),e[s(431)](n);let $=await q[s(1935)](A)??-1;if(e[s(1080)]($,L))this[s(1839)+"hMessageEvent"](a),q[s(1892)](A,L,a.message[s(1267)]);else throw new Error("recevied"+s(544)+s(1271)+L+(s(836)+s(1579)+s(770)+"r ")+$);return e.JAIeB(n)}return this[s(1839)+s(970)+"Event"](a),n()}}async function Lg(a,n){let s=t,l=va[s(1615)](this,a);if(!l[s(550)+s(1562)])return e[s(509)](n);let f=await Tl[s(1615)](this);if(l[s(924)+s(1482)+"age"]&&l.ackMsgIds[s(571)])for(let m of l[s(659)+"s"])await f[s(725)](m);e[s(1160)](n)}async function Ng(a,n){let s=t;if(e[s(857)](s(1465),s(1295)))return s(1546)+"_"+this[s(1639)];{let l=e.ttwie(a[s(1660)][s(1904)+"e"],kg),f=e[s(481)](a[s(1660)][s(1904)+"e"],Aa);if(e.XIqXx(!l,!f))return e[s(1943)](n);let m=e[s(1007)](ar,a[s(1660)][s(1739)],e.DrfWm);if(!m)return e[s(1244)](n);let v=await Rl[s(1615)](this,m);if(!v)return e[s(1943)](n);if(l){let y=await v.getCursors(),p={frameType:y?.["frameType"],SeqID:ue[s(1682)+"er"](this[s(1061)]++),LogID:ue[s(1682)+"er"](this._options["logIDGen"+s(1366)]()),service:9e3,method:5,headers:y?.[s(1739)],payload:y?.[s(603)]},A=S(p);this._ws&&this._ws.readyState&&this[s(775)][s(842)](A)}if(f){let y=a[s(1660)][s(603)];y&&v.setCursors(y)}}}let Mg=async function(a,n){let s=t;this[s(1457)]=!1,clearTimeout(this["_connect"+s(804)+s(455)]),e.pCpZE(n)},Bg=async function(a,n){let s=t;if(!this._ws||e[s(1710)](this[s(775)][s(545)+"te"],this[s(1819)]))return n();let{pingInterval:l}=this[s(690)];this["_endpoin"+s(1917)]?.[s(941)+s(1248)+s(532)]();for(let m=0;e[s(1684)](m,this[s(676)+s(1138)][s(571)]);m++){let v=this[s(676)+s(1138)][m];if(e[s(633)](this[s(775)][s(545)+"te"],this[s(1819)])&&v!==null)this[s(775)]&&this[s(775)].send(v),this[s(676)+"Queue"][m]=null;else break}this["_message"+s(1138)]=this[s(676)+s(1138)][s(1713)](m=>!!m),this[s(480)+s(1648)+"Id"]=setTimeout(()=>this[s(982)](),l),this[s(1839)+s(1322)+"nt"](a),this[s(1610)+"er"]&&this[s(775)]&&(this[s(775)][s(881)+"pe"]=this._binaryType);let f=this[s(1463)+s(1917)]?.[s(1436)+s(1001)+"nt"]();this._debug(s(1843)+f+s(708)),n()},Fg=async function(a,n){let s=t,l=this._endpointManager?.[s(1436)+s(1001)+"nt"]();this[s(1567)](s(1843)+l),e[s(1943)](n)};class zg extends ya{constructor(n){let s=t,l={MqOJL:function(y,p,A){return e[j(1018)](y,p,A)},rFRKG:function(y,p){return e.dWgnu(y,p)},ppeYx:e[s(867)],aGgiQ:s(998),tTYIP:function(y,p){return e[s(1928)](y,p)},USMmJ:function(y,p){return e[s(1554)](y,p)},eVAGY:e.CQlqk,ZugnF:e[s(1881)],aFsfX:e[s(713)],IxErI:function(y,p,A){return y(p,A)},QggKt:function(y,p){return e[s(479)](y,p)},pomRU:function(y,p){return e[s(828)](y,p)},YAtkC:e[s(569)],xvgGD:function(y,p,A,L){return y(p,A,L)},Ebpvb:e[s(1540)],Tnglg:e.sKTFp,jAFkN:e[s(1209)],KAkHx:function(y,p,A){return e[s(1692)](y,p,A)},NMPzo:"bye",ucawR:function(y,p){return e[s(940)](y,p)},ZjDKM:function(y,p,A){return e[s(883)](y,p,A)},aUSYi:e[s(566)],zicLS:function(y,p){return e[s(549)](y,p)},CvcDx:function(y,p,A){return e[s(1339)](y,p,A)}};super(),this[s(1629)+"igatorOn"+s(1455)]=!0,this._isBrowser=or,this._isNode=tg,this._isMiniTT=On,this[s(1453)+"X"]=ni,this._isWorker=ri,this[s(676)+s(1138)]=[],this["_endpoin"+s(1917)]=null,this["_readyCl"+s(1003)]=!1,this[s(1551)+s(1408)]=e[s(1518)],this[s(1728)+"Lock"]=!1,this[s(1728)+s(804)+s(455)]=null,this[s(769)+s(505)+s(1509)]=null,this[s(480)+s(1648)+"Id"]=null,this[s(1061)]=0,this[s(1457)]=!1,this[s(681)]="",this[s(1939)+s(1697)]=null,this[s(1668)+"anager"]=null,this[s(1328)+s(776)]=null,this[s(1940)+"ls"]=e[s(756)],this[s(1028)]=3,this[s(1069)+"NG"]=0,this[s(1819)]=1,this[s(1566)]=2,this[s(1534)]=y=>{let p=s;try{vl(this,y,[Mg,Bg,Fg])}catch(A){let L=e[p(1501)](dt,"error",{message:A.message,code:on.OPEN_ERROR,error:A});this._dispatchErrorEvent(L)}},this._onMessage=async y=>{let p=s,A={iEYGs:function(L,F,q){return l[j(1715)](L,F,q)}};if(l[p(1178)](l[p(916)],l[p(1204)])){let{pingInterval:L,pingFrequency:F}=this[p(690)];if((l[p(1749)]("hi",y[p(979)])&&l[p(1749)]("always",F)||l.USMmJ(l[p(957)],F))&&(this[p(518)+p(548)](),this.emit(l[p(1809)],l.aFsfX),this[p(480)+"gTimeoutId"]=l.IxErI(setTimeout,this._ping[p(1263)](this),L)),l[p(798)]("hi",y[p(979)]))return;try{if(l[p(1886)](p(1128),l[p(1836)]))return _0x3817eb?this[p(1644)+"E"]():this.toBytesBE();l[p(968)](vl,this,y,[gg,xg,Lg,Ng,Og,pg])}catch(q){if(l[p(595)](l[p(1077)],p(1002)))_0x981917&&this[p(1668)+p(1057)][p(1039)+p(1239)+p(1613)](_0x83874c);else{let $=dt(p(935),{message:q[p(1660)],code:on[p(1133)+p(1029)],error:q});this[p(1839)+p(489)+p(1916)]($)}}}else swwTfX.iEYGs(_0x2d3006,_0x42bffe,16),swwTfX[p(586)](_0x244b28,_0x2683dd,_0x2a7ae6)},this._onError=y=>{let p=s,A=this["_endpoin"+p(1917)]?.[p(1074)+"chMaxTries"](),L=this[p(1463)+p(1917)]?.[p(1436)+p(1001)+"nt"]();if(A&&!y[p(1660)]){let F="connect "+L+(p(903)+"ax retri"+p(929)+"ed");this[p(1839)+p(489)+p(1916)](dt(p(935),{message:F,code:on[p(1468)+p(1402)+"R"],error:y}));return}this._ws&&e[p(658)](this[p(775)][p(545)+"te"],this[p(1819)])&&this[p(855)+p(1093)](),this[p(1839)+p(489)+"ent"](dt(e[p(566)],{message:y[p(1660)],code:on[p(747)+p(1612)],error:y}))},this[s(1867)]=async y=>{let p=s;this[p(987)+p(1520)](),this[p(518)+p(548)](),this[p(1480)+"sListeners"](),this[p(775)]=null,this[p(1728)+"Lock"]=!1;let A=this[p(1463)+p(1917)]?.[p(1074)+p(1467)+"es"]();if(!A&&this[p(1735)+"orOnline"]()&&!this[p(553)+p(1003)]){let L=this["_endpoin"+p(1917)]?.[p(1436)+p(1001)+"nt"](),F=this[p(690)][p(709)+p(1070)+"ptor"](y[p(792)],y[p(1766)]);this[p(1839)+"hCloseEv"+p(1916)](l[p(1715)](gt,l[p(1933)],{code:1006,reason:y.reason||p(686)+"ng faile"+p(1642)+"wn reaso"+p(502)+p(1953)+L,willReconnect:F})),F&&this[p(1728)]();return}if(l[p(1886)](1e3,y.code)&&this[p(553)+p(1003)])if(l[p(1516)]!==p(423))this["currentE"+p(675)+p(1044)+"t"]=0;else{this[p(1839)+p(438)+p(1916)](l[p(785)](gt,l[p(1933)],{code:1e3,reason:l[p(1810)]})),this[p(1463)+p(1917)]?.[p(941)+p(1248)+p(532)](),this[p(1328)+p(776)]?.[p(1109)+p(706)]();return}if(l.pomRU(1e3,y[p(792)])&&A){let L=this._endpointManager?.[p(1436)+"ntEndpoint"](),F=y[p(1766)];F||(F=await l.ucawR(cg,this._url)),F=p(686)+p(1846)+"d, "+F+(p(972)+p(1243))+L+(p(1550)+p(411)+"ached"),this[p(1839)+p(438)+"ent"](l[p(1715)](gt,p(737),{code:y[p(792)],reason:F}));let q=p(495)+L+(p(903)+p(1314)+p(929)+"ed");this[p(1839)+p(489)+p(1916)](l[p(624)](dt,l[p(1711)],{message:q,code:on[p(1468)+p(1402)+"R"]})),this._endpointManager?.[p(941)+p(1248)+"fig"](),this[p(1328)+p(776)]?.[p(1109)+p(706)]();return}if(l[p(886)](1e3,y.code)&&!y[p(1766)]){let L=this._endpointManager?.[p(1436)+"ntEndpoint"]();this[p(1839)+p(438)+p(1916)](l[p(1792)](gt,p(737),{code:y[p(792)],reason:p(686)+p(1846)+"d, unkno"+p(1352)+p(502)+"ame: "+L})),this[p(1463)+p(1917)]?.[p(941)+p(1248)+p(532)](),this["_pingLos"+p(776)]?.[p(1109)+p(706)]();return}this[p(1839)+p(438)+p(1916)](y),this[p(1463)+p(1917)]?.["resetEndpointCon"+p(532)](),this[p(1328)+p(776)]?.[p(1109)+"nter"]()},this[s(1258)]=null,this[s(1801)]=null,this[s(906)+"e"]=null,this[s(1855)]=null,this["onStartR"+s(1651)]=null,this[s(1078)+s(1776)]=null,this[s(1108)+s(861)+s(1115)+"ct"]=null,this[s(1438)+s(1469)]=this[s(1438)+s(1469)][s(1263)](this),this[s(1438)+"ffLine"]=this[s(1438)+s(1309)][s(1263)](this),this._handlePageHide=this[s(1206)+s(1581)][s(1263)](this),this[s(1206)+"ageShow"]=this[s(1206)+s(1424)][s(1263)](this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1734)](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(1575)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1656)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:m}=n,v=Array[s(462)](f)?f:e.RFVKy("string",typeof f)?[f]:[];if(!v||e.zkkWa(0,v.length))throw new Error(e[s(1277)]);if(!ig(m))throw new Error(e[s(442)]);Object[s(1595)](this[s(690)],n),this[s(1463)+s(1917)]=new El(v,this._options[s(1193)+"es"]),this["_pingLos"+s(776)]=new ag(this[s(690)][s(797)+s(536)]),this[s(690)][s(1229)+s(1957)]&&(this[s(1457)]=!0,this._connect()),this._options[s(814)+s(1496)+"nged"]&&(this._isMiniTT||this[s(1453)+"X"]?this[s(1737)+s(402)+"ange"]():this[s(1610)+"er"]&&this[s(984)+s(531)+s(958)]())}["_handleO"+t(1469)](){let n=t;this[n(690)]["disableA"+n(800)+n(1597)]||this._readyClosed||this["_handleR"+n(1651)]()}[t(1438)+"ffLine"](){let n=t;this["_destroy"+n(824)+"t"]();let s=e[n(1688)](_a,e[n(1515)],{message:e.JqqWe});this["onStopIm"+n(861)+n(1115)+"ct"]&&this[n(1108)+n(861)+n(1115)+"ct"](s)}["_initGlo"+t(531)+t(958)](){let n=t;this[n(1610)+"er"]&&window[n(1821)+n(958)](e.xHIyi,this[n(1438)+n(1469)]),this[n(1610)+"er"]&&window[n(1821)+n(958)](e.hoURK,this[n(1438)+"ffLine"]),this._isBrowser&&window[n(1821)+"Listener"](n(1555),this[n(1206)+n(1581)]),this[n(1610)+"er"]&&window[n(1821)+"Listener"](e.lGucI,this[n(1206)+n(1424)])}[t(759)+t(531)+"Listener"](){let n=t;this._isBrowser&&window["removeEventListe"+n(1486)](n(738),this[n(1438)+"nLine"]),this[n(1610)+"er"]&&window["removeEv"+n(921)+n(1486)]("offline",this[n(1438)+"ffLine"]),this[n(1610)+"er"]&&window["removeEv"+n(921)+"ner"](n(1555),this[n(1206)+n(1581)]),this[n(1610)+"er"]&&window[n(767)+n(921)+n(1486)](e[n(1238)],this["_handleP"+n(1424)])}["_handleP"+t(1581)](n){let s=t;!n.persisted&&(this[s(1610)+"er"]&&window[s(767)+s(921)+"ner"]("pagehide",this["_handleP"+s(1581)]),this[s(1610)+"er"]&&window[s(767)+s(921)+s(1486)](e.lGucI,this[s(1206)+s(1424)]),this[s(737)]()),this._isBrowser&&window["removeEventListe"+s(1486)](e[s(615)],this[s(1438)+"nLine"]),this[s(1610)+"er"]&&window[s(767)+"entListe"+s(1486)](e[s(468)],this[s(1438)+"ffLine"])}[t(1206)+t(1424)](n){let s=t;n[s(1664)+"d"]&&(this[s(1735)+"orOnline"]()&&(!this[s(775)]||this[s(775)][s(545)+"te"]!==this[s(1819)]||e[s(1689)](this[s(775)].readyState,this.CONNECTING))&&this["_handleO"+s(1469)](),this[s(1610)+"er"]&&window[s(1821)+s(958)](e[s(615)],this[s(1438)+s(1469)]),this[s(1610)+"er"]&&window[s(1821)+s(958)](s(1491),this["_handleO"+s(1309)]))}async[t(679)+t(1641)](n){let s=t,{fpID:l,deviceID:f,bddID:m,ttwID:v,accessKey:y,aID:p,customParams:A={},enableAutoAck:L,enableQoS:F,QoSLevel:q,env:$}=this._options,ge,We,It;this._isBrowser||this[s(1453)+"X"]||this._isMiniTT?e[s(1118)]!==e[s(1331)]?(ge=location&&e[s(639)](e[s(1210)],location[s(860)])?e.DDRSO:e[s(1380)],We=n.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),It=/^wss(.*:\/\/)/.test(n)?n:""+ge+We):(this["_message"+s(1138)].shift(),this[s(676)+s(1138)][s(803)](_0x3c2dd8)):(ge=e[s(1130)],We=n[s(1120)](/(^http)((?:[s]*:\/\/))/,""),It=/(^ws)((?:[s]*:\/\/))/.test(We)?We:""+ge+We);let Ht=m?s(1377):v?e[s(471)]:e[s(1704)],Dl=m||v||f;if(e[s(999)](!Dl,!Ht))throw new Error(e[s(1505)]);let Ug=e[s(639)](e.HeAUq,typeof A)?await e[s(1769)](A):A,qg=$?og($[s(1416)],$.xTTEnv):{},ka=Object[s(1595)]({device_platform:e[s(896)],version_code:e.LOYHq,access_key:y,fpid:l,aid:p,[Ht]:Dl,xsack:L?1:0,xaack:L?1:0,xsqos:F?1:0,qos_level:F?q:void 0,qos_sdk_version:2,...qg},Ug),Hg=Object[s(1565)](ka)[s(643)]((Ta,Ca)=>ka[Ca]!==void 0?""+Ta+(Ta?"&":"?")+Ca+"="+ka[Ca]:Ta,"");return It+s(859)+Hg}async[t(1728)](){let n=t;if(!(this[n(1728)+n(969)]||this[n(553)+n(1003)])){this[n(1728)+n(969)]=!0;try{let s=this[n(1463)+n(1917)]?.[n(596)+n(1023)+n(1246)+n(1714)+n(1199)](),{timeoutInterval:l}=this[n(690)];if(s){let m=this["_endpoin"+n(1917)]?.[n(1436)+n(1001)+"nt"](),v=this[n(1463)+n(1917)]?.[n(1122)+"ackupEnd"+n(920)+n(1296)+"unt"](),y=this[n(1463)+"tManager"]?.["getCurre"+n(1001)+n(719)+"ount"]();if(v){let p=n(495)+m+(n(1024)+n(1550)+"tries re"+n(977)+"ill use "+n(1405)+n(491))+v+(n(1852)+"y"),A=e.QXpFu(dt,e[n(566)],{message:p,code:on[n(1468)+n(1402)+"R"]});this._debug(p),this[n(1839)+n(489)+n(1916)](A),this[n(681)]=await this["_generat"+n(1641)](v),this[n(1567)]("connect "+v+" "+y+" times"),this._removeWsListeners()}else{let p="connect "+m+(n(1024)+", max re"+n(411)+n(1049));this._debug(p),this["_dispatc"+n(489)+n(1916)](dt(e[n(566)],{message:p,code:on[n(1468)+"IES_ERROR"]}));return}}else{let m=this[n(1463)+n(1917)]?.[n(1436)+n(1001)+n(831)+n(1906)](),v=this[n(1463)+n(1917)]?.["getCurre"+n(1001)+n(719)+n(1163)]();this._url=await this[n(679)+n(1641)](m||""),this[n(1567)](n(495)+m+" "+v+" times"),this[n(1480)+"sListeners"]()}if(this[n(1457)])this._isInit=!1;else{let m=_a(e[n(1515)],{message:e.BGvuo});this.onStartReconnect&&this[n(1433)+n(1651)](m)}let f=this[n(1463)+n(1917)]?.[n(1436)+n(1001)+n(719)+n(1163)]()||0;e[n(1336)](f,1)&&await this[n(1626)](f-1),this[n(1567)](n(686)+n(986)+this[n(681)]+(n(1321)+n(606))+this[n(1940)+"ls"]),this[n(775)]=rg({url:this[n(681)],protocols:[this._protocols],headers:this[n(690)][n(1582)+n(1043)+"s"][n(1503)+n(483)]},this._options.ws),(this[n(1610)+"er"]||this[n(1262)+"r"])&&this[n(775)]&&(this[n(775)][n(881)+"pe"]=this[n(1551)+n(1408)]),this["_addWsLi"+n(1189)](),this[n(1728)+"ionTimeoutId"]=e[n(473)](setTimeout,this[n(1676)+"ut"][n(1263)](this),l)}catch(s){throw this[n(1728)+n(969)]=!1,s}}}["_clearTi"+t(1520)](){let n=t;e[n(1173)](clearTimeout,this[n(1728)+n(804)+n(455)]),this[n(1728)+n(804)+n(455)]=null}_clearPingTimer(){let n=t;if(e[n(1803)]!==e[n(1748)])clearTimeout(this["_pingPon"+n(1648)+"Id"]),e.vBWUS(clearTimeout,this[n(769)+n(505)+"tId"]),this[n(480)+"gTimeoutId"]=null,this["_reconne"+n(505)+n(1509)]=null;else return _0x534cb6?_0x123575["fromByte"+n(1632)](_0x4e0921,_0x54a2fa):_0x27df64[n(1861)+n(762)](_0x27ffe1,_0x4310bf)}[t(1567)](...n){let s=t;this[s(690)].debug&&console[s(1870)].apply(console,[e[s(907)],...n])}[t(1409)+"rvalValue"](n){let s=t;if(e[s(981)](s(858),e.LOkjv)){let{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:m}=this[s(690)],v=e[s(1111)](l,Math[s(1165)](m,e[s(954)](n,1)));return e.wrqwL(v,f)?f:v}else{let l=e[s(1951)](_0x323cc3,s(709)+"t",{message:e[s(1275)]});this[s(1433)+s(1651)]&&this[s(1433)+s(1651)](l)}}[t(982)](){let n=t;if(this._ws&&e[n(1232)](this[n(775)].readyState,this[n(1069)+"NG"]))if(e[n(1395)](e[n(1479)],n(1376)))this[n(518)+n(548)](),this[n(449)](e.woEHx,"success"),this[n(480)+n(1648)+"Id"]=_0x1c3a5c(this[n(982)][n(1263)](this),_0x147772);else{this[n(518)+n(548)](),this["_pingPon"+n(1648)+"Id"]=e[n(1310)](setTimeout,this[n(982)][n(1263)](this),this[n(690)][n(840)+"rval"]);return}if(!this._ws||e[n(1032)](this[n(775)][n(545)+"te"],this[n(1819)]))return void this[n(806)+n(1651)]();this[n(775)]&&this[n(775)][n(842)]("hi"),this[n(769)+n(505)+n(1509)]=e[n(843)](setTimeout,this["_handleReconnect"+n(1059)][n(1263)](this),this[n(690)][n(1312)+n(1847)+"val"])}[t(806)+t(1651)+t(1059)](){let n=t;this._pingLossCounter?.[n(1338)](),this[n(449)](e[n(1922)],e[n(1300)]),this["_pingLos"+n(776)]?.[n(1074)+n(1353)+"nt"]()?this._handleReconnect():this[n(982)]()}[t(1735)+t(1696)](){let n=t;return this[n(983)+"T"]||this._isMiniWX?this[n(1629)+"igatorOn"+n(1455)]:(this[n(1610)+"er"]||this[n(1262)+"r"])&&this[n(690)][n(814)+n(1496)+n(1308)]?navigator[n(1104)]:!0}["_handleR"+t(1651)](){let n=t;!this[n(1735)+n(1696)]()||this["_readyCl"+n(1003)]||(this[n(1463)+n(1917)]?.["resetEnd"+n(1248)+n(532)](),this[n(1328)+n(776)]?.[n(1109)+n(706)](),this[n(775)]?this["_disconn"+n(1093)](1001,n(1451)+n(1333)+n(709)+n(888)+n(802),!0):this._connect())}[t(1737)+t(402)+"ange"](){let n=t,s={XAgiY:e[n(1089)],kaxcs:e[n(1497)],vTgac:function(l,f){return e[n(642)](l,f)},QGSoo:e.XcucA,xMqTh:e.ELdme};this._isMiniTT?tt[n(1938)+n(1732)+n(1086)](({isConnected:l})=>{let f=n;if(s[f(454)]!==s[f(1709)])this[f(1629)+f(458)+f(1455)]=l,l?this[f(1438)+"nLine"]():this[f(1438)+f(1309)]();else{let m=this[f(1463)+"tManager"]?.[f(1436)+"ntEndpoint"]();this[f(1567)]("open "+m),_0x17421c()}}):this[n(1453)+"X"]&&wx[n(1938)+n(1732)+n(1086)](({isConnected:l})=>{let f=n;s.vTgac(s[f(1394)],s[f(604)])?_0xb77b05[f(1147)]=_0x18431c[f(826)]()[f(818)](()=>(_0xd50966(),_0x4d2061))[f(818)](function(m){return m}):(this[f(1629)+f(458)+f(1455)]=l,l?this[f(1438)+"nLine"]():this[f(1438)+f(1309)]())})}_wait(n){let s=t,l={xeMul:function(f,m){return e[j(951)](f,m)},uykNw:function(f,m){return e[j(1827)](f,m)},aGIrj:function(f,m){return e[j(1624)](f,m)},jSeKt:function(f,m){return e[j(772)](f,m)},MSYks:function(f,m){return e.obueX(f,m)},dgirZ:s(1663),yYUEX:function(f,m,v){return f(m,v)}};return new Promise(f=>{let m=s,v={PrawR:function(y,p){return l[j(529)](y,p)},tqRJU:function(y,p){return l.uykNw(y,p)},GBzPD:function(y,p){return l[j(1385)](y,p)},IuZVM:function(y,p){return l[j(529)](y,p)},yliMC:function(y,p){return l[j(529)](y,p)},dEyAF:function(y,p){return l[j(674)](y,p)},UtXCK:function(y,p){return l.jSeKt(y,p)}};l[m(1329)](m(1681),l[m(472)])?l[m(1038)](setTimeout,f,this["_getInte"+m(1812)+"e"](n)):(_0x4f6852=iMmmtb.PrawR(_0x2fdbae,_0x4e1319),_0x1fbd10|=iMmmtb[m(1448)](127&_0x4e2c36,14),iMmmtb[m(1736)](128,_0x13fe32)&&(_0xa322=_0x796e48(_0x15b69e),_0x21ff6a|=iMmmtb[m(1736)](127,_0x49311a)<<21,iMmmtb[m(1736)](128,_0xb0c6b3)&&(_0x435207=iMmmtb.IuZVM(_0x43621c,_0x16dc73),_0x19e21c=127&_0x2be270,128&_0x4f3e36&&(_0x6b8677=iMmmtb[m(1759)](_0x4d247c,_0x1d85d8),_0x37ce8e|=iMmmtb[m(973)](iMmmtb[m(409)](127,_0x34cff4),7)))))})}[t(855)+t(1093)](n=1e3,s="",l=!1){let f=t;this[f(775)]&&this[f(1249)+f(824)+"t"](n,s,l)}[t(1676)+"ut"](){let n=t,s=this["_endpoin"+n(1917)]?.[n(1436)+"ntEndpoint"]();this[n(1567)](n(495)+s+n(1024)),this._disconnect(1001,e[n(844)],!0)}[t(1547)](n){let s=t,l=e[s(1071)](qt,n);this[s(775)]&&e[s(642)](this[s(775)][s(545)+"te"],this[s(1819)])&&(this[s(775)]&&this[s(775)][s(842)](l),this[s(1567)](e[s(406)],n))}[t(1480)+t(1284)+"rs"](){let n=t,s="2|3|4|1|0"[n(654)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(775)][n(767)+n(921)+n(1486)](e.HvfPA,this[n(657)]);continue;case"1":this[n(775)][n(767)+n(921)+n(1486)](e[n(728)],this[n(890)+"ge"]);continue;case"2":if(!this._ws)return;continue;case"3":this[n(775)][n(767)+n(921)+n(1486)](n(1513),this._onOpen);continue;case"4":this[n(775)][n(767)+n(921)+n(1486)]("close",this._onClose);continue}break}}[t(1281)+t(1189)](){let n=t,s=e[n(1707)][n(654)]("|"),l=0;for(;;){switch(s[l++]){case"0":this._ws["addEvent"+n(958)](e[n(1152)],this[n(1867)]);continue;case"1":this._ws["addEvent"+n(958)](e[n(566)],this._onError);continue;case"2":this[n(775)][n(1821)+n(958)](e[n(830)],this[n(1534)]);continue;case"3":this._ws[n(1821)+"Listener"](e[n(728)],this[n(890)+"ge"]);continue;case"4":if(!this[n(775)])return;continue}break}}[t(1253)+t(486)](n=1e3,s=""){let l=t;try{this[l(775)]&&this[l(775)].close(n,s)}catch{}}[t(1249)+t(824)+"t"](n=1e3,s="",l=!1){let f=t,m={pVaux:e.zXHTO,GGgLO:function(v,y){return e.woXeT(v,y)},opxze:function(v){return e[j(1244)](v)},Xpzzl:f(934),lADMX:e[f(845)],iRovt:e[f(1686)],Ylunk:function(v){return e[f(1102)](v)},UsZfM:e[f(1221)],dRXDL:e[f(1661)],iVTrq:e[f(1606)],QFqwZ:function(v,y,p){return e[f(915)](v,y,p)},gcPuE:f(935),fDnJq:function(v,y,p){return v(y,p)},JtDnp:f(737)};if(this[f(518)+f(548)](),this[f(987)+f(1520)](),this._removeWsListeners(),this[f(1253)+f(486)](1e3,s),this[f(1728)+f(969)]=!1,l&&this[f(1735)+f(1696)]()&&!this[f(553)+f(1003)])if(e[f(559)]===e[f(559)]){if(this[f(1463)+"tManager"]?.[f(1074)+"chMaxTries"]())if(e[f(753)](e.bPgqL,e[f(1536)])){let y=m[f(1760)].split("|"),p=0;for(;;){switch(y[p++]){case"0":qmAMVr[f(1831)](_0x478042,A=>({...A,get:(L,F,q)=>_0x21e724(L,F)||A.get(L,F,q),has:(L,F)=>!!_0x2b8c62(L,F)||A[f(1488)](L,F)}));continue;case"1":qmAMVr[f(1140)](_0x2803d9);continue;case"2":_0x4cf588=["put",qmAMVr[f(464)],qmAMVr[f(1293)],qmAMVr[f(599)]];continue;case"3":qmAMVr[f(1387)](_0x1deb77);continue;case"4":_0x614d3e=new _0x237ba3;continue;case"5":_0x405ba1=[qmAMVr[f(1161)],f(1037),qmAMVr.dRXDL,qmAMVr[f(1781)],f(1404)];continue}break}}else{let y=this[f(1463)+f(1917)]?.[f(1436)+f(1001)+"nt"]();this[f(1839)+f(438)+"ent"](gt(e[f(1152)],{code:1006,reason:f(495)+y+(f(1024)+f(1550)+f(411)+f(1049)),wasClean:!0}))}else if(e[f(1228)](f(1194),"LzglL")){let y=this[f(690)][f(709)+"tInterce"+f(1841)](n,s);this._dispatchCloseEvent(gt(e[f(1152)],{code:n,reason:s,wasClean:!0,willReconnect:y})),y&&this[f(1728)]()}else{let y={nXpFa:function(p,A){return p(A)},OItvl:function(p,A){let L=f;return qmAMVr[L(1831)](p,A)}};return function(...p){let A=f;return _0x7b7fdb[A(1850)](y.nXpFa(_0x2de6eb,this),p),y[A(829)](_0x3365d0,_0x583c8d[A(1935)](this))}}return}else _0x13bb9f[f(826)]()[f(818)](()=>{let v=f,y=qmAMVr[v(665)](_0x2845f1,qmAMVr[v(560)],{message:this[v(1778)+v(1741)+v(1899)](_0x2362b9)});this[v(449)](qmAMVr.gcPuE,y);let p=qmAMVr[v(1185)](_0x3a9e89,qmAMVr[v(749)],{reason:this[v(1778)+v(1741)+v(1899)](_0x4db267)});this[v(449)](qmAMVr.JtDnp,p)});this[f(1735)+f(1696)]()||this[f(553)+f(1003)]?this[f(1839)+"hCloseEv"+f(1916)](e.guipx(gt,e[f(1152)],{code:n,reason:e[f(1410)]})):this["_dispatc"+f(438)+"ent"](gt(f(737),{code:1006,reason:f(1451)+f(1859)+f(1896)+"ine"})),this[f(775)]=null,this[f(1463)+f(1917)]?.["resetEnd"+f(1248)+f(532)](),this[f(1328)+"sCounter"]?.[f(1109)+"nter"]()}[t(1839)+"hOpenEvent"](n){let s=t;if(s(515)===s(515))this[s(449)](e[s(830)],n),this.onopen&&this[s(1855)](n);else{let l=e[s(954)](e[s(1098)](e[s(1786)](e[s(415)](e[s(1727)](7,_0x1a9dce)<<18,e[s(1434)](63&_0x36a177[_0x3ed12e++],12)),e[s(952)](e[s(1919)](63,_0x24aa76[_0x448db6++]),6)),e.jUBtE(63,_0x1fe932[_0x4daab3++])),65536);_0x3c23dd+=_0x3afd4e["fromChar"+s(1094)](e.EhLcT(55296,e[s(1324)](l,10))),_0x3aa540+=_0x4e3533[s(1773)+s(1094)](56320+e.jMcIw(1023,l))}}[t(1839)+t(970)+t(1898)](n){let s=t;this[s(449)](s(1660),n),this[s(906)+"e"]&&this[s(906)+"e"](n)}[t(1839)+t(475)+t(1462)](n){let s=t;e.ToRAE(e.zFGey,e[s(589)])?(this[s(449)](s(1458),n),this[s(1078)+"eAck"]&&this[s(1078)+"eAck"](n)):(this._ws&&this[s(775)].send(_0x511c74),this[s(1567)](s(870),_0xb2197e))}[t(1839)+t(489)+"ent"](n){let s=t;this[s(449)](e[s(566)],n),this[s(1801)]&&this.onerror(n)}[t(1839)+t(438)+t(1916)](n){let s=t;this.emit(e[s(1152)],n),this[s(1258)]&&this[s(1258)](n)}get binaryType(){let n=t;return this[n(775)]?this._ws[n(881)+"pe"]:this._binaryType}set binaryType(n){let s=t,l={XHrfh:function(f){return e[j(1521)](f)}};e[s(419)](s(1219),e.fqFKA)?(this._binaryType=n,this[s(775)]&&(this._ws[s(881)+"pe"]=n)):(RHVwDq[s(847)](_0x4314ae),_0x14e956())}get[t(1429)+"nt"](){let n=t;return this[n(1463)+n(1917)]?.["getCurre"+n(1001)+n(719)+n(1163)]()||0}get["buffered"+t(1371)](){let n=t,s=this["_message"+n(1138)].reduce((l,f)=>(l+=f&&f[n(412)+"th"]||0,l),0);return e[n(852)](s,this[n(775)]?this[n(775)][n(568)+n(1371)]:0)}get[t(476)+"ns"](){let n=t;return this[n(775)]?this[n(775)][n(476)+"ns"]:""}get[t(860)](){let n=t,s={iUaIe:function(l,f){return l===f},JnREV:e[n(406)]};if(e[n(1232)](e[n(612)],e[n(1561)])){let l=_0x33e148(_0xaea0a2);this[n(775)]&&WmLfpj[n(1598)](this[n(775)][n(545)+"te"],this.OPEN)&&(this[n(775)]&&this[n(775)][n(842)](l),this[n(1567)](WmLfpj[n(786)],_0x3c4c94))}else return this._ws?this[n(775)][n(860)]:""}get readyState(){let n=t;if(e[n(1327)](e.SpAHa,e[n(623)])){let s=_0x271169.bytes,l=_0xa97026[n(893)];return e[n(506)](s.length,l)?s:s[n(1273)](0,l)}else return this[n(775)]?this[n(775)].readyState:this._options[n(1229)+n(1957)]?this.CONNECTING:this[n(1028)]}get[t(1155)](){let n=t;return this[n(775)]?this[n(775)][n(1155)]:this[n(681)]}[t(737)](n=1e3,s){let l=t,f={fzdOW:e.pOIrn};if(e[l(1706)](e[l(441)],e.lhher))return _0x5cc7db[l(1870)](NWuCWy[l(693)],_0x2c7f89,_0x47eeff,_0x54ef8a),this[l(1062)][l(1892)]({cursor_name:_0x458183,cursor:_0x3253bd,service:_0x3339ea});if(this["_readyCl"+l(1003)]=!0,this["_clearTi"+l(1520)](),this._clearPingTimer(),this[l(759)+l(531)+l(958)](),this[l(1939)+l(1697)]?.[l(1789)](),!this._ws)return void this._debug(l(492)+l(1464)+l(1378)+l(1311)+"ed");if(this[l(775)].readyState===this[l(1028)]||e.bLQGt(this[l(775)][l(545)+"te"],this[l(1566)]))return void this[l(1567)](e.YIKxg);this["_destroy"+l(824)+"t"](n,s)}async[t(842)](n,s){let l=t;if(e.OkPps(null,n))throw new Error(e[l(1216)]);e[l(1302)](e.qZdXM,typeof n)&&(n=JSON.stringify(n)),e[l(1065)]!=typeof n&&!e[l(1447)](n,ArrayBuffer)&&!(n[l(1412)]&&e[l(1447)](n[l(1412)],ArrayBuffer))&&(n=JSON[l(1878)+"y"](n));let f=await e[l(1763)](Al,n),m=e[l(951)](sg,n),{method:v=0,service:y=this._options[l(1267)],logID:p=this[l(690)].logIDGenerator(),headers:A=this._options[l(1739)],payloadEncoding:L=this._options[l(1146)+"ncoding"],payloadType:F=this[l(690)][l(703)+l(1408)],logIDNew:q=this[l(690)][l(961)+l(1370)][l(1060)+l(1373)+l(1777)+"ew"]?i(this._options[l(961)+l(1370)][l(1798)]):""}=s||{};if(!y)throw new Error(e[l(540)]);let $={SeqID:ue.fromNumber(this[l(1061)]++),LogID:ue.fromNumber(p),service:y,method:v,headers:A,payloadEncoding:e.GMkKR(L,Object)?L[l(503)]?L[l(503)]:"":L,payloadType:e[l(727)](F,Object)?F[l(1088)]?F.type:m:F||m,payload:f,LogIDNew:q},ge=e[l(1729)](qt,$);return this._ws&&e[l(731)](this[l(775)][l(545)+"te"],this[l(1819)])?(this[l(775)]&&this._ws[l(842)](ge),this[l(1567)](e[l(1608)],$)):e[l(527)](this._messageQueue[l(571)],this[l(690)][l(1494)+l(678)+l(1335)])?(this[l(676)+l(1138)][l(803)](ge),this[l(1567)](e[l(600)],$)):(this[l(676)+"Queue"][l(895)](),this["_message"+l(1138)].push(ge)),{seqID:this[l(1061)],logID:p,logIDNew:q}}async[t(709)+"t"](n){let s=t,{url:l}=n||{},f=Array.isArray(l)?l:e[s(1065)]==typeof l?[l]:[];n&&Object[s(1595)](this[s(690)],n),f&&f[s(571)]?this[s(1463)+s(1917)]=new El(f,this._options[s(1193)+"es"]):this[s(1463)+"tManager"]?.[s(941)+"pointCon"+s(532)](),this[s(1328)+s(776)]?.["resetCou"+s(706)](this[s(690)][s(797)+s(536)]),this["_readyCl"+s(1003)]=!1,this[s(775)]&&e.PuFIl(this[s(775)].readyState,this[s(1028)])?this[s(855)+s(1093)](1e3,s(1722)+s(1651)+s(811),!0):(this[s(1457)]=!0,this[s(1728)]())}async[t(1135)](){let n=t,s={mNGOR:function(l,f,m){return l(f,m)},YhulQ:e.HvfPA};if(e.yxpMT(e[n(1791)],e[n(967)])){if(!this["_connect"+n(969)])if(e[n(658)](n(904),e.egafr)){let l=e[n(1694)][n(654)]("|"),f=0;for(;;){switch(l[f++]){case"0":this["_readyCl"+n(1003)]=!1;continue;case"1":this[n(1328)+n(776)]?.[n(1109)+n(706)]();continue;case"2":this._isInit=!0;continue;case"3":this[n(1728)]();continue;case"4":this[n(1463)+"tManager"]?.[n(941)+n(1248)+"fig"]();continue}break}}else e[n(1818)](_0x5b5b76,_0x5c3fdc,90),e.hQYVU(_0x55f982,_0x56763c,_0x35a570)}else{let l=pwbzNb.mNGOR(_0x47e038,pwbzNb[n(732)],{message:_0x152110[n(1660)],code:_0x538cd1[n(1133)+n(1029)],error:_0xf947a3});this[n(1839)+"hErrorEvent"](l)}}["addEvent"+t(958)](n,s){this.on(n,s)}[t(729)+t(1898)](n){let s=t,{type:l}=n;this[s(449)](l,n)}["removeEv"+t(921)+"ner"](n,s){this[t(1116)](n,s)}[t(1885)](){let n=t,s={yWvAY:function(l,f){return e[j(1364)](l,f)},BmfUJ:e[n(664)],VDdWl:n(1180),TKnqy:e[n(1881)],LQppQ:e[n(1922)],PfUhC:function(l,f){return e.pfrhl(l,f)},NEsxv:e.VMTZi,gCMIi:function(l,f){return e[n(777)](l,f)},bSZCY:e.mRGdT,vdzZD:e[n(884)],nCwNJ:function(l,f,m){return e[n(1800)](l,f,m)}};return new Promise((l,f)=>{let m=n,v={tZjQG:function(y,p){return s[j(863)](y,p)},wVRpn:s.NEsxv,mOVPk:s[m(1217)]};if(s[m(1794)](s.bSZCY,s[m(1787)])){this[m(518)+m(548)](),this[m(480)+m(1648)+"Id"]=s[m(1072)](setTimeout,this[m(982)][m(1263)](this),this._options[m(840)+"rval"]);let y=()=>{let A=m;v[A(1873)](l,v[A(902)]),this[A(1116)](v[A(956)],y),this[A(1116)](A(572)+A(587)+"t",p)},p=()=>{let A=m;if(s[A(1560)](s[A(1756)],s[A(1756)]))f(s[A(1844)]),this[A(1116)](s[A(1217)],y),this.off(s[A(1941)],p);else return new _0x51a517(_0x1f0481)};this.on(s[m(1217)],y),this.on(m(572)+m(587)+"t",p),this[m(982)]()}else return!!this._qosDB})}}})(),_e["CustomCl"+N(1779)]=Pe[N(1758)+N(1779)],_e[N(407)+N(779)]=Pe[N(407)+N(779)],_e.ErrorCode=Pe[N(1285)+"e"],_e[N(1898)]=Pe[N(1898)],_e.FWS=Pe[N(894)],_e[N(671)+N(851)+N(1723)]=Pe["Frontier"+N(851)+"vent"],_e["MessageE"+N(1723)]=Pe[N(851)+"vent"],_e[N(1475)+"t"]=Pe[N(1475)+"t"],_e[N(1337)+N(943)]=Pe["Reconnec"+N(943)],_e[N(735)+N(1779)]=Pe[N(735)+N(1779)],_e["createEr"+N(779)]=Pe[N(1683)+N(779)],_e[N(533)+N(1461)+"nt"]=Pe[N(533)+"ssageEvent"],_e[N(788)+N(1864)]=Pe[N(788)+N(1864)],_e["createRe"+N(1367)+N(1723)]=Pe[N(609)+N(1367)+"vent"],_e["decodedF"+N(680)]=Pe[N(450)+N(680)],_e["encodeFr"+N(955)]=Pe["encodeFr"+N(955)];for(Jo in Pe)[N(1758)+N(1779),N(407)+N(779),N(1285)+"e",N(1898),"FWS",N(671)+N(851)+"vent",N(851)+N(1723),"OpenEvent",N(1337)+"tEvent",N(735)+N(1779),N(1683)+N(779),"createMessageEvent",N(788)+N(1864),N(609)+N(1367)+N(1723),"decodedF"+N(680),N(1495)+"ame"].indexOf(Jo)===-1&&(_e[Jo]=Pe[Jo]);var Jo;Object[N(1625)+N(1342)](_e,N(520)+"le",{value:!0})});import{existsSync as y1,openSync as b1}from"node:fs";import{mkdir as E1}from"node:fs/promises";import{dirname as v1}from"node:path";import{fileURLToPath as S1}from"node:url";function A1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function el(t=J()){return y1(t.libEntry)?t.libEntry:S1(new URL("../index.ts",import.meta.url))}async function fp(t={}){let e=t.paths??J(),r=t.entryOverride??el(e),i=A1(e,process.env.COZE_BRIDGE_LOG_MODE);await E1(v1(i),{recursive:!0});let o=b1(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=it(process.execPath,d,{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 I1.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var I1,as,aa=et(()=>{"use strict";Jt();ne();Re();I1=H("spawn-daemon"),as="COZE_BRIDGE_DAEMON"});import{spawn as v2}from"node:child_process";import{mkdir as S2,unlink as I2,writeFile as A2}from"node:fs/promises";import{dirname as k2,join as T2}from"node:path";function Qr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function C2(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Qr(r)}</key>
21
- <string>${Qr(i)}</string>`).join(`
20
+ `+n)}function sr(t,e,n,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,sr),t.emit("wsClientError",d,n,e)}else as(n,i,o,c)}});var ip=ce(ze=>{"use strict";var N=$;function $(t,e){t=t-167;let n=da(),i=n[t];if($.wkzPIT===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",w="";for(let S=0,_,E,I=0;E=f.charAt(I++);~E&&(_=S%4?_*64+E:E,S++%4)?p+=String.fromCharCode(255&_>>(-2*S&6)):0)E=x.indexOf(E);for(let S=0,_=p.length;S<_;S++)w+="%"+("00"+p.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(w)};$.caBsut=o,$.puBbCw={},$.wkzPIT=!0}let c=n[0],d=t+c,u=$.puBbCw[d];return u?i=u:(i=$.caBsut(i),$.puBbCw[d]=i),i}(function(t,e){let n=$,i=t();for(;;)try{if(-parseInt(n(769))/1+-parseInt(n(547))/2*(-parseInt(n(1312))/3)+parseInt(n(902))/4+parseInt(n(393))/5+parseInt(n(185))/6*(parseInt(n(1551))/7)+parseInt(n(1569))/8+-parseInt(n(658))/9===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(da,753217);var JS=Object[N(281)+N(1368)],XS=Object[N(1307)+N(1043)+N(1341)],Qx=(t,e)=>function(){return t&&(e=(0,t[XS(t)[0]])(t=0)),e},QS=(t,e)=>{let n={JOvxG:function(o,c,d,u){return o(c,d,u)}};for(var i in e)n.JOvxG(JS,t,i,{get:e[i],enumerable:!0})};function e1(){return Vx||(Vx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function t1(){let t=N;return Zx||(Zx=[IDBCursor[t(954)+"e"][t(1477)],IDBCursor[t(954)+"e"].continue,IDBCursor[t(954)+"e"].continuePrimaryKey])}function n1(t){let e=N,n={pMTNK:function(o,c){return o!==c},jMtlN:e(364),ampGS:function(o,c){return o(c)},AfbZk:function(o){return o()},ipflL:function(o,c){return o(c)},sBuYB:e(1615),CsjVy:e(253),quAgI:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let d=e,u={HqwUV:n.sBuYB,fEbvs:d(253)},f=()=>{let w=d;t[w(1347)+w(649)+w(1236)](u[w(795)],x),t[w(1347)+w(649)+"ner"](u[w(1388)],p)},x=()=>{let w=d;if(n[w(1172)](w(364),n.jMtlN))return new _0xafc06e(_0x36af17,{data:_0x1ee0d4,message:_0xeeb1c8});o(n[w(1124)](Gt,t.result)),n.AfbZk(f)},p=()=>{n.ipflL(c,t.error),f()};t["addEvent"+d(1363)](n[d(667)],x),t["addEvent"+d(1363)](n[d(740)],p)});return i[e(287)](o=>{n.quAgI(o,IDBCursor)&&Qd.set(o,t)})[e(1616)](()=>{}),aa[e(770)](i,t),i}function r1(t){let e=N,n={ZBNGv:function(o,c){return o!==c},ZaoHB:e(517),bqTTW:function(o,c){return o(c)},zoGHd:function(o){return o()},hiINJ:e(1235),OovHf:e(253),pLHww:e(1586)+"3",IRjHp:e(1495),QUMQp:function(o){return o()},NAolX:e(613)};if(oa.has(t))return;let i=new Promise((o,c)=>{let d=e,u={pmeHJ:n.hiINJ,HGQsh:n.OovHf,ouwTL:"abort",oshFG:n[d(680)],HfZkG:n[d(728)],hIRuh:d(168),hqKbE:d(578),ABist:function(w,S){return n[d(507)](w,S)},OikhI:d(414),JIEwU:function(w){return n.QUMQp(w)}},f=()=>{let w=d;t["removeEv"+w(649)+w(1236)](u[w(688)],x),t["removeEv"+w(649)+w(1236)](u[w(438)],p),t["removeEv"+w(649)+w(1236)](u[w(1374)],p)},x=()=>{let w=d;if(u.ABist(u[w(1393)],u[w(1393)])){let S=u[w(986)][w(639)]("|"),_=0;for(;;){switch(S[_++]){case"0":this[w(1473)][w(1347)+"entListe"+w(1236)](u.HfZkG,this[w(1419)+"ge"]);continue;case"1":this[w(1473)][w(1347)+"entListe"+w(1236)](u[w(647)],this._onOpen);continue;case"2":this[w(1473)][w(1347)+w(649)+"ner"](u[w(455)],this._onClose);continue;case"3":this[w(1473)]["removeEv"+w(649)+w(1236)](u[w(438)],this[w(524)]);continue;case"4":if(!this[w(1473)])return;continue}break}}else o(),u[w(553)](f)},p=()=>{let w=d;if(n.ZBNGv(n.ZaoHB,"kgOLE"))n[w(850)](c,t[w(253)]||new DOMException(w(1527)+"or",w(1527)+"or")),n[w(1028)](f);else return this[w(1473)]?this[w(1473)][w(1298)+"te"]:this[w(1492)][w(1472)+w(372)]?this[w(952)+"NG"]:this[w(1004)]};t[d(1625)+d(1363)](d(1235),x),t[d(1625)+d(1363)](n.OovHf,p),t[d(1625)+d(1363)](n[d(714)],p)});oa[e(770)](t,i)}function i1(t){ca=t(ca)}function s1(t){let e=N,n={fmgxu:function(i,o){return i(o)},XvdnG:function(i,o){return i(o)},hpoAb:function(i,o){return i===o},TNOZD:function(i,o){return i in o},EJOAX:e(1141)+e(1084)};return n[e(443)](t,IDBDatabase[e(954)+"e"][e(449)+e(485)])&&!n[e(539)](n.EJOAX,IDBTransaction.prototype)?function(i,...o){let c=e,d=t[c(1382)](n.fmgxu(cs,this),i,...o);return Xd[c(770)](d,i.sort?i[c(1330)]():[i]),n.fmgxu(Gt,d)}:t1()[e(906)](t)?function(...i){let o=e;return t[o(790)](n[o(1457)](cs,this),i),n[o(1506)](Gt,Qd.get(this))}:function(...i){let o=e;return n[o(1506)](Gt,t[o(790)](n.XvdnG(cs,this),i))}}function o1(t){let e=N,n={peVml:"function",DJxkF:function(i,o){return i(o)},hNYSc:function(i,o){return i instanceof o},akszI:function(i,o){return i(o)},FZBWV:function(i){return i()}};return typeof t===n[e(1573)]?n[e(1399)](s1,t):(n[e(884)](t,IDBTransaction)&&n.akszI(r1,t),ep(t,n.FZBWV(e1))?new Proxy(t,ca):t)}function Gt(t){let e=N,n={EekRu:"4|3|0|1|2",esWZw:function(o,c){return o instanceof c},Wwltn:function(o,c){return o(c)},CjjVc:function(o,c){return o(c)},APDMC:function(o,c){return o!==c},fmUZg:"JsUfi",LJVVp:e(993)};if(n[e(465)](t,IDBRequest))return n.Wwltn(n1,t);if(ia[e(341)](t))return ia[e(1484)](t);let i=n.CjjVc(o1,t);if(i!==t)if(n[e(457)](n.fmUZg,n[e(841)]))ia[e(770)](t,i),aa.set(i,t);else{let o=n[e(1061)].split("|"),c=0;for(;;){switch(o[c++]){case"0":this[e(1309)+e(367)]=!1;continue;case"1":this[e(726)]=!0;continue;case"2":this[e(908)]();continue;case"3":this["_pingLos"+e(526)]?.["resetCou"+e(756)]();continue;case"4":this[e(1427)+"tManager"]?.[e(1186)+e(1198)+"fig"]();continue}break}}return i}var ep,Vx,Zx,Qd,oa,Xd,ia,aa,ca,cs,Yx=Qx({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={unpXZ:function(n,i){return n instanceof i},VBpee:function(n,i){return n===i},SfBdM:t(1403),dCKAh:function(n,i){return n!==i},WroaI:t(515),bPUwF:t(1206),qXtCO:"NgwTV",TMcLZ:function(n,i){return n in i}};ep=(n,i)=>i[t(1117)](o=>n instanceof o),Qd=new WeakMap,oa=new WeakMap,Xd=new WeakMap,ia=new WeakMap,aa=new WeakMap,ca={get(n,i,o){let c=t;if(e.unpXZ(n,IDBTransaction)){if(e[c(395)](i,e[c(609)]))return oa[c(1484)](n);if(e[c(395)](i,"objectSt"+c(1084)))if(e[c(1356)](e[c(1024)],e.WroaI))this[c(815)+c(1328)]=_0xdac243,this[c(982)]=0;else return n[c(1141)+c(1084)]||Xd[c(1484)](n);if(e[c(395)](i,e.bPUwF))return o["objectSt"+c(1084)][1]?void 0:o[c(1141)+c(210)](o[c(1141)+c(1084)][0])}return Gt(n[i])},set(n,i,o){let c=t;return e[c(1486)]!==e[c(1486)]?_0x532627[c(1141)+c(1084)]||_0x2cd2e6[c(1484)](_0x1cfd5f):(n[i]=o,!0)},has(n,i){let o=t;return e[o(997)](n,IDBTransaction)&&(e.VBpee(i,o(1403))||i===o(1206))?!0:e[o(284)](i,n)}},cs=n=>aa[t(1484)](n)}}),tp={};QS(tp,{deleteDB:()=>c1,openDB:()=>a1,unwrap:()=>cs,wrap:()=>Gt});function a1(t,e,{blocked:n,upgrade:i,blocking:o,terminated:c}={}){let d=N,u={MHhQn:function(p,w){return p(w)},eCPyP:function(p,w){return p(w)},vRQAk:d(578),dcDTd:d(306)+d(666),glOYu:function(p,w){return p(w)},ShBWk:d(189)+"eeded",wbOhh:"blocked"},f=indexedDB[d(168)](t,e),x=u[d(1590)](Gt,f);return i&&f[d(1625)+d(1363)](u[d(1444)],p=>{let w=d;i(u.MHhQn(Gt,f[w(1417)]),p[w(1299)+"on"],p.newVersion,u[w(464)](Gt,f[w(449)+"ion"]))}),n&&f["addEvent"+d(1363)](u[d(509)],()=>n()),x[d(287)](p=>{let w=d;c&&p[w(1625)+w(1363)](u.vRQAk,()=>c()),o&&p[w(1625)+w(1363)](u[w(1563)],()=>o())}).catch(()=>{}),x}function c1(t,{blocked:e}={}){let n=N,i={jUNHg:n(849),wziCD:function(c,d){return c(d)}},o=indexedDB["deleteDa"+n(181)](t);return e&&o[n(1625)+n(1363)](i[n(920)],()=>e()),i[n(1410)](Gt,o)[n(287)](()=>{})}function Jx(t,e){let n=N,i={TtwcF:n(1153),ISsAx:function(f,x){return f instanceof x},exBxX:function(f,x){return f===x},TbBJp:n(1278),wqRgS:function(f,x){return f!==x},GFbkM:function(f,x){return f in x}};if(!(i[n(412)](t,IDBDatabase)&&!(e in t)&&i[n(1550)](typeof e,i.TbBJp)))return;if(sa[n(1484)](e))return sa[n(1484)](e);let o=e[n(732)](/FromIndex$/,""),c=i[n(835)](e,o),d=rp.includes(o);if(!i[n(694)](o,(c?IDBIndex:IDBObjectStore)[n(954)+"e"])||!(d||np[n(906)](o)))return;let u=async function(f,...x){let p=n,w=this["transact"+p(485)](f,d?"readwrite":i[p(707)]),S=w[p(1206)];return c&&(S=S[p(1046)](x[p(254)]())),(await Promise.all([S[o](...x),d&&w[p(1403)]]))[0]};return sa[n(770)](e,u),u}function da(){let t=["EMrxBxm","x3bYB3rVy28","t3PhqLi","B25LCNjVCG","DgvZDa","qwj5A20","zw1PDa","u2r6rfu","CxLHt1q","CMvZzxrfBMq","y3vYCMvUDeu","EffOCNe","C2vUzf9Hy2S","EKjvruu","AxnmB25N","EKLWzfy","B25SAw5L","C3vIyxjYyxK","D2PcEeu","q2LJBgG","D2vI","Cg9PBNrdB24","x2HHBMrSzu8","v3HYrKW","CgLUz0LUDgu","txHHBfe","yMfSrxzLBNq","D1bcwKO","DMfS","C3rVCMu","EgPIEMK","uvLYrwu","ELzIDuq","mdaWma","uhzgDw4","x2fKzfDZtgK","y2rzrvm","x3jLBw92zvC","Cgz2vxC","DhLWzq","vujfrgS","CgTRqwS","yNL0zu9MzNm","z1zLBg8","ENvxwKK","m3WYFdr8mhW","Ehf0Cfm","BvPQtLu","DMjLzKi","CMfNzvn5BMm","AevYCM9Yrxy","rxH0rwu","y3jLyxrLt2i","rhLdzNG","q21qqLy","DfjQCLa","v3fyBgW","z2v0qwXS","y29TCgXLDgu","BMvY","rNrZA3e","r1fkuxK","yM5gy3C","shPrzMO","rxzft28","x29UvgLTzw8","DhPWz0O","Dufyvhm","B2zMBgLUzq","ihzHBgLKigq","CYbHBhjLywq","Duj2EfG","BeHTtMG","r21KtMu","A2v5","zMzLCG","ywnRtxnNswq","zMLN","x194x21Zz18","x3nLBMrby2S","sgz3q2i","C2DPza","quXm","ywrK","q3vZDg9Tq2W","zwn0","tfPAweW","DgfYz2v0","wfHSzKu","zMX1C2HfEha","t2jQzwn0","zvjXBxa","CIb0DhDjra","q1zRtw8","AurcvMu","BMfmBKS","wgrjyK0","CxbdsLm","DgvmB2Djre4","Cxfurgi","x2HHBMrSzva","C3rYAw5N","x2nYzwf0zvm","x2LUAxq","AhjzDuK","qwnSwwi","B0vdqK0","yxGGCMv0CMK","zcWG","zNnzrKu","x3jLy29UBMu","AMvJDfn0B3i","u3DIwMK","q3jnrfK","AxjLza","yw5Hz2vY","DLvxtu4","ywv3r0W","EuT4r2u","C2vYDMLJzq","rxnNqMW","CMvHzhLtDge","B2XKvMvYC2K","Dgv4Dc9Qyxy","t1jlBKy","rK9UwgW","zxjFDhrS","tg1is1a","ANPqC0W","CuzPu20","z2v0t3DUuhi","weTgEum","x3jLywr5q2W","B013uuG","tNverwu","m1Phr3bmzW","vLviqLC","zvvYBa","tuvtu0fhrv8","C05tDK8","BvPZDwu","BgLTAxq","y3vYCMvUDeK","DcbSAw1PDa","B2nRzxrgywK","AMLtvee","yu9ZAvy","CMvmtfi","x29Uq2XVC2u","Dg9cExrLC0i","yuTMDK0","B3vUDa","vLjmtgq","C29YDa","BgzKAgC","Cezlu20","D0fYuhC","ywDLu2HVDW","sxHure0","CMvJB25Uzwm","AwXLtMfTzq","z2v0q3vYC28","Bwvmqw0","zhvZA2K","BwvZ","s0fWzKW","ywXSq3vYC28","zM9Yy2u","zLz0DKm","BwvZC2fNztO","CMvTB3zLrxy","vKzlqu0","Bu1MzKe","DLbwBu4","C2v0sxrLBq","ihrPBwvVDxq","DhjPzxm","ENvcqM0","twLZC2LUzYa","zenlqwG","Cg9PBNrbBMq","EvzfALa","B1Lxwum","CgjICdi","q29Kzq","sLjIELC","tgLZDgvUzxi","Bwv0Ag9K","BwXnExq","BeHHBMrSzxi","EujTCvm","B3bLCNr5","tg9JAW","rLjptLrjrvi","CgfYC2u","tuLOAuK","CwHTELO","B3v3veW","v01pvfG","zxz2y1C","v2vPEgLUsLm","vMX1Dei","s1jJtK4","x19LC01Vzhu","x3nLCuLK","y2fSBa","tKfusvzfx0u","s3n3y1C","D1boAwO","mNWW","wKDwBNe","zKvIDNm","AxPwBgi","q050vKO","rNjVBNrPzxi","ug10veK","t2LRAeK","lcbTyxGGCMu","zMLSDgvY","BgLUzw5V","C2vYDMLJzs0","ugPAv1K","reP4A0y","CxHpA1a","uwfpr3C","y29SBM8","zg9Uzq","AxmGDw5Kzwy","z3PevNy","C1LSEhm","uev1wKO","t3j0vKi","ChjgEuS","D3PPq0q","Be9YrM0","x0rctMfTzq","tg9Nsuq","Bwu6ia","u2vXsuq","r3jYBxm","CMvZDwX0","we9gEha","x29UtwvZC2e","yMDWz2C","s2DyCLi","CgfNzxnOB3C","t3bLBKv2zw4","Au9nCfK","zcbLCNjVCI4","DMvY","x2vUzhbVAw4","B3bLBIa","x2HHBMrSzvi","tufyx1jfvfi","zNjHBwvuExa","B25fCNjVCG","uLHsAve","AvzkAum","thbxB3K","Dg9cExrLC0W","t2nSuM4","CMTLCKDSB2i","Agv3DKO","BwvZC2fNzv8","tuPXt0C","Cgf5Bg9Hzeu","Dhvmt0C","u2Hcv2S","Awj4ExK","y2uGBM90igK","A3jeAfK","sxjet0i","yw5ZzM9YBvq","txnLENC","DgPntg0","y3r4","rNHRvgi","zwnVBM5Ly3q","D0jYvha","y2XVC2veqG","whzKBKC","CMvWBgfJzui","ywXSzwqGBxu","DMvUDa","ywDLrxzLBNq","x2LUAxrhBg8","x21PBMLoyxy","CM9XCKW","vermBuK","Cg9W","C1LWBxu","svPzsMK","ywnOzwq","v3vmru4","rLfcBui","yxv0B21HDgK","x3DZ","rezsDKG","wuD1Cgy","r3jjyKG","ywr2yw5Jzq","zMTAA2O","sgrxBuK","zNjVBujPDhm","igzHAwWSig0","BgLZDgvUtMu","DMryvfK","z2v0","rgjxCuu","CvH0q08","Dhj1y3rVCIa","zxjHDg9Y","tKj4rvG","DxbKyxrLq3u","t0vjvuO","x29WDgLVBNm","wMDAA3q","x3vYBa","BwvZC2fNzq","CuXzBKe","yvHOBg0","Bwf4uMv0CMK","ExLZwMG","yxnL","wejxvNu","we1vwuy","serUtuK","z3nHBwi","yMrnzha","zM1NEhu","zxjqEfq","zfPMAu0","BNHvEMm","C1D6y1q","CwLSrLm","vg1MrfC","yvj3v1u","z2v0qwXSs2u","ugjrq04","C2HYzKe","zM1nzMq","vNv4vNC","y2HHCKnVzgu","wgrTywi","wLflzfa","rvjst1i","Dw5ZAwDUzwq","nhWXFdj8m3W","mNWZFdf8nhW","CgTUteW","qwjVCNrfCNi","r2nLAwm","zhfTEgS","B3f3wuG","BMDLza","zw50","yxztsuu","Dev2zw50","Bxvyq2y","yujMy2O","s2zmqxO","AeHmDKG","zxjYtxnN","igXHCMDLCIa","B25dBg9Zzq","uujxu3e","y2HOChq","y3jLyxrLrxi","y2XVC2uSihC","B2LUDfjLywm","zw5HyMXLuw8","tuTLC2i","x2nSzwfYvgK","zxHcEfG","n2HyBNbMyW","CK5HrMq","DujlDw4","x2zVCM1HDeu","BhrttNq","C0jf","rNbXyMe","x2DLDeLUDgu","EgHJq3C","zw50zwqGDhK","DgLTzw91DcW","z2LcsK8","zgnevgq","ALDZtLy","yKjSzwy","rujRuKW","zNfIrue","rwzRBfO","nZa2mdm2ofPjz21rBG","yuT4q3m","qvbPBwS","zMLUza","CgvwBwW","De9WDLK","vKPhvvy","AxnFywnR","y3vYDMfSDwu","qw1VDw50","BeDMDuW","BfrJz08","C2v0u3rVCMe","uK9kAui","yKnbCxq","ExP5rue","zfPLBLm","nhWXFdj8mhW","ENnSBwe","y29Kzq","v0DHtvy","z2Xpwxu","y3jLyxrLtwu","BNruCMLLC0m","C1z0A28","A2TIDgW","y1LRs0W","yKngwxy","yxnZAwDU","z1Pxzwy","C2v0y3vYC28","AKnLzwu","x2jPBMfYEvq","C3PothG","z0vICvy","CMfTzq","A2v0yvi","B25VCgvU","BxP6AKq","sKDtEKm","uLDdvKu","A1bqqwi","De1HBMfNzxi","AwXK","ENDltNa","x2LZtwLUAvq","C3vJy2vZCW","y2f0y2G","AxHbzvq","u3bTBgG","vgLTzw91Da","mxWWFdz8m3W","DeDbvu8","AhbtqNO","CKzOz2i","z2vY","ywrKrxzLBNq","x2n1CNnVCKy","z09qtNO","B3bLBG","Dg9Y","x2nSzwfYugK","z2vrDwv1zuW","B3bLBKrc","CNnVCKzPBgu","rNv5Dee","ANDUsK4","v1DgDuS","wMTUv0O","Aw9UvgLTzw8","DercwwG","x2XPC3rLBMu","DgfIyxnL","AgvHzgvY","B3nLrxzLBNq","rwvuCvK","ntKZmdq1nerXBLDNtG","uxvLDwu","uMTYCKC","yMfJA3vWigu","DxbNCMfKzw4","wMPjEuK","D3m6lY8","Dgjhs0C","ANrJt3a","su5tvefova","wLj3v1y","DxzssLa","BxnNsuq","tg9NsurozxC","BwfW","u2vYDMLJzvC","vxzxvNC","BNrbBMrvCgq","y2vZC0HHBMq","ufrKywG","rxjYB3jdB2q","DcbVzIbYyw4","rgjpDu8","EMXTq3C","x21LC3nHz2u","B3jL","x3DHAxq","D0fYqMW","x3nVy2TLDa","sxP2D1e","sfbTq1G","qMrLt1e","wfrdtKq","tKDhEuu","vw5PBxbSzw0","A1HtvMC","uNzdrNK","Dvn4vMC","CufYBhG","EKTzqKS","qvPIAM0","yuv3reO","Agv2sNq","CgvYC2LZDgu","tg1JsvC","ysbTDxn0igi","Ee1AyLa","Efrurw52","sfHSrve","te9QBKO","Ahr0Chm6","wNfvrvq","sezNCLC","rM1LC2i","Bg93","vMnfzNq","CMfTugfYyw0","v0jZt1K","AwrI","vfvzww0","CLzHBhvLCW","Aw5PDcbrB1m","BML0AwfSAxO","v1jpvKS","D3jPDgvvAw4","DMThDeq","yMLUza","r2rvrue","zxjYB3i","C2HPzNq","C2fNzq","u0Pxsha","zLf4tu8","uNDfwha","ALzRCe0","vg9grNa","A1n0yxr1C0m","A1DyAw4","uw5zwuu","y2XLyxjtDg8","B2nRzxq","suHNEKy","CfjsAMO","t0r3twW","CgXLyxnLiha","q1rXCee","y2TQENu","senev2K","v1rwrNm","AxnAzxjV","vurisve","t0jXuvO","qNLNru0","y2HnyxHuCMK","u3DjANm","rNnVzNq","zgvMAw5Luhi","C3rHCNq","Cw9Zx18","ve1JtfO","AxroDe0","yMnlzwu","DgHLBG","zgrjrcWGzgu","zw1LBNq","x2rYB3bhBg8","mhWXFdr8mNW","sff2Eg4","Ec11C2uT","CKnIq0O","AvntA2m","CxniDMu","sLnptLa","s1DkA2y","DhbizwfKzxi","BwLZzq","CNzHBfzHBhu","x2n1CNnVCK4","quTTvM4","uMvlu0G","ugTuwLG","DMvYC2LVBMm","sxjNB1y","zxrxB3jRq2G","yNvMzMvYzwq","zMvY","y2nuDw0","uezZCfa","rK5msuW","zxjYtM8","uwTVvKG","Bg9Nsurhzw4","wfz5DNO","q0Xpu0LorW","x3bYzwzPEa","sgHjEgW","t1nXD20","yLreCMG","zMXVB3i","zxjFAxnFywm","B01wC2C","yMTWCLe","yxKSihrYEsa","txnQsgq","Egvmv2K","rMvbyw4","x2rPC2nVBM4","qxPutvi","CYbPBNn0yw4","zM5cBe8","ue9MvNm","tfDrv2O","qLPczwq","ugLty0K","y2HLy2Tszwe","CMvKDwnL","AgfZ","wvbnDeG","EujYqNi","zxvmy0e","Au5LBey","tLb2wey","Cer5CeS","Evrhsu8","v3HQr2e","uhrtDwS","ExbL","rNvrsfy","uKHlzfe","ywrKt25L","t3npuLm","zKHNDeS","qxnev00","Dg9mB3DLCKm","qKjiwxm","yxKSig5LDhC","q0fAueG","z2vjBMzVu3K","EenfBM4","A21wrMq","rfDYBe0","zuLpsuu","B3nLza","BgvUz3rO","Dg9iyxnO","qwjNuuy","rxD0wMS","y09Wzw4","DvvfCee","teDHtMi","rLrrqwC","Exvdz0K","rMHbvKK","CM9YrxzLBNq","r3vgwKe","Bezls3y","CgLUz09Uy2u","AenSB3nLrxy","AeHrsxu","CNjpz1i","AwjLCeO","yNvMzMvY","AM5dBha","Fdb8nxWZFdy","CMvZzxrdB3u","v3PNAfu","B2rZzMu","DhjPzxmGCMu","mZKXotq4nwjVAMLnva","ywHMtK0","vKjWzwu","q2Tfufy","l3DZl3yY","yu51BhK","zMjRtvO","y3vYC29Yx2y","vxbKyxrLq28","vKDxr1u","y3jLyxrLuMu","z2v0q3vYCMu","whjWA0O","rfPYvLy","t0vwDMW","yNL0zuXLBMC","CK1mC00","y2HLy2TdDxi","EvjLy29UBMu","svnZqxG","D3PyzvK","u05xtve","CxbbwxO","DeLcDM0","C2D1ELy","zv90Aw1LB3u","ufbQyKW","ruTuBwy","C2v0zgi","DxnLCKLW","yvbeD1K","yxnJCMLWDa","zxf1rKK","ELLTu00","BMrWB2LUDfq","x29UugfNzu4","v1zMzhK","D2jRt3e","qMHUtuG","uM9cuuq","BNvTyMvY","uefuEMy","BwfUDwfSihi","t2fjshK","B3jRig9MzMW","seDrC2G","CLLLAg0","tMfTzq","tNH0EfG","rwXbrgy","AhbVqwi","Du1wqLi","A2nhB3O","Cgf5Bg9Hzfq","ugjhufu","q1ziqwW","DhjHBNnHy3q","wwr3svy","CMvXDwLYzwq","CNzHBa","v3nUr3q","ywX3yxLZ","AhflyKu","x3bPBMDmB3m","qvbetum","tfLjzhq","y3vZDg9Tshq","q091u00","BfrPBwvVDxq","qNvrq0q","u2Pbq00","zunqEva","zxnxwNC","BerXt00","q0fhB1K","zwrPyxrLBhK","svHHwxG","Bg5qAva","A2PmAe4","BM5Ly3q","C2rIy0m","s1jrEKe","Be1uDvy","CxfWvhG","x2rLC3rYB3K","rKLmrv9ot1q","DhDVCMTdAge","CMrNz04","x2LUDgvYDMe","BMv4DcGPigm","yNDHr1u","BvjRwg8","Aw9U","tvHkvhG","zw5HyMXLqxu","zxHWB3j0CW","zNjVBunOyxi","yNbKt0G","wgzYD1m","BurXC3e","CMvZzxruCMK","lcbOB3n0BMe","s05fB28","u3rYyxrLz3K","Ewvhvei","t1bftL9fuLi","BM1OEuG","s2z1s2S","zgjluNG","sw51veu","y3zirMS","z3LltLm","BwLUzW","uwTive0","wKjor3y","uKHfz0K","D2jpAgG","D2TZyva","AefHsvm","reDjDwi","r0Lyuwy","qKLWD2u","Bu9ZD3G","aaaaaaaaaaa","EKXsDw8","zvHvD2K","EwP1tge","ufLmv3i","AgvHzgvYCW","Eg9SB0S","qNfHs1e","x29UrxjYB3i","Ew5Jzuu","C0nVDw50zxi","DxjS","AKfXt2y","CMvHC29U","BhrPCgXLihq","zuz2rhG","C3rLBMvYCW","sMrrsK8","y29Uy2f0","ywDL","CgLUz1rPBwu","DxrVuMvJB24","BgvIy08","ve5pwKq","zsbHihn0CMK","EwXAsNK","zNjVBuj5Dgu","zKz0uMi","uKzwsKy","Bg9Rvfu","CMPcs1K","mJC1mteXogT5CwriDa","Ae9Wzw5fDMu","C3nHz2vfDMu","rLDt","CMvTB3zLq2G","tKDFrvjst1i","sKLfD1u","svjQtMC","x2LZqNjVD3m","ihrYEsbYzwm","y29UC3rYDwm","qvj0rMW","q291BNq","yMfSu2nVCgu","Ag5nuxK","ywzL","C2vYDMvYvgK","CMfoB0e","B2fK","tLHJyM0","Bureu3e","rvvyv1m","y3jLyxrLrwW","C2PizKe","A3bdsxi","ChDWrNC","B2nRzxrtDwm","zuXzz2u","q2DAAeO","AufNANy","ywTMzhe","y2XVC2u","D3jPDgu","B0XHqu4","rLjpzvy","ywnRx2nVzgu","x3bPBMC","rNnhzuS","suvtx0vsuK8","mtb8mtf8n3W","z1rPBwvVDxq","CxPRzgq","zw5KCg9PBNq","C3vIC3rYAw4","thjgC2S","CeTmC2W","m3WYFdb8mxW","D1D3AeO","y3jLyxrLq2W","Exbqv3a","B3bIteC","DgLTzw91Da","te9Nv2C","vKfnCuW","EgPhy1O","yujgquS","ChbMz0W","zcWGDw5RBM8","CNnjEKi","ugH1uuW","Dgv4DfbHEwW","Dg9VigXHCMC","u2zcze0","BMCGzMfPBgu","shPUu28","ChvZAa","ywjVCNq","swX0wMq","Be9zzui","Dg9tDhjPBMC","A29VyKK","B25tDgfYDfi","CYbWyxjHBxm","yuTPC04","rKf6Dxa","sxrHwfi","se9oDva","Aw5KzxGGB3u","z2v0s2v5","shLcrvO","uvHcEvq","CgLUz19VBMm","qLP1rfK","yvfLENG","DMfSDwvZ","uMvJB25Uzwm","zM9YrwfJAa","zNjVBNrPzxi","rMHSBwy","x2LUAxrqCM8","EMvlC3K","vMzjv1K","C3bSAxq","Du5UDgu","tgjIs2K","D01Xvvu","CMvJzxzPzwq","tw9KDwXL","z3jRCNO","igzPzwXKoIa","AeLsDwG","nhWXFdn8mhW","zw50tgLZDgu","yvruzMm","qMnUEvC","EsbJBg9Zzwq","zw5fDMvUDa","rLHmwMm","BMnwzLy","Exbtwwe","s1jcswi","mJiZmta3otncwLnpzwS","BIWGAg9ZDg4","s0vxqMq","v0T5CNO","uxDVs20","ExfAugS","wwfXA0W","zxj2AwnL","AgfUz2u","C0j1wui","B25szwnLAxy","BwvKAwf0zwW","yw5Nzq","BMrLEa","BwLUAvbYB2C","r2P5ruu","quroDuq","BvfOAM0","DMj6rK4","r1jOqMK","zfrezuK","qxnQsMS","CeXiD3C","y1jLyLK","zMznDwq","y1LhDe8","B1HTu3y","Efvhwu0","AvrZrgy","ywXty29Wzq","Cg1LseO","CNnVCL92ywW","y29UBMvJDeu","AgfOsfC","z2v0u3rVCMe","Dw5RBM93BIa","r0zIA00","sejPEfa","zgvJB2rLzey","EeL1q3G","vKTWzxK","yvzQt0K","EwHzs2y","Fdr8mxW5","Bwf4twvZC2e","vvPQwK8","BNrfBMrWB2K","qLvpCLG","AgvKtwf4uMu","vhr3y0y","ywDLsgLKzq","s2fsDgu","uhbzwee","AurXu20","zgLZywjSzue","B2vVuMi","tKfVBfG","CMfUzg9T","DK9vEfy","EffkDwq","o2nOyxjZzxq","DeTfz1y","AKHsswq","mdaWmdaWmda","wNfzwvq","Cw9Z","zufJAW","yw1Lu3bHy2u","x2LZsw5PDa","BvrzB08","svjQsha","uMvHzcbWyxm","vLPVv3e","zw5HyMXLvhi","CMvWBgfJzq","Ehjqqum","D1DrvMG","twvZC2fNzuu","zg16BM8","Bxz5tgq","Bu52z04","B25nzxnZywC","q3nQvNK","ihn1y2nLC3m","DurJs0i","ENvhsvy","D3jsChC","yw1LoIa","tfDgyK8","EuPktgS","z2v0sxrLBq","vuPTvge","uvDJzeu","CNnVCL9Uyw0","x3bHDgHlzxK","zv9ZDwnJzxm","u3D4zuq","txnTywi","BNrLCG","rK1TsuC","zNHfr3O","zvfbvvO","tePxzfa","u3ffwhe","zNjVBu51Bwi","DMfSDwu","CMLLC0nVDw4","BMnLq2XVC2u","DeXereO","zxH0ugf5Bg8","B2rcEfy","mtaWmdq5m25us09Vsa","C2v0","BMCGDxjSoIa","C0zzsLC","Ec1TC2CTCw8","rKLJwK8","DxrMofDYAxq","Agv3tNq","zw5NDgG","BM93","D3nZoI8V","zxq9DxrMltG","AuPgqK4","q29UzMLN","CM92AwrLige","CNjVCK1LC3m","y2HSuwu","AuPWtxi","CM1iwNe","x29Ut3bLBG","CxvLwuu","yxbWBhK","Aw47y2HHCNm","Duvgu1e","vgHOBLK","x2rItMfTzq","shf3vvy","sK10zfK","y29UBMvJDfm","BwvY","uMX1Dfu","Aw5N","C2vUza","Eff1EMG","y3vYC29Y","DhjPBq","Bg9N","qw5YAwS","BgvY","Aw9Ul2PZB24","Be5NzLq","z2vPug4","ywrftwG","y3vYC29Yx24","zgvSzxrL","rNnlu1q","Bwf4tg9ZC0m","B25JBg9Zzq","DwHur0u","BgLUzq","AK1vChq","y2XmquO","t1jcuhu","AxnrB1nby2S","uhjiDwK","AxnszwfKEq","x2rPC3bHDgm","yxbWzw5Kq2G","y3vYC29YlNm","x1fVu01HBMe","tw1hs0i","AgLNAa","ALDbANy","vevrq24","DMvYC2LVBG","vMXMqwC","D3fsz1m","DgHHBIbSB2m","zxjFBxnNAwq","yMrFzgLK","C29KAhq","tM9yvKu","tePwvNa","Ae1LC3nHz2u","D3Pytw8","B1jjBMm","y3ruAw1LB3u","Duv0Cxi","Bg1ItgS","z1LcA20","yMXVy2TLza","yNfuvfC","sw5qs2m","A2v5CW","lcbxzwjtB2m","CMv0CNLdB3u","DeLUDgvYy2u","AM5LAMe","u1rArgC","zufxwem","BgD2v0S","zxf1ywXZ","Aw5KzxHpzG","B0zWwxm","ve92AxK","Dg9oDw1Izxi","Ehj5tMy","Cg1vufe","AvnADfC","vxHXrgu","ueTpyva","B3jpBMXPBMu","zgvS","DgfLsMe","x25HDMLNyxq","y3jLyxrLt3a","zhjPwM0","DKr2D0K","q3vZDg9Trxi","BNP5qxK","AuzTAKm","uwzNvNi","C2XPy2u","yvPVCLi","Befnrg0","Ae5zu2m","yM9KEq","s3jPr0u","ExfTq1C","y29UBMvJDa","DM92weK","D2jYuNy","veXiugK","teTUD3O","qNvrvxG","AeXgruy","Dhzts1O","ExnYC3G","vxf4Eey","yxbWBgLJyxq","D0fQEee","BxPjDK8","u0DArfO","oda5mta0u2TOvenv","AefwyLm","zNvUy3rPB24","D2fZq2XLyw4","Aw5JBhvKzxm","sxPhuhy","x2nVBM5Ly3q","BKXPBMu","ihrVihjLDhi","DfvZu08","zw5JB2rLrNi","AhHwBgq","whLoB0G","vuLHExu","CML6zvG","x2rLyNvN","vujxz3y","Bg9NsurozxC","ALvosgC","z2D5rfG","tvHeuKi","u0HOB1C","rNLbtNi","DMLJzuLeig8","Dw5KzwzPBMu","B25tDg9Wsw0","DerWCgS","yxrcENO","wuTWBhm","yuDpEMi","uenSsuK","ywnRDxbfBMq","AefJA01LC3m","Aw1LCYbPBIa","yNvrEg0","CxbhBeu","AvnLsM0","BNj2D00","v1DJqMK","Bg9IywXty28","x3bPBMDqB24","rKvst0C","Dg9cExrLCW","BhvAtgO","y2vbsNO","Dgv4Dc9WBge","B25ozxr3B3i","ww9lAum","CLnTDNa","A29VreO","q09otKvdveK","EfbUwNm","ChjVDg90Exa","zhLizg8","DMnWv1O","yMLUyxj5","vuT0ENe","uevwrLO","x2DLBMvYyxq","v1Diwwq","EuTOqu4","tg9Lvve","zhfKCeG","C0XPC3rLBMu","C01iEgu","ENPKuNG","B2TKAfO","AgfZt3DUuhi","quPPsfO","C1Luvwi","v2jrq2S","yNL0zxm","C2nYAxb0","CK1zEhe","Bhm6ia","shD5swi","wM1TCMS","EfnJDKm","wK5fBwy","B25pCgvU","y291BNq","sfr3why","Ec1TC2CTy3u","vMvYtgG","B3nOrKC","Ee54y1i","ALPXu2K","qKXvsKi","whnxr1q","zgLZCgf0y2G","nhWZFdf8mhW","tMLXCgW","uKzgCM8","zfbHtNO","zeTvCvu","Dw5WwfO","ChjVDg9JB2W","z05eqxG","y0TMte8","z2HhDeG","AuX0uKm","D24GCMvHC28","q0Xpu0ve","icSG","C2v0q3vYC28","uLjpuG","rfrtyKK","wfrewhe","zwfwwLq","DgLUzYbZzxi","z0DQsg0","CgLUz0XVC3m","DvrttwK","Dw50","uw51wNa","AwDHDg9Yt24","EK9XCgm","Cgf5Bg9Hza","A1HSrwe","vxjcvMe","zgf0yq","y2HnyxHdB3u","v3jVyuK","Chv0","EfvZzuvUDG","vKv3ENm","EM9hsgq","EvfpwKG","vu5uvwy","yw1L","rurhA1u","yMLUyxj5vhK","ELnjze0","z2u6ia","q09oveLovuu","BMfTzq","zhDZCwK","AxnbCNjHEq","CMPrqMy","qu1UEw0","sKL6Bge","B3bLCNr5tMe","C3rYAw5NAwy","zMLSzw5HBwu","Aw5KzxG","B25mAw5L","DKX1wLq","Bfj5txi","x2TLEvbHDgG","q09jBfi","Ee1qt0q","ywWGy3vYC28","u0XWrwq","m3WXFdr8nxW","z2vtEw5J","EMrTrwi","y29UBMvJDca","D2LSBfjLy28","DeLK","rwvRuNu","D1Lcuu4","t2H5twm","CMvUDevUzha","uKvRyKy","qMLWAMq","DhfPwLm","qunnsvy","zxmGCMvHy2G","vw5Oyw5KBgu","zeDmtge","C0vfzMG","Dw1YEvG","zLvmru4","Ef9MCM9UDgK","whDYB3K","ExfHt3u","ELfezLC","qwr3weS","y29UBMvJDgK","rLzpt1G","AxnrB1nnzxm","BMnZueW","B3jLtMfTzxm","B2zMC2v0","uLrrrvq","zLDMz1y","B2fVsMC","BMDuAw1LCG","yLPIzeO","rxzLBNq","q1b4Cwi","x2LZv29YA2u","y2XLyxi","Dxrjza","zw5JB2rPBMC","x0vysvnu","vgfN","ywriBNq","ihrPBwvZ","zxH0zw5ZAw8","x2n1CNnVCK0","we9bEvK","v2TNq3e","x2LZtM9Kzq","t1jnsxa","Aw50zwDLCIa","z2nmwgq","BMrWB2LUDca","CMvZB2X2zq","x3fVC0rc","ChbL","whPJBhG","BezSDxnO","EgnHq0e","D3fJru0","C29Tzq","ywnRpwzYB24","BMnNBuO","B0TQEwW","AM9PBG","z1zNz2e","BxnN","yw1Wr1m","yu1ouuO","yxv0BW","qxLJvgK","C0fQyKy","Bu5cC3a","AwXSihvZzsa","uMPmDMi","Aw5Lza","shLVtK4","yw51Ce1LC3m","B25TzxnZywC","BMnVzgLUzW","B0z1EeG","tLjfzKC","zuHft0G","CMvJzwL2zwq","B2jQzwn0u3q","q0T1zKi","ChrVCG","v2vIu29JA2u","CMrYEKK","x2LZtwLUAvC","t0PMu1e","C0Xf","AMfdAhe","t1bftG","sfnxzvu","zuD0r0G","CMvHzg9UBhK","vxfgzhu","B2zM","yxjYyxLIDwy","ywnRx2LK","rMvNzhe","zxPIA1u","uejtAKe","zuvnvMi","C2vUDa","r1HNA2W","yKzHqK8","zMzmAw5L","CgrVt3q","ChjVy2vZCW","CMvHzfvjBNq","sLn6ChK","uxbKEwC","vfL0Dhu","Ce1utKS","Ee9MCva","BwPnrgG","su92t2W","zwrPtu8"];return da=function(){return t},da()}var np,rp,sa,d1=Qx({"node_modules/idb/build/index.js"(){let t=N,e={gsamb:function(n){return n()},sMHxe:t(1484),shrfA:t(625),zZAtK:t(1234),lFKKv:"getAllKeys",lDqOM:t(982),mlMyt:t(813),ZRwWV:function(n,i){return n(i)}};Yx(),e[t(1504)](Yx),np=[e[t(966)],e[t(1516)],e.zZAtK,e[t(380)],e[t(466)]],rp=[t(1025),"add",e[t(1365)],t(1094)],sa=new Map,e[t(195)](i1,n=>({...n,get:(i,o,c)=>Jx(i,o)||n.get(i,o,c),has:(i,o)=>!!Jx(i,o)||n.has(i,o)}))}}),l1={idb:function(t){let e=N;t[e(488)]=Promise.resolve()[e(287)](()=>(d1(),tp))[e(287)](function(n){return n})}},Xx={};function Ut(t){let e=N,n={CVHAl:e(1525)+"0",mZjNU:function(u,f){return u!==f}},i=n[e(448)].split("|"),o=0;for(;;){switch(i[o++]){case"0":return c[e(488)];case"1":var c=Xx[t]={exports:{}};continue;case"2":var d=Xx[t];continue;case"3":if(n[e(1224)](void 0,d))return d[e(488)];continue;case"4":l1[t](c,c[e(488)],Ut);continue}break}}(()=>{let t={PqXda:function(e,n){return e<=n},GKXdj:function(e,n){return e>=n},YdwIV:function(e,n){return e+n},AsDWM:function(e,n){return e!==n},XdIbM:"GEwSe"};Ut.d=(e,n)=>{let i=$,o={geiPn:function(d,u){return t.PqXda(d,u)},hewvJ:function(d,u){return t.GKXdj(d,u)},xQJud:function(d,u){return t[$(450)](d,u)}};if(t[i(357)](t[i(1273)],"rQaEC"))for(var c in n)Ut.o(n,c)&&!Ut.o(e,c)&&Object[i(281)+"operty"](e,c,{enumerable:!0,get:n[c]});else{if(o[i(810)](_0x3f3cb7,-_0x26c775))return _0x410f73;if(o[i(1439)](o[i(717)](_0x1d8e9f,1),_0x36e60d))return _0x10258c}}})(),(()=>{let t=N;Ut.o=(e,n)=>Object[t(954)+"e"][t(969)+t(1368)][t(1382)](e,n)})(),(()=>{let t=N,e={qpCJS:t(1380)+"le"};Ut.r=n=>{let i=t;i(926)+"d"!=typeof Symbol&&Symbol["toString"+i(1098)]&&Object["definePr"+i(1368)](n,Symbol["toString"+i(1098)],{value:i(644)}),Object["definePr"+i(1368)](n,e[i(1274)],{value:!0})}})();var Oe={};(()=>{let t=N,e={zYmSM:function(a,r){return a(r)},mNvgN:function(a,r){return a+r},reLLR:function(a,r){return a*r},WWHYd:function(a,r){return a(r)},IXaYx:function(a,r,s){return a(r,s)},uEFSQ:function(a,r){return a+r},jWAjv:function(a,r){return a!==r},InPKc:function(a,r){return a&r},muXCf:function(a,r){return a|r},bFaBO:function(a,r){return a<<r},wzXMo:function(a,r){return a&r},UJmTa:function(a,r){return a<<r},eRqmp:function(a,r){return a&r},ZqYYT:function(a,r){return a<=r},KRBIb:t(937),SwxeD:function(a,r){return a+r},HCDWi:function(a,r,s){return a(r,s)},BUOrX:function(a,r){return a(r)},InuTE:t(1210),cKfLO:"ffff",VekSZ:"00000000"+t(721)+t(721)+t(721),fQxMO:function(a,r){return a instanceof r},raNoA:t(947)+t(791)+t(780),TOviy:t(898)+t(808)+t(718)+"=utf-8",hHLvH:t(1278),SwIjs:"none_none",Pdogj:"binary",CPxqb:function(a,r,s,l){return a(r,s,l)},oLaAN:function(a,r){return a===r},hpSBz:t(915),vKmbD:"leMil",lHmNh:function(a,r){return a>r},IGxrP:t(857),qyaOT:function(a,r){return a>r},QBWSq:function(a,r){return a<r},zuGIV:function(a,r){return a-r},kXSVg:function(a,r){return a===r},wbrRv:"qcaIS",Gceic:function(a,r){return a<r},grkrz:function(a,r){return a!==r},odBxV:function(a,r){return a-r},MXJTx:function(a,r,s){return a(r,s)},izVlb:function(a,r,s){return a(r,s)},dbKRx:function(a,r){return a(r)},WqXll:"HAiAH",PvFun:function(a,r){return a>>>r},uEtqr:function(a,r){return a&r},WkgCq:function(a,r){return a===r},RFVJF:t(1355)+"required field: "+t(1251),FHaUs:t(1355)+t(451)+t(646)+t(763),ketaR:function(a){return a()},aMNQJ:function(a,r,s){return a(r,s)},tUsSO:"error",bkprQ:function(a,r,s){return a(r,s)},VAMqL:function(a,r){return a!==r},cRebY:function(a,r,s){return a(r,s)},aEwDJ:function(a,r){return a!==r},tDBYh:function(a,r,s){return a(r,s)},FyANr:function(a,r){return a(r)},FEROG:"HTwXv",sFYJW:function(a,r){return a!==r},WBsOY:function(a,r,s){return a(r,s)},tjMLm:function(a){return a()},Fegdq:function(a,r){return a!==r},oECBM:t(1602),ThhnY:function(a,r,s){return a(r,s)},KgXrR:function(a,r,s){return a(r,s)},kooDJ:function(a,r,s){return a(r,s)},PEuZJ:function(a,r){return a!==r},WTVFs:t(1493),wArBl:function(a,r,s){return a(r,s)},CAGoY:function(a,r){return a!==r},CYfpV:function(a,r){return a!==r},zOqpc:function(a,r,s){return a(r,s)},LmHKP:function(a,r){return a(r)},qilFS:function(a,r){return a(r)},MJqOG:function(a,r,s){return a(r,s)},TUYYm:function(a,r){return a(r)},uSxVg:function(a,r,s){return a(r,s)},ItaXR:function(a,r){return a(r)},ffMud:function(a,r){return a&r},HQvxn:t(1355)+t(451)+" field: "+t(1415),PYLWr:function(a,r){return a===r},wrRpw:t(1355)+t(451)+t(646)+"service",fxEGz:function(a,r){return a===r},WzghU:function(a,r){return a+r},yBrBr:function(a,r){return a(r)},EfklZ:function(a,r,s){return a(r,s)},CHMyT:function(a,r,s){return a(r,s)},AAFse:t(219)+t(1560)+"pe: ",qhmzZ:function(a,r){return a>=r},dqdpH:t(1108),aGOzb:function(a,r,s,l){return a(r,s,l)},TDLmI:t(710),tKEgV:function(a,r){return a===r},aQezx:function(a,r){return a+r},XTCND:"Skip pas"+t(1320),bZbdJ:function(a,r){return a>=r},ccTum:function(a,r){return a+r},eHEOH:function(a,r){return a>r},CKufB:function(a,r){return a*r},RWCVE:function(a,r){return a>r},HFgrW:function(a,r){return a+r},fBfzN:t(729)+t(1320),xeLWi:function(a,r,s){return a(r,s)},jnClp:function(a,r,s){return a(r,s)},koobI:function(a,r){return a&r},driZm:function(a,r,s,l){return a(r,s,l)},fmMfd:function(a,r){return a+r},sjHfA:t(1576),yzyEA:t(1157),dGLLa:function(a,r){return a||r},IRjNg:function(a,r){return a<<r},ZqUET:t(891),gYBkm:function(a,r,s){return a(r,s)},bcKee:function(a,r){return a<r},BcnyW:function(a,r){return a===r},lAMDm:function(a,r){return a&r},taeJa:function(a,r){return a(r)},sEEfh:function(a,r){return a&r},xcaCA:function(a,r){return a+r},zuBBm:function(a,r){return a&r},lRyMr:function(a,r){return a|r},GmdNe:function(a,r){return a&r},sYpmu:function(a,r){return a==r},vbzFN:"fVTBx",AsjJk:function(a,r){return a!==r},IltZd:function(a,r){return a|r},NGGyE:function(a,r){return a!==r},OGSZP:"XGzxg",UqxxF:function(a,r){return a|r},uNnte:function(a,r){return a<<r},gVgga:function(a,r){return a&r},iSZtW:function(a,r){return a&r},OrtVB:function(a,r){return a<=r},iDBVe:t(923),VerLh:t(471),GjyEE:function(a,r){return a(r)},sdbcC:function(a,r){return a>=r},tGAUO:function(a,r){return a+r},VfIWY:function(a,r){return a+r},jiSTA:function(a,r){return a|r},LLavI:function(a,r){return a|r},BBHYs:function(a,r){return a&r},SwbZi:function(a,r){return a&r},zKYBK:function(a,r){return a<<r},LbbKi:function(a,r){return a<r},oYWYC:t(1162),uUEpA:function(a,r){return a<r},uTSMi:function(a,r){return a>=r},hahHW:function(a,r){return a<=r},YaqkL:function(a,r){return a<r},xXkVN:function(a,r){return a-r},PFspP:function(a,r){return a+r},JdQJO:function(a,r,s){return a(r,s)},otLuR:t(1313),FeAan:t(1202),ypSYa:function(a,r){return a>=r},RIQrh:function(a,r){return a-r},jwnJN:function(a,r){return a<<r},adEMh:function(a,r){return a<r},lgvWK:function(a,r){return a|r},FuytA:function(a,r){return a>>r},uBKun:function(a,r){return a<r},dslWL:function(a,r){return a&r},roqrL:function(a,r){return a|r},SqEXq:function(a,r){return a>>r},PjZWY:function(a,r){return a|r},FAzup:function(a,r){return a|r},HhIxl:function(a,r){return a(r)},LOjnJ:function(a,r){return a+r},jMUpt:function(a,r){return a!==r},ltSNt:"Bmzpq",PKOaP:function(a,r,s){return a(r,s)},jneja:function(a,r){return a+r},yGCpv:function(a,r,s){return a(r,s)},PEVFZ:function(a,r){return a|r},WbQCk:function(a,r,s){return a(r,s)},aTTfc:function(a,r){return a<<r},bCAqt:function(a,r){return a&r},giBJO:function(a,r){return a&r},KApfL:function(a,r){return a&r},wzXeY:function(a,r){return a!==r},AMnym:t(1367),eNFav:function(a,r){return a<<r},jWsNV:function(a,r){return a&r},AclYb:t(276),JRbzW:function(a,r){return a<<r},MKesb:"eilKf",rrOgR:function(a,r){return a(r)},qzkdd:function(a,r){return a<<r},PClII:function(a,r){return a&r},fVtvC:function(a,r){return a!==r},sodht:t(858),hnMQy:function(a,r){return a<<r},XoKkV:function(a,r){return a&r},WxrFL:function(a,r){return a(r)},EwtZk:function(a,r){return a(r)},XMUYF:function(a,r){return a<<r},gsljF:function(a,r){return a(r)},wPBZJ:function(a,r){return a&r},GQAhy:function(a,r){return a<<r},mDDSq:function(a,r){return a>>>r},PmtTI:function(a,r){return a<r},zzdRx:function(a,r){return a<r},GuFZA:function(a,r){return a<r},ediMO:function(a,r){return a+r},lOrFm:function(a,r){return a&r},yeGTB:function(a,r){return a|r},zlmCw:function(a,r){return a>>>r},eGtGH:function(a,r){return a>>>r},aKisN:function(a,r){return a!==r},XOFxp:function(a,r){return a>>>r},dyHdo:function(a,r){return a>>>r},xryNf:function(a,r){return a+r},vOUxV:function(a,r){return a!==r},FNLIL:function(a,r){return a>>>r},FxkTb:function(a,r){return a>>>r},Abykm:function(a,r){return a|r},UrBVa:function(a,r){return a|r},pdoOt:function(a,r){return a&r},XKFyC:function(a,r){return a+r},yysZh:function(a,r){return a|r},aRwWU:function(a,r){return a>>>r},jCeee:function(a,r){return a+r},rdggN:function(a,r){return a>>>r},ElADf:function(a,r){return a&r},vdXTY:function(a,r){return a!==r},ghGtH:function(a,r){return a|r},DFRvH:function(a,r){return a(r)},RoBQD:function(a,r){return a|r},lOYeB:function(a,r){return a<<r},QfgVr:function(a,r){return a<<r},TYttu:function(a,r){return a<<r},IHgzF:function(a,r){return a<<r},OzGBR:function(a,r){return a|r},JHtwE:function(a,r){return a<<r},rjBKY:function(a,r){return a|r},LWQWj:function(a,r){return a===r},BZuDY:function(a,r){return a>>>r},xjGcZ:function(a,r){return a|r},qaaxN:function(a,r){return a|r},XIWOq:function(a,r){return a|r},fqbEA:function(a,r){return a<<r},PXtiq:function(a,r){return a|r},TspLW:function(a,r){return a|r},sAjbF:function(a,r){return a&r},xhcCw:function(a,r){return a&r},YKpls:function(a,r){return a>>>r},MIhiI:function(a,r){return a>>>r},OsORS:function(a,r){return a>>>r},WQmsz:function(a,r){return a(r)},PbGPU:function(a,r){return a!==r},rMLsM:function(a,r){return a<=r},BZkld:function(a,r){return a>=r},dZenS:function(a,r){return a+r},PiScI:function(a,r){return a|r},YoKiC:function(a,r){return a%r},SGZDZ:function(a,r){return a|r},WWcBi:function(a,r){return a/r},NuDEe:t(470),BuQUx:function(a,r){return a*r},CmPBV:function(a,r){return a>>>r},IzGPv:function(a,r){return a===r},pslWQ:function(a,r){return a>>>r},QIXTP:function(a,r){return a&r},VcEft:function(a,r){return a>>>r},tvSKZ:function(a,r){return a&r},DGIub:function(a,r){return a+r},akfdq:function(a,r){return a+r},EkSpV:function(a,r){return a<<r},yqZPk:function(a,r){return a|r},cdYES:function(a,r){return a===r},naLnK:function(a,r){return a===r},OEIUJ:function(a,r){return a===r},mvyLd:function(a,r){return a===r},LZZXL:function(a,r){return a===r},ARtFl:t(779),HONuP:function(a,r){return a&r},mzIvO:function(a,r){return a>>>r},xNxcR:function(a,r){return a>>>r},UxqDe:function(a,r){return a&r},BuQCD:function(a,r){return a>>>r},NPvXF:function(a,r){return a&r},XyNoH:function(a,r){return a>>>r},EUXWS:function(a,r){return a&r},hrYuI:function(a,r){return a&r},ixAeT:function(a,r){return a&r},IrDOB:"NATIVE_E"+t(1007),nrvwM:t(952)+t(552),XVyvz:"MESSAGE_"+t(1522),jAqOf:t(498)+"OR",UeNsf:function(a,r){return a>>>r},EtoqA:function(a,r){return a&r},FXLZc:t(1580),Rjuno:"SwSuE",OhyMc:"akSPy",uzjha:function(a,r){return a>=r},sqotw:function(a,r){return a===r},Fhlmf:function(a,r){return a-r},wWwhJ:function(a,r,s){return a(r,s)},fbkMZ:t(298),YJgYg:t(1512),SdzDU:function(a,r){return a+r},XTDXq:function(a,r){return a+r},UBEDk:function(a,r){return a===r},chhpt:t(315),fULEN:function(a,r){return a<r},uhTGE:t(685),HyoNN:function(a,r,s){return a(r,s)},Xzclx:function(a,r,s){return a(r,s)},Spmlh:t(578),Fsoft:t(168),rmHZq:t(1495),UQrZm:t(1170),opbLG:t(926)+"d",gZWef:t(992)+"2",ahfNM:function(a,r){return a!=r},Bipjd:t(482)+t(1459)+t(530)+t(935)+t(1167),CrMDY:t(231),OsPhA:"DbUnM",gQiqj:function(a,r){return a&r},wWQVh:function(a,r){return a===r},aPDwY:function(a,r){return a-r},RJMWT:function(a,r){return a>=r},oXmSv:function(a,r){return a<r},eFvDx:function(a,r){return a&r},KswcW:function(a,r){return a&r},EKTmf:function(a,r){return a>=r},ibxyy:function(a,r){return a-r},kXlEa:function(a,r){return a|r},Xdmab:function(a,r){return a&r},YpNzy:function(a,r){return a>>r},LYIdt:function(a,r){return a<r},gEbqV:function(a,r){return a<r},sNSvO:function(a,r){return a<r},jtcOp:function(a,r){return a===r},dNMnd:function(a,r){return a+r},RcuiG:t(1055)+t(1386),IxTDM:function(a,r){return a&r},sVtko:function(a,r){return a|r},rCbCJ:function(a,r){return a>>r},tDppk:function(a,r){return a+r},RHKdQ:function(a,r){return a>>r},QYrEe:function(a,r){return a|r},yhYKf:function(a,r){return a>>r},SMZvx:function(a,r){return a|r},SDkkt:function(a,r){return a>>r},POfVs:function(a,r){return a|r},CkEPV:function(a,r){return a&r},OclRn:function(a,r){return a>>r},mJYhf:function(a,r){return a|r},FnnEd:function(a,r){return a!==r},ZQKdP:t(1151),OnHZD:t(1376),vPVmN:function(a,r){return a(r)},ujZrr:function(a,r){return a instanceof r},FsGeK:function(a,r){return a!=r},iFmjC:function(a,r){return a instanceof r},TEQCn:"applicat"+t(808),zuWZI:"IkyHO",QWcdE:"boe",ROJiB:t(1112),WxjGa:t(291)+"3",fkZkj:"INsWy",rhbbb:function(a,r){return a+r},MmGKB:t(492),GIXQf:t(693)+"reason",oRInc:function(a,r){return a===r},Msmab:t(375),iJpMr:function(a,r){return a(r)},aNwqv:t(974),KfLAz:t(1300)+t(424),wMqUU:function(a,r){return a+r},ORKnF:"http",jFZpd:"&jscallb"+t(1118)+"tierJSONP",iOMpY:function(a,r){return a!==r},PkTZX:"BLDVb",AZbjm:function(a,r){return a(r)},zwKNp:function(a,r,s){return a(r,s)},ZjIyI:t(613),RFFro:"BLUJB",fnBlO:t(1333),mzzjD:t(307),CVkMo:t(1508),PbsoX:t(243),kCVrM:function(a,r){return a+r},qqTDb:function(a,r){return a|r},yKhAN:function(a,r){return a<<r},Fyxct:t(223),ncgmJ:"sQcqZ",xqtpS:function(a){return a()},dwsqi:t(400)+"ile_name",FMmIG:function(a,r){return a!==r},UKtzq:t(892),HyBEZ:function(a,r){return a!==r},ncVfV:function(a,r){return a!==r},yqmCW:"wgEVT",LOgWg:function(a,r){return a!==r},ezbkU:function(a,r){return a||r},LoeUQ:function(a,r,s){return a(r,s)},YGupf:t(796),rSmvp:t(995),AycTi:function(a,r){return a||r},BygEM:function(a,r){return a||r},iSeJm:function(a,r){return a||r},EsgBl:function(a,r){return a||r},OaIHy:function(a,r){return a!==r},FIcZO:t(1163),lGfuL:"nfQlF",lmbLk:function(a,r){return a||r},qBmiT:function(a,r){return a||r},SLpEd:t(246)+"DB failed",mTYoO:function(a,r,s){return a(r,s)},FhAVI:t(1440)+"id",aXhlm:function(a,r){return a!==r},zSIdM:t(922),mZsue:function(a,r,s){return a(r,s)},eQAUZ:t(834),LReoo:function(a,r){return a(r)},hLFEF:t(1075)+"er_qos",hAVbS:function(a,r,s,l){return a(r,s,l)},NBxEX:t(1075)+"er_qos_ack",XfrwS:function(a,r,s,l){return a(r,s,l)},BdeOQ:function(a,r,s){return a(r,s)},bBlef:"x_frontier_ack_m"+t(1258),RlutU:"need_ack",ckjzu:function(a,r){return a&&r},qFiSm:t(1331),PPjbL:t(1420),QaOGw:function(a,r){return a||r},CAZPH:t(582),XsWGT:t(1140),queYE:function(a,r){return a(r)},VKpey:function(a,r){return a(r)},rNaFd:t(979),gzDVv:function(a,r){return a instanceof r},pknLL:"rMYxq",KRQzA:function(a){return a()},oMVsg:function(a,r){return a>>>r},lMTuV:function(a,r){return a(r)},eIOIE:function(a,r){return a+r},buQxm:function(a,r){return a+r},zdWms:t(624)+t(206)+t(1035),ceAJz:t(1005),iVJiC:" > ",EvEOo:function(a,r){return a>r},eXUwi:t(1107)+t(608)+"e",bTDrh:function(a,r,s,l){return a(r,s,l)},DyCfx:function(a,r){return a+r},JGSzC:t(593)+"4",WhtuM:function(a,r){return a+r},VZoWq:function(a,r){return a<r},eLYge:function(a,r,s,l){return a(r,s,l)},WkINT:function(a,r){return a+r},NXcbm:function(a,r,s,l){return a(r,s,l)},pKLsl:function(a,r){return a|r},vUWMN:function(a,r){return a|r},EtsIP:function(a,r){return a<<r},lokTU:function(a,r){return a<<r},FROeV:function(a,r){return a<<r},uAXTs:function(a,r){return a<<r},oeoRb:t(1433),LpWoy:t(889),iNelF:function(a,r){return a>>>r},vbefB:function(a,r){return a+r},yqaOu:function(a,r){return a+r},VGWGU:function(a,r){return a&r},EKzZs:function(a,r){return a>>>r},jZqSi:function(a,r){return a+r},HDnMI:function(a,r){return a&r},QjIfK:function(a,r){return a>>>r},tpuJO:function(a,r){return a<r},JKXnP:function(a,r){return a>>>r},wqcEM:function(a,r){return a|r},odsfe:function(a,r){return a<<r},ZknWJ:function(a,r){return a|r},hevJt:function(a,r){return a|r},AdwXK:"8|7|2|10"+t(388)+t(701),BZBed:t(1296),FOnXl:function(a,r,s,l){return a(r,s,l)},HzQfj:t(182),VvBpk:t(1397)+t(1037),HFiQi:t(1577),sYTUb:function(a,r){return a(r)},yuCgI:function(a,r){return a<r},DTSbI:function(a,r,s){return a(r,s)},qsHve:function(a,r,s,l){return a(r,s,l)},WROVK:function(a,r){return a+r},cxTlm:function(a,r){return a(r)},wksaP:function(a,r){return a&r},bCFYv:function(a,r){return a&r},uBvxX:function(a,r){return a&r},luZLj:function(a,r){return a===r},HdWmI:t(1557),BqaKQ:t(478)+"_EXIST",PtSuk:function(a,r,s){return a(r,s)},iTsDf:t(812)+t(1031),JSzpy:t(1259),ftIuC:function(a,r,s,l){return a(r,s,l)},prFyK:t(1036),qqpTx:t(1599)+"r",FvhJY:function(a,r){return a|r},dxvvB:"quazs",VlutB:function(a,r,s){return a(r,s)},RHEgI:function(a,r,s){return a(r,s)},UOqVi:function(a,r,s){return a(r,s)},OEVvl:t(1588),ORBPu:function(a,r,s){return a(r,s)},ggyDX:t(1075)+t(837),WVfdy:function(a,r,s){return a(r,s)},aewGL:t(1075)+t(1303),RkrrG:t(984)+t(751)+"e",RvCFy:function(a,r){return a(r)},xoloK:function(a,r,s){return a(r,s)},HfwCb:"x-msg-cu"+t(689)+"ue",dKUqU:function(a,r){return a===r},HBixP:t(1232),mQhjm:function(a){return a()},aZorR:function(a){return a()},ncsPL:function(a,r){return a===r},UNTUf:function(a,r,s){return a(r,s)},KfuKk:t(196),dLJJp:function(a,r){return a(r)},chlQe:function(a){return a()},ONYIA:function(a,r){return a<<r},AKmVn:function(a,r){return a<<r},SJWHp:function(a,r){return a!==r},rizeX:function(a){return a()},xMPOD:function(a,r){return a<r},CNtVJ:function(a,r){return a===r},HwyIb:"jtUTk",HznSo:function(a){return a()},ZGVnq:function(a){return a()},PBSjA:function(a,r,s,l){return a(r,s,l)},iAgjv:function(a,r){return a===r},pwpFw:t(454),OSqwm:t(628)+t(753)+"s",AbgQF:t(1615),jVkpM:function(a,r,s,l){return a(r,s,l)},DZrVV:function(a,r,s){return a(r,s)},yjuLa:t(1189),dXtZv:t(1349),AzTMR:t(1286),krDhY:t(282),GMsQJ:"Xvzjw",fWfgV:function(a,r){return a!==r},pFKSm:function(a,r,s){return a(r,s)},bnFcw:"bye",sWzcT:function(a,r){return a!==r},zBUEE:function(a,r){return a!==r},ysrsx:"heRgO",rsIzB:t(1455),YXZuH:function(a,r,s){return a(r,s)},xPnZs:function(a,r){return a(r)},QwoKm:function(a,r){return a+r},GRhBi:function(a,r){return a!==r},hAaIS:"atBzz",fHgtK:t(1156)+t(310),UqFdu:t(1126),gNDAx:function(a,r){return a==r},GdUEA:t(269)+"rovide w"+t(619)+t(853)+"ket cons"+t(1487)+t(1404)+t(1132),uMVBR:t(267),poDMn:function(a,r){return a===r},fFtRb:t(538),BhnMH:t(1336)+"t",itNtM:"stop imm"+t(468)+" reconnect",ToFFp:t(1193),bdMdp:"pagehide",DWrlM:t(1422),KEWBd:t(1245),oatwL:function(a,r){return a!==r},rjQBf:"sTDmw",cvHFk:t(191),KRcNN:t(417),zeKsy:t(838),RwEXp:"ttwid",jHRId:t(269)+"rovide b"+t(288)+t(925)+t(1269),okdhZ:function(a,r){return a==r},kWXin:t(904),UvWVw:function(a){return a()},ypPWp:function(a,r,s){return a(r,s)},gVelo:"fws_1.0.0",wjBxE:function(a,r,s){return a(r,s)},xErzy:function(a,r,s){return a(r,s)},bDHaC:function(a,r,s){return a(r,s)},tuLOG:function(a,r){return a(r)},HPmCX:function(a,r){return a(r)},tLDDJ:function(a,r){return a(r)},yQOZH:t(1536),pKBkt:function(a,r,s){return a(r,s)},rYehm:t(628)+t(418)+"t",VRLLd:"going aw"+t(327)+t(1336)+t(1011)+t(1426),IUKrD:function(a,r){return a&r},duski:function(a,r){return a!==r},Fmesb:t(250),oLEYR:function(a,r){return a!==r},ADNuD:t(1174),qbmlS:t(1524)+"0",zNMwI:t(1222)+"1",qpAYz:t(1400),bwaGU:function(a,r,s){return a(r,s)},Ftskq:function(a,r){return a!==r},jzPsL:t(430),kijeB:function(a,r){return a!==r},JIzla:t(709),tkECa:"ack",LGaNb:function(a,r){return a===r},pDypK:function(a,r,s,l){return a(r,s,l)},CTqpA:function(a,r){return a===r},WuLEN:"QlkCe",aKxCs:function(a,r){return a===r},iPYDT:"kIRrY",EeTqY:"0|1|5|7|4|6|3|2",SjACM:t(1545)+t(1247)+t(652),TJXSH:t(1545)+t(333)+t(1446)+t(247)+"ed",pfvUw:t(269)+t(783)+t(1246)+"ata, dat"+t(230)+t(540)+"ng or an arraybu"+t(1252),EBkRL:t(433),erPxT:function(a,r){return a!=r},sYlxs:function(a,r){return a(r)},ExtEe:function(a,r){return a||r},DbOuO:function(a,r){return a===r},WbOTR:function(a,r){return a<r},OlSLV:"enqueue",hHQIu:function(a,r){return a===r},zTFIA:"eUSsM",Msezw:function(a,r){return a!==r},KNEoo:t(435)+"econnect"+t(800),AiDyO:function(a,r){return a<<r},TvtOM:"timeout",MTucG:function(a,r){return a!==r},dmzno:"iCeKz",hxVld:t(516),vLuZT:function(a,r){return a*r},nxUzc:"Window",cYkKL:function(a,r){return a===r},kpCIr:function(a,r){return a===r},COIlR:t(1267),VEwzs:"DedicatedWorkerG"+t(941)+"pe",ZNEmf:function(a,r){return a!=r},VuxVw:function(a,r){return a===r},zdmEb:function(a,r){return a==r},XrpkJ:function(a,r){return a!=r},RyqIg:function(a,r){return a===r},LPRRZ:t(200)+"orkerGlo"+t(560),BNkud:function(a,r){return a!=r},LJWdP:function(a,r,s){return a(r,s)},YPMtH:t(1255)+t(283)};Ut.r(Oe),Ut.d(Oe,{FWS:()=>qg,CustomErrorEvent:()=>_l,createCloseEvent:()=>wt,ReconnectEvent:()=>wl,createErrorEvent:()=>lt,decodedFrame:()=>sn,createOpenEvent:()=>Il,CustomCloseEvent:()=>yl,createReconnectEvent:()=>Aa,FrontierMessageEvent:()=>El,encodeFrame:()=>Ht,createMessageEvent:()=>Sl,OpenEvent:()=>vl,ErrorCode:()=>an,Event:()=>cr,MessageEvent:()=>bl});let n="";function i(a=""){let r=t,s="02",l=""+Date[r(778)](),h=n||(n=e[r(426)](f,a)),m=Math[r(715)]()[r(616)](16)[r(881)](-6);return e.mNvgN(e.mNvgN(s+l,h),m)}function o(){let a=t;return e.reLLR(1e4,Date[a(778)]())+Math[a(323)](e[a(1324)](1e4,Math[a(715)]()))}function c(a){let r=t;return e[r(738)](e[r(961)](Array,8)[r(1121)]("0"),e[r(469)](parseInt,a,10)[r(616)](2)).slice(-8)}function d(a){let r=t;if(e[r(657)]!==e[r(657)])_0x13a0f3=_0xa8b253[e[r(792)](e.mNvgN(_0x38cfb0,_0x20121d),1)],_0x44b03a=_0x5c86a7[e[r(738)](e[r(738)](_0xcad915,_0x444040),2)],e[r(831)](e[r(851)](e[r(1535)](_0x3283a2,e.bFaBO(_0x1dc4e7,8)),49344),32896)?_0x4aa835+=_0xd73356:(_0x2925d9=e.muXCf(e[r(843)](15,_0x383472)<<12,e.UJmTa(e.eRqmp(63,_0x4d7939),6))|e[r(843)](63,_0x5a6f99),_0x8df4c9<2048||_0xa6248>=55296&&e[r(722)](_0x24a310,57343)?_0x3a6e05+=_0xd40aaf:(_0x5e04c8+=e[r(961)](_0x574509,_0x2170ee),_0x2c47d7+=2));else return e[r(754)](e.WWHYd(Array,4)[r(1121)]("0"),e.HCDWi(parseInt,a,2)[r(616)](16)).slice(-4)}function u(a){let r=t,s=a[r(639)](/\./)[r(199)](m=>c(m)),l=[];return l[0]=d(s[0]+s[1]),l[1]=e[r(705)](d,e[r(738)](s[2],s[3])),[e[r(502)],e[r(502)],e[r(502)],e[r(502)],e.InuTE,e[r(1e3)],l[0],l[1]][r(1121)]("")}function f(a){let r=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}/[r(1181)](a),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(1181)](a);return s?u(a):l?e[r(705)](x,a):e.VekSZ}function x(a){let r=t;if(e[r(580)](e[r(1622)],e.vKmbD))return this[r(1427)+r(1611)]?.[r(404)+r(704)+"ntTriesC"+r(1328)]()||0;{let l="",h=[],m=0,b=0,v=!0,g=r(1210);if(e[r(1249)](a[r(861)]("::"),-1))if(e.IGxrP===e.IGxrP){let C=a[r(639)]("::");for(let B=0;B<C.length;B++){let G=C[B];if(e.qyaOT(G.indexOf(":"),0)){let Z=G[r(639)](":");v&&(m=Z[r(368)]),b+=Z[r(368)];for(let K=0;e.QBWSq(K,Z[r(368)]);K++)if(Z[K][r(368)]!==4){let ge=g.substring(0,e.zuGIV(4,Z[K][r(368)])),he=ge.concat(Z[K]);h.push(he)}else h[r(612)](Z[K]);v=!1}else if(e[r(220)](e[r(890)],e[r(890)])){if(G[r(368)]!==4){let Z=g.substring(0,4-G[r(368)]),K=Z[r(534)](G);h[r(612)](K)}else h[r(612)](G);v&&(m+=1),b+=1,v=!1}else for(var s in _0x5ad1e0)_0x53d810.o(_0x5e312e,s)&&!_0x54fc28.o(_0x482e81,s)&&_0x871a1d[r(281)+r(1368)](_0x54346f,s,{enumerable:!0,get:_0x26f53d[s]})}let L="";for(let B=0;B<e[r(743)](8,b);B++)L=L[r(534)](g);for(let B=0;e[r(1542)](B,h[r(368)]);B++)B===m?(l=l[r(534)](L),l=l[r(534)](h[B])):l=l.concat(h[B]);return l}else{let C=e[r(257)](this[r(1492)]["payloadE"+r(1136)],_0x38f8f2)?{force:!!this[r(1492)][r(1442)+r(1136)][r(1344)],encoding:this[r(1492)][r(1442)+r(1136)][r(1096)]?this[r(1492)][r(1442)+r(1136)][r(1096)][r(732)](/\s/g,"")[r(358)+r(1500)]():""}:{force:!1,encoding:this[r(1492)]["payloadE"+r(1136)]?this[r(1492)][r(1442)+"ncoding"][r(732)](/\s/g,"")[r(358)+r(1500)]():""},L=_0x54aed1[r(1442)+r(1136)]?_0x3ba089[r(1442)+"ncoding"][r(732)](/\s/g,"")[r(358)+r(1500)]():"",B=this._options["payloadT"+r(351)]instanceof _0x4cd181?{force:!!this[r(1492)][r(446)+r(351)][r(1344)],type:this[r(1492)]["payloadT"+r(351)].type?this[r(1492)][r(446)+r(351)][r(1216)][r(732)](/\s/g,"")["toLowerC"+r(1500)]():""}:{force:!1,type:this[r(1492)][r(446)+r(351)]?this[r(1492)]["payloadT"+r(351)][r(732)](/\s/g,"")["toLowerC"+r(1500)]():""},G=_0x2034b6["payloadT"+r(351)]?_0x234ebe[r(446)+r(351)][r(732)](/\s/g,"")["toLowerC"+r(1500)]():"",Z=B.force?B[r(1216)]:G||B[r(1216)],K=C[r(1344)]?C.encoding:L||C.encoding,ge=[e[r(564)],r(898)+r(808),e[r(863)],e[r(1538)]],he=[e[r(279)],e.Pdogj];this[r(1492)][r(731)+"ansformTextPayload"]&&ge.includes(Z)&&(!K||he.includes(K))?_0x35397c[r(607)+r(565)]=e[r(1092)](_0x5beb56,_0x40fae9[r(1019)],0,_0x2678e9.payload[r(408)+"th"]):_0x1317bd[r(607)+r(565)]=""}{let C=a.split(":");for(let L=0;e[r(1528)](L,C.length);L++){let B=C[L];if(e[r(645)](4,C[L][r(368)])){let G=g[r(590)+"g"](0,e[r(768)](4,C[L][r(368)])),Z=G[r(534)](B);l=l[r(534)](Z)}else l=l[r(534)](B)}return l}}}function p(a,r){let s=t,l=a.key;l!==void 0&&(e.MXJTx(we,r,10),e[s(486)](U,r,l));let h=a[s(763)];e.jWAjv(void 0,h)&&(e.HCDWi(we,r,18),e[s(1389)](U,r,h))}function w(a){let r=t,s={};e:for(;!e[r(501)](V,a);){if(e[r(645)](e[r(1233)],e[r(1233)]))return!!this[r(1111)];{let l=e.dbKRx(ue,a);switch(e[r(1211)](l,3)){case 0:break e;case 1:s.key=e[r(469)](D,a,ue(a));break;case 2:s[r(763)]=D(a,e.zYmSM(ue,a));break;default:T(a,e[r(846)](7,l))}}}if(e[r(1104)](void 0,s[r(1251)]))throw new Error(e[r(544)]);if(s.value===void 0)throw new Error(e.FHaUs);return s}function S(a){let r=t,s=e[r(1605)](R);return e[r(1125)](_,a,s),M(s)}function _(a,r){let s=t,l=a[s(1415)];e[s(600)](void 0,l)&&(e[s(1125)](we,r,8),e[s(681)](mt,r,l));let h=a[s(1413)];e[s(226)](void 0,h)&&(we(r,16),mt(r,h));let m=a[s(1296)];m!==void 0&&(e[s(179)](we,r,24),e[s(272)](mt,r,e[s(924)](P,m)));let b=a[s(1364)];e[s(600)](void 0,b)&&(e[s(220)](e[s(943)],s(983))?(e.bkprQ(we,r,32),e.cRebY(mt,r,P(b))):this.emit(e[s(911)],e[s(326)](_0x36c920,e.tUsSO,{message:this[s(1554)+"rrorMess"+s(535)](_0x3420d5)})));let v=a[s(521)];if(e[s(772)](void 0,v))for(let ge of v){e.WBsOY(we,r,42);let he=e[s(1451)](R);e[s(179)](p,ge,he),e[s(242)](we,r,he[s(1318)]),e[s(179)](j,r,he),e[s(705)](O,he)}let g=a.payloadEncoding;if(e[s(1158)](void 0,g)){if(e[s(831)](e[s(1283)],e[s(1283)]))return;we(r,50),e[s(793)](U,r,g)}let C=a[s(446)+"ype"];e[s(772)](void 0,C)&&(e[s(1421)](we,r,58),e[s(951)](U,r,C));let L=a[s(1019)];if(e[s(1407)](void 0,L))if(e[s(600)](e[s(273)],e[s(273)])){let ge=_0x3322ad[s(973)],he=_0x5796d6[s(1318)];return e.kXSVg(ge[s(368)],he)?ge:ge[s(1194)](0,he)}else e[s(1125)](we,r,66),e.IXaYx(we,r,L[s(368)]),e[s(212)](ae,r,L);let B=a.LogIDNew;e[s(467)](void 0,B)&&(we(r,74),e[s(212)](U,r,B));let G=a[s(563)+"ming"];e[s(831)](void 0,G)&&(e[s(1421)](we,r,82),e[s(681)](U,r,G));let Z=a[s(197)];e.CYfpV(void 0,Z)&&(we(r,90),U(r,Z));let K=a[s(1431)+"e"];K!==void 0&&(e[s(1018)](we,r,96),e.bkprQ(mt,r,e[s(426)](P,K)))}function E(a){let r=t;return r(1265)!=="XXlfE"?vNGdOO[r(1304)](_0x1b7992,_0x3f9d42[r(790)](vNGdOO[r(1304)](_0x4c1876,this),_0x299331)):e[r(961)](I,F(a))}function I(a){let r=t,s={};e:for(;!e[r(426)](V,a);){let l=e[r(1511)](ue,a);switch(e[r(1211)](l,3)){case 0:break e;case 1:s.SeqID=e[r(1441)](At,a,!0);break;case 2:s[r(1413)]=At(a,!0);break;case 3:s[r(1296)]=e.zYmSM(ue,a);break;case 4:s[r(1364)]=e.TUYYm(ue,a);break;case 5:{let h=A(a);(s.headers||(s.headers=[]))[r(612)](e[r(705)](w,a)),a[r(1318)]=h;break}case 6:s["payloadE"+r(1136)]=e[r(486)](D,a,e.TUYYm(ue,a));break;case 7:s[r(446)+r(351)]=e[r(222)](D,a,e[r(622)](ue,a));break;case 8:s[r(1019)]=e.MJqOG(ne,a,ue(a));break;case 9:s[r(198)]=e[r(212)](D,a,e[r(501)](ue,a));break;case 10:s[r(563)+r(505)]=e.wArBl(D,a,e[r(1511)](ue,a));break;case 11:s.msgID=e.ThhnY(D,a,e[r(705)](ue,a));break;case 12:s[r(1431)+"e"]=ue(a);break;default:e.HCDWi(T,a,e.ffMud(7,l))}}if(e[r(220)](void 0,s.SeqID))throw new Error(e[r(292)]);if(e[r(520)](void 0,s[r(1413)]))throw new Error(r(1355)+r(451)+" field: "+r(1413));if(e[r(520)](void 0,s[r(1296)]))throw new Error(e[r(744)]);if(e[r(758)](void 0,s[r(1364)]))throw new Error(r(1355)+r(451)+r(646)+r(1364));return s}function A(a){let r=t,s=e.FyANr(ue,a),l=a.limit;return a.limit=e[r(390)](a.offset,s),l}function T(a,r){let s=t;switch(r){case 0:for(;e[s(843)](128,e[s(343)](re,a)););break;case 2:e[s(1568)](Y,a,ue(a));break;case 5:e.CHMyT(Y,a,4);break;case 1:e[s(951)](Y,a,8);break;default:throw new Error(e.uEFSQ(e.AAFse,r))}}function P(a){let r=t;return a|=0,{low:a,high:a>>31,unsigned:e[r(1373)](a,0)}}let y=[];function R(){let a=t;if(e[a(226)](a(1108),e[a(964)]))return!!this[a(1111)];{let r=y[a(1466)]();return r?(r[a(1085)]=r.limit=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}}function O(a){y[t(612)](a)}function F(a){let r=t;if(e.TDLmI!==e[r(1465)])for(var s in _0x5dbe6f)vNGdOO[r(931)](_0x59f87a,_0x4d6fad,s,{get:_0x47614a[s],enumerable:!0});else return{bytes:a,offset:0,limit:a[r(368)]}}function M(a){let r=t,s=a[r(973)],l=a[r(1318)];return e[r(719)](s[r(368)],l)?s:s.subarray(0,l)}function Y(a,r){let s=t;if(e[s(630)](a[s(1085)],r)>a.limit)throw new Error(e[s(217)]);a.offset+=r}function V(a){let r=t;return e[r(1090)](a[r(1085)],a.limit)}function se(a,r){let s=t,l=a[s(973)],h=a.offset,m=a.limit,b=e[s(311)](h,r);if(e[s(1139)](b,l.length)){let v=new Uint8Array(e[s(1142)](2,b));v[s(770)](l),a[s(973)]=v}return a.offset=b,e[s(1139)](b,m)&&(a[s(1318)]=b),h}function Q(a,r){let s=t,l=a[s(1085)];if(e[s(1609)](e[s(237)](l,r),a[s(1318)]))throw new Error(e.fBfzN);return a[s(1085)]+=r,l}function ne(a,r){let s=t,l=e[s(329)](Q,a,r);return a[s(973)][s(1194)](l,l+r)}function ae(a,r){let s=t,l=e[s(387)](se,a,r[s(368)]);a[s(973)][s(770)](r,l)}function D(a,r){let s=t,l={euLcA:function(h,m){return e[$(617)](h,m)},cYGtO:function(h,m,b,v){return e[$(875)](h,m,b,v)},uDcKB:function(h,m){return e[$(1517)](h,m)},rFhgb:e[s(570)],Ciclh:e[s(1584)],FVOOX:function(h,m){return e[s(1071)](h,m)},tIBvm:"ack_code",VJGUV:function(h,m){return e.muXCf(h,m)},QkHTM:function(h,m){return h<<m},meLAm:function(h,m){return e[s(1164)](h,m)},xIuCx:function(h,m){return e.PvFun(h,m)},IGDZU:function(h,m){return e[s(1535)](h,m)},aMqMJ:function(h,m){return h|m},hJjBz:function(h,m){return e.IRjNg(h,m)}};if(e.aEwDJ(s(891),e[s(236)]))_0x1a0d8c(_0x38a2ce[s(253)]),vNGdOO[s(1605)](_0x29c44d);else{let h=e[s(848)](Q,a,r),m=String[s(489)+s(1361)],b=a[s(973)],v="\uFFFD",g="";for(let C=0;e[s(286)](C,r);C++){let L=b[e[s(738)](C,h)],B,G,Z,K;if(e[s(651)](e.lAMDm(128,L),0))g+=e[s(872)](m,L);else if(e[s(1072)](224,L)===192)e[s(1090)](C+1,r)?g+=v:(B=b[e.xcaCA(C+h,1)],e[s(1354)](192,B)!==128?g+=v:(K=e[s(1049)](e[s(554)](e[s(1250)](31,L),6),e[s(1268)](63,B)),K<128?g+=v:(g+=m(K),C++)));else if(e[s(1467)](e.koobI(240,L),224))if(e[s(1373)](C+2,r))g+=v;else if(e.jWAjv(e[s(676)],e.vbzFN)){let ge=l[s(344)](255,_0x2ebd87);l[s(683)](_0x57ae36,ge,_0x2c8596,l[s(742)](_0x3eede3,_0x3e83bb)),_0x3d3ef7>>>=8,_0x5b009d--}else if(B=b[e.WzghU(C,h)+1],G=b[e[s(738)](e[s(1517)](C,h),2)],e[s(679)](e.eRqmp(e.IltZd(B,G<<8),49344),32896))g+=v;else if(e[s(218)](e.OGSZP,e.OGSZP)){let{SeqID:ge,LogID:he,service:ut,LogIDNew:ai,method:gs}=_0x2c4b9c[s(1495)];this._sendAck({SeqID:ge,LogID:he,LogIDNew:ai,service:ut,method:gs,headers:[{key:l[s(1623)],value:"1"},{key:l[s(1196)],value:l[s(1081)](ai,"")},{key:l[s(416)],value:"0"}]})}else if(K=e.UqxxF(e[s(554)](e[s(883)](15,L),12),e[s(640)](e[s(1122)](63,B),6))|e.iSZtW(63,G),K<2048||K>=55296&&e[s(1408)](K,57343))g+=v;else if(e[s(1271)]!==e[s(985)])g+=e[s(673)](m,K),C+=2;else return _0x51900d===_0x2ce28d?_0x401094:new _0x5039a1(l[s(1575)](l[s(1575)](_0x4e8ef0.call(_0x487d14,0),_0x478a50[s(1382)](_0x1709da,1)<<8)|l.QkHTM(_0x2f7736[s(1382)](_0x3861aa,2),16),l[s(1339)](_0x3b2d94[s(1382)](_0x58cc73,3),24))>>>0,l[s(697)](l.IGDZU(l.aMqMJ(_0x2ecfd1[s(1382)](_0x2e387f,4),l.hJjBz(_0x5ad425.call(_0x4824ed,5),8))|l[s(506)](_0x4b7989[s(1382)](_0x12837c,6),16),_0x56723c[s(1382)](_0x332294,7)<<24),0),!0);else(248&L)==240?e[s(473)](C+3,r)?g+=v:(B=b[e[s(792)](e[s(1621)](C,h),1)],G=b[e[s(738)](C,h)+2],Z=b[e[s(630)](e.VfIWY(C,h),3)],(e[s(1322)](e[s(1322)](B,G<<8),e[s(640)](Z,16))&12632256)!==8421504?g+=v:(K=e.LLavI(e[s(1322)](e.bFaBO(e[s(359)](7,L),18),e[s(1289)](63,B)<<12),e[s(224)](e[s(1122)](63,G),6))|63&Z,e[s(641)](K,65536)||e[s(1139)](K,1114111)?g+=v:(K-=65536,g+=e[s(486)](m,(K>>10)+55296,e[s(846)](1023,K)+56320),C+=3))):g+=v}return g}}function U(a,r){let s=t,l=r[s(368)],h=0;for(let v=0;e[s(373)](v,l);v++){let g=r.charCodeAt(v);e[s(1014)](g,55296)&&e[s(691)](g,56319)&&e.YaqkL(e[s(237)](v,1),l)&&(g=e.xXkVN(e[s(312)](g<<10,r[s(1519)+"At"](++v)),56613888)),h+=e.Gceic(g,128)?1:g<2048?2:g<65536?3:4}e[s(272)](we,a,h);let m=e[s(533)](se,a,h),b=a[s(973)];for(let v=0;v<l;v++)if(e[s(467)](e.otLuR,e[s(330)])){let g=r[s(1519)+"At"](v);e.ypSYa(g,55296)&&e[s(691)](g,56319)&&e[s(286)](e.uEFSQ(v,1),l)&&(g=e.RIQrh(e.jwnJN(g,10)+r[s(1519)+"At"](++v),56613888)),e.adEMh(g,128)?b[m++]=g:(g<2048?b[m++]=e[s(859)](e[s(883)](e[s(174)](g,6),31),192):(e[s(1553)](g,65536)?b[m++]=e.lRyMr(e.dslWL(g>>12,15),224):(b[m++]=e[s(174)](g,18)&7|240,b[m++]=e[s(1464)](e[s(761)](g,12)&63,128)),b[m++]=e[s(1398)](e.gVgga(g>>6,63),128)),b[m++]=e[s(621)](e.eRqmp(63,g),128))}else this[s(1473)]&&this[s(1473)][s(801)](_0x209c7e),this[s(917)](e[s(1359)],_0x32f498)}function j(a,r){let s=t;if(e[s(819)](e[s(1555)],e[s(1555)])){let l=e[s(320)](_0xa82ce1,_0x313275),h=_0x5b7264.limit;return _0x3857cb.limit=e.LOjnJ(_0x498c14[s(1085)],l),h}else{let l=e[s(869)](se,a,r[s(1318)]),h=a[s(973)],m=r[s(973)];for(let b=0,v=r[s(1318)];e.uBKun(b,v);b++)h[e[s(856)](b,l)]=m[b]}}function re(a){return a[t(973)][Q(a,1)]}function Ye(a,r){let s=t,l=se(a,1);a[s(973)][l]=r}function ue(a){let r=t,s=0,l=0,h;do h=e[r(705)](re,a),s<32&&(l|=e[r(640)](e.gVgga(127,h),s)),s+=7;while(e[r(846)](128,h));return l}function we(a,r){let s=t;for(r>>>=0;e[s(656)](r,128);)e.yGCpv(Ye,a,e[s(959)](e[s(359)](127,r),128)),r>>>=7;e[s(972)](Ye,a,r)}function At(a,r){let s=t,l={eEMVb:function(g,C){return e[$(1535)](g,C)},ANRbx:function(g,C){return e[$(1049)](g,C)},umryX:function(g,C){return e[$(650)](g,C)},kZYLU:function(g,C){return e[$(1583)](g,C)},EDGkU:function(g,C){return e.wzXMo(g,C)},yJJLk:function(g,C){return g&C},yKxGe:function(g,C){return e[$(1289)](g,C)},XOAyY:function(g,C){return g+C},Zmmrk:function(g,C){return e[$(359)](g,C)},XqgTY:function(g,C){return e[$(1071)](g,C)}},h=0,m=0,b=0,v;if(v=re(a),h=e[s(1562)](127,v),e[s(1342)](128,v)){if(e[s(413)](e.AMnym,e[s(1041)]))this["_message"+s(186)][s(254)](),this[s(209)+s(186)][s(612)](_0x1f27b1);else if(v=re(a),h|=e.eNFav(127&v,7),e[s(1564)](128,v))if(s(1012)!==e[s(1282)]){if(v=re(a),h|=e[s(1362)](e[s(867)](127,v),14),e[s(1289)](128,v)){if(e.kXSVg(s(385),e[s(1548)]))_0x5cbcc9.d=(g,C)=>{let L=s;for(var B in C)_0x3bec98.o(C,B)&&!_0xa84e59.o(g,B)&&_0xa65a69[L(281)+"operty"](g,B,{enumerable:!0,get:C[B]})};else if(v=e[s(384)](re,a),h|=e[s(588)](e.bCAqt(127,v),21),128&v&&(v=e[s(1304)](re,a),m=127&v,e[s(932)](128,v)))if(e.fVtvC(e[s(839)],e.sodht)){let g=l[s(1161)](l.ANRbx(l[s(1073)](l.kZYLU(7,_0x247821),18)|l[s(1073)](l[s(1032)](63,_0x241e6c[_0xa3b5c6++]),12),l[s(1073)](l[s(747)](63,_0x127131[_0x256f77++]),6)),l[s(1295)](63,_0x110110[_0x36f749++]))-65536;_0x379675+=_0x43d9a8["fromChar"+s(1361)](l[s(1103)](55296,g>>10)),_0xa35883+=_0x23ff1b["fromChar"+s(1361)](l[s(1103)](56320,l[s(978)](1023,g)))}else v=re(a),m|=e[s(561)](e.XoKkV(127,v),7),128&v&&(v=e[s(1200)](re,a),m|=(127&v)<<14,e[s(1562)](128,v)&&(v=e[s(371)](re,a),m|=e[s(1502)](e[s(846)](127,v),21),e[s(1562)](128,v)&&(v=e.gsljF(re,a),b=e[s(1583)](127,v),e[s(1204)](128,v)&&(v=e.FyANr(re,a),b|=e[s(175)](e[s(846)](127,v),7)))))}}else{let g=this._qosDB[s(748)](this[s(319)]),C=_0x4fd6aa[s(1371)](l.XqgTY(g,"{}"));return C[_0x2345cf||_0x28d521[this[s(752)]]]=_0x4457fb,this[s(1111)][s(1351)](this[s(319)],_0x3e3869[s(1044)+"y"](C)),_0x14f48f||_0xf3cf83[this[s(752)]]}}return{low:h|e.GQAhy(m,28),high:e[s(1211)](m,4)|b<<24,unsigned:r}}function mt(a,r){let s=t,l=e.mDDSq(r[s(239)],0),h=e[s(897)](e[s(567)](r[s(239)],28),e[s(650)](r[s(830)],4))>>>0,m=e.mDDSq(r[s(830)],24),b=e.WkgCq(0,m)?e[s(580)](0,h)?l<16384?e[s(1528)](l,128)?1:2:e[s(1392)](l,2097152)?3:4:e.zzdRx(h,16384)?e[s(1542)](h,128)?5:6:e[s(379)](h,2097152)?7:8:e[s(286)](m,128)?9:10,v=e[s(681)](se,a,b),g=a[s(973)];switch(b){case 10:g[e[s(792)](v,9)]=e[s(1564)](e[s(567)](m,7),1);case 9:g[e[s(1176)](v,8)]=e[s(645)](9,b)?128|m:e[s(1411)](127,m);case 8:g[v+7]=b!==8?e[s(497)](e[s(208)](h,21),128):e[s(1342)](e[s(1152)](h,21),127);case 7:g[e[s(792)](v,6)]=e[s(620)](7,b)?e.XOFxp(h,14)|128:e.iSZtW(e[s(955)](h,14),127);case 6:g[e[s(865)](v,5)]=e[s(716)](6,b)?e[s(313)](h,7)|128:e.FxkTb(h,7)&127;case 5:g[e[s(792)](v,4)]=e[s(620)](5,b)?e.Abykm(128,h):e[s(846)](127,h);case 4:g[e[s(630)](v,3)]=b!==4?e[s(1021)](e.dyHdo(l,21),128):e[s(1166)](e[s(208)](l,21),127);case 3:g[e[s(1308)](v,2)]=b!==3?e[s(1499)](e[s(955)](l,14),128):e[s(1072)](e[s(1513)](l,14),127);case 2:g[e[s(1600)](v,1)]=e[s(467)](2,b)?e[s(480)](l,7)|128:e[s(442)](l>>>7,127);case 1:g[v]=e[s(1483)](1,b)?e[s(1001)](128,l):e.InPKc(127,l)}}function sn(a){return E(a)}function Ht(a){return e[t(1474)](S,a)}let on=65536,ii=e[t(913)],be=e[t(893)](on,on),Ce=e[t(1048)](be,be),ar=Ce/2,Me=String.prototype[t(1519)+"At"];class fe{constructor(r,s,l){let h=t;this.isLong=!0,this[h(239)]=e[h(432)](0,r),this[h(830)]=0|s,this[h(1523)]=!!l}static isLong(r){return r&&r[t(1191)]===!0}static[t(1480)](r,s,l){return new fe(r,s,l)}static[t(542)+"s"](r,s,l){let h=t,m={ppfgL:function(b,v){return b<v},yVEjP:function(b,v){return b!==v},hewNt:function(b,v){return e.RIQrh(b,v)}};if(e.vdXTY("tPEfw",h(1088)))return l?fe[h(542)+h(1148)](r,s):fe[h(542)+h(1556)](r,s);{let b=_0x3f4154[h(639)](":");for(let v=0;ApfHIa[h(603)](v,b[h(368)]);v++){let g=b[v];if(ApfHIa[h(1358)](4,b[v].length)){let C=_0x1ff633[h(590)+"g"](0,ApfHIa[h(776)](4,b[v][h(368)])),L=C[h(534)](g);_0x44142c=_0x49c547[h(534)](L)}else _0x5d10c7=_0x468fc6[h(534)](g)}return _0x51b320}}static["fromByte"+t(1148)](r,s){let l=t;return new fe(e[l(1182)](e.roqrL(e.IltZd(r[0],r[1]<<8),e[l(615)](r[2],16)),e[l(880)](r[3],24)),e[l(959)](r[4]|r[5]<<8,e[l(1171)](r[6],16))|e[l(266)](r[7],24),s)}static[t(542)+t(1556)](r,s){let l=t;return new fe(e[l(614)](e[l(1179)](e.JHtwE(r[4],24),e[l(224)](r[5],16)),r[6]<<8)|r[7],e[l(546)](e.yeGTB(e.muXCf(e[l(266)](r[0],24),e[l(224)](r[1],16)),r[2]<<8),r[3]),s)}static fromHash(r){let s=t;return e[s(336)](r,ii)?ml:new fe(e.BZuDY(e[s(601)](e.qaaxN(e.XIWOq(Me[s(1382)](r,0),Me[s(1382)](r,1)<<8),e[s(1567)](Me[s(1382)](r,2),16)),Me[s(1382)](r,3)<<24),0),e[s(629)](e.PXtiq(e.TspLW(Me[s(1382)](r,4),e[s(1171)](Me[s(1382)](r,5),8)),e[s(749)](Me.call(r,6),16))|Me.call(r,7)<<24,0),!0)}[t(369)](){let r=t;return String[r(489)+r(1361)](255&this[r(239)],e[r(1128)](this[r(239)]>>>8,255),e[r(1559)](this[r(239)]>>>16,255),e[r(313)](this.low,24),e[r(1564)](255,this[r(830)]),e[r(682)](e.YKpls(this[r(830)],8),255),e[r(1342)](e[r(1372)](this[r(830)],16),255),e.OsORS(this[r(830)],24))}static[t(762)+"er"](r,s=!0){let l=t,h={adHnt:function(m,b,v){return m(b,v)},tzpgJ:function(m,b,v){return m(b,v)},KpNOf:function(m,b){return e.WQmsz(m,b)}};if(isNaN(r))return s?tg:ml;if(s)if(e[l(447)]("hJbCY",l(806))){if(r>=Ce)return rg}else VBLCOu[l(1099)](_0x26ff1b,_0x7834bb,32),VBLCOu[l(1243)](_0x205c02,_0x5607c0,VBLCOu.KpNOf(_0x3410f6,_0x4d1c42));else{if(e[l(409)](r,-ar))return ig;if(e.BZkld(e[l(1585)](r,1),ar))return ng}return fe[l(1480)](e[l(338)](e[l(949)](r,be),0),e[l(901)](e[l(940)](r,be),0),s)}[t(864)](){let r=t;return e[r(1104)](r(470),e[r(1311)])?this[r(1523)]?e.BuQUx(e.MIhiI(this[r(830)],0),be)+e[r(1231)](this.low,0):e.dZenS(this[r(830)]*be,this[r(239)]>>>0):this[r(1111)]?.[r(1484)](_0x12fd92)}[t(274)](){let r=t;return e[r(907)](0,this[r(830)])&&e.WkgCq(0,this[r(239)])}[t(1260)](r){let s=t;fe[s(1191)](r)||(r=fe.fromNumber(r));let l=e.pslWQ(this.high,16),h=65535&this.high,m=e[s(1418)](this[s(239)],16),b=e.QIXTP(65535,this[s(239)]),v=e[s(240)](r[s(830)],16),g=e[s(895)](65535,r[s(830)]),C=e[s(1231)](r[s(239)],16),L=e[s(1072)](65535,r.low),B=0,G=0,Z=0,K=0;return K+=e[s(1621)](b,L),Z+=K>>>16,K&=65535,Z+=m+C,G+=e[s(1453)](Z,16),Z&=65535,G+=e[s(512)](h,g),B+=e[s(629)](G,16),G&=65535,B+=e[s(577)](l,v),B&=65535,fe[s(1480)](e.EkSpV(Z,16)|K,e[s(663)](B<<16,G),this.unsigned)}[t(860)](r){let s=t;return fe[s(1191)](r)||(r=fe.fromNumber(r)),e[s(413)](this.unsigned,r.unsigned)&&e[s(1213)](this[s(830)]>>>31,1)&&e[s(1272)](e[s(1418)](r.high,31),1)?!1:e[s(1272)](this[s(830)],r[s(830)])&&this.low===r[s(239)]}[t(354)](){let r=t;if(e[r(1491)](r(820),r(1145)))this[r(213)]&&this[r(213)][r(578)]({code:_0x4875c9,reason:_0x5c52a8});else return e.mvyLd(-1,this[r(239)])&&e[r(1272)](-1,this.high)?fe.fromBits(0,0,this[r(1523)]):e[r(1263)](-1,this[r(239)])?fe[r(1480)](0,e.DGIub(this[r(830)],1),this.unsigned):fe[r(1480)](this[r(239)]+1,this.high,this[r(1523)])}[t(944)](r){let s=t;if(e.fVtvC(s(504),s(504)))_0x2741c7=e.ARtFl,_0xf8efa4=_0x13493d[s(732)](/(^http)((?:[s]*:\/\/))/,""),_0x43a3e0=/(^ws)((?:[s]*:\/\/))/.test(_0x1da9cf)?_0x5a2d66:""+_0x1e1e9e+_0x22ade9;else return r?this.toBytesLE():this[s(1326)+"E"]()}[t(1436)+"E"](){let r=t,s=this.high,l=this[r(239)];return[255&l,e[r(623)](e[r(900)](l,8),255),l>>>16&255,e[r(355)](l,24),e[r(883)](255,s),e[r(1559)](e[r(987)](s,8),255),e[r(868)](e[r(567)](s,16),255),s>>>24]}toBytesBE(){let r=t,s=this[r(830)],l=this[r(239)];return[e[r(462)](s,24),e[r(346)](e[r(914)](s,16),255),e[r(568)](e.YKpls(s,8),255),e[r(1289)](255,s),e[r(1453)](l,24),e[r(1281)](e[r(955)](l,16),255),e[r(1617)](l>>>8,255),255&l]}}let ml=new fe(0,0,!1),tg=new fe(0,0,!0),ng=fe.fromBits(-1,2147483647,!1),rg=fe[t(1480)](-1,-1,!0),ig=fe[t(1480)](0,-2147483648,!1);var an=(function(a){let r=t;return a[a[e[r(1448)]]=5001]=e.IrDOB,a[a[r(952)+r(552)]=5002]=e[r(939)],a[a["MAX_RETR"+r(585)+"R"]=5003]=r(1430)+"IES_ERROR",a[a[r(1315)+r(1522)]=5004]=e[r(317)],a[a[e[r(528)]]=5005]=e[r(528)],a})({});class cr{constructor(r){let s=t,l={aBFAK:function(h,m){return h&m},aOsiV:function(h,m){return e.UeNsf(h,m)},iSSkc:function(h,m){return e.EtoqA(h,m)},TOELJ:function(h,m){return h&m},yXNxS:function(h,m){return e.FxkTb(h,m)}};if(s(1580)===e[s(654)])this[s(1216)]=r,this[s(1264)]=null;else{let h=this[s(830)],m=this[s(239)];return[rLdrXf.aBFAK(255,m),rLdrXf[s(602)](m>>>8,255),rLdrXf[s(602)](rLdrXf.aOsiV(m,16),255),m>>>24,rLdrXf[s(602)](255,h),rLdrXf[s(295)](rLdrXf[s(1323)](h,8),255),rLdrXf.TOELJ(rLdrXf.yXNxS(h,16),255),h>>>24]}}}class wl extends cr{constructor(r,s){let l=t;super(r),this[l(1495)]=s&&s[l(1495)]||null}}class _l extends cr{constructor(r,s){let l=t;super(r),this[l(253)]=s&&s[l(253)]||null,this[l(1402)]=s&&s[l(1402)]||0,this[l(1045)]=s&&s[l(1045)]||"",this[l(1396)]=s&&s[l(1396)]||0,this[l(1495)]=s&&s[l(1495)]||"",this[l(1588)]=s&&s[l(1588)]||5001}}class yl extends cr{constructor(r,s){let l=t,h=(l(648)+"2")[l(639)]("|"),m=0;for(;;){switch(h[m++]){case"0":this.wasClean=s&&s[l(905)]||!1;continue;case"1":this[l(1588)]=s&&s.code||0;continue;case"2":this[l(1059)+"nnect"]=s&&s["willReco"+l(472)]||!1;continue;case"3":this.reason=s&&s[l(529)]||"";continue;case"4":super(r);continue}break}}}class bl extends cr{constructor(r,s){let l=t;super(r),this.data=s&&s[l(1022)]||null}}class El extends bl{constructor(r,s){let l=t;super(r),this[l(1022)]=s&&s[l(1022)]||null,this[l(1495)]=s&&s[l(1495)]||null}}class vl extends cr{constructor(r,s){let l=t;super(r),this[l(1022)]=s&&s[l(1022)]||null}}function lt(a,{message:r,code:s,error:l}){return new _l(a,{message:r,code:s,error:l})}function wt(a,{code:r,reason:s,wasClean:l,willReconnect:h}){let m=t;return e.Rjuno!==e[m(1063)]?new yl(a,{code:r,reason:s,wasClean:l,willReconnect:h}):_0x38ea9e[m(1539)]||_0x5259c4[m(314)]?(m(1346)+" "+(_0x37ea69[m(1539)]||"")+" code: "+(_0x258f86.errNo||""))[m(804)]():_0x33422d[m(1044)+"y"](_0x2ce7d6)}function Sl(a,{data:r,message:s}){return new El(a,{data:r,message:s})}function Il(a,{data:r}){return new vl(a,{data:r})}function Aa(a,{message:r}){let s=t;return e[s(716)]("SkgfZ",s(445))?new wl(a,{message:r}):this[s(1473)]?this._ws[s(998)]:""}class Al{constructor(r,s){let l=t;this[l(589)+"s"]=r,this[l(1498)+"es"]=s,this[l(1319)+"ndex"]=0,this[l(1187)+l(427)+"riesCount"]=0}[t(1186)+t(1198)+t(1254)](){let r=t;this["currentI"+r(671)]=0,this[r(1187)+r(427)+r(764)+"t"]=0}[t(493)+"es"](){let r=t;this[r(1187)+r(427)+r(764)+"t"]=0}[t(404)+"ntEndpoint"](){let r=t;return this.endpoints[this[r(1319)+r(671)]]}[t(404)+t(704)+"ntTriesCount"](){let r=t;return this[r(1187)+r(427)+r(764)+"t"]}[t(339)+t(278)+"es"](){let r=t;return!!(e.uzjha(this[r(1319)+r(671)],this[r(589)+"s"][r(368)])||e.sqotw(this[r(1319)+r(671)],e[r(635)](this[r(589)+"s"].length,1))&&this["currentEndpointT"+r(764)+"t"]===this[r(1498)+"es"])}[t(410)+t(1064)+"ointReac"+t(706)+t(1353)](){let r=t;return e[r(1467)](this["currentI"+r(671)],this[r(589)+"s"].length)?!0:e[r(1139)](this["currentE"+r(427)+"riesCount"],this.maxRetries)}["replaceBackupEnd"+t(1357)+t(401)+t(1015)](){let r=t;return this[r(1187)+r(427)+"riesCount"]=1,this["currentI"+r(671)]++,this[r(589)+"s"][this[r(1319)+"ndex"]]}[t(404)+t(704)+t(202)+"ateCount"](){let r=t;return this[r(1187)+r(427)+r(764)+"t"]++,this[r(404)+r(704)+"nt"]()}}let dr=(e[t(597)]!=typeof globalThis&&e[t(737)](e[t(1509)],globalThis[t(557)+t(169)][t(1037)])||e[t(584)](e[t(597)],typeof window)&&e[t(1595)](e[t(1509)],window[t(557)+t(169)].name))&&e[t(597)]!=typeof document,Nn=e[t(394)](e[t(597)],typeof globalThis)&&(e[t(571)](e[t(1051)],globalThis[t(557)+t(169)][t(1037)])||e[t(1390)](e[t(1027)],globalThis[t(557)+t(169)][t(1037)]))&&t(926)+"d"!=typeof tt,si=(e.ZNEmf(e[t(597)],typeof globalThis)&&e[t(1518)](t(1267),globalThis[t(557)+t(169)].name)||e[t(1057)](e[t(597)],typeof globalThis)||e[t(405)](e[t(597)],typeof globalThis)&&!!globalThis[t(1377)+"Bridge"])&&e[t(597)]!=typeof wx,oi=e[t(1507)](e[t(597)],typeof globalThis)&&(e.RyqIg(e[t(1027)],globalThis.constructor[t(1037)])||e[t(1104)]("SharedWo"+t(1438)+t(687),globalThis[t(557)+"tor"].name)||e.LPRRZ===globalThis["construc"+t(169)][t(1037)])&&typeof self<"u",sg=t(926)+"d"!=typeof globalThis&&e[t(1051)]===globalThis[t(557)+t(169)].name&&e[t(980)](e.opbLG,typeof global)&&e.UBEDk(t(1267),global[t(557)+t(169)][t(1037)])&&e.BNkud(e.opbLG,typeof process)&&!!process[t(833)];class ka{constructor(){this._listeners={}}[t(1183)](r,...s){let l=t,h={HXlEQ:function(b,v,g){return e[$(594)](b,v,g)}},m=this[l(180)+"rs"][r];if(m)m.slice()[l(633)](b=>b.fn.apply(b[l(1452)],s));else if(e.tUsSO===r&&!this[l(1180)])if(e[l(1407)](e[l(399)],e.YJgYg)){let b=s.length&&s[0];if(b instanceof Error)throw b;let v=new Error(e[l(234)](l(1070)+l(1425),b?e[l(1184)](e[l(1009)](" (",b[l(1495)]),")"):""));throw v.context=b,b}else return _0x237f24[l(973)][qewuYR[l(233)](_0x1a56bc,_0x1eb1b9,1)];return this}off(r,s){let l=t;if(e[l(520)](void 0,r))this[l(180)+"rs"]={};else if(e[l(1217)](void 0,s))this._listeners[r]=null;else if(e[l(413)]("QkoVH",e[l(1543)]))_0x42ef49[l(770)](_0x3afc37,_0x1de8c3);else{let h=this[l(180)+"rs"][r];if(h)for(let m=0;e[l(1074)](m,h[l(368)]);)h[m].fn===s?h.splice(m,1):++m}return this}on(r,s,l){let h=t;return(this._listeners[r]||(this[h(180)+"rs"][r]=[]))[h(612)]({fn:s,ctx:l||this}),this}}class og extends ka{[t(1554)+t(784)+t(535)](r){let s=t,l={NoXVE:function(h,m,b){return e[$(469)](h,m,b)},eaVZT:e[s(911)]};if(e[s(817)]!==e[s(817)]){let h=l[s(840)](_0x4c59fe,l[s(1010)],{message:_0x261d42[s(1495)],code:_0x14978e[s(1315)+s(1522)],error:_0x3a4440});this[s(825)+s(1227)+"ent"](h)}else return r.errMsg||r[s(314)]?(s(1346)+" "+(r[s(1539)]||"")+" code: "+(r[s(314)]||""))[s(804)]():JSON[s(1044)+"y"](r)}constructor(r,s,l){let h=t;super(),this._socket=null,si&&wx[h(797)+h(265)]&&(this[h(213)]=wx[h(797)+h(265)]({url:r,protocols:s,header:l,fail:this["_createS"+h(1321)+h(1366)][h(251)](this),success:this[h(1279)+"ocketSuc"+h(203)+h(807)][h(251)](this)})),Nn&&tt[h(797)+h(265)]&&(this[h(213)]=tt[h(797)+h(265)]({url:r,protocols:s,header:l,fail:this[h(1279)+h(1321)+h(1366)].bind(this),success:this[h(1279)+h(573)+h(203)+h(807)][h(251)](this)}))}[t(1279)+t(573)+"cessHandler"](){let r=t;Promise[r(1110)]().then(()=>{let s=r;this[s(1212)+s(532)]()})}[t(1279)+t(1321)+t(1366)](r){let s=t,l={ylZJy:function(h,m,b){return e[$(1133)](h,m,b)},NxtxX:e[s(911)],OJfSQ:function(h,m,b){return e[s(533)](h,m,b)},RTQET:"close"};Promise.resolve()[s(287)](()=>{let h=s,m=l[h(541)](lt,l[h(441)],{message:this[h(1554)+h(784)+"age"](r)});this[h(1183)](l[h(441)],m);let b=l[h(1147)](wt,h(578),{reason:this[h(1554)+"rrorMessage"](r)});this[h(1183)](l[h(1086)],b)})}[t(1212)+t(532)](){let r=t,s={wAjxA:e.Fsoft,nmhyH:function(l,h,m){return l(h,m)},nzyAy:e.rmHZq,IzvwQ:function(l,h,m){return e[$(469)](l,h,m)},LWFbO:e[r(911)]};this._socket[r(981)](l=>{let h=r;this[h(1183)](s[h(899)],s[h(499)](Il,s[h(899)],{...l,data:l[h(1539)]||""}))}),this[r(213)][r(1541)](l=>{let h=r;this[h(1183)](h(578),e[h(1113)](wt,e[h(1618)],{...l}))}),this._socket[r(739)+"e"](l=>{let h=r;this[h(1183)](s[h(878)],s[h(214)](Sl,s.nzyAy,{...l}))}),this[r(213)][r(1432)](l=>{let h=r;this[h(1183)](s[h(746)],lt(h(253),{...l,message:l[h(1539)]||""}))})}send(r){let s=t,l={vDvwI:s(253),mNBsp:function(h,m,b){return e.wArBl(h,m,b)}};if(e[s(257)](r,Uint8Array)){let h=r.buffer[s(881)](r.byteOffset,r[s(408)+"th"]+r[s(1219)+"et"]);this[s(213)]&&this[s(213)][s(801)]({data:h,fail:m=>{let b=s;this[b(1183)](l[b(876)],lt(l.vDvwI,{message:this[b(1554)+b(784)+b(535)](m)}))}})}else this[s(213)]&&this[s(213)][s(801)]({data:r,fail:h=>{let m=s;this.emit(l[m(876)],l[m(1129)](lt,l[m(876)],{message:this[m(1554)+"rrorMess"+m(535)](h)}))}})}close(r,s){this[t(213)]&&this._socket.close({code:r,reason:s})}[t(1625)+t(1363)](r,s){this.on(r,s)}[t(1347)+"entListe"+t(1236)](r,s){this[t(1155)](r,s)}get[t(1298)+"te"](){let r=t;return this[r(213)][r(1298)+"te"]}get[t(1033)+"pe"](){let r=t;return this[r(213)][r(1033)+"pe"]}set[t(1033)+"pe"](r){}get[t(527)](){let r=t;return this[r(213)][r(527)]}get protocol(){let r=t;if(r(1170)!==e.UQrZm){let s=this[r(1111)].getItem(this[r(319)]),l=_0x258b79.parse(e[r(1071)](s,"{}"));return _0x1fa39b[r(852)](l)}else return this._socket[r(998)]}get[t(1101)+"ns"](){let r=t;return this[r(213)][r(1101)+"ns"]}get[t(309)+t(1578)](){return 0}}function ag(a,r){let s=t;if(r)return new r(a[s(527)],a[s(998)]);if(e.dGLLa(si,Nn))return new og(a[s(527)],a[s(998)],a[s(521)]);if(e[s(1071)](dr,oi)&&e[s(597)]!=typeof WebSocket&&WebSocket)return new WebSocket(a[s(527)],a[s(998)+"s"])}function cg(a){let r=t,s=e[r(1598)][r(639)]("|"),l=0;for(;;){switch(s[l++]){case"0":if((dr||oi)&&e[r(394)](e[r(597)],typeof WebSocket)&&WebSocket)return!0;continue;case"1":if(Nn&&tt[r(797)+r(265)])return!0;continue;case"2":return!1;case"3":if(si&&wx["connectS"+r(265)])return!0;continue;case"4":if(a)return!0;continue}break}}function kl(a,r,s){let l=t,h={yYjES:e[l(1066)],BQuXu:function(v,g){return e[l(520)](v,g)},BIpwe:function(v,g){return v+g}},m=-1;async function b(v){let g=l;return v<=m?Promise.reject(new Error(h.yYjES)):(m=v,h.BQuXu(v,s.length)?Promise.resolve():s[v].bind(a)(r,b.bind(null,h[g(514)](v,1))))}e.yBrBr(b,0)}function Tl(a){let r=t,s=0,l=0;for(let h=0;h<a[r(368)];++h)if(e[r(1483)](e[r(1290)],e.OsPhA))l=a.charCodeAt(h),l<128?s+=1:e[r(811)](l,2048)?s+=2:e.gQiqj(64512,l)===55296&&e[r(734)](e.gVgga(64512,a[r(1519)+"At"](e[r(754)](h,1))),56320)?(++h,s+=4):s+=3;else return _0x5bda57?_0x1ef5ba[r(542)+"sLE"](_0x2c5096,_0x412564):_0x3521ee[r(542)+"sBE"](_0x3a10e7,_0x41cd49);return s}function Cl(a,r,s){let l=t;if(e[l(423)](s,r)<1)return"";let h="";for(let m=r;e[l(664)](m,s);){let b=a[m++];if(e[l(1408)](b,127))h+=String[l(489)+"Code"](b);else if(e.RJMWT(b,192)&&e[l(967)](b,224))h+=String[l(489)+"Code"]((31&b)<<6|e[l(1354)](63,a[m++]));else if(b>=224&&e[l(684)](b,240))h+=String["fromChar"+l(1361)](e.yysZh(e[l(1567)](e[l(531)](15,b),12),e.hnMQy(e[l(1384)](63,a[m++]),6))|e[l(1268)](63,a[m++]));else if(e[l(420)](b,240)){let v=e[l(1445)](e[l(1020)](e.yeGTB(e[l(1520)](7,b)<<18,e[l(175)](63&a[m++],12))|e.gVgga(63,a[m++])<<6,e.Xdmab(63,a[m++])),65536);h+=String[l(489)+l(1361)](55296+e.YpNzy(v,10)),h+=String[l(489)+l(1361)](e[l(1585)](56320,1023&v))}}return h}function Ta(a,r,s){let l=t,h=s,m,b;for(let v=0;e[l(458)](v,a[l(368)]);++v)if(m=a[l(1519)+"At"](v),e[l(1603)](m,128))r[s++]=m;else if(e[l(1316)](m,2048))r[s++]=e[l(546)](e.FuytA(m,6),192),r[s++]=e[l(1049)](63&m,128);else if(e[l(193)](e[l(1289)](64512,m),55296)&&e[l(719)](64512&(b=a[l(1519)+"At"](e.dNMnd(v,1))),56320)){let g=e.RcuiG.split("|"),C=0;for(;;){switch(g[C++]){case"0":r[s++]=e[l(1335)](63,m)|128;continue;case"1":++v;continue;case"2":r[s++]=e[l(1593)](e[l(294)](m,6)&63,128);continue;case"3":m=e[l(856)](e[l(928)](65536,e[l(1411)](1023,m)<<10),e[l(846)](1023,b));continue;case"4":r[s++]=e[l(353)](m,18)|240;continue;case"5":r[s++]=e[l(1208)](e[l(682)](e[l(700)](m,12),63),128);continue}break}}else r[s++]=e.SMZvx(e.SDkkt(m,12),224),r[s++]=e[l(335)](e[l(396)](e[l(1437)](m,6),63),128),r[s++]=e.mJYhf(63&m,128);return e[l(423)](s,h)}async function Rl(a){let r=t;if(e.FnnEd(e[r(1521)],e.OnHZD)){if(e.hHLvH==typeof a){let s=new Uint8Array(e[r(1350)](Tl,a));return Ta(a,s,0),s}return e.ujZrr(a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[r(386)],a[r(1219)+"et"],a.byteLength)}else _0x2ee56a(this[r(908)+r(178)+r(1095)]),this[r(908)+r(178)+"utId"]=null}function dg(a){let r=t;if(e[r(1158)]("yIPEq",r(434)))try{return e[r(584)](r(1278),typeof a)&&(a instanceof ArrayBuffer||a.buffer&&e[r(879)](a[r(386)],ArrayBuffer))||e[r(1538)]!=typeof a?"":(JSON[r(1371)](a),e[r(832)])}catch{return e[r(1221)]!==r(699)?e.hHLvH==typeof a?r(947)+r(791)+"et=utf-8":"":this._isMiniTT||this[r(1146)+"X"]?this[r(1463)+"igatorOn"+r(818)]:(this[r(555)+"er"]||this[r(1093)+"r"])&&this[r(1492)]["listenNe"+r(479)+r(1531)]?_0x3e2d5b[r(1047)]:!0}else return _0x577d61[r(805)](_0x5c3940),!1}let lg=(a,r)=>{let s=t;switch(a){case e[s(750)]:case e[s(1582)]:return{[s(293)+a]:1,"x-tt-env":r};default:return{}}};class ug{constructor(r){let s=t;if(e[s(600)](e[s(1478)],e[s(1478)])){let l=e[s(349)].split("|"),h=0;for(;;){switch(l[h++]){case"0":if(!this._ws)return;continue;case"1":this._ws[s(1625)+s(1363)](e.Fsoft,this[s(788)]);continue;case"2":this[s(1473)][s(1625)+"Listener"](s(1495),this[s(1419)+"ge"]);continue;case"3":this[s(1473)][s(1625)+s(1363)](s(253),this._onError);continue;case"4":this[s(1473)][s(1625)+s(1363)](e.Spmlh,this[s(1325)]);continue}break}}else this["maxLossC"+s(1328)]=r,this.count=0}addCount(){let r=t;if(e.cdYES(e[r(829)],e[r(829)]))this.count++;else{let s=0,l={};for(let h=0;e[r(664)](h,_0x36c689.length);h++)l[_0x1676c9[h][r(812)+r(1031)]]=_0xbb03b8(_0x2c7f1c[h][r(812)+"ame"]),s+=e.rhbbb(14,l[_0x446086[h][r(812)+"ame"]]);return[s,l]}}[t(339)+t(1023)+"nt"](){let r=t;return e.BZkld(this.count,this[r(815)+r(1328)])}resetCounter(r=0){let s=t;this["maxLossC"+s(1328)]=r,this[s(982)]=0}}async function fg(a){let r={AJiHZ:function(s){return e.tjMLm(s)},WWFuK:function(s,l,h){return e[$(1613)](s,l,h)}};return new Promise(s=>{let l=$,h={PbQCN:function(m,b){return m(b)},APimk:e[l(513)]};if(e[l(844)](e[l(755)],"FTQAg")){if(!dr)return e[l(786)](s,e[l(513)]);try{let m=document[l(569)+l(289)](e.aNwqv);window["frontier"+l(297)]=b=>{let v=l;document[v(885)][v(551)+v(1612)](m),window["frontier"+v(297)]=void 0,h[v(1515)](s,b&&b[v(1123)]||h[v(1571)])},m[l(1216)]=e[l(1537)],m.src=e[l(642)](a[l(732)](/^ws/,e[l(1301)]),e.jFZpd);try{document[l(885)][l(826)+l(1612)](m)}catch{if(e[l(1424)]("BLDVb",e[l(305)])){let b=dZVeTT[l(970)](_0x38e2b1);return dZVeTT[l(176)](_0x43ccdd,_0x48ac04,b),_0x12ed7b(b)}else document.body["removeCh"+l(1612)](m)}}catch{window[l(634)+l(297)]=void 0,e.AZbjm(s,"unknown "+l(529))}}else _0x509127[l(805)](_0x4315ea)})}function cn(a,r,s){let l=t,h={pmUPQ:l(253),xCEnn:e[l(190)]};if(e[l(758)](l(989),e[l(994)]))return!!a?.[l(1572)](m=>m[l(1251)]===r&&m.value===s);_0x2b21c7[l(1347)+l(649)+l(1236)]("complete",_0x26418f),_0x3c9604["removeEv"+l(649)+l(1236)](ebymwb[l(866)],_0x2b00b7),_0x353dfc[l(1347)+l(649)+l(1236)](ebymwb[l(363)],_0x2835c4)}function lr(a,r){let s=t;if(e[s(1407)](e[s(334)],e[s(1607)]))return a?.[s(1572)](l=>l[s(1251)]===r)?.[s(763)];this[s(481)+"lFlush"]()}let Ca=null;async function hg(){let a=t;if(e[a(1263)](e[a(1270)],a(1508)))return Ca||(Ca=Promise[a(1110)]()[a(287)](Ut[a(251)](Ut,e.PbsoX))),Ca;_0x1579a2[a(885)][a(551)+a(1612)](_0x55d0ff)}class xg extends ka{constructor(r,s){let l=t,h={RjLvb:function(m,b){return m>>>b},FQBmB:function(m,b){return m&b},pkkAk:function(m,b){return e[$(629)](m,b)},bpdOH:function(m,b){return m&b},xOfqP:function(m,b){return e[$(1411)](m,b)},avSIE:function(m,b){return e.kCVrM(m,b)},dExyV:function(m,b){return e.xryNf(m,b)},gOPNz:function(m,b){return e[$(1276)](m,b)},PTdah:function(m,b){return e[$(962)](m,b)}};if(e.Fyxct===e.Fyxct)super(),this[l(794)]=r,this[l(1050)]=s,this._qosDB=void 0,this[l(636)+"mise"]=null;else{_0x14546b[l(1191)](_0xad0dca)||(_0x21adb8=_0x26155c.fromNumber(_0x137959));let m=sYVpbM[l(1131)](this[l(830)],16),b=sYVpbM[l(1471)](65535,this.high),v=sYVpbM.pkkAk(this.low,16),g=65535&this[l(239)],C=sYVpbM[l(1218)](_0x16af38[l(830)],16),L=sYVpbM[l(490)](65535,_0x436e9d[l(830)]),B=sYVpbM[l(1218)](_0x5d252b[l(239)],16),G=sYVpbM[l(1173)](65535,_0x146ba7[l(239)]),Z=0,K=0,ge=0,he=0;return he+=sYVpbM[l(1533)](g,G),ge+=sYVpbM[l(1131)](he,16),he&=65535,ge+=sYVpbM.avSIE(v,B),K+=ge>>>16,ge&=65535,K+=sYVpbM.dExyV(b,L),Z+=sYVpbM[l(1131)](K,16),K&=65535,Z+=m+C,Z&=65535,_0xef93b2[l(1480)](sYVpbM[l(167)](sYVpbM[l(204)](ge,16),he),sYVpbM[l(167)](sYVpbM[l(204)](Z,16),K),this.unsigned)}}async openDB(){await this[t(1280)]()}async[t(1280)](){let r=t,s={KriGE:function(l,h){return e[$(193)](l,h)},vcpWZ:e[r(1119)],QXByT:function(l){return e[r(1223)](l)},LRyWm:function(l,h,m,b){return e[r(875)](l,h,m,b)},xXZym:e[r(1038)],UZjZO:r(478)+r(1097)};if(!this[r(1111)]){if(this[r(636)+"mise"])return this["_initPro"+r(300)];try{let l=this[r(794)],h=this[r(1050)];this[r(636)+r(300)]=(async()=>{let m=r,b={TBxWZ:function(g,C){return s[$(886)](g,C)},NREfG:s[m(956)]},{openDB:v}=await s[m(627)](hg);this[m(1111)]=await s.LRyWm(v,m(634)+"_"+l,1,{upgrade(g){let C=m;b.TBxWZ(b.NREfG,b[C(1138)])?g[C(1229)+C(1288)+"e"](l,{keyPath:h}):(this[C(1412)]=_0x247241,this[C(752)]=_0x993469,this[C(1111)]=_0x4f4947?_0x52553c:_0x5d4b18?_0x47007b:null)}})})(),await this[r(636)+r(300)]}catch(l){console.log(l)}finally{if(e[r(757)](e[r(958)],e[r(958)]))return{frameType:_0xdf2e19,headers:[{key:s.xXZym,value:s[r(703)]}],payload:void 0};this[r(636)+r(300)]=null}}}async get(r){let s=t;try{return await this._init(),this[s(1111)]?.[s(1484)](this[s(794)],r)}catch(l){console[s(805)](l)}}async set(r,s){let l=t;return await this._init(),this[l(1111)]?.[l(1025)](this[l(794)],r)}async[t(871)](r){let s=t;try{return await this._init(),this[s(1111)]?.[s(813)](this[s(794)],r)}catch(l){console[s(805)](l)}}async clear(){let r=t;try{return await this[r(1280)](),this._qosDB?.[r(1094)](this[r(794)])}catch(s){if(e[r(655)](e[r(887)],e.yqmCW)){if(_0x1b108e instanceof _0x35cd41)return vNGdOO[r(1304)](_0x28e9f5,_0x2591ae);if(_0x1f13c0[r(341)](_0x3f8e7a))return _0x4d1eab[r(1484)](_0xfb8eb7);let l=vNGdOO.AZbjm(_0x315098,_0x277a06);return vNGdOO[r(626)](l,_0x13d945)&&(_0x247f29[r(770)](_0x36235b,l),_0x5b2ef6[r(770)](l,_0x3a3a9f)),l}else console[r(805)](s)}}async keys(){let r=t;return await this[r(1280)](),this[r(1111)]?.[r(1514)+"ys"](this[r(794)])}async[t(1234)](){let r=t;return await this[r(1280)](),this[r(1111)]?.getAll(this._dbName)}async[t(1456)](){let r=t;try{e[r(599)](r(1062),r(1076))?(this[r(1111)]?.[r(578)](),this._qosDB=void 0):(this["_dispatc"+r(842)+r(1091)](_0x455a9f),_0x4e4678.set(_0x463377,_0x39c505,_0x50382d[r(1495)][r(1296)]))}catch(s){console[r(805)](s)}}get[t(824)](){let r=t;try{return!!this._qosDB}catch(s){return console[r(805)](s),!1}}}class pg{constructor(r,s){let l=t;this[l(1412)]=r,this[l(752)]=s,this[l(1111)]=localStorage}async openDB(){}get[t(319)](){let r=t;return r(634)+"_"+this[r(1412)]}async[t(1484)](r){let s=t,l=this[s(1111)][s(748)](this[s(319)]);return JSON[s(1371)](l||"{}")[r]}async[t(770)](r,s){let l=t,h=this[l(1111)][l(748)](this[l(319)]),m=JSON[l(1371)](e[l(1071)](h,"{}"));return m[s||r[this[l(752)]]]=r,this._qosDB.setItem(this[l(319)],JSON.stringify(m)),s||r[this._pathKey]}async del(r){let s=t,l=this._qosDB.getItem(this[s(319)]),h=JSON[s(1371)](e[s(1159)](l,"{}"));return h[r]=void 0,this[s(1111)][s(1351)](this[s(319)],JSON.stringify(h))}async[t(1094)](){let r=t;if(e[r(1475)]!==e[r(950)])return this._qosDB[r(1094)]();{let s=e[r(963)](_0x43e402,e[r(911)],{message:this[r(1554)+"rrorMess"+r(535)](_0x304c0a)});this[r(1183)]("error",s);let l=_0xda4d8d(e[r(1618)],{reason:this[r(1554)+r(784)+r(535)](_0x2e87c8)});this[r(1183)](e[r(1618)],l)}}async keys(){let r=t,s=this[r(1111)][r(748)](this[r(319)]),l=JSON[r(1371)](e.AycTi(s,"{}"));return Object[r(852)](l)}async[t(1234)](){let r=t,s=this[r(1111)][r(748)](this[r(319)]),l=JSON[r(1371)](e[r(277)](s,"{}"));return Object.values(l)}[t(1456)](){return Promise[t(1110)]()}get[t(824)](){return!!this[t(1111)]}}class gg{constructor(r,s){let l=t;this[l(1412)]=r,this[l(752)]=s,this._qosDB=Nn?tt:si?wx:null}async[t(172)](){}get _prefix(){let r=t;return r(634)+"_"+this[r(1412)]}async[t(1484)](r){let s=t,l=this._qosDB[s(692)+s(1056)](this[s(319)]);return JSON[s(1371)](e[s(938)](l,"{}"))[r]}async set(r,s){let l=t,h=this._qosDB[l(692)+l(1056)](this[l(319)]),m=JSON[l(1371)](e[l(1297)](h,"{}"));return m[s||r[this[l(752)]]]=r,this._qosDB.setStorageSync(this[l(319)],JSON[l(1044)+"y"](m)),s||r[this._pathKey]}async[t(871)](r){let s=t;if(e[s(436)](e[s(774)],e[s(1579)])){let l=this[s(1111)].getStorageSync(this[s(319)]),h=JSON[s(1371)](e.ezbkU(l,"{}"));return h[r]=void 0,this._qosDB[s(1581)+s(1056)](this[s(319)],JSON.stringify(h))}else try{e[s(1092)](_0x34f81d,this,_0x3c17de,[_0x23de04,_0x2c95c7,_0x2f330e])}catch(l){let h=e[s(486)](_0x22c94d,e[s(911)],{message:l[s(1495)],code:_0x2cd601[s(498)+"OR"],error:l});this[s(825)+s(1227)+"ent"](h)}}async[t(1094)](){let r=t;return this[r(1111)][r(264)+r(1226)]()}async keys(){let r=t,s=this[r(1111)][r(692)+r(362)+"nc"](this[r(319)]),l=JSON[r(1371)](e[r(1297)](s,"{}"));return Object[r(852)](l)}async[t(1234)](){let r=t,s=this[r(1111)][r(692)+r(362)+"nc"](this[r(319)]),l=JSON[r(1371)](e[r(847)](s,"{}"));return Object.values(l)}[t(1456)](){return Promise[t(1110)]()}get isReady(){return!!this._qosDB}}function Dl(a,r){let s=t;if(Nn||Nn)return new gg(a,r);if((dr||oi)&&e[s(394)](e[s(597)],typeof indexedDB))return new xg(a,r);if(e.qBmiT(dr,oi)&&e[s(584)](e[s(597)],typeof localStorage))return new pg(a,r);throw new Error(e[s(1054)])}class mg{constructor(){let r=t;this[r(481)+"lTimeoutId"]=null,this._interval=36e5,this[r(1111)]=e[r(727)](Dl,r(723),e[r(377)])}async[t(481)+t(1114)](){let r=t;if(e[r(1497)](e[r(1034)],e[r(1034)])){let s=this[r(1111)].getItem(this._prefix),l=_0x476bc3[r(1371)](e[r(847)](s,"{}"));return l[_0x20740e]=void 0,this._qosDB.setItem(this[r(319)],_0x464bd8[r(1044)+"y"](l))}else clearInterval(this[r(481)+r(461)+"Id"]),this[r(481)+"lTimeoutId"]=e[r(1317)](setInterval,()=>{this["flushExp"+r(1291)]()},this._interval)}async[t(172)](){let r=t;await this[r(1111)].openDB()[r(287)](()=>{this[r(481)+"lFlush"]()})}async[t(1266)+"ired"](){let r=t;(await this[r(1111)]?.[r(1234)]()||[]).filter(({timestamp:h})=>h<Date[r(778)]()).forEach(h=>{let m=r;this[m(1111)]?.[m(871)](h[m(1440)+"id"])})}async[t(871)](r){let s=t;return this[s(1111)]?.[s(871)](r)}async[t(770)](r,s){let l=t;if(e[l(759)]===l(834))return this[l(1111)]?.[l(770)]({message_id:r,timestamp:s})}async[t(1484)](r){let s=t;return this._qosDB?.[s(1484)](r)}async closeDB(){let r=t;e.LReoo(clearInterval,this[r(481)+r(461)+"Id"]),await this[r(1111)]?.closeDB()}get[t(824)](){let r=t;return this[r(1111)]?.[r(824)]}}function Ra(a){let r=t,s=!!this[r(1492)][r(1547)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=cn(a[r(1495)][r(521)],e[r(894)],"2"),h=l&&e.hAVbS(cn,a[r(1495)][r(521)],e[r(1489)],"1"),m=l&&e[r(491)](cn,a[r(1495)][r(521)],"x_fronti"+r(324)+"k","1"),b=m?e[r(216)](lr,a[r(1495)].headers,e[r(1565)])?.[r(639)](",")[r(1395)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:m,ackMsgIds:b}}async function Pl(){let a=t;return this["_QoSMana"+a(1624)]||(this[a(828)+a(1624)]=new mg),this[a(828)+"ger"][a(824)]||await this[a(828)+a(1624)].openDB(),this[a(828)+a(1624)]}async function wg(a,r){let s=t,{enableAutoAck:l}=this._options,h=cn(a[s(1495)].headers,e[s(799)],"1"),m=e[s(903)](cn,a[s(1495)][s(521)],s(1576),"1"),b=Ra[s(1382)](this,a);if(e[s(271)](l,h))if(e[s(1306)]===e[s(419)])this[s(1626)+"ileName"]=_0x3e3eaf;else{let{SeqID:v,LogID:g,service:C,LogIDNew:L,method:B}=a[s(1495)];this._sendAck({SeqID:v,LogID:g,LogIDNew:L,service:C,method:B,headers:[{key:e.sjHfA,value:"1"},{key:e[s(1584)],value:e[s(1401)](L,"")},{key:e[s(361)],value:"0"}]})}m&&!b[s(822)]&&this[s(825)+s(934)+s(1461)](a),e.xqtpS(r)}async function _g(a,r){let s=t;this._debug(e[s(990)],a[s(1495)]),e[s(1451)](r)}async function yg(a,r){let s=t,l=e[s(789)](sn,await e[s(698)](Rl,a[s(1022)]));try{if(e.ujZrr(l[s(1019)],Uint8Array)){if(e[s(1552)]!==s(979))return this[s(1111)]?.[s(871)](_0x5df33f);{let h=e[s(1405)](this[s(1492)][s(1442)+s(1136)],Object)?{force:!!this[s(1492)][s(1442)+s(1136)][s(1344)],encoding:this._options[s(1442)+s(1136)][s(1096)]?this[s(1492)][s(1442)+s(1136)][s(1096)][s(732)](/\s/g,"")[s(358)+s(1500)]():""}:{force:!1,encoding:this[s(1492)][s(1442)+s(1136)]?this[s(1492)]["payloadE"+s(1136)][s(732)](/\s/g,"")[s(358)+"ase"]():""},m=l["payloadE"+s(1136)]?l[s(1442)+s(1136)].replace(/\s/g,"")[s(358)+s(1500)]():"",b=this._options["payloadT"+s(351)]instanceof Object?{force:!!this[s(1492)]["payloadT"+s(351)][s(1344)],type:this[s(1492)].payloadType[s(1216)]?this[s(1492)][s(446)+s(351)][s(1216)][s(732)](/\s/g,"")[s(358)+"ase"]():""}:{force:!1,type:this[s(1492)][s(446)+s(351)]?this._options["payloadT"+s(351)][s(732)](/\s/g,"")[s(358)+s(1500)]():""},v=l["payloadT"+s(351)]?l[s(446)+"ype"][s(732)](/\s/g,"")[s(358)+s(1500)]():"",g=b[s(1344)]?b.type:v||b[s(1216)],C=h.force?h[s(1096)]:m||h[s(1096)],L=[s(947)+s(791)+s(780),s(898)+"ion/json",e[s(863)],e[s(1538)]],B=[e[s(279)],s(957)];this[s(1492)][s(731)+s(1449)+s(767)+"ad"]&&L[s(906)](g)&&(!C||B[s(906)](C))?l[s(607)+"oad"]=e[s(491)](Cl,l.payload,0,l[s(1019)][s(408)+"th"]):l["textPayl"+s(565)]=""}}else l[s(607)+"oad"]=""}catch(h){e[s(1526)]!==s(975)?_0xfe34c5&&this[s(1102)+s(1292)][s(1490)+"rsorFile"+s(440)](_0x4b21f1):(l["textPayl"+s(565)]="",console.log(h))}a[s(1495)]=l,e[s(474)](r)}function bg(a,r,s){let l=t,h={aNuly:function(C,L){return e[$(1185)](C,L)},lNgfT:function(C,L){return e[$(1249)](C,L)},kkbtl:function(C,L){return C+L},equFI:function(C,L){return e[$(225)](C,L)},UBWgv:function(C,L){return C&L},VHHHX:function(C,L){return e.XIWOq(C,L)}},m=e.ezbkU(s,8192),b=e[l(325)](m,1),v=null,g=m;return function(C){let L=l;if(C<1||h[L(398)](C,b))return a(C);h[L(809)](h[L(1594)](g,C),m)&&(v=h[L(425)](a,m),g=0);let B=r[L(1382)](v,g,g+=C);return h[L(918)](7,g)&&(g=h[L(1594)](h.VHHHX(7,g),1)),B}}let Eg=4294967295;function vg(a,r,s){let l=t;return e[l(475)](RangeError,e[l(638)](e[l(366)](e.PFspP(e[l(936)](e[l(234)](e[l(1177)],a),e[l(946)]),r||1),e[l(1434)]),s))}function Sg(a,r,s){let l=t;if(e[l(1241)](s,Eg))throw new Error(e[l(518)]);let h=3;for(;h>=0;){let m=e[l(682)](255,s);e[l(322)](Pa,m,a,e.DyCfx(r,h)),s>>>=8,h--}return e[l(638)](r,4)}function Ig(a,r){let s=t,l=0,h=r,m=e[s(1176)](r,4);for(;h<m;){let{value:b,offset:v}=Da(a,h);h=v,l=e[s(1567)](l,8)>>>0,l+=b}return{value:l,offset:m}}function Ag(a,r,s){let l=t,h=e[l(1608)].split("|"),m=0;for(;;){switch(h[m++]){case"0":if(r.utf8Write)return r[l(775)+"e"](a,s)+s;continue;case"1":if(r[l(579)])return e.WhtuM(r.write(a,s),s);continue;case"2":if(e[l(730)](a[l(368)],40))return e[l(237)](e.eLYge(Ta,a,r,s),s);continue;case"3":if(!a)return s;continue;case"4":return e.WkINT(e[l(566)](Ta,a,r,s),s)}break}}function kg(a,r){let s=t,l=new fe(e[s(592)](e[s(1293)](e.LLavI(e[s(561)](a[r+4],24),e.EtsIP(a[e[s(1230)](r,5)],16)),e[s(545)](a[e[s(237)](r,6)],8)),a[r+7]),e.OzGBR(e[s(581)](a[e[s(1621)](r,0)],24)|e[s(650)](a[e[s(512)](r,1)],16),e[s(1244)](a[e[s(312)](r,2)],8))|a[e[s(1115)](r,3)],!0);return r+=8,{value:l,offset:e[s(642)](r,8)}}function Tg(a,r,s){let l=t;if(e[l(1491)](e[l(713)],e[l(1435)]))return this[l(213)][l(1298)+"te"];{let h=a[l(239)],m=a.high;return r[s]=e.iNelF(m,24),r[s+1]=e.KswcW(e[l(1211)](m,16),255),r[e.jCeee(s,2)]=e[l(987)](m,8)&255,r[e[l(1225)](s,3)]=e[l(851)](255,m),r[e.DGIub(s,4)]=e[l(345)](h,24),r[e[l(1077)](s,5)]=h>>>16&255,r[s+6]=e[l(402)](e.EKzZs(h,8),255),r[e[l(988)](s,7)]=255&h,s+=8,s}}function Da(a,r){let s=t;return a.readUInt8?{value:a[s(1168)+"8"](r),offset:e[s(366)](r,1)}:{value:e[s(1503)](255,a[r]),offset:e[s(638)](r,1)}}function Pa(a,r,s){let l=t;return r[l(249)+"t8"]?r.writeUint8(a,s):r[s]=e[l(1204)](255,a),s+1}let Cg=function(a){return new Uint8Array(a)},Rg=e[t(1507)](e[t(597)],typeof Buffer)?Buffer["allocUns"+t(562)]:e[t(760)](bg,Cg,Uint8Array[t(954)+"e"][t(1194)]);(()=>{let a=t,r={AxwfL:a(1620)+"4|2|9|8|"+a(586)+"5",zslma:function(l,h){return l|h},oMwQH:function(l,h){return e.QjIfK(l,h)},dqmxk:function(l,h){return e[a(1617)](l,h)},dTDeI:function(l,h){return e[a(379)](l,h)},nKFVI:function(l,h){return e.tpuJO(l,h)},VFKAM:function(l,h){return e[a(546)](l,h)},LmcIW:function(l,h){return l<<h},ynceE:function(l,h){return e.EtoqA(l,h)},KDlym:function(l,h){return e.JKXnP(l,h)},WKyrz:function(l,h){return e[a(1116)](l,h)},NzbFH:function(l,h){return e.UJmTa(l,h)},aeOVC:function(l,h){return l>h},ReKSH:function(l,h){return e[a(930)](l,h)},PrHui:function(l,h){return e[a(391)](l,h)},ZnNNQ:function(l,h){return e[a(177)](l,h)},CgZhJ:function(l,h){return l<h},xrPAC:function(l,h){return e[a(227)](l,h)}},s=4294967295;return function(l,h,m=!0){let b=a,v=r.AxwfL.split("|"),g=0;for(;;){switch(v[g++]){case"0":if(l[h++]<128)return{value:m?s:r[b(1587)](0,s),offset:h};continue;case"1":s=r[b(1310)](r[b(1529)](127,l[h]),0);continue;case"2":if(r[b(678)](l[h++],128))return{value:m?s:r[b(1587)](0,s),offset:h};continue;case"3":if(r.nKFVI(l[h++],128))return{value:m?s:r[b(1348)](0,s),offset:h};continue;case"4":s=r[b(1310)](r[b(1587)](s,r[b(229)](r.ynceE(127,l[h]),14)),0);continue;case"5":return{value:m?s:0|s,offset:h};case"6":s=r.KDlym(r[b(661)](s,r.NzbFH(127&l[h],7)),0);continue;case"7":if(r.aeOVC(h+=5,l[b(368)]))throw h=l.length,vg(h,10,l.length);continue;case"8":if(l[h++]<128)return{value:m?s:r[b(1587)](0,s),offset:h};continue;case"9":s=r[b(304)](r[b(661)](s,r.PrHui(r[b(525)](127,l[h]),21)),0);continue;case"10":s=r.ZnNNQ(s,r[b(823)](15&l[h],28))>>>0;continue;case"11":if(r[b(575)](l[h++],128))return{value:m?s:r[b(733)](0,s),offset:h};continue}break}}})();let Dg=16,Oa=32;function Pg(a){let r=t,s=0,l={};for(let h=0;e[r(379)](h,a[r(368)]);h++)l[a[h][r(812)+r(1031)]]=Tl(a[h][r(812)+r(1031)]),s+=e[r(234)](14,l[a[h][r(812)+r(1031)]]);return[s,l]}function Ol(a,r,s){let l=t,[h,m]=Pg(a),b=e[l(971)](Rg,h),v=0;return a[l(633)](g=>{let C=l,L=e[C(1079)][C(639)]("|"),B=0;for(;;){switch(L[B++]){case"0":console[C(805)](e[C(337)],v);continue;case"1":v=e[C(1302)](Tg,fe[C(762)+"er"](g[C(803)]||r),b,v);continue;case"2":console[C(805)](e[C(1240)],v);continue;case"3":console.log(e.VvBpk,v);continue;case"4":console[C(805)]("name",v);continue;case"5":v=e[C(491)](Pa,m[g["cursor_n"+C(1031)]],b,v);continue;case"6":v=e[C(491)](Ag,g[C(812)+C(1031)],b,v);continue;case"7":v=Pa(0,b,v);continue;case"8":console[C(805)](C(827)+C(665),g,g.service);continue;case"9":console[C(805)](e.HFiQi,v);continue;case"10":v=e[C(931)](Sg,b,v,g.service||0);continue}break}}),{frameType:Oa,headers:[{key:e[l(1038)],value:s}],payload:b}}function Og(a){let r=t,s=0,l=[];for(;e.yuCgI(s,a[r(408)+"th"]);){let{offset:h}=Da(a,s);s=h;let m={cursor_name:"",cursor:0,service:0},{value:b,offset:v}=Ig(a,s);m[r(1296)]=b,s=v;let{value:g,offset:C}=e[r(1008)](Da,a,s);s=C,m["cursor_n"+r(1031)]=e[r(296)](Cl,a,s,e[r(248)](s,g)),s+=g;let{value:L,offset:B}=kg(a,s);m[r(803)]=L[r(864)](),s=B,l.push(m)}return l}function Lg(){let a=t;if(e[a(945)]("Fpqba",e[a(1479)]))return{frameType:Oa,headers:[{key:e[a(1038)],value:e[a(523)]}],payload:void 0};_0x111909=e[a(1200)](_0x63e95c,_0xea68e),_0x2a8ab8|=e.JRbzW(e.pdoOt(127,_0x576b64),21),e.uEtqr(128,_0x314130)&&(_0x16d07c=e.cxTlm(_0x2d97d7,_0x4f0ad6),_0x26b227=e[a(510)](127,_0x50f648),e[a(1596)](128,_0x3ff03f)&&(_0x12141b=e[a(698)](_0x31610e,_0x17d805),_0x56954a|=e[a(1248)](127,_0x896f7b)<<7))}class Ng{constructor(r,s,l){let h=t;this[h(302)+h(725)]=r,this[h(1626)+h(1337)]=s,this[h(209)+h(496)]=l,this[h(1111)]=e[h(350)](Dl,this[h(302)+h(725)],e[h(686)])}async[t(172)](){let r=t;await this[r(1111)][r(172)]()}async[t(1338)+"rs"](){let r=t;if(!this[r(1111)][r(824)])return;let s=this[r(209)+"Strategy"],l=await this[r(1111)][r(1234)]();switch(console[r(805)](r(1343)+r(245),l),s){case e[r(1169)]:return l&&l[r(368)]?e.ftIuC(Ol,l,0,this[r(1626)+r(1337)]):void 0;case r(194):return;case e[r(1409)]:return l&&l.length?e[r(574)](Ol,l,0,this[r(1626)+r(1337)]):Lg()}}async[t(770)](r,s,l){let h=t;return console[h(805)](h(421),r,s,l),this[h(1111)].set({cursor_name:r,cursor:s,service:l})}async[t(1006)+"rs"](r){let s=t,l=e.GjyEE(Og,r);for(let h of l)console[s(805)](e[s(476)],l),await this._qosDB.set(h)}async[t(1484)](r){let s=t;return(await this[s(1111)][s(1484)](r))?.cursor}async[t(1456)](){let r=t;await this[r(1111)][r(1456)]()}[t(1490)+t(173)+t(440)](r){let s=t;this[s(1626)+"ileName"]=r}get[t(824)](){let r=t;return this._qosDB[r(824)]}}let Mg=e[t(342)];async function Ll(a){let r=t;if(e.naLnK(e.dxvvB,e.dxvvB)){if(!this[r(1492)][r(1547)+"S"])return null;let{aID:s,fpID:l,messageStrategy:h}=this._options,m=e[r(1401)](a,Mg);try{return this[r(1102)+r(1292)]?a&&this[r(1102)+"anager"]["updateCu"+r(173)+r(440)](a):this["_cursorM"+r(1292)]=new Ng(l+"_"+s+"_"+m,m,h),this[r(1102)+"anager"][r(824)]||await this[r(1102)+"anager"][r(172)](),this[r(1102)+r(1292)]}catch{return null}}else _0x58d765[_0x3f7701++]=e.FvhJY(_0x31f008>>6,192),_0x2978a6[_0x382a53++]=e[r(1268)](63,_0x5e565a)|128}async function Bg(a,r){let s=t,l=e[s(931)](cn,a.message[s(521)],e[s(407)],"-1"),h=cn(a[s(1495)][s(521)],e[s(570)],"1"),m=e[s(821)](lr,a.message.headers,e[s(921)]),b=e[s(872)](Number,e[s(429)](lr,a.message[s(521)],e[s(1294)]))||0,v=Ra.call(this,a),g=cn(a[s(1495)][s(521)],s(773)+"s","2"),C=lr(a[s(1495)][s(521)],e[s(187)]),L=e[s(221)](Number,e[s(522)](lr,a.message[s(521)],e[s(1257)]));if(v.isQoSAck)return r();let B=v["isQoSMes"+s(255)]?await Pl[s(1382)](this):null;if(a[s(1495)].service>0&&h&&!l||a.message.service>0){if(m&&v[s(1082)+s(255)]&&B)return!!!await B[s(1484)](m)&&(this[s(825)+s(842)+s(1091)](a),await B.set(m,e[s(512)](Date.now(),b))),e[s(1451)](r);if(g)if(e[s(996)](e.HBixP,e[s(695)])){let G=await Ll[s(1382)](this);if(!G)if(e[s(655)](s(460),s(460))){let K={iLtRC:"error"},ge=_0x208ce3[s(386)][s(881)](_0x257bb3[s(1219)+"et"],_0x18c6c3[s(408)+"th"]+_0x1bd25f[s(1219)+"et"]);this[s(213)]&&this._socket[s(801)]({data:ge,fail:he=>{let ut=s;this[ut(1183)](K[ut(1002)],_0x125e7f(K[ut(1002)],{message:this[ut(1554)+ut(784)+ut(535)](he)}))}})}else return this["_dispatc"+s(842)+s(1091)](a),e[s(1223)](r);let Z=await G[s(1484)](C)??-1;if(Z<L)this[s(825)+s(842)+s(1091)](a),G[s(770)](C,L,a[s(1495)][s(1296)]);else throw new Error(s(643)+" message cursor "+L+(s(1540)+s(836)+s(1053)+"r ")+Z);return r()}else{e[s(1378)](_0x310e02,_0x4cba6e,42);let G=e[s(474)](_0x1c8db6);e[s(508)](_0x1d3e9c,_0xea36ab,G),e[s(272)](_0x25420b,_0x24aa3f,G[s(1318)]),e.UOqVi(_0x504c91,_0x1d2f67,G),e.dbKRx(_0x259263,G)}return this[s(825)+s(842)+"Event"](a),e[s(675)](r)}}async function Fg(a,r){let s=t,l=Ra[s(1382)](this,a);if(!l[s(1082)+s(255)])return e[s(882)](r);let h=await Pl[s(1382)](this);if(l["isAckCle"+s(1134)+s(535)]&&l[s(1253)+"s"][s(368)])for(let m of l[s(1253)+"s"])await h.del(m);r()}async function zg(a,r){let s=t,l=e[s(651)](a.message[s(1431)+"e"],Dg),h=e[s(1083)](a[s(1495)][s(1431)+"e"],Oa);if(!l&&!h)return e.tjMLm(r);let m=e[s(1030)](lr,a.message[s(521)],e.dwsqi);if(!m)return e[s(882)](r);let b=await Ll.call(this,m);if(!b)return e.tjMLm(r);if(l){let v=await b[s(1338)+"rs"](),g={frameType:v?.[s(1431)+"e"],SeqID:fe[s(762)+"er"](this[s(1381)]++),LogID:fe[s(762)+"er"](this._options[s(316)+"erator"]()),service:9e3,method:5,headers:v?.headers,payload:v?.[s(1019)]},C=S(g);this[s(1473)]&&this[s(1473)][s(1298)+"te"]&&this[s(1473)][s(801)](C)}if(h){let v=a[s(1495)][s(1019)];v&&b.setCursors(v)}}let Ug=async function(a,r){let s=t,l={ORMIp:function(h,m){return e[$(872)](h,m)},WsnGt:s(628)+"e_success"};e.LWQWj(s(1175),e[s(500)])?(l[s(1106)](_0x57543d,s(598)),this.off(l[s(453)],_0x14ac29),this[s(1155)](s(628)+s(418)+"t",_0x9b03c6)):(this._isInit=!1,e.dLJJp(clearTimeout,this["_connect"+s(178)+s(1095)]),e[s(785)](r))},Gg=async function(a,r){let s=t,l={LrFsk:function(b,v){return e.ZknWJ(b,v)},HEkmx:function(b,v){return b|v},xQuzh:function(b,v){return e.ONYIA(b,v)},XBWVu:function(b,v){return e.RoBQD(b,v)},QnuZp:function(b,v){return e[$(303)](b,v)}};if(!this._ws||e[s(256)](this._ws.readyState,this[s(1150)]))return e[s(916)](r);let{pingInterval:h}=this[s(1492)];this[s(1427)+s(1611)]?.[s(1186)+"pointCon"+s(1254)]();for(let b=0;e[s(1052)](b,this[s(209)+"Queue"][s(368)]);b++)if(e[s(1390)](e[s(977)],e[s(977)])){let v=this["_message"+s(186)][b];if(e[s(945)](this[s(1473)].readyState,this.OPEN)&&e[s(1407)](null,v))this[s(1473)]&&this[s(1473)][s(801)](v),this["_message"+s(186)][b]=null;else break}else return new _0x352db6(tXFKxL[s(591)](tXFKxL.HEkmx(tXFKxL.xQuzh(_0x31f7c7[4],24),_0xbe2334[5]<<16)|tXFKxL[s(802)](_0x44ab93[6],8),_0x55b978[7]),tXFKxL[s(1501)](tXFKxL[s(591)](tXFKxL[s(802)](_0x4f9ebc[0],24),tXFKxL[s(1016)](_0x2a8584[1],16))|_0x483d65[2]<<8,_0x5d1cbc[3]),_0x10e65f);this[s(209)+s(186)]=this[s(209)+"Queue"][s(1395)](b=>!!b),this["_pingPon"+s(587)+"Id"]=setTimeout(()=>this[s(583)](),h),this[s(825)+s(548)+"nt"](a),this[s(555)+"er"]&&this[s(1473)]&&(this[s(1473)][s(1033)+"pe"]=this[s(1601)+s(351)]);let m=this[s(1427)+s(1611)]?.[s(404)+s(704)+"nt"]();this[s(917)]("open "+m+s(741)),e[s(611)](r)},Hg=async function(a,r){let s=t,l=this[s(1427)+"tManager"]?.[s(404)+s(704)+"nt"]();this._debug(s(1428)+l),e[s(1387)](r)};class qg extends ka{constructor(r){let s=t,l={xjbzi:function(h,m){return e[$(953)](h,m)},zQDfW:s(693)+"reason",DbWqE:function(h,m){return e[s(336)](h,m)},zVbuD:function(h,m){return e[s(662)](h,m)},gIkLV:function(h,m){return e.XKFyC(h,m)},Xvlei:function(h,m){return h||m}};if(e[s(677)](s(929),e[s(511)]))_0x1435cc.body["removeCh"+s(1612)](_0x1b0e01),_0x48cd1e[s(634)+s(297)]=void 0,wpmctX[s(1207)](_0x171eb7,_0x36674f&&_0x56bde7[s(1123)]||wpmctX[s(1078)]);else{super(),this[s(1463)+s(1017)+s(818)]=!0,this[s(555)+"er"]=dr,this[s(1105)]=sg,this._isMiniTT=Nn,this._isMiniWX=si,this[s(1093)+"r"]=oi,this[s(209)+s(186)]=[],this[s(1427)+"tManager"]=null,this[s(1309)+s(367)]=!1,this[s(1601)+"ype"]=e[s(356)],this["_connect"+s(1369)]=!1,this[s(908)+"ionTimeo"+s(1095)]=null,this[s(1287)+"ctTimeou"+s(1060)]=null,this[s(942)+s(587)+"Id"]=null,this[s(1381)]=0,this[s(726)]=!1,this[s(1494)]="",this["_QoSMana"+s(1624)]=null,this[s(1102)+"anager"]=null,this[s(456)+s(526)]=null,this[s(1178)+"ls"]=s(1360),this[s(1004)]=3,this[s(952)+"NG"]=0,this[s(1150)]=1,this[s(318)]=2,this[s(788)]=v=>{let g=s;try{e[g(1160)](kl,this,v,[Ug,Gg,Hg])}catch(C){let L=e[g(242)](lt,e.tUsSO,{message:C.message,code:an[g(498)+"OR"],error:C});this[g(825)+g(1227)+g(1532)](L)}},this[s(1419)+"ge"]=async v=>{let g=s,{pingInterval:C,pingFrequency:L}=this._options;if((v[g(1022)]==="hi"&&e[g(576)](e[g(572)],L)||e[g(651)](g(1126),L))&&(this[g(170)+g(1089)](),this[g(1183)](e[g(321)],e[g(370)]),this[g(942)+g(587)+"Id"]=setTimeout(this[g(583)][g(251)](this),C)),!e.sqotw("hi",v[g(1022)]))try{e[g(259)](kl,this,v,[yg,wg,Fg,zg,Bg,_g])}catch(B){let G=e[g(406)](lt,e[g(911)],{message:B[g(1495)],code:an[g(1315)+"ERROR"],error:B});this[g(825)+g(1227)+g(1532)](G)}},this[s(524)]=v=>{let g=s,C={XqfnA:function(G,Z){return G===Z},ODwMl:e[g(519)]},L=this[g(1427)+g(1611)]?.[g(339)+g(278)+"es"](),B=this._endpointManager?.[g(404)+"ntEndpoint"]();if(L&&!v[g(1495)])if(e.dXtZv===e[g(332)]){let G=_0x241541(_0x525418);this[g(1473)]&&C.XqfnA(this[g(1473)][g(1298)+"te"],this.OPEN)&&(this[g(1473)]&&this[g(1473)][g(801)](G),this._debug(C[g(268)],_0x57c538))}else{let G=g(1058)+B+(g(1481)+g(1284)+g(1069)+"ed");this["_dispatc"+g(1227)+g(1532)](e.uSxVg(lt,e[g(911)],{message:G,code:an[g(1430)+g(585)+"R"],error:v}));return}this[g(1473)]&&this[g(1473)][g(1298)+"te"]===this.OPEN&&this._disconnect(),this["_dispatc"+g(1227)+"ent"](e[g(1018)](lt,e.tUsSO,{message:v[g(1495)],code:an[g(1383)+g(1007)],error:v}))},this[s(1325)]=async v=>{let g=s,C={oFuxH:function(L,B,G){return e.wWwhJ(L,B,G)},FKGAF:e[g(1447)]};if(e[g(996)]("Xvzjw",e.GMsQJ)){this[g(1549)+g(798)](),this[g(170)+g(1089)](),this[g(1214)+g(965)+"rs"](),this[g(1473)]=null,this[g(908)+g(1369)]=!1;let L=this._endpointManager?.[g(339)+g(278)+"es"]();if(!L&&this[g(873)+"orOnline"]()&&!this[g(1309)+g(367)]){let B=this[g(1427)+g(1611)]?.["getCurre"+g(704)+"nt"](),G=this[g(1492)][g(1336)+g(855)+g(1143)](v.code,v[g(529)]);this["_dispatc"+g(382)+g(1532)](wt(g(578),{code:1006,reason:v[g(529)]||"connecti"+g(610)+g(604)+g(1003)+"n, hostname: "+B,willReconnect:G})),G&&this[g(908)]();return}if(e[g(1087)](1e3,v[g(1588)])&&this[g(1309)+"osed"]){this[g(825)+g(382)+g(1532)](e[g(1332)](wt,e[g(1618)],{code:1e3,reason:e[g(1239)]})),this[g(1427)+g(1611)]?.["resetEnd"+g(1198)+g(1254)](),this[g(456)+"sCounter"]?.[g(389)+g(756)]();return}if(e[g(1510)](1e3,v[g(1588)])&&L){if(e[g(1190)](e[g(896)],e[g(896)]))return wpmctX[g(1485)](-1,this[g(239)])&&wpmctX[g(1485)](-1,this[g(830)])?_0x5bee10[g(1480)](0,0,this[g(1523)]):this.low===-1?_0x40123a[g(1480)](0,wpmctX[g(1209)](this[g(830)],1),this[g(1523)]):_0x21228a[g(1480)](wpmctX.gIkLV(this[g(239)],1),this.high,this[g(1523)]);{let B=this[g(1427)+"tManager"]?.[g(404)+g(704)+"nt"](),G=v.reason;G||(G=await e[g(244)](fg,this._url)),G=g(1080)+"ng faile"+g(1285)+G+(g(494)+g(1414))+B+(g(1394)+g(392)+g(1469)),this[g(825)+"hCloseEvent"](e[g(329)](wt,e.Spmlh,{code:v[g(1588)],reason:G}));let Z=g(1058)+B+(g(1481)+g(1284)+"es reached");this[g(825)+g(1227)+g(1532)](lt(e[g(911)],{message:Z,code:an["MAX_RETR"+g(585)+"R"]})),this[g(1427)+"tManager"]?.["resetEndpointCon"+g(1254)](),this[g(456)+g(526)]?.resetCounter();return}}if(e[g(1483)](1e3,v[g(1588)])&&!v.reason)if(g(275)!==e[g(605)]){let B=this[g(1427)+g(1611)]?.[g(404)+g(704)+"nt"]();this[g(825)+g(382)+g(1532)](e.YXZuH(wt,e[g(1618)],{code:v[g(1588)],reason:g(1080)+"ng faile"+g(604)+g(1003)+g(659)+g(745)+B})),this[g(1427)+g(1611)]?.["resetEnd"+g(1198)+"fig"](),this[g(456)+"sCounter"]?.[g(389)+"nter"]();return}else{let B=C[g(1137)](_0x2edfff,g(1336)+"t",{message:C.FKGAF});this[g(618)+"econnect"]&&this[g(618)+"econnect"](B)}this["_dispatc"+g(382)+g(1532)](v),this["_endpoin"+g(1611)]?.[g(1186)+g(1198)+g(1254)](),this._pingLossCounter?.["resetCou"+g(756)]()}else{let L=this[g(1111)][g(748)](this._prefix),B=_0x5cfd80[g(1371)](wpmctX.Xvlei(L,"{}"));return _0x4141ec[g(631)](B)}},this.onclose=null,this[s(1180)]=null,this[s(1135)+"e"]=null,this.onopen=null,this["onStartR"+s(1454)]=null,this[s(668)+"eAck"]=null,this[s(927)+s(669)+s(411)+"ct"]=null,this[s(1199)+s(909)]=this[s(1199)+s(909)][s(251)](this),this["_handleO"+s(1165)]=this[s(1199)+s(1165)][s(251)](this),this["_handleP"+s(708)]=this[s(1277)+s(708)].bind(this),this._handlePageShow=this[s(1277)+s(1334)][s(251)](this),this[s(1492)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e.WWcBi(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(1154)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1409)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:m}=r,b=Array[s(1039)](h)?h:e[s(999)](e[s(1538)],typeof h)?[h]:[];if(!b||b[s(368)]===0)throw new Error("please provide valid url");if(!cg(m))throw new Error(e[s(252)]);if(Object.assign(this[s(1492)],r),this[s(1427)+s(1611)]=new Al(b,this[s(1492)][s(1498)+"es"]),this[s(456)+s(526)]=new ug(this[s(1492)][s(1013)+s(559)]),this[s(1492)][s(1472)+s(372)]&&(this[s(726)]=!0,this[s(908)]()),this[s(1492)]["listenNe"+s(479)+s(1531)])if(e[s(1483)](e[s(444)],e[s(444)])){let v=this[s(1111)].getStorageInfoSync(this[s(319)]),g=_0x477c86[s(1371)](e[s(1127)](v,"{}"));return _0x2755dc[s(852)](g)}else this[s(1614)+"T"]||this[s(1146)+"X"]?this[s(428)+s(308)+s(670)]():this[s(555)+"er"]&&this[s(1462)+s(1203)+"Listener"]()}}["_handleO"+t(909)](){let r=t,s={oqwYH:function(l,h){return e.qBmiT(l,h)}};if(e.poDMn(e[r(543)],e.fFtRb)){if(this[r(1492)][r(712)+r(537)+"nect"]||this[r(1309)+"osed"])return;this[r(1429)+r(1454)]()}else{let l=this[r(1111)][r(692)+r(362)+"nc"](this[r(319)]),h=_0x57bff8[r(1371)](wegkDN[r(1530)](l,"{}"));return _0x11d79d[r(631)](h)}}[t(1199)+t(1165)](){let r=t;this["_destroy"+r(1144)+"t"]();let s=e.IXaYx(Aa,e[r(431)],{message:e[r(285)]});this[r(927)+r(669)+r(411)+"ct"]&&this[r(927)+r(669)+r(411)+"ct"](s)}[t(1462)+t(1203)+"Listener"](){let r=t;this[r(555)+"er"]&&window[r(1625)+r(1363)](e[r(260)],this._handleOnLine),this[r(555)+"er"]&&window[r(1625)+r(1363)](r(1245),this["_handleO"+r(1165)]),this._isBrowser&&window["addEvent"+r(1363)](e.bdMdp,this[r(1277)+r(708)]),this._isBrowser&&window[r(1625)+r(1363)](e[r(365)],this[r(1277)+"ageShow"])}[t(290)+t(1203)+"Listener"](){let r=t;this[r(555)+"er"]&&window[r(1347)+r(649)+"ner"](e.ToFFp,this[r(1199)+r(909)]),this[r(555)+"er"]&&window[r(1347)+r(649)+r(1236)](e[r(660)],this[r(1199)+r(1165)]),this[r(555)+"er"]&&window[r(1347)+r(649)+r(1236)](e[r(1505)],this["_handleP"+r(708)]),this[r(555)+"er"]&&window[r(1347)+r(649)+r(1236)](e[r(365)],this[r(1277)+r(1334)])}[t(1277)+t(708)](r){let s=t;!r.persisted&&(this[s(555)+"er"]&&window["removeEv"+s(649)+s(1236)](e.bdMdp,this[s(1277)+"ageHide"]),this[s(555)+"er"]&&window[s(1347)+s(649)+s(1236)]("pageshow",this._handlePageShow),this[s(578)]()),this[s(555)+"er"]&&window[s(1347)+"entListe"+s(1236)](e.ToFFp,this["_handleO"+s(909)]),this[s(555)+"er"]&&window[s(1347)+"entListe"+s(1236)](e[s(660)],this[s(1199)+s(1165)])}[t(1277)+t(1334)](r){let s=t;r[s(228)+"d"]&&(this[s(873)+s(870)]()&&(!this[s(1473)]||e[s(1345)](this[s(1473)][s(1298)+"te"],this[s(1150)])||this[s(1473)][s(1298)+"te"]!==this.CONNECTING)&&this[s(1199)+"nLine"](),this[s(555)+"er"]&&window["addEvent"+s(1363)](e[s(260)],this[s(1199)+"nLine"]),this[s(555)+"er"]&&window[s(1625)+s(1363)](e[s(660)],this[s(1199)+s(1165)]))}async[t(960)+t(1314)](r){let s=t,l={REkbF:function(Mn,dn,ms,$g){return e[$(322)](Mn,dn,ms,$g)}},{fpID:h,deviceID:m,bddID:b,ttwID:v,accessKey:g,aID:C,customParams:L={},enableAutoAck:B,enableQoS:G,QoSLevel:Z,env:K}=this[s(1492)],ge,he,ut;if(this[s(555)+"er"]||this[s(1146)+"X"]||this[s(1614)+"T"]){if(e.oatwL(e[s(1040)],e[s(1040)]))throw _0x56a318=_0x2c6c9b[s(368)],tHTJWJ[s(1065)](_0x3b820b,_0x3035b1,10,_0x1d73cf.length);ge=location&&e[s(1467)](s(235),location[s(998)])?e[s(558)]:e[s(503)],he=r[s(732)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),ut=/^wss(.*:\/\/)/[s(1181)](r)?r:""+ge+he}else if(e[s(1379)]!==e.KRcNN){let Mn=this[s(209)+s(186)][s(340)]((dn,ms)=>(dn+=ms&&ms.byteLength||0,dn),0);return e[s(1115)](Mn,this[s(1473)]?this._ws[s(309)+s(1578)]:0)}else ge=e.ARtFl,he=r[s(732)](/(^http)((?:[s]*:\/\/))/,""),ut=/(^ws)((?:[s]*:\/\/))/[s(1181)](he)?he:""+ge+he;let ai=b?e[s(637)]:v?e[s(258)]:"device_id",gs=b||v||m;if(e.dGLLa(!gs,!ai))throw new Error(e[s(720)]);let jg=e[s(968)](e[s(262)],typeof L)?await e[s(201)](L):L,Wg=K?e[s(596)](lg,K[s(1026)],K[s(232)]):{},La=Object[s(1597)]({device_platform:s(1197),version_code:e[s(1220)],access_key:g,fpid:h,aid:C,[ai]:gs,xsack:B?1:0,xaack:B?1:0,xsqos:G?1:0,qos_level:G?Z:void 0,qos_sdk_version:2,...Wg},jg),Kg=Object[s(852)](La)[s(340)]((Mn,dn)=>La[dn]!==void 0?""+Mn+(Mn?"&":"?")+dn+"="+La[dn]:Mn,"");return ut+s(397)+Kg}async[t(908)](){let r=t;if(!(this[r(908)+r(1369)]||this[r(1309)+r(367)])){this[r(908)+r(1369)]=!0;try{let s=this[r(1427)+r(1611)]?.[r(410)+r(1064)+r(1546)+r(706)+r(1353)](),{timeoutInterval:l}=this._options;if(s){let m=this[r(1427)+"tManager"]?.[r(404)+r(704)+"nt"](),b=this[r(1427)+r(1611)]?.[r(1458)+r(933)+r(1357)+r(401)+r(1015)](),v=this[r(1427)+r(1611)]?.[r(404)+r(704)+"ntTriesC"+r(1328)]();if(b){let g=r(1058)+m+(" timeout"+r(1394)+"tries reached, w"+r(1130)+r(188)+r(1109))+b+(r(910)+"y"),C=lt(r(253),{message:g,code:an[r(1430)+r(585)+"R"]});this._debug(g),this[r(825)+"hErrorEv"+r(1532)](C),this[r(1494)]=await this["_generat"+r(1314)](b),this[r(917)](r(1058)+b+" "+v+" times"),this[r(1214)+r(965)+"rs"]()}else{let g=r(1058)+m+(" timeout, max retries re"+r(1469));this[r(917)](g),this[r(825)+r(1227)+r(1532)](e[r(1195)](lt,e[r(911)],{message:g,code:an["MAX_RETR"+r(585)+"R"]}));return}}else{let m=this._endpointManager?.[r(404)+r(704)+r(202)+"ateCount"](),b=this[r(1427)+r(1611)]?.["getCurre"+r(704)+r(1592)+r(1328)]();this[r(1494)]=await this[r(960)+r(1314)](e[r(1297)](m,"")),this[r(917)]("connect "+m+" "+b+r(1100)),this[r(1214)+r(965)+"rs"]()}if(this[r(726)])this[r(726)]=!1;else{let m=e.xErzy(Aa,e[r(431)],{message:e[r(1447)]});this.onStartReconnect&&this["onStartR"+r(1454)](m)}let h=this[r(1427)+r(1611)]?.["getCurre"+r(704)+r(1592)+"ount"]()||0;h>1&&await this._wait(e[r(635)](h,1)),this[r(917)](r(1080)+r(771)+this[r(1494)]+(" protoco"+r(976))+this._protocols),this[r(1473)]=e.bDHaC(ag,{url:this[r(1494)],protocols:[this[r(1178)+"ls"]],headers:this[r(1492)][r(672)+r(241)+"s"][r(459)+r(299)]},this[r(1492)].ws),(this[r(555)+"er"]||this[r(1093)+"r"])&&this._ws&&(this._ws[r(1033)+"pe"]=this[r(1601)+r(351)]),this[r(1212)+r(532)](),this[r(908)+"ionTimeo"+r(1095)]=setTimeout(this[r(1242)+"ut"][r(251)](this),l)}catch(s){throw this["_connect"+r(1369)]=!1,s}}}["_clearTi"+t(798)](){let r=t;e[r(1443)](clearTimeout,this[r(908)+r(178)+r(1095)]),this[r(908)+"ionTimeo"+r(1095)]=null}[t(170)+"ngTimer"](){let r=t;e[r(215)](clearTimeout,this[r(942)+r(587)+"Id"]),e[r(766)](clearTimeout,this[r(1287)+r(845)+r(1060)]),this[r(942)+r(587)+"Id"]=null,this[r(1287)+r(845)+r(1060)]=null}[t(917)](...r){let s=t;this[s(1492)].debug&&console[s(805)][s(790)](console,[s(1370)+">",...r])}[t(1558)+t(301)+"e"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:m}=this[s(1492)],b=l*Math.pow(m,e[s(423)](r,1));return e[s(1609)](b,h)?h:b}[t(583)](){let r=t,s={kPPAb:function(l,h){return l<h},bYvWM:function(l,h){return l===h}};if(this._ws&&this[r(1473)][r(1298)+"te"]===this.CONNECTING)if(e[r(758)](e[r(1029)],r(1536))){this[r(170)+r(1089)](),this[r(942)+r(587)+"Id"]=setTimeout(this[r(583)][r(251)](this),this._options["pingInte"+r(452)]);return}else{let l=this[r(180)+"rs"][_0x27b279];if(l)for(let h=0;Hqjkiu[r(1610)](h,l[r(368)]);)Hqjkiu.bYvWM(l[h].fn,_0x42130c)?l.splice(h,1):++h}if(!this._ws||this._ws.readyState!==this[r(1150)])return void this[r(1429)+"econnect"]();this[r(1473)]&&this[r(1473)][r(801)]("hi"),this[r(1287)+r(845)+r(1060)]=e.pKBkt(setTimeout,this[r(1429)+r(1454)+r(1619)][r(251)](this),this[r(1492)][r(536)+"outInter"+r(1205)])}[t(1429)+t(1454)+t(1619)](){let r=t;this[r(456)+r(526)]?.addCount(),this[r(1183)](e.rYehm,r(598)),this["_pingLos"+r(526)]?.[r(339)+r(1023)+"nt"]()?this["_handleR"+r(1454)]():this[r(583)]()}[t(873)+"orOnline"](){let r=t;return this[r(1614)+"T"]||this[r(1146)+"X"]?this[r(1463)+r(1017)+"line"]:(this[r(555)+"er"]||this[r(1093)+"r"])&&this._options[r(1482)+r(479)+r(1531)]?navigator[r(1047)]:!0}[t(1429)+"econnect"](){let r=t;!this[r(873)+"orOnline"]()||this[r(1309)+r(367)]||(this[r(1427)+r(1611)]?.[r(1186)+r(1198)+r(1254)](),this[r(456)+r(526)]?.["resetCou"+r(756)](),this[r(1473)]?this[r(331)+r(1262)](1001,e[r(1329)],!0):this[r(908)]())}[t(428)+"etWorkCh"+t(670)](){let r=t,s={yTGIO:function(l,h){return e[$(642)](l,h)},aKfvM:function(l,h){return l(h)},tqiZS:function(l,h,m){return e[$(329)](l,h,m)},wPNij:function(l,h){return l!==h},oFpYs:r(1496),tOpvY:r(192)};e[r(1340)](r(250),e[r(238)])?(_0x36155d=e[r(617)](31,_0x3d011e)<<6|e.IUKrD(63,_0x4c8831),e[r(376)](_0x5d1153,128)?_0x1fdd89+=_0x477efe:(_0x381de9+=e[r(1350)](_0x4d4102,_0x4ef24e),_0x5aac44++)):this._isMiniTT?tt[r(948)+r(261)+"hange"](({isConnected:l})=>{let h=r,m={WMOTX:function(b,v){return s[$(348)](b,v)},MsjHd:function(b,v){return s[$(1327)](b,v)},PhuQL:function(b,v,g){return s[$(1067)](b,v,g)}};if(s[h(1385)]("qLYnA",s[h(862)]))return DrqUZM[h(1375)](DrqUZM[h(328)](_0x116c9f,8)[h(1121)]("0"),DrqUZM[h(606)](_0x5d9e83,_0x167398,10)[h(616)](2))[h(881)](-8);this[h(1463)+h(1017)+h(818)]=l,l?this[h(1199)+h(909)]():this[h(1199)+"ffLine"]()}):this._isMiniWX&&wx[r(948)+r(261)+r(666)](({isConnected:l})=>{let h=r;s[h(1385)](s[h(1574)],s[h(1574)])?this[h(1266)+"ired"]():(this[h(1463)+h(1017)+h(818)]=l,l?this[h(1199)+h(909)]():this[h(1199)+h(1165)]())})}[t(211)](r){let s={WGaMV:function(l,h,m){return e[$(1441)](l,h,m)}};return new Promise(l=>{let h=$;s[h(1589)](setTimeout,l,this[h(1558)+h(301)+"e"](r))})}[t(331)+t(1262)](r=1e3,s="",l=!1){let h=t;if(e.oLEYR(e[h(674)],e[h(674)]))return 0;if(!this[h(1473)])return;this[h(477)+h(1144)+"t"](r,s,l)}[t(1242)+"ut"](){let r=t,s=this[r(1427)+r(1611)]?.getCurrentEndpoint();this[r(917)](r(1058)+s+" timeout"),this[r(331)+r(1262)](1001,r(1561)+r(556)+"onnecting",!0)}[t(1256)](r){let s=t,l=e[s(475)](Ht,r);this[s(1473)]&&e[s(576)](this[s(1473)][s(1298)+"te"],this.OPEN)&&(this[s(1473)]&&this._ws[s(801)](l),this._debug("send_ack",r))}[t(1214)+t(965)+"rs"](){let r=t,s=e.qbmlS[r(639)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1473)][r(1347)+r(649)+r(1236)](e.tUsSO,this[r(524)]);continue;case"1":this._ws[r(1347)+r(649)+r(1236)](e[r(280)],this[r(788)]);continue;case"2":this[r(1473)][r(1347)+"entListe"+r(1236)](e[r(1618)],this[r(1325)]);continue;case"3":this[r(1473)][r(1347)+"entListe"+r(1236)]("message",this[r(1419)+"ge"]);continue;case"4":if(!this[r(1473)])return;continue}break}}["_addWsLi"+t(532)](){let r=t,s=e.zNMwI[r(639)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1473)]["addEvent"+r(1363)](e[r(787)],this[r(1419)+"ge"]);continue;case"1":this[r(1473)][r(1625)+r(1363)](e.tUsSO,this._onError);continue;case"2":this._ws[r(1625)+r(1363)](r(168),this._onOpen);continue;case"3":if(!this._ws)return;continue;case"4":this[r(1473)][r(1625)+r(1363)](e.Spmlh,this[r(1325)]);continue}break}}["_wsInsta"+t(765)](r=1e3,s=""){let l=t,h={AKusE:e[l(513)]};if(e[l(996)](e[l(415)],e[l(415)]))try{this[l(1473)]&&this[l(1473)][l(578)](r,s)}catch{}else _0x32bc9b["frontier"+l(297)]=void 0,_0x5e724e(ugMsLx.AKusE)}[t(477)+t(1144)+"t"](r=1e3,s="",l=!1){let h=t;if(this["_clearPi"+h(1089)](),this["_clearTi"+h(798)](),this[h(1214)+h(965)+"rs"](),this._wsInstanceClose(1e3,s),this[h(908)+h(1369)]=!1,l&&this._navigatorOnline()&&!this[h(1309)+h(367)]){if(this[h(1427)+h(1611)]?.[h(339)+"chMaxTries"]()){let b=this[h(1427)+"tManager"]?.[h(404)+h(704)+"nt"]();this["_dispatc"+h(382)+h(1532)](e[h(483)](wt,e[h(1618)],{code:1006,reason:h(1058)+b+(h(1352)+h(1394)+"tries re"+h(1469)),wasClean:!0}))}else{let b=this[h(1492)]["reconnec"+h(855)+"ptor"](r,s);this[h(825)+h(382)+h(1532)](wt(e.Spmlh,{code:r,reason:s,wasClean:!0,willReconnect:b})),b&&this._connect()}return}this[h(873)+h(870)]()||this._readyClosed?this[h(825)+h(382)+h(1532)](e.jnClp(wt,e[h(1618)],{code:r,reason:e.bnFcw})):this[h(825)+h(382)+"ent"](e.MJqOG(wt,h(578),{code:1006,reason:"going aw"+h(360)+h(437)+"ine"})),this._ws=null,this[h(1427)+h(1611)]?.[h(1186)+h(1198)+"fig"](),this["_pingLos"+h(526)]?.[h(389)+h(756)]()}[t(825)+t(548)+"nt"](r){let s=t;this[s(1183)](e[s(280)],r),this.onopen&&this[s(1606)](r)}[t(825)+"hMessageEvent"](r){let s=t,l={jaChq:function(h,m){return e.cdYES(h,m)}};if(e[s(1237)](e[s(1305)],e[s(1305)]))return _0xef5624&&IoOIyq[s(1149)](!0,_0x25e183[s(1191)]);this[s(1183)](e[s(787)],r),this[s(1135)+"e"]&&this[s(1135)+"e"](r)}[t(825)+t(934)+t(1461)](r){let s=t;e.kijeB(e[s(1042)],e[s(1042)])?(_0x5417fe-=65536,_0xda00f7+=_0x1f2933((_0x5e8652>>10)+55296,e[s(928)](e.SwbZi(1023,_0x56a187),56320)),_0x388aed+=3):(this[s(1183)](e.tkECa,r),this[s(668)+s(724)]&&this[s(668)+s(724)](r))}[t(825)+t(1227)+t(1532)](r){let s=t;this[s(1183)](e[s(911)],r),this.onerror&&this[s(1180)](r)}[t(825)+"hCloseEv"+t(1532)](r){let s=t;this.emit(e[s(1618)],r),this.onclose&&this[s(816)](r)}get[t(1033)+"pe"](){let r=t;if(e[r(270)](r(1192),e[r(1470)])){let{pingInterval:s,pingFrequency:l}=this._options;if((e[r(374)]("hi",_0x3e0292[r(1022)])&&e[r(758)](e.pwpFw,l)||e[r(374)](e[r(1154)],l))&&(this[r(170)+r(1089)](),this[r(1183)]("ping_onc"+r(753)+"s",e[r(370)]),this["_pingPon"+r(587)+"Id"]=e[r(1389)](_0x1c669a,this[r(583)][r(251)](this),s)),_0xafc786[r(1022)]==="hi")return;try{e[r(347)](_0x4d2fa4,this,_0xc9305e,[_0x4a44e0,_0x39d0c0,_0x16233a,_0x11555f,_0x57dce7,_0x258b14])}catch(h){let m=e[r(1008)](_0x176b1b,e.tUsSO,{message:h.message,code:_0x3e09e5.MESSAGE_ERROR,error:h});this[r(825)+r(1227)+"ent"](m)}}else return this[r(1473)]?this._ws[r(1033)+"pe"]:this[r(1601)+r(351)]}set[t(1033)+"pe"](r){let s=t,l={Grrms:function(h,m){return e[$(1570)](h,m)},GQJQy:function(h,m){return e[$(1474)](h,m)},GrIbH:function(h,m){return h instanceof m},IZYJi:function(h,m,b){return e[$(1195)](h,m,b)},QnYYE:function(h){return e[$(882)](h)}};if(e[s(226)](e.iPYDT,s(1120)))this._binaryType=r,this._ws&&(this[s(1473)][s(1033)+"pe"]=r);else return FwQpIw[s(1416)](typeof _0x3c7bc5,s(904))?FwQpIw[s(1238)](_0x526135,_0x122561):(FwQpIw[s(1476)](_0x503fe0,_0x43e033)&&FwQpIw[s(1238)](_0x1238db,_0x4bfe1e),FwQpIw[s(1468)](_0xfdab18,_0x4b0128,FwQpIw[s(263)](_0x3008ce))?new _0x5b782b(_0x3fa391,_0x454f6e):_0x1247e9)}get[t(854)+"nt"](){let r=t;return this._endpointManager?.["getCurrentEndpointTriesC"+r(1328)]()||0}get[t(309)+t(1578)](){let r=t,s=this[r(209)+r(186)].reduce((l,h)=>(l+=h&&h[r(408)+"th"]||0,l),0);return e[r(1115)](s,this[r(1473)]?this._ws[r(309)+r(1578)]:0)}get[t(1101)+"ns"](){let r=t;return this[r(1473)]?this[r(1473)][r(1101)+"ns"]:""}get[t(998)](){let r=t;return this[r(1473)]?this[r(1473)].protocol:""}get[t(1298)+"te"](){let r=t;return this[r(1473)]?this[r(1473)][r(1298)+"te"]:this[r(1492)][r(1472)+r(372)]?this.CONNECTING:this[r(1004)]}get[t(527)](){let r=t;return this._ws?this._ws[r(527)]:this._url}close(r=1e3,s){let l=t,h=e[l(184)][l(639)]("|"),m=0;for(;;){switch(h[m++]){case"0":this[l(1309)+l(367)]=!0;continue;case"1":this._clearTimer();continue;case"2":this[l(477)+l(1144)+"t"](r,s);continue;case"3":if(this[l(1473)][l(1298)+"te"]===this[l(1004)]||e[l(1213)](this[l(1473)][l(1298)+"te"],this[l(318)]))return void this[l(917)](e[l(463)]);continue;case"4":this[l(828)+l(1624)]?.[l(1456)]();continue;case"5":this[l(170)+l(1089)]();continue;case"6":if(!this[l(1473)])return void this[l(917)](e.TJXSH);continue;case"7":this[l(290)+l(1203)+l(1363)]();continue}break}}async send(r,s){let l=t;if(r==null)throw new Error(e[l(1215)]);e[l(1467)](e[l(1566)],typeof r)&&(r=JSON[l(1044)+"y"](r)),e[l(1507)](e[l(1538)],typeof r)&&!(r instanceof ArrayBuffer)&&!(r[l(386)]&&r[l(386)]instanceof ArrayBuffer)&&(r=JSON.stringify(r));let h=await e[l(1406)](Rl,r),m=dg(r),{method:b=0,service:v=this._options.service,logID:g=this[l(1492)][l(316)+l(1488)](),headers:C=this[l(1492)][l(521)],payloadEncoding:L=this._options[l(1442)+l(1136)],payloadType:B=this._options[l(446)+l(351)],logIDNew:G=this[l(1492)][l(919)+l(782)][l(487)+"toGenera"+l(1275)+"ew"]?i(this[l(1492)]["logIDNew"+l(782)][l(422)]):""}=e[l(1228)](s,{});if(!v)throw new Error(l(269)+l(783)+" valid s"+l(665));let Z={SeqID:fe.fromNumber(this[l(1381)]++),LogID:fe.fromNumber(g),service:v,method:b,headers:C,payloadEncoding:e[l(879)](L,Object)?L[l(1096)]?L[l(1096)]:"":L,payloadType:e[l(1405)](B,Object)?B[l(1216)]?B[l(1216)]:m:B||m,payload:h,LogIDNew:G},K=Ht(Z);return this[l(1473)]&&e[l(207)](this._ws[l(1298)+"te"],this[l(1150)])?(this[l(1473)]&&this._ws[l(801)](K),this[l(917)](l(1162),Z)):e.WbOTR(this[l(209)+l(186)][l(368)],this[l(1492)][l(702)+l(171)+l(777)])?(this[l(209)+l(186)][l(612)](K),this[l(917)](e.OlSLV,Z)):(this[l(209)+l(186)][l(254)](),this[l(209)+l(186)][l(612)](K)),{seqID:this[l(1381)],logID:g,logIDNew:G}}async[t(1336)+"t"](r){let s=t;if(e[s(383)](e.zTFIA,e.zTFIA)){let{url:l}=r||{},h=Array[s(1039)](l)?l:e.sYpmu(e[s(1538)],typeof l)?[l]:[];r&&Object[s(1597)](this[s(1492)],r),h&&h.length?this[s(1427)+"tManager"]=new Al(h,this[s(1492)][s(1498)+"es"]):this["_endpoin"+s(1611)]?.resetEndpointConfig(),this["_pingLos"+s(526)]?.resetCounter(this[s(1492)][s(1013)+"Count"]),this["_readyCl"+s(367)]=!1,this[s(1473)]&&e[s(1450)](this[s(1473)][s(1298)+"te"],this[s(1004)])?this[s(331)+s(1262)](1e3,e[s(495)],!0):(this[s(726)]=!0,this[s(908)]())}else this[s(302)+s(725)]=_0x4e29aa,this[s(1626)+s(1337)]=_0x4b5d8b,this[s(209)+"Strategy"]=_0x44a5f9,this[s(1111)]=e[s(1133)](_0x3773d0,this[s(302)+s(725)],e[s(686)])}async[t(888)](){let r=t;!this._connectLock&&(this[r(1427)+r(1611)]?.[r(1186)+"pointCon"+r(1254)](),this[r(456)+"sCounter"]?.[r(389)+r(756)](),this[r(1309)+r(367)]=!1,this[r(726)]=!0,this[r(908)]())}[t(1625)+t(1363)](r,s){this.on(r,s)}[t(991)+t(1091)](r){let{type:s}=r;this.emit(s,r)}[t(1347)+"entListe"+t(1236)](r,s){this[t(1155)](r,s)}[t(381)](){let r=t,s={mRkXo:function(l,h,m){return e.zwKNp(l,h,m)},iJFBN:function(l,h){return l>>>h},FsKST:function(l,h){return e.AiDyO(l,h)},ACMIV:function(l,h){return l(h)},BHcXu:e[r(370)],iDqSm:e[r(321)],FuQHV:e[r(439)],Yihyl:e.TvtOM,xQhrq:function(l,h,m){return l(h,m)}};if(e.MTucG(e[r(736)],e[r(736)])){let l=0,h=_0x2eb375,m=_0x4e95ff+4;for(;h<m;){let{value:b,offset:v}=JUoMSr[r(484)](_0x27113c,_0x4e3d72,h);h=v,l=JUoMSr[r(781)](JUoMSr[r(814)](l,8),0),l+=b}return{value:l,offset:m}}else return new Promise((l,h)=>{let m=r;this["_clearPi"+m(1089)](),this["_pingPon"+m(587)+"Id"]=s[m(1188)](setTimeout,this._ping[m(251)](this),this[m(1492)][m(1201)+m(452)]);let b=()=>{let g=m;s[g(1068)](l,s.BHcXu),this[g(1155)](s[g(711)],b),this[g(1155)](s[g(352)],v)},v=()=>{let g=m;s[g(1068)](h,s.Yihyl),this.off(s.iDqSm,b),this[g(1155)](s[g(352)],v)};this.on(s.iDqSm,b),this.on(s[m(352)],v),this[m(583)]()})}}})(),ze[N(1261)+N(183)]=Oe[N(1261)+N(183)],ze[N(877)+N(378)]=Oe[N(877)+"rorEvent"],ze[N(205)+"e"]=Oe.ErrorCode,ze.Event=Oe[N(1091)],ze.FWS=Oe[N(550)],ze[N(1391)+"MessageE"+N(1460)]=Oe[N(1391)+N(735)+N(1460)],ze[N(735)+N(1460)]=Oe["MessageE"+N(1460)],ze.OpenEvent=Oe.OpenEvent,ze["Reconnec"+N(1534)]=Oe[N(632)+N(1534)],ze[N(595)+N(183)]=Oe["createCl"+N(183)],ze["createEr"+N(378)]=Oe[N(1544)+N(378)],ze[N(1591)+N(549)+"nt"]=Oe[N(1591)+N(549)+"nt"],ze[N(874)+N(653)]=Oe[N(874)+N(653)],ze[N(403)+N(690)+N(1460)]=Oe[N(403)+N(690)+N(1460)],ze[N(696)+"rame"]=Oe[N(696)+N(1604)],ze[N(912)+N(1031)]=Oe["encodeFr"+N(1031)];for(ra in Oe)["CustomCl"+N(183),N(877)+"rorEvent","ErrorCode","Event",N(550),N(1391)+"MessageE"+N(1460),N(735)+N(1460),N(1423)+"t",N(632)+"tEvent","createCl"+N(183),N(1544)+N(378),N(1591)+N(549)+"nt",N(874)+N(653),N(403)+N(690)+N(1460),"decodedF"+N(1604),"encodeFrame"][N(861)](ra)===-1&&(ze[ra]=Oe[ra]);var ra;Object[N(281)+N(1368)](ze,N(1380)+"le",{value:!0})});import{existsSync as D1,openSync as P1}from"node:fs";import{mkdir as O1}from"node:fs/promises";import{dirname as L1}from"node:path";import{fileURLToPath as N1}from"node:url";function B1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function il(t=J()){return D1(t.libEntry)?t.libEntry:N1(new URL("../index.ts",import.meta.url))}async function gp(t={}){let e=t.paths??J(),n=t.entryOverride??il(e),i=B1(e,process.env.COZE_BRIDGE_LOG_MODE);await O1(L1(i),{recursive:!0});let o=P1(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=st(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[us]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return M1.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var M1,us,xa=nt(()=>{"use strict";Yt();ie();De();M1=H("spawn-daemon"),us="COZE_BRIDGE_DAEMON"});import{spawn as LI}from"node:child_process";import{mkdir as NI,unlink as MI,writeFile as BI}from"node:fs/promises";import{dirname as FI,join as zI}from"node:path";function ni(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function UI(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${ni(n)}</key>
21
+ <string>${ni(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function R2(t,e){return new Promise((r,i)=>{let o=v2(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var Xr,ls,ha,dl,Np=et(()=>{"use strict";ne();Xr=H("supervisor.launchd"),ls="ai.coze.bridge",ha=R2,dl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function GI(t,e){return new Promise((n,i)=>{let o=LI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var ti,xs,ya,hl,zp=nt(()=>{"use strict";ie();ti=H("supervisor.launchd"),xs="ai.coze.bridge",ya=GI,hl={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>${ls}</string>
31
+ <string>${xs}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Qr(t.nodeBin)}</string>
35
- <string>${Qr(t.entry)}</string>
34
+ <string>${ni(t.nodeBin)}</string>
35
+ <string>${ni(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>${Qr(t.logFile)}</string>
45
+ <string>${ni(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Qr(t.logFile)}</string>${C2(t.env)}
47
+ <string>${ni(t.logFile)}</string>${UI(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return T2(t.homeDir,"Library","LaunchAgents",`${ls}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await S2(k2(i),{recursive:!0}),await A2(i,this.renderConfig(t),"utf8"),Xr.info("plist written",{plistPath:i,activate:r}),!r)return;await ha("launchctl",["unload","-w",i]).catch(c=>Xr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ha("launchctl",["load","-w",i]),Xr.info("launchd job loaded",{label:ls});let o=process.getuid?.()??0;await ha("launchctl",["kickstart","-k",`gui/${o}/${ls}`]),Xr.info("launchd job kickstarted",{label:ls,uid:o})},async uninstall(t){let e=this.configPath(t);await ha("launchctl",["unload","-w",e]).catch(r=>Xr.warn("launchctl unload failed (ignored)",{err:String(r)})),await I2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Xr.info("launchd job removed",{plistPath:e})}}});import{spawn as D2}from"node:child_process";import{mkdir as P2,unlink as O2,writeFile as L2}from"node:fs/promises";import{dirname as N2,join as Mp}from"node:path";function pa(t,e){return t.isRoot?e:["--user",...e]}function B2(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function ga(t,e){return new Promise((r,i)=>{let o=D2(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var xa,ei,M2,ll,Bp=et(()=>{"use strict";ne();xa=H("supervisor.systemd"),ei="coze-bridge.service",M2="/etc/systemd/system";ll={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return zI(t.homeDir,"Library","LaunchAgents",`${xs}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await NI(FI(i),{recursive:!0}),await BI(i,this.renderConfig(t),"utf8"),ti.info("plist written",{plistPath:i,activate:n}),!n)return;await ya("launchctl",["unload","-w",i]).catch(c=>ti.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ya("launchctl",["load","-w",i]),ti.info("launchd job loaded",{label:xs});let o=process.getuid?.()??0;await ya("launchctl",["kickstart","-k",`gui/${o}/${xs}`]),ti.info("launchd job kickstarted",{label:xs,uid:o})},async uninstall(t){let e=this.configPath(t);await ya("launchctl",["unload","-w",e]).catch(n=>ti.warn("launchctl unload failed (ignored)",{err:String(n)})),await MI(e).catch(n=>{if(n.code!=="ENOENT")throw n}),ti.info("launchd job removed",{plistPath:e})}}});import{spawn as HI}from"node:child_process";import{mkdir as qI,unlink as jI,writeFile as WI}from"node:fs/promises";import{dirname as KI,join as Up}from"node:path";function Ea(t,e){return t.isRoot?e:["--user",...e]}function VI(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function va(t,e){return new Promise((n,i)=>{let o=HI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var ba,ri,$I,xl,Gp=nt(()=>{"use strict";ie();ba=H("supervisor.systemd"),ri="coze-bridge.service",$I="/etc/systemd/system";xl={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
- ${B2(t.env)}
62
+ ${VI(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Mp(M2,ei):Mp(t.homeDir,".config","systemd","user",ei)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await P2(N2(i),{recursive:!0}),await L2(i,this.renderConfig(t),"utf8"),xa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await ga("systemctl",pa(t,["daemon-reload"])),await ga("systemctl",pa(t,r?["enable","--now",ei]:["enable",ei])),xa.info("systemd unit enabled",{unitName:ei,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await ga("systemctl",pa(t,["disable","--now",ei])).catch(r=>xa.warn("systemctl disable failed (ignored)",{err:String(r)})),await O2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await ga("systemctl",pa(t,["daemon-reload"])).catch(()=>{}),xa.info("systemd unit removed",{unitPath:e})}}});import{spawn as F2}from"node:child_process";import{join as z2}from"node:path";function Fp(t,e){return new Promise((r,i)=>{let o=F2(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var ul,ma,fl,zp=et(()=>{"use strict";ne();ul=H("supervisor.taskscheduler"),ma="CozeBridge",fl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Up($I,ri):Up(t.homeDir,".config","systemd","user",ri)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await qI(KI(i),{recursive:!0}),await WI(i,this.renderConfig(t),"utf8"),ba.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await va("systemctl",Ea(t,["daemon-reload"])),await va("systemctl",Ea(t,n?["enable","--now",ri]:["enable",ri])),ba.info("systemd unit enabled",{unitName:ri,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await va("systemctl",Ea(t,["disable","--now",ri])).catch(n=>ba.warn("systemctl disable failed (ignored)",{err:String(n)})),await jI(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await va("systemctl",Ea(t,["daemon-reload"])).catch(()=>{}),ba.info("systemd unit removed",{unitPath:e})}}});import{spawn as ZI}from"node:child_process";import{join as YI}from"node:path";function Hp(t,e){return new Promise((n,i)=>{let o=ZI(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var pl,Sa,gl,qp=nt(()=>{"use strict";ie();pl=H("supervisor.taskscheduler"),Sa="CozeBridge",gl={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,58 +86,59 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return z2(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 Fp("schtasks",["/Create","/SC","ONLOGON","/TN",ma,"/TR",r,"/RU",t.userName,"/F"]),ul.info("task scheduler entry created",{task:ma,logFile:t.logFile})},async uninstall(t){await Fp("schtasks",["/Delete","/TN",ma,"/F"]).catch(e=>ul.warn("schtasks /Delete failed (ignored)",{err:String(e)})),ul.info("task scheduler entry removed",{task:ma})}}});var Up={};Da(Up,{buildContext:()=>W2,getSupervisor:()=>H2,launchdSupervisor:()=>dl,systemdSupervisor:()=>ll,taskSchedulerSupervisor:()=>fl});import{homedir as U2,userInfo as q2}from"node:os";function H2(t=process.platform){switch(t){case"darwin":return dl;case"linux":return ll;case"win32":return fl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function j2(){let t={};for(let e of G2){let r=process.env[e];r&&(t[e]=r)}return t}function W2(){let t=J();return{nodeBin:process.execPath,entry:el(t),logFile:t.logFile,homeDir:U2(),userName:q2().username,isRoot:process.getuid?.()===0,env:j2()}}var G2,qp=et(()=>{"use strict";Re();aa();Np();Bp();zp();G2=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();cn();var Gl=H("acp-installer-warmup"),pm=["claude-code","codex"];async function jl(t={}){let e=t.ensure??fr,i=(await Promise.allSettled(pm.map(async o=>{let c=await e(o);Gl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Gl.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))})}hn();ne();import{readdir as Dm}from"node:fs/promises";import{mkdir as Vl,readFile as Cm,writeFile as Zl}from"node:fs/promises";import{join as Fa}from"node:path";var Rm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function hr(t,e,r){await Vl(t,{recursive:!0});let i=Rm[e],o=Fa(t,i);return await Zl(o,r??"","utf8"),o}async function za(t,e,r){let i=Fa(t,".claude");await Vl(i,{recursive:!0});let o=Fa(i,"settings.local.json"),c={};try{let u=await Cm(o,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(c=h)}catch{}let d=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=r)}return c.permissions=d,await Zl(o,JSON.stringify(c,null,2),"utf8"),o}var Xe=H("agent-detail-sync"),Pm=6e4,Om=5*6e4,Es=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await Dm(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(d){Xe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),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(h){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),g=x?Math.min(x.currentDelay*2,Om):Pm;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,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(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 Fe(i,this.opts.paths),Xe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Xe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await hr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var ld=Gt(Tu(),1);import{createHash as py}from"node:crypto";import{lstat as nd,mkdir as rd,readFile as po,readdir as g0,rm as id,stat as cd,writeFile as sd}from"node:fs/promises";import{homedir as gy}from"node:os";import{basename as h0,dirname as my,join as xe,normalize as wy,relative as dd,resolve as od,sep as m0}from"node:path";import{Readable as w0}from"node:stream";import{pipeline as _0}from"node:stream/promises";import tw from"events";import rt from"fs";import{EventEmitter as zc}from"node:events";import uf from"node:stream";import{StringDecoder as nw}from"node:string_decoder";import xf from"node:path";import Ir from"node:fs";import{dirname as pw,parse as gw}from"path";import{EventEmitter as Sw}from"events";import yc from"assert";import{Buffer as Wn}from"buffer";import*as Ou from"zlib";import Iw from"zlib";import{posix as wr}from"node:path";import{basename as Qw}from"node:path";import eo from"fs";import Rt from"fs";import qu from"path";import{win32 as f_}from"node:path";import Vu from"path";import Cf from"node:fs";import C_ from"node:assert";import{randomBytes as Rf}from"node:crypto";import ie from"node:fs";import Be from"node:path";import Df from"fs";import lo from"node:fs";import Ti from"node:path";import at from"node:fs";import M_ from"node:fs/promises";import ro from"node:path";import{join as Hf}from"node:path";import ot from"node:fs";import Wf from"node:path";var Qm=Object.defineProperty,ew=(t,e)=>{for(var r in e)Qm(t,r,{get:e[r],enumerable:!0})},Cu=typeof process=="object"&&process?process:{stdout:null,stderr:null},rw=t=>!!t&&typeof t=="object"&&(t instanceof Vn||t instanceof uf||iw(t)||sw(t)),iw=t=>!!t&&typeof t=="object"&&t instanceof zc&&typeof t.pipe=="function"&&t.pipe!==uf.Writable.prototype.pipe,sw=t=>!!t&&typeof t=="object"&&t instanceof zc&&typeof t.write=="function"&&typeof t.end=="function",jt=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),pn=Symbol("emittedEnd"),ks=Symbol("emittingEnd"),li=Symbol("emittedError"),Ts=Symbol("closed"),Ru=Symbol("read"),Cs=Symbol("flush"),Du=Symbol("flushChunk"),mt=Symbol("encoding"),mr=Symbol("decoder"),ze=Symbol("flowing"),ui=Symbol("paused"),Er=Symbol("resume"),Ue=Symbol("buffer"),Qe=Symbol("pipes"),qe=Symbol("bufferLength"),Wa=Symbol("bufferPush"),Rs=Symbol("bufferShift"),Ye=Symbol("objectMode"),ke=Symbol("destroyed"),Ka=Symbol("error"),$a=Symbol("emitData"),Pu=Symbol("emitEnd"),Va=Symbol("emitEnd2"),At=Symbol("async"),Za=Symbol("abort"),Ds=Symbol("aborted"),fi=Symbol("signal"),Mn=Symbol("dataListeners"),st=Symbol("discarded"),hi=t=>Promise.resolve().then(t),ow=t=>t(),aw=t=>t==="end"||t==="finish"||t==="prefinish",cw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,dw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),ff=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Er](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},lw=class extends ff{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)}},uw=t=>!!t.objectMode,fw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Vn=class extends zc{[ze]=!1;[ui]=!1;[Qe]=[];[Ue]=[];[Ye];[mt];[At];[mr];[jt]=!1;[pn]=!1;[ks]=!1;[Ts]=!1;[li]=null;[qe]=0;[ke]=!1;[fi];[Ds]=!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");uw(e)?(this[Ye]=!0,this[mt]=null):fw(e)?(this[mt]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[mt]=null),this[At]=!!e.async,this[mr]=this[mt]?new nw(this[mt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ue]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:r}=e;r&&(this[fi]=r,r.aborted?this[Za]():r.addEventListener("abort",()=>this[Za]()))}get bufferLength(){return this[qe]}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[At]}set async(t){this[At]=this[At]||!!t}[Za](){this[Ds]=!0,this.emit("abort",this[fi]?.reason),this.destroy(this[fi]?.reason)}get aborted(){return this[Ds]}set aborted(t){}write(t,e,r){if(this[Ds])return!1;if(this[jt])throw new Error("write after end");if(this[ke])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[At]?hi:ow;if(!this[Ye]&&!Buffer.isBuffer(t)){if(dw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(cw(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[ze]&&this[qe]!==0&&this[Cs](!0),this[ze]?this.emit("data",t):this[Wa](t),this[qe]!==0&&this.emit("readable"),r&&i(r),this[ze]):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[ze]&&this[qe]!==0&&this[Cs](!0),this[ze]?this.emit("data",t):this[Wa](t),this[qe]!==0&&this.emit("readable"),r&&i(r),this[ze]):(this[qe]!==0&&this.emit("readable"),r&&i(r),this[ze])}read(t){if(this[ke])return null;if(this[st]=!1,this[qe]===0||t===0||t&&t>this[qe])return this[Wt](),null;this[Ye]&&(t=null),this[Ue].length>1&&!this[Ye]&&(this[Ue]=[this[mt]?this[Ue].join(""):Buffer.concat(this[Ue],this[qe])]);let e=this[Ru](t||null,this[Ue][0]);return this[Wt](),e}[Ru](t,e){if(this[Ye])this[Rs]();else{let r=e;t===r.length||t===null?this[Rs]():typeof r=="string"?(this[Ue][0]=r.slice(t),e=r.slice(0,t),this[qe]-=t):(this[Ue][0]=r.subarray(t),e=r.subarray(0,t),this[qe]-=t)}return this.emit("data",e),!this[Ue].length&&!this[jt]&&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[jt]=!0,this.writable=!1,(this[ze]||!this[ui])&&this[Wt](),this}[Er](){this[ke]||(!this[Mn]&&!this[Qe].length&&(this[st]=!0),this[ui]=!1,this[ze]=!0,this.emit("resume"),this[Ue].length?this[Cs]():this[jt]?this[Wt]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[ze]=!1,this[ui]=!0,this[st]=!1}get destroyed(){return this[ke]}get flowing(){return this[ze]}get paused(){return this[ui]}[Wa](t){this[Ye]?this[qe]+=1:this[qe]+=t.length,this[Ue].push(t)}[Rs](){return this[Ye]?this[qe]-=1:this[qe]-=this[Ue][0].length,this[Ue].shift()}[Cs](t=!1){do;while(this[Du](this[Rs]())&&this[Ue].length);!t&&!this[Ue].length&&!this[jt]&&this.emit("drain")}[Du](t){return this.emit("data",t),this[ze]}pipe(t,e){if(this[ke])return t;this[st]=!1;let r=this[pn];return e=e||{},t===Cu.stdout||t===Cu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Qe].push(e.proxyErrors?new lw(this,t,e):new ff(this,t,e)),this[At]?hi(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[Qe].find(r=>r.dest===t);e&&(this[Qe].length===1?(this[ze]&&this[Mn]===0&&(this[ze]=!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[ze]&&this[Er]();else if(t==="readable"&&this[qe]!==0)super.emit("readable");else if(aw(t)&&this[pn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[li]){let i=e;this[At]?hi(()=>i.call(this,this[li])):i.call(this,this[li])}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[ze]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Mn]=0,!this[st]&&!this[Qe].length&&(this[ze]=!1)),e}get emittedEnd(){return this[pn]}[Wt](){!this[ks]&&!this[pn]&&!this[ke]&&this[Ue].length===0&&this[jt]&&(this[ks]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ts]&&this.emit("close"),this[ks]=!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[At]?(hi(()=>this[$a](r)),!0):this[$a](r);if(t==="end")return this[Pu]();if(t==="close"){if(this[Ts]=!0,!this[pn]&&!this[ke])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[li]=r,super.emit(Ka,r);let o=!this[fi]||this.listeners("error").length?super.emit("error",r):!1;return this[Wt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Wt](),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[Wt](),i}[$a](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[Wt](),e}[Pu](){return this[pn]?!1:(this[pn]=!0,this.readable=!1,this[At]?(hi(()=>this[Va]()),!0):this[Va]())}[Va](){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[jt])return e();let i,o,c=x=>{this.off("data",d),this.off("end",u),this.off(ke,h),e(),o(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(ke,h),this.pause(),i({value:x,done:!!this[jt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(ke,h),e(),i({done:!0,value:void 0})},h=()=>c(new Error("stream destroyed"));return new Promise((x,g)=>{o=g,i=x,this.once(ke,h),this.once("error",c),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[st]=!1;let t=!1,e=()=>(this.pause(),this.off(Ka,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(Ka,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[Ue].length=0,this[qe]=0;let e=this;return typeof e.close=="function"&&!this[Ts]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return rw}},hw=rt.writev,Sn=Symbol("_autoClose"),bt=Symbol("_close"),xi=Symbol("_ended"),de=Symbol("_fd"),Ja=Symbol("_finished"),Zt=Symbol("_flags"),Ya=Symbol("_flush"),wc=Symbol("_handleChunk"),_c=Symbol("_makeBuf"),Ai=Symbol("_mode"),Ps=Symbol("_needDrain"),kr=Symbol("_onerror"),Tr=Symbol("_onopen"),Xa=Symbol("_onread"),vr=Symbol("_onwrite"),In=Symbol("_open"),yt=Symbol("_path"),_n=Symbol("_pos"),kt=Symbol("_queue"),Sr=Symbol("_read"),Qa=Symbol("_readSize"),Vt=Symbol("_reading"),pi=Symbol("_remain"),ec=Symbol("_size"),Hs=Symbol("_write"),Bn=Symbol("_writing"),Gs=Symbol("_defaultFlag"),jn=Symbol("_errored"),Uc=class extends Vn{[jn]=!1;[de];[yt];[Qa];[Vt]=!1;[ec];[pi];[Sn];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[de]=typeof e.fd=="number"?e.fd:void 0,this[yt]=t,this[Qa]=e.readSize||16*1024*1024,this[Vt]=!1,this[ec]=typeof e.size=="number"?e.size:1/0,this[pi]=this[ec],this[Sn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[de]=="number"?this[Sr]():this[In]()}get fd(){return this[de]}get path(){return this[yt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[In](){rt.open(this[yt],"r",(t,e)=>this[Tr](t,e))}[Tr](t,e){t?this[kr](t):(this[de]=e,this.emit("open",e),this[Sr]())}[_c](){return Buffer.allocUnsafe(Math.min(this[Qa],this[pi]))}[Sr](){if(!this[Vt]){this[Vt]=!0;let t=this[_c]();if(t.length===0)return process.nextTick(()=>this[Xa](null,0,t));rt.read(this[de],t,0,t.length,null,(e,r,i)=>this[Xa](e,r,i))}}[Xa](t,e,r){this[Vt]=!1,t?this[kr](t):this[wc](e,r)&&this[Sr]()}[bt](){if(this[Sn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[kr](t){this[Vt]=!0,this[bt](),this.emit("error",t)}[wc](t,e){let r=!1;return this[pi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[pi]<=0)&&(r=!1,this[bt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[de]=="number"&&this[Sr](),!1;case"error":return this[jn]?!1:(this[jn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},xw=class extends Uc{[In](){let t=!0;try{this[Tr](null,rt.openSync(this[yt],"r")),t=!1}finally{t&&this[bt]()}}[Sr](){let t=!0;try{if(!this[Vt]){this[Vt]=!0;do{let e=this[_c](),r=e.length===0?0:rt.readSync(this[de],e,0,e.length,null);if(!this[wc](r,e))break}while(!0);this[Vt]=!1}t=!1}finally{t&&this[bt]()}}[bt](){if(this[Sn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,rt.closeSync(t),this.emit("close")}}},io=class extends tw{readable=!1;writable=!0;[jn]=!1;[Bn]=!1;[xi]=!1;[kt]=[];[Ps]=!1;[yt];[Ai];[Sn];[de];[Gs];[Zt];[Ja]=!1;[_n];constructor(t,e){e=e||{},super(e),this[yt]=t,this[de]=typeof e.fd=="number"?e.fd:void 0,this[Ai]=e.mode===void 0?438:e.mode,this[_n]=typeof e.start=="number"?e.start:void 0,this[Sn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[_n]!==void 0?"r+":"w";this[Gs]=e.flags===void 0,this[Zt]=e.flags===void 0?r:e.flags,this[de]===void 0&&this[In]()}emit(t,...e){if(t==="error"){if(this[jn])return!1;this[jn]=!0}return super.emit(t,...e)}get fd(){return this[de]}get path(){return this[yt]}[kr](t){this[bt](),this[Bn]=!0,this.emit("error",t)}[In](){rt.open(this[yt],this[Zt],this[Ai],(t,e)=>this[Tr](t,e))}[Tr](t,e){this[Gs]&&this[Zt]==="r+"&&t&&t.code==="ENOENT"?(this[Zt]="w",this[In]()):t?this[kr](t):(this[de]=e,this.emit("open",e),this[Bn]||this[Ya]())}end(t,e){return t&&this.write(t,e),this[xi]=!0,!this[Bn]&&!this[kt].length&&typeof this[de]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[xi]?(this.emit("error",new Error("write() after end()")),!1):this[de]===void 0||this[Bn]||this[kt].length?(this[kt].push(t),this[Ps]=!0,!1):(this[Bn]=!0,this[Hs](t),!0)}[Hs](t){rt.write(this[de],t,0,t.length,this[_n],(e,r)=>this[vr](e,r))}[vr](t,e){t?this[kr](t):(this[_n]!==void 0&&typeof e=="number"&&(this[_n]+=e),this[kt].length?this[Ya]():(this[Bn]=!1,this[xi]&&!this[Ja]?(this[Ja]=!0,this[bt](),this.emit("finish")):this[Ps]&&(this[Ps]=!1,this.emit("drain"))))}[Ya](){if(this[kt].length===0)this[xi]&&this[vr](null,0);else if(this[kt].length===1)this[Hs](this[kt].pop());else{let t=this[kt];this[kt]=[],hw(this[de],t,this[_n],(e,r)=>this[vr](e,r))}}[bt](){if(this[Sn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},hf=class extends io{[In](){let t;if(this[Gs]&&this[Zt]==="r+")try{t=rt.openSync(this[yt],this[Zt],this[Ai])}catch(e){if(e?.code==="ENOENT")return this[Zt]="w",this[In]();throw e}else t=rt.openSync(this[yt],this[Zt],this[Ai]);this[Tr](null,t)}[bt](){if(this[Sn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,rt.closeSync(t),this.emit("close")}}[Hs](t){let e=!0;try{this[vr](null,rt.writeSync(this[de],t,0,t.length,this[_n])),e=!1}finally{if(e)try{this[bt]()}catch{}}}},mw=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"]]),ww=t=>!!t.sync&&!!t.file,_w=t=>!t.sync&&!!t.file,yw=t=>!!t.sync&&!t.file,bw=t=>!t.sync&&!t.file,Ew=t=>!!t.file,vw=t=>mw.get(t)||t,qc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=vw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Ni=(t,e,r,i,o)=>Object.assign((c=[],d,u)=>{Array.isArray(c)&&(d=c,c={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let h=qc(c);if(o?.(h,d),ww(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(_w(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(yw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(h,d)}else if(bw(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),Aw=Iw.constants||{ZLIB_VERNUM:4736},Pt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Aw)),kw=Wn.concat,Lu=Object.getOwnPropertyDescriptor(Wn,"concat"),Tw=t=>t,tc=Lu?.writable===!0||Lu?.set!==void 0?t=>{Wn.concat=t?Tw:kw}:t=>{},Kn=Symbol("_superWrite"),Os=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"}},nc=Symbol("flushFlag"),Hc=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 Ou[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Ou[e](t)}catch(r){throw new Os(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 Os(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return yc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Wn.alloc(0),{[nc]: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}[Kn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Wn.from(t,e)),this.#e)return;yc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},tc(!0);let d;try{let h=typeof t[nc]=="number"?t[nc]:this.#r;d=this.#t._processChunk(t,h),tc(!1)}catch(h){tc(!1),this.#o(new Os(h,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",h=>this.#o(new Os(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[Kn](Wn.from(h));for(let x=1;x<d.length;x++)u=this[Kn](d[x])}else u=this[Kn](Wn.from(d));return r&&r(),u}},pf=class extends Hc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Pt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Pt.Z_FINISH,t.fullFlushFlag=Pt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Pt.Z_SYNC_FLUSH),yc(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 pf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Kn](t){return this.#e?(this.#e=!1,t[9]=255,super[Kn](t)):super[Kn](t)}},Rw=class extends pf{constructor(t){super(t,"Unzip")}},gf=class extends Hc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Pt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Pt.BROTLI_OPERATION_FLUSH,super(t,e)}},Dw=class extends gf{constructor(t){super(t,"BrotliCompress")}},Pw=class extends gf{constructor(t){super(t,"BrotliDecompress")}},mf=class extends Hc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Pt.ZSTD_e_end,t.fullFlushFlag=Pt.ZSTD_e_flush,super(t,e)}},Ow=class extends mf{constructor(t){super(t,"ZstdCompress")}},Lw=class extends mf{constructor(t){super(t,"ZstdDecompress")}},Nw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Bw(t,e):Mw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Mw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Bw=(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]=wf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=_f(o))}},Fw=t=>{let e=t[0],r=e===128?Uw(t.subarray(1,t.length)):e===255?zw(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},zw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=wf(c):c===0?d=c:(i=!0,d=_f(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},Uw=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},wf=t=>(255^t)&255,_f=t=>(255^t)+1&255,qw={};ew(qw,{code:()=>Gc,isCode:()=>js,isName:()=>Hw,name:()=>so,normalFsTypes:()=>yf});var js=t=>so.has(t),Hw=t=>Gc.has(t),yf=new Set(["0","","1","2","3","4","5","6","7","D"]),so=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"]]),Gc=new Map(Array.from(so).map(t=>[t[1],t[0]])),Gw=t=>t===void 0||t<0?void 0:t,$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");let o=Fn(t,e+156,1),c=yf.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??Fn(t,e,100),this.mode=d?.mode??u?.mode??yn(t,e+100,8),this.uid=d?.uid??u?.uid??yn(t,e+108,8),this.gid=d?.gid??u?.gid??yn(t,e+116,8),this.size=Gw(d?.size??u?.size??yn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??rc(t,e+136,12),this.cksum=yn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),js(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=d?.uname??u?.uname??Fn(t,e+265,32),this.gname=d?.gname??u?.gname??Fn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??yn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??yn(t,e+337,8)??0,t[e+475]!==0){let x=Fn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Fn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=r?.atime??i?.atime??rc(t,e+476,12),this.ctime=r?.ctime??i?.ctime??rc(t,e+488,12)}let h=256;for(let x=e;x<e+148;x++)h+=t[x];for(let x=e+156;x<e+512;x++)h+=t[x];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="size"&&Number(i)<0||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=jw(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=zn(t,e,100,o)||this.needPax,this.needPax=bn(t,e+100,8,this.mode)||this.needPax,this.needPax=bn(t,e+108,8,this.uid)||this.needPax,this.needPax=bn(t,e+116,8,this.gid)||this.needPax,this.needPax=bn(t,e+124,12,this.size)||this.needPax,this.needPax=ic(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=bn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=bn(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=ic(t,e+476,12,this.atime)||this.needPax,this.needPax=ic(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,bn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:so.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Gc.get(t));if(js(e)||e==="Unsupported")this.#e=e;else if(js(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},jw=(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.*/,""),rc=(t,e,r)=>Ww(yn(t,e,r)),Ww=t=>t===void 0?void 0:new Date(t*1e3),yn=(t,e,r)=>Number(t[e])&128?Fw(t.subarray(e,e+r)):$w(t,e,r),Kw=t=>isNaN(t)?void 0:t,$w=(t,e,r)=>Kw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Vw={12:8589934591,8:2097151},bn=(t,e,r,i)=>i===void 0?!1:i>Vw[r]||i<0?(Nw(i,t.subarray(e,e+r)),!0):(Zw(t,e,r,i),!1),Zw=(t,e,r,i)=>t.write(Jw(i,r),e,r,"ascii"),Jw=(t,e)=>Yw(Math.floor(t).toString(8),e),Yw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",ic=(t,e,r,i)=>i===void 0?!1:bn(t,e,r,i.getTime()/1e3),Xw=new Array(156).join("\0"),zn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Xw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Qs=class bf{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/"+Qw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
- `,c=Buffer.byteLength(o),d=Math.floor(Math.log(c)/Math.log(10))+1;return c+d>=Math.pow(10,d)&&(d+=1),d+c+o}static parse(e,r,i=!1){return new bf(e_(t_(e),r),i)}},e_=(t,e)=>e?Object.assign({},e,t):t,t_=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(n_,Object.create(null)),n_=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(c){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[c]=d;break;case"ctime":case"atime":case"mtime":t[c]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[c]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[c]=+d;break}return t},r_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=r_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),i_=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=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},oo=(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))},s_=1024*1024,bc=Buffer.from([31,139]),Ec=Buffer.from([40,181,47,253]),o_=Math.max(bc.length,Ec.length),lt=Symbol("state"),Un=Symbol("writeEntry"),Kt=Symbol("readEntry"),sc=Symbol("nextEntry"),Nu=Symbol("processEntry"),Tt=Symbol("extendedHeader"),gi=Symbol("globalExtendedHeader"),gn=Symbol("meta"),Mu=Symbol("emitMeta"),me=Symbol("buffer"),$t=Symbol("queue"),mn=Symbol("ended"),oc=Symbol("emittedEnd"),qn=Symbol("emit"),Ae=Symbol("unzip"),Ls=Symbol("consumeChunk"),Ns=Symbol("consumeChunkSub"),ac=Symbol("consumeBody"),Bu=Symbol("consumeMeta"),Fu=Symbol("consumeHeader"),mi=Symbol("consuming"),cc=Symbol("bufferConcat"),Ms=Symbol("maybeEnd"),_r=Symbol("writing"),Ct=Symbol("aborted"),Bs=Symbol("onDone"),Hn=Symbol("sawValidEntry"),Fs=Symbol("sawNullBlock"),zs=Symbol("sawEOF"),zu=Symbol("closeStream"),a_=1e3,wi=Symbol("compressedBytesRead"),dc=Symbol("decompressedBytesRead"),Uu=Symbol("checkDecompressionRatio"),c_=()=>!0,Li=class extends Sw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[$t]=[];[me];[Kt];[Un];[lt]="begin";[gn]="";[Tt];[gi];[mn]=!1;[Ae];[Ct]=!1;[Hn];[Fs]=!1;[zs]=!1;[_r]=!1;[mi]=!1;[oc]=!1;[wi]=0;[dc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Bs,()=>{(this[lt]==="begin"||this[Hn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Bs,t.ondone):this.on(Bs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:a_,this.maxMetaEntrySize=t.maxMetaEntrySize||s_,this.filter=typeof t.filter=="function"?t.filter:c_;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[zu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){oo(this,t,e,r)}[Fu](t,e){this[Hn]===void 0&&(this[Hn]=!1);let r;try{r=new $n(t,e,this[Tt],this[gi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Fs]?(this[zs]=!0,this[lt]==="begin"&&(this[lt]="header"),this[qn]("eof")):(this[Fs]=!0,this[qn]("nullBlock"));else if(this[Fs]=!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 i_(r,this[Tt],this[gi]);if(!this[Hn])if(o.remain){let c=()=>{o.invalid||(this[Hn]=!0)};o.on("end",c)}else this[Hn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[qn]("ignoredEntry",o),this[lt]="ignore",o.resume()):o.size>0&&(this[gn]="",o.on("data",c=>this[gn]+=c),this[lt]="meta"):(this[Tt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[qn]("ignoredEntry",o),this[lt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[lt]="body":(this[lt]="header",o.end()),this[Kt]?this[$t].push(o):(this[$t].push(o),this[sc]())))}}}[zu](){queueMicrotask(()=>this.emit("close"))}[Nu](t){let e=!0;if(!t)this[Kt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Kt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[sc]()),e=!1);return e}[sc](){do;while(this[Nu](this[$t].shift()));if(this[$t].length===0){let t=this[Kt];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[ac](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}[Bu](t,e){let r=this[Un],i=this[ac](t,e);return!this[Un]&&r&&this[Mu](r),i}[qn](t,e,r){this[$t].length===0&&!this[Kt]?this.emit(t,e,r):this[$t].push([t,e,r])}[Mu](t){switch(this[qn]("meta",this[gn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Tt]=Qs.parse(this[gn],this[Tt],!1);break;case"GlobalExtendedHeader":this[gi]=Qs.parse(this[gn],this[gi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Tt]??Object.create(null);this[Tt]=e,e.path=this[gn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Tt]||Object.create(null);this[Tt]=e,e.linkpath=this[gn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Ct]){if(this[Ae]){let e=this[Ae];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Ct]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[Uu](t){this[dc]+=t.length;let e=this[dc]/this[wi];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}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[Ct])return r?.(),!1;if((this[Ae]===void 0||this.brotli===void 0&&this[Ae]===!1)&&t){if(this[me]&&(t=Buffer.concat([this[me],t]),this[me]=void 0),t.length<o_)return this[me]=t,r?.(),!0;for(let d=0;this[Ae]===void 0&&d<bc.length;d++)t[d]!==bc[d]&&(this[Ae]=!1);let o=!1;if(this[Ae]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Ec.length;d++)if(t[d]!==Ec[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Ae]===!1&&c)if(t.length<512)if(this[mn])this.brotli=!0;else return this[me]=t,r?.(),!0;else try{new $n(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ae]===void 0||this[Ae]===!1&&(this.brotli||o)){let d=this[mn];this[mn]=!1,this[Ae]=this[Ae]===void 0?new Rw({}):o?new Lw({}):new Pw({}),this[Ae].on("data",h=>{this[Uu](h)&&this[Ls](h)}),this[Ae].on("error",h=>{this[Ct]||this.abort(h)}),this[Ae].on("end",()=>{this[mn]=!0,this[Ls]()}),this[_r]=!0,this[wi]+=t.length;let u=!!this[Ae][d?"end":"write"](t);return this[_r]=!1,r?.(),u}}this[_r]=!0,this[Ae]?(this[wi]+=t.length,this[Ae].write(t)):this[Ls](t),this[_r]=!1;let i=this[$t].length>0?!1:this[Kt]?this[Kt].flowing:!0;return!i&&this[$t].length===0&&this[Kt]?.once("drain",()=>this.emit("drain")),r?.(),i}[cc](t){t&&!this[Ct]&&(this[me]=this[me]?Buffer.concat([this[me],t]):t)}[Ms](){if(this[mn]&&!this[oc]&&!this[Ct]&&!this[mi]){this[oc]=!0;let t=this[Un];if(t?.blockRemain){let e=this[me]?this[me].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[me]&&t.write(this[me]),t.end()}this[qn](Bs)}}[Ls](t){if(this[mi]&&t)this[cc](t);else if(!t&&!this[me])this[Ms]();else if(t){if(this[mi]=!0,this[me]){this[cc](t);let e=this[me];this[me]=void 0,this[Ns](e)}else this[Ns](t);for(;this[me]&&this[me]?.length>=512&&!this[Ct]&&!this[zs];){let e=this[me];this[me]=void 0,this[Ns](e)}this[mi]=!1}(!this[me]||this[mn])&&this[Ms]()}[Ns](t){let e=0,r=t.length;for(;e+512<=r&&!this[Ct]&&!this[zs];)switch(this[lt]){case"begin":case"header":this[Fu](t,e),e+=512;break;case"ignore":case"body":e+=this[ac](t,e);break;case"meta":e+=this[Bu](t,e);break;default:throw new Error("invalid state: "+this[lt])}e<r&&(this[me]=this[me]?Buffer.concat([t.subarray(e),this[me]]):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[Ct]||(this[Ae]?(t&&(this[wi]+=t.length,this[Ae].write(t)),this[Ae].end()):(this[mn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ms]())),this}},ki=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)},d_=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},Ef=(t,e)=>{let r=new Map(e.map(c=>[ki(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||gw(c).root||".",h;if(c===u)h=!1;else{let x=r.get(c);h=x!==void 0?x:o(pw(c),u)}return r.set(c,h),h};t.filter=i?(c,d)=>i(c,d)&&o(ki(c)):c=>o(ki(c))},l_=t=>{let e=new Li(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 d=Buffer.allocUnsafe(o.size),u=Ir.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(c);for(;d<o.size;){let h=Ir.readSync(i,u,0,c,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Ir.closeSync(i)}catch{}}},u_=(t,e)=>{let r=new Li(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),Ir.stat(o,(u,h)=>{if(u)d(u);else{let x=new Uc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},Cr=Ni(l_,u_,t=>new Li(t),t=>new Li(t),(t,e)=>{e?.length&&Ef(t,e),t.noResume||d_(t)}),vf=(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:h_,parse:Hu}=f_,jc=t=>{let e="",r=Hu(t);for(;h_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Hu(t)}return[e,t]},ao=["|","<",">","?",":"],Wc=ao.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),x_=new Map(ao.map((t,e)=>[t,Wc[e]])),p_=new Map(Wc.map((t,e)=>[t,ao[e]])),Gu=t=>ao.reduce((e,r)=>e.split(r).join(x_.get(r)),t),g_=t=>Wc.reduce((e,r)=>e.split(r).join(p_.get(r)),t),Sf=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),ki(e)+"/"+t):Q(t),m_=16*1024*1024,ju=Symbol("process"),Wu=Symbol("file"),Ku=Symbol("directory"),vc=Symbol("symlink"),$u=Symbol("hardlink"),_i=Symbol("header"),Ws=Symbol("read"),Sc=Symbol("lstat"),Ks=Symbol("onlstat"),Ic=Symbol("onread"),Ac=Symbol("onreadlink"),kc=Symbol("openfile"),Tc=Symbol("onopenfile"),En=Symbol("close"),to=Symbol("mode"),Cc=Symbol("awaitDrain"),lc=Symbol("ondrain"),Dt=Symbol("prefix"),If=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=qc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||m_,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Q(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Q(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=jc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=g_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||qu.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[Ks](o):this[Sc]()}warn(t,e,r={}){return oo(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Sc](){Rt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Ks](e)})}[Ks](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=y_(t),this.emit("stat",t),this[ju]()}[ju](){switch(this.type){case"File":return this[Wu]();case"Directory":return this[Ku]();case"SymbolicLink":return this[vc]();default:return this.end()}}[to](t){return vf(t,this.type==="Directory",this.portable)}[Dt](t){return Sf(t,this.prefix)}[_i](){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[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,mode:this[to](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 Qs({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[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](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)}[Ku](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[_i](),this.end()}[vc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Ac](e)})}[Ac](t){this.linkpath=Q(t),this[_i](),this.end()}[$u](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(qu.relative(this.cwd,t)),this.stat.size=0,this[_i](),this.end()}[Wu](){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[$u](e);this.linkCache.set(t,this.absolute)}if(this[_i](),this.stat.size===0)return this.end();this[kc]()}[kc](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Tc](e)})}[Tc](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[Ws]()}[Ws](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Rt.read(t,e,r,i,o,(c,d)=>{if(c)return this[En](()=>this.emit("error",c));this[Ic](d)})}[En](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[Ic](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[lc]():this[Cc](()=>this[lc]())}[Cc](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)}[lc](){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[Ws]()}},w_=class extends If{sync=!0;[Sc](){this[Ks](Rt.lstatSync(this.absolute))}[vc](){this[Ac](Rt.readlinkSync(this.absolute))}[kc](){this[Tc](Rt.openSync(this.absolute,"r"))}[Ws](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let d=Rt.readSync(e,r,i,o,c);this[Ic](d),t=!1}finally{if(t)try{this[En](()=>{})}catch{}}}[Cc](t){t()}[En](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},__=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 oo(this,t,e,r)}constructor(t,e={}){let r=qc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[to](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=jc(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new $n({path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](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 Qs({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[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](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)}[Dt](t){return Sf(t,this.prefix)}[to](t){return vf(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}},y_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",b_=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++)v_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)S_(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 d=0;o&&d<e;d++)o=o.next;let c=[];for(let d=0;o&&d<r;d++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=E_(this,o,d);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=r,this.tail=e,this}};function E_(t,e,r){let i=e,o=e?e.next:t.head,c=new Kc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function v_(t,e){t.tail=new Kc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function S_(t,e){t.head=new Kc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Kc=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}},Ju=Buffer.alloc(1024),$s=Symbol("onStat"),yi=Symbol("ended"),wt=Symbol("queue"),bi=Symbol("pendingLinks"),wn=Symbol("current"),Gn=Symbol("process"),Ei=Symbol("processing"),Us=Symbol("processJob"),_t=Symbol("jobs"),uc=Symbol("jobDone"),Vs=Symbol("addFSEntry"),Yu=Symbol("addTarEntry"),Rc=Symbol("stat"),Dc=Symbol("readdir"),Zs=Symbol("onreaddir"),Js=Symbol("pipe"),Xu=Symbol("entry"),fc=Symbol("entryOpt"),Ys=Symbol("writeEntryClass"),Af=Symbol("write"),hc=Symbol("ondrain"),co=class extends Vn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Ys];onWriteEntry;[wt];[bi]=new Map;[_t]=0;[Ei]=!1;[yi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[Ys]=If,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 Dw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Ow(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[hc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[hc]);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 b_,this[_t]=0,this.jobs=Number(t.jobs)||4,this[Ei]=!1,this[yi]=!1}[Af](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[yi]=!0,this[Gn](),r&&r(),this}write(t){if(this[yi])throw new Error("write after end");return typeof t=="string"?this[Vs](t):this[Yu](t),this.flowing}[Yu](t){let e=Q(Vu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Zu(t.path,e);r.entry=new __(t,this[fc](r)),r.entry.on("end",()=>this[uc](r)),this[_t]+=1,this[wt].push(r)}this[Gn]()}[Vs](t){let e=Q(Vu.resolve(this.cwd,t));this[wt].push(new Zu(t,e)),this[Gn]()}[Rc](t){t.pending=!0,this[_t]+=1;let e=this.follow?"stat":"lstat";eo[e](t.absolute,(r,i)=>{t.pending=!1,this[_t]-=1,r?this.emit("error",r):this[$s](t,i)})}[$s](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[wn])this[Us](t);else{let r=`${e.dev}:${e.ino}`,i=this[bi].get(r);i?i.push(t):this[bi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[Gn]()}[Dc](t){t.pending=!0,this[_t]+=1,eo.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[_t]-=1,e)return this.emit("error",e);this[Zs](t,r)})}[Zs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Gn]()}[Gn](){if(!this[Ei]){this[Ei]=!0;for(let t=this[wt].head;t&&this[_t]<this.jobs;t=t.next)if(this[Us](t.value),t.value.ignore){let e=t.next;this[wt].removeNode(t),t.next=e}this[Ei]=!1,this[yi]&&this[wt].length===0&&this[_t]===0&&(this.zip?this.zip.end(Ju):(super.write(Ju),super.end()))}}get[wn](){return this[wt]&&this[wt].head&&this[wt].head.value}[uc](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[bi].get(r);if(i){this[bi].delete(r);for(let o of i)o.pending=!1,this[Us](o)}}this[Gn]()}[Us](t){if(t.pending&&t.pendingLink&&t===this[wn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[wn]&&!t.piped&&this[Js](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[$s](t,e):this[Rc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Zs](t,e):this[Dc](t),!t.readdir)return}if(t.entry=this[Xu](t),!t.entry){t.ignore=!0;return}t===this[wn]&&!t.piped&&this[Js](t)}}}[fc](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}}[Xu](t){this[_t]+=1;try{return new this[Ys](t.path,this[fc](t)).on("end",()=>this[uc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[hc](){this[wn]&&this[wn].entry&&this[wn].entry.resume()}[Js](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Vs](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={}){oo(this,t,e,r)}},$c=class extends co{sync=!0;constructor(t){super(t),this[Ys]=w_}pause(){}resume(){}[Rc](t){let e=this.follow?"statSync":"lstatSync";this[$s](t,eo[e](t.absolute))}[Dc](t){this[Zs](t,eo.readdirSync(t.absolute))}[Js](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Vs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[Af](i)})}},I_=(t,e)=>{let r=new $c(t),i=new hf(t.file,{mode:t.mode||438});r.pipe(i),kf(r,e)},A_=(t,e)=>{let r=new co(t),i=new io(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((c,d)=>{i.on("error",d),i.on("close",c),r.on("error",d)});return Tf(r,e).catch(c=>r.emit("error",c)),o},kf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:xf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},Tf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:xf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},k_=(t,e)=>{let r=new $c(t);return kf(r,e),r},T_=(t,e)=>{let r=new co(t);return Tf(r,e).catch(i=>r.emit("error",i)),r},kA=Ni(I_,A_,k_,T_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),R_=process.env.__FAKE_PLATFORM__||process.platform,Pf=R_==="win32",{O_CREAT:Of,O_NOFOLLOW:Qu,O_TRUNC:Lf,O_WRONLY:Nf}=Df.constants,Mf=Number(process.env.__FAKE_FS_O_FILENAME__)||Df.constants.UV_FS_O_FILEMAP||0,D_=Pf&&!!Mf,P_=512*1024,O_=Mf|Lf|Of|Nf,ef=!Pf&&typeof Qu=="number"?Qu|Lf|Of|Nf:null,Bf=ef!==null?()=>ef:D_?t=>t<P_?O_:"w":()=>"w",Pc=(t,e,r)=>{try{return lo.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},no=(t,e,r,i)=>{lo.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},L_=(t,e,r,i,o)=>{if(e.isDirectory())Ff(Ti.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=Ti.resolve(t,e.name);no(d,r,i,o)});else{let c=Ti.resolve(t,e.name);no(c,r,i,o)}},Ff=(t,e,r,i)=>{lo.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 no(t,e,r,i);let d=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return no(t,e,r,i)}};for(let x of c)L_(t,x,e,r,h)})},N_=(t,e,r,i)=>{e.isDirectory()&&zf(Ti.resolve(t,e.name),r,i),Pc(Ti.resolve(t,e.name),r,i)},zf=(t,e,r)=>{let i;try{i=lo.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Pc(t,e,r);throw c}for(let o of i)N_(t,o,e,r);return Pc(t,e,r)},Uf=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"}},uo=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"}},B_=(t,e)=>{at.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Uf(t,r?.code||"ENOTDIR")),e(r)})},F_=(t,e,r)=>{t=Q(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,d=e.uid,u=e.gid,h=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,g=e.unlink,w=Q(e.cwd),S=(E,I)=>{E?r(E):I&&h?Ff(I,d,u,k=>S(k)):c?at.chmod(t,o,r):r()};if(t===w)return B_(t,S);if(x)return M_.mkdir(t,{mode:o,recursive:!0}).then(E=>S(null,E??void 0),S);let _=Q(ro.relative(w,t)).split("/");Oc(w,_,o,g,w,void 0,S)},Oc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),h=Q(ro.resolve(t+"/"+u));at.mkdir(h,r,qf(h,e,r,i,o,c,d))},qf=(t,e,r,i,o,c,d)=>u=>{u?at.lstat(t,(h,x)=>{if(h)h.path=h.path&&Q(h.path),d(h);else if(x.isDirectory())Oc(t,e,r,i,o,c,d);else if(i)at.unlink(t,g=>{if(g)return d(g);at.mkdir(t,r,qf(t,e,r,i,o,c,d))});else{if(x.isSymbolicLink())return d(new uo(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Oc(t,e,r,i,o,c,d))},z_=t=>{let e=!1,r;try{e=at.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Uf(t,r??"ENOTDIR")}},U_=(t,e)=>{t=Q(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,d=e.gid,u=typeof c=="number"&&typeof d=="number"&&(c!==e.processUid||d!==e.processGid),h=e.preserve,x=e.unlink,g=Q(e.cwd),w=E=>{E&&u&&zf(E,c,d),o&&at.chmodSync(t,i)};if(t===g)return z_(g),w();if(h)return w(at.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(ro.relative(g,t)).split("/"),_;for(let E=S.shift(),I=g;E&&(I+="/"+E);E=S.shift()){I=Q(ro.resolve(I));try{at.mkdirSync(I,i),_=_||I}catch{let k=at.lstatSync(I);if(k.isDirectory())continue;if(x){at.unlinkSync(I),at.mkdirSync(I,i),_=_||I;continue}else if(k.isSymbolicLink())return new uo(I,I+"/"+S.join("/"))}}return w(_)},xc=Object.create(null),tf=1e4,yr=new Set,q_=t=>{yr.has(t)?yr.delete(t):xc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=xc[t],r=yr.size-tf;if(r>tf/10){for(let i of yr)if(yr.delete(i),delete xc[i],--r<=0)break}return e},H_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,G_=H_==="win32",j_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Hf(i,r)),e.push(r||"/"),e},[]),W_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=G_?["win32 parallelization disabled"]:t.map(i=>ki(Hf(q_(i))));let r=new Set(t.map(i=>j_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let d=this.#e.get(c);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(c);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let h of u)o.add(h)}for(let c of i){let d=this.#e.get(c),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(c);continue}else if(u.size===1){d.shift();let h=d[0];typeof h=="function"&&o.add(h)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},K_=()=>process.umask(),nf=Symbol("onEntry"),Lc=Symbol("checkFs"),rf=Symbol("checkFs2"),Nc=Symbol("isReusable"),ut=Symbol("makeFs"),Mc=Symbol("file"),Bc=Symbol("directory"),Xs=Symbol("link"),sf=Symbol("symlink"),of=Symbol("hardlink"),Ii=Symbol("ensureNoSymlink"),af=Symbol("unsupported"),cf=Symbol("checkPath"),pc=Symbol("stripAbsolutePath"),vn=Symbol("mkdir"),He=Symbol("onError"),qs=Symbol("pending"),df=Symbol("pend"),br=Symbol("unpend"),gc=Symbol("ended"),mc=Symbol("maybeClose"),Fc=Symbol("skip"),Ci=Symbol("doChown"),Ri=Symbol("uid"),Di=Symbol("gid"),Pi=Symbol("checkedCwd"),$_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Oi=$_==="win32",V_=1024,Z_=(t,e)=>{if(!Oi)return ie.unlink(t,e);let r=t+".DELETE."+Rf(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},J_=t=>{if(!Oi)return ie.unlinkSync(t);let e=t+".DELETE."+Rf(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},lf=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Vc=class extends Li{[gc]=!1;[Pi]=!1;[qs]=0;reservations=new W_;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[gc]=!0,this[mc]()},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?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:V_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Oi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Be.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:K_():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[nf](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[mc](){this[gc]&&this[qs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[pc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=jc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Oi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Be.posix.dirname(t.path),h=Be.posix.normalize(Be.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")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}[cf](t){let e=Q(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=Q(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[pc](t,"path")||!this[pc](t,"linkpath"))return!1;if(t.absolute=Be.isAbsolute(t.path)?Q(Be.resolve(t.path)):Q(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:Q(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Be.win32.parse(String(t.absolute));t.absolute=i+Gu(String(t.absolute).slice(i.length));let{root:o}=Be.win32.parse(t.path);t.path=o+Gu(t.path.slice(o.length))}return!0}[nf](t){if(!this[cf](t))return t.resume();switch(C_.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[Lc](t);default:return this[af](t)}}[He](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[br](),e.resume())}[vn](t,e,r){F_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Ci](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}[Ri](t){return lf(this.uid,t.uid,this.processUid)}[Di](t){return lf(this.gid,t.gid,this.processGid)}[Mc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new io(String(t.absolute),{flags:Bf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[He](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[He](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,h=>{h?this[He](h,t):this[br](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,g=t.mtime;ie.futimes(h,x,g,w=>w?ie.utimes(u,x,g,S=>c(S&&w)):c())}if(typeof h=="number"&&this[Ci](t)){o++;let x=this[Ri](t),g=this[Di](t);typeof x=="number"&&typeof g=="number"&&ie.fchown(h,x,g,w=>w?ie.chown(u,x,g,S=>c(S&&w)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[He](u,t),e()}),t.pipe(d)),d.pipe(i)}[Bc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[vn](String(t.absolute),r,i=>{if(i){this[He](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[br](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ci](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ri](t)),Number(this[Di](t)),c)),c()})}[af](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[sf](t,e){let r=Q(Be.relative(this.cwd,Be.resolve(Be.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ii](t,this.cwd,r,()=>this[Xs](t,String(t.linkpath),"symlink",e),i=>{this[He](i,t),e()})}[of](t,e){let r=Q(Be.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Ii](t,this.cwd,i,()=>this[Xs](t,r,"link",e),o=>{this[He](o,t),e()})}[Ii](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Be.resolve(e,c);ie.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new uo(d,Be.resolve(d,r.join("/"))));this[Ii](t,d,r,i,o)})}[df](){this[qs]++}[br](){this[qs]--,this[mc]()}[Fc](t){this[br](),t.resume()}[Nc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Oi}[Lc](t){this[df]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[rf](t,r))}[rf](t,e){let r=d=>{e(d)},i=()=>{this[vn](this.cwd,this.dmode,d=>{if(d){this[He](d,t),r();return}this[Pi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Be.dirname(String(t.absolute)));if(d!==this.cwd)return this[vn](d,this.dmode,u=>{if(u){this[He](u,t),r();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Fc](t),r();return}if(d||this[Nc](t,u))return this[ut](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[ut](g??null,t,r);return h?ie.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),h=>this[ut](h??null,t,r))}if(t.absolute===this.cwd)return this[ut](null,t,r);Z_(String(t.absolute),h=>this[ut](h??null,t,r))})};this[Pi]?o():i()}[ut](t,e,r){if(t){this[He](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Mc](e,r);case"Link":return this[of](e,r);case"SymbolicLink":return this[sf](e,r);case"Directory":case"GNUDumpDir":return this[Bc](e,r)}}[Xs](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[He](o,t):(this[br](),t.resume()),i()})}},vi=t=>{try{return[null,t()]}catch(e){return[e,null]}},Gf=class extends Vc{sync=!0;[ut](t,e){return super[ut](t,e,()=>{})}[Lc](t){if(!this[Pi]){let o=this[vn](this.cwd,this.dmode);if(o)return this[He](o,t);this[Pi]=!0}if(t.absolute!==this.cwd){let o=Q(Be.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[vn](o,this.dmode);if(c)return this[He](c,t)}}let[e,r]=vi(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Fc](t);if(e||this[Nc](t,r))return this[ut](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?vi(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ut](d,t)}let[o]=vi(()=>ie.rmdirSync(String(t.absolute)));this[ut](o,t)}let[i]=t.absolute===this.cwd?[]:vi(()=>J_(String(t.absolute)));this[ut](i,t)}[Mc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{ie.closeSync(o)}catch(h){u=h}(d||u)&&this[He](d||u,t),e()},o;try{o=ie.openSync(String(t.absolute),Bf(t.size),r)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[He](d,t)),t.pipe(c)),c.on("data",d=>{try{ie.writeSync(o,d,0,d.length)}catch(u){i(u)}}),c.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{ie.futimesSync(o,u,h)}catch(x){try{ie.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[Ci](t)){let u=this[Ri](t),h=this[Di](t);try{ie.fchownSync(o,Number(u),Number(h))}catch(x){try{ie.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[Bc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[vn](String(t.absolute),r);if(i){this[He](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ci](t))try{ie.chownSync(String(t.absolute),Number(this[Ri](t)),Number(this[Di](t)))}catch{}e(),t.resume()}[vn](t,e){try{return U_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[Ii](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Be.resolve(c,d);let[u,h]=vi(()=>ie.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return o(new uo(c,Be.resolve(e,r.join("/"))))}i()}[Xs](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[He](c,t)}}},Y_=t=>{let e=new Gf(t),r=t.file,i=Cf.statSync(r),o=t.maxReadSize||16*1024*1024;new xw(r,{readSize:o,size:i.size}).pipe(e)},X_=(t,e)=>{let r=new Vc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),Cf.stat(o,(u,h)=>{if(u)d(u);else{let x=new Uc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},jf=Ni(Y_,X_,t=>new Gf(t),t=>new Vc(t),(t,e)=>{e?.length&&Ef(t,e)}),Q_=(t,e)=>{let r=new $c(t),i=!0,o,c;try{try{o=ot.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=ot.openSync(t.file,"w+");else throw h}let d=ot.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let g=0,w=0;g<512;g+=w){if(w=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(!w)break e}let h=new $n(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(c+x+512>d.size)break;c+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,ey(t,r,c,o,e)}finally{if(i)try{ot.closeSync(o)}catch{}}},ey=(t,e,r,i,o)=>{let c=new hf(t.file,{fd:i,start:r});e.pipe(c),ny(e,o)},ty=(t,e)=>{e=Array.from(e);let r=new co(t),i=(o,c,d)=>{let u=(S,_)=>{S?ot.close(o,E=>d(S)):d(null,_)},h=0;if(c===0)return u(null,0);let x=0,g=Buffer.alloc(512),w=(S,_)=>{if(S||_===void 0)return u(S);if(x+=_,x<512&&_)return ot.read(o,g,x,g.length-x,h+x,w);if(h===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let E=new $n(g);if(!E.cksumValid)return u(null,h);let I=512*Math.ceil((E.size??0)/512);if(h+I+512>c||(h+=I+512,h>=c))return u(null,h);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),x=0,ot.read(o,g,0,512,h,w)};ot.read(o,g,0,512,h,w)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",ot.open(t.file,d,u);if(h||!x)return c(h);ot.fstat(x,(g,w)=>{if(g)return ot.close(x,()=>c(g));i(x,w.size,(S,_)=>{if(S)return c(S);let E=new io(t.file,{fd:x,start:_});r.pipe(E),E.on("error",c),E.on("close",o),ry(r,e)})})};ot.open(t.file,d,u)})},ny=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:Wf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},ry=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:Wf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},Si=Ni(Q_,ty,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Ew(t))throw new TypeError("file is required");if(t.gzip||t.brotli||t.zstd||t.file.endsWith(".br")||t.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!e?.length)throw new TypeError("no paths specified to add/replace")}),HA=Ni(Si.syncFile,Si.asyncFile,Si.syncNoFile,Si.asyncNoFile,(t,e=[])=>{Si.validate?.(t,e),iy(t)}),iy=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))};hn();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 fo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Kf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ho(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function $f(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function Vf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Zf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Zn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Jt();Ke();ne();Re();Ke();function Rr(t,e){if(fo(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Mi(t){return t.startsWith("http://")||t.startsWith("https://")}function Dr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as Ok}from"node:fs";import{dirname as Nk,join as Mk}from"node:path";import{fileURLToPath as Fk}from"node:url";var Ot="0.2.7-alpha.13";Ke();ne();var xo="1008033",Qf="1289";var e0="pbbp2",t0="https://www.coze.cn",n0="/api/coze_claw/resource/get_frontier_key",fy="https://www.coze.cn",hy="wss://frontier.coze.cn";function Pr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??fy}function r0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??hy}function An(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 Fi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Bi=H("handshake");async function Zc(t){let e=Pr(t.endpoint),r=t.timeoutMs??1e4,i=`${Dr(e)}${n0}?aid=${encodeURIComponent(xo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...An(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Bi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),h=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let E=await u.text().catch(()=>"");throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${E.slice(0,200)}`)}let g=await u.json();if(g.code!==void 0&&g.code!==0)throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${g.code} msg=${g.msg??"-"} logid=${h}`);let w=g.data??{},S=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,_=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!S||!_){let E=JSON.stringify(g).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${E}`)}return Bi.info("handshake ok",{remoteDeviceId:_,logid:h,traceId:x}),{accessKey:S,deviceId:_}}catch(u){if(u instanceof T)throw Bi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Bi.warn("handshake timeout",{base:e,timeoutMs:r}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let h=u.cause;throw Bi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:h?.code,syscall:h?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var Yc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Lt="auto",Jc=15e4,i0=32e3;function o0(t){return{model:Xc(t.model)??Lt,...t.modelToken?{modelToken:t.modelToken}:{}}}function a0(t){return!t||t===Lt}var xy=new Set(["auto","\u81EA\u52A8"]);function Xc(t){let e=t?.trim();if(e)return xy.has(e.toLowerCase())?Lt:e}function c0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Yc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||Lt;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)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else a0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function d0(t,e,r,i){let o={};if(t.modelToken?o.model=t.model||Lt:a0(t.model)||(o.model=t.model),t.modelToken){let c={name:"coze",base_url:`${Yc}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=Qc(e,r,i);Object.keys(d).length>0&&(c.http_headers=d),o.model_providers={coze:c},o.model_context_window=t.modelInfo?.contextWindow??Jc}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function l0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Qc(t,e,r){let{ttEnv:i,usePpe:o}=Fi(t),c={};return i&&(c["x-tt-env"]=i),o&&(c["x-use-ppe"]=o),e&&(c["x-mock-scenario"]=e),r&&(c["x-coze-request-scene"]=r),c}function u0(t,e,r,i){if(!t.modelToken)return{};let o=Qc(e,r,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,u])=>`${d}:${u}`).join(`
92
- `)}}function ed(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function td(t){return t.model||Lt}function s0(t,e,r,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:r,maxTokens:i,api:"openai-completions"}}function f0(t,e,r,i,o){if(!t.modelToken)return null;let c=td(t),d=Qc(e,r,o),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let h=[s0(c,u,t.modelInfo?.contextWindow??Jc,t.modelInfo?.maxOutput??i0)],x=new Set([c]);for(let w of i??[])!w||x.has(w)||(x.add(w),h.push(s0(w,["text"],Jc,i0)));let g={baseUrl:`${Yc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:h};return Object.keys(d).length>0&&(g.headers=d),g}var he=H("agent-handlers"),x0=5*1024*1024,_y=1,yy=6,by=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ey=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,vy=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Sy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Iy(t){let e=t?.trim();return e?Sy.test(e)||vy.test(e)?e:(he.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Ay(t){return new Promise((e,r)=>{let i=it("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=d=>{o||(o=!0,d?r(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",d=>c(d))})}var go=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Zn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??$e(r).workspace,c=i?.skills??[],d=[],u=new Set;for(let h of c){let x=xe(o,h.relPath,"SKILL.md");await cd(x).then(w=>w.isFile()).catch(()=>!1)&&(d.push(Dy(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",x=await I0(r,o,h),g=await A0(r,h);for(let w of[...x,...g])u.has(w.relPath)||(u.add(w.relPath),d.push(w.skill))}return{skills:d}}async addSkills(e){e._meta;let r=Zn(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((h,x)=>[h.skillId,x])),u=[];for(let h of o){let x=await mo({agentId:r,workspace:i.workspace,framework:i.framework,skill:h});wo(c,d,x),u.push(h)}return await ci(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Zn(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],d=[];for(let u of c){if(!o.has(u.skillId)){d.push(u);continue}let h=xe(i.workspace,u.relPath);await id(h,{recursive:!0,force:!0}),he.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await ci(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Zn(e._meta);if(!e.skillName)throw new T("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");he.info("_agent/publishSkill start",{agentId:r,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(r),o=i?.workspace??$e(r).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=await Ty(r,o,c,e.skillName,d);if(!u){let P=d?"global":"workspace";throw new T("SKILL_NOT_FOUND",`skill not found in ${P}: ${e.skillName}`)}let{absDir:h,relPath:x,dirName:g}=u,w=xe(h,"SKILL.md"),S=new ld.default;S.addLocalFolder(h,g);let _=S.toBuffer();if(_.length>p0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${p0}`);let E=await po(w,{encoding:"utf8"}).then(P=>v0(P).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...E?{description:E}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):he.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let k=I.version??"v1.0",C=I.skillId??e.skillId??E0(r,x);if(i&&!d){let P=i.skills??[],b=P.find(R=>R.relPath===x);b?(b.version=k,b.skillId=C):P.push({skillId:C,skillName:e.skillName,relPath:x,version:k,installedAt:Date.now(),...E?{description:E}:{}}),await ci(r,P)}return he.info("skill published",{agentId:r,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:C,version:k}),{ok:!0,skillId:C,version:k}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,he.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let h=c.downstream;c.downstream=void 0,he.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),h.stop(r).catch(x=>he.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return he.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await De(r);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return he.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await hr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw he.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Fe(i),he.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new T("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await De(r))throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Mi(e.registry)&&o.push(`--registry=${e.registry}`);let c=Iy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&Ey.test(d)&&o.push("--env",d);let u=await Ay(o);return he.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new T("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await De(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Fe(i),he.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(he.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new T("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 d=$e(r);return c==="cloud"?await id(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Fe(i)),he.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 T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Xc(e.model)??Lt,i=await De(e.agentId);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Fe(i),he.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return he.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model;o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(u=>he.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)}));let d=[];for(let[u,h]of o.allSessionQueues())d.push(h.enqueue(async()=>{let x=o.sessions.get(u);x?.downstream&&(await x.downstream.stop(`switchModel: ${r}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(d),he.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:d.length}),{ok:!0}}async resetAgent(e){if(Rr(e._meta,ft.RESET),!e.agentId)throw new T("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),he.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await ai(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 Fe(r)}async repairAgent(e){if(Rr(e._meta,ft.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ft.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("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){he.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){he.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){he.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Rr(e._meta,"_agent/getFileTree");let r=e._meta,i=Zn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await nd(d).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await oi(d,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=Gy(e.depth);return u.isDirectory()?{tree:await Hy(o,d,c,h)}:{tree:[{name:jy(c),path:C0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Rr(e._meta,"_agent/getFileContent");let r=Zn(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new T("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await nd(o).catch(()=>null);if(!c||!c.isFile())throw new T("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await oi(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>x0)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${x0})`);let d=await po(o);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:c.size}:{content:d.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await De(e).catch(()=>null))?.workspace??$e(e).workspace}safeJoin(e,r){let i=od(e,r||"."),o=dd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${m0}`))throw new T("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 T("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function y0(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 ud(t){return t==="claude-code"?xe(".claude","skills"):xe(".agents","skills")}function b0(t){let e=gy();return t==="claude-code"?[xe(e,".claude","skills")]:t==="codex"?[xe(e,".agents","skills"),xe(e,".codex","skills")]:[xe(e,".agents","skills"),xe(e,".openclaw","skills")]}async function ky(t,e,r,i){let o=async c=>cd(xe(c,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let c=xe(ud(e),r),d=xe(t,c);return await o(d)?{absDir:d,relPath:c}:null}for(let c of b0(e)){let d=xe(c,r);if(await o(d))return{absDir:d,relPath:d}}return null}async function Ty(t,e,r,i,o){let c=y0(i),d=await ky(e,r,c,o);if(d)return{...d,dirName:c};let h=(o?await A0(t,r):await I0(t,e,r)).filter(w=>w.skill.skillName===i);if(h.length>1)throw new T("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${h.map(w=>h0(w.relPath)).join(", ")} \u2014 rename or remove duplicates`);let x=h[0];return x?{absDir:o?x.relPath:xe(e,x.relPath),relPath:x.relPath,dirName:h0(x.relPath)}:null}function E0(t,e){return(py("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function v0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
- ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
94
- `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function S0(t,e,r,i){let o=await g0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let d of o){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await cd(xe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=d.name,x=xe(r,h),g=xe(e,h,"SKILL.md"),w=await po(g,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let S=v0(w);c.push({relPath:x,skill:{skillId:E0(t,x),skillName:S.name||h,...S.description?{description:S.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function I0(t,e,r){let i=ud(r);return S0(t,xe(e,i),i,!1)}async function A0(t,e){let r=[],i=new Set;for(let o of b0(e)){let c=await S0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var Cy=3e4,Ry=50*1024*1024,p0=10*1024*1024,Or=3e4;async function mo(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new T("IPC_BAD_REQUEST","skill missing skillName");let c=typeof o.content=="string"&&o.content.length>0,d=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!d)throw new T("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=y0(o.skillName),h=ud(i),x=xe(h,u),g=xe(r,x);if(await rd(g,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");zi(S.length),await sd(xe(g,"SKILL.md"),S,"utf8")}else{let S=await Oy(o.downloadUrl);Ny(S)?await zy(S,g):My(S)?await By(S,g):await sd(xe(g,"SKILL.md"),S.toString("utf8"),"utf8")}let w={skillId:o.skillId,skillName:o.skillName,relPath:x,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return he.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:c?"content":"downloadUrl"}),w}function wo(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 Dy(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 Py(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 k0(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=Ot,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await Fe(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=new Map(c.map((g,w)=>[g.skillId,w])),u=c.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Fe(r,e),{status:"noop",count:0};let h=0,x=0;for(let g of u)try{await id(xe(r.workspace,g.relPath),{recursive:!0,force:!0});let w=await mo({agentId:t,workspace:r.workspace,framework:r.framework,skill:Py(g)});wo(c,d,w),h+=1}catch(w){x+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(w)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await Fe(r,e),he.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function Oy(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);zi(e);let r=Ly(t);return zi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await po(e);return zi(r.length),r}if(Mi(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),Cy);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new T("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return zi(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new T("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function zi(t){if(t>Ry)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Ly(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new T("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function Ny(t){return t.length>=2&&t[0]===31&&t[1]===139}function My(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 ad(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function By(t,e){let r,i;try{r=new ld.default(t),i=r.getEntries()}catch(d){throw new T("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||ad(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new T("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=Fy(i),c=od(e);for(let d of i){if(ad(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=od(e,u),x=dd(c,h);if(x.startsWith("..")||x==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await rd(h,{recursive:!0});continue}await rd(my(h),{recursive:!0});let g;try{g=d.getData()}catch(w){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await sd(h,g)}}function Fy(t){let e;for(let r of t){let i=r.entryName;if(!i||ad(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 zy(t,e){await Uy(t);let r=jf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await _0(w0.from(t),r)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Uy(t){let e=[],r=Cr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await _0(w0.from(t),r)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var qy=5e3;async function Hy(t,e,r,i){return T0(t,e,r,i,{count:0})}async function T0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await g0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(by.has(u.name)||u.isSymbolicLink())continue;if(o.count>=qy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=xe(e,u.name),x=wy(xe(r,u.name)),g=null;try{g=await nd(h)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let w={name:u.name,path:C0(dd(t,h)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(w.children=await T0(t,h,x,i-1,o)),d.push(w)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function Gy(t){return!t||t<=0?_y:Math.min(t,yy)}function jy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function C0(t){return t.split(m0).join("/")}ne();var kn=H("agent-health-reporter"),Wy=1e4,Ky=3,Ui=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Wy,this.livenessFailureThreshold=e.livenessFailureThreshold??Ky}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()}),kn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),kn.info("heartbeat stopped"))}async tick(){if(this.inFlight){kn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,kn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let d of this.opts.core.agents.values()){let u=$y(d);if(!u)continue;let h={agentId:d.agentId,status:u};d.patToken&&(h.patToken=d.patToken),d.accountId&&(h.accountId=d.accountId),r.push(h)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Ot,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,kn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(kn.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(d){kn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){kn.warn("onTickEnd hook failed",{err:String(r)})}}};function $y(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}hn();import{mkdir as yd,rm as lE,stat as uE}from"node:fs/promises";import{homedir as fE}from"node:os";import{join as bd}from"node:path";cn();import{existsSync as ob}from"node:fs";import{release as ab}from"node:os";import{basename as cb,isAbsolute as db}from"node:path";function qi(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 Tn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ke();var _o=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)}},Y={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 R0(t){return"method"in t&&"id"in t&&t.id!==void 0}function D0(t){return"method"in t&&!("id"in t)}function yo(t){return!("method"in t)&&"id"in t}var Vy={AGENT_NOT_FOUND:Y.AGENT_NOT_FOUND,AGENT_BUSY:Y.AGENT_BUSY,AGENT_DISCONNECTED:Y.AGENT_DISCONNECTED,AGENT_TIMEOUT:Y.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Y.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Y.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Y.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Y.INTERNAL_ERROR,BRIDGE_INTERNAL:Y.INTERNAL_ERROR,IPC_AUTH_FAILED:Y.INTERNAL_ERROR,IPC_BAD_REQUEST:Y.INVALID_REQUEST,METHOD_NOT_FOUND:Y.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Y.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Y.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Y.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Y.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Y.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Y.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Y.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Y.FILE_TOO_LARGE,UNSUPPORTED_MIME:Y.UNSUPPORTED_MIME,UPLOAD_FAILED:Y.UPLOAD_FAILED,UPSTREAM_NOT_READY:Y.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Y.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Y.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Y.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Y.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Y.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Y.SKILL_ZIP_TOO_LARGE};function Zy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Hi(t.message)}:typeof t=="string"?Hi(t):typeof t=="object"?Yy(t):t}var Jy=[[/\/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 Hi(t){let e=t;for(let[r,i]of Jy)e=e.replace(r,i);return e}function Yy(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Hi(i):e[r]=i;return e}function Gi(t){if(t instanceof T){let e=Zy(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:Vy[t.code]??Y.INTERNAL_ERROR,message:Hi(t.message),data:r}}return{code:Y.INTERNAL_ERROR,message:Hi(t instanceof Error?t.message:String(t))}}function P0(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:d,...u}=e;c=u}return new T(r,o,{retriable:e?.retriable??!1,cause:c})}function L0(t){return`${JSON.stringify(t)}
95
- `}var O0=10*1024*1024,bo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>O0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${O0} bytes`)}),[]}let r=this.buffer.split(`
96
- `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(d){this.onError?.({line:c,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var M0={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission","session/set_mode":"session.setMode",initialize:"initialize"},vT=Object.fromEntries(Object.entries(M0).map(([t,e])=>[e,t])),Xy={"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=M0[e]??Qy(e),o=Xy[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(h=>N0(r?.[h]??"")),u=eb(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>N0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function Qy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function N0(t){return t.replace(/[:_\s]+/g,"-")}function eb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}fn();import{readFileSync as tb}from"node:fs";var nb=384;async function fd(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await un(t.agentEnvFile,r,{mode:nb})}function ji(t){try{let e=JSON.parse(tb(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Eo(t,e,r={},i=o=>o){return{...i({...t,...ji(e)}),...r}}Jt();cr();Ke();ne();Re();import{execFileSync as rb,spawnSync as ib}from"node:child_process";function Wi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Ki(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),ib("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var hd=new Set;function B0(t){typeof t=="number"&&t>0&&hd.add(t)}function F0(t){typeof t=="number"&&hd.delete(t)}function z0(){for(let t of hd)Ki(t,"SIGKILL")}var Br="coze-bridge-daemon";function U0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return rb("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 q0(t,e){if(t.length===0)return;let r=e?.killFn??Ki,i=e?.isAliveFn??Wi,o=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),c=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(h=>i(h));u+=d)await o(Math.min(d,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var sb=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]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 H0(t,e){if(!e)return null;for(let r of sb)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function G0(t,e){return H0(t,e)}function j0(t,e){return H0(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 W0(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,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:Fr(c,!0,e)}: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 K0=Je("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),lb=200,ub=40,fb=Je("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),hb=Je("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),xb=Je("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),pb=Je("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),gb=Je("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),mb=Je("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),$0=500;function wb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=$0?t:`${e.slice(0,$0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function _b(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 V0(t){try{return ob(t)}catch{return}}function yb(t,e){return{platform:process.platform,osRelease:ab(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:db(e.command)?V0(e.command):void 0,cwd:e.cwd,cwdExists:V0(e.cwd),envKeys:e.envKeys}}function bb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${cb(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 bo({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 T("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=Eo(process.env,this.opts.agentEnvFile??J().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>lb&&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,F0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,d=yb(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new T("AGENT_SPAWN_FAILED",bb(c,d),{cause:d}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));Ki(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||Ki(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:gb,phase2GateMs:fb,livenessWindowMs:hb,absoluteMaxMs:xb,approvalMaxMs:mb,suspendThresholdMs:pb,...r};return this.call("session/prompt",e,K0,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(Tn(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=K0,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=qi(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let h=r.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let g={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),S={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:Fr(0,!1,o),sessionId:u};g.promptTimeout=S;let _=()=>{let E={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(),k=W0(E,S.cfg,I),C=P=>{S.armedAt=I,S.expectedIntervalMs=P,g.timer=setTimeout(_,P)};if(k.action==="suspend"){S.suspendedMs+=k.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:k.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),C(k.rearmMs);return}if(k.action==="continue"){C(k.rearmMs);return}this.pending.delete(c),k.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:k.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),x(k.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};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 T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,g);try{this.writeFrame(d)}catch(w){g.timer&&clearTimeout(g.timer),this.pending.delete(c),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(L0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(yo(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new T("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:wb(e.result)}),r.resolve(e.result));return}if(D0(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(R0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Tn(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(Tn(e.id,Gi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=P0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=j0(this.framework,_b(e));return i?new T(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):r}buildExitError(e,r){if(this.stopReason!==void 0)return new T("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(ub).join(`
98
- `),o=G0(this.framework,i);return o?new T(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new T("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${r})`,{cause:{code:e,signal:r,stderrTail:i}})}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Eb(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 vo=class extends Nt{framework="claude-code";constructor(e){let{command:r,args:i}=si("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 Eb(e)}};cn();import{spawn as vb}from"node:child_process";import{closeSync as Sb,existsSync as gd,mkdirSync as Ib,mkdtempSync as Ab,openSync as kb,readFileSync as eh,readSync as Tb,readdirSync as Cb,rmSync as Rb,statSync as Db}from"node:fs";import{homedir as Pb,tmpdir as Ob}from"node:os";import{join as zr}from"node:path";var Z0=["default","acceptEdits","plan","auto","bypassPermissions"],J0=["read-only","auto","full-access"];function Mt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return Z0.includes(e);case"codex":return J0.includes(e);case"openclaw":return!1}}function So(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Y0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function xd(t){switch(t){case"claude-code":return Z0.join("/");case"codex":return J0.join("/");case"openclaw":return""}}Re();var md=9e4,Lb=64*1024,Nb=100;function Mb(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?md:Math.max(1,Math.floor(e*1e3))}function Bb(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?md:Math.max(1,Math.floor(e))}function Fb(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 X0(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:md};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=Fb(e.env);return{command:r,timeoutMs:e.timeout_ms===void 0?Mb(e.timeout):Bb(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function pd(t){if(Array.isArray(t))return t.flatMap(i=>pd(i));if(!t||typeof t!="object"){let i=X0(t);return i?[i]:[]}let e=t;if(e.hooks)return pd(e.hooks);let r=X0(e);return r?[r]:[]}function zb(t){let e=zr(t,"hooks.json");if(!gd(e))return[];let r=JSON.parse(eh(e,"utf8")),o=r.hooks&&typeof r.hooks=="object"?r.hooks:r;return pd(o.Stop??o.stop)}function Ub(t,e){let r=zr(t,"sessions");if(!gd(r))return;let i=[],o=c=>{let d;try{d=Cb(c,{withFileTypes:!0})}catch{return}for(let u of d){let h=zr(c,u.name);if(u.isDirectory())o(h);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:h,mtimeMs:Db(h).mtimeMs})}catch{}}};o(r),i.sort((c,d)=>d.mtimeMs-c.mtimeMs);for(let c of i.slice(0,Nb))if(qb(c.path,e))return c.path;return i[0]?.path}function qb(t,e){let r;try{r=kb(t,"r");let i=Buffer.alloc(Lb),o=Tb(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{Sb(r)}catch{}}}function Hb(t){return ji(t??J().agentEnvFile)}function Gb(t){let e=t.trim();if(e.length>=2){let r=e[0];if((r==='"'||r==="'")&&e.endsWith(r)){let i=e.slice(1,-1);return r==='"'?i.replace(/\\n/g,`
99
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function jb(t){let e={};for(let r of t.split(/\r?\n/)){let i=r.trim();if(!i||i.startsWith("#"))continue;let o=i.startsWith("export ")?i.slice(7).trimStart():i,c=o.indexOf("=");if(c<=0)continue;let d=o.slice(0,c).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=Gb(o.slice(c+1)))}return e}function Wb(t){let e=zr(t,"cozeloop.env");return gd(e)?jb(eh(e,"utf8")):{}}function Q0(t){let e=t?.trim();return e||void 0}function Kb(t){let e=Hb(t.agentEnvFile),r=Q0(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(r)return r;let i=Q0(t.env?.HOME??e.HOME??process.env.HOME)??Pb();return zr(i,".codex")}var Io=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}=si("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Ab(zr(Ob(),"coze-bridge-codex-home-")):Kb(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&Ib(d,{recursive:!0});let h=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...h?{env:h}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=d,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}setSessionMode(e){let r=Mt("codex",e.modeId)?So(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e($b(r)))}async runStopHooksBestEffort(e){let r=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!r)return;let i;try{i=zb(r)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:r,err:String(d)});return}if(i.length===0)return;let o=Ub(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 d=>{try{await this.runHookCommand(d,c)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:r,command:d.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,r){return new Promise((i,o)=>{let c=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=c?Wb(c):{},u=vb(e.command,{cwd:e.cwd??this.opts.cwd,env:Eo(process.env,this.opts.agentEnvFile??J().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}}),shell:!0,stdio:["pipe","ignore","pipe"]}),h="",x=setTimeout(()=>{u.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);u.stderr?.setEncoding("utf8"),u.stderr?.on("data",g=>{h+=g,h.length>4e3&&(h=h.slice(-4e3))}),u.on("error",g=>{clearTimeout(x),o(g)}),u.on("close",(g,w)=>{if(clearTimeout(x),g===0){i();return}o(new Error(`hook exited code=${g} signal=${w} stderr=${h.slice(-1e3)}`))}),u.stdin.end(`${r}
100
- `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{Rb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function $b(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=Y0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}Ke();var Vb=3e4,Ur=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}`}]},Vb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};fn();Ke();ne();Re();function wd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}cn();var Cn=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((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 Ao=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)qr(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 qr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Yt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Jt();ne();import{constants as th}from"node:fs";import{access as Zb}from"node:fs/promises";import{delimiter as Jb,join as Yb}from"node:path";var Et=H("framework-detector"),nh={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},Xb=[".exe",".cmd",".bat",".ps1"],Jn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??it,access:e.access??Zb}}async detect(e){let r=nh[e],i=await this.which(r);if(!i)return Et.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(nh).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(Jb).filter(Boolean),i=this.env.platform==="win32"?["",...Xb]:[""];for(let o of r)for(let c of i){let d=Yb(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?th.F_OK:th.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return Et.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return Et.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return Et.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return Et.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(Et.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(Et.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return Et.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return Et.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||Et.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let d=JSON.parse(c[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){Et.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(eE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,d,u=h=>{c||(c=!0,d&&clearTimeout(d),i(h))};try{let h=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{o+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},Qb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function eE(t){return t.replace(Qb,"")}import{homedir as ih}from"node:os";import{join as To}from"node:path";fn();Jt();cr();Ke();ne();async function sh(){let t=To(ih(),".openclaw/openclaw.json");return dn(t)}async function oh(){return(await sh())?.gateway?.auth?.token??""}var Yn=H("openclaw.config"),tE=[0,5e3,5e3],nE=Je("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),rh="models.providers.",ko="agents.defaults.models",rE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function _d(t,e){if(!Array.isArray(t))return!1;let r=new Set(t);return e.every(i=>r.has(i))}var Co=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??tE,this.cliTimeoutMs=e.cliTimeoutMs??nE,this.openclawDir=e.openclawDir??To(ih(),".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(d=>setTimeout(d,c));try{return await r()}catch(d){i=d,Yn.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new T("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=it(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=x=>{d||(d=!0,clearTimeout(h),x())};o.stderr?.on("data",x=>{c+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.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.runCliTolerant(["config","unset",r],["Config path not found","Nothing was changed"])))}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",`${rh}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${rh}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${ko}[${e}]`,()=>this.runCli(["config","set",ko,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${ko}[${e}]`,`${ko}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await sh())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,c=[];for(let d of Object.keys(i))d.startsWith(o)&&c.push(d.slice(o.length));return c}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=To(this.openclawDir,"identity","device.json"),i=(await dn(e))?.deviceId?.trim();if(!i)return Yn.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=To(this.openclawDir,"devices","paired.json"),c=await dn(o),d=c?.[i];if(!c||!d)return Yn.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=[...rE],h=d.tokens?.operator;return _d(d.scopes,u)&&_d(d.approvedScopes,u)&&_d(h?.scopes,u)?(Yn.debug("acp device already has full operator scopes",{deviceId:i}),!1):(d.scopes=[...u],d.approvedScopes=[...u],h&&(h.scopes=[...u]),await un(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"])))}};import{readFile as iE,writeFile as sE}from"node:fs/promises";import{join as oE}from"node:path";var aE=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
101
- `),cE=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
102
- `);function dE(t){return t.length===0?t:`${(t.endsWith(`
89
+ `},configPath(t){return YI(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 Hp("schtasks",["/Create","/SC","ONLOGON","/TN",Sa,"/TR",n,"/RU",t.userName,"/F"]),pl.info("task scheduler entry created",{task:Sa,logFile:t.logFile})},async uninstall(t){await Hp("schtasks",["/Delete","/TN",Sa,"/F"]).catch(e=>pl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),pl.info("task scheduler entry removed",{task:Sa})}}});var jp={};Ma(jp,{buildContext:()=>n2,getSupervisor:()=>QI,launchdSupervisor:()=>hl,systemdSupervisor:()=>xl,taskSchedulerSupervisor:()=>gl});import{homedir as JI,userInfo as XI}from"node:os";function QI(t=process.platform){switch(t){case"darwin":return hl;case"linux":return xl;case"win32":return gl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function t2(){let t={};for(let e of e2){let n=process.env[e];n&&(t[e]=n)}return t}function n2(){let t=J();return{nodeBin:process.execPath,entry:il(t),logFile:t.logFile,homeDir:JI(),userName:XI().username,isRoot:process.getuid?.()===0,env:t2()}}var e2,Wp=nt(()=>{"use strict";De();xa();zp();Gp();qp();e2=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ie();ln();var Kl=H("acp-installer-warmup"),ym=["claude-code","codex"];async function $l(t={}){let e=t.ensure??pr,i=(await Promise.allSettled(ym.map(async o=>{let c=await e(o);Kl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Kl.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}pn();ie();import{readdir as Mm}from"node:fs/promises";import{mkdir as Jl,readFile as Lm,writeFile as Xl}from"node:fs/promises";import{join as qa}from"node:path";var Nm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function gr(t,e,n){await Jl(t,{recursive:!0});let i=Nm[e],o=qa(t,i);return await Xl(o,n??"","utf8"),o}async function ja(t,e,n){let i=qa(t,".claude");await Jl(i,{recursive:!0});let o=qa(i,"settings.local.json"),c={};try{let u=await Lm(o,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}catch{}let d=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return c.permissions=d,await Xl(o,JSON.stringify(c,null,2),"utf8"),o}var Qe=H("agent-detail-sync"),Bm=6e4,Fm=5*6e4,Ts=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await Mm(n)}catch(o){Qe.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}Qe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await Pe(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Qe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(d){Qe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Qe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&n.push(i);if(n.length!==0){Qe.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){Qe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await Pe(e,this.opts.paths);if(!i){Qe.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){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,Fm):Bm;this.retryQueue.set(e,{dueAt:Date.now()+p,currentDelay:p});return}if(o.agentId&&o.agentId!==e){Qe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Qe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Qe.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Qe.debug("detail sync: no diff",{agentId:e});return}await Ge(i,this.opts.paths),Qe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Qe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await gr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var pd=qt(Du(),1);import{createHash as yy}from"node:crypto";import{lstat as ad,mkdir as cd,readFile as bo,readdir as _0,rm as dd,stat as hd,writeFile as ld}from"node:fs/promises";import{homedir as by}from"node:os";import{basename as g0,dirname as Ey,join as me,normalize as vy,relative as xd,resolve as ud,sep as y0}from"node:path";import{Readable as b0}from"node:stream";import{pipeline as E0}from"node:stream/promises";import ow from"events";import it from"fs";import{EventEmitter as jc}from"node:events";import xf from"node:stream";import{StringDecoder as aw}from"node:string_decoder";import mf from"node:path";import Tr from"node:fs";import{dirname as yw,parse as bw}from"path";import{EventEmitter as Cw}from"events";import Ic from"assert";import{Buffer as Vn}from"buffer";import*as Mu from"zlib";import Rw from"zlib";import{posix as br}from"node:path";import{basename as i_}from"node:path";import oo from"fs";import Dt from"fs";import ju from"path";import{win32 as m_}from"node:path";import Ju from"path";import Pf from"node:fs";import L_ from"node:assert";import{randomBytes as Of}from"node:crypto";import oe from"node:fs";import Fe from"node:path";import Lf from"fs";import go from"node:fs";import Pi from"node:path";import ct from"node:fs";import G_ from"node:fs/promises";import lo from"node:path";import{join as Wf}from"node:path";import at from"node:fs";import Vf from"node:path";var iw=Object.defineProperty,sw=(t,e)=>{for(var n in e)iw(t,n,{get:e[n],enumerable:!0})},Pu=typeof process=="object"&&process?process:{stdout:null,stderr:null},cw=t=>!!t&&typeof t=="object"&&(t instanceof Jn||t instanceof xf||dw(t)||lw(t)),dw=t=>!!t&&typeof t=="object"&&t instanceof jc&&typeof t.pipe=="function"&&t.pipe!==xf.Writable.prototype.pipe,lw=t=>!!t&&typeof t=="object"&&t instanceof jc&&typeof t.write=="function"&&typeof t.end=="function",jt=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),mn=Symbol("emittedEnd"),Os=Symbol("emittingEnd"),xi=Symbol("emittedError"),Ls=Symbol("closed"),Ou=Symbol("read"),Ns=Symbol("flush"),Lu=Symbol("flushChunk"),_t=Symbol("encoding"),yr=Symbol("decoder"),He=Symbol("flowing"),pi=Symbol("paused"),Ir=Symbol("resume"),qe=Symbol("buffer"),et=Symbol("pipes"),je=Symbol("bufferLength"),Ya=Symbol("bufferPush"),Ms=Symbol("bufferShift"),Xe=Symbol("objectMode"),Te=Symbol("destroyed"),Ja=Symbol("error"),Xa=Symbol("emitData"),Nu=Symbol("emitEnd"),Qa=Symbol("emitEnd2"),kt=Symbol("async"),ec=Symbol("abort"),Bs=Symbol("aborted"),gi=Symbol("signal"),zn=Symbol("dataListeners"),ot=Symbol("discarded"),mi=t=>Promise.resolve().then(t),uw=t=>t(),fw=t=>t==="end"||t==="finish"||t==="prefinish",hw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,xw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),pf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Ir](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},pw=class extends pf{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)}},gw=t=>!!t.objectMode,mw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Jn=class extends jc{[He]=!1;[pi]=!1;[et]=[];[qe]=[];[Xe];[_t];[kt];[yr];[jt]=!1;[mn]=!1;[Os]=!1;[Ls]=!1;[xi]=null;[je]=0;[Te]=!1;[gi];[Bs]=!1;[zn]=0;[ot]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");gw(e)?(this[Xe]=!0,this[_t]=null):mw(e)?(this[_t]=e.encoding,this[Xe]=!1):(this[Xe]=!1,this[_t]=null),this[kt]=!!e.async,this[yr]=this[_t]?new aw(this[_t]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[qe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:n}=e;n&&(this[gi]=n,n.aborted?this[ec]():n.addEventListener("abort",()=>this[ec]()))}get bufferLength(){return this[je]}get encoding(){return this[_t]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Xe]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[kt]}set async(t){this[kt]=this[kt]||!!t}[ec](){this[Bs]=!0,this.emit("abort",this[gi]?.reason),this.destroy(this[gi]?.reason)}get aborted(){return this[Bs]}set aborted(t){}write(t,e,n){if(this[Bs])return!1;if(this[jt])throw new Error("write after end");if(this[Te])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[kt]?mi:uw;if(!this[Xe]&&!Buffer.isBuffer(t)){if(xw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(hw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Xe]?(this[He]&&this[je]!==0&&this[Ns](!0),this[He]?this.emit("data",t):this[Ya](t),this[je]!==0&&this.emit("readable"),n&&i(n),this[He]):t.length?(typeof t=="string"&&!(e===this[_t]&&!this[yr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[_t]&&(t=this[yr].write(t)),this[He]&&this[je]!==0&&this[Ns](!0),this[He]?this.emit("data",t):this[Ya](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[Te])return null;if(this[ot]=!1,this[je]===0||t===0||t&&t>this[je])return this[Wt](),null;this[Xe]&&(t=null),this[qe].length>1&&!this[Xe]&&(this[qe]=[this[_t]?this[qe].join(""):Buffer.concat(this[qe],this[je])]);let e=this[Ou](t||null,this[qe][0]);return this[Wt](),e}[Ou](t,e){if(this[Xe])this[Ms]();else{let n=e;t===n.length||t===null?this[Ms]():typeof n=="string"?(this[qe][0]=n.slice(t),e=n.slice(0,t),this[je]-=t):(this[qe][0]=n.subarray(t),e=n.subarray(0,t),this[je]-=t)}return this.emit("data",e),!this[qe].length&&!this[jt]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[jt]=!0,this.writable=!1,(this[He]||!this[pi])&&this[Wt](),this}[Ir](){this[Te]||(!this[zn]&&!this[et].length&&(this[ot]=!0),this[pi]=!1,this[He]=!0,this.emit("resume"),this[qe].length?this[Ns]():this[jt]?this[Wt]():this.emit("drain"))}resume(){return this[Ir]()}pause(){this[He]=!1,this[pi]=!0,this[ot]=!1}get destroyed(){return this[Te]}get flowing(){return this[He]}get paused(){return this[pi]}[Ya](t){this[Xe]?this[je]+=1:this[je]+=t.length,this[qe].push(t)}[Ms](){return this[Xe]?this[je]-=1:this[je]-=this[qe][0].length,this[qe].shift()}[Ns](t=!1){do;while(this[Lu](this[Ms]())&&this[qe].length);!t&&!this[qe].length&&!this[jt]&&this.emit("drain")}[Lu](t){return this.emit("data",t),this[He]}pipe(t,e){if(this[Te])return t;this[ot]=!1;let n=this[mn];return e=e||{},t===Pu.stdout||t===Pu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[et].push(e.proxyErrors?new pw(this,t,e):new pf(this,t,e)),this[kt]?mi(()=>this[Ir]()):this[Ir]()),t}unpipe(t){let e=this[et].find(n=>n.dest===t);e&&(this[et].length===1?(this[He]&&this[zn]===0&&(this[He]=!1),this[et]=[]):this[et].splice(this[et].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[ot]=!1,this[zn]++,!this[et].length&&!this[He]&&this[Ir]();else if(t==="readable"&&this[je]!==0)super.emit("readable");else if(fw(t)&&this[mn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[xi]){let i=e;this[kt]?mi(()=>i.call(this,this[xi])):i.call(this,this[xi])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[zn]=this.listeners("data").length,this[zn]===0&&!this[ot]&&!this[et].length&&(this[He]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[zn]=0,!this[ot]&&!this[et].length&&(this[He]=!1)),e}get emittedEnd(){return this[mn]}[Wt](){!this[Os]&&!this[mn]&&!this[Te]&&this[qe].length===0&&this[jt]&&(this[Os]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ls]&&this.emit("close"),this[Os]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Te&&this[Te])return!1;if(t==="data")return!this[Xe]&&!n?!1:this[kt]?(mi(()=>this[Xa](n)),!0):this[Xa](n);if(t==="end")return this[Nu]();if(t==="close"){if(this[Ls]=!0,!this[mn]&&!this[Te])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[xi]=n,super.emit(Ja,n);let o=!this[gi]||this.listeners("error").length?super.emit("error",n):!1;return this[Wt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Wt](),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[Wt](),i}[Xa](t){for(let n of this[et])n.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[Wt](),e}[Nu](){return this[mn]?!1:(this[mn]=!0,this.readable=!1,this[kt]?(mi(()=>this[Qa]()),!0):this[Qa]())}[Qa](){if(this[yr]){let e=this[yr].end();if(e){for(let n of this[et])n.dest.write(e);this[ot]||super.emit("data",e)}}for(let e of this[et])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Xe]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Xe]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Xe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[_t]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Te,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ot]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[jt])return e();let i,o,c=x=>{this.off("data",d),this.off("end",u),this.off(Te,f),e(),o(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(Te,f),this.pause(),i({value:x,done:!!this[jt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Te,f),e(),i({done:!0,value:void 0})},f=()=>c(new Error("stream destroyed"));return new Promise((x,p)=>{o=p,i=x,this.once(Te,f),this.once("error",c),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ot]=!1;let t=!1,e=()=>(this.pause(),this.off(Ja,e),this.off(Te,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(Ja,e),this.once(Te,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Te])return t?this.emit("error",t):this.emit(Te),this;this[Te]=!0,this[ot]=!0,this[qe].length=0,this[je]=0;let e=this;return typeof e.close=="function"&&!this[Ls]&&e.close(),t?this.emit("error",t):this.emit(Te),this}static get isStream(){return cw}},ww=it.writev,An=Symbol("_autoClose"),vt=Symbol("_close"),wi=Symbol("_ended"),le=Symbol("_fd"),tc=Symbol("_finished"),Zt=Symbol("_flags"),nc=Symbol("_flush"),vc=Symbol("_handleChunk"),Sc=Symbol("_makeBuf"),Ri=Symbol("_mode"),Fs=Symbol("_needDrain"),Rr=Symbol("_onerror"),Dr=Symbol("_onopen"),rc=Symbol("_onread"),Ar=Symbol("_onwrite"),kn=Symbol("_open"),Et=Symbol("_path"),bn=Symbol("_pos"),Tt=Symbol("_queue"),kr=Symbol("_read"),ic=Symbol("_readSize"),Vt=Symbol("_reading"),_i=Symbol("_remain"),sc=Symbol("_size"),Vs=Symbol("_write"),Un=Symbol("_writing"),Zs=Symbol("_defaultFlag"),$n=Symbol("_errored"),Wc=class extends Jn{[$n]=!1;[le];[Et];[ic];[Vt]=!1;[sc];[_i];[An];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[$n]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Et]=t,this[ic]=e.readSize||16*1024*1024,this[Vt]=!1,this[sc]=typeof e.size=="number"?e.size:1/0,this[_i]=this[sc],this[An]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[kr]():this[kn]()}get fd(){return this[le]}get path(){return this[Et]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[kn](){it.open(this[Et],"r",(t,e)=>this[Dr](t,e))}[Dr](t,e){t?this[Rr](t):(this[le]=e,this.emit("open",e),this[kr]())}[Sc](){return Buffer.allocUnsafe(Math.min(this[ic],this[_i]))}[kr](){if(!this[Vt]){this[Vt]=!0;let t=this[Sc]();if(t.length===0)return process.nextTick(()=>this[rc](null,0,t));it.read(this[le],t,0,t.length,null,(e,n,i)=>this[rc](e,n,i))}}[rc](t,e,n){this[Vt]=!1,t?this[Rr](t):this[vc](e,n)&&this[kr]()}[vt](){if(this[An]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Rr](t){this[Vt]=!0,this[vt](),this.emit("error",t)}[vc](t,e){let n=!1;return this[_i]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[_i]<=0)&&(n=!1,this[vt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[kr](),!1;case"error":return this[$n]?!1:(this[$n]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},_w=class extends Wc{[kn](){let t=!0;try{this[Dr](null,it.openSync(this[Et],"r")),t=!1}finally{t&&this[vt]()}}[kr](){let t=!0;try{if(!this[Vt]){this[Vt]=!0;do{let e=this[Sc](),n=e.length===0?0:it.readSync(this[le],e,0,e.length,null);if(!this[vc](n,e))break}while(!0);this[Vt]=!1}t=!1}finally{t&&this[vt]()}}[vt](){if(this[An]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}},uo=class extends ow{readable=!1;writable=!0;[$n]=!1;[Un]=!1;[wi]=!1;[Tt]=[];[Fs]=!1;[Et];[Ri];[An];[le];[Zs];[Zt];[tc]=!1;[bn];constructor(t,e){e=e||{},super(e),this[Et]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Ri]=e.mode===void 0?438:e.mode,this[bn]=typeof e.start=="number"?e.start:void 0,this[An]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[bn]!==void 0?"r+":"w";this[Zs]=e.flags===void 0,this[Zt]=e.flags===void 0?n:e.flags,this[le]===void 0&&this[kn]()}emit(t,...e){if(t==="error"){if(this[$n])return!1;this[$n]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[Et]}[Rr](t){this[vt](),this[Un]=!0,this.emit("error",t)}[kn](){it.open(this[Et],this[Zt],this[Ri],(t,e)=>this[Dr](t,e))}[Dr](t,e){this[Zs]&&this[Zt]==="r+"&&t&&t.code==="ENOENT"?(this[Zt]="w",this[kn]()):t?this[Rr](t):(this[le]=e,this.emit("open",e),this[Un]||this[nc]())}end(t,e){return t&&this.write(t,e),this[wi]=!0,!this[Un]&&!this[Tt].length&&typeof this[le]=="number"&&this[Ar](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[wi]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[Un]||this[Tt].length?(this[Tt].push(t),this[Fs]=!0,!1):(this[Un]=!0,this[Vs](t),!0)}[Vs](t){it.write(this[le],t,0,t.length,this[bn],(e,n)=>this[Ar](e,n))}[Ar](t,e){t?this[Rr](t):(this[bn]!==void 0&&typeof e=="number"&&(this[bn]+=e),this[Tt].length?this[nc]():(this[Un]=!1,this[wi]&&!this[tc]?(this[tc]=!0,this[vt](),this.emit("finish")):this[Fs]&&(this[Fs]=!1,this.emit("drain"))))}[nc](){if(this[Tt].length===0)this[wi]&&this[Ar](null,0);else if(this[Tt].length===1)this[Vs](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],ww(this[le],t,this[bn],(e,n)=>this[Ar](e,n))}}[vt](){if(this[An]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},gf=class extends uo{[kn](){let t;if(this[Zs]&&this[Zt]==="r+")try{t=it.openSync(this[Et],this[Zt],this[Ri])}catch(e){if(e?.code==="ENOENT")return this[Zt]="w",this[kn]();throw e}else t=it.openSync(this[Et],this[Zt],this[Ri]);this[Dr](null,t)}[vt](){if(this[An]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}[Vs](t){let e=!0;try{this[Ar](null,it.writeSync(this[le],t,0,t.length,this[bn])),e=!1}finally{if(e)try{this[vt]()}catch{}}}},Ew=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"]]),vw=t=>!!t.sync&&!!t.file,Sw=t=>!t.sync&&!!t.file,Iw=t=>!!t.sync&&!t.file,Aw=t=>!t.sync&&!t.file,kw=t=>!!t.file,Tw=t=>Ew.get(t)||t,Kc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=Tw(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},zi=(t,e,n,i,o)=>Object.assign((c=[],d,u)=>{Array.isArray(c)&&(d=c,c={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let f=Kc(c);if(o?.(f,d),vw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(Sw(f)){let x=e(f,d);return u?x.then(()=>u(),u):x}else if(Iw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(f,d)}else if(Aw(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:o}),Dw=Rw.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},Dw)),Pw=Vn.concat,Bu=Object.getOwnPropertyDescriptor(Vn,"concat"),Ow=t=>t,oc=Bu?.writable===!0||Bu?.set!==void 0?t=>{Vn.concat=t?Ow:Pw}:t=>{},Zn=Symbol("_superWrite"),zs=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"}},ac=Symbol("flushFlag"),$c=class extends Jn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Mu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Mu[e](t)}catch(n){throw new zs(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 zs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Ic(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Vn.alloc(0),{[ac]: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}[Zn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Vn.from(t,e)),this.#e)return;Ic(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},oc(!0);let d;try{let f=typeof t[ac]=="number"?t[ac]:this.#r;d=this.#t._processChunk(t,f),oc(!1)}catch(f){oc(!1),this.#o(new zs(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 zs(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[Zn](Vn.from(f));for(let x=1;x<d.length;x++)u=this[Zn](d[x])}else u=this[Zn](Vn.from(d));return n&&n(),u}},wf=class extends $c{#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),Ic(this.handle,"zlib binding closed");let n=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=n}this.handle&&(this.#e=t,this.#n=e)}}}},Lw=class extends wf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Zn](t){return this.#e?(this.#e=!1,t[9]=255,super[Zn](t)):super[Zn](t)}},Nw=class extends wf{constructor(t){super(t,"Unzip")}},_f=class extends $c{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)}},Mw=class extends _f{constructor(t){super(t,"BrotliCompress")}},Bw=class extends _f{constructor(t){super(t,"BrotliDecompress")}},yf=class extends $c{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 yf{constructor(t){super(t,"ZstdCompress")}},zw=class extends yf{constructor(t){super(t,"ZstdDecompress")}},Uw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Hw(t,e):Gw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Gw=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},Hw=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),n?e[i-1]=bf(o):o===0?e[i-1]=0:(n=!0,e[i-1]=Ef(o))}},qw=t=>{let e=t[0],n=e===128?Ww(t.subarray(1,t.length)):e===255?jw(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},jw=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=bf(c):c===0?d=c:(i=!0,d=Ef(c)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},Ww=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(n+=o*Math.pow(256,e-i-1))}return n},bf=t=>(255^t)&255,Ef=t=>(255^t)+1&255,Kw={};sw(Kw,{code:()=>Vc,isCode:()=>Ys,isName:()=>$w,name:()=>fo,normalFsTypes:()=>vf});var Ys=t=>fo.has(t),$w=t=>Vc.has(t),vf=new Set(["0","","1","2","3","4","5","6","7","D"]),fo=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"]]),Vc=new Map(Array.from(fo).map(t=>[t[1],t[0]])),Vw=t=>t===void 0||t<0?void 0:t,Yn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=Gn(t,e+156,1),c=vf.has(o),d=c?n:void 0,u=c?i:void 0;if(this.path=d?.path??Gn(t,e,100),this.mode=d?.mode??u?.mode??En(t,e+100,8),this.uid=d?.uid??u?.uid??En(t,e+108,8),this.gid=d?.gid??u?.gid??En(t,e+116,8),this.size=Vw(d?.size??u?.size??En(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??cc(t,e+136,12),this.cksum=En(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Ys(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Gn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Gn(t,e+265,32),this.gname=d?.gname??u?.gname??Gn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??En(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??En(t,e+337,8)??0,t[e+475]!==0){let x=Gn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Gn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??cc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??cc(t,e+488,12)}let f=256;for(let x=e;x<e+148;x++)f+=t[x];for(let x=e+156;x<e+512;x++)f+=t[x];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="size"&&Number(i)<0||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=Zw(this.path||"",n),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Hn(t,e,100,o)||this.needPax,this.needPax=vn(t,e+100,8,this.mode)||this.needPax,this.needPax=vn(t,e+108,8,this.uid)||this.needPax,this.needPax=vn(t,e+116,8,this.gid)||this.needPax,this.needPax=vn(t,e+124,12,this.size)||this.needPax,this.needPax=dc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Hn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Hn(t,e+265,32,this.uname)||this.needPax,this.needPax=Hn(t,e+297,32,this.gname)||this.needPax,this.needPax=vn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=vn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Hn(t,e+345,n,c)||this.needPax,t[e+475]!==0?this.needPax=Hn(t,e+345,155,c)||this.needPax:(this.needPax=Hn(t,e+345,130,c)||this.needPax,this.needPax=dc(t,e+476,12,this.atime)||this.needPax,this.needPax=dc(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,vn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:fo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Vc.get(t));if(Ys(e)||e==="Unsupported")this.#e=e;else if(Ys(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Zw=(t,e)=>{let n=t,i="",o,c=br.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=br.dirname(n),n=br.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?o=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?o=[n.slice(0,99),i,!0]:(n=br.join(br.basename(i),n),i=br.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Gn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),cc=(t,e,n)=>Yw(En(t,e,n)),Yw=t=>t===void 0?void 0:new Date(t*1e3),En=(t,e,n)=>Number(t[e])&128?qw(t.subarray(e,e+n)):Xw(t,e,n),Jw=t=>isNaN(t)?void 0:t,Xw=(t,e,n)=>Jw(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),Qw={12:8589934591,8:2097151},vn=(t,e,n,i)=>i===void 0?!1:i>Qw[n]||i<0?(Uw(i,t.subarray(e,e+n)),!0):(e_(t,e,n,i),!1),e_=(t,e,n,i)=>t.write(t_(i,n),e,n,"ascii"),t_=(t,e)=>n_(Math.floor(t).toString(8),e),n_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",dc=(t,e,n,i)=>i===void 0?!1:vn(t,e,n,i.getTime()/1e3),r_=new Array(156).join("\0"),Hn=(t,e,n,i)=>i===void 0?!1:(t.write(i+r_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),so=class Sf{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),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[c]=0;new Yn({path:("PaxHeader/"+i_(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(o),o.write(e,512,n,"utf8");for(let c=n+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 n=this[e],i=n instanceof Date?n.getTime()/1e3:n,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(o),d=Math.floor(Math.log(c)/Math.log(10))+1;return c+d>=Math.pow(10,d)&&(d+=1),d+c+o}static parse(e,n,i=!1){return new Sf(s_(o_(e),n),i)}},s_=(t,e)=>e?Object.assign({},e,t):t,o_=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(a_,Object.create(null)),a_=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(c){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[c]=d;break;case"ctime":case"atime":case"mtime":t[c]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[c]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[c]=+d;break}return t},c_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ee=c_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),d_=class extends Jn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,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=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),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=ee(t.path)),t.linkpath&&(t.linkpath=ee(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},ho=(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))},l_=1024*1024,Ac=Buffer.from([31,139]),kc=Buffer.from([40,181,47,253]),u_=Math.max(Ac.length,kc.length),ft=Symbol("state"),qn=Symbol("writeEntry"),Kt=Symbol("readEntry"),lc=Symbol("nextEntry"),Fu=Symbol("processEntry"),Ct=Symbol("extendedHeader"),yi=Symbol("globalExtendedHeader"),wn=Symbol("meta"),zu=Symbol("emitMeta"),_e=Symbol("buffer"),$t=Symbol("queue"),_n=Symbol("ended"),uc=Symbol("emittedEnd"),jn=Symbol("emit"),ke=Symbol("unzip"),Us=Symbol("consumeChunk"),Gs=Symbol("consumeChunkSub"),fc=Symbol("consumeBody"),Uu=Symbol("consumeMeta"),Gu=Symbol("consumeHeader"),bi=Symbol("consuming"),hc=Symbol("bufferConcat"),Hs=Symbol("maybeEnd"),Er=Symbol("writing"),Rt=Symbol("aborted"),qs=Symbol("onDone"),Wn=Symbol("sawValidEntry"),js=Symbol("sawNullBlock"),Ws=Symbol("sawEOF"),Hu=Symbol("closeStream"),f_=1e3,Ei=Symbol("compressedBytesRead"),xc=Symbol("decompressedBytesRead"),qu=Symbol("checkDecompressionRatio"),h_=()=>!0,Fi=class extends Cw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[$t]=[];[_e];[Kt];[qn];[ft]="begin";[wn]="";[Ct];[yi];[_n]=!1;[ke];[Rt]=!1;[Wn];[js]=!1;[Ws]=!1;[Er]=!1;[bi]=!1;[uc]=!1;[Ei]=0;[xc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(qs,()=>{(this[ft]==="begin"||this[Wn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(qs,t.ondone):this.on(qs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:f_,this.maxMetaEntrySize=t.maxMetaEntrySize||l_,this.filter=typeof t.filter=="function"?t.filter:h_;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[Hu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){ho(this,t,e,n)}[Gu](t,e){this[Wn]===void 0&&(this[Wn]=!1);let n;try{n=new Yn(t,e,this[Ct],this[yi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[js]?(this[Ws]=!0,this[ft]==="begin"&&(this[ft]="header"),this[jn]("eof")):(this[js]=!0,this[jn]("nullBlock"));else if(this[js]=!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 o=this[qn]=new d_(n,this[Ct],this[yi]);if(!this[Wn])if(o.remain){let c=()=>{o.invalid||(this[Wn]=!0)};o.on("end",c)}else this[Wn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[jn]("ignoredEntry",o),this[ft]="ignore",o.resume()):o.size>0&&(this[wn]="",o.on("data",c=>this[wn]+=c),this[ft]="meta"):(this[Ct]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[jn]("ignoredEntry",o),this[ft]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ft]="body":(this[ft]="header",o.end()),this[Kt]?this[$t].push(o):(this[$t].push(o),this[lc]())))}}}[Hu](){queueMicrotask(()=>this.emit("close"))}[Fu](t){let e=!0;if(!t)this[Kt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Kt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[lc]()),e=!1);return e}[lc](){do;while(this[Fu](this[$t].shift()));if(this[$t].length===0){let t=this[Kt];!t||t.flowing||t.size===t.remain?this[Er]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[fc](t,e){let n=this[qn];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(o),n.blockRemain||(this[ft]="header",this[qn]=void 0,n.end()),o.length}[Uu](t,e){let n=this[qn],i=this[fc](t,e);return!this[qn]&&n&&this[zu](n),i}[jn](t,e,n){this[$t].length===0&&!this[Kt]?this.emit(t,e,n):this[$t].push([t,e,n])}[zu](t){switch(this[jn]("meta",this[wn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=so.parse(this[wn],this[Ct],!1);break;case"GlobalExtendedHeader":this[yi]=so.parse(this[wn],this[yi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[wn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[wn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Rt]){if(this[ke]){let e=this[ke];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Rt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[qu](t){this[xc]+=t.length;let e=this[xc]/this[Ei];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}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[Rt])return n?.(),!1;if((this[ke]===void 0||this.brotli===void 0&&this[ke]===!1)&&t){if(this[_e]&&(t=Buffer.concat([this[_e],t]),this[_e]=void 0),t.length<u_)return this[_e]=t,n?.(),!0;for(let d=0;this[ke]===void 0&&d<Ac.length;d++)t[d]!==Ac[d]&&(this[ke]=!1);let o=!1;if(this[ke]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<kc.length;d++)if(t[d]!==kc[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[ke]===!1&&c)if(t.length<512)if(this[_n])this.brotli=!0;else return this[_e]=t,n?.(),!0;else try{new Yn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[ke]===void 0||this[ke]===!1&&(this.brotli||o)){let d=this[_n];this[_n]=!1,this[ke]=this[ke]===void 0?new Nw({}):o?new zw({}):new Bw({}),this[ke].on("data",f=>{this[qu](f)&&this[Us](f)}),this[ke].on("error",f=>{this[Rt]||this.abort(f)}),this[ke].on("end",()=>{this[_n]=!0,this[Us]()}),this[Er]=!0,this[Ei]+=t.length;let u=!!this[ke][d?"end":"write"](t);return this[Er]=!1,n?.(),u}}this[Er]=!0,this[ke]?(this[Ei]+=t.length,this[ke].write(t)):this[Us](t),this[Er]=!1;let i=this[$t].length>0?!1:this[Kt]?this[Kt].flowing:!0;return!i&&this[$t].length===0&&this[Kt]?.once("drain",()=>this.emit("drain")),n?.(),i}[hc](t){t&&!this[Rt]&&(this[_e]=this[_e]?Buffer.concat([this[_e],t]):t)}[Hs](){if(this[_n]&&!this[uc]&&!this[Rt]&&!this[bi]){this[uc]=!0;let t=this[qn];if(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[jn](qs)}}[Us](t){if(this[bi]&&t)this[hc](t);else if(!t&&!this[_e])this[Hs]();else if(t){if(this[bi]=!0,this[_e]){this[hc](t);let e=this[_e];this[_e]=void 0,this[Gs](e)}else this[Gs](t);for(;this[_e]&&this[_e]?.length>=512&&!this[Rt]&&!this[Ws];){let e=this[_e];this[_e]=void 0,this[Gs](e)}this[bi]=!1}(!this[_e]||this[_n])&&this[Hs]()}[Gs](t){let e=0,n=t.length;for(;e+512<=n&&!this[Rt]&&!this[Ws];)switch(this[ft]){case"begin":case"header":this[Gu](t,e),e+=512;break;case"ignore":case"body":e+=this[fc](t,e);break;case"meta":e+=this[Uu](t,e);break;default:throw new Error("invalid state: "+this[ft])}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[Rt]||(this[ke]?(t&&(this[Ei]+=t.length,this[ke].write(t)),this[ke].end()):(this[_n]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Hs]())),this}},Di=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)},x_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},If=(t,e)=>{let n=new Map(e.map(c=>[Di(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||bw(c).root||".",f;if(c===u)f=!1;else{let x=n.get(c);f=x!==void 0?x:o(yw(c),u)}return n.set(c,f),f};t.filter=i?(c,d)=>i(c,d)&&o(Di(c)):c=>o(Di(c))},p_=t=>{let e=new Fi(t),n=t.file,i;try{i=Tr.openSync(n,"r");let o=Tr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Tr.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(c);for(;d<o.size;){let f=Tr.readSync(i,u,0,c,d);if(f===0)break;d+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Tr.closeSync(i)}catch{}}},g_=(t,e)=>{let n=new Fi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("end",c),Tr.stat(o,(u,f)=>{if(u)d(u);else{let x=new Wc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},Pr=zi(p_,g_,t=>new Fi(t),t=>new Fi(t),(t,e)=>{e?.length&&If(t,e),t.noResume||x_(t)}),Af=(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:w_,parse:Wu}=m_,Zc=t=>{let e="",n=Wu(t);for(;w_(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Wu(t)}return[e,t]},xo=["|","<",">","?",":"],Yc=xo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),__=new Map(xo.map((t,e)=>[t,Yc[e]])),y_=new Map(Yc.map((t,e)=>[t,xo[e]])),Ku=t=>xo.reduce((e,n)=>e.split(n).join(__.get(n)),t),b_=t=>Yc.reduce((e,n)=>e.split(n).join(y_.get(n)),t),kf=(t,e)=>e?(t=ee(t).replace(/^\.(\/|$)/,""),Di(e)+"/"+t):ee(t),E_=16*1024*1024,$u=Symbol("process"),Vu=Symbol("file"),Zu=Symbol("directory"),Tc=Symbol("symlink"),Yu=Symbol("hardlink"),vi=Symbol("header"),Js=Symbol("read"),Cc=Symbol("lstat"),Xs=Symbol("onlstat"),Rc=Symbol("onread"),Dc=Symbol("onreadlink"),Pc=Symbol("openfile"),Oc=Symbol("onopenfile"),Sn=Symbol("close"),ao=Symbol("mode"),Lc=Symbol("awaitDrain"),pc=Symbol("ondrain"),Pt=Symbol("prefix"),Tf=class extends Jn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let n=Kc(e);super(),this.path=ee(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||E_,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=ee(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?ee(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=Zc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=b_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ee(n.absolute||ju.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[Xs](o):this[Cc]()}warn(t,e,n={}){return ho(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Cc](){Dt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Xs](e)})}[Xs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=I_(t),this.emit("stat",t),this[$u]()}[$u](){switch(this.type){case"File":return this[Vu]();case"Directory":return this[Zu]();case"SymbolicLink":return this[Tc]();default:return this.end()}}[ao](t){return Af(t,this.type==="Directory",this.portable)}[Pt](t){return kf(t,this.prefix)}[vi](){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 Yn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this[ao](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 so({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)}[Zu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[vi](),this.end()}[Tc](){Dt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Dc](e)})}[Dc](t){this.linkpath=ee(t),this[vi](),this.end()}[Yu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ee(ju.relative(this.cwd,t)),this.stat.size=0,this[vi](),this.end()}[Vu](){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[Yu](e);this.linkCache.set(t,this.absolute)}if(this[vi](),this.stat.size===0)return this.end();this[Pc]()}[Pc](){Dt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Oc](e)})}[Oc](t){if(this.fd=t,this.#e)return this[Sn]();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[Js]()}[Js](){let{fd:t,buf:e,offset:n,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,n,i,o,(c,d)=>{if(c)return this[Sn](()=>this.emit("error",c));this[Rc](d)})}[Sn](t=()=>{}){this.fd!==void 0&&Dt.close(this.fd,t)}[Rc](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[Sn](()=>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[Sn](()=>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[pc]():this[Lc](()=>this[pc]())}[Lc](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)}[pc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Sn](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[Js]()}},v_=class extends Tf{sync=!0;[Cc](){this[Xs](Dt.lstatSync(this.absolute))}[Tc](){this[Dc](Dt.readlinkSync(this.absolute))}[Pc](){this[Oc](Dt.openSync(this.absolute,"r"))}[Js](){let t=!0;try{let{fd:e,buf:n,offset:i,length:o,pos:c}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let d=Dt.readSync(e,n,i,o,c);this[Rc](d),t=!1}finally{if(t)try{this[Sn](()=>{})}catch{}}}[Lc](t){t()}[Sn](t=()=>{}){this.fd!==void 0&&Dt.closeSync(this.fd),t()}},S_=class extends Jn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,n={}){return ho(this,t,e,n)}constructor(t,e={}){let n=Kc(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=ee(t.path),this.mode=t.mode!==void 0?this[ao](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?ee(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Zc(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Yn({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 so({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 kf(t,this.prefix)}[ao](t){return Af(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}},I_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",A_=class Cr{tail;head;length=0;static create(e=[]){return new Cr(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++)T_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)C_(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,o=0;i;o++)e.call(n,i.value,o,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(n,i.value,o,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 Cr;for(let o=this.head;o;)i.push(e.call(n,o.value,this)),o=o.next;return i}mapReverse(e,n){n=n||this;var i=new Cr;for(let o=this.tail;o;)i.push(e.call(n,o.value,this)),o=o.prev;return i}reduce(e,n){let i,o=this.head;if(arguments.length>1)i=n;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,n){let i,o=this.tail;if(arguments.length>1)i=n;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 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 Cr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<n;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Cr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.length,c=this.tail;for(;c&&o>n;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let d=0;o&&d<e;d++)o=o.next;let c=[];for(let d=0;o&&d<n;d++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=k_(this,o,d);return c}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=n,this.tail=e,this}};function k_(t,e,n){let i=e,o=e?e.next:t.head,c=new Jc(n,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function T_(t,e){t.tail=new Jc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function C_(t,e){t.head=new Jc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Jc=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}},Xu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Qu=Buffer.alloc(1024),Qs=Symbol("onStat"),Si=Symbol("ended"),yt=Symbol("queue"),Ii=Symbol("pendingLinks"),yn=Symbol("current"),Kn=Symbol("process"),Ai=Symbol("processing"),Ks=Symbol("processJob"),bt=Symbol("jobs"),gc=Symbol("jobDone"),eo=Symbol("addFSEntry"),ef=Symbol("addTarEntry"),Nc=Symbol("stat"),Mc=Symbol("readdir"),to=Symbol("onreaddir"),no=Symbol("pipe"),tf=Symbol("entry"),mc=Symbol("entryOpt"),ro=Symbol("writeEntryClass"),Cf=Symbol("write"),wc=Symbol("ondrain"),po=class extends Jn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ro];onWriteEntry;[yt];[Ii]=new Map;[bt]=0;[Ai]=!1;[Si]=!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[ro]=Tf,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 Lw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Mw(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",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[wc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[wc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[yt]=new A_,this[bt]=0,this.jobs=Number(t.jobs)||4,this[Ai]=!1,this[Si]=!1}[Cf](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[Si]=!0,this[Kn](),n&&n(),this}write(t){if(this[Si])throw new Error("write after end");return typeof t=="string"?this[eo](t):this[ef](t),this.flowing}[ef](t){let e=ee(Ju.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new Xu(t.path,e);n.entry=new S_(t,this[mc](n)),n.entry.on("end",()=>this[gc](n)),this[bt]+=1,this[yt].push(n)}this[Kn]()}[eo](t){let e=ee(Ju.resolve(this.cwd,t));this[yt].push(new Xu(t,e)),this[Kn]()}[Nc](t){t.pending=!0,this[bt]+=1;let e=this.follow?"stat":"lstat";oo[e](t.absolute,(n,i)=>{t.pending=!1,this[bt]-=1,n?this.emit("error",n):this[Qs](t,i)})}[Qs](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[yn])this[Ks](t);else{let n=`${e.dev}:${e.ino}`,i=this[Ii].get(n);i?i.push(t):this[Ii].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Kn]()}[Mc](t){t.pending=!0,this[bt]+=1,oo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[bt]-=1,e)return this.emit("error",e);this[to](t,n)})}[to](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Kn]()}[Kn](){if(!this[Ai]){this[Ai]=!0;for(let t=this[yt].head;t&&this[bt]<this.jobs;t=t.next)if(this[Ks](t.value),t.value.ignore){let e=t.next;this[yt].removeNode(t),t.next=e}this[Ai]=!1,this[Si]&&this[yt].length===0&&this[bt]===0&&(this.zip?this.zip.end(Qu):(super.write(Qu),super.end()))}}get[yn](){return this[yt]&&this[yt].head&&this[yt].head.value}[gc](t){this[yt].shift(),this[bt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Ii].get(n);if(i){this[Ii].delete(n);for(let o of i)o.pending=!1,this[Ks](o)}}this[Kn]()}[Ks](t){if(t.pending&&t.pendingLink&&t===this[yn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[yn]&&!t.piped&&this[no](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Qs](t,e):this[Nc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[to](t,e):this[Mc](t),!t.readdir)return}if(t.entry=this[tf](t),!t.entry){t.ignore=!0;return}t===this[yn]&&!t.piped&&this[no](t)}}}[mc](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}}[tf](t){this[bt]+=1;try{return new this[ro](t.path,this[mc](t)).on("end",()=>this[gc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[wc](){this[yn]&&this[yn].entry&&this[yn].entry.resume()}[no](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[eo](c+i)});let e=t.entry,n=this.zip;if(!e)throw new Error("cannot pipe without source");n?e.on("data",i=>{n.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,n={}){ho(this,t,e,n)}},Xc=class extends po{sync=!0;constructor(t){super(t),this[ro]=v_}pause(){}resume(){}[Nc](t){let e=this.follow?"statSync":"lstatSync";this[Qs](t,oo[e](t.absolute))}[Mc](t){this[to](t,oo.readdirSync(t.absolute))}[no](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[eo](c+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Cf](i)})}},R_=(t,e)=>{let n=new Xc(t),i=new gf(t.file,{mode:t.mode||438});n.pipe(i),Rf(n,e)},D_=(t,e)=>{let n=new po(t),i=new uo(t.file,{mode:t.mode||438});n.pipe(i);let o=new Promise((c,d)=>{i.on("error",d),i.on("close",c),n.on("error",d)});return Df(n,e).catch(c=>n.emit("error",c)),o},Rf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Pr({file:mf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Df=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Pr({file:mf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},P_=(t,e)=>{let n=new Xc(t);return Rf(n,e),n},O_=(t,e)=>{let n=new po(t);return Df(n,e).catch(i=>n.emit("error",i)),n},zA=zi(R_,D_,P_,O_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),N_=process.env.__FAKE_PLATFORM__||process.platform,Nf=N_==="win32",{O_CREAT:Mf,O_NOFOLLOW:nf,O_TRUNC:Bf,O_WRONLY:Ff}=Lf.constants,zf=Number(process.env.__FAKE_FS_O_FILENAME__)||Lf.constants.UV_FS_O_FILEMAP||0,M_=Nf&&!!zf,B_=512*1024,F_=zf|Bf|Mf|Ff,rf=!Nf&&typeof nf=="number"?nf|Bf|Mf|Ff:null,Uf=rf!==null?()=>rf:M_?t=>t<B_?F_:"w":()=>"w",Bc=(t,e,n)=>{try{return go.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},co=(t,e,n,i)=>{go.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},z_=(t,e,n,i,o)=>{if(e.isDirectory())Gf(Pi.resolve(t,e.name),n,i,c=>{if(c)return o(c);let d=Pi.resolve(t,e.name);co(d,n,i,o)});else{let c=Pi.resolve(t,e.name);co(c,n,i,o)}},Gf=(t,e,n,i)=>{go.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 co(t,e,n,i);let d=c.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--d===0)return co(t,e,n,i)}};for(let x of c)z_(t,x,e,n,f)})},U_=(t,e,n,i)=>{e.isDirectory()&&Hf(Pi.resolve(t,e.name),n,i),Bc(Pi.resolve(t,e.name),n,i)},Hf=(t,e,n)=>{let i;try{i=go.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Bc(t,e,n);throw c}for(let o of i)U_(t,o,e,n);return Bc(t,e,n)},qf=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"}},mo=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)=>{ct.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new qf(t,n?.code||"ENOTDIR")),e(n)})},q_=(t,e,n)=>{t=ee(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,d=e.uid,u=e.gid,f=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,p=e.unlink,w=ee(e.cwd),S=(E,I)=>{E?n(E):I&&f?Gf(I,d,u,A=>S(A)):c?ct.chmod(t,o,n):n()};if(t===w)return H_(t,S);if(x)return G_.mkdir(t,{mode:o,recursive:!0}).then(E=>S(null,E??void 0),S);let _=ee(lo.relative(w,t)).split("/");Fc(w,_,o,p,w,void 0,S)},Fc=(t,e,n,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),f=ee(lo.resolve(t+"/"+u));ct.mkdir(f,n,jf(f,e,n,i,o,c,d))},jf=(t,e,n,i,o,c,d)=>u=>{u?ct.lstat(t,(f,x)=>{if(f)f.path=f.path&&ee(f.path),d(f);else if(x.isDirectory())Fc(t,e,n,i,o,c,d);else if(i)ct.unlink(t,p=>{if(p)return d(p);ct.mkdir(t,n,jf(t,e,n,i,o,c,d))});else{if(x.isSymbolicLink())return d(new mo(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Fc(t,e,n,i,o,c,d))},j_=t=>{let e=!1,n;try{e=ct.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new qf(t,n??"ENOTDIR")}},W_=(t,e)=>{t=ee(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==0,c=e.uid,d=e.gid,u=typeof c=="number"&&typeof d=="number"&&(c!==e.processUid||d!==e.processGid),f=e.preserve,x=e.unlink,p=ee(e.cwd),w=E=>{E&&u&&Hf(E,c,d),o&&ct.chmodSync(t,i)};if(t===p)return j_(p),w();if(f)return w(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=ee(lo.relative(p,t)).split("/"),_;for(let E=S.shift(),I=p;E&&(I+="/"+E);E=S.shift()){I=ee(lo.resolve(I));try{ct.mkdirSync(I,i),_=_||I}catch{let A=ct.lstatSync(I);if(A.isDirectory())continue;if(x){ct.unlinkSync(I),ct.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new mo(I,I+"/"+S.join("/"))}}return w(_)},_c=Object.create(null),sf=1e4,vr=new Set,K_=t=>{vr.has(t)?vr.delete(t):_c[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),vr.add(t);let e=_c[t],n=vr.size-sf;if(n>sf/10){for(let i of vr)if(vr.delete(i),delete _c[i],--n<=0)break}return e},$_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,V_=$_==="win32",Z_=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Wf(i,n)),e.push(n||"/"),e},[]),Y_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=V_?["win32 parallelization disabled"]:t.map(i=>Di(Wf(K_(i))));let n=new Set(t.map(i=>Z_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:n,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 n){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(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,o=new Set;for(let c of n){let d=this.#e.get(c);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(c);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let f of u)o.add(f)}for(let c of i){let d=this.#e.get(c),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(c);continue}else if(u.size===1){d.shift();let f=d[0];typeof f=="function"&&o.add(f)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},J_=()=>process.umask(),of=Symbol("onEntry"),zc=Symbol("checkFs"),af=Symbol("checkFs2"),Uc=Symbol("isReusable"),ht=Symbol("makeFs"),Gc=Symbol("file"),Hc=Symbol("directory"),io=Symbol("link"),cf=Symbol("symlink"),df=Symbol("hardlink"),Ci=Symbol("ensureNoSymlink"),lf=Symbol("unsupported"),uf=Symbol("checkPath"),yc=Symbol("stripAbsolutePath"),In=Symbol("mkdir"),We=Symbol("onError"),$s=Symbol("pending"),ff=Symbol("pend"),Sr=Symbol("unpend"),bc=Symbol("ended"),Ec=Symbol("maybeClose"),qc=Symbol("skip"),Oi=Symbol("doChown"),Li=Symbol("uid"),Ni=Symbol("gid"),Mi=Symbol("checkedCwd"),X_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Bi=X_==="win32",Q_=1024,ey=(t,e)=>{if(!Bi)return oe.unlink(t,e);let n=t+".DELETE."+Of(16).toString("hex");oe.rename(t,n,i=>{if(i)return e(i);oe.unlink(n,e)})},ty=t=>{if(!Bi)return oe.unlinkSync(t);let e=t+".DELETE."+Of(16).toString("hex");oe.renameSync(t,e),oe.unlinkSync(e)},hf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,Qc=class extends Fi{[bc]=!1;[Mi]=!1;[$s]=0;reservations=new Y_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[bc]=!0,this[Ec]()},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?.()===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:Q_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Bi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ee(Fe.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:J_():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[of](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Ec](){this[bc]&&this[$s]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[yc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,c]=Zc(n),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Bi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=Fe.posix.dirname(t.path),f=Fe.posix.normalize(Fe.posix.join(u,d.join("/")));if(f.startsWith("../")||f==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:n})),!0}[uf](t){let e=ee(t.path),n=e.split("/");if(this.strip){if(n.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}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[yc](t,"path")||!this[yc](t,"linkpath"))return!1;if(t.absolute=Fe.isAbsolute(t.path)?ee(Fe.resolve(t.path)):ee(Fe.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}=Fe.win32.parse(String(t.absolute));t.absolute=i+Ku(String(t.absolute).slice(i.length));let{root:o}=Fe.win32.parse(t.path);t.path=o+Ku(t.path.slice(o.length))}return!0}[of](t){if(!this[uf](t))return t.resume();switch(L_.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[zc](t);default:return this[lf](t)}}[We](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Sr](),e.resume())}[In](t,e,n){q_(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},n)}[Oi](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}[Li](t){return hf(this.uid,t.uid,this.processUid)}[Ni](t){return hf(this.gid,t.gid,this.processGid)}[Gc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new uo(String(t.absolute),{flags:Uf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&oe.close(i.fd,()=>{}),i.write=()=>!0,this[We](u,t),e()});let o=1,c=u=>{if(u){i.fd&&oe.close(i.fd,()=>{}),this[We](u,t),e();return}--o===0&&i.fd!==void 0&&oe.close(i.fd,f=>{f?this[We](f,t):this[Sr](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,p=t.mtime;oe.futimes(f,x,p,w=>w?oe.utimes(u,x,p,S=>c(S&&w)):c())}if(typeof f=="number"&&this[Oi](t)){o++;let x=this[Li](t),p=this[Ni](t);typeof x=="number"&&typeof p=="number"&&oe.fchown(f,x,p,w=>w?oe.chown(u,x,p,S=>c(S&&w)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[We](u,t),e()}),t.pipe(d)),d.pipe(i)}[Hc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[In](String(t.absolute),n,i=>{if(i){this[We](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[Sr](),t.resume())};t.mtime&&!this.noMtime&&(o++,oe.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Oi](t)&&(o++,oe.chown(String(t.absolute),Number(this[Li](t)),Number(this[Ni](t)),c)),c()})}[lf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[cf](t,e){let n=ee(Fe.relative(this.cwd,Fe.resolve(Fe.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ci](t,this.cwd,n,()=>this[io](t,String(t.linkpath),"symlink",e),i=>{this[We](i,t),e()})}[df](t,e){let n=ee(Fe.resolve(this.cwd,String(t.linkpath))),i=ee(String(t.linkpath)).split("/");this[Ci](t,this.cwd,i,()=>this[io](t,n,"link",e),o=>{this[We](o,t),e()})}[Ci](t,e,n,i,o){let c=n.shift();if(this.preservePaths||c===void 0)return i();let d=Fe.resolve(e,c);oe.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new mo(d,Fe.resolve(d,n.join("/"))));this[Ci](t,d,n,i,o)})}[ff](){this[$s]++}[Sr](){this[$s]--,this[Ec]()}[qc](t){this[Sr](),t.resume()}[Uc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Bi}[zc](t){this[ff]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[af](t,n))}[af](t,e){let n=d=>{e(d)},i=()=>{this[In](this.cwd,this.dmode,d=>{if(d){this[We](d,t),n();return}this[Mi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=ee(Fe.dirname(String(t.absolute)));if(d!==this.cwd)return this[In](d,this.dmode,u=>{if(u){this[We](u,t),n();return}c()})}c()},c=()=>{oe.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[qc](t),n();return}if(d||this[Uc](t,u))return this[ht](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=p=>this[ht](p??null,t,n);return f?oe.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return oe.rmdir(String(t.absolute),f=>this[ht](f??null,t,n))}if(t.absolute===this.cwd)return this[ht](null,t,n);ey(String(t.absolute),f=>this[ht](f??null,t,n))})};this[Mi]?o():i()}[ht](t,e,n){if(t){this[We](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Gc](e,n);case"Link":return this[df](e,n);case"SymbolicLink":return this[cf](e,n);case"Directory":case"GNUDumpDir":return this[Hc](e,n)}}[io](t,e,n,i){oe[n](e,String(t.absolute),o=>{o?this[We](o,t):(this[Sr](),t.resume()),i()})}},ki=t=>{try{return[null,t()]}catch(e){return[e,null]}},Kf=class extends Qc{sync=!0;[ht](t,e){return super[ht](t,e,()=>{})}[zc](t){if(!this[Mi]){let o=this[In](this.cwd,this.dmode);if(o)return this[We](o,t);this[Mi]=!0}if(t.absolute!==this.cwd){let o=ee(Fe.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[In](o,this.dmode);if(c)return this[We](c,t)}}let[e,n]=ki(()=>oe.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[qc](t);if(e||this[Uc](t,n))return this[ht](null,t);if(n.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=c?ki(()=>{oe.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ht](d,t)}let[o]=ki(()=>oe.rmdirSync(String(t.absolute)));this[ht](o,t)}let[i]=t.absolute===this.cwd?[]:ki(()=>ty(String(t.absolute)));this[ht](i,t)}[Gc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{oe.closeSync(o)}catch(f){u=f}(d||u)&&this[We](d||u,t),e()},o;try{o=oe.openSync(String(t.absolute),Uf(t.size),n)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[We](d,t)),t.pipe(c)),c.on("data",d=>{try{oe.writeSync(o,d,0,d.length)}catch(u){i(u)}}),c.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{oe.futimesSync(o,u,f)}catch(x){try{oe.utimesSync(String(t.absolute),u,f)}catch{d=x}}}if(this[Oi](t)){let u=this[Li](t),f=this[Ni](t);try{oe.fchownSync(o,Number(u),Number(f))}catch(x){try{oe.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||x}}}i(d)})}[Hc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[In](String(t.absolute),n);if(i){this[We](i,t),e();return}if(t.mtime&&!this.noMtime)try{oe.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Oi](t))try{oe.chownSync(String(t.absolute),Number(this[Li](t)),Number(this[Ni](t)))}catch{}e(),t.resume()}[In](t,e){try{return W_(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(n){return n}}[Ci](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let c=e;for(let d of n){c=Fe.resolve(c,d);let[u,f]=ki(()=>oe.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new mo(c,Fe.resolve(e,n.join("/"))))}i()}[io](t,e,n,i){let o=`${n}Sync`;try{oe[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[We](c,t)}}},ny=t=>{let e=new Kf(t),n=t.file,i=Pf.statSync(n),o=t.maxReadSize||16*1024*1024;new _w(n,{readSize:o,size:i.size}).pipe(e)},ry=(t,e)=>{let n=new Qc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("close",c),Pf.stat(o,(u,f)=>{if(u)d(u);else{let x=new Wc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},$f=zi(ny,ry,t=>new Kf(t),t=>new Qc(t),(t,e)=>{e?.length&&If(t,e)}),iy=(t,e)=>{let n=new Xc(t),i=!0,o,c;try{try{o=at.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=at.openSync(t.file,"w+");else throw f}let d=at.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let p=0,w=0;p<512;p+=w){if(w=at.readSync(o,u,p,u.length-p,c+p),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let f=new Yn(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(c+x+512>d.size)break;c+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,sy(t,n,c,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},sy=(t,e,n,i,o)=>{let c=new gf(t.file,{fd:i,start:n});e.pipe(c),ay(e,o)},oy=(t,e)=>{e=Array.from(e);let n=new po(t),i=(o,c,d)=>{let u=(S,_)=>{S?at.close(o,E=>d(S)):d(null,_)},f=0;if(c===0)return u(null,0);let x=0,p=Buffer.alloc(512),w=(S,_)=>{if(S||_===void 0)return u(S);if(x+=_,x<512&&_)return at.read(o,p,x,p.length-x,f+x,w);if(f===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let E=new Yn(p);if(!E.cksumValid)return u(null,f);let I=512*Math.ceil((E.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),x=0,at.read(o,p,0,512,f,w)};at.read(o,p,0,512,f,w)};return new Promise((o,c)=>{n.on("error",c);let d="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",at.open(t.file,d,u);if(f||!x)return c(f);at.fstat(x,(p,w)=>{if(p)return at.close(x,()=>c(p));i(x,w.size,(S,_)=>{if(S)return c(S);let E=new uo(t.file,{fd:x,start:_});n.pipe(E),E.on("error",c),E.on("close",o),cy(n,e)})})};at.open(t.file,d,u)})},ay=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Pr({file:Vf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},cy=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Pr({file:Vf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Ti=zi(iy,oy,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!kw(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")}),ek=zi(Ti.syncFile,Ti.asyncFile,Ti.syncNoFile,Ti.asyncNoFile,(t,e=[])=>{Ti.validate?.(t,e),dy(t)}),dy=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))};pn();var xt={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function wo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Zf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function _o(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Yf(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function Jf(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function Xf(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function Xn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Yt();Ve();ie();De();Ve();function Or(t,e){if(wo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ui(t){return t.startsWith("http://")||t.startsWith("https://")}function Lr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as Wk}from"node:fs";import{dirname as $k,join as Vk}from"node:path";import{fileURLToPath as Yk}from"node:url";var Lt="0.2.7-alpha.15";Ve();ie();var yo="1008033",n0="1289";var r0="pbbp2",i0="https://www.coze.cn",s0="/api/coze_claw/resource/get_frontier_key",my="https://www.coze.cn",wy="wss://frontier.coze.cn";function Nr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??my}function o0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??wy}function Tn(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 Hi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Gi=H("handshake");async function ed(t){let e=Nr(t.endpoint),n=t.timeoutMs??1e4,i=`${Lr(e)}${s0}?aid=${encodeURIComponent(yo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Tn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),n);Gi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),f=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let E=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${E.slice(0,200)}`)}let p=await u.json();if(p.code!==void 0&&p.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${p.code} msg=${p.msg??"-"} logid=${f}`);let w=p.data??{},S=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,_=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!S||!_){let E=JSON.stringify(p).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${E}`)}return Gi.info("handshake ok",{remoteDeviceId:_,logid:f,traceId:x}),{accessKey:S,deviceId:_}}catch(u){if(u instanceof k)throw Gi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Gi.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let f=u.cause;throw Gi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var nd=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Nt="auto",td=15e4,a0=32e3;function d0(t){return{model:rd(t.model)??Nt,...t.modelToken?{modelToken:t.modelToken}:{}}}function l0(t){return!t||t===Nt}var _y=new Set(["auto","\u81EA\u52A8"]);function rd(t){let e=t?.trim();if(e)return _y.has(e.toLowerCase())?Nt:e}function u0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=nd,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Nt;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)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else l0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function f0(t,e,n,i){let o={};if(t.modelToken?o.model=t.model||Nt:l0(t.model)||(o.model=t.model),t.modelToken){let c={name:"coze",base_url:`${nd}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=id(e,n,i);Object.keys(d).length>0&&(c.http_headers=d),o.model_providers={coze:c},o.model_context_window=t.modelInfo?.contextWindow??td}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function h0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function id(t,e,n){let{ttEnv:i,usePpe:o}=Hi(t),c={};return i&&(c["x-tt-env"]=i),o&&(c["x-use-ppe"]=o),e&&(c["x-mock-scenario"]=e),n&&(c["x-coze-request-scene"]=n),c}function x0(t,e,n,i){if(!t.modelToken)return{};let o=id(e,n,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,u])=>`${d}:${u}`).join(`
92
+ `)}}function sd(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function od(t){return t.model||Nt}function c0(t,e,n,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:i,api:"openai-completions"}}function p0(t,e,n,i,o){if(!t.modelToken)return null;let c=od(t),d=id(e,n,o),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let f=[c0(c,u,t.modelInfo?.contextWindow??td,t.modelInfo?.maxOutput??a0)],x=new Set([c]);for(let w of i??[])!w||x.has(w)||(x.add(w),f.push(c0(w,["text"],td,a0)));let p={baseUrl:`${nd}/v1`,api:"openai-completions",apiKey:t.modelToken,models:f};return Object.keys(d).length>0&&(p.headers=d),p}var pe=H("agent-handlers"),m0=5*1024*1024,Sy=1,Iy=6,Ay=new Set(["node_modules",".git",".coze","dist","build",".next"]),ky=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ty=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Cy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Ry(t){let e=t?.trim();return e?Cy.test(e)||Ty.test(e)?e:(pe.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Dy(t){return new Promise((e,n)=>{let i=st("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=d=>{o||(o=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",d=>c(d))})}var Eo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let n=Xn(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Ue(n).workspace,c=i?.skills??[],d=[],u=new Set;for(let f of c){let x=me(o,f.relPath,"SKILL.md");await hd(x).then(w=>w.isFile()).catch(()=>!1)&&(d.push(My(f)),u.add(f.relPath))}if(e.scanLocal){let f=i?.framework??"claude-code",x=await T0(n,o,f),p=await C0(n,f);for(let w of[...x,...p])u.has(w.relPath)||(u.add(w.relPath),d.push(w.skill))}return{skills:d}}async addSkills(e){e._meta;let n=Xn(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await vo({agentId:n,workspace:i.workspace,framework:i.framework,skill:f});So(c,d,x),u.push(f)}return await fi(n,c),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=Xn(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),c=i.skills??[],d=[];for(let u of c){if(!o.has(u.skillId)){d.push(u);continue}let f=me(i.workspace,u.relPath);await dd(f,{recursive:!0,force:!0}),pe.info("skill removed",{agentId:n,skillId:u.skillId,relPath:u.relPath})}return await fi(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=Xn(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");pe.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),o=i?.workspace??Ue(n).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=await Oy(n,o,c,e.skillName,d);if(!u){let P=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${P}: ${e.skillName}`)}let{absDir:f,relPath:x,dirName:p}=u,w=me(f,"SKILL.md"),S=new pd.default;S.addLocalFolder(f,p);let _=S.toBuffer();if(_.length>w0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${w0}`);let E=await bo(w,{encoding:"utf8"}).then(P=>A0(P).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...E?{description:E}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):pe.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??I0(n,x);if(i&&!d){let P=i.skills??[],y=P.find(R=>R.relPath===x);y?(y.version=A,y.skillId=T):P.push({skillId:T,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...E?{description:E}:{}}),await fi(n,P)}return pe.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:T,version:A}),{ok:!0,skillId:T,version:A}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,pe.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let f=c.downstream;c.downstream=void 0,pe.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(n).catch(x=>pe.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:o,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 pe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await Pe(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return pe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await gr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw pe.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Ge(i),pe.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 k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Pe(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&Ui(e.registry)&&o.push(`--registry=${e.registry}`);let c=Ry(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&ky.test(d)&&o.push("--env",d);let u=await Dy(o);return pe.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Pe(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ge(i),pe.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}):(pe.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST",`${xt.DELETE}: missing agentId`);let i=await Pe(n),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(n,e.reason??"delete");let d=Ue(n);return c==="cloud"?await dd(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ge(i)),pe.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Or(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=rd(e.model)??Nt,i=await Pe(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ge(i),pe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,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};let c=o.model;o.model=n,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(u=>pe.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)}));let d=[];for(let[u,f]of o.allSessionQueues())d.push(f.enqueue(async()=>{let x=o.sessions.get(u);x?.downstream&&(await x.downstream.stop(`switchModel: ${n}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(d),pe.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:d.length}),{ok:!0}}async resetAgent(e){if(Or(e._meta,xt.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${xt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,xt.RESET),await this.runDetailSync(e.agentId,xt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),pe.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(n);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await ui(e,o)}async clearPersistedAcpSessionIds(e){let n=await Pe(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let o of Object.values(n.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await Ge(n)}async repairAgent(e){if(Or(e._meta,xt.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${xt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${xt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){pe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,xt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){pe.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){pe.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Or(e._meta,"_agent/getFileTree");let n=e._meta,i=Xn(n),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await ad(d).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await li(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=Vy(e.depth);return u.isDirectory()?{tree:await $y(o,d,c,f)}:{tree:[{name:Zy(c),path:P0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Or(e._meta,"_agent/getFileContent");let n=Xn(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await ad(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 li(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>m0)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${m0})`);let d=await bo(o);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:c.size}:{content:d.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let n=this.opts.agents.get(e);return n?n.workspace:(await Pe(e).catch(()=>null))?.workspace??Ue(e).workspace}safeJoin(e,n){let i=ud(e,n||"."),o=xd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${y0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return Pe(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function v0(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 gd(t){return t==="claude-code"?me(".claude","skills"):me(".agents","skills")}function S0(t){let e=by();return t==="claude-code"?[me(e,".claude","skills")]:t==="codex"?[me(e,".agents","skills"),me(e,".codex","skills")]:[me(e,".agents","skills"),me(e,".openclaw","skills")]}async function Py(t,e,n,i){let o=async c=>hd(me(c,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let c=me(gd(e),n),d=me(t,c);return await o(d)?{absDir:d,relPath:c}:null}for(let c of S0(e)){let d=me(c,n);if(await o(d))return{absDir:d,relPath:d}}return null}async function Oy(t,e,n,i,o){let c=v0(i),d=await Py(e,n,c,o);if(d)return{...d,dirName:c};let f=(o?await C0(t,n):await T0(t,e,n)).filter(w=>w.skill.skillName===i);if(f.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${f.map(w=>g0(w.relPath)).join(", ")} \u2014 rename or remove duplicates`);let x=f[0];return x?{absDir:o?x.relPath:me(e,x.relPath),relPath:x.relPath,dirName:g0(x.relPath)}:null}function I0(t,e){return(yy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function A0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
+ ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let o of n.split(`
94
+ `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function k0(t,e,n,i){let o=await _0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let d of o){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await hd(me(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,x=me(n,f),p=me(e,f,"SKILL.md"),w=await bo(p,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let S=A0(w);c.push({relPath:x,skill:{skillId:I0(t,x),skillName:S.name||f,...S.description?{description:S.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function T0(t,e,n){let i=gd(n);return k0(t,me(e,i),i,!1)}async function C0(t,e){let n=[],i=new Set;for(let o of S0(e)){let c=await k0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var Ly=3e4,Ny=50*1024*1024,w0=10*1024*1024,Mr=3e4;async function vo(t){let{agentId:e,workspace:n,framework:i,skill:o}=t;if(!o.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let c=typeof o.content=="string"&&o.content.length>0,d=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!d)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=v0(o.skillName),f=gd(i),x=me(f,u),p=me(n,x);if(await cd(p,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");qi(S.length),await ld(me(p,"SKILL.md"),S,"utf8")}else{let S=await Fy(o.downloadUrl);Uy(S)?await jy(S,p):Gy(S)?await Hy(S,p):await ld(me(p,"SKILL.md"),S.toString("utf8"),"utf8")}let w={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"}),w}function So(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 My(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 By(t){return{skillId:t.skillId,skillName:t.skillName,...t.downloadUrl?{downloadUrl:t.downloadUrl}:{},...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function R0(t,e){let n=await Pe(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Lt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await Ge(n,e),{status:"seeded",count:0};let c=[...n.skills??[]],d=new Map(c.map((p,w)=>[p.skillId,w])),u=c.filter(p=>p.builtin===!0&&!!p.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Ge(n,e),{status:"noop",count:0};let f=0,x=0;for(let p of u)try{await dd(me(n.workspace,p.relPath),{recursive:!0,force:!0});let w=await vo({agentId:t,workspace:n.workspace,framework:n.framework,skill:By(p)});So(c,d,w),f+=1}catch(w){x+=1,pe.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:p.skillId,skillName:p.skillName,err:String(w)})}return n.skills=c,x===0&&(n.skillsRefreshedForVersion=i),await Ge(n,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 Fy(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);qi(e);let n=zy(t);return qi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await bo(e);return qi(n.length),n}if(Ui(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),Ly);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 qi(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function qi(t){if(t>Ny)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function zy(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("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 Uy(t){return t.length>=2&&t[0]===31&&t[1]===139}function Gy(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 fd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Hy(t,e){let n,i;try{n=new pd.default(t),i=n.getEntries()}catch(d){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||fd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=qy(i),c=ud(e);for(let d of i){if(fd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=ud(e,u),x=xd(c,f);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await cd(f,{recursive:!0});continue}await cd(Ey(f),{recursive:!0});let p;try{p=d.getData()}catch(w){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await ld(f,p)}}function qy(t){let e;for(let n of t){let i=n.entryName;if(!i||fd(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 jy(t,e){await Wy(t);let n=$f({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Mr}ms)`))},Mr);try{await E0(b0.from(t),n)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Mr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Wy(t){let e=[],n=Pr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Mr}ms)`))},Mr);try{await E0(b0.from(t),n)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Mr}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 Ky=5e3;async function $y(t,e,n,i){return D0(t,e,n,i,{count:0})}async function D0(t,e,n,i,o){if(i<=0)return[];let c;try{c=await _0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(Ay.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Ky){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=me(e,u.name),x=vy(me(n,u.name)),p=null;try{p=await ad(f)}catch{continue}if(p.isSymbolicLink())continue;o.count++;let w={name:u.name,path:P0(xd(t,f)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(w.children=await D0(t,f,x,i-1,o)),d.push(w)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function Vy(t){return!t||t<=0?Sy:Math.min(t,Iy)}function Zy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function P0(t){return t.split(y0).join("/")}ie();var Cn=H("agent-health-reporter"),Yy=1e4,Jy=3,ji=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Yy,this.livenessFailureThreshold=e.livenessFailureThreshold??Jy}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()}),Cn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Cn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Cn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Cn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let d of this.opts.core.agents.values()){let u=Xy(d);if(!u)continue;let f={agentId:d.agentId,status:u};d.patToken&&(f.patToken=d.patToken),d.accountId&&(f.accountId=d.accountId),n.push(f)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Lt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Cn.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(Cn.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(d){Cn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Cn.warn("onTickEnd hook failed",{err:String(n)})}}};function Xy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}pn();import{copyFile as pE,cp as gE,mkdir as Mo,readFile as mE,rm as wE,stat as Ad,writeFile as _E}from"node:fs/promises";import{homedir as hh}from"node:os";import{basename as yE,join as Xt}from"node:path";ln();import{existsSync as ub}from"node:fs";import{release as fb}from"node:os";import{basename as hb,isAbsolute as xb}from"node:path";function Wi(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Br(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Fr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Rn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ve();var Io=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 O0(t){return"method"in t&&"id"in t&&t.id!==void 0}function L0(t){return"method"in t&&!("id"in t)}function Ao(t){return!("method"in t)&&"id"in t}var Qy={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 eb(t){if(t!=null)return t instanceof Error?{name:t.name,message:Ki(t.message)}:typeof t=="string"?Ki(t):typeof t=="object"?nb(t):t}var tb=[[/\/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 Ki(t){let e=t;for(let[n,i]of tb)e=e.replace(n,i);return e}function nb(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Ki(i):e[n]=i;return e}function $i(t){if(t instanceof k){let e=eb(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:Qy[t.code]??X.INTERNAL_ERROR,message:Ki(t.message),data:n}}return{code:X.INTERNAL_ERROR,message:Ki(t instanceof Error?t.message:String(t))}}function N0(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:d,...u}=e;c=u}return new k(n,o,{retriable:e?.retriable??!1,cause:c})}function B0(t){return`${JSON.stringify(t)}
95
+ `}var M0=10*1024*1024,ko=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>M0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${M0} bytes`)}),[]}let n=this.buffer.split(`
96
+ `);this.buffer=n.pop()??"";let i=[];for(let o of n){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(d){this.onError?.({line:c,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(n){return this.onError?.({line:e,error:n}),[]}}};var z0={"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"},NT=Object.fromEntries(Object.entries(z0).map(([t,e])=>[e,t])),rb={"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:[]},zr=class{seq=0;next(e,n){this.seq+=1;let i=z0[e]??ib(e),o=rb[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>F0(n?.[f]??"")),u=sb(d).join(":");u&&c.push(u)}else n&&Object.values(n).some(d=>d)&&c.push(Object.values(n).filter(Boolean).map(d=>F0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function ib(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function F0(t){return t.replace(/[:_\s]+/g,"-")}function sb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}xn();import{readFileSync as ob}from"node:fs";var ab=384;async function md(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await hn(t.agentEnvFile,n,{mode:ab})}function Vi(t){try{let e=JSON.parse(ob(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function To(t,e,n={},i=o=>o){return{...i({...t,...Vi(e)}),...n}}Yt();ur();Ve();ie();De();import{execFileSync as cb,spawnSync as db}from"node:child_process";function Zi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Yi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),db("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var wd=new Set;function U0(t){typeof t=="number"&&t>0&&wd.add(t)}function G0(t){typeof t=="number"&&wd.delete(t)}function H0(){for(let t of wd)Yi(t,"SIGKILL")}var Ur="coze-bridge-daemon";function q0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return cb("pgrep",["-U",String(o),"-f",Ur],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
97
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function j0(t,e){if(t.length===0)return;let n=e?.killFn??Yi,i=e?.isAliveFn??Zi,o=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),c=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<c&&t.some(f=>i(f));u+=d)await o(Math.min(d,c-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var lb=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]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 W0(t,e){if(!e)return null;for(let n of lb)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function K0(t,e){return W0(t,e)}function $0(t,e){return W0(t,e)}function Gr(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 V0(t,e,n){let o=n-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,p=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Gr(p,t.firstFrameSeen,e)}}let c=n-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:Gr(c,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Gr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Gr(c,!1,e)}}var Z0=Je("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),pb=200,gb=40,mb=Je("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),wb=Je("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),_b=Je("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),yb=Je("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),bb=Je("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Eb=Je("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Y0=500;function vb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Y0?t:`${e.slice(0,Y0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Sb(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 J0(t){try{return ub(t)}catch{return}}function Ib(t,e){return{platform:process.platform,osRelease:fb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:xb(e.command)?J0(e.command):void 0,cwd:e.cwd,cwdExists:J0(e.cwd),envKeys:e.envKeys}}function Ab(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${hb(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Mt=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new ko({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new zr;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",n=To(process.env,this.opts.agentEnvFile??J().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=st(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,U0(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>pb&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,c)=>{this.stopped=!0,G0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,d=Ib(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new k("AGENT_SPAWN_FAILED",Ab(c,d),{cause:d}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let n=this.child,i=new Promise(c=>n.once("exit",()=>c()));Yi(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||Yi(n.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,n){let i={firstUpdateMs:bb,phase2GateMs:mb,livenessWindowMs:wb,absoluteMaxMs:_b,approvalMaxMs:Eb,suspendThresholdMs:yb,...n};return this.call("session/prompt",e,Z0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Br("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(Fr(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(Rn(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=Z0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Wi(c,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 p={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),S={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:Gr(0,!1,o),sessionId:u};p.promptTimeout=S;let _=()=>{let E={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=V0(E,S.cfg,I),T=P=>{S.armedAt=I,S.expectedIntervalMs=P,p.timer=setTimeout(_,P)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(_,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(p.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,p);try{this.writeFrame(d)}catch(w){p.timer&&clearTimeout(p.timer),this.pending.delete(c),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(B0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(Ao(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 k("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:vb(e.result)}),n.resolve(e.result));return}if(L0(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(O0(e)){let 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,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Rn(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(Rn(e.id,$i(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=N0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=$0(this.framework,Sb(e));return i?new k(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 k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(gb).join(`
98
+ `),o=K0(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:n,stderrTail:i}}):new k("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 kb(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 Co=class extends Mt{framework="claude-code";constructor(e){let{command:n,args:i}=di("claude-code",e.command,e.args??[]),o={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return kb(e)}};ln();import{spawn as Tb}from"node:child_process";import{closeSync as Cb,existsSync as bd,mkdirSync as Rb,mkdtempSync as Db,openSync as Pb,readFileSync as rh,readSync as Ob,readdirSync as Lb,rmSync as Nb,statSync as Mb}from"node:fs";import{homedir as Bb,tmpdir as Fb}from"node:os";import{join as Hr}from"node:path";var X0=["default","acceptEdits","plan","auto","bypassPermissions"],Q0=["read-only","auto","full-access"];function Bt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return X0.includes(e);case"codex":return Q0.includes(e);case"openclaw":return!1}}function Ro(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function eh(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function _d(t){switch(t){case"claude-code":return X0.join("/");case"codex":return Q0.join("/");case"openclaw":return""}}De();var Ed=9e4,zb=64*1024,Ub=100;function Gb(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Ed:Math.max(1,Math.floor(e*1e3))}function Hb(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Ed:Math.max(1,Math.floor(e))}function qb(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n]=i);return Object.keys(e).length>0?e:void 0}function th(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:Ed};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let n=typeof e.command=="string"?e.command.trim():"";if(!n)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=qb(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?Gb(e.timeout):Hb(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function yd(t){if(Array.isArray(t))return t.flatMap(i=>yd(i));if(!t||typeof t!="object"){let i=th(t);return i?[i]:[]}let e=t;if(e.hooks)return yd(e.hooks);let n=th(e);return n?[n]:[]}function jb(t){let e=Hr(t,"hooks.json");if(!bd(e))return[];let n=JSON.parse(rh(e,"utf8")),o=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return yd(o.Stop??o.stop)}function Wb(t,e){let n=Hr(t,"sessions");if(!bd(n))return;let i=[],o=c=>{let d;try{d=Lb(c,{withFileTypes:!0})}catch{return}for(let u of d){let f=Hr(c,u.name);if(u.isDirectory())o(f);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:f,mtimeMs:Mb(f).mtimeMs})}catch{}}};o(n),i.sort((c,d)=>d.mtimeMs-c.mtimeMs);for(let c of i.slice(0,Ub))if(Kb(c.path,e))return c.path;return i[0]?.path}function Kb(t,e){let n;try{n=Pb(t,"r");let i=Buffer.alloc(zb),o=Ob(n,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(n!==void 0)try{Cb(n)}catch{}}}function $b(t){return Vi(t??J().agentEnvFile)}function Vb(t){let e=t.trim();if(e.length>=2){let n=e[0];if((n==='"'||n==="'")&&e.endsWith(n)){let i=e.slice(1,-1);return n==='"'?i.replace(/\\n/g,`
99
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function Zb(t){let e={};for(let n of t.split(/\r?\n/)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.startsWith("export ")?i.slice(7).trimStart():i,c=o.indexOf("=");if(c<=0)continue;let d=o.slice(0,c).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=Vb(o.slice(c+1)))}return e}function Yb(t){let e=Hr(t,"cozeloop.env");return bd(e)?Zb(rh(e,"utf8")):{}}function nh(t){let e=t?.trim();return e||void 0}function Jb(t){let e=$b(t.agentEnvFile),n=nh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=nh(t.env?.HOME??e.HOME??process.env.HOME)??Bb();return Hr(i,".codex")}var Do=class extends Mt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:c}=di("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Db(Hr(Fb(),"coze-bridge-codex-home-")):Jb(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&Rb(d,{recursive:!0});let f=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}: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=d,this.cleanupCodexHomeDir=u}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async sessionPrompt(e){let n=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),n}setSessionMode(e){let n=Bt("codex",e.modeId)?Ro(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(Xb(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=jb(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let o=Wb(n,e),c=JSON.stringify({hook_event_name:"Stop",session_id:e,...o?{transcript_path:o}:{},trigger:"coze-bridge"});await Promise.all(i.map(async d=>{try{await this.runHookCommand(d,c)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:n,command:d.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,n){return new Promise((i,o)=>{let c=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=c?Yb(c):{},u=To(process.env,this.opts.agentEnvFile??J().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}});this.opts.env?.COZELAB_ONBOARD_CLOUD==="true"&&u.COZE_API_TOKEN&&(u.COZELOOP_API_TOKEN=u.COZE_API_TOKEN);let f=Tb(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",p=setTimeout(()=>{f.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);f.stderr?.setEncoding("utf8"),f.stderr?.on("data",w=>{x+=w,x.length>4e3&&(x=x.slice(-4e3))}),f.on("error",w=>{clearTimeout(p),o(w)}),f.on("close",(w,S)=>{if(clearTimeout(p),w===0){i();return}o(new Error(`hook exited code=${w} signal=${S} stderr=${x.slice(-1e3)}`))}),f.stdin.end(`${n}
100
+ `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{Nb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function Xb(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=eh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}Ve();var Qb=3e4,qr=class extends Mt{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 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=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}`}]},Qb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};xn();Ve();ie();De();function vd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}ln();var Dn=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 Po=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 Dn,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)jr(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 jr(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"}Yt();ie();import{constants as ih}from"node:fs";import{access as eE}from"node:fs/promises";import{delimiter as tE,join as nE}from"node:path";var St=H("framework-detector"),sh={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},rE=[".exe",".cmd",".bat",".ps1"],Qn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??st,access:e.access??eE}}async detect(e){let n=sh[e],i=await this.which(n);if(!i)return St.debug("framework binary not found",{framework:e,bin:n}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(sh).map(async i=>[i,await this.detect(i)])),n={};for(let[i,o]of e)o&&(n[i]=o);return n}async which(e){let n=this.env.pathEnv.split(tE).filter(Boolean),i=this.env.platform==="win32"?["",...rE]:[""];for(let o of n)for(let c of i){let d=nE(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?ih.F_OK:ih.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return St.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return St.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return St.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return St.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(St.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(St.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return St.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return St.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||St.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let o={reachable:i},c=n.stdout.match(/\{[\s\S]*\}/);if(c)try{let d=JSON.parse(c[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){St.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(sE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let o="",c=!1,d,u=f=>{c||(c=!0,d&&clearTimeout(d),i(f))};try{let f=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{o+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},iE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function sE(t){return t.replace(iE,"")}import{homedir as ah}from"node:os";import{join as Lo}from"node:path";xn();Yt();ur();Ve();ie();async function ch(){let t=Lo(ah(),".openclaw/openclaw.json");return un(t)}async function dh(){return(await ch())?.gateway?.auth?.token??""}var er=H("openclaw.config"),oE=[0,5e3,5e3],aE=Je("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),oh="models.providers.",Oo="agents.defaults.models",cE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function Sd(t,e){if(!Array.isArray(t))return!1;let n=new Set(t);return e.every(i=>n.has(i))}var No=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Dn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??oE,this.cliTimeoutMs=e.cliTimeoutMs??aE,this.openclawDir=e.openclawDir??Lo(ah(),".openclaw")}async withRetry(e,n){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(d=>setTimeout(d,c));try{return await n()}catch(d){i=d,er.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=st(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=x=>{d||(d=!0,clearTimeout(f),x())};o.stderr?.on("data",x=>{c+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let o=String(i);if(n.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",n],["Config path not found","Nothing was changed"])))}catch(i){er.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",`${oh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${oh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Oo}[${e}]`,()=>this.runCli(["config","set",Oo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Oo}[${e}]`,`${Oo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await ch())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,c=[];for(let d of Object.keys(i))d.startsWith(o)&&c.push(d.slice(o.length));return c}ensureAgent(e,n,i){let o=["agents","add",e,"--workspace",n,"--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=Lo(this.openclawDir,"identity","device.json"),i=(await un(e))?.deviceId?.trim();if(!i)return er.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Lo(this.openclawDir,"devices","paired.json"),c=await un(o),d=c?.[i];if(!c||!d)return er.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=[...cE],f=d.tokens?.operator;return Sd(d.scopes,u)&&Sd(d.approvedScopes,u)&&Sd(f?.scopes,u)?(er.debug("acp device already has full operator scopes",{deviceId:i}),!1):(d.scopes=[...u],d.approvedScopes=[...u],f&&(f.scopes=[...u]),await hn(o,c,{mode:384}),er.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:u}),!0)}catch(e){return er.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};import{readFile as dE,writeFile as lE}from"node:fs/promises";import{join as uE}from"node:path";var fE=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
101
+ `),hE=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
102
+ `);function xE(t){return t.length===0?t:`${(t.endsWith(`
103
103
  `)?t.slice(0,-1):t).split(`
104
104
  `).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
105
105
  `)}
106
- `}async function ah(t){let e=oE(t,"HEARTBEAT.md"),r=await iE(e,"utf8");return dE(r)!==aE?!1:(await sE(e,cE),!0)}var oe=H("agent-manager"),vd="acceptEdits",lh="full-access",uh="read-only";function hE(t){return{INITIAL_AGENT_MODE:So(t)}}var xE=(t,e,r,i,o,c,d,u,h,x,g,w)=>{switch(t){case"claude-code":{let S={...o?{...c0(o),...u0(o,d,u,w)}:{},...h??{},IS_SANDBOX:"1"};return new vo({cwd:r,env:S,agentId:i})}case"codex":{let S=lh;x!==void 0&&(Mt("codex",x)?S=x:oe.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _={...o?{...l0(o),...d0(o,d,u,w)}:{},...hE(S),...h??{}},E=!!o;return new Io({cwd:r,agentId:i,...Object.keys(_).length>0?{env:_}:{},...E?{authMethodId:"api-key",isolateCodexHome:!0,...g?{codexHomeDir:g}:{}}:{}})}case"openclaw":return new Ur({command:e,cwd:r,agentId:i,...c?{sessionName:wd(c)}:{}})}};function Ed(t){return t==="claude-code"||t==="codex"}function pE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(gE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
106
+ `}async function lh(t){let e=uE(t,"HEARTBEAT.md"),n=await dE(e,"utf8");return xE(n)!==fE?!1:(await lE(e,hE),!0)}var te=H("agent-manager"),bE=["hooks.json","cozeloop.env"],EE=["hooks"];async function vE(t,e){let n=Xt(Ue(t,e).root,"codex-home"),i=Xt(hh(),".codex");if(n!==i){await Mo(n,{recursive:!0});for(let o of EE){let c=Xt(i,o),d=Xt(n,o);try{await Ad(d);continue}catch{}try{await gE(c,d,{recursive:!0,errorOnExist:!0,filter:u=>{let f=yE(u);return!f.endsWith(".log")&&!f.includes(".bak")}}),te.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&te.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}for(let o of bE){let c=Xt(i,o),d=Xt(n,o);try{await Ad(d);continue}catch{}try{if(o==="cozeloop.env"){let f=(await mE(c,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
107
+ `);await _E(d,f,{mode:384})}else await pE(c,d);te.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&te.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var kd="acceptEdits",xh="full-access",ph="read-only";function SE(t){return{INITIAL_AGENT_MODE:Ro(t)}}var IE=(t,e,n,i,o,c,d,u,f,x,p,w)=>{switch(t){case"claude-code":{let S={...o?{...u0(o),...x0(o,d,u,w)}:{},...f??{},IS_SANDBOX:"1"};return new Co({cwd:n,env:S,agentId:i})}case"codex":{let S=xh;x!==void 0&&(Bt("codex",x)?S=x:te.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _={...o?{...h0(o),...f0(o,d,u,w)}:{},...SE(S),...f??{},...o?{COZELAB_ONBOARD_CLOUD:"true"}:{}},E=!!o;return new Do({cwd:n,agentId:i,...Object.keys(_).length>0?{env:_}:{},...E?{authMethodId:"api-key",isolateCodexHome:!0,...p?{codexHomeDir:p}:{}}:{}})}case"openclaw":return new qr({command:e,cwd:n,agentId:i,...c?{sessionName:vd(c)}:{}})}};function Id(t){return t==="claude-code"||t==="codex"}function AE(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(kE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
107
108
  `)}
108
- `}function gE(t){if(t.includes(`
109
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var mE={path:"",version:"cloud-deployed"},ch="openclaw_gateway_unavailable",wE="openclaw_default_agent_missing";function dh(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 _E={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},yE=6e4,Ro=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??xE,this.createTimeoutMs=e.createTimeoutMs??yE,this.detectorFactory=e.detectorFactory??(()=>new Jn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Co({command:r,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??bd(fE(),".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=>{oe.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=bd(e,".env");if(await uE(r).then(c=>c.isFile()).catch(()=>!1)){oe.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=pE({...process.env,...ji(this.paths.agentEnvFile)});await ln(r,o,{mode:384}),oe.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),oe.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new T("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new T("IPC_BAD_REQUEST","framework required");let i=await De(e.agentId,this.paths).catch(()=>null),o=fo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new T("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")oe.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(C=>oe.warn("dispose stale agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")oe.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(C=>oe.warn("dispose drifted agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){oe.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let C=await De(e.agentId,this.paths).catch(()=>null);C&&(C.patToken=e.patToken,await Fe(C,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){oe.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let C=await De(e.agentId,this.paths).catch(()=>null);C&&(C.modelInfo=e.modelInfo,await Fe(C,this.paths))}return oe.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework])throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=$e(e.agentId,this.paths),h=o?"cloud":"local",x=e.framework==="openclaw"&&h==="local",g;x&&!r?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??w??u.workspace,_=new AbortController,E=setTimeout(()=>_.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,k=!1;try{o&&Ed(e.framework)&&await fr(e.framework,_.signal);let C=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await yd(u.root,{recursive:!0}),await yd(S,{recursive:!0}),await yd(u.logs,{recursive:!0}),C(),x||await hr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await za(S,"cloud"):await za(S,"local",vd)),C();let P=i,b=o0({model:e.model??P?.model}),R=Kf(e._meta)??P?.accountId,O=e.patToken??P?.patToken,B=h==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new Ao({agentId:e.agentId,framework:e.framework,workspace:S,model:b.model??Lt,deployType:h,...R?{accountId:R}:{},...O?{patToken:O}:{},...B?{modelInfo:B}:{}}),I.status="ok",P?.sessions){let V=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,ee]of Object.entries(P.sessions)){let se={acpSessionId:ee.acpSessionId,modelToken:ee.modelToken,tokenGeneratedAt:ee.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?ee.permissionMode===void 0?(se.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",oe.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:se.permissionMode})):Mt(e.framework,ee.permissionMode)?se.permissionMode=ee.permissionMode:oe.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:ee.permissionMode}):ee.permissionMode!==void 0&&oe.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:h}),ee.cozeGroupId&&(se.cozeGroupId=ee.cozeGroupId),ee.tokenGroupId&&(se.tokenGroupId=ee.tokenGroupId),ee.requestScene&&(se.requestScene=ee.requestScene),I.sessions.set(X,se)}let re=Object.keys(P.sessions).length;re>0&&oe.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(I),k=!0;let M={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:b.model};if(h==="cloud"&&(M.deployType="cloud"),R&&(M.accountId=R),O&&(M.patToken=O),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??Ot,e.framework==="openclaw"&&h==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):oe.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await ah(S)&&oe.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:S})}catch(V){oe.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:S,err:String(V)})}}let Z=e.initialSkills??[];if(Z.length>0){let V=[...M.skills??[]],re=new Map(V.map((se,D)=>[se.skillId,D])),X=await Promise.allSettled(Z.map(se=>mo({agentId:e.agentId,workspace:S,framework:e.framework,skill:se}))),ee=0;for(let[se,D]of X.entries()){let U=Z[se];U&&(D.status==="fulfilled"?(wo(V,re,D.value),ee++):oe.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(D.reason)}))}ee>0&&(M.skills=V,oe.info("initialSkills installed",{agentId:e.agentId,installed:ee,requested:Z.length}))}return await Fe(M,this.paths),oe.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(C){throw oe.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),k&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await lE(u.root,{recursive:!0,force:!0}).catch(P=>oe.warn("rm agent dir failed (ignored)",{err:String(P)})),C instanceof T?C:new T("AGENT_SPAWN_FAILED",String(C),{cause:C})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,r,i,o,c,d){let h=this.config.frameworksCache?.[e.framework];if(!h)if(e.deployType==="cloud"&&Ed(e.framework))h=mE;else throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Ed(e.framework)&&!ws(e.framework)&&(oe.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await fr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,g;if(e.framework==="openclaw")g=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:c,requestScene:d,command:h.path});else{let w=e.sessions.get(i),S=Yt(e)?w?.permissionMode??lh:"full-access";g=this.factory(e.framework,h.path,e.workspace,e.agentId,x,i,o,c,this.buildBinShimPathEnv(),S,e.framework==="codex"&&e.deployType==="cloud"?bd($e(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await g.start(),await g.initialize(_E),g}catch(w){let S=g instanceof Nt?g.getStderrTail():[];throw S.length>0&&oe.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof T?w.code:"unknown",recentStderr:S}),await g.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,h.path,w)}}async resolveSpawnFailure(e,r,i){if(e.framework==="openclaw"&&e.deployType==="local"&&r)try{let o=await this.detectorFactory().probeOpenclawGateway(r);if(!o.reachable)return new T("AGENT_ENV_NOT_READY",dh(o),{cause:{reason:ch}})}catch(o){oe.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof T?i:new T("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};oe.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 oe.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new T("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:wE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new T("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new T("AGENT_ENV_NOT_READY",dh(r),{cause:{reason:ch}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,requestScene:u,command:h}=e,x=wd(o);if(r.deployType==="local"){let S=await this.ensureOpenclawDefaultAgent();return new Ur({command:h,cwd:S.workspace,agentId:S.id,sessionName:x})}let g=await oh();try{await this.getOpenclawConfig().ensureAcpDeviceScopes()}catch(S){oe.warn("acp device scope ensure failed (ignored)",{err:String(S)})}let w;if(i?.modelToken){let S=ed(o),_=td(i),E=`${S}/${_}`;if(!this.ensuredProviders.has(E)){let I=this.getOpenclawConfig(),k=await I.getAllowlistModelsForProvider(S),C=f0(i,c,d,k,u);C&&(await I.ensureProvider(S,C),await I.addModelToAllowlist(E),this.ensuredProviders.add(E))}w=E}return new Ur({command:h,cwd:r.workspace,agentId:r.agentId,sessionName:x,...g?{gatewayToken:g}:{},...w?{slashModelOnStart:w}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e,r){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=r??e.model;for(let c of e.sessions.keys()){let d=ed(c),u=`${d}/${o}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,oe.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,oe.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as gh}from"node:crypto";import{promises as kE}from"node:fs";import{basename as mh}from"node:path";Ke();ne();import{promises as bE}from"node:fs";import{basename as EE}from"node:path";var fh=H("file-upload"),vE="/api/coze_claw/file/agent_upload",SE=6e4;async function hh(t,e={}){let i=`${Dr(Pr(e.handshakeBase))}${vE}`,o=e.timeoutMs??SE,c=await bE.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...An(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),o);fh.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:d,signal:h.signal}),w=g.headers.get("x-tt-logid")??"";if(!g.ok){let E=await g.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${w}: ${E.slice(0,200)}`)}let S=await g.json();if(S.code!==void 0&&S.code!==0)throw new T("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${w}`);let _=S.data?.file?.file_url;if(!_)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(S).slice(0,200)}`);return fh.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(g){throw g instanceof T?g:g.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${EE(t.path)}`):new T("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}Ke();ne();import{extname as IE}from"node:path";var AE={".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 xh(t){let e=IE(t).toLowerCase();return AE[e]??"application/octet-stream"}Re();var Do=H("agent-send"),ph=50*1024*1024;function wh(t,e,r){let i=t.get(e);if(!i)throw new T("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new T("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new T("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function _h(t,e,r,i,o,c){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(x){u=x,h<2&&(Do.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(g=>setTimeout(g,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function yh(t,e){let{session:r,runtime:i}=wh(e.core,t.agentId,t.sessionId);if(!await oi(t.path,r.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await kE.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new T("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>ph)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${ph}`);let c=await xh(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new T("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??mh(t.path),u;try{u=await hh({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Do.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:x instanceof T?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:gh(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:d,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await _h(e,r,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Do.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function bh(t,e){let{session:r,runtime:i}=wh(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new T("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??mh(t.path),c={sessionUpdate:"group_file",messageId:gh(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await _h(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Do.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:o,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function Eh(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(r.length,i.length);for(let c=0;c<o;c++){let d=r[c]??0,u=i[c]??0;if(d<u)return!0;if(d>u)return!1}return!1}cn();Jt();ne();var Bt=H("coze-cli-installer"),vh="@coze/cli@latest",TE="coze",Sh="0.1.8",CE=5e3,RE=5e3,DE=9e4,Ih=1e4,$i=null,Po=!1;async function Id(t,e={}){if(Po)return;if($i)return $i;let r=e.exec??Xf;return $i=(async()=>{try{let i=await PE(TE,r),o=!1;if(i){let d=await OE(r);if(d===void 0)Bt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Eh(d,Sh))Bt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:Sh}),o=!0;else{Bt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Po=!0;return}}let c=o?"upgrade-only":"full";Bt.info("coze-cli install start",{package:vh,mode:c});try{await r("npm",["i","-g","--prefer-online",vh],{timeout:DE,maxBuffer:10*1024*1024}),Bt.info("coze-cli install ok")}catch(d){Bt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Po=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:Ih}),Bt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Bt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:Ih}),Bt.info("coze auth login ok")}catch(d){Bt.warn("coze auth login failed",{err:String(d)});return}Po=!0}finally{$i=null}})(),$i}async function PE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:CE});return Ba(i)}catch{return}}async function OE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:RE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}fn();Re();var LE=10*6e4;function Ah(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?LE:e}function Oo(t){return dn(t??J().configFile)}function Vi(t,e){return un(e??J().configFile,t)}import{randomBytes as ev}from"node:crypto";cr();Ke();ne();import{createReadStream as NE}from"node:fs";import{mkdir as ME,readFile as BE,realpath as FE,stat as zE,writeFile as UE}from"node:fs/promises";import{basename as qE,dirname as Ad,isAbsolute as HE,join as GE,relative as jE,resolve as kh,sep as WE}from"node:path";import{createInterface as KE}from"node:readline";var Ch=H("fs-rpc"),Zi=Je("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Rh(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Zi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Zi} bytes`);let i=await Ph(t.path,e);return await ME(Ad(i),{recursive:!0}),await UE(i,t.content,"utf8"),Ch.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Dh(t,e){let r=await Ph(t.path,e),i=await zE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Zi&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Zi} bytes`);let c;if(o&&i.size>Zi)c=await $E(r,t.line??1,t.limit);else{let d=await BE(r,"utf8");if(o){let u=d.split(`
110
- `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;c=u.slice(h,x).join(`
111
- `)}else c=d}return Ch.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function $E(t,e,r){let i=KE({input:NE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let h of i)if(u>=o&&u<c&&d.push(h),u++,u>=c)break}finally{i.close()}return d.join(`
112
- `)}async function Ph(t,e){if(typeof t!="string"||t.length===0)throw new T("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([Th(kh(e)),Th(kh(t))]),o=jE(r,i);if(VE(o,WE,HE(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function VE(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function Th(t){let e=[],r=t;for(;r!==Ad(r);)try{let i=await FE(r);return e.length?GE(i,...e.reverse()):i}catch{e.push(qE(r)),r=Ad(r)}return t}ne();var Oh=H("prompt-multimodal"),Lh=10*1024*1024,ZE=15e3,JE=6;async function Nh(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,d=t[c];d!==void 0&&(e[c]=await YE(d))}}let o=Array.from({length:Math.min(JE,t.length)},()=>i());return await Promise.all(o),e}function Mh(t){return t.some(e=>e.type==="image")}async function YE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Mi(e.uri))return t;try{let{buf:r,contentType:i}=await QE(e.uri),o=e.mimeType||XE(i)||"application/octet-stream";return Oh.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 Oh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function XE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function QE(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ZE);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>Lh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Lh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}hn();Ke();ne();var K=H("core"),tv=3e4,nv=/^(boe|ppe)_[A-Za-z0-9_-]+$/,rv="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",iv="\u5BA1\u6279\u5DF2\u8D85\u65F6",sv=3e4,Lo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Mr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=Ah(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}getRequestSceneForSession(e){return this.requestSceneBySession.get(e)}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(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),K.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(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,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,d)=>{K.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),qr(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){K.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(Tn(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(d=>K.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:Y.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){K.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Y.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(yo(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&&nv.test(i)?this.currentCozeEnv=i:i&&K.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,c=$f(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);c&&u!==c?(this.requestSceneBySession.set(d,c),K.info("cached request_scene for session",{sessionId:d,requestScene:c})):!c&&u!==void 0&&(this.requestSceneBySession.delete(d),K.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):K.warn("drop notification: extension not registered",{method:e.method});return}let h=await u(e,this);r!==null&&await this.upstream.send(Nr(r,h));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Nr(r,u));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,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):K.warn("drop unknown notification",{method:e.method})}catch(u){K.error("handleFrame failed",{method:e.method,err:String(u)}),r!==null&&await this.upstream.send(Tn(r,Gi(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new T("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new T("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new T("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new T("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let h=o.sessions.get(c);if(h?.pendingPermission){let x=r._meta?.cozeTriggerMsgId,g=ho(r._meta);return K.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,h,c,rv,x,g)}}let d=Date.now(),u=!1;try{let h=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,h}finally{K.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Zf(i);switch(r){case"session/new":{let c=ov();return K.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return K.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,d=c.sessionId;if(!d)throw new T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Yt(e)?Vf(i._meta):void 0;if(u!==void 0&&!Mt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${xd(e.framework)}`);let h=ho(i._meta),x=this.requestSceneBySession.get(d),g=await this.ensureRuntime(e,d,h,x);if(u!==void 0&&g.permissionMode===void 0&&(g.permissionMode=u,await this.persistSessionMapping(e)),g.replySeq=0,await this.ensureDownstream(e,d,g),!g.downstream||!g.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&g.permissionMode!==void 0&&g.permissionMode!==u){let _=g.permissionMode;g.permissionMode=u,await this.persistSessionMapping(e);try{await g.downstream.setSessionMode({sessionId:g.acpSessionId,modeId:u})}catch(E){throw g.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),E}}let w=i._meta?.cozeTriggerMsgId;if(w?e.activeTriggers.set(g.acpSessionId,w):e.activeTriggers.delete(g.acpSessionId),h?e.activeGroupIds.set(g.acpSessionId,h):e.activeGroupIds.delete(g.acpSessionId),h&&g.cozeGroupId!==h&&(g.cozeGroupId=h,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Mh(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let S=await Nh(c.prompt);try{let _=await g.downstream.sessionPrompt({...c,sessionId:g.acpSessionId,prompt:S});return g.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof T&&_.code==="AGENT_APPROVAL_TIMEOUT"){let E=g.pendingPermission;E&&(E.downstream.respondAgentRequest(E.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(E.upstreamId),g.pendingPermission=void 0);let I=g.acpSessionId,k=I?e.activeTriggers.get(I):void 0,C=I?e.activeGroupIds.get(I):void 0;return K.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,g,d,iv,k,C)}throw _}finally{if(e.activeTriggers.delete(g.acpSessionId),e.activeGroupIds.delete(g.acpSessionId),g.pendingPermission=void 0,g.reloadAfterTurn){g.reloadAfterTurn=!1;let _=g.downstream;_&&(g.downstream=void 0,K.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:g.acpSessionId}),_.stop("reload-after-turn").catch(E=>K.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(E)})))}else g.downstream?.isAlive()&&this.armIdleTimer(e,d,g)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new T("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&(K.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new T("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,d=c.sessionId,u=c.modeId,h=ho(i._meta);if(!d)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Yt(e))throw e.framework==="openclaw"?new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new T("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Mt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${xd(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let 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(w){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),w}else K.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new T("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return K.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};K.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of o){let u=d.runtime.downstream,h=d.runtime.acpSessionId;u?.isAlive()&&h&&c.push({downstream:u,acpSessionId:h,oldMode:d.oldMode,runtime:d.runtime})}for(let d of c)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let h of o)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r,i,o){let c=e.sessions.get(r);if(c){let h=e.deployType==="cloud"&&c.tokenGroupId!==i,x=c.requestScene!==o;if(h&&(c.modelToken=await this.requestSessionToken(e.agentId,r,i),c.tokenGeneratedAt=Date.now(),c.tokenGroupId=i),h||x){qr(c);let g=c.downstream;c.downstream=void 0,g&&await g.stop("request-context-changed")}return c.cozeGroupId=i,c.requestScene=o,(h||x)&&await this.persistSessionMapping(e),c}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...o?{requestScene:o}:{}};return Yt(e)&&(u.permissionMode=e.framework==="claude-code"?vd:uh),e.sessions.set(r,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,r,i){let o={sessionId:r,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let c=await this.sendRequest(ft.GEN_MODEL_TOKEN,o,sv);if(!c?.modelToken)throw new T("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return c.modelToken}catch(c){throw c instanceof T&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new T("MODEL_TOKEN_GEN_FAILED",c instanceof Error?c.message:String(c),{cause:c})}}async ensureDownstream(e,r,i){if(qr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new T("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<c)throw new T("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let h;try{let x=this.requestSceneBySession.get(r);x&&K.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:r,requestScene:x}),h=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(K.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=h,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await h.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),K.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){K.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 h.sessionNew({cwd:e.workspace});i.acpSessionId=g.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw K.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),Yt(e)&&i.acpSessionId&&i.permissionMode)try{await h.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){K.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(qr(i),this.isRuntimeBusy(e,i)){K.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)){K.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}K.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=>K.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let d=e.activeTriggers.get(r.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Lr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),d&&(u.cozeGroupId=d),await this.upstream.send(Lr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(h=>K.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){K.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){K.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(dv(r)){K.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=r.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Yt(e)){let g=d.currentModeId;Mt(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(w=>K.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof g=="string"&&!Mt(e.framework,g)&&K.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},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Lr("session/update",{...r,sessionId:o,_meta:u})).catch(g=>K.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}K.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:Y.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await Rh(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await Dh(c,o);r.respondAgentRequest(i.id,d)}}catch(o){K.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Gi(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,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let g=u?e.activeGroupIds.get(u):void 0;g&&(x.cozeGroupId=g);let w=u?this.reverseSessionId(e,u):void 0,S=w?e.sessions.get(w):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let _={...c,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:w}),K.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:w,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(qi(o,"session/request_permission",_)).catch(E=>{this.pendingUpstream.delete(o),K.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),r.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(K.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"&&av(e.result,o),K.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 _o(e.error)):i.value.resolve(e.result);return}K.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),d=e.get(c);if(d)return K.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:d,key:c}}}sendRequest(e,r,i=tv){let o=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(qi(o,e,r)).catch(h=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(h)})})}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&&Yt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),o.tokenGroupId&&(c.tokenGroupId=o.tokenGroupId),o.requestScene&&(c.requestScene=o.requestScene),r.set(i,c)}await ai(e.agentId,r,this.paths)}catch(r){K.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(Tn(e,{code:r,message:i,data:{bridgeVersion:Ot}}))}};function ov(){return ev(16).toString("hex")}function av(t,e){if(!t||typeof t!="object"){K.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){K.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"){K.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")&&K.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var cv=["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 dv(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 cv.some(c=>o.startsWith(c))}fn();ne();Re();import{randomBytes as lv}from"node:crypto";import{createServer as uv}from"node:http";var fv=1e6,Bh=H("ipc"),No=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??J()}async start(){this.token=lv(32).toString("hex");let e=uv((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(),Bh.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 ln(this.paths.portFile,String(this.port)),await ln(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Ji(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Ji(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await hv(e)}catch(u){Ji(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Ji(r,200,u??{ok:!0})}catch(u){Bh.error("IPC handler failed",{key:o,err:String(u)}),Ji(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Ji(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function hv(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>fv)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 OS=Gt(Ox(),1),LS=Gt(jo(),1),NS=Gt(jr(),1),MS=Gt(Bd(),1),BS=Gt(Ud(),1),FS=Gt(Kd(),1),Hx=Gt(Vo(),1),zS=Gt(qx(),1);var Gx=Hx.default;Ke();ne();var{FWS:t1}=ep(),Oe=H("upstream.frontier"),np="application/json",rp="none",n1=15e3;function r1(t){class e extends Gx{constructor(i){super(i,e0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Oe.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(Ml("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let d=Buffer.from(c.slice(0,128)).toString("hex");Oe.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){Oe.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){Oe.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:t0,...An(this.opts.ppeOverride)},r=r1(e),i=r0(this.opts.urlOverride),o={url:i,ws:r,fpID:Qf,aID:xo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:np,force:!0},payloadEncoding:{encoding:rp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new t1(o),d=!1,u=null,h,x,g=new Promise((_,E)=>{h=_,x=E}),w=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?x(_):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Oe.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&w();for(let E of this.connectHandlers)Promise.resolve(E({initial:_})).catch(I=>Oe.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=_=>{this.opened=!1,Oe.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{Oe.warn("frontier error",{code:_.code,msg:_.message}),w(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let S=this.opts.openTimeoutMs??n1;u=setTimeout(()=>{w(new T("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(E){Oe.warn("fws close during start failure threw (ignored)",{err:String(E)})}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){Oe.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Oe.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?(Oe.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new T("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;ip(c)||Oe.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:np,payloadEncoding:rp})}catch(u){throw Oe.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new T("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=r(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let r=e.message?.service;if(r!==33555712){Oe.debug("drop non-adapter frontier frame",{service:r});return}let i=o1(e);if(!i){Oe.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Oe.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Oe.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;ip(c)||Oe.info("frontier frame in",{logid:s1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:i1(i)}),Promise.resolve(this.handler(o)).catch(d=>Oe.warn("frontier frame handler threw",{err:String(d)}))}};function ip(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var sp=2e3;function i1(t){return t.length<=sp?t:`${t.slice(0,sp)}...<truncated, total ${t.length} chars>`}function s1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function o1(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}}Ke();ne();var Jd=H("skill-publish"),a1="/api/marketplace/product/skill/publish_with_assets",c1=15e4;async function op(t,e={}){let i=`${Dr(Pr(e.handshakeBase))}${a1}`,o=e.timeoutMs??c1,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...An(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),o);Jd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${_.slice(0,200)}`)}let w=await x.json();if(Jd.info("skill publish response",{logid:g,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${g}`);let S={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(S.skillId=String(w.data.skill_id)),w.data?.version&&(S.version=w.data.version),Jd.info("skill publish ok",{logid:g,skillId:S.skillId??"",version:S.version??""}),S}catch(x){throw x instanceof T?x:x.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}ne();var Yd=H("upstream.switchable"),ra=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Yd.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 Yd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Yd.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 Xd=H("upstream"),Jr=class{handler=null;async start(){Xd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Xd.info("NoopUpstream stopped",{reason:e})}async send(e){Xd.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)}};Ke();ne();fn();ne();Re();import{promises as d1}from"node:fs";var ap=H("pat-token-store");async function ia(t=J()){try{let r=(await d1.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(ap.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"&&ap.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function os(t,e=J()){if(!t)throw new Error("writePatToken: empty patToken");await ln(e.patTokenFile,t,{mode:384})}Re();Re();import{promises as sa}from"node:fs";import{join as l1}from"node:path";function u1(t,e){return`#!/bin/sh
109
+ `}function kE(t){if(t.includes(`
110
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var TE={path:"",version:"cloud-deployed"},uh="openclaw_gateway_unavailable",CE="openclaw_default_agent_missing";function fh(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 RE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},DE=6e4,Bo=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??IE,this.createTimeoutMs=e.createTimeoutMs??DE,this.detectorFactory=e.detectorFactory??(()=>new Qn),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new No({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??Xt(hh(),".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=>{te.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=Xt(e,".env");if(await Ad(n).then(c=>c.isFile()).catch(()=>!1)){te.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=AE({...process.env,...Vi(this.paths.agentEnvFile)});await fn(n,o,{mode:384}),te.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),te.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){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 Pe(e.agentId,this.paths).catch(()=>null),o=wo(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")te.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>te.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")te.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>te.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){te.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await Pe(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Ge(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){te.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await Pe(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Ge(T,this.paths))}return te.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=Ue(e.agentId,this.paths),f=o?"cloud":"local",x=e.framework==="openclaw"&&f==="local",p;x&&!n?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??w??u.workspace,_=new AbortController,E=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&Id(e.framework)&&await pr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await Mo(u.root,{recursive:!0}),await Mo(S,{recursive:!0}),await Mo(u.logs,{recursive:!0}),T(),x||await gr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await ja(S,"cloud"):await ja(S,"local",kd)),T();let P=i,y=d0({model:e.model??P?.model}),R=Zf(e._meta)??P?.accountId,O=e.patToken??P?.patToken,F=f==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new Po({agentId:e.agentId,framework:e.framework,workspace:S,model:y.model??Nt,deployType:f,...R?{accountId:R}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",P?.sessions){let V=f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Q,ne]of Object.entries(P.sessions)){let ae={acpSessionId:ne.acpSessionId,modelToken:ne.modelToken,tokenGeneratedAt:ne.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?ne.permissionMode===void 0?(ae.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",te.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Q,framework:e.framework,fallback:ae.permissionMode})):Bt(e.framework,ne.permissionMode)?ae.permissionMode=ne.permissionMode:te.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Q,framework:e.framework,value:ne.permissionMode}):ne.permissionMode!==void 0&&te.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Q,framework:e.framework,deployType:f}),ne.cozeGroupId&&(ae.cozeGroupId=ne.cozeGroupId),ne.tokenGroupId&&(ae.tokenGroupId=ne.tokenGroupId),ne.requestScene&&(ae.requestScene=ne.requestScene),I.sessions.set(Q,ae)}let se=Object.keys(P.sessions).length;se>0&&te.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:se})}this.registry.register(I),A=!0;let M={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:y.model};if(f==="cloud"&&(M.deployType="cloud"),R&&(M.accountId=R),O&&(M.patToken=O),F&&(M.modelInfo=F),P?.skills&&(M.skills=P.skills),P?.agentName&&(M.agentName=P.agentName),P?.description&&(M.description=P.description),M.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&f==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):te.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await lh(S)&&te.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:S})}catch(V){te.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:S,err:String(V)})}}let Y=e.initialSkills??[];if(Y.length>0){let V=[...M.skills??[]],se=new Map(V.map((ae,D)=>[ae.skillId,D])),Q=await Promise.allSettled(Y.map(ae=>vo({agentId:e.agentId,workspace:S,framework:e.framework,skill:ae}))),ne=0;for(let[ae,D]of Q.entries()){let U=Y[ae];U&&(D.status==="fulfilled"?(So(V,se,D.value),ne++):te.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(D.reason)}))}ne>0&&(M.skills=V,te.info("initialSkills installed",{agentId:e.agentId,installed:ne,requested:Y.length}))}return await Ge(M,this.paths),te.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 te.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 wE(u.root,{recursive:!0,force:!0}).catch(P=>te.warn("rm agent dir failed (ignored)",{err:String(P)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,n,i,o,c,d){let f=this.config.frameworksCache?.[e.framework];if(!f)if(e.deployType==="cloud"&&Id(e.framework))f=TE;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Id(e.framework)&&!Ss(e.framework)&&(te.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await pr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,p;if(e.framework==="openclaw")p=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:c,requestScene:d,command:f.path});else{let w=e.sessions.get(i),S=Jt(e)?w?.permissionMode??xh:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await vE(e.agentId,this.paths),p=this.factory(e.framework,f.path,e.workspace,e.agentId,x,i,o,c,this.buildBinShimPathEnv(),S,e.framework==="codex"&&e.deployType==="cloud"?Xt(Ue(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await p.start(),await p.initialize(RE),p}catch(w){let S=p instanceof Mt?p.getStderrTail():[];throw S.length>0&&te.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof k?w.code:"unknown",recentStderr:S}),await p.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,f.path,w)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let o=await this.detectorFactory().probeOpenclawGateway(n);if(!o.reachable)return new k("AGENT_ENV_NOT_READY",fh(o),{cause:{reason:uh}})}catch(o){te.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};te.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 te.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 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:CE}})}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 n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new k("AGENT_ENV_NOT_READY",fh(n),{cause:{reason:uh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,requestScene:u,command:f}=e,x=vd(o);if(n.deployType==="local"){let S=await this.ensureOpenclawDefaultAgent();return new qr({command:f,cwd:S.workspace,agentId:S.id,sessionName:x})}let p=await dh();try{await this.getOpenclawConfig().ensureAcpDeviceScopes()}catch(S){te.warn("acp device scope ensure failed (ignored)",{err:String(S)})}let w;if(i?.modelToken){let S=sd(o),_=od(i),E=`${S}/${_}`;if(!this.ensuredProviders.has(E)){let I=this.getOpenclawConfig(),A=await I.getAllowlistModelsForProvider(S),T=p0(i,c,d,A,u);T&&(await I.ensureProvider(S,T),await I.addModelToAllowlist(E),this.ensuredProviders.add(E))}w=E}return new qr({command:f,cwd:n.workspace,agentId:n.agentId,sessionName:x,...p?{gatewayToken:p}:{},...w?{slashModelOnStart:w}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=n??e.model;for(let c of e.sessions.keys()){let d=sd(c),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(x){f=!1,te.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){f=!1,te.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as yh}from"node:crypto";import{promises as FE}from"node:fs";import{basename as bh}from"node:path";Ve();ie();import{promises as PE}from"node:fs";import{basename as OE}from"node:path";var gh=H("file-upload"),LE="/api/coze_claw/file/agent_upload",NE=6e4;async function mh(t,e={}){let i=`${Lr(Nr(e.handshakeBase))}${LE}`,o=e.timeoutMs??NE,c=await PE.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Tn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);gh.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let p=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),w=p.headers.get("x-tt-logid")??"";if(!p.ok){let E=await p.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${w}: ${E.slice(0,200)}`)}let S=await p.json();if(S.code!==void 0&&S.code!==0)throw new k("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${w}`);let _=S.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(S).slice(0,200)}`);return gh.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(p){throw p instanceof k?p:p.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${OE(t.path)}`):new k("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}Ve();ie();import{extname as ME}from"node:path";var BE={".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 wh(t){let e=ME(t).toLowerCase();return BE[e]??"application/octet-stream"}De();var Fo=H("agent-send"),_h=50*1024*1024;function Eh(t,e,n){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(n);if(!o)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function vh(t,e,n,i,o,c){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,n,i,o);return}catch(x){u=x,f<2&&(Fo.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function Sh(t,e){let{session:n,runtime:i}=Eh(e.core,t.agentId,t.sessionId);if(!await li(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await FE.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>_h)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${_h}`);let c=await wh(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??bh(t.path),u;try{u=await mh({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:o.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Fo.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:yh(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:d,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await vh(e,n,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Fo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Ih(t,e){let{session:n,runtime:i}=Eh(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??bh(t.path),c={sessionUpdate:"group_file",messageId:yh(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await vh(e,n,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Fo.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 Ah(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(n.length,i.length);for(let c=0;c<o;c++){let d=n[c]??0,u=i[c]??0;if(d<u)return!0;if(d>u)return!1}return!1}ln();Yt();ie();var Ft=H("coze-cli-installer"),kh="@coze/cli@latest",zE="coze",Th="0.1.8",UE=5e3,GE=5e3,HE=9e4,Ch=1e4,Ji=null,zo=!1;async function Cd(t,e={}){if(zo)return;if(Ji)return Ji;let n=e.exec??t0;return Ji=(async()=>{try{let i=await qE(zE,n),o=!1;if(i){let d=await jE(n);if(d===void 0)Ft.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Ah(d,Th))Ft.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:Th}),o=!0;else{Ft.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),zo=!0;return}}let c=o?"upgrade-only":"full";Ft.info("coze-cli install start",{package:kh,mode:c});try{await n("npm",["i","-g","--prefer-online",kh],{timeout:HE,maxBuffer:10*1024*1024}),Ft.info("coze-cli install ok")}catch(d){Ft.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){zo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:Ch}),Ft.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Ft.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:Ch}),Ft.info("coze auth login ok")}catch(d){Ft.warn("coze auth login failed",{err:String(d)});return}zo=!0}finally{Ji=null}})(),Ji}async function qE(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:UE});return Ha(i)}catch{return}}async function jE(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:GE});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}xn();De();var WE=10*6e4;function Rh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?WE:e}function Uo(t){return un(t??J().configFile)}function Xi(t,e){return hn(e??J().configFile,t)}import{randomBytes as uv}from"node:crypto";ur();Ve();ie();import{createReadStream as KE}from"node:fs";import{mkdir as $E,readFile as VE,realpath as ZE,stat as YE,writeFile as JE}from"node:fs/promises";import{basename as XE,dirname as Rd,isAbsolute as QE,join as ev,relative as tv,resolve as Dh,sep as nv}from"node:path";import{createInterface as rv}from"node:readline";var Oh=H("fs-rpc"),Qi=Je("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Lh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>Qi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${Qi} bytes`);let i=await Mh(t.path,e);return await $E(Rd(i),{recursive:!0}),await JE(i,t.content,"utf8"),Oh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Nh(t,e){let n=await Mh(t.path,e),i=await YE(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Qi&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Qi} bytes`);let c;if(o&&i.size>Qi)c=await iv(n,t.line??1,t.limit);else{let d=await VE(n,"utf8");if(o){let u=d.split(`
111
+ `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;c=u.slice(f,x).join(`
112
+ `)}else c=d}return Oh.info("fs/read_text_file ok",{path:n,size:c.length}),{content:c}}async function iv(t,e,n){let i=rv({input:KE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof n=="number"?o+n:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let f of i)if(u>=o&&u<c&&d.push(f),u++,u>=c)break}finally{i.close()}return d.join(`
113
+ `)}async function Mh(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([Ph(Dh(e)),Ph(Dh(t))]),o=tv(n,i);if(sv(o,nv,QE(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function sv(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Ph(t){let e=[],n=t;for(;n!==Rd(n);)try{let i=await ZE(n);return e.length?ev(i,...e.reverse()):i}catch{e.push(XE(n)),n=Rd(n)}return t}ie();var Bh=H("prompt-multimodal"),Fh=10*1024*1024,ov=15e3,av=6;async function zh(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let c=n++,d=t[c];d!==void 0&&(e[c]=await cv(d))}}let o=Array.from({length:Math.min(av,t.length)},()=>i());return await Promise.all(o),e}function Uh(t){return t.some(e=>e.type==="image")}async function cv(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Ui(e.uri))return t;try{let{buf:n,contentType:i}=await lv(e.uri),o=e.mimeType||dv(i)||"application/octet-stream";return Bh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:o}),{type:"image",data:n.toString("base64"),mimeType:o}}catch(n){return Bh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function dv(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function lv(t){let e=new AbortController,n=setTimeout(()=>e.abort(),ov);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=await i.arrayBuffer();if(o.byteLength>Fh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Fh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}pn();Ve();ie();var W=H("core"),fv=3e4,hv=/^(boe|ppe)_[A-Za-z0-9_-]+$/,xv="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",pv="\u5BA1\u6279\u5DF2\u8D85\u65F6",gv=3e4,Go=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new zr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=Rh(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}getRequestSceneForSession(e){return this.requestSceneBySession.get(e)}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(n=>n.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of n)await this.agents.get(i)?.killAllRuntimes("reload");return n}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,d)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:c,signal:d}),jr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"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[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(Rn(o,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>W.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:X.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code: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(Ao(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&&hv.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,c=Yf(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);c&&u!==c?(this.requestSceneBySession.set(d,c),W.info("cached request_scene for session",{sessionId:d,requestScene:c})):!c&&u!==void 0&&(this.requestSceneBySession.delete(d),W.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){n!==null?await this.sendError(n,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let f=await u(e,this);n!==null&&await this.upstream.send(Fr(n,f));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Fr(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Fr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(u){W.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Rn(n,$i(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._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 n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,n);if(e.method==="session/prompt"){let f=o.sessions.get(c);if(f?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,p=_o(n._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,xv,x,p)}}let d=Date.now(),u=!1;try{let f=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return u=!0,f}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=Xf(i);switch(n){case"session/new":{let c=mv();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,d=c.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Jt(e)?Jf(i._meta):void 0;if(u!==void 0&&!Bt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${_d(e.framework)}`);let f=_o(i._meta),x=this.requestSceneBySession.get(d),p=await this.ensureRuntime(e,d,f,x);if(u!==void 0&&p.permissionMode===void 0&&(p.permissionMode=u,await this.persistSessionMapping(e)),p.replySeq=0,await this.ensureDownstream(e,d,p),!p.downstream||!p.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&p.permissionMode!==void 0&&p.permissionMode!==u){let _=p.permissionMode;p.permissionMode=u,await this.persistSessionMapping(e);try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(E){throw p.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),E}}let w=i._meta?.cozeTriggerMsgId;if(w?e.activeTriggers.set(p.acpSessionId,w):e.activeTriggers.delete(p.acpSessionId),f?e.activeGroupIds.set(p.acpSessionId,f):e.activeGroupIds.delete(p.acpSessionId),f&&p.cozeGroupId!==f&&(p.cozeGroupId=f,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Uh(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let S=await zh(c.prompt);try{let _=await p.downstream.sessionPrompt({...c,sessionId:p.acpSessionId,prompt:S});return p.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof k&&_.code==="AGENT_APPROVAL_TIMEOUT"){let E=p.pendingPermission;E&&(E.downstream.respondAgentRequest(E.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(E.upstreamId),p.pendingPermission=void 0);let I=p.acpSessionId,A=I?e.activeTriggers.get(I):void 0,T=I?e.activeGroupIds.get(I):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,p,d,pv,A,T)}throw _}finally{if(e.activeTriggers.delete(p.acpSessionId),e.activeGroupIds.delete(p.acpSessionId),p.pendingPermission=void 0,p.reloadAfterTurn){p.reloadAfterTurn=!1;let _=p.downstream;_&&(p.downstream=void 0,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:p.acpSessionId}),_.stop("reload-after-turn").catch(E=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(E)})))}else p.downstream?.isAlive()&&this.armIdleTimer(e,d,p)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let f=e.getSessionQueue(d);f.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:f.size}),f.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,d=c.sessionId,u=c.modeId,f=_o(i._meta);if(!d)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(!Bt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${_d(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let p=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(w){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),w}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of o){let u=d.runtime.downstream,f=d.runtime.acpSessionId;u?.isAlive()&&f&&c.push({downstream:u,acpSessionId:f,oldMode:d.oldMode,runtime:d.runtime})}for(let d of c)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let f of o)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n,i,o){let c=e.sessions.get(n);if(c){let f=e.deployType==="cloud"&&c.tokenGroupId!==i,x=c.requestScene!==o;if(f&&(c.modelToken=await this.requestSessionToken(e.agentId,n,i),c.tokenGeneratedAt=Date.now(),c.tokenGroupId=i),f||x){jr(c);let p=c.downstream;c.downstream=void 0,p&&await p.stop("request-context-changed")}return c.cozeGroupId=i,c.requestScene=o,(f||x)&&await this.persistSessionMapping(e),c}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...o?{requestScene:o}:{}};return Jt(e)&&(u.permissionMode=e.framework==="claude-code"?kd:ph),e.sessions.set(n,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,n,i){let o={sessionId:n,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let c=await this.sendRequest(xt.GEN_MODEL_TOKEN,o,gv);if(!c?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return c.modelToken}catch(c){throw c instanceof k&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new k("MODEL_TOKEN_GEN_FAILED",c instanceof Error?c.message:String(c),{cause:c})}}async ensureDownstream(e,n,i){if(jr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let f;try{let x=this.requestSceneBySession.get(n);x&&W.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),f=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId: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}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId: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),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:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(jr(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let 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:n,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Br("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,n,i,o,c,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return c&&(u.cozeTriggerMsgId=c),d&&(u.cozeGroupId=d),await this.upstream.send(Br("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,n){let i=n.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(yv(n)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Jt(e)){let p=d.currentModeId;Bt(e.framework,p)&&c.permissionMode!==p?(c.permissionMode=p,this.persistSessionMapping(e).catch(w=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof p=="string"&&!Bt(e.framework,p)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:p})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Br("session/update",{...n,sessionId:o,_meta:u})).catch(p=>W.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:X.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await Lh(c,o);n.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await Nh(c,o);n.respondAgentRequest(i.id,d)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,$i(o))}}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 o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let p=u?e.activeGroupIds.get(u):void 0;p&&(x.cozeGroupId=p);let w=u?this.reverseSessionId(e,u):void 0,S=w?e.sessions.get(w):void 0;S&&(S.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...c,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:w}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:w,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(Wi(o,"session/request_permission",_)).catch(E=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),n.respondAgentRequestError(i.id,{code:X.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let o=n.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"&&wv(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 Io(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let o=e.get(n);if(o)return{value:o,key:n};if(typeof n=="number"){let c=String(n),d=e.get(c);if(d)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:c}),{value:d,key:c}}}sendRequest(e,n,i=fv){let o=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(Wi(o,e,n)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(f)})})}async persistSessionMapping(e){if(this.paths)try{let n=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),o.tokenGroupId&&(c.tokenGroupId=o.tokenGroupId),o.requestScene&&(c.requestScene=o.requestScene),n.set(i,c)}await ui(e.agentId,n,this.paths)}catch(n){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Rn(e,{code:n,message:i,data:{bridgeVersion:Lt}}))}};function mv(){return uv(16).toString("hex")}function wv(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=n.outcome;if(!i||typeof i!="object"){W.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var _v=["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 yv(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:o}=i;return _v.some(c=>o.startsWith(c))}xn();ie();De();import{randomBytes as bv}from"node:crypto";import{createServer as Ev}from"node:http";var vv=1e6,Gh=H("ipc"),Ho=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??J()}async start(){this.token=bv(32).toString("hex");let e=Ev((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 n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),Gh.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(o=>o?i(o):n())}),this.server=null)}async persistAuthFiles(){await fn(this.paths.portFile,String(this.port)),await fn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){es(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){es(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await Sv(e)}catch(u){es(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);es(n,200,u??{ok:!0})}catch(u){Gh.error("IPC handler failed",{key:o,err:String(u)}),es(n,500,{error:u instanceof Error?u.message:String(u)})}}};function es(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function Sv(t){let e=[],n=0;for await(let o of t){let c=o;if(n+=c.length,n>vv)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 jS=qt(Bx(),1),WS=qt(Jo(),1),KS=qt($r(),1),$S=qt(Gd(),1),VS=qt(jd(),1),ZS=qt(Yd(),1),Kx=qt(ta(),1),YS=qt(Wx(),1);var $x=Kx.default;Ve();ie();var{FWS:f1}=ip(),Le=H("upstream.frontier"),op="application/json",ap="none",h1=15e3;function x1(t){class e extends $x{constructor(i){super(i,r0,{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(zl("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let d=Buffer.from(c.slice(0,128)).toString("hex");Le.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){Le.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var ds=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:i0,...Tn(this.opts.ppeOverride)},n=x1(e),i=o0(this.opts.urlOverride),o={url:i,ws:n,fpID:n0,aID:yo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:op,force:!0},payloadEncoding:{encoding:ap,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new f1(o),d=!1,u=null,f,x,p=new Promise((_,E)=>{f=_,x=E}),w=_=>{d||(d=!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}),_&&w();for(let E of this.connectHandlers)Promise.resolve(E({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}),w(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??h1;u=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await p}catch(_){try{c.close(1e3,"open failed")}catch(E){Le.warn("fws close during start failure threw (ignored)",{err:String(E)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Le.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Le.warn("frontier send refused: upstream not started",{method:i}),new 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:n.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=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;cp(c)||Le.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:op,payloadEncoding:ap})}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 n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=n(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Le.debug("drop non-adapter frontier frame",{service:n});return}let i=m1(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(d){Le.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;cp(c)||Le.info("frontier frame in",{logid:g1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:p1(i)}),Promise.resolve(this.handler(o)).catch(d=>Le.warn("frontier frame handler threw",{err:String(d)}))}};function cp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var dp=2e3;function p1(t){return t.length<=dp?t:`${t.slice(0,dp)}...<truncated, total ${t.length} chars>`}function g1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function m1(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}}Ve();ie();var el=H("skill-publish"),w1="/api/marketplace/product/skill/publish_with_assets",_1=15e4;async function lp(t,e={}){let i=`${Lr(Nr(e.handshakeBase))}${w1}`,o=e.timeoutMs??_1,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Tn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);el.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${_.slice(0,200)}`)}let w=await x.json();if(el.info("skill publish response",{logid:p,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${p}`);let S={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(S.skillId=String(w.data.skill_id)),w.data?.version&&(S.version=w.data.version),el.info("skill publish ok",{logid:p,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)}}ie();var tl=H("upstream.switchable"),la=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;tl.info("swap upstream",{reason:n});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 tl.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>tl.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()}};ie();var nl=H("upstream"),Qr=class{handler=null;async start(){nl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){nl.info("NoopUpstream stopped",{reason:e})}async send(e){nl.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)}};Ve();ie();xn();ie();De();import{promises as y1}from"node:fs";var up=H("pat-token-store");async function ua(t=J()){try{let n=(await y1.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(up.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"&&up.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ls(t,e=J()){if(!t)throw new Error("writePatToken: empty patToken");await fn(e.patTokenFile,t,{mode:384})}De();De();import{promises as fa}from"node:fs";import{join as b1}from"node:path";function E1(t,e){return`#!/bin/sh
113
114
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
114
- `}function f1(t,e){return`@echo off\r
115
+ `}function v1(t,e){return`@echo off\r
115
116
  "${e}" "${t}" %*\r
116
- `}async function cp(t,e=J()){let r=e.binDir;await sa.mkdir(r,{recursive:!0});let i=l1(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?f1(t,o):u1(t,o);return await sa.readFile(i,"utf8").catch(()=>null)===c||(await sa.writeFile(i,c,"utf8"),process.platform!=="win32"&&await sa.chmod(i,493)),r}ne();Re();import{execSync as dp}from"node:child_process";import{readFileSync as lp,unlinkSync as h1}from"node:fs";import{mkdir as x1,open as p1,readFile as up,unlink as Qd,writeFile as g1}from"node:fs/promises";import{dirname as m1}from"node:path";var w1=H("single-instance"),_1=t=>new Promise(e=>setTimeout(e,t)),oa=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??J().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Wi(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&&w1.warn("removing stale pid file",{stalePid:i}),await g1(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 up(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Qd(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let r=await up(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 x1(m1(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await p1(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let d=await this.readPidFrom(r);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await _1(this.claimLockIntervalMs);continue}await Qd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Qd(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=lp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Br)||r.includes("lib/index.js"))}catch{}try{let r=dp(`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=dp(`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{lp(this.pidFile,"utf8").trim()===String(this.selfPid)&&h1(this.pidFile)}catch{}})}};aa();ne();var rr=H("daemon.upstream-watchdog"),k1=12e4,T1=9e5,C1=3e4;function tl(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ca=class{constructor(e){this.opts=e;this.softMs=e.softMs??tl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",k1),this.hardMs=e.hardMs??tl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",T1),this.intervalMs=e.intervalMs??tl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",C1),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 G=H("daemon");async function xp(){let t=J();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Ll({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:D=>$e(D,t).logs,listAgentIds:()=>_s(t)});try{let{writeFileSync:D}=await import("node:fs");D(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
117
+ `}async function fp(t,e=J()){let n=e.binDir;await fa.mkdir(n,{recursive:!0});let i=b1(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?v1(t,o):E1(t,o);return await fa.readFile(i,"utf8").catch(()=>null)===c||(await fa.writeFile(i,c,"utf8"),process.platform!=="win32"&&await fa.chmod(i,493)),n}ie();De();import{execSync as hp}from"node:child_process";import{readFileSync as xp,unlinkSync as S1}from"node:fs";import{mkdir as I1,open as A1,readFile as pp,unlink as rl,writeFile as k1}from"node:fs/promises";import{dirname as T1}from"node:path";var C1=H("single-instance"),R1=t=>new Promise(e=>setTimeout(e,t)),ha=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??J().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Zi(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&&C1.warn("removing stale pid file",{stalePid:i}),await k1(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 pp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await rl(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 pp(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 I1(T1(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await A1(n,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let d=await this.readPidFrom(n);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await R1(this.claimLockIntervalMs);continue}await rl(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await rl(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=xp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Ur)||n.includes("lib/index.js"))}catch{}try{let n=hp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Ur)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=hp(`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{xp(this.pidFile,"utf8").trim()===String(this.selfPid)&&S1(this.pidFile)}catch{}})}};xa();ie();var or=H("daemon.upstream-watchdog"),F1=12e4,z1=9e5,U1=3e4;function sl(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var pa=class{constructor(e){this.opts=e;this.softMs=e.softMs??sl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",F1),this.hardMs=e.hardMs??sl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",z1),this.intervalMs=e.intervalMs??sl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",U1),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?.(),or.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&&or.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&&or.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,or.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){or.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,or.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>or.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var q=H("daemon");async function wp(){let t=J();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Bl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:D=>Ue(D,t).logs,listAgentIds:()=>Is(t)});try{let{writeFileSync:D}=await import("node:fs");D(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
117
118
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
118
119
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
119
- `)}catch{}}let e=new oa({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 Oo(),o=i??{};ps({pid:process.pid}),G.info(i?"loaded bridge config":"initialized bridge config");let c=new ra(new Jr),d=null,u=new Lo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(D,U,W,te,Ze,le)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(D,U,W,te,Ze,le)}}),h=new Ro({paths:t,config:o,registry:u});d=h;let x,g,w=null,S={},_,E=null,I=null,k=null,C=new Cn;function P(D,U){return C.enqueue(()=>R(D,U))}function b(){I||(I=new ca({isConnected:()=>c.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>k?P(k,{force:!0}):void 0,onFatal:D=>{if(process.env[as]==="1"){G.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:D});return}G.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:D}),process.exit(1)}})),I.start()}async function R(D,U){let W=D,te=W?.privatecode;if(!te)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let Ze=Fi(W.env),le=W.handshake_url,pe=W.frontier_url,St=hp(W.env,le,pe);if(k=W,!U?.force&&x===te&&g===St){let ye=await R1(t);return u.agents.size===0&&ye?(G.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),la(t,h).catch(Te=>G.warn("connect-noop auto-revive error (ignored)",{err:String(Te)}))):G.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let pt=!!x&&x!==te,rn=g!==void 0&&g!==St,qt=pt||rn,sn=await Zc({privatecode:te,...le?{endpoint:le}:{},ppeOverride:Ze});if(qt){G.warn("connect config switched, resetting agents",{pcChanged:pt,envChanged:rn,previousPc:x?da(x):"",nextPc:da(te)});for(let ye of[...u.agents.values()])await ye.dispose("connect config switch").catch(()=>{}),u.agents.delete(ye.agentId);u.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Jr,"connect switch").catch(()=>{})}w=sn.deviceId,ps({deviceId:w,pid:process.pid}),Id({patToken:te,env:W.env}).catch(ye=>G.warn("coze-cli setup error (ignored)",{err:String(ye)}));let ti=new ss({handshake:sn,privatecode:te,...pe?{urlOverride:pe}:{},ppeOverride:Ze,getPatTokenForAgent:ye=>u.agents.get(ye)?.patToken});return await c.swap(ti,"connect"),x=te,g=St,S=Ze,_=le,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),G.info("mock scenario set",{scenario:W.mock_scenario})),E||(E=new Ui({core:u,getDeviceId:()=>w??"",onTickEnd:()=>M.retryPending().catch(ye=>G.warn("detailSync.retryPending failed (ignored)",{err:String(ye)})),onAuthFailures:Z})),E.start(),b(),qt&&la(t,h).catch(ye=>G.warn("post-connect-switch auto-revive error (ignored)",{err:String(ye)})),os(te,t).catch(ye=>G.warn("writePatToken after /connect failed (ignored)",{err:String(ye)})),G.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async D=>h.createAgent(D.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},B=new go({agents:u.agents,publishSkillToMarketplace:async D=>{let U=u.agents.get(D.agentId)?.patToken??x;if(!U)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return op({patToken:U,zip:D.zip,...D.skillId?{skillId:D.skillId}:{},skillName:D.skillName,...D.description?{description:D.description}:{},agentId:D.agentId,...D.accountId?{accountId:D.accountId}:{}},{handshakeBase:_,ppeOverride:S})},disposeAndMarkDisconnected:async(D,U)=>{let W=u.agents.get(D);if(W){await h.cleanupOpenclawSessionProviders(W).catch(Ze=>G.warn("cleanup openclaw providers failed (ignored)",{agentId:D,err:String(Ze)}));let te=!0;try{await W.dispose(`disconnect: ${U}`)}catch(Ze){te=!1,G.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:D,err:String(Ze)}),W.status="error"}te&&(W.status="disconnected",u.unregister(D),u.disconnectedAgents.add(D))}else u.disconnectedAgents.add(D)},disposeForDelete:async(D,U)=>{let W=u.agents.get(D);W&&(await h.cleanupOpenclawSessionProviders(W).catch(te=>G.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:D,err:String(te)})),await W.dispose(`delete: ${U}`).catch(te=>G.warn("dispose during delete failed (ignored)",{agentId:D,err:String(te)})),u.unregister(D)),u.disconnectedAgents.delete(D)},detailSyncer:async D=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(D)},cleanupOpenclawProviders:async(D,U)=>{await h.cleanupOpenclawSessionProviders(D,U)},openclawRepair:async(D,U)=>{await h.openclawRepair(D,U)},isRuntimePendingPermission:D=>u.hasPendingPermissionFor(D)});u.registerExtension("_agent/listSkills",D=>B.listSkills(D.params)),u.registerExtension("_agent/addSkills",D=>B.addSkills(D.params)),u.registerExtension("_agent/removeSkills",D=>B.removeSkills(D.params)),u.registerExtension("_agent/publishSkill",D=>B.publishSkill(D.params)),u.registerExtension("_agent/getFileTree",D=>B.getFileTree(D.params)),u.registerExtension("_agent/getFileContent",D=>B.getFileContent(D.params)),u.registerExtension("_agent/update",D=>B.updateAgent(D.params)),u.registerExtension("_agent/disconnect",D=>B.disconnectAgent(D.params)),u.registerExtension("_agent/switchModel",D=>B.switchModel(D.params)),u.registerExtension("_agent/reset",D=>B.resetAgent(D.params)),u.registerExtension("_agent/repair",D=>B.repairAgent(D.params)),u.registerExtension("_agent/delete",D=>B.deleteAgent(D.params)),u.registerExtension("_agent/upgrade",D=>B.upgradeBridge(D.params));let M=new Es({paths:t,handlers:B,agentManager:h,sendDetail:D=>u.sendRequest("_agent/detail",D)});O.ref=M;let Z=async D=>{await Promise.allSettled(D.map(async U=>{try{await B.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),G.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(W){G.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(W)})}}))};c.onConnect(({initial:D})=>{G.info("frontier upstream connected, triggering detail sync",{initial:D}),M.syncAll(D?"initial-connect":"reconnect").catch(U=>G.warn("detail sync top-level error (ignored)",{err:String(U)}))});let V=new No({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let D=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[as]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...D?{mockScenario:D}:{}}}},{method:"POST",path:"/pair",handler:async D=>{let U=D,W=U?.privatecode,te=U?.pairing_code;if(!W||!te)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ze=Fi(U.env),le=U.handshake_url,pe=U.frontier_url,St=hp(U.env,le,pe),pt=!!x&&x!==W,rn=g!==void 0&&g!==St,qt=pt||rn,sn=await Zc({privatecode:W,...le?{endpoint:le}:{},ppeOverride:Ze});if(qt){G.warn("pair config switched, resetting agents",{pcChanged:pt,envChanged:rn,previousPc:x?da(x):"",nextPc:da(W),previousEnvKey:g??"",nextEnvKey:St});for(let Te of[...u.agents.values()])await Te.dispose("pair config switch").catch(()=>{}),u.agents.delete(Te.agentId);u.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Jr,"pair switch").catch(()=>{})}w=sn.deviceId,ps({deviceId:w,pid:process.pid}),Id({patToken:W,env:U.env}).catch(Te=>G.warn("coze-cli setup error (ignored)",{err:String(Te)}));let ti=new ss({handshake:sn,privatecode:W,...pe?{urlOverride:pe}:{},ppeOverride:Ze,getPatTokenForAgent:Te=>u.agents.get(Te)?.patToken});await c.swap(ti,"pair");try{let Te=new Jn;o.frameworksCache=await Te.detectAll(),await Vi(o),G.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Te){G.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Te)})}let ye=Object.keys(o.frameworksCache??{});try{let Te=await u.sendRequest("_agent/pair",{pairCode:te,patToken:W,frameworks:ye,_meta:{cozeDeviceId:w}});G.info("_agent/pair ok",{pairResult:Te}),x=W,g=St,S=Ze,_=le,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),G.info("mock scenario set",{scenario:U.mock_scenario})),os(W,t).catch(Ne=>G.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),E||(E=new Ui({core:u,getDeviceId:()=>w??"",onTickEnd:()=>M.retryPending().catch(Ne=>G.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:Z})),E.start(),b(),qt&&la(t,h).catch(Ne=>G.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let ir;return U.agent_id&&(ir=await P1(U.agent_id,t,h,Ne=>u.sendRequest("_agent/detail",Ne),W).catch(Ne=>(G.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 G.error("_agent/pair failed",{err:String(Te)}),{ok:!1,note:`pair failed: ${String(Te)}`}}}},{method:"POST",path:"/connect",handler:D=>P(D)},{method:"POST",path:"/_agent/create",handler:async D=>{let U=D;return{ok:!0,result:await h.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async D=>{let U=D;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new T("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let W=U;return await(W.groupFile?bh:yh)(W,{core:u,patToken:x,handshakeBase:_,ppeOverride:S})}catch(W){if(W instanceof T)return{ok:!1,code:W.code,message:W.message};throw W}}},{method:"POST",path:"/reload",handler:async D=>{let U=D?.agent_id,W=await u.reloadAgents(U);return G.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>(G.info("IPC /shutdown received"),setImmediate(()=>{se.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:X}=await V.start();try{await cp(t.libEntry,t)}catch(D){G.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(D)})}await u.start(),O1({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new Jn().detectAll(),await Vi(o),o.frameworksCache)}).catch(D=>G.warn("startup warmup error (ignored)",{err:String(D)})),jl().then(async()=>{let{probeAcpVersion:D}=await Promise.resolve().then(()=>(cn(),Hl));for(let U of["claude-code","codex"]){let W=await D(U);W&&G.info("acp wrapper version",{framework:U,version:W})}}).catch(D=>G.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(D)}));let ee=null,se={port:re,token:X,core:u,ipc:V,shutdown(D){return ee||(G.info("daemon shutdown",{reason:D}),ee=(async()=>{E?.stop(),I?.stop(),await u.stop(D),await V.stop(),await e.release()})(),ee)}};for(let D of["SIGTERM","SIGINT"])process.on(D,()=>{se.shutdown(D).then(()=>process.exit(0))});return process.on("exit",()=>z0()),process.on("unhandledRejection",D=>{G.error("unhandledRejection",{reason:D instanceof Error?D.message:String(D),stack:D instanceof Error?D.stack:void 0})}),process.on("uncaughtException",D=>{G.error("uncaughtException (will exit, supervisor will restart)",{message:D.message,stack:D.stack,name:D.name});try{process.stderr.write(`FATAL uncaughtException: ${D.stack??D.message}
120
- `)}catch{}process.exit(1)}),G.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),N1({cliSpawned:process.env[as]==="1",readPatToken:()=>ia(t),connect:P}).catch(D=>G.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(D)})),se}async function R1(t){return _s(t).length>0}function da(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function hp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function D1(t,e){let r=_s(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(hn(),bs));for(let c of r){await o(c,t).catch(d=>G.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),G.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),G.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){G.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function P1(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(hn(),bs)),d=await c(t,e);if(d){if(d.deletedAt)throw new T("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);G.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let g=pp(d),w={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...g?{_meta:g}:{}};return await r.createAgent(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}G.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new T("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let h={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(h);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function O1(t){let e=t.logger??G;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 D1(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await la(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await L1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function la(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(()=>(hn(),bs));G.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let h;try{h=await o(u,t)}catch(x){G.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){G.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){G.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{G.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=pp(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){G.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),d+=1}}return G.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function L1(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 k0(o,t)).status==="refreshed"&&(i+=1)}catch(c){G.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&G.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function N1(t){let e=t.logger??G;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 pp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}aa();Re();import{readFile as gp}from"node:fs/promises";var nn=class{paths;constructor(e){this.paths=e??J()}async probe(e=1e3){let r=await ua(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,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:B1(i)}}}async request(e){let r=await ua(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let i=r.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,d=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),h=await u.text();return{status:u.status,body:M1(h)}}finally{clearTimeout(d)}}};async function ua(t){try{let[e,r]=await Promise.all([gp(t.portFile,"utf8"),gp(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 M1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function B1(t){return t instanceof Error?t.message:String(t)}Jt();ne();cr();import{spawn as F1}from"node:child_process";import{userInfo as wp}from"node:os";var nl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",z1=new Set(["bash","zsh","sh","dash","ksh"]),mp=Je("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),U1=2e3;function q1(t,e=nl){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let d of o.split(`
121
- `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function H1(){let t=(process.env.SHELL??"").trim()||(wp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return z1.has(e)?t:null}function G1(t){return new Promise(e=>{let r=`printf '%s' '${nl}'; env; printf '%s' '${nl}'`,i;try{i=F1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??wp().homedir}})}catch{e(null);return}let o="",c=!1,d=g=>{try{i.pid&&process.kill(-i.pid,g)}catch{}},u=g=>{c||(c=!0,clearTimeout(h),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 h=setTimeout(()=>d("SIGTERM"),mp),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},mp+U1)})}async function rl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=H1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??G1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=q1(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],d=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||r.push(c)}return{value:i,rest:r}}cn();import{chmod as j1,copyFile as _p,mkdir as bp,readFile as ds,rename as yp,rm as ol,stat as Ep,writeFile as W1}from"node:fs/promises";import{homedir as a3}from"node:os";import{dirname as K1,join as Le,resolve as al,sep as cs}from"node:path";import{fileURLToPath as $1}from"node:url";Jt();ne();Re();function Yr(t,e,r,i){nt(t.bridgeLogsDir,e,"dist-install",r,i)}function vp(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function V1(){return{darwin:{arm64:Le("vendor","aarch64-apple-darwin","bin","codex"),x64:Le("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Le("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Le("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Le("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Le("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function Z1(t){let e=$1(t),r=K1(e),i=`${cs}src${cs}`;if(r.includes(i)||r.endsWith(`${cs}src${cs}cli`))return null;let o=al(r,"index.js"),c=al(r,"..","package.json");return{dist:o,pkgJson:c}}async function cl(t={}){let e=t.paths??J(),r=Z1(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,d;try{let E=JSON.parse(await ds(o,"utf8"));c=E.version??"unknown",d=E.dependencies??{}}catch(E){throw Yr(e,"error","cannot read source package.json",{err:String(E)}),new Error(`cannot read source package.json: ${String(E)}`,{cause:E})}let u=ms.map(E=>({name:E,spec:d[E]??"latest"})),h=u.map(({name:E,spec:I})=>`${E}@${I}`),x=await Oo(e.configFile)??{},g=x.libVersion,w=await ds(e.libEntry).then(()=>!0).catch(()=>!1),S=g===c,_=await Sp(e,u);if(S&&w&&_)return{kind:"already-current",libVersion:c};if(!S||!w){await bp(e.libDir,{recursive:!0}),await _p(i,e.libEntry),await _p(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=al(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
122
- `;await ds(E,"utf8").catch(()=>null)!==I&&await W1(E,I)}return _||(t.installWrappers?await t.installWrappers(e,h):await X1(e,h,u)),x.libVersion=c,await Vi(x,e.configFile),Yr(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:c}),S&&w?{kind:"already-current",libVersion:c}:g?{kind:"version-changed",fromVersion:g,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Sp(t,e){for(let r of e){let i=Le(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await ds(i,"utf8"))}catch(d){return Yr(t,"debug","wrapper not ready: package.json read failed",{package:r.name,expected:r.spec,pkgJson:i,err:String(d)}),!1}let c=o.version;if(!c)return Yr(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!J1(c,r.spec))return Yr(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await Ip(Le(t.libDir,"node_modules"))}function J1(t,e){let r=il(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=il(i.slice(1));if(!c)return!0;if(sl(r,c)<0)return!1;let d=Y1(c);return sl(r,d)<0}let o=il(i);return o?sl(r,o)===0:!0}function Y1(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function il(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function sl(t,e){for(let r=0;r<3;r++){let i=(t[r]??0)-(e[r]??0);if(i!==0)return i}return 0}async function X1(t,e,r){await t2(t.installLock,async()=>{if(await Sp(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${cs}.staging-${process.pid}-${i}`,c=Le(o,"node_modules"),d=Le(t.libDir,"node_modules");try{await bp(o,{recursive:!0}),await Q1(e,o),await e2(c);let u=`${d}.trash-${i}`;await yp(d,u).catch(()=>{}),await yp(c,d),await ol(u,{recursive:!0,force:!0}).catch(()=>{}),Yr(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await ol(o,{recursive:!0,force:!0}).catch(()=>{})}})}function Q1(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=it("npm",r,{stdio:["ignore","pipe","pipe"]}),d="";c.stderr?.on("data",h=>{d.length<8192&&(d+=h.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",h=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(h)}`))}),c.once("close",h=>{clearTimeout(u),h===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${h}: ${d.trim().slice(0,2e3)}`))})})}async function e2(t){for(let e of ms){let r=Le(t,...e.split("/")),i=JSON.parse(await ds(Le(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=Le(t,".bin",o),d=await Ep(c);process.platform!=="win32"&&!(d.mode&73)&&await j1(c,d.mode|73).catch(()=>{})}if(!await Ip(t)){let e=vp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function Ip(t){let e=vp(),r=V1();if(!e||!r)return!0;let i=Le(t,"@openai","codex"),o=Le(t,...e.split("/")),c=[Le(i,"package.json"),Le(i,"bin","codex.js"),Le(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Le(o,"package.json"),Le(o,r)];return(await Promise.all(c.map(u=>Ep(u).then(h=>h.isFile()).catch(()=>!1)))).every(Boolean)}async function t2(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 ol(t,{force:!0}).catch(()=>{})}}Oa();ne();Re();import{closeSync as kp,fstatSync as Tp,openSync as Cp,readFileSync as n2,readSync as r2,readdirSync as i2,statSync as s2}from"node:fs";import{join as fa}from"node:path";var o2=new Set(["debug","info","warn","error"]);function Rp(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 d=Pn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),h=Number.isInteger(u)&&u>=0?u:200,x=c.value&&o2.has(c.value)?c.value:void 0,g={lines:h,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),d.value&&(g.grep=d.value),g}function a2(t,e){return t.agentId?fa($e(t.agentId,e).logs,dr("agent",t.date)):fa(e.bridgeLogsDir,dr("bridge",t.date))}function c2(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function d2(t,e){let r;try{r=i2(t)}catch{return[]}let i=[];for(let o of r){let c=Pa(o,e);if(!c)continue;let d=0;try{d=s2(fa(t,o)).size}catch{}i.push({file:fa(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Dp(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let r;try{r=JSON.parse(t).level}catch{return!0}if(typeof r=="string"&&!Bl(r,e.level))return!1}return!0}var Ap={debug:"90",info:"36",warn:"33",error:"31"},l2=new Set(["ts","level","module","msg"]);function u2(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Pp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=u2(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&Ap[o]&&(c=`\x1B[${Ap[o]}m${c}\x1B[0m`);let d=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",h=Object.entries(r).filter(([x])=>!l2.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${d} ${u}${h}`}function f2(t,e,r){let c=n2(t,"utf8").split(`
123
- `).filter(d=>d.length>0).filter(d=>Dp(d,{level:e.level,grep:e.grep}));for(let d of c2(c,e.lines))process.stdout.write(`${Pp(d,{raw:e.raw,color:r})}
124
- `)}async function Op(t,e){let r=e.paths??J(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?$e(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=d2(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
125
- `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
126
- `);return 0}let o=t.date??Ln(new Date),c=a2({agentId:t.agentId,date:o},r);try{f2(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
120
+ `)}catch{}}let e=new ha({processTitle:Ur}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Uo(),o=i??{};bs({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let c=new la(new Qr),d=null,u=new Go({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(D,U,j,re,Ye,ue)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(D,U,j,re,Ye,ue)}}),f=new Bo({paths:t,config:o,registry:u});d=f;let x,p,w=null,S={},_,E=null,I=null,A=null,T=new Dn;function P(D,U){return T.enqueue(()=>R(D,U))}function y(){I||(I=new pa({isConnected:()=>c.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:D=>{if(process.env[us]==="1"){q.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:D});return}q.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:D}),process.exit(1)}})),I.start()}async function R(D,U){let j=D,re=j?.privatecode;if(!re)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Ye=Hi(j.env),ue=j.handshake_url,we=j.frontier_url,At=mp(j.env,ue,we);if(A=j,!U?.force&&x===re&&p===At){let be=await G1(t);return u.agents.size===0&&be?(q.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ma(t,f).catch(Ce=>q.warn("connect-noop auto-revive error (ignored)",{err:String(Ce)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let mt=!!x&&x!==re,sn=p!==void 0&&p!==At,Ht=mt||sn,on=await ed({privatecode:re,...ue?{endpoint:ue}:{},ppeOverride:Ye});if(Ht){q.warn("connect config switched, resetting agents",{pcChanged:mt,envChanged:sn,previousPc:x?ga(x):"",nextPc:ga(re)});for(let be of[...u.agents.values()])await be.dispose("connect config switch").catch(()=>{}),u.agents.delete(be.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Qr,"connect switch").catch(()=>{})}w=on.deviceId,bs({deviceId:w,pid:process.pid}),Cd({patToken:re,env:j.env}).catch(be=>q.warn("coze-cli setup error (ignored)",{err:String(be)}));let ii=new ds({handshake:on,privatecode:re,...we?{urlOverride:we}:{},ppeOverride:Ye,getPatTokenForAgent:be=>u.agents.get(be)?.patToken});return await c.swap(ii,"connect"),x=re,p=At,S=Ye,_=ue,j.mock_scenario!==void 0&&(u.setMockScenario(j.mock_scenario),q.info("mock scenario set",{scenario:j.mock_scenario})),E||(E=new ji({core:u,getDeviceId:()=>w??"",onTickEnd:()=>M.retryPending().catch(be=>q.warn("detailSync.retryPending failed (ignored)",{err:String(be)})),onAuthFailures:Y})),E.start(),y(),Ht&&ma(t,f).catch(be=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(be)})),ls(re,t).catch(be=>q.warn("writePatToken after /connect failed (ignored)",{err:String(be)})),q.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async D=>f.createAgent(D.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},F=new Eo({agents:u.agents,publishSkillToMarketplace:async D=>{let U=u.agents.get(D.agentId)?.patToken??x;if(!U)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return lp({patToken:U,zip:D.zip,...D.skillId?{skillId:D.skillId}:{},skillName:D.skillName,...D.description?{description:D.description}:{},agentId:D.agentId,...D.accountId?{accountId:D.accountId}:{}},{handshakeBase:_,ppeOverride:S})},disposeAndMarkDisconnected:async(D,U)=>{let j=u.agents.get(D);if(j){await f.cleanupOpenclawSessionProviders(j).catch(Ye=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:D,err:String(Ye)}));let re=!0;try{await j.dispose(`disconnect: ${U}`)}catch(Ye){re=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:D,err:String(Ye)}),j.status="error"}re&&(j.status="disconnected",u.unregister(D),u.disconnectedAgents.add(D))}else u.disconnectedAgents.add(D)},disposeForDelete:async(D,U)=>{let j=u.agents.get(D);j&&(await f.cleanupOpenclawSessionProviders(j).catch(re=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:D,err:String(re)})),await j.dispose(`delete: ${U}`).catch(re=>q.warn("dispose during delete failed (ignored)",{agentId:D,err:String(re)})),u.unregister(D)),u.disconnectedAgents.delete(D)},detailSyncer:async D=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(D)},cleanupOpenclawProviders:async(D,U)=>{await f.cleanupOpenclawSessionProviders(D,U)},openclawRepair:async(D,U)=>{await f.openclawRepair(D,U)},isRuntimePendingPermission:D=>u.hasPendingPermissionFor(D)});u.registerExtension("_agent/listSkills",D=>F.listSkills(D.params)),u.registerExtension("_agent/addSkills",D=>F.addSkills(D.params)),u.registerExtension("_agent/removeSkills",D=>F.removeSkills(D.params)),u.registerExtension("_agent/publishSkill",D=>F.publishSkill(D.params)),u.registerExtension("_agent/getFileTree",D=>F.getFileTree(D.params)),u.registerExtension("_agent/getFileContent",D=>F.getFileContent(D.params)),u.registerExtension("_agent/update",D=>F.updateAgent(D.params)),u.registerExtension("_agent/disconnect",D=>F.disconnectAgent(D.params)),u.registerExtension("_agent/switchModel",D=>F.switchModel(D.params)),u.registerExtension("_agent/reset",D=>F.resetAgent(D.params)),u.registerExtension("_agent/repair",D=>F.repairAgent(D.params)),u.registerExtension("_agent/delete",D=>F.deleteAgent(D.params)),u.registerExtension("_agent/upgrade",D=>F.upgradeBridge(D.params));let M=new Ts({paths:t,handlers:F,agentManager:f,sendDetail:D=>u.sendRequest("_agent/detail",D)});O.ref=M;let Y=async D=>{await Promise.allSettled(D.map(async U=>{try{await F.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),q.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(j){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(j)})}}))};c.onConnect(({initial:D})=>{q.info("frontier upstream connected, triggering detail sync",{initial:D}),M.syncAll(D?"initial-connect":"reconnect").catch(U=>q.warn("detail sync top-level error (ignored)",{err:String(U)}))});let V=new Ho({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let D=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[us]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...D?{mockScenario:D}:{}}}},{method:"POST",path:"/pair",handler:async D=>{let U=D,j=U?.privatecode,re=U?.pairing_code;if(!j||!re)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ye=Hi(U.env),ue=U.handshake_url,we=U.frontier_url,At=mp(U.env,ue,we),mt=!!x&&x!==j,sn=p!==void 0&&p!==At,Ht=mt||sn,on=await ed({privatecode:j,...ue?{endpoint:ue}:{},ppeOverride:Ye});if(Ht){q.warn("pair config switched, resetting agents",{pcChanged:mt,envChanged:sn,previousPc:x?ga(x):"",nextPc:ga(j),previousEnvKey:p??"",nextEnvKey:At});for(let Ce of[...u.agents.values()])await Ce.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ce.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Qr,"pair switch").catch(()=>{})}w=on.deviceId,bs({deviceId:w,pid:process.pid}),Cd({patToken:j,env:U.env}).catch(Ce=>q.warn("coze-cli setup error (ignored)",{err:String(Ce)}));let ii=new ds({handshake:on,privatecode:j,...we?{urlOverride:we}:{},ppeOverride:Ye,getPatTokenForAgent:Ce=>u.agents.get(Ce)?.patToken});await c.swap(ii,"pair");try{let Ce=new Qn;o.frameworksCache=await Ce.detectAll(),await Xi(o),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ce){q.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ce)})}let be=Object.keys(o.frameworksCache??{});try{let Ce=await u.sendRequest("_agent/pair",{pairCode:re,patToken:j,frameworks:be,_meta:{cozeDeviceId:w}});q.info("_agent/pair ok",{pairResult:Ce}),x=j,p=At,S=Ye,_=ue,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),q.info("mock scenario set",{scenario:U.mock_scenario})),ls(j,t).catch(Me=>q.warn("writePatToken after /pair failed (ignored)",{err:String(Me)})),E||(E=new ji({core:u,getDeviceId:()=>w??"",onTickEnd:()=>M.retryPending().catch(Me=>q.warn("detailSync.retryPending failed (ignored)",{err:String(Me)})),onAuthFailures:Y})),E.start(),y(),Ht&&ma(t,f).catch(Me=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(Me)}));let ar;return U.agent_id&&(ar=await q1(U.agent_id,t,f,Me=>u.sendRequest("_agent/detail",Me),j).catch(Me=>(q.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Me)}),{ok:!1,agentId:U.agent_id??"",note:String(Me)}))),{ok:!0,note:"paired with cloud",...ar?{agent:ar}:{}}}catch(Ce){return q.error("_agent/pair failed",{err:String(Ce)}),{ok:!1,note:`pair failed: ${String(Ce)}`}}}},{method:"POST",path:"/connect",handler:D=>P(D)},{method:"POST",path:"/_agent/create",handler:async D=>{let U=D;return{ok:!0,result:await f.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async D=>{let U=D;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=U;return await(j.groupFile?Ih:Sh)(j,{core:u,patToken:x,handshakeBase:_,ppeOverride:S})}catch(j){if(j instanceof k)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async D=>{let U=D?.agent_id,j=await u.reloadAgents(U);return q.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:se,token:Q}=await V.start();try{await fp(t.libEntry,t)}catch(D){q.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(D)})}await u.start(),j1({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new Qn().detectAll(),await Xi(o),o.frameworksCache)}).catch(D=>q.warn("startup warmup error (ignored)",{err:String(D)})),$l().then(async()=>{let{probeAcpVersion:D}=await Promise.resolve().then(()=>(ln(),Wl));for(let U of["claude-code","codex"]){let j=await D(U);j&&q.info("acp wrapper version",{framework:U,version:j})}}).catch(D=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(D)}));let ne=null,ae={port:se,token:Q,core:u,ipc:V,shutdown(D){return ne||(q.info("daemon shutdown",{reason:D}),ne=(async()=>{E?.stop(),I?.stop(),await u.stop(D),await V.stop(),await e.release()})(),ne)}};for(let D of["SIGTERM","SIGINT"])process.on(D,()=>{ae.shutdown(D).then(()=>process.exit(0))});return process.on("exit",()=>H0()),process.on("unhandledRejection",D=>{q.error("unhandledRejection",{reason:D instanceof Error?D.message:String(D),stack:D instanceof Error?D.stack:void 0})}),process.on("uncaughtException",D=>{q.error("uncaughtException (will exit, supervisor will restart)",{message:D.message,stack:D.stack,name:D.name});try{process.stderr.write(`FATAL uncaughtException: ${D.stack??D.message}
121
+ `)}catch{}process.exit(1)}),q.info("daemon ready",{port:se,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),K1({cliSpawned:process.env[us]==="1",readPatToken:()=>ua(t),connect:P}).catch(D=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(D)})),ae}async function G1(t){return Is(t).length>0}function ga(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function mp(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function H1(t,e){let n=Is(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(pn(),ks));for(let c of n){await o(c,t).catch(d=>q.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),q.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),q.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){q.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function q1(t,e,n,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(pn(),ks)),d=await c(t,e);if(d){if(d.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let p=_p(d),w={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...p?{_meta:p}:{}};return await n.createAgent(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}q.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await 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 j1(t){let e=t.logger??q;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 H1(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await ma(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await W1(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function ma(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:o}=await Promise.resolve().then(()=>(pn(),ks));q.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let f;try{f=await o(u,t)}catch(x){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){q.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){q.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{q.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=_p(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),d+=1}}return q.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function W1(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 o of n)try{(await R0(o,t)).status==="refreshed"&&(i+=1)}catch(c){q.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&q.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function K1(t){let e=t.logger??q;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 _p(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}xa();De();import{readFile as yp}from"node:fs/promises";var rn=class{paths;constructor(e){this.paths=e??J()}async probe(e=1e3){let n=await wa(this.paths);if(!n)return{kind:"not-running"};try{let i=await this.fetch(n,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...n,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:V1(i)}}}async request(e){let n=await wa(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,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,d=setTimeout(()=>c.abort(),n.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:o,body:i?JSON.stringify(n.body):void 0,signal:c.signal}),f=await u.text();return{status:u.status,body:$1(f)}}finally{clearTimeout(d)}}};async function wa(t){try{let[e,n]=await Promise.all([yp(t.portFile,"utf8"),yp(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=n.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function $1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function V1(t){return t instanceof Error?t.message:String(t)}Yt();ie();ur();import{spawn as Z1}from"node:child_process";import{userInfo as Ep}from"node:os";var ol="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",Y1=new Set(["bash","zsh","sh","dash","ksh"]),bp=Je("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),J1=2e3;function X1(t,e=ol){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let o=t.slice(n+e.length,i),c={};for(let d of o.split(`
122
+ `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function Q1(){let t=(process.env.SHELL??"").trim()||(Ep().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return Y1.has(e)?t:null}function eI(t){return new Promise(e=>{let n=`printf '%s' '${ol}'; env; printf '%s' '${ol}'`,i;try{i=Z1(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Ep().homedir}})}catch{e(null);return}let o="",c=!1,d=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},u=p=>{c||(c=!0,clearTimeout(f),clearTimeout(x),e(p))};i.stdout?.on("data",p=>{o+=p.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>d("SIGTERM"),bp),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},bp+J1)})}async function al(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=Q1();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??eI)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=X1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}De();function Ln(t,...e){let n=[],i;for(let o=0;o<t.length;o++){let c=t[o],d=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||n.push(c)}return{value:i,rest:n}}ln();import{chmod as tI,copyFile as vp,mkdir as Ip,readFile as hs,rename as Sp,rm as ll,stat as Ap,writeFile as nI}from"node:fs/promises";import{homedir as _O}from"node:os";import{dirname as rI,join as Ne,resolve as ul,sep as fs}from"node:path";import{fileURLToPath as iI}from"node:url";Yt();ie();De();function ei(t,e,n,i){rt(t.bridgeLogsDir,e,"dist-install",n,i)}function kp(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function sI(){return{darwin:{arm64:Ne("vendor","aarch64-apple-darwin","bin","codex"),x64:Ne("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Ne("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Ne("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Ne("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Ne("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function oI(t){let e=iI(t),n=rI(e),i=`${fs}src${fs}`;if(n.includes(i)||n.endsWith(`${fs}src${fs}cli`))return null;let o=ul(n,"index.js"),c=ul(n,"..","package.json");return{dist:o,pkgJson:c}}async function fl(t={}){let e=t.paths??J(),n=oI(import.meta.url),i=t.sourceDist??n?.dist,o=t.sourcePackageJson??n?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,d;try{let E=JSON.parse(await hs(o,"utf8"));c=E.version??"unknown",d=E.dependencies??{}}catch(E){throw ei(e,"error","cannot read source package.json",{err:String(E)}),new Error(`cannot read source package.json: ${String(E)}`,{cause:E})}let u=vs.map(E=>({name:E,spec:d[E]??"latest"})),f=u.map(({name:E,spec:I})=>`${E}@${I}`),x=await Uo(e.configFile)??{},p=x.libVersion,w=await hs(e.libEntry).then(()=>!0).catch(()=>!1),S=p===c,_=await Tp(e,u);if(S&&w&&_)return{kind:"already-current",libVersion:c};if(!S||!w){await Ip(e.libDir,{recursive:!0}),await vp(i,e.libEntry),await vp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=ul(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
123
+ `;await hs(E,"utf8").catch(()=>null)!==I&&await nI(E,I)}return _||(t.installWrappers?await t.installWrappers(e,f):await dI(e,f,u)),x.libVersion=c,await Xi(x,e.configFile),ei(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:p,toVersion:c}),S&&w?{kind:"already-current",libVersion:c}:p?{kind:"version-changed",fromVersion:p,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Tp(t,e){for(let n of e){let i=Ne(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await hs(i,"utf8"))}catch(d){return ei(t,"debug","wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(d)}),!1}let c=o.version;if(!c)return ei(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!aI(c,n.spec))return ei(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:c,expected:n.spec}),!1}return!!await Cp(Ne(t.libDir,"node_modules"))}function aI(t,e){let n=cl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=cl(i.slice(1));if(!c)return!0;if(dl(n,c)<0)return!1;let d=cI(c);return dl(n,d)<0}let o=cl(i);return o?dl(n,o)===0:!0}function cI(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function cl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function dl(t,e){for(let n=0;n<3;n++){let i=(t[n]??0)-(e[n]??0);if(i!==0)return i}return 0}async function dI(t,e,n){await fI(t.installLock,async()=>{if(await Tp(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${fs}.staging-${process.pid}-${i}`,c=Ne(o,"node_modules"),d=Ne(t.libDir,"node_modules");try{await Ip(o,{recursive:!0}),await lI(e,o),await uI(c);let u=`${d}.trash-${i}`;await Sp(d,u).catch(()=>{}),await Sp(c,d),await ll(u,{recursive:!0,force:!0}).catch(()=>{}),ei(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await ll(o,{recursive:!0,force:!0}).catch(()=>{})}})}function lI(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=st("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";c.stderr?.on("data",f=>{d.length<8192&&(d+=f.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",f=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(f)}`))}),c.once("close",f=>{clearTimeout(u),f===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${d.trim().slice(0,2e3)}`))})})}async function uI(t){for(let e of vs){let n=Ne(t,...e.split("/")),i=JSON.parse(await hs(Ne(n,"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=Ne(t,".bin",o),d=await Ap(c);process.platform!=="win32"&&!(d.mode&73)&&await tI(c,d.mode|73).catch(()=>{})}if(!await Cp(t)){let e=kp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function Cp(t){let e=kp(),n=sI();if(!e||!n)return!0;let i=Ne(t,"@openai","codex"),o=Ne(t,...e.split("/")),c=[Ne(i,"package.json"),Ne(i,"bin","codex.js"),Ne(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Ne(o,"package.json"),Ne(o,n)];return(await Promise.all(c.map(u=>Ap(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function fI(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await ll(t,{force:!0}).catch(()=>{})}}Fa();ie();De();import{closeSync as Dp,fstatSync as Pp,openSync as Op,readFileSync as hI,readSync as xI,readdirSync as pI,statSync as gI}from"node:fs";import{join as _a}from"node:path";var mI=new Set(["debug","info","warn","error"]);function Lp(t){let e=t,n=Ln(e,"--agent-id");e=n.rest;let i=Ln(e,"--date");e=i.rest;let o=Ln(e,"-n","--lines");e=o.rest;let c=Ln(e,"--level");e=c.rest;let d=Ln(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,x=c.value&&mI.has(c.value)?c.value:void 0,p={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(p.agentId=n.value),i.value&&(p.date=i.value),x&&(p.level=x),d.value&&(p.grep=d.value),p}function wI(t,e){return t.agentId?_a(Ue(t.agentId,e).logs,fr("agent",t.date)):_a(e.bridgeLogsDir,fr("bridge",t.date))}function _I(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function yI(t,e){let n;try{n=pI(t)}catch{return[]}let i=[];for(let o of n){let c=Ba(o,e);if(!c)continue;let d=0;try{d=gI(_a(t,o)).size}catch{}i.push({file:_a(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Np(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"&&!Ul(n,e.level))return!1}return!0}var Rp={debug:"90",info:"36",warn:"33",error:"31"},bI=new Set(["ts","level","module","msg"]);function EI(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Mp(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=EI(n.ts),o=typeof n.level=="string"?n.level:"",c=o.toUpperCase().padEnd(5);e.color&&Rp[o]&&(c=`\x1B[${Rp[o]}m${c}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",f=Object.entries(n).filter(([x])=>!bI.has(x)).map(([x,p])=>` ${x}=${typeof p=="string"?p:JSON.stringify(p)}`).join("");return`${i} ${c} ${d} ${u}${f}`}function vI(t,e,n){let c=hI(t,"utf8").split(`
124
+ `).filter(d=>d.length>0).filter(d=>Np(d,{level:e.level,grep:e.grep}));for(let d of _I(c,e.lines))process.stdout.write(`${Mp(d,{raw:e.raw,color:n})}
125
+ `)}async function Bp(t,e){let n=e.paths??J(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Ue(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=yI(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
126
+ `),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
127
+ `);return 0}let o=t.date??Bn(new Date),c=wI({agentId:t.agentId,date:o},n);try{vI(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
127
128
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
128
- (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
129
- `),1}return t.follow&&await p2(c,t,i),0}var h2=500;function x2(t){try{let e=Cp(t,"r");try{return Tp(e).size}finally{kp(e)}}catch{return 0}}async function p2(t,e,r){let i=x2(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let h=Cp(t,"r");try{let x=Tp(h).size;if(x>i){let g=Buffer.allocUnsafe(x-i),w=r2(h,g,0,g.length,i);u=g.subarray(0,w).toString("utf8"),i+=w}}finally{kp(h)}}catch{}if(u){let h=(o+u).split(`
130
- `);o=h.pop()??"";for(let x of h)x.length>0&&Dp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Pp(x,{raw:e.raw,color:r})}
131
- `)}await new Promise(h=>setTimeout(h,h2))}}finally{process.off("SIGINT",d)}}import{basename as g2,resolve as m2}from"node:path";Re();var w2=9e4,_2={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 y2(t){return _2[t]??1}async function Lp(t,e={}){let r=e.paths??J();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>
129
+ (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
130
+ `),1}return t.follow&&await AI(c,t,i),0}var SI=500;function II(t){try{let e=Op(t,"r");try{return Pp(e).size}finally{Dp(e)}}catch{return 0}}async function AI(t,e,n){let i=II(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let f=Op(t,"r");try{let x=Pp(f).size;if(x>i){let p=Buffer.allocUnsafe(x-i),w=xI(f,p,0,p.length,i);u=p.subarray(0,w).toString("utf8"),i+=w}}finally{Dp(f)}}catch{}if(u){let f=(o+u).split(`
131
+ `);o=f.pop()??"";for(let x of f)x.length>0&&Np(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Mp(x,{raw:e.raw,color:n})}
132
+ `)}await new Promise(f=>setTimeout(f,SI))}}finally{process.off("SIGINT",d)}}import{basename as kI,resolve as TI}from"node:path";De();var CI=9e4,RI={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 DI(t){return RI[t]??1}async function Fp(t,e={}){let n=e.paths??J();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>
132
133
  `),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.
133
- `),3;let i=await ua(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.
134
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:m2(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 b2(i,"/agent/send",o,w2)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
134
+ `),3;let i=await wa(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.
135
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:TI(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 PI(i,"/agent/send",o,CI)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
135
136
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
136
- `),y2(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
137
- `);else{let d=t.name??g2(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
138
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${E2(c.bytes)})
139
- `)}return 0}async function b2(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await d.text(),h=u?JSON.parse(u):null;return h&&typeof h=="object"&&"ok"in h?h:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function E2(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var jp=H("cli");function je(t,e){let{value:r,rest:i}=Pn(t,e);return{value:r,rest:i}}function wa(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
140
- `)}function K2(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}=je(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 $2(e.slice(1));if(e[0]==="log")return{mode:"log",...Rp(e.slice(1))};if(e[0]==="connect")return V2(e.slice(1));if(e.includes("--status"))return wa("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return wa("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return wa("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return wa("--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}=je(r,"--pat-token");r=o;let{value:c,rest:d}=je(r,"--pair-code");r=d;let{value:u,rest:h}=je(r,"--env");r=h;let{value:x,rest:g}=je(r,"--handshake-url");r=g;let{value:w,rest:S}=je(r,"--frontier-url");r=S;let{value:_,rest:E}=je(r,"--mock-scenario");r=E;let{value:I}=je(r,"--agent-id"),k=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let C={mode:"pair",privatecode:i,pairingCode:c};return u&&(C.env=u),x&&(C.handshakeUrl=x),w&&(C.frontierUrl=w),_&&(C.mockScenario=_),I&&(C.agentId=I),k&&(C.skipRebuildEnv=!0),C}function $2(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}=je(i,"--caption");i=c;let{value:d,rest:u}=je(i,"--name");i=u;let{value:h,rest:x}=je(i,"--agent-id");i=x;let{value:g,rest:w}=je(i,"--session-id");i=w;let{value:S,rest:_}=je(i,"--mime");i=_;let E=i.includes("--group-file");i=i.filter(C=>C!=="--group-file");let I=i.includes("--json"),k={mode:"send",kind:e,path:r,json:I};return o&&(k.caption=o),d&&(k.name=d),h&&(k.agentId=h),g&&(k.sessionId=g),E&&(k.groupFile=!0),S&&(k.mimeType=S),k}function V2(t){let e=t,{value:r,rest:i}=je(e,"--pat-token");e=i;let{value:o,rest:c}=je(e,"--env");e=c;let{value:d,rest:u}=je(e,"--handshake-url");e=u;let{value:h,rest:x}=je(e,"--frontier-url");e=x;let{value:g,rest:w}=je(e,"--mock-scenario");e=w;let S=e.includes("--skip-rebuild-env"),_={mode:"connect"};return r&&(_.privatecode=r),o&&(_.env=o),d&&(_.handshakeUrl=d),h&&(_.frontierUrl=h),g&&(_.mockScenario=g),S&&(_.skipRebuildEnv=!0),_}var Z2=`
137
+ `),DI(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
138
+ `);else{let d=t.name??kI(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
139
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${OI(c.bytes)})
140
+ `)}return 0}async function PI(t,e,n,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:o.signal}),u=await d.text(),f=u?JSON.parse(u):null;return f&&typeof f=="object"&&"ok"in f?f:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function OI(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 $e(t,e){let{value:n,rest:i}=Ln(t,e);return{value:n,rest:i}}function Ia(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
141
+ `)}function r2(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}=$e(e.slice(1),"--agent-id");return P?{mode:"reload",agentId:P}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return i2(e.slice(1));if(e[0]==="log")return{mode:"log",...Lp(e.slice(1))};if(e[0]==="connect")return s2(e.slice(1));if(e.includes("--status"))return Ia("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ia("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ia("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ia("--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:o}=$e(n,"--pat-token");n=o;let{value:c,rest:d}=$e(n,"--pair-code");n=d;let{value:u,rest:f}=$e(n,"--env");n=f;let{value:x,rest:p}=$e(n,"--handshake-url");n=p;let{value:w,rest:S}=$e(n,"--frontier-url");n=S;let{value:_,rest:E}=$e(n,"--mock-scenario");n=E;let{value:I}=$e(n,"--agent-id"),A=n.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),w&&(T.frontierUrl=w),_&&(T.mockScenario=_),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function i2(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:o,rest:c}=$e(i,"--caption");i=c;let{value:d,rest:u}=$e(i,"--name");i=u;let{value:f,rest:x}=$e(i,"--agent-id");i=x;let{value:p,rest:w}=$e(i,"--session-id");i=w;let{value:S,rest:_}=$e(i,"--mime");i=_;let E=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return o&&(A.caption=o),d&&(A.name=d),f&&(A.agentId=f),p&&(A.sessionId=p),E&&(A.groupFile=!0),S&&(A.mimeType=S),A}function s2(t){let e=t,{value:n,rest:i}=$e(e,"--pat-token");e=i;let{value:o,rest:c}=$e(e,"--env");e=c;let{value:d,rest:u}=$e(e,"--handshake-url");e=u;let{value:f,rest:x}=$e(e,"--frontier-url");e=x;let{value:p,rest:w}=$e(e,"--mock-scenario");e=w;let S=e.includes("--skip-rebuild-env"),_={mode:"connect"};return n&&(_.privatecode=n),o&&(_.env=o),d&&(_.handshakeUrl=d),f&&(_.frontierUrl=f),p&&(_.mockScenario=p),S&&(_.skipRebuildEnv=!0),_}var o2=`
141
142
  coze-bridge - local bridge daemon for cloud Agent Service
142
143
 
143
144
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -218,57 +219,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
218
219
 
219
220
  Internal:
220
221
  <node> <entry> --daemon daemon mode (OS supervisor only)
221
- `.trimStart();async function Wp(t=process.argv,e={}){let r=K2(t);switch(r.mode){case"help":return process.stdout.write(Z2),0;case"version":return process.stdout.write(`${Ot}
222
- `),0;case"daemon":{try{await xp()}catch(i){return jp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return J2(e);case"stop":return $p(e);case"reload":return Q2(r.agentId,e);case"log":return Op(r,e);case"update":return Y2(e);case"purge":return tI(e);case"service-install":return nI(e);case"service-uninstall":return rI(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),iI(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),sI(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Lp({kind:r.kind,path:r.path,...r.agentId?{agentId:r.agentId}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.caption?{caption:r.caption}:{},...r.name?{name:r.name}:{},...r.groupFile?{groupFile:!0}:{},...r.mimeType?{mimeType:r.mimeType}:{},json:r.json},e)}}async function Kp(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 J2(t){let e=t.paths??J(),r=new nn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
223
- `),1;if(i.kind==="stale")return await Kp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
224
- `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
222
+ `.trimStart();async function Zp(t=process.argv,e={}){let n=r2(t);switch(n.mode){case"help":return process.stdout.write(o2),0;case"version":return process.stdout.write(`${Lt}
223
+ `),0;case"daemon":{try{await wp()}catch(i){return Vp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return a2(e);case"stop":return Jp(e);case"reload":return l2(n.agentId,e);case"log":return Bp(n,e);case"update":return c2(e);case"purge":return f2(e);case"service-install":return h2(e);case"service-uninstall":return x2(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),p2(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),g2(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return Fp({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 Yp(t){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(t.pidFile).catch(()=>{}),e(t.portFile).catch(()=>{}),e(t.tokenFile).catch(()=>{})])}async function a2(t){let e=t.paths??J(),n=new rn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
224
+ `),1;if(i.kind==="stale")return await Yp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
225
+ `),1;let o=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
225
226
  ${JSON.stringify(o.body,null,2)}
226
- `),0}async function $p(t){let e=t.paths??J(),r=new nn(e),i=t.daemonSweep??(async()=>{let h=U0();return await q0(h),h}),o=async()=>{t.skipProcessKill||await i(e)},c=await us(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
227
- `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
227
+ `),0}async function Jp(t){let e=t.paths??J(),n=new rn(e),i=t.daemonSweep??(async()=>{let f=q0();return await j0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await ps(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
228
+ `)}let u=await n.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
228
229
  `:`coze-bridge: not running
229
- `),0;if(u.kind==="stale")return await Kp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
230
- `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
231
- `),0}catch(h){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
232
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
233
- `),1)}}async function Y2(t){return await $p(t),(t.spawnNpx??X2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function X2(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)}
234
- `),e(1)})})}async function Q2(t,e){let r=new nn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
235
- `),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)
230
+ `),0;if(u.kind==="stale")return await Yp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
231
+ `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
232
+ `),0}catch(f){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
233
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
234
+ `),1)}}async function c2(t){return await Jp(t),(t.spawnNpx??d2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function d2(t){return new Promise(e=>{let n=st("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
235
+ `),e(1)})})}async function l2(t,e){let n=new rn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
236
+ `),1;try{let o=await n.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)
236
237
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
237
238
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
238
239
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
239
- `),1}}async function us(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(qp(),Up)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Vp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??oI,c=t.paths??J();if(r.kind==="connected"){if(!eI(r.body))return r;nt(c.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:r.body}),await e.request({method:"POST",path:"/shutdown"}).catch(h=>nt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await Gp(c.pidFile,o)}let d=t.spawnDaemon??fp,u=await us(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await Hp(e,i,o);if(h.kind==="connected")return h;nt(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(h){nt(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}nt(c.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await Gp(c.pidFile,o)}else u&&await u.install({activate:!1}).catch(h=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(h)}
240
+ `),1}}async function ps(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(Wp(),jp)),i=e(),o=n();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Xp(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??m2,c=t.paths??J();if(n.kind==="connected"){if(!u2(n.body))return n;rt(c.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:n.body}),await e.request({method:"POST",path:"/shutdown"}).catch(f=>rt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await $p(c.pidFile,o)}let d=t.spawnDaemon??gp,u=await ps(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await Kp(e,i,o);if(f.kind==="connected")return f;rt(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(f){rt(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}rt(c.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await $p(c.pidFile,o)}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)}
240
241
  `));return process.stdout.write(`coze-bridge: starting daemon...
241
- `),await d({paths:t.paths}),Hp(e,i,o)}function eI(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.nodeExecPath!="string"||typeof e.nodeArch!="string"?!1:e.nodeExecPath!==process.execPath||e.nodeArch!==process.arch}async function tI(t){let e=new nn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
242
+ `),await d({paths:t.paths}),Kp(e,i,o)}function u2(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.nodeExecPath!="string"||typeof e.nodeArch!="string"?!1:e.nodeExecPath!==process.execPath||e.nodeArch!==process.arch}async function f2(t){let e=new rn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
242
243
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
243
- `)}await new Promise(d=>setTimeout(d,500))}let i=await us(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
244
+ `)}await new Promise(d=>setTimeout(d,500))}let i=await ps(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
244
245
  `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
245
246
  `)}let o=t.paths??J(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
246
247
  `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
247
248
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
248
- `),0}async function nI(t){let e=await us(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
249
+ `),0}async function h2(t){let e=await ps(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
249
250
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
250
- `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
251
- `),1}}async function rI(t){let e=await us(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
252
- `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
253
- `),1}}async function Zp(t,e,r){if(e)return nt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(nt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(nt(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)
254
- `),nt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function iI(t,e,r,i={},o,c){let d=new nn(r.paths),u=r.paths??J(),h=await Zp(u,c,r.reconstructEnv??rl);if(await fd(u,h).catch(w=>nt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!r.skipDistInstall){let w=await cl({paths:r.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
251
+ `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
252
+ `),1}}async function x2(t){let e=await ps(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
253
+ `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
254
+ `),1}}async function Qp(t,e,n){if(e)return rt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(rt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(rt(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)
255
+ `),rt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function p2(t,e,n,i={},o,c){let d=new rn(n.paths),u=n.paths??J(),f=await Qp(u,c,n.reconstructEnv??al);if(await md(u,f).catch(w=>rt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!n.skipDistInstall){let w=await fl({paths:n.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
255
256
  `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
256
- `)}let x=await Vp(r,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
257
- `),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 w=await d.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let S=w.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
257
+ `)}let x=await Xp(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
258
+ `),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),o&&(p.agent_id=o);try{let w=await d.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let S=w.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
258
259
  `),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"
259
260
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
260
261
  `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
261
- `),1}}async function sI(t,e,r={},i){let o=e.paths??J(),c=t??await ia(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new nn(e.paths),u=await Zp(o,i,e.reconstructEnv??rl);if(await fd(o,u).catch(g=>nt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await cl({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
262
- `),(await d.probe()).kind==="connected"&&(await d.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}
263
- `)}let h=await Vp(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
264
- `),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 d.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"})
265
- `),t!==void 0&&await os(c,o).catch(w=>jp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
266
- `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
267
- `),1}}async function Hp(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 Gp(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Wi(u))return;await e(i)}}function oI(t){return new Promise(e=>setTimeout(e,t))}ne();function aI(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let r=Number(e[1]),i=Number(e[2]??0);return r<18||r===18&&i<4?"fatal":r<20?"warn":"ok"}function Jp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=aI(t);if(i==="ok")return;let o=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
268
- `),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
262
+ `),1}}async function g2(t,e,n={},i){let o=e.paths??J(),c=t??await ua(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new rn(e.paths),u=await Qp(o,i,e.reconstructEnv??al);if(await md(o,u).catch(p=>rt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(p)})),!e.skipDistInstall){let p=await fl({paths:e.paths});p.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${p.fromVersion} \u2192 ${p.toVersion}
263
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):p.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${p.libVersion}
264
+ `)}let f=await Xp(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
265
+ `),1;let x={privatecode:c};n.env&&(x.env=n.env),n.handshakeUrl&&(x.handshake_url=n.handshakeUrl),n.frontierUrl&&(x.frontier_url=n.frontierUrl),n.mockScenario&&(x.mock_scenario=n.mockScenario);try{let p=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return p.status===200&&p.body?.ok?(process.stdout.write(`coze-bridge: connected (${p.body.note??"ok"})
266
+ `),t!==void 0&&await ls(c,o).catch(w=>Vp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(p.body)}
267
+ `),1)}catch(p){return process.stderr.write(`coze-bridge: connect failed: ${String(p)}
268
+ `),1}}async function Kp(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await n(200)}return t.probe(500)}async function $p(t,e,n=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<n;c++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Zi(u))return;await e(i)}}function m2(t){return new Promise(e=>setTimeout(e,t))}ie();function w2(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 eg(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){let i=w2(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
269
+ `),n(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
269
270
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
270
271
  npx -y coze-bridge@latest stop
271
272
  npx -y coze-bridge@latest connect
272
273
 
273
- `)}Jp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Nl("warn");Wp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
274
+ `)}eg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Fl("warn");Zp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
274
275
  `),process.exit(1)});