coze-bridge 0.2.4 → 0.2.5

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 +82 -88
  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 Dg=Object.create;var Aa=Object.defineProperty;var Pg=Object.getOwnPropertyDescriptor;var Og=Object.getOwnPropertyNames;var Lg=Object.getPrototypeOf,Ng=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 rt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ka=(t,e)=>{for(var r in e)Aa(t,r,{get:e[r],enumerable:!0})},Mg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Og(e))!Ng.call(t,o)&&o!==r&&Aa(t,o,{get:()=>e[o],enumerable:!(i=Pg(e,o))||i.enumerable});return t};var jt=(t,e,r)=>(r=t!=null?Dg(Lg(t)):{},Mg(e||!t||!t.__esModule?Aa(r,"default",{value:t,enumerable:!0}):r,t));function Ze(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var or=rt(()=>{"use strict"});import{createWriteStream as Bg,mkdirSync as Fg,readdirSync as zg,unlinkSync as Ug}from"node:fs";import{join as vl}from"node:path";function On(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function ar(t,e){return`${t}-${e}.log`}function Ta(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function Gg(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 us(t,e,r,i){let o;try{o=zg(t)}catch{return}for(let c of o){let d=Ta(c,e);if(d&&Gg(d,r,i))try{Ug(vl(t,c))}catch{}}}var ni,Ca=rt(()=>{"use strict";ni=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>On(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{Fg(this.dir,{recursive:!0});let r=Bg(vl(this.dir,ar(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
8
+ var Cg=Object.create;var Sa=Object.defineProperty;var Rg=Object.getOwnPropertyDescriptor;var Pg=Object.getOwnPropertyNames;var Dg=Object.getPrototypeOf,Og=Object.prototype.hasOwnProperty;var he=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var nt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ia=(t,e)=>{for(var r in e)Sa(t,r,{get:e[r],enumerable:!0})},Lg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pg(e))!Og.call(t,o)&&o!==r&&Sa(t,o,{get:()=>e[o],enumerable:!(i=Rg(e,o))||i.enumerable});return t};var Gt=(t,e,r)=>(r=t!=null?Cg(Dg(t)):{},Lg(e||!t||!t.__esModule?Sa(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 sr=nt(()=>{"use strict"});import{createWriteStream as Ng,mkdirSync as Mg,readdirSync as Bg,unlinkSync as Fg}from"node:fs";import{join as El}from"node:path";function Dn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function or(t,e){return`${t}-${e}.log`}function Aa(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function zg(t,e,r){let i=c=>{let[d,u,f]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>r}function cs(t,e,r,i){let o;try{o=Bg(t)}catch{return}for(let c of o){let d=Aa(c,e);if(d&&zg(d,r,i))try{Fg(El(t,c))}catch{}}}var ei,ka=nt(()=>{"use strict";ei=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Dn(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{Mg(this.dir,{recursive:!0});let r=Ng(El(this.dir,or(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
9
  `)),this.stream=r}catch(r){process.stderr.write(`[log-sink] rotate failed: ${String(r)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&us(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Hg,mkdirSync as qg}from"node:fs";import{join as jg}from"node:path";function Il(t){let e=t.retentionDays??$g,r=t.clock??(()=>On(new Date));hs={bridgeSink:new ni(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ni(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();us(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])us(t.agentLogsDir(o),"agent",i,e)}function Vg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Al(t){Ra=t}function kl(t){return cr[Ra]<=cr[t]}function Tl(t,e){let r=cr[t];return r===void 0?!0:r>=cr[e]}function xs(t){Sl={...t}}function Cl(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`${On(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function it(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Cl(new Date),level:e,module:r,msg:i,...o})}
11
- `;qg(t,{recursive:!0}),Hg(jg(t,ar("bridge",On(new Date))),c)}catch{}}function Jg(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function fs(t,e,r,i,o){if(cr[t]<cr[Ra])return;let c=`${JSON.stringify({ts:Cl(new Date),level:t,module:e,msg:r,...Sl,...i})}
12
- `;if(hs){let d=Jg(o,i),u=d?Vg(hs,d):hs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Kg.write(c):Wg.write(c)}function H(t,e){return{debug:(r,i)=>fs("debug",t,r,i,e),info:(r,i)=>fs("info",t,r,i,e),warn:(r,i)=>fs("warn",t,r,i,e),error:(r,i)=>fs("error",t,r,i,e),child:r=>H(`${t}.${r}`,e),forAgent:r=>H(t,r)}}var cr,Ra,Wg,Kg,Sl,$g,hs,ne=rt(()=>{"use strict";or();Ca();cr={debug:10,info:20,warn:30,error:40},Ra=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Wg=process.stdout,Kg=process.stderr,Sl={},$g=Ze("COZE_BRIDGE_LOG_RETENTION_DAYS",30),hs=null});var T,Ve=rt(()=>{"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 Ol={};ka(Ol,{ACP_WRAPPER_NPM_PACKAGES:()=>ps,_resetAcpInstallerForTests:()=>tm,_setBinaryPathCacheForTests:()=>nm,buildAcpSpawn:()=>ii,ensureAcpInstalled:()=>dr,getAcpBinaryPath:()=>gs,pickWhichLine:()=>Oa,probeAcpVersion:()=>em,resolveAcpCommand:()=>Pl});import{readFileSync as Rl}from"node:fs";import{createRequire as Zg}from"node:module";import{dirname as Xg,resolve as Yg}from"node:path";function Oa(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 Qg(t){let e=Dl.resolve(`${t.npmPackage}/package.json`),r=Xg(e),i=JSON.parse(Rl(e,"utf8")),o=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!o)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return Yg(r,o)}async function dr(t,e){let r=Pa[t];if(!r)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ri.get(t);if(i)return i;try{let o=Qg(r);return ri.set(t,o),Da.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Da.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(o)}),new T("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
- `),{cause:o})}}async function em(t){let e=Pa[t];if(e)try{let r=Dl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Rl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Da.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function gs(t){return ri.get(t)}function Pl(t,e){if(e)return e;let r=gs(t);if(!r)throw new T("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function ii(t,e,r){if(e)return{command:e,args:[...r]};let i=Pl(t);return{command:process.execPath,args:[i,...r]}}function tm(){ri.clear()}function nm(t,e){ri.set(t,e)}var Da,Pa,ps,Dl,ri,dn=rt(()=>{"use strict";Ve();ne();Da=H("agents.acp-installer"),Pa={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ps=Object.values(Pa).filter(t=>t!==void 0).map(t=>t.npmPackage),Dl=Zg(import.meta.url),ri=new Map});import{chmod as im,mkdir as sm,readFile as om,rename as am,rm as cm,writeFile as dm}from"node:fs/promises";import{dirname as lm}from"node:path";async function lr(t){try{let e=await om(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ln(t,e,r){await sm(lm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await dm(i,e,{encoding:"utf8",mode:r?.mode}),await am(i,t),r?.mode!==void 0&&await im(t,r.mode)}catch(o){throw await cm(i,{force:!0}).catch(()=>{}),o}}async function ur(t,e,r){await ln(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var un=rt(()=>{"use strict"});import{promises as Ml,readdirSync as um}from"node:fs";import{homedir as fm}from"node:os";import{sep as hm,join as De,resolve as Bl}from"node:path";function ee(t){let e=t??fm(),r=De(e,".coze"),i=De(r,"bridge"),o=De(i,"lib"),c=De(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:De(o,"index.js"),binDir:De(i,"bin"),pidFile:De(i,"bridge.pid"),portFile:De(i,"bridge.port"),tokenFile:De(i,"bridge.token"),patTokenFile:De(i,"pat-token"),agentEnvFile:De(i,"agent-env.json"),logFile:De(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:De(c,"daemon-stdio.log"),installLock:De(i,"install.lock"),configFile:De(i,"config.json"),agentsRoot:De(r,"agents")}}function Xe(t,e=ee()){let r=De(e.agentsRoot,t);return{root:r,config:De(r,"config.json"),workspace:De(r,"workspace"),logs:De(r,"logs")}}function ms(t=ee()){try{return um(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function si(t,e){let r=await Ml.realpath(Bl(t)).catch(()=>null);if(!r)return!1;let i=await Ml.realpath(Bl(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?r.toLowerCase():r,c=process.platform==="win32"?i.toLowerCase():i;return o===c||o.startsWith(c+hm)}var Be=rt(()=>{"use strict"});var _s={};ka(_s,{AGENT_CONFIG_FILE_MODE:()=>ws,enforceAgentConfigMode:()=>gm,loadAgentConfig:()=>Pe,persistAgentSessions:()=>oi,persistAgentSkills:()=>ai,saveAgentConfig:()=>Ge});import{chmod as xm,stat as pm}from"node:fs/promises";function Pe(t,e){return lr(Xe(t,e).config)}function Ge(t,e){return ur(Xe(t.agentId,e).config,t,{mode:ws})}async function gm(t,e){if(process.platform==="win32")return;let r=Xe(t,e).config;try{let i=await pm(r);if(!i.isFile())return;let o=i.mode&511;o!==ws&&(await xm(r,ws),Fl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Fl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function oi(t,e,r){let i=await Pe(t,r);i&&(i.sessions=Object.fromEntries(e),await Ge(i,r))}async function ai(t,e,r){let i=await Pe(t,r);i&&(i.skills=e,await Ge(i,r))}var Fl,ws,fn=rt(()=>{"use strict";un();ne();Be();Fl=H("agent-config"),ws=384});var Ma=ce((p2,Gl)=>{Gl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var bs=ce(ql=>{var Hl={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 Em(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(Hl))ql[t]=Em(Hl[t])});var Vl=ce((m2,$l)=>{var vm=fe("fs"),Fe=fe("path"),jl=Ma(),Sm=bs(),Im=typeof process=="object"&&process.platform==="win32",Wl=t=>typeof t=="object"&&t!==null,Kl=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 Ae(t){this.sep=Fe.sep,this.fs=vm,Wl(t)&&Wl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}$l.exports=Ae;Ae.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 Sm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Ae.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=Fe.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};Ae.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=Fe.dirname(t);c.fs.exists(x,function(m){m||c.makeDir(x),c.fs.open(t,"w",438,function(_,S){_?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,v){c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){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)})})})})})};Ae.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=Fe.join(i,u),x=e.fs.statSync(h);(!o||o.test(h))&&d.push(Fe.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(r(h,o,c)))}),d}return r(t,void 0,!0)};Ae.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=Fe.join(t,u),r.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Fe.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(m,_){if(m)return e(m);i=i.concat(_),--d||e(null,i)}):--d||e(null,i))})})})};Ae.prototype.getAttributes=function(){};Ae.prototype.setAttributes=function(){};Ae.crc32update=function(t,e){return Kl[(t^e)&255]^t>>>8};Ae.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Ae.crc32update(r,t[i++]);return~r>>>0};Ae.methodToString=function(t){switch(t){case jl.STORED:return"STORED ("+t+")";case jl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ae.canonical=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.join(".",e)};Ae.zipnamefix=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.posix.join(".",e)};Ae.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ae.sanitize=function(t,e){t=Fe.resolve(Fe.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Fe.normalize(Fe.join(t,r.slice(i,o).join(Fe.sep)));if(c.indexOf(t)===0)return c}return Fe.normalize(Fe.join(t,Fe.basename(e)))};Ae.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Ae.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Ae.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ae.fromDate2DOS=function(t){let e=0,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};Ae.isWin=Im;Ae.crcTable=Kl});var Zl=ce((w2,Jl)=>{var Am=fe("path");Jl.exports=function(t,{fs:e}){var r=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(o=e.statSync(r),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=Am.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 Yl=ce((_2,Xl)=>{Xl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var xr=ce((y2,hr)=>{hr.exports=Vl();hr.exports.Constants=Ma();hr.exports.Errors=bs();hr.exports.FileAttr=Zl();hr.exports.decoder=Yl()});var eu=ce((b2,Ql)=>{var hn=xr(),z=hn.Constants;Ql.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,h=0,x=0,m=0,_=0,S=0,y=0,v=0;t|=hn.isWin?2560:768,r|=z.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,C=b=>Math.max(0,b)&65535,P=b=>Math.max(0,b)&255;return o=hn.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 hn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=hn.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=A(b)},get timeHighByte(){return P(o>>>8)},get crc(){return c},set crc(b){c=A(b)},get compressedSize(){return d},set compressedSize(b){d=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return h},set fileNameLength(b){h=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return m},set commentLength(b){m=b},get diskNumStart(){return _},set diskNumStart(b){_=A(b)},get inAttr(){return S},set inAttr(b){S=A(b)},get attr(){return y},set attr(b){y=A(b)},get fileAttr(){return(y||0)>>16&4095},get offset(){return v},set offset(b){v=A(b)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+x+m},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var R=b.slice(v,v+z.LOCHDR);if(R.readUInt32LE(0)!==z.LOCSIG)throw hn.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=v+z.LOCHDR+I.fnameLen,M=O+I.extraLen;return b.slice(O,M)},loadFromBinary:function(b){if(b.length!==z.CENHDR||b.readUInt32LE(0)!==z.CENSIG)throw hn.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),m=b.readUInt16LE(z.CENCOM),_=b.readUInt16LE(z.CENDSK),S=b.readUInt16LE(z.CENATT),y=b.readUInt32LE(z.CENATX),v=b.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(z.LOCHDR);return b.writeUInt32LE(z.LOCSIG,0),b.writeUInt16LE(e,z.LOCVER),b.writeUInt16LE(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+m);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(m,z.CENCOM),b.writeUInt16LE(_,z.CENDSK),b.writeUInt16LE(S,z.CENATT),b.writeUInt32LE(y,z.CENATX),b.writeUInt32LE(v,z.CENOFF),b},toJSON:function(){let b=function(R){return R+" bytes"};return{made:t,version:e,flags:r,method:hn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(m),diskNumStart:_,inAttr:S,attr:y,offset:v,centralHeaderSize:b(z.CENHDR+h+x+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var nu=ce((E2,tu)=>{var pr=xr(),Ee=pr.Constants;tu.exports=function(){var t=0,e=0,r=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return r},set size(c){r=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return 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 pr.Errors.INVALID_END();c.readUInt32LE(0)===Ee.ENDSIG?(t=c.readUInt16LE(Ee.ENDSUB),e=c.readUInt16LE(Ee.ENDTOT),r=c.readUInt32LE(Ee.ENDSIZ),i=c.readUInt32LE(Ee.ENDOFF),o=c.readUInt16LE(Ee.ENDCOM)):(t=pr.readBigUInt64LE(c,Ee.ZIP64SUB),e=pr.readBigUInt64LE(c,Ee.ZIP64TOT),r=pr.readBigUInt64LE(c,Ee.ZIP64SIZE),i=pr.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(r,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 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 Fa=ce(Ba=>{Ba.EntryHeader=eu();Ba.MainHeader=nu()});var iu=ce((S2,ru)=>{ru.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 m=c[x];m.copy(u,h),h+=m.length}i&&i(u)}),o.end(t)}}}});var ou=ce((I2,su)=>{var km=+(process.versions?process.versions.node:"").split(".")[0]||0;su.exports=function(t,e){var r=fe("zlib");let i=km>=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 m=0;m<d.length;m++){var _=d[m];_.copy(h,x),x+=_.length}o&&o(h)}),c.end(t)}}}});var uu=ce((A2,lu)=>{"use strict";var{randomFillSync:au}=fe("crypto"),Tm=bs(),Cm=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),du=(t,e)=>Math.imul(t,e)>>>0,cu=(t,e)=>Cm[(t^e)&255]^t>>>8,ci=()=>typeof au=="function"?au(Buffer.alloc(12)):ci.node();ci.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var Es={genSalt:ci};function vs(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}vs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=cu(e[0],t),e[1]+=e[0]&255,e[1]=du(e[1],134775813)+1,e[2]=cu(e[2],e[1]>>>24),t};vs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return du(t,t^1)>>8&255};function Rm(t){let e=new vs(t);return function(r){let i=Buffer.alloc(r.length),o=0;for(let c of r)i[o++]=e.updateKeys(c^e.next());return i}}function Dm(t){let e=new vs(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 Pm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Rm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Tm.WRONG_PASSWORD();return i(t.slice(12))}function Om(t){Buffer.isBuffer(t)&&t.length>=12?Es.genSalt=function(){return t.slice(0,12)}:t==="node"?Es.genSalt=ci.node:Es.genSalt=ci}function Lm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Dm(r),c=Es.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)}lu.exports={decrypt:Pm,encrypt:Lm,_salter:Om}});var fu=ce(Ss=>{Ss.Deflater=iu();Ss.Inflater=ou();Ss.ZipCrypto=uu()});var Ua=ce((T2,hu)=>{var de=xr(),Nm=Fa(),ke=de.Constants,za=fu();hu.exports=function(t,e){var r=new Nm.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let m=t,_=typeof m.decoder=="object"?m.decoder:de.decoder;x=_.hasOwnProperty("efs")?_.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 y(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(de.crc32(b)!==r.localHeader.crc)return!1}else{let R={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==ke.LOCSIG||e.readUInt32LE(O)==ke.CENSIG)throw de.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==ke.EXTSIG)R.crc=e.readUInt32LE(O+ke.EXTCRC),R.compressedSize=e.readUInt32LE(O+ke.EXTSIZ),R.size=e.readUInt32LE(O+ke.EXTLEN);else if(e.readUInt16LE(O+12)===19280)R.crc=e.readUInt32LE(O+ke.EXTCRC-4),R.compressedSize=e.readUInt32LE(O+ke.EXTSIZ-4),R.size=e.readUInt32LE(O+ke.EXTLEN-4);else throw de.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==r.compressedSize||R.size!==r.size||R.crc!==r.crc)throw de.Errors.DESCRIPTOR_FAULTY();if(de.crc32(b)!==R.crc)return!1}return!0}function v(b,R,O){if(typeof R>"u"&&typeof b=="string"&&(O=b,b=void 0),c)return b&&R&&R(Buffer.alloc(0),de.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var M=S();if(M.length===0)return b&&R&&R(M),M;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw de.Errors.INVALID_PASS_PARAM();M=za.ZipCrypto.decrypt(M,r,O)}var N=Buffer.alloc(r.size);switch(r.method){case de.Constants.STORED:if(M.copy(N),y(N))return b&&R&&R(N),N;throw b&&R&&R(N,de.Errors.BAD_CRC()),de.Errors.BAD_CRC();case de.Constants.DEFLATED:var J=new za.Inflater(M,r.size);if(b)J.inflateAsync(function(V){V.copy(V,0),R&&(y(V)?R(V):R(V,de.Errors.BAD_CRC()))});else{if(J.inflate(N).copy(N,0),!y(N))throw de.Errors.BAD_CRC(`"${_.decode(i)}"`);return N}break;default:throw b&&R&&R(Buffer.alloc(0),de.Errors.UNKNOWN_METHOD()),de.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 de.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(d.length),d.copy(O),b&&R&&R(O),O;default:case de.Constants.DEFLATED:var M=new za.Deflater(d);if(b)M.deflateAsync(function(J){O=Buffer.alloc(J.length),r.compressedSize=J.length,J.copy(O),R&&R(O)});else{var N=M.deflate();return r.compressedSize=N.length,N}M=null;break}}else if(b&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,R){return de.readBigUInt64LE(b,R)}function C(b){try{for(var R=0,O,M,N;R+4<b.length;)O=b.readUInt16LE(R),R+=2,M=b.readUInt16LE(R),R+=2,N=b.slice(R,R+M),R+=M,ke.ID_ZIP64===O&&P(N)}catch{throw de.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(b){var R,O,M,N;b.length>=ke.EF_ZIP64_SCOMP&&(R=A(b,ke.EF_ZIP64_SUNCOMP),r.size===ke.EF_ZIP64_OR_32&&(r.size=R)),b.length>=ke.EF_ZIP64_RHO&&(O=A(b,ke.EF_ZIP64_SCOMP),r.compressedSize===ke.EF_ZIP64_OR_32&&(r.compressedSize=O)),b.length>=ke.EF_ZIP64_DSN&&(M=A(b,ke.EF_ZIP64_RHO),r.offset===ke.EF_ZIP64_OR_32&&(r.offset=M)),b.length>=ke.EF_ZIP64_DSN+4&&(N=b.readUInt32LE(ke.EF_ZIP64_DSN),r.diskNumStart===ke.EF_ZIP64_OR_16&&(r.diskNumStart=N))}return{get entryName(){return _.decode(i)},get rawEntryName(){return i},set entryName(b){i=de.toBuffer(b,_.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 _.decode(o)},set comment(b){if(o=de.toBuffer(b,_.encode),r.commentLength=o.length,o.length>65535)throw de.Errors.COMMENT_TOO_LONG()},get name(){var b=_.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){d=de.toBuffer(b,de.decoder.encode),!c&&d.length?(r.size=d.length,r.method=de.Constants.DEFLATED,r.crc=de.crc32(b),r.changed=!0):r.method=de.Constants.STORED},getData:function(b){return r.changed?d:v(!1,null,b)},getDataAsync:function(b,R){r.changed?b(d):v(!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=de.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 gu=ce((C2,pu)=>{var xu=Ua(),Mm=Fa(),Je=xr();pu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Mm.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:m,decoder:_}=x;t?v(x.readEntries):d=!0;function S(){let A=new Set;for(let 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("/")+"/";A.add(R)}}for(let C of A)if(!(C in i)){let P=new xu(x);P.entryName=C,P.attr=16,P.temporary=!0,r.push(P),i[P.entryName]=P,h.add(P)}}function y(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/Je.Constants.CENHDR)throw Je.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,C=0;C<r.length;C++){var P=A,b=new xu(x,t);b.header=t.slice(P,P+=Je.Constants.CENHDR),b.entryName=t.slice(P,P+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(P,P+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(P,P+b.header.commentLength)),A+=b.header.centralHeaderSize,r[C]=b,i[b.entryName]=b}h.clear(),S()}function v(A){var C=t.length-Je.Constants.ENDHDR,P=Math.max(0,C-65535),b=P,R=t.length,O=-1,M=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),C;C>=b;C--)if(t[C]===80){if(t.readUInt32LE(C)===Je.Constants.ENDSIG){O=C,M=C,R=C+Je.Constants.ENDHDR,b=C-Je.Constants.END64HDR;continue}if(t.readUInt32LE(C)===Je.Constants.END64SIG){b=P;continue}if(t.readUInt32LE(C)===Je.Constants.ZIP64SIG){O=C,R=C+Je.readBigUInt64LE(t,C+Je.Constants.ZIP64SIZE)+Je.Constants.ZIP64LEAD;break}}if(O==-1)throw Je.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,R)),c.commentLength&&(o=t.slice(M+Je.Constants.ENDHDR)),A&&y()}function I(){r.length>1&&!m&&r.sort((A,C)=>A.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return d||y(),r.filter(A=>!h.has(A))},get comment(){return _.decode(o)},set comment(A){o=Je.toBuffer(A,_.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||y(),i[A]||null},setEntry:function(A){d||y(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,C=!0){d||y();let P=i[A];this.getEntryChildren(P,C).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let C=i[A],P=r.indexOf(C);P>=0&&(r.splice(P,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,C=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&C){let P=[],b=A.entryName;for(let R of r)R.entryName.startsWith(b)&&P.push(R);return P}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let C=this.getEntryChildren(A);return C.includes(A)?C.length-1:C.length}return 0},compressToBuffer:function(){d||y(),I();let A=[],C=[],P=0,b=0;c.size=0,c.offset=0;let R=0;for(let N of this.entries){let J=N.getCompressedData();N.header.offset=b;let V=N.packLocalHeader(),re=V.length+J.length;b+=re,A.push(V),A.push(J);let Y=N.packCentralHeader();C.push(Y),c.size+=Y.length,P+=re+Y.length,R++}P+=c.mainHeaderSize,c.offset=b,c.totalEntries=R,b=0;let O=Buffer.alloc(P);for(let N of A)N.copy(O,b),b+=N.length;for(let N of C)N.copy(O,b),b+=N.length;let M=c.toBinary();return o&&o.copy(M,Je.Constants.ENDHDR),M.copy(O,b),t=O,d=!1,O},toAsyncBuffer:function(A,C,P,b){try{d||y(),I();let R=[],O=[],M=0,N=0,J=0;c.size=0,c.offset=0;let V=function(re){if(re.length>0){let Y=re.shift(),se=Y.entryName+Y.extra.toString();P&&P(se),Y.getCompressedDataAsync(function(ae){b&&b(se),Y.header.offset=N;let D=Y.packLocalHeader(),U=D.length+ae.length;N+=U,R.push(D),R.push(ae);let W=Y.packCentralHeader();O.push(W),c.size+=W.length,M+=U+W.length,J++,V(re)})}else{M+=c.mainHeaderSize,c.offset=N,c.totalEntries=J,N=0;let Y=Buffer.alloc(M);R.forEach(function(ae){ae.copy(Y,N),N+=ae.length}),O.forEach(function(ae){ae.copy(Y,N),N+=ae.length});let se=c.toBinary();o&&o.copy(se,Je.Constants.ENDHDR),se.copy(Y,N),t=Y,d=!1,A(Y)}};V(Array.from(this.entries))}catch(R){C(R)}}}}});var _u=ce((R2,wu)=>{var Se=xr(),ve=fe("path"),Bm=Ua(),Fm=gu(),Ln=(...t)=>Se.findLast(t,e=>typeof e=="boolean"),mu=(...t)=>Se.findLast(t,e=>typeof e=="string"),zm=(...t)=>Se.findLast(t,e=>typeof e=="function"),Um={noSort:!1,readEntries:!1,method:Se.Constants.NONE,fs:null};wu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Um);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=Se.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Se(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Se.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Se.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw Se.Errors.INVALID_FILENAME();let c=new Fm(r,i),{canonical:d,sanitize:u,zipnamefix:h}=Se;function x(y){if(y&&c){var v;if(typeof y=="string"&&(v=c.getEntry(ve.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(v=c.getEntry(y.entryName)),v)return v}return null}function m(y){let{join:v,normalize:I,sep:A}=ve.posix;return v(ve.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function _(y){return y instanceof RegExp?(function(v){return function(I){return v.test(I)}})(y):typeof y!="function"?()=>!0:y}let S=(y,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",ve.relative(y,v)+I};return{readFile:function(y,v){var I=x(y);return I&&I.getData(v)||null},childCount:function(y){let v=x(y);if(v)return c.getChildCount(v)},readFileAsync:function(y,v){var I=x(y);I?I.getDataAsync(v):v(null,"getEntry failed for:"+y)},readAsText:function(y,v){var I=x(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(y,v,I){var A=x(y);A?A.getDataAsync(function(C,P){if(P){v(C,P);return}C&&C.length?v(C.toString(I||"utf8")):v("")}):v("")},deleteFile:function(y,v=!0){var I=x(y);I&&c.deleteFile(I.entryName,v)},deleteEntry:function(y){var v=x(y);v&&c.deleteEntry(v.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,v){var I=x(y);I&&(I.comment=v)},getZipEntryComment:function(y){var v=x(y);return v&&v.comment||""},updateFile:function(y,v){var I=x(y);I&&I.setData(v)},addLocalFile:function(y,v,I,A){if(o.fs.existsSync(y)){v=v?m(v):"";let C=ve.win32.basename(ve.win32.normalize(y));v+=I||C;let P=o.fs.statSync(y),b=P.isFile()?o.fs.readFileSync(y):Buffer.alloc(0);P.isDirectory()&&(v+=o.sep),this.addFile(v,b,A,P)}else throw Se.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,v){y=typeof y=="object"?y:{localPath:y};let I=ve.resolve(y.localPath),{comment:A}=y,{zipPath:C,zipName:P}=y,b=this;o.fs.stat(I,function(R,O){if(R)return v(R,!1);C=C?m(C):"";let M=ve.win32.basename(ve.win32.normalize(I));if(C+=P||M,O.isFile())o.fs.readFile(I,function(N,J){return N?v(N,!1):(b.addFile(C,J,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return C+=o.sep,b.addFile(C,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(y,v,I){if(I=_(I),v=v?m(v):"",y=ve.normalize(y),o.fs.existsSync(y)){let A=o.findFiles(y),C=this;if(A.length)for(let P of A){let b=ve.join(v,S(y,P));I(b)&&C.addLocalFile(P,ve.dirname(b))}}else throw Se.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,v,I,A){A=_(A),I=I?m(I):"",y=ve.normalize(y);var C=this;o.fs.open(y,"r",function(P){if(P&&P.code==="ENOENT")v(void 0,Se.Errors.FILE_NOT_FOUND(y));else if(P)v(void 0,P);else{var b=o.findFiles(y),R=-1,O=function(){if(R+=1,R<b.length){var M=b[R],N=S(y,M).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(N)?o.fs.stat(M,function(J,V){J&&v(void 0,J),V.isFile()?o.fs.readFile(M,function(re,Y){re?v(void 0,re):(C.addFile(I+N,Y,"",V),O())}):(C.addFile(I+N+"/",Buffer.alloc(0),"",V),O())}):process.nextTick(()=>{O()})}else v(!0,void 0)};O()}})},addLocalFolderAsync2:function(y,v){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=ve.resolve(m(y.localPath));let{zipPath:A,filter:C,namefix:P}=y;C instanceof RegExp?C=(function(O){return function(M){return O.test(M)}})(C):typeof C!="function"&&(C=function(){return!0}),A=A?m(A):"",P=="latin1"&&(P=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=O=>O);let b=O=>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"?v(void 0,Se.Errors.FILE_NOT_FOUND(localPath)):O?v(void 0,O):o.findFilesAsync(localPath,function(M,N){if(M)return v(M);N=N.filter(J=>C(b(J))),N.length||v(void 0,!1),setImmediate(N.reverse().reduce(function(J,V){return function(re,Y){if(re||Y===!1)return setImmediate(J,re,!1);I.addLocalFileAsync({localPath:V,zipPath:ve.dirname(b(V)),zipName:R(V)},J)}},v))})})},addLocalFolderPromise:function(y,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},v),(C,P)=>{C&&A(C),P&&I(this)})})},addFile:function(y,v,I,A){y=h(y);let C=x(y),P=C!=null;P||(C=new Bm(i),C.entryName=y),C.comment=I||"";let b=typeof A=="object"&&A instanceof o.fs.Stats;b&&(C.header.time=A.mtime);var R=C.isDirectory?16:0;let O=C.isDirectory?16384:32768;return b?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=C.isDirectory?493:420,R=(R|O<<16)>>>0,C.attr=R,C.setData(v),P||c.setEntry(C),C},getEntries:function(y){return c.password=y,c?c.entries:[]},getEntry:function(y){return x(y)},getEntryCount:function(){return c.getEntryCount()},forEach:function(y){return c.forEach(y)},extractEntryTo:function(y,v,I,A,C,P){A=Ln(!1,A),C=Ln(!1,C),I=Ln(!0,I),P=mu(C,P);var b=x(y);if(!b)throw Se.Errors.NO_ENTRY();var R=d(b.entryName),O=u(v,P&&!b.isDirectory?P:I?R:ve.basename(R));if(b.isDirectory){var M=c.getEntryChildren(b);return M.forEach(function(V){if(V.isDirectory)return;var re=V.getData();if(!re)throw Se.Errors.CANT_EXTRACT_FILE();var Y=d(V.entryName),se=u(v,I?Y:ve.basename(Y));let ae=C?V.header.fileAttr:void 0;o.writeFileTo(se,re,A,ae)}),!0}var N=b.getData(c.password);if(!N)throw Se.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw Se.Errors.CANT_OVERRIDE();let J=C?y.header.fileAttr:void 0;return o.writeFileTo(O,N,A,J),!0},test:function(y){if(!c)return!1;for(var v in c.entries)try{if(v.isDirectory)continue;var I=c.entries[v].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,v,I,A){if(I=Ln(!1,I),A=mu(I,A),v=Ln(!1,v),!c)throw Se.Errors.NO_ZIP();c.entries.forEach(function(C){var P=u(y,d(C.entryName));if(C.isDirectory){o.makeDir(P);return}var b=C.getData(A);if(!b)throw Se.Errors.CANT_EXTRACT_FILE();let R=I?C.header.fileAttr:void 0;o.writeFileTo(P,b,v,R);try{o.fs.utimesSync(P,C.header.time,C.header.time)}catch{throw Se.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,v,I,A){if(A=zm(v,I,A),I=Ln(!1,I),v=Ln(!1,v),!A)return new Promise((O,M)=>{this.extractAllToAsync(y,v,I,function(N){N?M(N):O(this)})});if(!c){A(Se.Errors.NO_ZIP());return}y=ve.resolve(y);let C=O=>u(y,ve.normalize(d(O.entryName))),P=(O,M)=>new Error(O+': "'+M+'"'),b=[],R=[];c.entries.forEach(O=>{O.isDirectory?b.push(O):R.push(O)});for(let O of b){let M=C(O),N=I?O.header.fileAttr:void 0;try{o.makeDir(M),N&&o.fs.chmodSync(M,N),o.fs.utimesSync(M,O.header.time,O.header.time)}catch{A(P("Unable to create folder",M))}}R.reverse().reduce(function(O,M){return function(N){if(N)O(N);else{let J=ve.normalize(d(M.entryName)),V=u(y,J);M.getDataAsync(function(re,Y){if(Y)O(Y);else if(!re)O(Se.Errors.CANT_EXTRACT_FILE());else{let se=I?M.header.fileAttr:void 0;o.writeFileToAsync(V,re,v,se,function(ae){ae||O(P("Unable to write file",V)),o.fs.utimes(V,M.header.time,M.header.time,function(D){D?O(P("Unable to set times",V)):O()})})}})}}},A)()},writeZip:function(y,v){if(arguments.length===1&&typeof y=="function"&&(v=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(y,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((C,P)=>{!y&&i.filename&&(y=i.filename),y||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(y,b,I,A,R)},P)})},toBufferPromise:function(){return new Promise((y,v)=>{c.toAsyncBuffer(y,v)})},toBuffer:function(y,v,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,v,I,A),null):c.compressToBuffer()}}}});import{execFile as V_,spawn as J_,spawnSync as VA}from"node:child_process";import{promisify as Z_}from"node:util";function Y_(t){if(process.platform!=="win32")return!1;if(Uf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Uf,"").toLowerCase();return X_.has(r)}function Gf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return Y_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function ot(t,e=[],r={}){return J_(t,e,Gf(t,r))}function Hf(t,e=[],r={}){return Q_(t,e,Gf(t,r))}var X_,Uf,Q_,Xt=rt(()=>{"use strict";X_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Uf=/\.(cmd|bat|ps1)$/i;Q_=Z_(V_)});var Qt=ce((NR,Ch)=>{"use strict";var kh=["nodebuffer","arraybuffer","fragments"],Th=typeof Blob<"u";Th&&kh.push("blob");Ch.exports={BINARY_TYPES:kh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Th,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Zi=ce((MR,Po)=>{"use strict";var{EMPTY_BUFFER:BE}=Qt(),_d=Buffer[Symbol.species];function FE(t,e){if(t.length===0)return BE;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let c=t[o];r.set(c,i),i+=c.length}return i<e?new _d(r.buffer,r.byteOffset,i):r}function Rh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Dh(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function zE(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function yd(t){if(yd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new _d(t):ArrayBuffer.isView(t)?e=new _d(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),yd.readOnly=!1),e}Po.exports={concat:FE,mask:Rh,toArrayBuffer:zE,toBuffer:yd,unmask:Dh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=fe("bufferutil");Po.exports.mask=function(e,r,i,o,c){c<48?Rh(e,r,i,o,c):t.mask(e,r,i,o,c)},Po.exports.unmask=function(e,r){e.length<32?Dh(e,r):t.unmask(e,r)}}catch{}});var Lh=ce((BR,Oh)=>{"use strict";var Ph=Symbol("kDone"),bd=Symbol("kRun"),Ed=class{constructor(e){this[Ph]=()=>{this.pending--,this[bd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[bd]()}[bd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ph])}}};Oh.exports=Ed});var Gr=ce((FR,Fh)=>{"use strict";var Xi=fe("zlib"),Nh=Zi(),UE=Lh(),{kStatusCode:Mh}=Qt(),GE=Buffer[Symbol.species],HE=Buffer.from([0,0,255,255]),Lo=Symbol("permessage-deflate"),en=Symbol("total-length"),zr=Symbol("callback"),Cn=Symbol("buffers"),Ur=Symbol("error"),Oo,vd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Oo){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Oo=new UE(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[zr];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){Oo.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){Oo.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[Lo]=this,this._inflate[en]=0,this._inflate[Cn]=[],this._inflate.on("error",jE),this._inflate.on("data",Bh)}this._inflate[zr]=i,this._inflate.write(e),r&&this._inflate.write(HE),this._inflate.flush(()=>{let c=this._inflate[Ur];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Nh.concat(this._inflate[Cn],this._inflate[en]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[en]=0,this._inflate[Cn]=[],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[en]=0,this._deflate[Cn]=[],this._deflate.on("data",qE)}this._deflate[zr]=i,this._deflate.write(e),this._deflate.flush(Xi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Nh.concat(this._deflate[Cn],this._deflate[en]);r&&(c=new GE(c.buffer,c.byteOffset,c.length-4)),this._deflate[zr]=null,this._deflate[en]=0,this._deflate[Cn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Fh.exports=vd;function qE(t){this[Cn].push(t),this[en]+=t.length}function Bh(t){if(this[en]+=t.length,this[Lo]._maxPayload<1||this[en]<=this[Lo]._maxPayload){this[Cn].push(t);return}this[Ur]=new RangeError("Max payload size exceeded"),this[Ur].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ur][Mh]=1009,this.removeListener("data",Bh),this.reset()}function jE(t){if(this[Lo]._inflate=null,this[Ur]){this[zr](this[Ur]);return}t[Mh]=1007,this[zr](t)}});var Hr=ce((zR,No)=>{"use strict";var{isUtf8:zh}=fe("buffer"),{hasBlob:WE}=Qt(),KE=[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 $E(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Sd(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function VE(t){return WE&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}No.exports={isBlob:VE,isValidStatusCode:$E,isValidUTF8:Sd,tokenChars:KE};if(zh)No.exports.isValidUTF8=function(t){return t.length<24?Sd(t):zh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=fe("utf-8-validate");No.exports.isValidUTF8=function(e){return e.length<32?Sd(e):t(e)}}catch{}});var Cd=ce((UR,Kh)=>{"use strict";var{Writable:JE}=fe("stream"),Uh=Gr(),{BINARY_TYPES:ZE,EMPTY_BUFFER:Gh,kStatusCode:XE,kWebSocket:YE}=Qt(),{concat:Id,toArrayBuffer:QE,unmask:ev}=Zi(),{isValidStatusCode:tv,isValidUTF8:Hh}=Hr(),Mo=Buffer[Symbol.species],gt=0,qh=1,jh=2,Wh=3,Ad=4,kd=5,Bo=6,Td=class extends JE{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ZE[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[YE]=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=gt}_write(e,r,i){if(this._opcode===8&&this._state==gt)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 Mo(i.buffer,i.byteOffset+e,i.length-e),new Mo(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 Mo(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 gt:this.getInfo(e);break;case qh:this.getPayloadLength16(e);break;case jh:this.getPayloadLength64(e);break;case Wh:this.getMask();break;case Ad:this.getData(e);break;case kd:case Bo: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[Uh.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=qh:this._payloadLength===127?this._state=jh: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=Wh:this._state=Ad}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ad}getData(e){let r=Gh;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&&ev(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=kd,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Uh.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===gt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=gt;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Id(i,r):this._binaryType==="arraybuffer"?o=QE(Id(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=gt):(this._state=Bo,setImmediate(()=>{this.emit("message",o,!0),this._state=gt,this.startLoop(e)}))}else{let o=Id(i,r);if(!this._skipUTF8Validation&&!Hh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===kd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=gt):(this._state=Bo,setImmediate(()=>{this.emit("message",o,!1),this._state=gt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Gh),this.end();else{let i=e.readUInt16BE(0);if(!tv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Mo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Hh(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=gt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=gt):(this._state=Bo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=gt,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[XE]=o,d}};Kh.exports=Td});var Pd=ce((HR,Jh)=>{"use strict";var{Duplex:GR}=fe("stream"),{randomFillSync:nv}=fe("crypto"),$h=Gr(),{EMPTY_BUFFER:rv,kWebSocket:iv,NOOP:sv}=Qt(),{isBlob:qr,isValidStatusCode:ov}=Hr(),{mask:Vh,toBuffer:Zn}=Zi(),mt=Symbol("kByteLength"),av=Buffer.alloc(4),Fo=8*1024,Xn,jr=Fo,At=0,cv=1,dv=2,Rd=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=At,this.onerror=sv,this[iv]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||av,r.generateMask?r.generateMask(i):(jr===Fo&&(Xn===void 0&&(Xn=Buffer.alloc(Fo)),nv(Xn,0,Fo),jr=0),i[0]=Xn[jr++],i[1]=Xn[jr++],i[2]=Xn[jr++],i[3]=Xn[jr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[mt]!==void 0?u=r[mt]:(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?(Vh(e,i,x,c,u),[x]):(Vh(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=rv;else{if(typeof e!="number"||!ov(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={[mt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==At?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):qr(e)?(o=e.size,c=!1):(e=Zn(e),o=e.length,c=Zn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[mt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};qr(e)?this._state!==At?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==At?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):qr(e)?(o=e.size,c=!1):(e=Zn(e),o=e.length,c=Zn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[mt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};qr(e)?this._state!==At?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==At?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[$h.extensionName],c=r.binary?2:1,d=r.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):qr(e)?(u=e.size,h=!1):(e=Zn(e),u=e.length,h=Zn.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={[mt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:d};qr(e)?this._state!==At?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==At?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[mt],this._state=dv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Dd,this,u,o);return}this._bufferedBytes-=i[mt];let d=Zn(c);r?this.dispatch(d,r,i,o):(this._state=At,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(lv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[$h.extensionName];this._bufferedBytes+=i[mt],this._state=cv,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");Dd(this,h,o);return}this._bufferedBytes-=i[mt],this._state=At,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===At&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][mt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][mt],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)}};Jh.exports=Rd;function Dd(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],c=o[o.length-1];typeof c=="function"&&c(e)}}function lv(t,e,r){Dd(t,e,r),t.onerror(e)}});var ix=ce((qR,rx)=>{"use strict";var{kForOnEventAttribute:Yi,kListener:Od}=Qt(),Zh=Symbol("kCode"),Xh=Symbol("kData"),Yh=Symbol("kError"),Qh=Symbol("kMessage"),ex=Symbol("kReason"),Wr=Symbol("kTarget"),tx=Symbol("kType"),nx=Symbol("kWasClean"),tn=class{constructor(e){this[Wr]=null,this[tx]=e}get target(){return this[Wr]}get type(){return this[tx]}};Object.defineProperty(tn.prototype,"target",{enumerable:!0});Object.defineProperty(tn.prototype,"type",{enumerable:!0});var Yn=class extends tn{constructor(e,r={}){super(e),this[Zh]=r.code===void 0?0:r.code,this[ex]=r.reason===void 0?"":r.reason,this[nx]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Zh]}get reason(){return this[ex]}get wasClean(){return this[nx]}};Object.defineProperty(Yn.prototype,"code",{enumerable:!0});Object.defineProperty(Yn.prototype,"reason",{enumerable:!0});Object.defineProperty(Yn.prototype,"wasClean",{enumerable:!0});var Kr=class extends tn{constructor(e,r={}){super(e),this[Yh]=r.error===void 0?null:r.error,this[Qh]=r.message===void 0?"":r.message}get error(){return this[Yh]}get message(){return this[Qh]}};Object.defineProperty(Kr.prototype,"error",{enumerable:!0});Object.defineProperty(Kr.prototype,"message",{enumerable:!0});var Qi=class extends tn{constructor(e,r={}){super(e),this[Xh]=r.data===void 0?null:r.data}get data(){return this[Xh]}};Object.defineProperty(Qi.prototype,"data",{enumerable:!0});var uv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Yi]&&o[Od]===e&&!o[Yi])return;let i;if(t==="message")i=function(c,d){let u=new Qi("message",{data:d?c:c.toString()});u[Wr]=this,zo(e,this,u)};else if(t==="close")i=function(c,d){let u=new Yn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Wr]=this,zo(e,this,u)};else if(t==="error")i=function(c){let d=new Kr("error",{error:c,message:c.message});d[Wr]=this,zo(e,this,d)};else if(t==="open")i=function(){let c=new tn("open");c[Wr]=this,zo(e,this,c)};else return;i[Yi]=!!r[Yi],i[Od]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Od]===e&&!r[Yi]){this.removeListener(t,r);break}}};rx.exports={CloseEvent:Yn,ErrorEvent:Kr,Event:tn,EventTarget:uv,MessageEvent:Qi};function zo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Uo=ce((jR,sx)=>{"use strict";var{tokenChars:es}=Hr();function Ut(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function fv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,h=-1,x=-1,m=-1,_=0;for(;_<t.length;_++)if(x=t.charCodeAt(_),d===void 0)if(m===-1&&es[x]===1)h===-1&&(h=_);else if(_!==0&&(x===32||x===9))m===-1&&h!==-1&&(m=_);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_);let y=t.slice(h,m);x===44?(Ut(e,y,r),r=Object.create(null)):d=y,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(u===void 0)if(m===-1&&es[x]===1)h===-1&&(h=_);else if(x===32||x===9)m===-1&&h!==-1&&(m=_);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_),Ut(r,t.slice(h,m),!0),x===44&&(Ut(e,d,r),r=Object.create(null),d=void 0),h=m=-1}else if(x===61&&h!==-1&&m===-1)u=t.slice(h,_),h=m=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(o){if(es[x]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);h===-1?h=_:i||(i=!0),o=!1}else if(c)if(es[x]===1)h===-1&&(h=_);else if(x===34&&h!==-1)c=!1,m=_;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(x===34&&t.charCodeAt(_-1)===61)c=!0;else if(m===-1&&es[x]===1)h===-1&&(h=_);else if(h!==-1&&(x===32||x===9))m===-1&&(m=_);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_);let y=t.slice(h,m);i&&(y=y.replace(/\\/g,""),i=!1),Ut(r,u,y),x===44&&(Ut(e,d,r),r=Object.create(null),d=void 0),u=void 0,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=_);let S=t.slice(h,m);return d===void 0?Ut(e,S,r):(u===void 0?Ut(r,S,!0):i?Ut(r,u,S.replace(/\\/g,"")):Ut(r,u,S),Ut(e,d,r)),e}function hv(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(", ")}sx.exports={format:hv,parse:fv}});var jo=ce(($R,mx)=>{"use strict";var xv=fe("events"),pv=fe("https"),gv=fe("http"),cx=fe("net"),mv=fe("tls"),{randomBytes:wv,createHash:_v}=fe("crypto"),{Duplex:WR,Readable:KR}=fe("stream"),{URL:Ld}=fe("url"),Rn=Gr(),yv=Cd(),bv=Pd(),{isBlob:Ev}=Hr(),{BINARY_TYPES:ox,CLOSE_TIMEOUT:vv,EMPTY_BUFFER:Go,GUID:Sv,kForOnEventAttribute:Nd,kListener:Iv,kStatusCode:Av,kWebSocket:Ke,NOOP:dx}=Qt(),{EventTarget:{addEventListener:kv,removeEventListener:Tv}}=ix(),{format:Cv,parse:Rv}=Uo(),{toBuffer:Dv}=Zi(),lx=Symbol("kAborted"),Md=[8,13],nn=["CONNECTING","OPEN","CLOSING","CLOSED"],Pv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_e=class t extends xv{constructor(e,r,i){super(),this._binaryType=ox[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Go,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(i=r,r=[]):r=[r]),ux(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ox.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 bv(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",Nv),o.on("drain",Mv),o.on("error",Bv),o.on("message",Fv),o.on("ping",zv),o.on("pong",Uv),c.onerror=Gv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",xx),e.on("data",qo),e.on("end",px),e.on("error",gx),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Rn.extensionName]&&this._extensions[Rn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){lt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),hx(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Go,r,i)}pong(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Go,r,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(i=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Rn.extensionName]||(o.compress=!1),this._sender.send(e||Go,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){lt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(_e,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(_e.prototype,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(_e,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(_e.prototype,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(_e,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(_e.prototype,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(_e,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});Object.defineProperty(_e.prototype,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_e.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_e.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Nd])return e[Iv];return null},set(e){for(let r of this.listeners(t))if(r[Nd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Nd]:!0})}})});_e.prototype.addEventListener=kv;_e.prototype.removeEventListener=Tv;mx.exports=_e;function ux(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:vv,protocolVersion:Md[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Md.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Md.join(", ")})`);let c;if(e instanceof Ld)c=e;else try{c=new Ld(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let 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;Ho(t,I);return}let x=d?443:80,m=wv(16).toString("base64"),_=d?pv.request:gv.request,S=new Set,y;if(o.createConnection=o.createConnection||(d?Lv:Ov),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":m,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(y=new Rn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Cv({[Rn.extensionName]:y.offer()})),r.length){for(let I of r){if(typeof I!="string"||!Pv.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,C]of Object.entries(I))i.headers[A.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!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")),v=t._req=_(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=_(o);o.timeout&&v.on("timeout",()=>{lt(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[lx]||(v=t._req=null,Ho(t,I))}),v.on("response",I=>{let A=I.headers.location,C=I.statusCode;if(A&&o.followRedirects&&C>=300&&C<400){if(++t._redirects>o.maxRedirects){lt(t,v,"Maximum redirects exceeded");return}v.abort();let P;try{P=new Ld(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);Ho(t,R);return}ux(t,P,r,i)}else t.emit("unexpected-response",v,I)||lt(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,C)=>{if(t.emit("upgrade",I),t.readyState!==_e.CONNECTING)return;v=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){lt(t,A,"Invalid Upgrade header");return}let b=_v("sha1").update(m+Sv).digest("base64");if(I.headers["sec-websocket-accept"]!==b){lt(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){lt(t,A,O);return}R&&(t._protocol=R);let M=I.headers["sec-websocket-extensions"];if(M!==void 0){if(!y){lt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=Rv(M)}catch{lt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(N);if(J.length!==1||J[0]!==Rn.extensionName){lt(t,A,"Server indicated an extension that was not requested");return}try{y.accept(N[Rn.extensionName])}catch{lt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Rn.extensionName]=y}t.setSocket(A,C,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(v,t):v.end()}function Ho(t,e){t._readyState=_e.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Ov(t){return t.path=t.socketPath,cx.connect(t)}function Lv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=cx.isIP(t.host)?"":t.host),mv.connect(t)}function lt(t,e,r){t._readyState=_e.CLOSING;let i=new Error(r);Error.captureStackTrace(i,lt),e.setHeader?(e[lx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ho,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Bd(t,e,r){if(e){let i=Ev(e)?e.size:Dv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${nn[t.readyState]})`);process.nextTick(r,i)}}function Nv(t,e){let r=this[Ke];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Ke]!==void 0&&(r._socket.removeListener("data",qo),process.nextTick(fx,r._socket),t===1005?r.close():r.close(t,e))}function Mv(){let t=this[Ke];t.isPaused||t._socket.resume()}function Bv(t){let e=this[Ke];e._socket[Ke]!==void 0&&(e._socket.removeListener("data",qo),process.nextTick(fx,e._socket),e.close(t[Av])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ax(){this[Ke].emitClose()}function Fv(t,e){this[Ke].emit("message",t,e)}function zv(t){let e=this[Ke];e._autoPong&&e.pong(t,!this._isServer,dx),e.emit("ping",t)}function Uv(t){this[Ke].emit("pong",t)}function fx(t){t.resume()}function Gv(t){let e=this[Ke];e.readyState!==_e.CLOSED&&(e.readyState===_e.OPEN&&(e._readyState=_e.CLOSING,hx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function hx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function xx(){let t=this[Ke];if(this.removeListener("close",xx),this.removeListener("data",qo),this.removeListener("end",px),t._readyState=_e.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",ax),t._receiver.on("finish",ax))}function qo(t){this[Ke]._receiver.write(t)||this.pause()}function px(){let t=this[Ke];t._readyState=_e.CLOSING,t._receiver.end(),this.end()}function gx(){let t=this[Ke];this.removeListener("error",gx),this.on("error",dx),t&&(t._readyState=_e.CLOSING,this.destroy())}});var Ex=ce((JR,bx)=>{"use strict";var VR=jo(),{Duplex:Hv}=fe("stream");function _x(t){t.emit("close")}function qv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function yx(t){this.removeListener("error",yx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function jv(t,e){let r=!0,i=new Hv({...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(_x,i);return}let d=!1;t.once("error",function(h){d=!0,c(h)}),t.once("close",function(){d||c(o),process.nextTick(_x,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",qv),i.on("error",yx),i}bx.exports=jv});var Fd=ce((ZR,vx)=>{"use strict";var{tokenChars:Wv}=Hr();function Kv(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&&Wv[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}vx.exports={parse:Kv}});var Rx=ce((YR,Cx)=>{"use strict";var $v=fe("events"),Wo=fe("http"),{Duplex:XR}=fe("stream"),{createHash:Vv}=fe("crypto"),Sx=Uo(),Qn=Gr(),Jv=Fd(),Zv=jo(),{CLOSE_TIMEOUT:Xv,GUID:Yv,kWebSocket:Qv}=Qt(),eS=/^[+/0-9A-Za-z]{22}==$/,Ix=0,Ax=1,Tx=2,zd=class extends $v{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Xv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Zv,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Wo.createServer((i,o)=>{let c=Wo.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=tS(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=Ix}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===Tx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ts,this);return}if(e&&this.once("close",e),this._state!==Ax)if(this._state=Ax,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ts,this):process.nextTick(ts,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{ts(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",kx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){er(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){er(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!eS.test(c)){er(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){er(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ns(r,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=Jv.parse(h)}catch{er(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&m!==void 0){let S=new Qn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=Sx.parse(m);y[Qn.extensionName]&&(S.accept(y[Qn.extensionName]),_[Qn.extensionName]=S)}catch{er(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,(y,v,I,A)=>{if(!y)return ns(r,v||401,I,A);this.completeUpgrade(_,c,x,e,r,i,o)});return}if(!this.options.verifyClient(S))return ns(r,401)}this.completeUpgrade(_,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[Qv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ix)return ns(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Vv("sha1").update(r+Yv).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let _=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;_&&(x.push(`Sec-WebSocket-Protocol: ${_}`),m._protocol=_)}if(e[Qn.extensionName]){let _=e[Qn.extensionName].params,S=Sx.format({[Qn.extensionName]:[_]});x.push(`Sec-WebSocket-Extensions: ${S}`),m._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&cs(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Ug,mkdirSync as qg}from"node:fs";import{join as Gg}from"node:path";function vl(t){let e=t.retentionDays??Wg,r=t.clock??(()=>Dn(new Date));ls={bridgeSink:new ei(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ei(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();cs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])cs(t.agentLogsDir(o),"agent",i,e)}function Kg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Sl(t){Ta=t}function Il(t){return ar[Ta]<=ar[t]}function Al(t,e){let r=ar[t];return r===void 0?!0:r>=ar[e]}function us(t){bl={...t}}function kl(t){let e=(u,f=2)=>String(u).padStart(f,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),d=e(o%60);return`${Dn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function rt(t,e,r,i,o){try{let c=`${JSON.stringify({ts:kl(new Date),level:e,module:r,msg:i,...o})}
11
+ `;qg(t,{recursive:!0}),Ug(Gg(t,or("bridge",Dn(new Date))),c)}catch{}}function $g(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function ds(t,e,r,i,o){if(ar[t]<ar[Ta])return;let c=`${JSON.stringify({ts:kl(new Date),level:t,module:e,msg:r,...bl,...i})}
12
+ `;if(ls){let d=$g(o,i),u=d?Kg(ls,d):ls.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?jg.write(c):Hg.write(c)}function W(t,e){return{debug:(r,i)=>ds("debug",t,r,i,e),info:(r,i)=>ds("info",t,r,i,e),warn:(r,i)=>ds("warn",t,r,i,e),error:(r,i)=>ds("error",t,r,i,e),child:r=>W(`${t}.${r}`,e),forAgent:r=>W(t,r)}}var ar,Ta,Hg,jg,bl,Wg,ls,ne=nt(()=>{"use strict";sr();ka();ar={debug:10,info:20,warn:30,error:40},Ta=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Hg=process.stdout,jg=process.stderr,bl={},Wg=Je("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ls=null});var k,$e=nt(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Pl={};Ia(Pl,{ACP_WRAPPER_NPM_PACKAGES:()=>fs,_resetAcpInstallerForTests:()=>Qg,_setBinaryPathCacheForTests:()=>em,buildAcpSpawn:()=>ni,ensureAcpInstalled:()=>cr,getAcpBinaryPath:()=>hs,pickWhichLine:()=>Pa,probeAcpVersion:()=>Xg,resolveAcpCommand:()=>Rl});import{readFileSync as Tl}from"node:fs";import{createRequire as Vg}from"node:module";import{dirname as Jg,resolve as Zg}from"node:path";function Pa(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function Yg(t){let e=Cl.resolve(`${t.npmPackage}/package.json`),r=Jg(e),i=JSON.parse(Tl(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 Zg(r,o)}async function cr(t,e){let r=Ra[t];if(!r)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ti.get(t);if(i)return i;try{let o=Yg(r);return ti.set(t,o),Ca.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Ca.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(o)}),new k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
+ `),{cause:o})}}async function Xg(t){let e=Ra[t];if(e)try{let r=Cl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Tl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Ca.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function hs(t){return ti.get(t)}function Rl(t,e){if(e)return e;let r=hs(t);if(!r)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function ni(t,e,r){if(e)return{command:e,args:[...r]};let i=Rl(t);return{command:process.execPath,args:[i,...r]}}function Qg(){ti.clear()}function em(t,e){ti.set(t,e)}var Ca,Ra,fs,Cl,ti,an=nt(()=>{"use strict";$e();ne();Ca=W("agents.acp-installer"),Ra={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},fs=Object.values(Ra).filter(t=>t!==void 0).map(t=>t.npmPackage),Cl=Vg(import.meta.url),ti=new Map});import{chmod as nm,mkdir as rm,readFile as im,rename as sm,rm as om,writeFile as am}from"node:fs/promises";import{dirname as cm}from"node:path";async function dr(t){try{let e=await im(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function cn(t,e,r){await rm(cm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await am(i,e,{encoding:"utf8",mode:r?.mode}),await sm(i,t),r?.mode!==void 0&&await nm(t,r.mode)}catch(o){throw await om(i,{force:!0}).catch(()=>{}),o}}async function lr(t,e,r){await cn(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var dn=nt(()=>{"use strict"});import{promises as Ll,readdirSync as dm}from"node:fs";import{homedir as lm}from"node:os";import{sep as um,join as Ce,resolve as Nl}from"node:path";function ee(t){let e=t??lm(),r=Ce(e,".coze"),i=Ce(r,"bridge"),o=Ce(i,"lib"),c=Ce(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Ce(o,"index.js"),binDir:Ce(i,"bin"),pidFile:Ce(i,"bridge.pid"),portFile:Ce(i,"bridge.port"),tokenFile:Ce(i,"bridge.token"),patTokenFile:Ce(i,"pat-token"),agentEnvFile:Ce(i,"agent-env.json"),logFile:Ce(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Ce(c,"daemon-stdio.log"),installLock:Ce(i,"install.lock"),configFile:Ce(i,"config.json"),agentsRoot:Ce(r,"agents")}}function Ze(t,e=ee()){let r=Ce(e.agentsRoot,t);return{root:r,config:Ce(r,"config.json"),workspace:Ce(r,"workspace"),logs:Ce(r,"logs")}}function xs(t=ee()){try{return dm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ri(t,e){let r=await Ll.realpath(Nl(t)).catch(()=>null);if(!r)return!1;let i=await Ll.realpath(Nl(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+um)}var Me=nt(()=>{"use strict"});var gs={};Ia(gs,{AGENT_CONFIG_FILE_MODE:()=>ps,enforceAgentConfigMode:()=>xm,loadAgentConfig:()=>Re,persistAgentSessions:()=>ii,persistAgentSkills:()=>si,saveAgentConfig:()=>Ue});import{chmod as fm,stat as hm}from"node:fs/promises";function Re(t,e){return dr(Ze(t,e).config)}function Ue(t,e){return lr(Ze(t.agentId,e).config,t,{mode:ps})}async function xm(t,e){if(process.platform==="win32")return;let r=Ze(t,e).config;try{let i=await hm(r);if(!i.isFile())return;let o=i.mode&511;o!==ps&&(await fm(r,ps),Ml.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Ml.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ii(t,e,r){let i=await Re(t,r);i&&(i.sessions=Object.fromEntries(e),await Ue(i,r))}async function si(t,e,r){let i=await Re(t,r);i&&(i.skills=e,await Ue(i,r))}var Ml,ps,ln=nt(()=>{"use strict";dn();ne();Me();Ml=W("agent-config"),ps=384});var La=ce((oI,zl)=>{zl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var ws=ce(ql=>{var Ul={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function ym(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(Ul))ql[t]=ym(Ul[t])});var Kl=ce((cI,Wl)=>{var Em=he("fs"),Be=he("path"),Gl=La(),bm=ws(),vm=typeof process=="object"&&process.platform==="win32",Hl=t=>typeof t=="object"&&t!==null,jl=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Ie(t){this.sep=Be.sep,this.fs=Em,Hl(t)&&Hl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Wl.exports=Ie;Ie.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var 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 bm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Ie.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var 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,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!r)return o(!1);c.fs.stat(t,function(u,f){if(d&&f.isDirectory())return o(!1);var x=Be.dirname(t);c.fs.exists(x,function(g){g||c.makeDir(x),c.fs.open(t,"w",438,function(m,S){m?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,b){c.fs.write(b,e,0,e.length,0,function(){c.fs.close(b,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ie.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let f=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(r(f,o,c)))}),d}return r(t,void 0,!0)};Ie.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Be.join(t,u),r.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Be.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(g,m){if(g)return e(g);i=i.concat(m),--d||e(null,i)}):--d||e(null,i))})})})};Ie.prototype.getAttributes=function(){};Ie.prototype.setAttributes=function(){};Ie.crc32update=function(t,e){return jl[(t^e)&255]^t>>>8};Ie.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Ie.crc32update(r,t[i++]);return~r>>>0};Ie.methodToString=function(t){switch(t){case Gl.STORED:return"STORED ("+t+")";case Gl.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 r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ie.sanitize=function(t,e){t=Be.resolve(Be.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Be.normalize(Be.join(t,r.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,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Ie.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Ie.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ie.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};Ie.isWin=vm;Ie.crcTable=jl});var Vl=ce((dI,$l)=>{var Sm=he("path");$l.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=Sm.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 Zl=ce((lI,Jl)=>{Jl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var hr=ce((uI,fr)=>{fr.exports=Kl();fr.exports.Constants=La();fr.exports.Errors=ws();fr.exports.FileAttr=Vl();fr.exports.decoder=Zl()});var Xl=ce((fI,Yl)=>{var un=hr(),U=un.Constants;Yl.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,f=0,x=0,g=0,m=0,S=0,y=0,b=0;t|=un.isWin?2560:768,r|=U.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,D=E=>Math.max(0,E)&255;return o=un.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return r},set flags(E){r=E},get flags_efs(){return(r&U.FLG_EFS)>0},set flags_efs(E){E?r|=U.FLG_EFS:r&=~U.FLG_EFS},get flags_desc(){return(r&U.FLG_DESC)>0},set flags_desc(E){E?r|=U.FLG_DESC:r&=~U.FLG_DESC},get method(){return i},set method(E){switch(E){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=E},get time(){return un.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=un.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=A(E)},get timeHighByte(){return D(o>>>8)},get crc(){return c},set crc(E){c=A(E)},get compressedSize(){return d},set compressedSize(E){d=A(E)},get size(){return u},set size(E){u=A(E)},get fileNameLength(){return f},set fileNameLength(E){f=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return g},set commentLength(E){g=E},get diskNumStart(){return m},set diskNumStart(E){m=A(E)},get inAttr(){return S},set inAttr(E){S=A(E)},get attr(){return y},set attr(E){y=A(E)},get fileAttr(){return(y||0)>>16&4095},get offset(){return b},set offset(E){b=A(E)},get encrypted(){return(r&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+f+x+g},get realDataOffset(){return b+U.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var R=E.slice(b,b+U.LOCHDR);if(R.readUInt32LE(0)!==U.LOCSIG)throw un.Errors.INVALID_LOC();I.version=R.readUInt16LE(U.LOCVER),I.flags=R.readUInt16LE(U.LOCFLG),I.flags_desc=(I.flags&U.FLG_DESC)>0,I.method=R.readUInt16LE(U.LOCHOW),I.time=R.readUInt32LE(U.LOCTIM),I.crc=R.readUInt32LE(U.LOCCRC),I.compressedSize=R.readUInt32LE(U.LOCSIZ),I.size=R.readUInt32LE(U.LOCLEN),I.fnameLen=R.readUInt16LE(U.LOCNAM),I.extraLen=R.readUInt16LE(U.LOCEXT);let O=b+U.LOCHDR+I.fnameLen,F=O+I.extraLen;return E.slice(O,F)},loadFromBinary:function(E){if(E.length!==U.CENHDR||E.readUInt32LE(0)!==U.CENSIG)throw un.Errors.INVALID_CEN();t=E.readUInt16LE(U.CENVEM),e=E.readUInt16LE(U.CENVER),r=E.readUInt16LE(U.CENFLG),i=E.readUInt16LE(U.CENHOW),o=E.readUInt32LE(U.CENTIM),c=E.readUInt32LE(U.CENCRC),d=E.readUInt32LE(U.CENSIZ),u=E.readUInt32LE(U.CENLEN),f=E.readUInt16LE(U.CENNAM),x=E.readUInt16LE(U.CENEXT),g=E.readUInt16LE(U.CENCOM),m=E.readUInt16LE(U.CENDSK),S=E.readUInt16LE(U.CENATT),y=E.readUInt32LE(U.CENATX),b=E.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(U.LOCHDR);return E.writeUInt32LE(U.LOCSIG,0),E.writeUInt16LE(e,U.LOCVER),E.writeUInt16LE(r,U.LOCFLG),E.writeUInt16LE(i,U.LOCHOW),E.writeUInt32LE(o,U.LOCTIM),E.writeUInt32LE(c,U.LOCCRC),E.writeUInt32LE(d,U.LOCSIZ),E.writeUInt32LE(u,U.LOCLEN),E.writeUInt16LE(f,U.LOCNAM),E.writeUInt16LE(I.extraLen,U.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(U.CENHDR+f+x+g);return E.writeUInt32LE(U.CENSIG,0),E.writeUInt16LE(t,U.CENVEM),E.writeUInt16LE(e,U.CENVER),E.writeUInt16LE(r,U.CENFLG),E.writeUInt16LE(i,U.CENHOW),E.writeUInt32LE(o,U.CENTIM),E.writeUInt32LE(c,U.CENCRC),E.writeUInt32LE(d,U.CENSIZ),E.writeUInt32LE(u,U.CENLEN),E.writeUInt16LE(f,U.CENNAM),E.writeUInt16LE(x,U.CENEXT),E.writeUInt16LE(g,U.CENCOM),E.writeUInt16LE(m,U.CENDSK),E.writeUInt16LE(S,U.CENATT),E.writeUInt32LE(y,U.CENATX),E.writeUInt32LE(b,U.CENOFF),E},toJSON:function(){let E=function(R){return R+" bytes"};return{made:t,version:e,flags:r,method:un.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(f),extraLength:E(x),commentLength:E(g),diskNumStart:m,inAttr:S,attr:y,offset:b,centralHeaderSize:E(U.CENHDR+f+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var eu=ce((hI,Ql)=>{var xr=hr(),be=xr.Constants;Ql.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 xr.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=xr.readBigUInt64LE(c,be.ZIP64SUB),e=xr.readBigUInt64LE(c,be.ZIP64TOT),r=xr.readBigUInt64LE(c,be.ZIP64SIZE),i=xr.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 f=d.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ma=ce(Na=>{Na.EntryHeader=Xl();Na.MainHeader=eu()});var nu=ce((pI,tu)=>{tu.exports=function(t){var e=he("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],d=0;o.on("data",function(u){c.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),f=0;u.fill(0);for(var x=0;x<c.length;x++){var g=c[x];g.copy(u,f),f+=g.length}i&&i(u)}),o.end(t)}}}});var iu=ce((gI,ru)=>{var Im=+(process.versions?process.versions.node:"").split(".")[0]||0;ru.exports=function(t,e){var r=he("zlib");let i=Im>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),d=[],u=0;c.on("data",function(f){d.push(f),u+=f.length}),c.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var g=0;g<d.length;g++){var m=d[g];m.copy(f,x),x+=m.length}o&&o(f)}),c.end(t)}}}});var du=ce((mI,cu)=>{"use strict";var{randomFillSync:su}=he("crypto"),Am=ws(),km=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}),au=(t,e)=>Math.imul(t,e)>>>0,ou=(t,e)=>km[(t^e)&255]^t>>>8,oi=()=>typeof su=="function"?su(Buffer.alloc(12)):oi.node();oi.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var _s={genSalt:oi};function ys(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])}ys.prototype.updateKeys=function(t){let e=this.keys;return e[0]=ou(e[0],t),e[1]+=e[0]&255,e[1]=au(e[1],134775813)+1,e[2]=ou(e[2],e[1]>>>24),t};ys.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return au(t,t^1)>>8&255};function Tm(t){let e=new ys(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 Cm(t){let e=new ys(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 Rm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Tm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Am.WRONG_PASSWORD();return i(t.slice(12))}function Pm(t){Buffer.isBuffer(t)&&t.length>=12?_s.genSalt=function(){return t.slice(0,12)}:t==="node"?_s.genSalt=oi.node:_s.genSalt=oi}function Dm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Cm(r),c=_s.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)}cu.exports={decrypt:Rm,encrypt:Dm,_salter:Pm}});var lu=ce(Es=>{Es.Deflater=nu();Es.Inflater=iu();Es.ZipCrypto=du()});var Fa=ce((_I,uu)=>{var de=hr(),Om=Ma(),Ae=de.Constants,Ba=lu();uu.exports=function(t,e){var r=new Om.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let g=t,m=typeof g.decoder=="object"?g.decoder:de.decoder;x=m.hasOwnProperty("efs")?m.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function y(E){if(!r.flags_desc&&!r.localHeader.flags_desc){if(de.crc32(E)!==r.localHeader.crc)return!1}else{let R={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==Ae.LOCSIG||e.readUInt32LE(O)==Ae.CENSIG)throw de.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Ae.EXTSIG)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!==r.compressedSize||R.size!==r.size||R.crc!==r.crc)throw de.Errors.DESCRIPTOR_FAULTY();if(de.crc32(E)!==R.crc)return!1}return!0}function b(E,R,O){if(typeof R>"u"&&typeof E=="string"&&(O=E,E=void 0),c)return E&&R&&R(Buffer.alloc(0),de.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return E&&R&&R(F),F;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw de.Errors.INVALID_PASS_PARAM();F=Ba.ZipCrypto.decrypt(F,r,O)}var B=Buffer.alloc(r.size);switch(r.method){case de.Constants.STORED:if(F.copy(B),y(B))return E&&R&&R(B),B;throw E&&R&&R(B,de.Errors.BAD_CRC()),de.Errors.BAD_CRC();case de.Constants.DEFLATED:var Z=new Ba.Inflater(F,r.size);if(E)Z.inflateAsync(function(J){J.copy(J,0),R&&(y(J)?R(J):R(J,de.Errors.BAD_CRC()))});else{if(Z.inflate(B).copy(B,0),!y(B))throw de.Errors.BAD_CRC(`"${m.decode(i)}"`);return B}break;default:throw E&&R&&R(Buffer.alloc(0),de.Errors.UNKNOWN_METHOD()),de.Errors.UNKNOWN_METHOD()}}function I(E,R){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&R&&R(S()),S();if(d.length&&!c){var O;switch(r.method){case de.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(d.length),d.copy(O),E&&R&&R(O),O;default:case de.Constants.DEFLATED:var F=new Ba.Deflater(d);if(E)F.deflateAsync(function(Z){O=Buffer.alloc(Z.length),r.compressedSize=Z.length,Z.copy(O),R&&R(O)});else{var B=F.deflate();return r.compressedSize=B.length,B}F=null;break}}else if(E&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,R){return de.readBigUInt64LE(E,R)}function T(E){try{for(var R=0,O,F,B;R+4<E.length;)O=E.readUInt16LE(R),R+=2,F=E.readUInt16LE(R),R+=2,B=E.slice(R,R+F),R+=F,Ae.ID_ZIP64===O&&D(B)}catch{throw de.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(E){var R,O,F,B;E.length>=Ae.EF_ZIP64_SCOMP&&(R=A(E,Ae.EF_ZIP64_SUNCOMP),r.size===Ae.EF_ZIP64_OR_32&&(r.size=R)),E.length>=Ae.EF_ZIP64_RHO&&(O=A(E,Ae.EF_ZIP64_SCOMP),r.compressedSize===Ae.EF_ZIP64_OR_32&&(r.compressedSize=O)),E.length>=Ae.EF_ZIP64_DSN&&(F=A(E,Ae.EF_ZIP64_RHO),r.offset===Ae.EF_ZIP64_OR_32&&(r.offset=F)),E.length>=Ae.EF_ZIP64_DSN+4&&(B=E.readUInt32LE(Ae.EF_ZIP64_DSN),r.diskNumStart===Ae.EF_ZIP64_OR_16&&(r.diskNumStart=B))}return{get entryName(){return m.decode(i)},get rawEntryName(){return i},set entryName(E){i=de.toBuffer(E,m.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(E){u=E,r.extraLength=E.length,T(E)},get comment(){return m.decode(o)},set comment(E){if(o=de.toBuffer(E,m.encode),r.commentLength=o.length,o.length>65535)throw de.Errors.COMMENT_TOO_LONG()},get name(){var E=m.decode(i);return c?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){d=de.toBuffer(E,de.decoder.encode),!c&&d.length?(r.size=d.length,r.method=de.Constants.DEFLATED,r.crc=de.crc32(E),r.changed=!0):r.method=de.Constants.STORED},getData:function(E){return r.changed?d:b(!1,null,E)},getDataAsync:function(E,R){r.changed?E(d):b(!0,E,R)},set attr(E){r.attr=E},get attr(){return r.attr},set header(E){r.loadFromBinary(E)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var E=r.centralHeaderToBinary(),R=de.Constants.CENHDR;return i.copy(E,R),R+=i.length,u.copy(E,R),R+=r.extraLength,o.copy(E,R),E},packLocalHeader:function(){let E=0;r.flags_efs=this.efs,r.extraLocalLength=f.length;let R=r.localHeaderToBinary(),O=Buffer.alloc(R.length+i.length+r.extraLocalLength);return R.copy(O,E),E+=R.length,i.copy(O,E),E+=i.length,f.copy(O,E),E+=f.length,O},toJSON:function(){let E=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:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var xu=ce((yI,hu)=>{var fu=Fa(),Lm=Ma(),Ve=hr();hu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Lm.MainHeader,d=!1,u=null;let f=new Set,x=e,{noSort:g,decoder:m}=x;t?b(x.readEntries):d=!0;function S(){let A=new Set;for(let T of Object.keys(i)){let D=T.split("/");if(D.pop(),!!D.length)for(let E=0;E<D.length;E++){let R=D.slice(0,E+1).join("/")+"/";A.add(R)}}for(let T of A)if(!(T in i)){let D=new fu(x);D.entryName=T,D.attr=16,D.temporary=!0,r.push(D),i[D.entryName]=D,f.add(D)}}function y(){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 A=c.offset,T=0;T<r.length;T++){var D=A,E=new fu(x,t);E.header=t.slice(D,D+=Ve.Constants.CENHDR),E.entryName=t.slice(D,D+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(D,D+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(D,D+E.header.commentLength)),A+=E.header.centralHeaderSize,r[T]=E,i[E.entryName]=E}f.clear(),S()}function b(A){var T=t.length-Ve.Constants.ENDHDR,D=Math.max(0,T-65535),E=D,R=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(D=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===Ve.Constants.ENDSIG){O=T,F=T,R=T+Ve.Constants.ENDHDR,E=T-Ve.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Ve.Constants.END64SIG){E=D;continue}if(t.readUInt32LE(T)===Ve.Constants.ZIP64SIG){O=T,R=T+Ve.readBigUInt64LE(t,T+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(F+Ve.Constants.ENDHDR)),A&&y()}function I(){r.length>1&&!g&&r.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||y(),r.filter(A=>!f.has(A))},get comment(){return m.decode(o)},set comment(A){o=Ve.toBuffer(A,m.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||y(),i[A]||null},setEntry:function(A){d||y(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,T=!0){d||y();let D=i[A];this.getEntryChildren(D,T).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let T=i[A],D=r.indexOf(T);D>=0&&(r.splice(D,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,T=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&T){let D=[],E=A.entryName;for(let R of r)R.entryName.startsWith(E)&&D.push(R);return D}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){d||y(),I();let A=[],T=[],D=0,E=0;c.size=0,c.offset=0;let R=0;for(let B of this.entries){let Z=B.getCompressedData();B.header.offset=E;let J=B.packLocalHeader(),re=J.length+Z.length;E+=re,A.push(J),A.push(Z);let X=B.packCentralHeader();T.push(X),c.size+=X.length,D+=re+X.length,R++}D+=c.mainHeaderSize,c.offset=E,c.totalEntries=R,E=0;let O=Buffer.alloc(D);for(let B of A)B.copy(O,E),E+=B.length;for(let B of T)B.copy(O,E),E+=B.length;let F=c.toBinary();return o&&o.copy(F,Ve.Constants.ENDHDR),F.copy(O,E),t=O,d=!1,O},toAsyncBuffer:function(A,T,D,E){try{d||y(),I();let R=[],O=[],F=0,B=0,Z=0;c.size=0,c.offset=0;let J=function(re){if(re.length>0){let X=re.shift(),oe=X.entryName+X.extra.toString();D&&D(oe),X.getCompressedDataAsync(function(ae){E&&E(oe),X.header.offset=B;let P=X.packLocalHeader(),q=P.length+ae.length;B+=q,R.push(P),R.push(ae);let $=X.packCentralHeader();O.push($),c.size+=$.length,F+=q+$.length,Z++,J(re)})}else{F+=c.mainHeaderSize,c.offset=B,c.totalEntries=Z,B=0;let X=Buffer.alloc(F);R.forEach(function(ae){ae.copy(X,B),B+=ae.length}),O.forEach(function(ae){ae.copy(X,B),B+=ae.length});let oe=c.toBinary();o&&o.copy(oe,Ve.Constants.ENDHDR),oe.copy(X,B),t=X,d=!1,A(X)}};J(Array.from(this.entries))}catch(R){T(R)}}}}});var mu=ce((EI,gu)=>{var Se=hr(),ve=he("path"),Nm=Fa(),Mm=xu(),On=(...t)=>Se.findLast(t,e=>typeof e=="boolean"),pu=(...t)=>Se.findLast(t,e=>typeof e=="string"),Bm=(...t)=>Se.findLast(t,e=>typeof e=="function"),Fm={noSort:!1,readEntries:!1,method:Se.Constants.NONE,fs:null};gu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Fm);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=Se.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Se(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Se.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Se.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw Se.Errors.INVALID_FILENAME();let c=new Mm(r,i),{canonical:d,sanitize:u,zipnamefix:f}=Se;function x(y){if(y&&c){var b;if(typeof y=="string"&&(b=c.getEntry(ve.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(b=c.getEntry(y.entryName)),b)return b}return null}function g(y){let{join:b,normalize:I,sep:A}=ve.posix;return b(ve.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function m(y){return y instanceof RegExp?(function(b){return function(I){return b.test(I)}})(y):typeof y!="function"?()=>!0:y}let S=(y,b)=>{let I=b.slice(-1);return I=I===o.sep?o.sep:"",ve.relative(y,b)+I};return{readFile:function(y,b){var I=x(y);return I&&I.getData(b)||null},childCount:function(y){let b=x(y);if(b)return c.getChildCount(b)},readFileAsync:function(y,b){var I=x(y);I?I.getDataAsync(b):b(null,"getEntry failed for:"+y)},readAsText:function(y,b){var I=x(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(b||"utf8")}return""},readAsTextAsync:function(y,b,I){var A=x(y);A?A.getDataAsync(function(T,D){if(D){b(T,D);return}T&&T.length?b(T.toString(I||"utf8")):b("")}):b("")},deleteFile:function(y,b=!0){var I=x(y);I&&c.deleteFile(I.entryName,b)},deleteEntry:function(y){var b=x(y);b&&c.deleteEntry(b.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,b){var I=x(y);I&&(I.comment=b)},getZipEntryComment:function(y){var b=x(y);return b&&b.comment||""},updateFile:function(y,b){var I=x(y);I&&I.setData(b)},addLocalFile:function(y,b,I,A){if(o.fs.existsSync(y)){b=b?g(b):"";let T=ve.win32.basename(ve.win32.normalize(y));b+=I||T;let D=o.fs.statSync(y),E=D.isFile()?o.fs.readFileSync(y):Buffer.alloc(0);D.isDirectory()&&(b+=o.sep),this.addFile(b,E,A,D)}else throw Se.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,b){y=typeof y=="object"?y:{localPath:y};let I=ve.resolve(y.localPath),{comment:A}=y,{zipPath:T,zipName:D}=y,E=this;o.fs.stat(I,function(R,O){if(R)return b(R,!1);T=T?g(T):"";let F=ve.win32.basename(ve.win32.normalize(I));if(T+=D||F,O.isFile())o.fs.readFile(I,function(B,Z){return B?b(B,!1):(E.addFile(T,Z,A,O),setImmediate(b,void 0,!0))});else if(O.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),A,O),setImmediate(b,void 0,!0)})},addLocalFolder:function(y,b,I){if(I=m(I),b=b?g(b):"",y=ve.normalize(y),o.fs.existsSync(y)){let A=o.findFiles(y),T=this;if(A.length)for(let D of A){let E=ve.join(b,S(y,D));I(E)&&T.addLocalFile(D,ve.dirname(E))}}else throw Se.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,b,I,A){A=m(A),I=I?g(I):"",y=ve.normalize(y);var T=this;o.fs.open(y,"r",function(D){if(D&&D.code==="ENOENT")b(void 0,Se.Errors.FILE_NOT_FOUND(y));else if(D)b(void 0,D);else{var E=o.findFiles(y),R=-1,O=function(){if(R+=1,R<E.length){var F=E[R],B=S(y,F).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(B)?o.fs.stat(F,function(Z,J){Z&&b(void 0,Z),J.isFile()?o.fs.readFile(F,function(re,X){re?b(void 0,re):(T.addFile(I+B,X,"",J),O())}):(T.addFile(I+B+"/",Buffer.alloc(0),"",J),O())}):process.nextTick(()=>{O()})}else b(!0,void 0)};O()}})},addLocalFolderAsync2:function(y,b){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=ve.resolve(g(y.localPath));let{zipPath:A,filter:T,namefix:D}=y;T instanceof RegExp?T=(function(O){return function(F){return O.test(F)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?g(A):"",D=="latin1"&&(D=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=O=>O);let E=O=>ve.join(A,D(S(localPath,O))),R=O=>ve.win32.basename(ve.win32.normalize(D(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?b(void 0,Se.Errors.FILE_NOT_FOUND(localPath)):O?b(void 0,O):o.findFilesAsync(localPath,function(F,B){if(F)return b(F);B=B.filter(Z=>T(E(Z))),B.length||b(void 0,!1),setImmediate(B.reverse().reduce(function(Z,J){return function(re,X){if(re||X===!1)return setImmediate(Z,re,!1);I.addLocalFileAsync({localPath:J,zipPath:ve.dirname(E(J)),zipName:R(J)},Z)}},b))})})},addLocalFolderPromise:function(y,b){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},b),(T,D)=>{T&&A(T),D&&I(this)})})},addFile:function(y,b,I,A){y=f(y);let T=x(y),D=T!=null;D||(T=new Nm(i),T.entryName=y),T.comment=I||"";let E=typeof A=="object"&&A instanceof o.fs.Stats;E&&(T.header.time=A.mtime);var R=T.isDirectory?16:0;let O=T.isDirectory?16384:32768;return E?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=T.isDirectory?493:420,R=(R|O<<16)>>>0,T.attr=R,T.setData(b),D||c.setEntry(T),T},getEntries:function(y){return c.password=y,c?c.entries:[]},getEntry:function(y){return x(y)},getEntryCount:function(){return c.getEntryCount()},forEach:function(y){return c.forEach(y)},extractEntryTo:function(y,b,I,A,T,D){A=On(!1,A),T=On(!1,T),I=On(!0,I),D=pu(T,D);var E=x(y);if(!E)throw Se.Errors.NO_ENTRY();var R=d(E.entryName),O=u(b,D&&!E.isDirectory?D:I?R:ve.basename(R));if(E.isDirectory){var F=c.getEntryChildren(E);return F.forEach(function(J){if(J.isDirectory)return;var re=J.getData();if(!re)throw Se.Errors.CANT_EXTRACT_FILE();var X=d(J.entryName),oe=u(b,I?X:ve.basename(X));let ae=T?J.header.fileAttr:void 0;o.writeFileTo(oe,re,A,ae)}),!0}var B=E.getData(c.password);if(!B)throw Se.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw Se.Errors.CANT_OVERRIDE();let Z=T?y.header.fileAttr:void 0;return o.writeFileTo(O,B,A,Z),!0},test:function(y){if(!c)return!1;for(var b in c.entries)try{if(b.isDirectory)continue;var I=c.entries[b].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,b,I,A){if(I=On(!1,I),A=pu(I,A),b=On(!1,b),!c)throw Se.Errors.NO_ZIP();c.entries.forEach(function(T){var D=u(y,d(T.entryName));if(T.isDirectory){o.makeDir(D);return}var E=T.getData(A);if(!E)throw Se.Errors.CANT_EXTRACT_FILE();let R=I?T.header.fileAttr:void 0;o.writeFileTo(D,E,b,R);try{o.fs.utimesSync(D,T.header.time,T.header.time)}catch{throw Se.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,b,I,A){if(A=Bm(b,I,A),I=On(!1,I),b=On(!1,b),!A)return new Promise((O,F)=>{this.extractAllToAsync(y,b,I,function(B){B?F(B):O(this)})});if(!c){A(Se.Errors.NO_ZIP());return}y=ve.resolve(y);let T=O=>u(y,ve.normalize(d(O.entryName))),D=(O,F)=>new Error(O+': "'+F+'"'),E=[],R=[];c.entries.forEach(O=>{O.isDirectory?E.push(O):R.push(O)});for(let O of E){let F=T(O),B=I?O.header.fileAttr:void 0;try{o.makeDir(F),B&&o.fs.chmodSync(F,B),o.fs.utimesSync(F,O.header.time,O.header.time)}catch{A(D("Unable to create folder",F))}}R.reverse().reduce(function(O,F){return function(B){if(B)O(B);else{let Z=ve.normalize(d(F.entryName)),J=u(y,Z);F.getDataAsync(function(re,X){if(X)O(X);else if(!re)O(Se.Errors.CANT_EXTRACT_FILE());else{let oe=I?F.header.fileAttr:void 0;o.writeFileToAsync(J,re,b,oe,function(ae){ae||O(D("Unable to write file",J)),o.fs.utimes(J,F.header.time,F.header.time,function(P){P?O(D("Unable to set times",J)):O()})})}})}}},A)()},writeZip:function(y,b){if(arguments.length===1&&typeof y=="function"&&(b=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(y,I,!0);typeof b=="function"&&b(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,b){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},b);return new Promise((T,D)=>{!y&&i.filename&&(y=i.filename),y||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let R=O=>O?T(O):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(y,E,I,A,R)},D)})},toBufferPromise:function(){return new Promise((y,b)=>{c.toAsyncBuffer(y,b)})},toBuffer:function(y,b,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,b,I,A),null):c.compressToBuffer()}}}});import{execFile as j_,spawn as W_,spawnSync as zA}from"node:child_process";import{promisify as K_}from"node:util";function V_(t){if(process.platform!=="win32")return!1;if(Bf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Bf,"").toLowerCase();return $_.has(r)}function Ff(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return V_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function st(t,e=[],r={}){return W_(t,e,Ff(t,r))}function zf(t,e=[],r={}){return J_(t,e,Ff(t,r))}var $_,Bf,J_,Jt=nt(()=>{"use strict";$_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Bf=/\.(cmd|bat|ps1)$/i;J_=K_(j_)});var Yt=ce((bR,Ah)=>{"use strict";var Sh=["nodebuffer","arraybuffer","fragments"],Ih=typeof Blob<"u";Ih&&Sh.push("blob");Ah.exports={BINARY_TYPES:Sh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ih,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var $i=ce((vR,Co)=>{"use strict";var{EMPTY_BUFFER:kb}=Yt(),gd=Buffer[Symbol.species];function Tb(t,e){if(t.length===0)return kb;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 gd(r.buffer,r.byteOffset,i):r}function kh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Th(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Cb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function md(t){if(md.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new gd(t):ArrayBuffer.isView(t)?e=new gd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),md.readOnly=!1),e}Co.exports={concat:Tb,mask:kh,toArrayBuffer:Cb,toBuffer:md,unmask:Th};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=he("bufferutil");Co.exports.mask=function(e,r,i,o,c){c<48?kh(e,r,i,o,c):t.mask(e,r,i,o,c)},Co.exports.unmask=function(e,r){e.length<32?Th(e,r):t.unmask(e,r)}}catch{}});var Ph=ce((SR,Rh)=>{"use strict";var Ch=Symbol("kDone"),wd=Symbol("kRun"),_d=class{constructor(e){this[Ch]=()=>{this.pending--,this[wd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[wd]()}[wd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ch])}}};Rh.exports=_d});var Ur=ce((IR,Nh)=>{"use strict";var Vi=he("zlib"),Dh=$i(),Rb=Ph(),{kStatusCode:Oh}=Yt(),Pb=Buffer[Symbol.species],Db=Buffer.from([0,0,255,255]),Po=Symbol("permessage-deflate"),Xt=Symbol("total-length"),Fr=Symbol("callback"),Tn=Symbol("buffers"),zr=Symbol("error"),Ro,yd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ro){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ro=new Rb(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[Fr];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){Ro.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){Ro.add(o=>{this._compress(e,r,(c,d)=>{o(),i(c,d)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Vi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Po]=this,this._inflate[Xt]=0,this._inflate[Tn]=[],this._inflate.on("error",Lb),this._inflate.on("data",Lh)}this._inflate[Fr]=i,this._inflate.write(e),r&&this._inflate.write(Db),this._inflate.flush(()=>{let c=this._inflate[zr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Dh.concat(this._inflate[Tn],this._inflate[Xt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Xt]=0,this._inflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Vi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Xt]=0,this._deflate[Tn]=[],this._deflate.on("data",Ob)}this._deflate[Fr]=i,this._deflate.write(e),this._deflate.flush(Vi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Dh.concat(this._deflate[Tn],this._deflate[Xt]);r&&(c=new Pb(c.buffer,c.byteOffset,c.length-4)),this._deflate[Fr]=null,this._deflate[Xt]=0,this._deflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Nh.exports=yd;function Ob(t){this[Tn].push(t),this[Xt]+=t.length}function Lh(t){if(this[Xt]+=t.length,this[Po]._maxPayload<1||this[Xt]<=this[Po]._maxPayload){this[Tn].push(t);return}this[zr]=new RangeError("Max payload size exceeded"),this[zr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[zr][Oh]=1009,this.removeListener("data",Lh),this.reset()}function Lb(t){if(this[Po]._inflate=null,this[zr]){this[Fr](this[zr]);return}t[Oh]=1007,this[Fr](t)}});var qr=ce((AR,Do)=>{"use strict";var{isUtf8:Mh}=he("buffer"),{hasBlob:Nb}=Yt(),Mb=[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 Bb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ed(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 Fb(t){return Nb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Do.exports={isBlob:Fb,isValidStatusCode:Bb,isValidUTF8:Ed,tokenChars:Mb};if(Mh)Do.exports.isValidUTF8=function(t){return t.length<24?Ed(t):Mh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=he("utf-8-validate");Do.exports.isValidUTF8=function(e){return e.length<32?Ed(e):t(e)}}catch{}});var Ad=ce((kR,Hh)=>{"use strict";var{Writable:zb}=he("stream"),Bh=Ur(),{BINARY_TYPES:Ub,EMPTY_BUFFER:Fh,kStatusCode:qb,kWebSocket:Gb}=Yt(),{concat:bd,toArrayBuffer:Hb,unmask:jb}=$i(),{isValidStatusCode:Wb,isValidUTF8:zh}=qr(),Oo=Buffer[Symbol.species],xt=0,Uh=1,qh=2,Gh=3,vd=4,Sd=5,Lo=6,Id=class extends zb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ub[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Gb]=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=xt}_write(e,r,i){if(this._opcode===8&&this._state==xt)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Oo(i.buffer,i.byteOffset+e,i.length-e),new Oo(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 Oo(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 xt:this.getInfo(e);break;case Uh:this.getPayloadLength16(e);break;case qh:this.getPayloadLength64(e);break;case Gh:this.getMask();break;case vd:this.getData(e);break;case Sd:case Lo: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[Bh.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=Uh:this._payloadLength===127?this._state=qh: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=Gh:this._state=vd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vd}getData(e){let r=Fh;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&&jb(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Sd,this.decompress(r,e);return}if(r.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(r)}this.dataMessage(e)}decompress(e,r){this._extensions[Bh.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return r(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(d);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let d=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(d);return}this._fragments.push(c)}this.dataMessage(r),this._state===xt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=xt;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=bd(i,r):this._binaryType==="arraybuffer"?o=Hb(bd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=xt):(this._state=Lo,setImmediate(()=>{this.emit("message",o,!0),this._state=xt,this.startLoop(e)}))}else{let o=bd(i,r);if(!this._skipUTF8Validation&&!zh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Sd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=xt):(this._state=Lo,setImmediate(()=>{this.emit("message",o,!1),this._state=xt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Fh),this.end();else{let i=e.readUInt16BE(0);if(!Wb(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Oo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zh(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=xt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=xt):(this._state=Lo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xt,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[qb]=o,d}};Hh.exports=Id});var Cd=ce((CR,Kh)=>{"use strict";var{Duplex:TR}=he("stream"),{randomFillSync:Kb}=he("crypto"),{types:{isUint8Array:$b}}=he("util"),jh=Ur(),{EMPTY_BUFFER:Vb,kWebSocket:Jb,NOOP:Zb}=Yt(),{isBlob:Gr,isValidStatusCode:Yb}=qr(),{mask:Wh,toBuffer:Jn}=$i(),pt=Symbol("kByteLength"),Xb=Buffer.alloc(4),No=8*1024,Zn,Hr=No,It=0,Qb=1,ev=2,kd=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=It,this.onerror=Zb,this[Jb]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||Xb,r.generateMask?r.generateMask(i):(Hr===No&&(Zn===void 0&&(Zn=Buffer.alloc(No)),Kb(Zn,0,No),Hr=0),i[0]=Zn[Hr++],i[1]=Zn[Hr++],i[2]=Zn[Hr++],i[3]=Zn[Hr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[pt]!==void 0?u=r[pt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let f=u;u>=65536?(c+=8,f=127):u>125&&(c+=2,f=126);let x=Buffer.allocUnsafe(o?u+c:c);return x[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(x[0]|=64),x[1]=f,f===126?x.writeUInt16BE(u,2):f===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),r.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],d?[x,e]:o?(Wh(e,i,x,c,u),[x]):(Wh(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=Vb;else{if(typeof e!="number"||!Yb(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(r);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");if(c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof r=="string")c.write(r,2);else if($b(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[pt]: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,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Jn(e),o=e.length,c=Jn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Gr(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,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Jn(e),o=e.length,c=Jn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Gr(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,r,i){let o=this._extensions[jh.extensionName],c=r.binary?2:1,d=r.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Gr(e)?(u=e.size,f=!1):(e=Jn(e),u=e.length,f=Jn.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={[pt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:f,rsv1:d};Gr(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,r,i,o){this._bufferedBytes+=i[pt],this._state=ev,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Td,this,u,o);return}this._bufferedBytes-=i[pt];let d=Jn(c);r?this.dispatch(d,r,i,o):(this._state=It,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(tv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[jh.extensionName];this._bufferedBytes+=i[pt],this._state=Qb,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Td(this,f,o);return}this._bufferedBytes-=i[pt],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][pt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][pt],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)}};Kh.exports=kd;function Td(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 tv(t,e,r){Td(t,e,r),t.onerror(e)}});var tx=ce((RR,ex)=>{"use strict";var{kForOnEventAttribute:Ji,kListener:Rd}=Yt(),$h=Symbol("kCode"),Vh=Symbol("kData"),Jh=Symbol("kError"),Zh=Symbol("kMessage"),Yh=Symbol("kReason"),jr=Symbol("kTarget"),Xh=Symbol("kType"),Qh=Symbol("kWasClean"),Qt=class{constructor(e){this[jr]=null,this[Xh]=e}get target(){return this[jr]}get type(){return this[Xh]}};Object.defineProperty(Qt.prototype,"target",{enumerable:!0});Object.defineProperty(Qt.prototype,"type",{enumerable:!0});var Yn=class extends Qt{constructor(e,r={}){super(e),this[$h]=r.code===void 0?0:r.code,this[Yh]=r.reason===void 0?"":r.reason,this[Qh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[$h]}get reason(){return this[Yh]}get wasClean(){return this[Qh]}};Object.defineProperty(Yn.prototype,"code",{enumerable:!0});Object.defineProperty(Yn.prototype,"reason",{enumerable:!0});Object.defineProperty(Yn.prototype,"wasClean",{enumerable:!0});var Wr=class extends Qt{constructor(e,r={}){super(e),this[Jh]=r.error===void 0?null:r.error,this[Zh]=r.message===void 0?"":r.message}get error(){return this[Jh]}get message(){return this[Zh]}};Object.defineProperty(Wr.prototype,"error",{enumerable:!0});Object.defineProperty(Wr.prototype,"message",{enumerable:!0});var Zi=class extends Qt{constructor(e,r={}){super(e),this[Vh]=r.data===void 0?null:r.data}get data(){return this[Vh]}};Object.defineProperty(Zi.prototype,"data",{enumerable:!0});var nv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Ji]&&o[Rd]===e&&!o[Ji])return;let i;if(t==="message")i=function(c,d){let u=new Zi("message",{data:d?c:c.toString()});u[jr]=this,Mo(e,this,u)};else if(t==="close")i=function(c,d){let u=new Yn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[jr]=this,Mo(e,this,u)};else if(t==="error")i=function(c){let d=new Wr("error",{error:c,message:c.message});d[jr]=this,Mo(e,this,d)};else if(t==="open")i=function(){let c=new Qt("open");c[jr]=this,Mo(e,this,c)};else return;i[Ji]=!!r[Ji],i[Rd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Rd]===e&&!r[Ji]){this.removeListener(t,r);break}}};ex.exports={CloseEvent:Yn,ErrorEvent:Wr,Event:Qt,EventTarget:nv,MessageEvent:Zi};function Mo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Bo=ce((PR,nx)=>{"use strict";var{tokenChars:Yi}=qr();function Ft(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function rv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,f=-1,x=-1,g=-1,m=0;for(;m<t.length;m++)if(x=t.charCodeAt(m),d===void 0)if(g===-1&&Yi[x]===1)f===-1&&(f=m);else if(m!==0&&(x===32||x===9))g===-1&&f!==-1&&(g=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let y=t.slice(f,g);x===44?(Ft(e,y,r),r=Object.create(null)):d=y,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(u===void 0)if(g===-1&&Yi[x]===1)f===-1&&(f=m);else if(x===32||x===9)g===-1&&f!==-1&&(g=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m),Ft(r,t.slice(f,g),!0),x===44&&(Ft(e,d,r),r=Object.create(null),d=void 0),f=g=-1}else if(x===61&&f!==-1&&g===-1)u=t.slice(f,m),f=g=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(o){if(Yi[x]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);f===-1?f=m:i||(i=!0),o=!1}else if(c)if(Yi[x]===1)f===-1&&(f=m);else if(x===34&&f!==-1)c=!1,g=m;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(x===34&&t.charCodeAt(m-1)===61)c=!0;else if(g===-1&&Yi[x]===1)f===-1&&(f=m);else if(f!==-1&&(x===32||x===9))g===-1&&(g=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let y=t.slice(f,g);i&&(y=y.replace(/\\/g,""),i=!1),Ft(r,u,y),x===44&&(Ft(e,d,r),r=Object.create(null),d=void 0),u=void 0,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(f===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=m);let S=t.slice(f,g);return 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 iv(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(", ")}nx.exports={format:iv,parse:rv}});var qo=ce((LR,xx)=>{"use strict";var sv=he("events"),ov=he("https"),av=he("http"),sx=he("net"),cv=he("tls"),{randomBytes:dv,createHash:lv}=he("crypto"),{Duplex:DR,Readable:OR}=he("stream"),{URL:Pd}=he("url"),Cn=Ur(),uv=Ad(),fv=Cd(),{isBlob:hv}=qr(),{BINARY_TYPES:rx,CLOSE_TIMEOUT:xv,EMPTY_BUFFER:Fo,GUID:pv,kForOnEventAttribute:Dd,kListener:gv,kStatusCode:mv,kWebSocket:We,NOOP:ox}=Yt(),{EventTarget:{addEventListener:wv,removeEventListener:_v}}=tx(),{format:yv,parse:Ev}=Bo(),{toBuffer:bv}=$i(),ax=Symbol("kAborted"),Od=[8,13],en=["CONNECTING","OPEN","CLOSING","CLOSED"],vv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ye=class t extends sv{constructor(e,r,i){super(),this._binaryType=rx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Fo,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]),cx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){rx.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 uv({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new fv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[We]=this,c[We]=this,e[We]=this,o.on("conclude",Av),o.on("drain",kv),o.on("error",Tv),o.on("message",Cv),o.on("ping",Rv),o.on("pong",Pv),c.onerror=Dv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",ux),e.on("data",Uo),e.on("end",fx),e.on("error",hx),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[Cn.extensionName]&&this._extensions[Cn.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){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,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),lx(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){Ld(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Fo,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){Ld(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Fo,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){Ld(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Cn.extensionName]||(o.compress=!1),this._sender.send(e||Fo,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:en.indexOf("CONNECTING")});Object.defineProperty(ye.prototype,"CONNECTING",{enumerable:!0,value:en.indexOf("CONNECTING")});Object.defineProperty(ye,"OPEN",{enumerable:!0,value:en.indexOf("OPEN")});Object.defineProperty(ye.prototype,"OPEN",{enumerable:!0,value:en.indexOf("OPEN")});Object.defineProperty(ye,"CLOSING",{enumerable:!0,value:en.indexOf("CLOSING")});Object.defineProperty(ye.prototype,"CLOSING",{enumerable:!0,value:en.indexOf("CLOSING")});Object.defineProperty(ye,"CLOSED",{enumerable:!0,value:en.indexOf("CLOSED")});Object.defineProperty(ye.prototype,"CLOSED",{enumerable:!0,value:en.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[Dd])return e[gv];return null},set(e){for(let r of this.listeners(t))if(r[Dd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Dd]:!0})}})});ye.prototype.addEventListener=wv;ye.prototype.removeEventListener=_v;xx.exports=ye;function cx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:xv,protocolVersion:Od[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Od.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Od.join(", ")})`);let c;if(e instanceof Pd)c=e;else try{c=new Pd(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;zo(t,I);return}let x=d?443:80,g=dv(16).toString("base64"),m=d?ov.request:av.request,S=new Set,y;if(o.createConnection=o.createConnection||(d?Iv:Sv),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&&(y=new Cn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=yv({[Cn.extensionName]:y.offer()})),r.length){for(let I of r){if(typeof I!="string"||!vv.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let b;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=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")),b=t._req=m(o),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=m(o);o.timeout&&b.on("timeout",()=>{dt(t,b,"Opening handshake has timed out")}),b.on("error",I=>{b===null||b[ax]||(b=t._req=null,zo(t,I))}),b.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){dt(t,b,"Maximum redirects exceeded");return}b.abort();let D;try{D=new Pd(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);zo(t,R);return}cx(t,D,r,i)}else t.emit("unexpected-response",b,I)||dt(t,b,`Unexpected server response: ${I.statusCode}`)}),b.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==ye.CONNECTING)return;b=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){dt(t,A,"Invalid Upgrade header");return}let E=lv("sha1").update(g+pv).digest("base64");if(I.headers["sec-websocket-accept"]!==E){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(!y){dt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=Ev(F)}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Z=Object.keys(B);if(Z.length!==1||Z[0]!==Cn.extensionName){dt(t,A,"Server indicated an extension that was not requested");return}try{y.accept(B[Cn.extensionName])}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Cn.extensionName]=y}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(b,t):b.end()}function zo(t,e){t._readyState=ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Sv(t){return t.path=t.socketPath,sx.connect(t)}function Iv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=sx.isIP(t.host)?"":t.host),cv.connect(t)}function dt(t,e,r){t._readyState=ye.CLOSING;let i=new Error(r);Error.captureStackTrace(i,dt),e.setHeader?(e[ax]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(zo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ld(t,e,r){if(e){let i=hv(e)?e.size:bv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${en[t.readyState]})`);process.nextTick(r,i)}}function Av(t,e){let r=this[We];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[We]!==void 0&&(r._socket.removeListener("data",Uo),process.nextTick(dx,r._socket),t===1005?r.close():r.close(t,e))}function kv(){let t=this[We];t.isPaused||t._socket.resume()}function Tv(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",Uo),process.nextTick(dx,e._socket),e.close(t[mv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ix(){this[We].emitClose()}function Cv(t,e){this[We].emit("message",t,e)}function Rv(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,ox),e.emit("ping",t)}function Pv(t){this[We].emit("pong",t)}function dx(t){t.resume()}function Dv(t){let e=this[We];e.readyState!==ye.CLOSED&&(e.readyState===ye.OPEN&&(e._readyState=ye.CLOSING,lx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function lx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ux(){let t=this[We];if(this.removeListener("close",ux),this.removeListener("data",Uo),this.removeListener("end",fx),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[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",ix),t._receiver.on("finish",ix))}function Uo(t){this[We]._receiver.write(t)||this.pause()}function fx(){let t=this[We];t._readyState=ye.CLOSING,t._receiver.end(),this.end()}function hx(){let t=this[We];this.removeListener("error",hx),this.on("error",ox),t&&(t._readyState=ye.CLOSING,this.destroy())}});var _x=ce((MR,mx)=>{"use strict";var NR=qo(),{Duplex:Ov}=he("stream");function px(t){t.emit("close")}function Lv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function gx(t){this.removeListener("error",gx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Nv(t,e){let r=!0,i=new Ov({...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(px,i);return}let d=!1;t.once("error",function(f){d=!0,c(f)}),t.once("close",function(){d||c(o),process.nextTick(px,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",Lv),i.on("error",gx),i}mx.exports=Nv});var Nd=ce((BR,yx)=>{"use strict";var{tokenChars:Mv}=qr();function Bv(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&&Mv[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}yx.exports={parse:Bv}});var kx=ce((zR,Ax)=>{"use strict";var Fv=he("events"),Go=he("http"),{Duplex:FR}=he("stream"),{createHash:zv}=he("crypto"),Ex=Bo(),Xn=Ur(),Uv=Nd(),qv=qo(),{CLOSE_TIMEOUT:Gv,GUID:Hv,kWebSocket:jv}=Yt(),Wv=/^[+/0-9A-Za-z]{22}==$/,bx=0,vx=1,Ix=2,Md=class extends Fv{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Gv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:qv,...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=Go.createServer((i,o)=>{let c=Go.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=Kv(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=bx}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===Ix){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xi,this);return}if(e&&this.once("close",e),this._state!==vx)if(this._state=vx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Xi,this):process.nextTick(Xi,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Xi(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,o){r.on("error",Sx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Qn(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){Qn(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!Wv.test(c)){Qn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Qn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qi(r,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=Uv.parse(f)}catch{Qn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&g!==void 0){let S=new Xn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=Ex.parse(g);y[Xn.extensionName]&&(S.accept(y[Xn.extensionName]),m[Xn.extensionName]=S)}catch{Qn(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,(y,b,I,A)=>{if(!y)return Qi(r,b||401,I,A);this.completeUpgrade(m,c,x,e,r,i,o)});return}if(!this.options.verifyClient(S))return Qi(r,401)}this.completeUpgrade(m,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[jv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>bx)return Qi(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${zv("sha1").update(r+Hv).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;m&&(x.push(`Sec-WebSocket-Protocol: ${m}`),g._protocol=m)}if(e[Xn.extensionName]){let m=e[Xn.extensionName].params,S=Ex.format({[Xn.extensionName]:[m]});x.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",kx),m.setSocket(c,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ts,this)})),u(m,o)}};Cx.exports=zd;function tS(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 ts(t){t._state=Tx,t.emit("close")}function kx(){this.destroy()}function ns(t,e,r,i){r=r||Wo.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Wo.STATUS_CODES[e]}\r
16
+ `)),c.removeListener("error",Sx),g.setSocket(c,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(g),g.on("close",()=>{this.clients.delete(g),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Xi,this)})),u(g,o)}};Ax.exports=Md;function Kv(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function Xi(t){t._state=Ix,t.emit("close")}function Sx(){this.destroy()}function Qi(t,e,r,i){r=r||Go.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} ${Go.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 er(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,er),t.emit("wsClientError",d,r,e)}else ns(r,i,o,c)}});var qx=ce(Ue=>{"use strict";var F=Z;(function(t,e){let r=Z,i=t();for(;;)try{if(-parseInt(r(874))/1*(-parseInt(r(1186))/2)+parseInt(r(1257))/3*(parseInt(r(1227))/4)+parseInt(r(1407))/5+-parseInt(r(1098))/6*(parseInt(r(1188))/7)+parseInt(r(1247))/8*(-parseInt(r(1504))/9)+-parseInt(r(858))/10+parseInt(r(1216))/11*(parseInt(r(1631))/12)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Yo,594557);var dS=Object[F(436)+F(852)],lS=Object["getOwnPr"+F(758)+F(1035)],Fx=(t,e)=>function(){return t&&(e=(0,t[lS(t)[0]])(t=0)),e},uS=(t,e)=>{for(var r in e)dS(t,r,{get:e[r],enumerable:!0})};function fS(){return Ox||(Ox=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function hS(){let t=F;return Lx||(Lx=[IDBCursor[t(1353)+"e"][t(1068)],IDBCursor[t(1353)+"e"][t(1579)],IDBCursor[t(1353)+"e"][t(1579)+t(632)+"ey"]])}function xS(t){let e=F,r={ZOPoI:function(o,c){return o(c)},EpjNg:e(913),aERwo:function(o,c){return o===c},sXXfW:"kjIad",RSjIw:function(o,c){return o(c)},MdBxJ:"error",pWOYS:"pbdnf"},i=new Promise((o,c)=>{let d=e,u={KNrqn:r[d(341)],NzGGF:function(_,S){return r[d(711)](_,S)},JMTnm:r.sXXfW,edipy:function(_,S){return r[d(1263)](_,S)}},h=()=>{let _=d;t["removeEv"+_(1327)+_(895)](u.KNrqn,x),t[_(475)+_(1327)+_(895)](_(1473),m)},x=()=>{let _=d;r[_(547)](o,r[_(547)](Ht,t[_(1393)])),h()},m=()=>{let _=d,S={OErSc:function(y,v){return y-v}};if(u[_(1535)](u[_(346)],u[_(346)]))u[_(479)](c,t[_(1473)]),h();else{let y=_0xc1bc1d[_(626)+"g"](0,S[_(642)](4,_0x1ac06a[_0x5758f6][_(1818)])),v=y[_(456)](_0x9459d1[_0x421ee4]);_0x494edd[_(1241)](v)}};t[d(480)+d(1147)](r.EpjNg,x),t[d(480)+d(1147)](r[d(971)],m)});return i[e(1486)](o=>{let c=e,d={CQGij:r[c(971)]};o instanceof IDBCursor&&(c(571)===r[c(1595)]?(this[c(1433)](d[c(783)],_0x553b7b),this.onerror&&this[c(522)](_0x17bfb4)):Gd[c(1172)](o,t))}).catch(()=>{}),Zo.set(i,t),i}function pS(t){let e=F,r={DRHWY:e(724),BzXoC:e(1473),XFrAJ:function(o){return o()},AXvjq:function(o,c){return o(c)},LqJKE:e(785)+"or",YuVAd:function(o){return o()},aVBGU:function(o,c){return o!==c},SXCeJ:e(1660),gLKdm:"GuDcx",tiigc:e(1808)};if(Jo[e(840)](t))return;let i=new Promise((o,c)=>{let d=e;if(r[d(735)](r[d(712)],r[d(1715)])){let u=()=>{let m=d;t["removeEv"+m(1327)+"ner"](r[m(1023)],h),t[m(475)+"entListe"+m(895)](r.BzXoC,x),t["removeEv"+m(1327)+"ner"](m(1808),x)},h=()=>{let m=d;o(),r[m(584)](u)},x=()=>{let m=d;r.AXvjq(c,t[m(1473)]||new DOMException(r[m(738)],r[m(738)])),r.YuVAd(u)};t["addEvent"+d(1147)](r[d(1023)],h),t[d(480)+d(1147)](r[d(555)],x),t["addEvent"+d(1147)](r[d(1532)],x)}else return this[d(1028)+d(519)+"riesCount"]++,this[d(875)+d(1420)+"nt"]()});Jo[e(1172)](t,i)}function gS(t){Xo=t(Xo)}function mS(t){let e=F,r={eWxsC:function(i,o){return i(o)},yPwST:function(i,o){return i(o)},wZcNC:function(i,o,c){return i(o,c)},CRbQS:e(399),oOBbC:e(1345),yBbzs:"going away, network offl"+e(334),daJZY:function(i,o){return i!==o},QZANj:e(734),KrDHj:function(i,o){return i(o)},FHPOB:function(i,o){return i(o)},nHsuU:function(i,o,c){return i(o,c)},yDjqM:function(i,o,c){return i(o,c)},DkgHL:function(i,o){return i instanceof o},YOJiu:function(i,o){return i+o},YZewQ:function(i,o){return i(o)},IZWes:function(i,o){return i(o)},odczj:function(i,o){return i in o},TcaWR:e(995)+e(1359),wAoKe:function(i,o){return i===o},cdYeb:e(1600),lAtXH:e(1463),LWZPr:e(1118)};if(t===IDBDatabase.prototype["transact"+e(1038)]&&!r.odczj(r.TcaWR,IDBTransaction.prototype)){if(r[e(1804)](r[e(304)],r[e(304)]))return function(i,...o){let c=e,d=t[c(994)](r[c(990)](rs,this),i,...o);return Ud[c(1172)](d,i[c(624)]?i[c(624)]():[i]),r[c(795)](Ht,d)};if(this[e(967)+e(732)](),this[e(1322)+"mer"](),this[e(1567)+e(1037)+"rs"](),this[e(1784)+e(280)](1e3,_0x10245c),this["_connect"+e(1703)]=!1,_0x16ad32&&this[e(1025)+e(1469)]()&&!this["_readyCl"+e(1108)]){if(this[e(1464)+"tManager"]?.[e(1301)+e(1461)+"es"]()){let o=this[e(1464)+e(933)]?.[e(875)+"ntEndpoint"]();this["_dispatchCloseEv"+e(1558)](r[e(1638)](_0x29195b,"close",{code:1006,reason:e(1201)+o+(e(417)+", max re"+e(1308)+e(972)),wasClean:!0}))}else{let o=this[e(1796)][e(1620)+e(1695)+e(1815)](_0x597161,_0x57c1db);this[e(1713)+"hCloseEv"+e(1558)](_0x41f21c(r[e(702)],{code:_0x1a1e82,reason:_0x48b1a0,wasClean:!0,willReconnect:o})),o&&this[e(371)]()}return}this[e(1025)+e(1469)]()||this[e(1580)+"osed"]?this[e(1713)+"hCloseEv"+e(1558)](r[e(1638)](_0x31430a,r[e(702)],{code:_0x3cf574,reason:r[e(1716)]})):this[e(1713)+e(904)+e(1558)](r[e(1638)](_0x17236e,r[e(702)],{code:1006,reason:r.yBbzs})),this[e(1226)]=null,this["_endpoin"+e(933)]?.resetEndpointConfig(),this[e(886)+e(1801)]?.[e(1126)+e(1466)]()}if(hS()[e(934)](t)){if(r[e(1798)](r[e(1619)],r[e(1066)]))return function(...i){let o=e;if(r[o(1798)](o(311),r.QZANj))return t[o(832)](r.KrDHj(rs,this),i),r[o(515)](Ht,Gd[o(928)](this));throw this[o(371)+"Lock"]=!1,_0x568130};{let i={ehHvf:e(1473),YtHzB:function(o,c,d){return r[e(1816)](o,c,d)},IUeFz:function(o,c,d){return r[e(1207)](o,c,d)}};if(r[e(1678)](_0x4fbaba,_0x4f9ddc)){let o=_0x2baebb[e(923)][e(1573)](_0x28e04f[e(1640)+"et"],r[e(1094)](_0x4f1112[e(1553)+"th"],_0x91f47d[e(1640)+"et"]));this[e(1236)]&&this[e(1236)][e(925)]({data:o,fail:c=>{let d=e;this.emit(i[d(1157)],i[d(1507)](_0x84970a,i[d(1157)],{message:this[d(1637)+d(892)+d(1312)](c)}))}})}else this._socket&&this[e(1236)][e(925)]({data:_0x2aa13f,fail:o=>{let c=e;this[c(1433)]("error",i[c(541)](_0x4d1f44,"error",{message:this[c(1637)+c(892)+c(1312)](o)}))}})}}return function(...i){return r[e(794)](Ht,t.apply(r.IZWes(rs,this),i))}}function wS(t){let e=F,r={gKTrJ:function(i,o){return i===o},IZrhK:e(567),PpnVn:function(i,o){return i(o)},VWQwv:function(i,o){return i instanceof o},QwQwj:function(i,o,c){return i(o,c)},mdClv:function(i){return i()}};return r[e(1616)](typeof t,r[e(616)])?r.PpnVn(mS,t):(r.VWQwv(t,IDBTransaction)&&r[e(297)](pS,t),r[e(1300)](zx,t,r[e(464)](fS))?new Proxy(t,Xo):t)}function Ht(t){let e=F,r={VdoWB:function(o,c){return o instanceof c},RUcLO:function(o,c){return o(c)},jRkdy:function(o,c){return o(c)},nCInT:function(o,c){return o!==c}};if(r[e(1283)](t,IDBRequest))return r.RUcLO(xS,t);if($o[e(840)](t))return $o[e(928)](t);let i=r[e(1129)](wS,t);return r[e(705)](i,t)&&($o[e(1172)](t,i),Zo[e(1172)](i,t)),i}var zx,Ox,Lx,Gd,Jo,Ud,$o,Zo,Xo,rs,Nx=Fx({"node_modules/idb/build/wrap-idb-value.js"(){let t=F,e={kRwbs:function(r,i){return r instanceof i},fdICC:function(r,i){return r===i},AJWds:t(1538),kFbff:"store",rQISd:function(r,i){return r(i)},nmeIZ:function(r,i,o,c,d){return r(i,o,c,d)},pkGaw:function(r,i){return r(i)},NYCMS:function(r,i){return r!==i},UZllr:t(1577),RvEmh:t(1072),jabRd:function(r,i){return r in i}};zx=(r,i)=>i[t(455)](o=>r instanceof o),Gd=new WeakMap,Jo=new WeakMap,Ud=new WeakMap,$o=new WeakMap,Zo=new WeakMap,Xo={get(r,i,o){let c=t;if(e[c(366)](r,IDBTransaction)){if(e.fdICC(i,e[c(546)]))return Jo[c(928)](r);if(e[c(1731)](i,c(995)+c(1359)))return r[c(995)+c(1359)]||Ud[c(928)](r);if(e.fdICC(i,e[c(1279)]))return o[c(995)+c(1359)][1]?void 0:o["objectSt"+c(1272)](o["objectSt"+c(1359)][0])}return e[c(966)](Ht,r[i])},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t,c={MnjsE:function(d,u,h,x,m){return e.nmeIZ(d,u,h,x,m)},pNkVJ:function(d,u){return e[Z(1254)](d,u)},XGOUG:o(974)+o(561)};if(e.kRwbs(r,IDBTransaction)&&(e[o(1731)](i,e[o(546)])||e[o(1731)](i,e[o(1279)]))){if(e.NYCMS(e[o(880)],e[o(382)]))return!0;{let d={lXAXR:function(u,h,x,m,_){return c[o(1471)](u,h,x,m,_)},xqBhF:function(u,h){return c[o(953)](u,h)}};_0x22e9d1[o(480)+o(1147)](c.XGOUG,u=>{let h=o;d.lXAXR(_0x384ad3,d[h(532)](_0x48b1a6,_0x437151.result),u[h(1627)+"on"],u.newVersion,_0x554e39(_0x54c997[h(943)+h(1038)]))})}}return e.jabRd(i,r)}},rs=r=>Zo.get(r)}}),Ux={};uS(Ux,{deleteDB:()=>yS,openDB:()=>_S,unwrap:()=>rs,wrap:()=>Ht});function _S(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=F,u={pqRia:function(m,_,S,y,v){return m(_,S,y,v)},pXHij:function(m,_){return m(_)},cguCA:function(m,_){return m(_)},RCRFa:d(1785)+"hange",MNVvB:d(974)+d(561)},h=indexedDB[d(1556)](t,e),x=Ht(h);return i&&h[d(480)+d(1147)](u[d(716)],m=>{let _=d;u[_(1542)](i,u[_(1614)](Ht,h.result),m.oldVersion,m[_(962)+"on"],u.cguCA(Ht,h[_(943)+_(1038)]))}),r&&h[d(480)+d(1147)](d(825),()=>r()),x[d(1486)](m=>{let _=d;c&&m[_(480)+_(1147)](_(399),()=>c()),o&&m[_(480)+_(1147)](u[_(1778)],()=>o())})[d(513)](()=>{}),x}function yS(t,{blocked:e}={}){let r=F,i={CQOIm:"blocked",lNZzl:function(c,d){return c(d)}},o=indexedDB[r(1512)+"tabase"](t);return e&&o[r(480)+r(1147)](i.CQOIm,()=>e()),i[r(761)](Ht,o)[r(1486)](()=>{})}function Mx(t,e){let r=F,i={oBECP:"readwrite",wwqMl:r(997),arRPP:function(h,x){return h in x},RejIP:function(h,x){return h===x},sWXsj:"string",Dcunz:function(h,x){return h===x},bEZNv:r(830),LQpPW:r(509)};if(!(t instanceof IDBDatabase&&!i[r(1682)](e,t)&&i.RejIP(typeof e,i[r(1103)])))if(i[r(682)](i.bEZNv,i[r(688)]))this[r(640)+r(529)]=_0x2e572e,this._ws&&(this._ws[r(1166)+"pe"]=_0x305c23);else return;if(Vo[r(928)](e))return Vo[r(928)](e);let o=e[r(581)](/FromIndex$/,""),c=e!==o,d=Hx.includes(o);if(!(o in(c?IDBIndex:IDBObjectStore).prototype)||!(d||Gx[r(934)](o)))return;let u=async function(h,...x){let m=r,_=this[m(943)+m(1038)](h,d?i[m(1670)]:i[m(1370)]),S=_[m(976)];return c&&(S=S[m(1421)](x[m(1498)]())),(await Promise[m(857)]([S[o](...x),d&&_[m(1538)]]))[0]};return Vo[r(1172)](e,u),u}var Gx,Hx,Vo,bS=Fx({"node_modules/idb/build/index.js"(){let t=F,e={oacIA:t(1230)+t(927),gfovn:function(o){return o()},kxVbp:t(490),kzOQd:t(374),okGcS:t(1480),BybKp:t(1390),cnect:t(1185),LthFp:"getAllKeys",cLHzW:t(1110),BqFDi:function(o){return o()},rIGNf:function(o,c){return o(c)}},r=e[t(1585)].split("|"),i=0;for(;;){switch(r[i++]){case"0":e.gfovn(Nx);continue;case"1":Vo=new Map;continue;case"2":Hx=[e[t(760)],e[t(1091)],e[t(1598)],e[t(1802)]];continue;case"3":Gx=[t(928),t(710),e[t(460)],e[t(1184)],e[t(609)]];continue;case"4":e[t(1238)](Nx);continue;case"5":e[t(930)](gS,o=>({...o,get:(c,d,u)=>Mx(c,d)||o[t(928)](c,d,u),has:(c,d)=>!!Mx(c,d)||o[t(840)](c,d)}));continue}break}}}),ES={idb:function(t){let e=F;t[e(931)]=Promise[e(718)]()[e(1486)](()=>(bS(),Ux))[e(1486)](function(r){return r})}},Bx={};function Gt(t){let e=F,r={uUhhK:function(u,h){return u!==h}},i=(e(1602)+"4")[e(1414)]("|"),o=0;for(;;){switch(i[o++]){case"0":var c=Bx[t]={exports:{}};continue;case"1":var d=Bx[t];continue;case"2":ES[t](c,c[e(931)],Gt);continue;case"3":if(r.uUhhK(void 0,d))return d[e(931)];continue;case"4":return c[e(931)]}break}}Gt.d=(t,e)=>{let r=Z;for(var i in e)Gt.o(e,i)&&!Gt.o(t,i)&&Object[r(436)+r(852)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=F;Gt.o=(e,r)=>Object[t(1353)+"e"][t(802)+t(852)][t(994)](e,r)})(),(()=>{let t=F,e={HjxjP:function(r,i){return r!=i},YtBPX:t(1456)+"d",dbHxy:t(954),NVUJQ:t(1809)+"le",ZIRfw:function(r,i){return r===i},HTjXa:t(828),KyCbX:t(603)};Gt.r=r=>{let i=t;e[i(1040)](e[i(1633)],e.KyCbX)?(e.HjxjP(e[i(1793)],typeof _0x2d4f40)&&_0x21fe05.toStringTag&&_0x5b8b40["definePr"+i(852)](_0x3bc1cf,_0x137ccc["toString"+i(1275)],{value:e.dbHxy}),_0x2a1f57[i(436)+i(852)](_0x25ccbc,e.NVUJQ,{value:!0})):(e[i(1793)]!=typeof Symbol&&Symbol[i(1375)+i(1275)]&&Object[i(436)+i(852)](r,Symbol["toString"+i(1275)],{value:e[i(1694)]}),Object[i(436)+i(852)](r,e[i(1522)],{value:!0}))}})();function Yo(){let t=["CfDpwvm","CgzRDgu","C0vcsgC","B2Thy1m","rMnerLG","s295wg4","C2vUzf9Hy2S","mxWZFdb8mNW","B25nzxnZywC","x2LZv29YA2u","yw51Ce1LC3m","r3vxtKu","qNj1B28","zM9YrwfJAa","C3nHz2vfDMu","ELLZz0e","sLjrz2q","Cgfxr0y","yuzcqLO","CfHiAwO","txHhqw0","z0TuCKO","uvrhwe0","tKfusvzfx0u","Bef0weG","CMvJB25Uzwm","AKXSwuu","BMCGB3iGyw4","ueDlEMS","uLjpuG","s2f4vha","rhzTteq","B2XKvMvYC2K","CNzHBfzHBhu","sgnKBwq","zuDRvxK","mty0ndGYoe9AC01oDq","teTACwu","sfrQwge","yNnPBw8","Aw5KzxHpzG","ign1CNnVCIa","x2zVCM1HDeu","D1PJtKm","v0rPyuW","yNL0zu9MzNm","ExvOwfi","x2n1CNnVCK4","qLvUtgq","qM50CuC","ohW3Fdj8nhW","A0zkAeS","igfYCMf5yNu","Cw9fCNC","Cw9Zx18","A01twhy","AxnszwfKEq","Cwr1wNa","CMvWBgfJzui","zvvYBa","CLPXuvG","BhHQte4","x3vYBa","BfvLvxm","v2LUzg93","A3DtyxG","yxnJCMLWDa","vfLQs3G","uKfcAve","s2vts0W","wezMsvC","Ewj1uMu","x3bYB3rVy28","z3Ldv0q","x2LZtwLUAvC","B0jfq1a","AwDHDg9Yt24","EgnuEwq","ALH6vNO","C1f6t1O","x29UvgLTzw8","q0Xpu0LorW","BgjfAgu","rgTNseW","u3P3rLG","yxGGCMv0CMK","x2LUAxq","yxjsufa","quXcBhi","igzHAwWSig0","rfPSqMO","B3bLBIa","sgfKtuK","q09otKvdveK","DhLPzg8","CgLUz09Uy2u","uwLlEwG","CgXcuM4","wuPODgy","zgjiEhK","DeLUDgvYy2u","ALfcuw0","Cwzovgm","B2fuB24","BgDgvw8","tMjRsKC","B25JBg9Zzq","Dg9iyxnO","tg9JAW","yLvZvuG","Dg9cExrLC0W","zwHoELy","De11u2q","Cg1ZzKm","u0DXEM4","tezXwwS","Bg93","u3zpt0q","x2rPC3bHDgm","qwT2C3a","z0Xlzg0","B09cyKm","CMvZzxrfBMq","DhbizwfKzxi","B2zMBgLUzq","rNvzDw8","rwzXrva","ywXPzcb1CMW","zgLZywjSzue","yNbitfy","BMTdCwm","v1LxCvi","o2nOyxjZzxq","EMTWB0W","tMDNvLa","C3rHCNq","zMrjq0m","rNjVBNrPzxi","vgLTzw91Da","y29UDgv4Da","BNvTyMvY","C2v0y3vYC28","x3bPBMDqB24","x29UrxjYB3i","CMvQzwn0","CNbTsLy","C1PQyKK","CgfNzwHPzgu","u1vdyM4","BwfUDwfSihi","yxv0BW","whHevM0","wwXjCui","yMLUyxj5","yMfJA3vWigu","u2vXsuq","x29UtwvZC2e","rLjptLrjrvi","tvn0tKm","EurSENe","s25kB3y","zhf0tKy","rgfTDwO","zKzKy1m","ve5Ny0i","q2Lot1K","B2vrwgK","DgLTzw91Da","rMHXy0O","y29UBMvJDeu","A256veO","DM5lB3u","Aw47y2HHCNm","ChjVDg9JB2W","CNDZrva","ExHlv08","uuvvC0S","D29cuMO","Dg9oDw1Izxi","BhbeD08","r3rHs2m","weHAy0m","t3L0Awe","uKnsrMe","te5dChu","uMXLDe0","uKnPA0K","q291sfy","BgLTAxq","x3DZsw5ZDge","DMvYC2LVBMm","pxv0zI04","EhDKwg4","qwvgyNy","CMvHzhLtDge","uMvHzcbWyxm","tKDFrvjst1i","DxrKzfC","wxrcufG","v2ztuva","tM9KqvK","x29WDgLVBNm","yuzurfe","zgfkwLK","tKXurNm","seP1rMW","C0nVDw50zxi","qNLIs3a","v2vPEgLUsLm","D0fVs2u","s0r1z3O","q1fyDwq","yMTOzfi","ywjVCNq","x19LC01Vzhu","qw1VDw50","yMr0CeW","q29Kzq","Cgf5Bg9Hzeu","zLLgyuO","ChrVCG","BKHZDvu","D2vIsgy","BgvUz3rO","AwrI","sMvVyMO","txDfwvC","y3jLyxrLuMu","C1bvuM8","A1r2s2W","t09VANC","BMnLq2XVC2u","ChLyzKi","rvniz0S","DvrVExG","DLzXyui","BgvY","m3W0Fdj8mxW","A2v5CW","AwXLtMfTzq","s050qMq","x3bPBMC","CKHXEvy","wKXHyKG","EKL6Due","aaaaaaaaaaa","shfLt0y","Bg9Nsurhzw4","uhbUvM4","BM93","ywXty29Wzq","r2fQsxK","B3nLrxzLBNq","zKHMyK4","tgnUAKO","y2rzzwi","vw5Oyw5KBgu","wffnqNO","z2vjBMzVu3K","sM9vAxu","ywHHBgu","u21iwu4","v2frEeS","v0fAtLy","rgnyv3e","sgjxBee","uMnUwvK","txvXvha","A2LRDwK","vuDqzLa","ywXSB2nvBNm","x0rctMfTzq","tufyx1jfvfi","AxnbCNjHEq","s1jMvhm","q3Hmyue","ywnRx2LK","uxHSuhq","uxvLDwu","DMfSDwvZ","CMvJzwL2zwq","sufIBLa","yKTKsKS","zw5JB2rLrNi","rgjPuhO","Aw5L","rgLJBei","Bwu6ia","wKjqswW","Bxjrsuu","D3jPDgvvAw4","Ec11C2uT","rxbQtMC","yLj1zMK","qKnoqu0","wfLVtKO","B0LOyvi","sK1uBM0","Dw50","y09Wzw4","Dw1xCKS","wvrjwfy","y0ndBei","ywDLsgLKzq","v1jszvO","twLZC2LUzYa","zwzQqva","x2HHBMrSzva","rgzvruO","CeziEw0","t21vAwu","A1L3Dg0","C3rYAw5NAwy","z1vxzuO","vhzkwLy","uKvrANC","x29Uq2XVC2u","A1j3yNm","CLLqEvO","uw1qANq","EvjLy29UBMu","z1PQBLC","x2nVBM5Ly3q","swLhwuS","DxjS","ywrK","zw5XDwv1zq","AMHcuK8","ru9nqvK","uxbfweq","u2npEwu","EvrZthm","BNruCMLLC0m","uNzfBwG","zwn0","CxfJt04","D3DyrKK","rLLbrxO","EMHQvgC","Eu1zruG","rvjst1i","z0zJtge","wfDuz2K","zNDZxZeUmc4","zgvJB2rLzey","De5uweC","D24GCMvHC28","z2j0wK0","Bg9IywXty28","s0XPswG","y2XVC2u","DhLWzq","D3nZoI8V","qLHxq28","zcWGDw5RBM8","wNrcwge","nhWZFdf8mNW","wvrLvei","x2n1CNnVCKy","y2zxCum","B0fUs2K","vxbKyxrLq28","v0Prwxe","ywnOzwqSihC","y2n2ruW","u01wthy","DgnHDhC","CMvZzxruCMK","ihrPBwvVDxq","vuLKAg4","qM52y0O","yxjYyxLIDwy","yujVDKm","BMvJDa","B3zwBfu","vM9PBhC","B01Ut0q","BwLZzq","DK1NvLy","EwjpvMW","txz6yLO","AevYCM9Yrxy","y09wrvy","nhW2Fdi","sNz3DwK","zfrkCuW","BMzpsLq","zgvMAw5Luhi","vuH4z0C","q1rNzLC","B3jwuMK","CMzYvuS","Cw9JtKy","tKPsCKK","DgfYz2v0","ze1gywC","yuDfrwO","D1fhzvG","AxnrB1nby2S","rLfpEuG","wevLrLu","ALLNtNe","AejNCLG","D3b5qva","B25TzxnZywC","uKL1DLm","C29Tzq","y29Uy2f0","D2vlAMm","CNnVCL92ywW","whvPvum","y25Ly3q","zxq9DxrMltG","zw5KCg9PBNq","ywnRpwzYB24","BwrdBhy","mxW1FdeWFdy","CgvYC2LZDgu","zxjFAxnFywm","C2vUDa","y09lB24","uwfotNu","y3vYC29Y","CYbWyxjHBxm","B3bLBKrc","sfbRAfK","CMvTB3zLrxy","y2vZC0HHBMq","y3H6rue","sMfnzvu","zwrPChK","ywrKrxzLBNq","B2HRt1C","sxLrvha","AxvAqxm","DgvZDa","DNbRrMy","EKnPru8","sgXMC1C","x29UugfNzu4","zezowxu","Chv0","ue52thK","DvPtvLu","wwfKA2S","ENfbwwW","uMriEhG","ywDLrxzLBNq","yMfSrxzLBNq","A1n0yxr1C0m","AxPrCe4","Cu5dD3K","BMnVzgLUzW","C2v0zgi","x2HHBMrSzvi","lcbTyxGGCMu","whvTtvi","DcbVzIbYyw4","zgvIDwC","ANHOAxi","vfHpEuu","AvbhyNm","zw5HyMXLuw8","se1NteG","y2f0y2G","Dg9VigXHCMC","rKHqt0i","lcbxzwjtB2m","D29uzvm","x1fVu01HBMe","BMrWB2LUDfq","qKLiEva","BNDHsxe","B25LCNjVCG","yxrLq291BNq","CgfNzxnOB3C","qwjjsge","zxjYtM8","ywXSzwqGBxu","t0rUDfO","ExbL","A0z3C3m","Ehjdtfq","EhfcAey","vKH1C2C","BgLUzw5V","vuDNrLm","Dg9Vy24","x2rItMfTzq","A0Tkt2e","BvrQwM8","wMr0A1u","svvLrNO","zM5wzK0","DeLK","AKzju1q","uxb0wLy","quPxzhm","wK9qB0K","CfzyzMO","ALb6rNC","wNPXBe0","Bg9N","y29Kzq","B0HSveO","Aw5Lza","qNPyB0m","ywzL","AMXwqwi","uK1sBfG","txbqu2S","yNvMzMvYzwq","zwvKzwq","sxDjr0i","zxjFDhrS","EevMu3a","ENHAr2e","Aw50zwDLCIa","zNvUy3rPB24","vxjcAuy","Ae9Wzw5fDMu","y3r4","zezpuhK","sKT2y3C","wgviufu","swPvsfm","B2fK","z3LUBvu","EK1qtNq","Egr1s0O","CM9YrxzLBNq","vffLtLu","CMvWBgfJzq","vNjlsfe","tM9gsgK","wezYquO","q3HiCw0","y2HnyxHdB3u","zKPjt04","vMH1wMW","CK5qswe","CgPbquS","CgfYC2u","BIWGAg9ZDg4","rxLnBwG","tKDnAeC","s1HPtKC","re9qu1y","u3DpA3a","wgXvtgO","q0TYy3m","DMvUDa","AvLlAfi","vwTTDgi","uK5Tu2S","zKzoEfi","vLjkDg8","AeXiz2m","rfrvuxm","Dg9Y","y0XiELC","DLnZr2S","wvHTrvu","CLnqCgS","EufoEvG","ywLTqM0","zxjHDg9Y","svPYAeS","yuTxwwq","wg5iu2S","r2fRB0O","txj0zxq","Eu5uAe0","sfHoBuG","CMfUzg9T","C29YDa","zNjHBwvuExa","C3vIC3rYAw4","Auz3A1i","C0jf","s3DiBgS","DgXOsMm","zxj2AwnL","uhjPBwfYEuS","ihzHBgLKihm","zKXIthK","ENPPzvi","x2n1CNnVCK0","s3z3Bfm","s0fxExe","wNrhBvC","x2jPBMfYEvq","EwLuA2W","t0vYu2m","EfrXzhq","Bgn5teS","tfDtswy","Cg9PBNrdB24","y3jLyxrLt2i","yNvHv0m","zM9Yy2u","vwrHDgC","EvziyuC","zNjVBunOyxi","r0TkvwS","rgvxtuC","v2Pxv20","zxjFCw9Z","wujmq0i","C1jptwC","wMnnz2i","rxjYB3jdB2q","zwfiwKu","x3DHAxq","B2zMC2v0","Du9dwue","wu9WtNC","u1rZtg0","ELDAyMC","m3W0Fdb8mxW","qMLtsMu","q3LMsg0","x2rLC3rYB3K","rertBLC","vwvNyM4","BNrbBMrvCgq","zNrQrva","CM92AwrLige","A1vsvLq","y29UBMvJDa","B25ozxr3B3i","q291BNq","tw5PvhK","rgn1BNO","qMPVrM0","BxrcqvG","BKLdA1i","Bwf4twvZC2e","y29UC3rYDwm","tffWufC","B3zzBLe","ufvSwK8","tgDwrhG","uxPpqNq","ue5csNO","sfDfCuO","vuDiBuK","De1eseu","tuvtu0fhrv8","uvLZEhO","DxHHvxu","CgLUz1rPBwu","sw5tvhK","q1jIuvm","ve1Tu0u","q0Xpu0ve","BKnjBLq","weXMug0","z2HfAg8","Aezbque","C3vIyxjYyxK","z2v0s2v5","yuvsD28","u1HdzuO","wMPyDuO","FdeXFdb8oxW","DxDoswS","tu5wDKi","u2rwrei","CMvZB2X2zq","y3vYCMvUDeK","zgztChK","z3fPBMu","zxmGCMvHy2G","C0Tnzeu","y29TCgXLDgu","zMX1C2HfEha","CMvTB3zLq2G","A2HYBve","CfH2y0u","yvrOtfq","x3bYzwzPEa","Aur1A3y","BMDuAw1LCG","qMnKCKG","EhfUvvC","yvzcr1u","u25Wwxq","u0fIsgG","thfks0u","rK1MtKy","x3bHDgHlzxK","qwjHuvy","AgLqDfK","DxrMofDYAxq","wLPbCgm","BeXIqvi","D2fZq2XLyw4","Dg9cExrLC0i","Cgf5Bg9Hzfq","BwLUAvbYB2C","t3H5vNO","y3jLyxrLt3a","rNbKBfa","AwXK","C2jou0e","zhvyAxe","x3nLBMrby2S","tgTtsgq","B3bLCNr5tMe","y09NzxC","A3HwyNa","Be5AEMW","y1fMAMG","EMHnzuy","EfvZzuvUDG","ufrTCNK","x2LZtwLUAvq","BKDHwLm","zw5JB2rPBMC","DenoB1a","q2vjzeW","BKXPBMu","DxD2v3C","s0Dmt20","DvnftvC","B25szwnLAxy","Cgf3D3m","rNzLsvy","y1v0Eum","zgzkzxq","icSG","A0HQtxe","ywrKq291BNq","q1fhAwO","A0rTz1q","qwjVCNrfCNi","yKffzgO","Efrurw52","CwDyCxq","BM5Ly3q","CMfNzvn5BMm","CM92AwrLihC","Axnby2TdBgu","vgP5Chi","wvPLD1e","Evb3u1q","CMvJzxzPzwq","C2vYDMLJzq","mhWXFdv8m3W","AvDTAvK","v3DQELu","ywDLu2HVDW","AgfZt3DUuhi","zsbHihn0CMK","wLvqz08","CNnVCKzPBgu","B25VCgvU","v2nRwKK","AhPXC3m","rhnJDLG","vgrJquS","vezdzNu","zNLKzuu","yw5ZzM9YBvq","t1bftG","Ef9MCM9UDgK","qwnAsvG","twXotxm","C2v0u3rVCMe","B0rzzuu","swnQz3C","ELfns0u","qKjYDwq","DMfS","yMDhzwi","yMXVy2TLza","Bwv0Ag9K","CgfWs2e","uKDKDhK","D0Twvuq","Bhvcqwi","y2rkvw0","yxbWBhK","sNvUzxa","wgLgtfm","serjBg0","Au9UAMW","u3jREwy","DwrMqKq","C1n5B3K","AgfZ","BwvKAwf0zwW","yKDzwKm","r0TqCwm","BeD0s00","Cu9rqNa","CM92AwrLihy","y3jLyxrLq2W","suvtx0vsuK8","t1zuDvq","DMfSDwu","z1rPBwvVDxq","B3bLCNr5","sNziu2G","EwPSsMO","BwfW","yxLPuMq","ywXS","mJeYmZqYmeXhC3vSDq","ywX3yxLZ","DLbxr0W","t095r3C","y05Svgq","C09kufq","q3vRsgu","wwvmEgC","EK1JBui","wgDcrvu","s1Hkt1C","sxrnwMO","A0HArfq","tw1sr2q","C3nzrw8","yw1L","odq4mdu0uvDmug9R","z2v0q3vYCMu","Dg9hzw5LCMe","vuPxCwW","AxnFywnR","Ahn6yvu","vvPSBhi","Aw5N","vwzsuK8","s1HHwuy","EfPjsMe","rxrvwLC","x3bPBMDmB3m","zNjVBNrPzxi","zLbPs2C","BMrLEa","C2nYAxb0","vuftrha","CNjVCK1LC3m","x2LUAxrhBg8","ueTSAKO","BMvY","EwfyBwq","BMrWB2LUDca","Ae1LC3nHz2u","AxnAzxjV","q1PUCw0","sxrnEvG","y3PbD3m","l3DZl3yY","AenSB3nLrxy","x2XPC3rLBMu","BMCGzMfPBgu","q3vZDg9Tq2W","CurOtxa","vvb4rNG","BfrPBwvVDxq","qLvPz3q","qNDtDM0","C3vJy2vZCW","D0T0swi","Aw9UvgLTzw8","zMLUza","CMvUDevUzha","Bwfgs1q","AxjltxC","BhjjAMS","qLPoBuq","q010DLC","yNvMzMvY","y2PdugK","C2vUza","tu1tvu0","mxW1","z2v0","y2XVC2uSihC","CKLhtMy","zxHWB3j0CW","qMP5Efq","De1HBMfNzxi","Aw5JBhvKzxm","Ec1TC2CTCw8","zu10Dhi","C2Pgqvu","tvrHshK","y3ruAw1LB3u","wvLZDhG","uLvuAu0","EuLbDu0","DhjHBNnHy3q","ywWGy3vYC28","t1LVBum","yvHstgC","uLrcz1q","svjbv0e","yunrue4","z0PdrM4","yMLUza","tNn1DNu","Ce5RvKO","tw9KDwXL","zw5fDMvUDa","tLfzBxa","DhjPzxm","BwvZC2fNzq","EfjWv0y","B1rfv2C","DwvWDwm","BMv3vMvYC2K","zNjVBujPDhm","x2LUAxrqCM8","t2PPt0q","CLfju2q","x2nSzwfYugK","BgTTBM4","y1fIEM0","tuDXz0G","twrcEeO","ywnOzwq","y3rsvK0","DxbNCMfKzw4","zNjstM8","C3rVCMu","uNjbs3q","C2vYDMvYvgK","vw5PBxbSzw0","u09SDLK","BLbAvva","wwXesgW","C1fTv1e","DM5KEfe","z0zyCKG","C3bmqK0","Dgv4Dc9WBge","B2nRzxrgywK","C3jJ","zvD4C0m","uhzlyNO","yLffv1q","AxjLza","y2fSBa","B2jQzwn0u3q","CNnVCL9Uyw0","CMvHzg9UBhK","z0fjA1G","rhLkveq","BfjRyK8","CM92AwrLigi","zhD1vM8","BKztB3K","DMLJzuLeig8","qNH0EK0","CvDQEuu","z1rHz04","A2DTz00","DM9HugW","q1LOtKm","Dg9mB3DLCKm","x2TLEvbHDgG","C2vLvLa","ywnRtxnNswq","ywLHCNy","DhDVCMTdAge","rwjPuLi","AfvJCey","sLPty2W","A3vusKi","CMDswwK","s0ziC2e","rfjiv1K","suTdAwu","x25HDMLNyxq","x3jLy29UBMu","zv9ZDwnJzxm","y3vYCMvUDeu","zNjVBuj5Dgu","vw1OBMS","B2nRzxq","shvcBvq","reXOB2C","wMzmrK4","BwvZ","BvrfywW","C0XPC3rLBMu","Aw9U","DgThrgq","wKLszNC","B2LUDfjLywm","AeTuzuO","t0TMu2i","r2zTB2u","AMvJDfn0B3i","t1bftL9fuLi","zKD4wLa","ChbL","CKXABMu","zNDntKG","s3HdruC","D2Hfuw8","z3PQDgy","y29UBMvJDfm","D3D2wKe","Dg5NrKy","zhnitgm","rLDt","uhHLqvm","ww5Oy3a","wgT1Efq","AgDKCxC","AxnmB25N","ywnRDxbfBMq","B3jRig9MzMW","tfDAuhi","Dg9LAvq","ywr2yw5Jzq","s29QDhG","x2LZsw5PDa","ELLkAuq","s1nqDgy","wfjuqNO","CMvHzfvjBNq","C3rYAw5N","x29Ut3bLBG","B25tDgfYDfi","Bxz6ELy","sxnryvy","Cw9Z","BfrODei","zxP4CMu","ChjVy2vZCW","A3LvBe0","DgLUzYbZzxi","BLDTs1O","mNW0Fdb8mxW","CgLUz19VBMm","u3f6DxC","BK11Ee0","A3Ppuwq","BMHuuhC","D3jPDgu","wu9kAxu","AxmGDw5Kzwy","z29PBMCGyxC","B1DWv2S","ndK4uNv3qNfQ","z2v0qwXSs2u","yxbWBgLJyxq","Cg9PBNrbBMq","Bwf4uMv0CMK","C1DyC2O","nNW0Fdn8mxW","y2DyDvy","DLLSsNm","sNrvweq","B3nLza","Dwj2twS","y291BNq","CunKwMS","zgf0yq","BfDqwwu","BwvZC2fNzv8","AgvHzgvYCW","DcbSAw1PDa","twvZC2fNzuu","Cfburxm","sgf1B2i","zeH3EwS","CNzHBa","ALjJEgi","sw9rqwS","sLnptLa","z2vY","CMvZzxrdB3u","CMv0CNLdB3u","rMnvEMy","ALjRzhK","zMvY","BMDLza","ig1LC3nHz2u","CejQvw0","rfDvvui","rg12qKG","yKXuDxe","rK9QrfK","CMvKDwnL","Cgf5Bg9Hza","y3jLyxrLrwW","tw1vqMW","ENf2z2m","wfnlwgm","ihbYB3rVy28","DMDMzgy","zMLN","tgLZDgvUzxi","De5Zr2i","t3bLBKv2zw4","A1jyq0e","CMvXDwLYzwq","Aw5KzxGGB3u","B25fCNjVCG","zMzmAw5L","Dhj1y3rVCIa","ELzdy1G","zwHiDMy","C2v0q3vYC28","uen4q0u","yxbWzw5Kq2G","r3fgAwq","B2nRzxrtDwm","BwrSyui","yxnZAwDU","ufzotKq","yMLUyxj5vhK","r2TJrMG","igzPzwXKoIa","uLrSAw0","AM9PBG","rKf1tgu","C2v0","Bu54D3e","vgr3q1e","Dw5ZAwDUzwq","wMXPAu0","x2fKzfDZtgK","wKLuvgm","tvHRCfe","x2HHBMrSzu8","rvzLBLm","t2jQzwn0","u2D6zNq","thrOrNa","z2v0qwXS","mMfODgHvzq","zMLSDgvY","otu2nJLoCMzRyNO","qwHYDwi","rhvTv2K","ihjLy29UBMu","zhbVqxC","t05irMq","sezlD0C","AhvJDuq","qLjezK4","C2fNzq","yKPbA3a","r3fMsuq","rMjSEKS","y29UBMvJDca","q0fOEgG","y2XVC2veqG","wKDdtxy","AxnrB1nnzxm","wKndDMe","EurQCu0","y3vYC29YlNm","B25pCgvU","y1DSAfm","jMPZy2fSBgi","AMznyuy","z2vtEw5J","zufJAW","rNnzzwm","mtfOqLLXEgG","A2XZrKW","D3LXzem","zgLZCgf0y2G","BeHHBMrSzxi","z2v0u3rVCMe","EgfWvhe","CuPiwe4","r0vWBxu","Exzrz2K","x3DZ","mtj4txPwwuq","y2Tqs2O","BwvY","mhW0Fdn8mNW","C2zTu2G","B3vUDa","tg9NsurozxC","uMHHBNK","ywzqCfi","x3nVy2TLDa","q0Pys08","qNfgrgK","zxH0zw5ZAw8","B2zcyKy","ChvZAa","ue5KqMK","DxbKyxrLq3u","CgXLyxnLiha","zhLJzgu","yw5Hz2vY","mJy4mg9xwwrZva","r05LweW","A2v5","yw5Nzq","Bw14D0e","DxnLCKLW","AgvHzgvY","CgThyxC","y2HHCKnVzgu","x2rYB3bhBg8","otmWotq1B0TRBxvu","r3voy2q","Bg9NsurozxC","AMzYsfa","wKXOwK8","BwvZC2fNztO","uLnQsxC","DxrVuMvJB24","ihzHBgLKigq","Aw9Ul2PZB24","DKHOA0y","y3ftDgS","CMLLC0nVDw4","v1jYCvC","D2nzt3y","B3jL","yvbUwK4","yM9KEq","vgfN","zw1LBNq","BM9Uzv9UB24","BMD3ruW","A0zIzMy","AeDlzuO","rxzLBNq","z3n3tfe","vMrVv0i","ANz4Evy","AuLuuK4","BezSDxnO","y0neuhG","BMjpvKK","q05PCwu","zKfcy3y","Bhfxq3e","tg9Nsuq","B1HnsvC","zuvyEKG","CIb0DhDjra","rhjIvui","AwXSihvZzsa","DwvHt1a","zfbRshi","uxDrD2O","y2HLy2Tszwe","BxnNsuq","rwfXExK","Ahr0Ca","q0rsuMq","yvfMqLK","twXjyKK","DhjPzxmGCMu","C3jAvem","AefJA01LC3m","ignVzgu6ia","ywDL","x2LZtM9Kzq","ihrPBwvZ","DujNr0G","vwryz0G","yw1LoIa","zNjVBuHHC2G","tMfTzq","v2DQruC","ywXSq3vYC28","x2nSzwfYvgK","zMzLCG","wxvQt2y","zv90Aw1LB3u","CgLUz0XVC3m","zw50tgLZDgu","y3nJvhO","ysbTDxn0igi","yM1bzg0","q29UzMLN","D2LSBfjLy28","ugfjz2u","DhjPBq","yKXrEhe","EK10q2G","r3fqExi","zNPvq1u","wK91te0","B3v0sw50zxi","AvjkEeW","z2vrDwv1zuW","vhDoruy","zKfNt2S","yNLL","ywnRx2nVzgu","x3fVC0rc","zKXbv3e","zMLdywy","zxH0ugf5Bg8","sxHkwvi","uevjrLy","ChjVDg90Exa","vMvbt0u","BgLizgu","terkt20","reiGzMfPBgu","wKrKCMO","B3jLtMfTzxm","u2zbr2G","Axrjtwu","DwnQzNa","we1drhC","yxv0B21HDgK","s1LnBgW","r1v1Bgi","B25Uzwn0Aw4","tu5lswu","CMTLCKDSB2i","D3DXtwW","AvLuuwu","q2jTr08","v1Dks3G","x2rPC2nVBM4","Dg9tDhjPBMC","zvLyBfO","Aw1LCYbPBIa","x21PBMLoyxy","Dhr3Awq","tKn4AwC","B09AC0i","D3v5AuG","qK1rAxq","B25SAw5L","vhrbCMm","wvnbC2e","zxrxB3jRq2G","C3rVCcbPBw0","z2v0q3vYC28","y2XLyxi","lcbOB3n0BMe","teryDNG","CMvZDwX0","ywrKt25L","EwndzvG","ruPzthy","x2LUDgvYDMe","D3LVvhy","B2zM","DwHPzNi","zwnVBM5Ly3q","wLrQEu4","q25gr3G","ENf3uKS","x3nLCuLK","wfPAwg0","mZmZmdiZnwjguMv0BG","Dxrjza","zNjVBu51Bwi","y2HLy2TdDxi","EvH2twG","Cgu6ia","ugTiree","C3bSAxq","zgvS","zvL0DNy","AKvjDvK","Dev2zw50","u1LPq0u","BNrfBMrWB2K","Aw5KzxG","tKndBuK","C1DwAwu","Ec1TC2CTy3u","vNbXrM8","CgLUz0LUDgu","q0zgEuS","BMvvuey","igXHCMDLCIa","yMP4swu","r0LZyK0","zxjYtxnN","zw1PDa","C3rLBMvYCW","BMCGDxjSoIa","u2HHCMvKv28","AhDZvNq","Dgv4DfbHEwW","EKrLBvC","AK9squ4","rxfiDhq","AhvuEKC","B0HQvem","C3bSAwnL","vu1LsMm","y2uGBM90igK","y2XLyxjtDg8","wNLXC1C","vxPmBwS","x2nYzwf0zvm","rvr2A2q","zLH5zfm","s1HSwgG","z21VqvK","Bhm6ia","Dw5KzwzPBMu","B21JBum","EeDQtMe","C0fStvG","EMvhve8","y2HnyxHuCMK","x2rLyNvN","sKP2zgW","x2vUzhbVAw4","Eg51Awe","BNrLCG","whvnsKq","v1nwBuO","B3jpBMXPBMu","Dxb6BNu","tw5QC0u","DgLLCKPtt04","zxjYB3i","BLvKAM8","rwfmA3O","uMvJB25Uzwm","q2fNz2O","CND5sNK","DffSCw8","zgvSzxrL","x0vysvnu","Cxn1zwC","whj1vMu","yNL0zxm","AgLNAa","DgHLBG","twjIt04","AvvSy3e","twrXyKm","DeH5zem","CMvHC29U","terky0O","rLzswM8","y3zbExO","D3rYCwi","q2zuq1G","rhvbywe","C2HPzNq","vg5myw4","y3vYC29Yx24","x2DLBMvYyxq","BMfTzq","y29UBMvJDgK","mtCYmtDoA3ffvgi","ExLtEfO","B25mAw5L","wxriEKi","AgvKtwf4uMu","vfPUr24","DezMrwK","DwLjCvm","zgvSzxrLrge","yxKSihrYEsa","EvLXwMm","wKLLwgG","qwnJy3y","C3vqDu4","id4G","t1fHwee","yxnL","x2DLDeLUDgu","tLzvsLe","r2vsuuG","zxjFCw9Zx2e","vK9nyuW","ugv1A3y","wK1pD0C","r0L1Evy","vvzWuMW","A0LZtey","EeDevNm","DgLPz2m","tuDtDwC","v25Jyue","tNPhr0y","C2XHvhi","y1HpvuW","zg9Uzq","wfbYu1a","ugftAvu","CMfTzq","ChfsAwe","zw5HyMXLqxu","yMfSu2nVCgu","AgfUz2u","AwTHsMW","s1jtD28","BgLZDgvUtMu","u3rYyxrLz3K","uK9YBKG","tNvezK4","D2vI","yNL0zuXLBMC","sNbnq1u","wK1MCKK","B3bLBG","BMvLzf9Hy2S","zw50","Bwf4tg9ZC0m","DwD1C2K","DNriyxi","z3n2BxO","swjyD1G","BMXWweS","zLnVDfi","AeDJteq","x3jLBw92zvC","Ahr0Chm6","mdaWmdaWmda","quLXrvq","x2LZqNjVD3m","zu1ZrLa","C2XPy2u","AMLizgC","A2v0ignVBNm","mdaWma","z2LQtKi","zK5RuMi","y29UDgLUDwu","x3jLywr5q2W","x21LC3nHz2u","z2v0sxrLBq","AvrAv0u","zMLSzw5HBwu","B2fJsue","DezozLO","BgLUzq","Au5Rz04","DLjIque","tKLpuvK","CKLpDe0","B25tDg9Wsw0","DLrxEu0","qvLRzLe"];return Yo=function(){return t},Yo()}var Oe={};(()=>{let t=F,e={KLiIh:function(a,n){return a===n},Uegbn:function(a,n){return a<n},rSPpk:"XaTLg",nPZUP:t(1005),fzUCU:function(a,n){return a(n)},NLTFs:function(a,n){return a+n},LgVDx:function(a,n){return a*n},fHfbN:function(a,n){return a(n)},VpqFo:function(a,n){return a+n},EfqEP:function(a,n,s){return a(n,s)},XxDVm:function(a,n){return a+n},ONHFd:t(1576),SAbHh:"ffff",CKrcs:t(1569)+t(1569)+t(1569)+t(1569),VRJto:function(a,n){return a||n},LNCpu:t(1762),Icjgw:"ping_once_success",DZlBj:function(a,n){return a>n},gTagN:function(a,n){return a(n)},MXkpQ:function(a,n){return a+n},zCiEO:function(a,n){return a&n},cfWqC:function(a,n){return a|n},xGDVs:function(a,n){return a||n},KNtBd:function(a,n){return a>>>n},kURVT:function(a,n){return a>n},OjiOD:function(a,n){return a!==n},uwNIk:"XtcvL",ZLabH:function(a,n){return a===n},vJIls:t(278),ZIeXh:function(a,n){return a>n},nbOVI:function(a,n){return a<n},afPpR:function(a,n){return a!==n},FYAEz:function(a,n){return a-n},FMfNF:function(a,n){return a!==n},nWmKZ:"eYXlZ",SOlvY:function(a,n){return a<n},bAEdj:function(a,n){return a!==n},ghEho:function(a,n,s){return a(n,s)},bmAdm:function(a,n){return a(n)},PNdBi:function(a,n){return a(n)},zYJiD:function(a,n){return a(n)},WRReZ:function(a,n){return a(n)},HJuFl:function(a,n){return a&n},xGjNa:"Missing "+t(1151)+" field: "+t(850),BUnLd:function(a){return a()},zqAYl:function(a,n){return a!==n},ZtGmW:function(a,n,s){return a(n,s)},ZcMgb:function(a,n,s){return a(n,s)},MvzbZ:function(a,n,s){return a(n,s)},neUPF:function(a,n,s){return a(n,s)},KGLOm:function(a,n,s){return a(n,s)},ovYnQ:function(a,n){return a(n)},Zksqy:function(a,n){return a===n},tMuSd:t(452),UPxFx:function(a,n){return a!==n},TNgcB:function(a,n,s){return a(n,s)},VrKHQ:function(a,n,s){return a(n,s)},bKdJK:function(a,n){return a!==n},MNKIe:function(a,n,s){return a(n,s)},ueaOP:function(a,n,s){return a(n,s)},woTeS:function(a,n,s){return a(n,s)},utddW:function(a,n){return a|n},aQfBY:function(a,n){return a>>n},OOyGw:function(a,n){return a|n},CDRRd:function(a,n){return a&n},BiSJe:function(a,n){return a>>n},wOrmA:function(a,n){return a>>n},SnpYt:function(a,n){return a===n},IZCYd:t(1141),ScOye:function(a,n){return a(n)},wwvZA:function(a,n){return a(n)},ZMfrI:function(a,n){return a>>>n},nGaZS:function(a,n){return a(n)},TQeNU:function(a,n){return a(n)},HqeOF:function(a,n,s){return a(n,s)},DwJqg:function(a,n,s){return a(n,s)},MlIbI:function(a,n){return a(n)},kMSXv:function(a,n,s){return a(n,s)},sOJPT:function(a,n){return a&n},tkGDd:function(a,n){return a===n},ftjEP:t(354)+"required"+t(1168)+"SeqID",xapTq:t(354)+t(1151)+t(1168)+t(1292),fNkRb:t(354)+t(1151)+t(1168)+"service",KaxTp:function(a,n){return a===n},Hcdmd:t(354)+t(1151)+t(1168)+t(826),YlDHl:function(a,n){return a+n},zqvgc:function(a,n){return a(n)},JtUXD:function(a,n){return a(n)},toqgY:function(a,n,s){return a(n,s)},iFPXW:function(a,n,s){return a(n,s)},NGMhG:function(a,n){return a>=n},gFXrH:"Skip pas"+t(1116),YYstx:function(a,n){return a>n},cCjeT:function(a,n){return a+n},bJAkp:t(1790)+t(1116),xrCLT:function(a,n){return a(n)},Bruoo:function(a,n){return a!==n},kDmgT:t(601),fwMNH:function(a,n,s){return a(n,s)},AeFbv:function(a,n,s){return a(n,s)},JKvcw:function(a,n){return a<n},GtaKc:function(a,n){return a+n},oDYeE:function(a,n){return a|n},KwHlk:function(a,n){return a<<n},TvJZV:function(a,n){return a&n},WncaA:function(a,n){return a&n},jYgNq:function(a,n){return a<n},ZUsYz:function(a,n){return a==n},EcfEX:function(a,n){return a+n},MdqbC:function(a,n){return a|n},HXNmH:function(a,n){return a|n},Oytia:function(a,n){return a<=n},aThLT:function(a,n){return a(n)},YBLCB:function(a,n){return a&n},WjWWm:function(a,n){return a>=n},PkHDA:function(a,n){return a+n},aCQPN:function(a,n){return a+n},wuyiH:function(a,n){return a+n},yiTkl:function(a,n){return a+n},sWVie:function(a,n){return a&n},papKa:function(a,n){return a|n},FcUzf:function(a,n){return a<<n},nICkR:function(a,n){return a<<n},dsHLc:function(a,n){return a&n},ZfLFN:function(a,n){return a&n},lgFUo:function(a,n){return a&n},SvOOD:function(a,n){return a<n},KXaYF:function(a,n){return a>n},ndMcx:t(448),yvQgi:function(a,n,s){return a(n,s)},KeSKL:function(a,n,s){return a(n,s)},GqPyr:function(a,n){return a+n},RTBgT:function(a,n){return a<n},mTEal:function(a,n){return a<<n},GIuyV:function(a,n){return a&n},CouHV:function(a,n){return a!==n},FhqcJ:"ZGBup",uiIqS:function(a,n){return a&n},UNSWy:function(a,n){return a|n},fSotR:function(a,n){return a|n},pmsfC:function(a,n){return a>>n},ODntZ:function(a,n){return a&n},kuTJB:function(a,n,s){return a(n,s)},fFdcS:function(a,n,s){return a(n,s)},SIfiz:function(a,n,s){return a(n,s)},YlIqB:function(a,n){return a<n},OVTuT:t(1075),GEpmu:"GbFzY",cWlhS:t(1296),buaWC:function(a,n){return a|n},UpXNq:function(a,n,s){return a(n,s)},yySxZ:t(399),ctRVM:function(a,n,s){return a(n,s)},yANyX:function(a,n){return a|n},aFTDQ:function(a,n){return a&n},dqtNF:function(a,n){return a>>n},ycCeX:function(a,n){return a|n},cgXuV:function(a,n){return a&n},HYGFM:function(a,n){return a&n},JZScl:function(a,n){return a&n},wzRjX:t(1530),izQpN:function(a,n){return a&n},EMHzH:function(a,n){return a&n},sQzOZ:function(a,n){return a(n)},tQxNq:function(a,n){return a&n},EbiRR:function(a,n){return a&n},PVNND:function(a,n){return a===n},XFfIW:"Spvuq",iDukv:function(a,n){return a&n},bdtpL:function(a,n){return a(n)},QyQSf:function(a,n){return a(n)},iUlcq:function(a,n){return a&n},nfOJT:function(a,n){return a|n},CAhxh:function(a,n){return a|n},zkpoL:function(a,n){return a>>>n},IoQAk:function(a,n){return a===n},OOojw:function(a,n){return a<n},ahale:function(a,n){return a<n},Acccv:function(a,n){return a+n},jlVAb:function(a,n){return a|n},jRcxb:function(a,n){return a&n},ZzqlM:function(a,n){return a+n},KxCEG:function(a,n){return a|n},KXJOW:function(a,n){return a>>>n},FsYec:function(a,n){return a>>>n},UmyxN:function(a,n){return a|n},ZLhZO:function(a,n){return a!==n},dycde:function(a,n){return a&n},mNxwq:function(a,n){return a!==n},pawws:function(a,n){return a>>>n},lWPYe:function(a,n){return a&n},hzqss:function(a,n){return a|n},UGPfP:function(a,n){return a!==n},DscvX:function(a,n){return a(n)},XZZXm:function(a,n){return a|n},RletM:function(a,n){return a<<n},wyoTv:function(a,n){return a|n},AbaQV:function(a,n){return a<<n},DDSnW:function(a,n){return a|n},NCCmI:function(a,n){return a|n},hGKeJ:function(a,n){return a<<n},tFNfZ:function(a,n){return a<<n},XgBEU:function(a,n){return a<<n},NoFHi:function(a,n){return a|n},fGxZP:function(a,n){return a<<n},mmxwA:function(a,n){return a<<n},MBSfp:"0|5|2|4|3|1",tNsGb:function(a,n){return a<<n},uFBLz:function(a,n){return a|n},CxHqm:function(a,n){return a>>n},hiPtY:t(1109),ohkOW:function(a,n){return a===n},PvKbz:function(a,n){return a|n},ETvkd:function(a,n){return a|n},sAlMX:function(a,n){return a|n},dwuVo:function(a,n){return a|n},HDIlm:function(a,n){return a|n},Caggj:function(a,n){return a|n},Damuj:function(a,n){return a!==n},CUgCu:t(1106),IAbnP:function(a,n){return a&n},toeiT:function(a,n){return a>>>n},MuqTp:function(a,n){return a&n},PGKzk:function(a,n){return a&n},ucjfp:function(a,n){return a>>>n},JaMeU:function(a,n,s){return a(n,s)},ItMZj:"CtRdA",pfkte:function(a,n){return a>=n},oTEWg:function(a,n){return a<=n},vHhkF:function(a,n){return a+n},ZOuLM:function(a,n){return a%n},vIHlN:function(a,n){return a/n},CxLaA:function(a,n){return a instanceof n},Voilw:function(a,n){return a!=n},Eaqyy:t(1100)+t(1266),RrAKt:"text/plain;chars"+t(461),PKljJ:t(1696),mdlaB:function(a,n){return a*n},zVCcX:function(a,n){return a===n},XHZcC:function(a,n){return a===n},Jeobj:t(1474),XPrSP:function(a,n){return a>>>n},rLZne:function(a,n){return a&n},cCClB:function(a,n){return a>>>n},Mrtet:function(a,n){return a+n},OOOwN:function(a,n){return a>>>n},eQnVr:function(a,n){return a+n},PaSiU:function(a,n){return a|n},ZtBXa:function(a,n){return a<<n},liHde:function(a,n){return a===n},oIhaR:function(a,n){return a>>>n},lRkbO:function(a,n){return a>>>n},Sgzft:function(a,n){return a===n},aHbvs:function(a,n){return a<=n},zYsgA:function(a,n){return a>=n},LFqYk:function(a,n){return a+n},XQMBz:t(1030),CeIdL:function(a,n){return a===n},bQEWT:"PhHnf",JiXqr:t(1150),vgfdf:function(a,n){return a&n},XkuxT:function(a,n){return a>>>n},UMeJc:function(a,n){return a&n},pFWJq:function(a,n){return a>>>n},hszaU:function(a,n){return a>>>n},gmoAY:function(a,n){return a&n},UrBiF:function(a,n){return a>>>n},hUcpF:function(a,n){return a>>>n},ybuRe:function(a,n){return a&n},wKtIb:t(465)+t(714)+t(1645)+"3",cvAyz:function(a,n){return a<n},iFwkR:function(a,n){return a>>>n},vYeJh:function(a,n){return a!==n},lbEhe:t(1755),lGtKM:"suPjW",VLOTe:"NATIVE_E"+t(1624),pXvcE:"CONNECTI"+t(1791),YVqPt:t(321)+"IES_ERROR",XruVe:t(697)+"ERROR",qWjyE:"OPEN_ERROR",UVpRl:function(a,n){return a===n},DeWMG:t(696),EOMAY:function(a,n){return a>=n},UdXgH:function(a,n){return a-n},wyqdC:function(a,n){return a===n},cHTQj:function(a,n){return a===n},oXMIW:"yQcXj",rOuhT:t(1361),cdJUm:function(a,n){return a==n},REQjw:t(1473),omcmC:t(305)+"d error.",lnUGS:function(a,n){return a+n},KAWyq:function(a,n){return a===n},lrIjk:function(a,n){return a===n},zxZGa:function(a,n){return a===n},jfMaF:t(487),uSLQv:function(a,n){return a!==n},mVVyF:"fFNxR",EaLkz:t(1556),sjFAU:function(a,n,s){return a(n,s)},fYFaJ:t(958),WAZNV:t(1384),voaPl:t(1719),GIsbM:"xHnEZ",SzwFX:"zZwVK",FveIV:function(a,n){return a!==n},mpsaj:t(1419),cCDPx:t(1456)+"d",QzOBt:"cursor_file_name",GUulb:t(824),fLbLy:t(405)+"0",lpDwO:function(a,n){return a!=n},VHusg:function(a,n){return a+n},tFfEi:function(a,n){return a===n},kYwtm:function(a,n,s){return a(n,s)},Gfmoe:"BzZZw",TYjKx:t(932),UGHmI:function(a,n){return a<n},IsQaV:function(a,n){return a&n},QiKyh:t(1328),JzyBV:t(1606),TMmSE:"QbCJm",WDiaL:function(a,n){return a>=n},hunoO:function(a,n){return a&n},bUsUH:function(a,n){return a&n},jORAN:function(a,n){return a>=n},MmRGd:function(a,n){return a<n},KDugz:function(a,n){return a|n},rYPyZ:function(a,n){return a|n},dTJqL:function(a,n){return a&n},lIEhF:function(a,n){return a|n},CTgfW:function(a,n){return a<<n},nwaIq:function(a,n){return a&n},Yuhfx:function(a,n){return a&n},ZskHr:function(a,n){return a<<n},wcYOv:function(a,n){return a+n},cQfjh:function(a,n){return a&n},KFHsa:function(a,n){return a<n},EqHtt:function(a,n){return a|n},zYvtM:function(a,n){return a&n},gwaUQ:function(a,n){return a===n},RABiQ:function(a,n){return a&n},wkMIS:function(a,n){return a+n},jEIuY:t(668)+"2|5",UzLmk:function(a,n){return a|n},XuMJD:function(a,n){return a>>n},iWmiY:function(a,n){return a>>n},kHjMq:function(a,n){return a|n},XeHPU:function(a,n){return a+n},iHxYc:function(a,n){return a&n},zeGTO:function(a,n){return a&n},NQYmp:function(a,n){return a|n},nMuxM:function(a,n){return a&n},ufjLR:function(a,n){return a&n},zzieR:function(a,n){return a||n},aBovC:function(a,n){return a===n},rwsEP:t(1231),wtrqb:function(a,n){return a(n)},UIdhn:function(a,n,s,l){return a(n,s,l)},FblzK:function(a,n){return a instanceof n},QxlPt:"timeout, try rec"+t(1367)+"g",BCNAM:function(a,n){return a===n},jXzVz:"NTuzE",sEBHg:function(a,n){return a instanceof n},KuJmH:function(a,n){return a instanceof n},OKfSb:function(a,n){return a===n},pyXfB:t(1190),tngFF:t(358),Junep:"boe",srZTC:function(a,n){return a>=n},Vbklf:function(a,n){return a(n)},LkSHd:"unknown "+t(1491),YeLxg:function(a,n,s){return a(n,s)},qfNTc:function(a,n){return a!==n},gqine:t(838),uToyx:t(1052),MStNC:t(890),uOCYA:"text/jav"+t(1661),ayiRd:function(a,n){return a+n},jxhir:function(a,n){return a(n)},vRbAA:t(273),MniTy:function(a){return a()},Ahrub:t(1181),AbIHa:"yBbWH",PxeAS:"ZkLDM",slaTr:"VOKdx",ptuas:t(921),CYhNC:"wLCtF",KYMll:function(a,n){return a||n},WRrqW:function(a,n){return a||n},BIHyP:t(1547),GkcFh:function(a,n){return a>>n},CbmGO:t(1089),ccvEL:function(a,n){return a(n)},qocNF:function(a,n){return a<<n},XumMR:function(a,n){return a&n},JRQgd:function(a,n){return a&n},vhyWr:function(a,n){return a&n},oHlTJ:function(a,n){return a&n},SGpHP:function(a,n){return a&n},fPiKg:function(a,n){return a(n)},OGBQc:function(a,n){return a!==n},ZZApc:"zgIVm",azFsn:function(a,n){return a||n},cxzEA:function(a,n){return a||n},NJRrI:function(a,n){return a!==n},qOQBp:t(1493),BMQit:function(a,n){return a||n},xxZrn:t(1080),yMYEH:t(1114)+"id",WWJKx:t(815)+t(1524)+"ck",hgdqw:t(815)+t(467)+"k",FuYuo:function(a,n,s,l){return a(n,s,l)},fFglu:t(1557),vSsGk:function(a,n,s,l){return a(n,s,l)},DfUEJ:"is_ack",BUigt:function(a,n){return a&&n},IiGYK:t(325),pjAAK:t(1346),GakoJ:t(329),BntqG:function(a,n){return a(n)},DvmLD:t(752),woBRj:t(1748),YSAsa:function(a){return a()},xTqdt:function(a,n){return a>n},YXmEU:"DjuVG",maFKT:t(474),zMPNt:function(a,n){return a(n)},CJXKO:function(a,n){return a+n},fRmzk:function(a,n){return a|n},PNvLy:function(a,n){return a+n},QTGXM:t(902),kKJOa:function(a,n){return a||n},HWEqJ:function(a,n){return a>>>n},fMLnf:function(a,n){return a(n)},lLbAR:function(a,n){return a+n},Udatg:t(1152)+t(506)+"ge: ",DuAaa:function(a,n){return a||n},qduZp:t(1518),DmvBH:function(a,n,s,l){return a(n,s,l)},PEIFV:function(a,n){return a<n},iduUF:function(a,n){return a<<n},ssYEo:t(724),DOPSV:t(1808),FvLNp:function(a,n){return a!==n},GqfID:"wUwUr",wwXFI:"1|2|4|0|3",iSxyE:function(a,n){return a+n},qJHXN:function(a,n){return a+n},qoErw:function(a,n){return a!==n},dxIMo:function(a,n){return a!==n},tHydC:t(998),gFcLa:function(a,n){return a|n},hKTeJ:function(a,n){return a<<n},umWrK:function(a,n){return a+n},mrQIE:function(a,n){return a+n},yTsLs:function(a,n){return a<<n},XuiUC:function(a,n){return a+n},ugusi:function(a,n){return a<<n},OsffD:function(a,n){return a+n},XYeyc:function(a,n){return a+n},dFNYu:function(a,n){return a&n},yaXmd:function(a,n){return a+n},uSEMW:function(a,n){return a>>>n},fABcv:function(a,n){return a&n},BXWCo:function(a,n){return a+n},SGqzn:function(a,n){return a>>>n},XnHSk:function(a,n,s,l){return a(n,s,l)},ntTeO:function(a,n){return a!==n},jbsBz:t(683),aiarv:"vnghg",ZITTc:function(a,n){return a&n},uAqgY:function(a,n){return a|n},fwJgn:function(a,n){return a<n},xnuia:function(a,n){return a<<n},ESHgK:function(a,n){return a<n},LDJOm:function(a,n){return a|n},WfSQP:function(a,n){return a|n},rnMST:function(a,n){return a|n},Jvwui:function(a,n){return a>n},tlhJc:function(a,n){return a!==n},gsvmz:t(836),bqDkD:function(a,n,s,l){return a(n,s,l)},NNpgz:t(1208)+t(631),nlnJh:t(1253),zMtCh:t(797),pVXfj:"name",hHTni:"curvalue",huTzG:t(1668),rpmJV:t(1282),VlNFi:function(a,n){return a<n},fSXnq:function(a,n,s){return a(n,s)},fiCaf:function(a,n){return a+n},SdVDB:function(a,n,s){return a(n,s)},jLlYE:"FILE_NOT"+t(1481),uepuc:function(a,n,s){return a(n,s)},ZGCMv:t(1321)+"rValues",aRqgA:"ALL",xduKJ:function(a,n,s,l){return a(n,s,l)},rfrUK:"CONTINUE",wQGeX:function(a,n){return a||n},JoUiu:function(a,n){return a!==n},aVJwm:t(699),plBRn:"UAjRq",HMgLH:t(502),DxQpE:function(a,n){return a>n},dpoAw:function(a,n){return a(n)},vndxQ:t(549),STsLm:t(1736)+"r",dHwyk:function(a,n){return a|n},AcZIX:function(a,n){return a|n},ZTjyN:function(a,n){return a<<n},WYWqR:function(a,n){return a+n},zQMKE:function(a,n){return a+n},xRpWF:function(a,n){return a+n},SUCbn:function(a,n){return a*n},Srkyf:function(a,n){return a>>>n},yXvMh:function(a,n){return a>>>n},ehNzV:function(a,n,s){return a(n,s)},cjCPi:t(954),gynmU:function(a,n,s,l){return a(n,s,l)},GuNcd:t(552),oMnOD:function(a,n,s,l){return a(n,s,l)},sKMdE:function(a,n,s){return a(n,s)},bLTuq:t(815)+"er_msgid",XYoNJ:t(815)+t(563),kSdye:function(a,n,s,l){return a(n,s,l)},RIuvS:t(935)+"s",tcatw:"x-msg-cu"+t(996)+"e",GNeXL:t(1424)+t(458)+"ue",GTsks:function(a,n){return a>n},bRufi:t(588),QpEXD:t(1591),SmHYN:function(a){return a()},oAnKi:t(750),ItMyX:t(1354),eEXzH:function(a){return a()},FOjDY:function(a,n){return a<n},OQaXA:function(a,n){return a===n},mTjZo:function(a,n){return a===n},hwsVt:function(a,n){return a&&n},WSVmJ:function(a,n){return a(n)},yFMBk:function(a,n){return a===n},CiNOY:function(a,n){return a!==n},DTUQs:function(a){return a()},bLQxq:function(a,n){return a===n},UJWql:function(a,n,s){return a(n,s)},rwyJy:function(a,n,s){return a(n,s)},yIAuM:"bye",bkhdR:function(a,n){return a(n)},eMsFP:function(a,n,s){return a(n,s)},VXTgt:function(a,n,s){return a(n,s)},QYsxz:function(a,n){return a!==n},zZYIb:function(a,n){return a===n},CfTCX:t(859),kHZDT:function(a,n,s){return a(n,s)},PTmry:t(420)+t(1130),LWSIf:"pbbp2",EtUZW:function(a,n){return a/n},iTZWE:function(a,n){return a==n},sSyoy:t(1244)+t(846)+t(1722),CnFGx:function(a,n){return a(n)},KXKct:t(1244)+t(791)+t(472)+t(516)+t(1575)+t(1155)+t(1095)+t(554),TlYTr:function(a,n){return a!==n},paWGF:t(1742),HbWlA:t(524),SMVLv:function(a,n){return a+n},oaTon:function(a,n){return a+n},WckZI:function(a,n){return a<<n},CukHe:function(a,n){return a|n},fJION:function(a,n){return a&n},ddhdZ:function(a,n){return a<n},fAgOk:function(a,n){return a>n},zMcmB:function(a,n,s){return a(n,s)},iRJxL:function(a,n){return a+n},GeRQH:function(a,n){return a!==n},GajIy:t(919),aimBm:t(564),IxJYR:t(843),ckPKj:function(a){return a()},LjRIS:t(1568),gzjtf:t(401),MwEYW:"ws://",HFKwG:function(a,n){return a!==n},gZjnW:t(1479),upznu:"bd_did",WhLAv:"device_id",AIqET:function(a,n){return a||n},yxKWO:t(1244)+t(1001)+"ddID, de"+t(1004)+t(1295),ZDdrj:function(a,n){return a==n},nhTPw:function(a){return a()},irCEw:function(a,n,s){return a(n,s)},Qnxtr:t(392)+"0",dHBsV:t(1291),bsimo:t(368),ZMOwG:function(a,n,s){return a(n,s)},jFIST:t(1620)+"t",UASDp:function(a,n,s){return a(n,s)},sbNSA:t(485),WwjzU:t(293),yACXm:t(1752)+">",cUtyC:function(a,n){return a*n},NbkJG:function(a,n){return a===n},vtHar:function(a,n,s){return a(n,s)},RTlim:function(a,n,s){return a(n,s)},IKCie:t(1088)+t(1325)+"t",EJYLv:t(1096)+t(1513)+t(1620)+t(1085)+"ver",yxilM:t(1277)+"e",XWTgi:function(a,n,s,l){return a(n,s,l)},YvcrV:function(a,n){return a===n},xcTyd:"Tjypr",bEawr:function(a,n){return a||n},jhBRO:function(a,n){return a||n},ngwEL:function(a,n){return a!==n},CZnqm:t(451),iPGbs:function(a,n){return a||n},MGSug:t(1566),knzTJ:function(a,n){return a(n)},IbXwX:t(1601),AYkfQ:t(690),LsABw:t(1087)+"3",Yadkk:function(a,n){return a>n},XlULj:function(a,n){return a+n},MGqgH:"TJCPp",SCVVP:t(1096)+"ay, netw"+t(1065)+"ine",spLBM:function(a,n){return a instanceof n},zWZbg:function(a,n){return a+n},YujOf:t(1111),KRfTs:t(701),fXydS:function(a,n,s){return a(n,s)},HigQG:function(a,n){return a+n},NuDfN:t(941),TdwCQ:function(a,n,s,l){return a(n,s,l)},AwzIt:function(a,n){return a||n},nEsNf:function(a){return a()},MxGAm:t(1360),kGOuq:function(a,n){return a+n},uhifr:function(a,n){return a!==n},zhjTg:t(651),rHqyV:function(a,n){return a<<n},CFFyK:function(a,n){return a!==n},QaNNu:t(559),JpMCU:t(1806),UfRRO:t(1104)+"2|7|0|5",ezxre:function(a,n){return a===n},Akvsp:function(a,n){return a===n},vUEAm:t(929)+"s already closed",Peukv:function(a,n){return a==n},yNThM:t(1244)+t(676)+t(1265)+"ata, dat"+t(1329)+t(803)+t(1622)+t(1647)+t(1323),ALBlr:function(a,n){return a!=n},zqwRK:function(a,n){return a(n)},orVRi:t(1244)+"rovide a"+t(633)+"ervice",QEUsK:function(a,n){return a instanceof n},wUghq:function(a,n){return a(n)},EAqIb:t(468),CMtvW:function(a,n){return a<n},mvzzV:function(a,n){return a||n},BBrud:function(a,n){return a==n},khrmQ:t(1744)+t(1401)+"ing",nFSoy:t(1416),jfrHP:t(286)+"0",PCxCE:t(913),cOVEV:function(a,n){return a(n)},DtBmA:t(294),bjxIe:function(a,n){return a*n},zhMeF:function(a,n){return a!=n},aiIWg:function(a,n){return a===n},pBjUm:t(1659),qDhMp:function(a,n){return a===n},webHf:function(a,n){return a===n},iNkgN:t(1182),Kojtx:function(a,n){return a===n},FAuLe:function(a,n){return a!=n},eMttr:function(a,n){return a!=n},yjlJj:function(a,n){return a!=n},ovVlU:function(a,n){return a!=n},ZliiM:function(a,n){return a===n},XMCDw:t(1436)+t(1369)+t(299),NggVP:function(a,n){return a===n},EGZTY:function(a,n){return a!=n},BwSvm:function(a,n){return a!=n},ekRLk:function(a,n){return a===n},cOKon:function(a,n){return a!=n},sROMg:function(a,n){return a!=n}};Gt.r(Oe),Gt.d(Oe,{FWS:()=>Tg,CustomErrorEvent:()=>al,createCloseEvent:()=>_t,ReconnectEvent:()=>ol,createErrorEvent:()=>ut,decodedFrame:()=>sn,createOpenEvent:()=>hl,CustomCloseEvent:()=>cl,createReconnectEvent:()=>pa,FrontierMessageEvent:()=>ll,encodeFrame:()=>qt,createMessageEvent:()=>fl,OpenEvent:()=>ul,ErrorCode:()=>an,Event:()=>rr,MessageEvent:()=>dl});let r="";function i(a=""){let n=t,s={qsueg:function(l,f){return e.KLiIh(l,f)},lcyLK:function(l,f){return e[Z(673)](l,f)},qgXqt:function(l,f){return l===f}};if(e[n(612)]!==e[n(981)]){let f=""+Date[n(298)](),g=r||(r=e[n(1338)](h,a)),w=Math[n(623)]().toString(16)[n(1573)](-6);return e[n(1799)](e[n(1799)]("02",f),g)+w}else{if(s[n(1482)](void 0,_0x216b7d))this[n(905)+"rs"]={};else if(s.qsueg(void 0,_0x32415b))this[n(905)+"rs"][_0x52e84a]=null;else{let l=this[n(905)+"rs"][_0x1920be];if(l)for(let f=0;s[n(644)](f,l[n(1818)]);)s[n(788)](l[f].fn,_0x8457b0)?l[n(1444)](f,1):++f}return this}}function o(){let a=t;return e[a(691)](1e4,Date[a(298)]())+Math.floor(1e4*Math[a(623)]())}function c(a){let n=t;return(e.fHfbN(Array,8)[n(1170)]("0")+parseInt(a,10)[n(1375)](2))[n(1573)](-8)}function d(a){let n=t;return e[n(1425)](e[n(1338)](Array,4)[n(1170)]("0"),e[n(1721)](parseInt,a,2).toString(16))[n(1573)](-4)}function u(a){let n=t,s=a[n(1414)](/\./)[n(855)](g=>c(g)),l=[];return l[0]=e.fzUCU(d,e[n(1425)](s[0],s[1])),l[1]=d(e[n(1746)](s[2],s[3])),[e.ONHFd,e.ONHFd,e[n(1193)],e[n(1193)],e[n(1193)],e[n(737)],l[0],l[1]][n(1170)]("")}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(484)](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(484)](a);return s?u(a):l?x(a):e[n(599)]}function x(a){let n=t,s={LDJcJ:function(k){return k()},FLYCR:e[n(1779)],KXiNG:e.Icjgw,fnVfM:function(k,L){return k<L},ZdtkU:function(k,L){return e[n(1685)](k,L)},dfSpy:function(k,L){return e.gTagN(k,L)},KvwlS:function(k,L){return e[n(1179)](k,L)},YTIXV:function(k,L){return e[n(486)](k,L)},NIOQY:function(k,L){return e[n(408)](k,L)},PNBJz:function(k,L){return e.xGDVs(k,L)},wMJzq:function(k,L){return e[n(289)](k,L)}},l="",f=[],g=0,w=0,E=!0,p=e.ONHFd;if(e[n(677)](a[n(1635)]("::"),-1)){if(e.OjiOD(e[n(715)],e[n(715)]))return this[n(1713)+n(898)+n(1281)](_0x33d8a1),s[n(1492)](_0x250427);{let k=a[n(1414)]("::");for(let B=0;e[n(673)](B,k[n(1818)]);B++)if(e[n(292)](e.vJIls,n(492))){let $=this[n(1347)][n(1221)+n(307)+"nc"](this[n(730)]),G=_0x563eb1[n(591)](e.VRJto($,"{}"));return _0x1008ed[n(328)](G)}else{let $=k[B];if(e[n(1515)]($[n(1635)](":"),0)){let G=$[n(1414)](":");E&&(g=G[n(1818)]),w+=G[n(1818)];for(let j=0;e[n(1288)](j,G[n(1818)]);j++)if(e[n(1235)](4,G[j][n(1818)]))if(e[n(398)](n(812),n(948)))_0xd5f736(s.FLYCR),this.off(s[n(595)],_0x1d15b7),this[n(1399)](n(1088)+n(1325)+"t",_0x55227c);else{let be=p.substring(0,e[n(386)](4,G[j][n(1818)])),me=be[n(456)](G[j]);f[n(1241)](me)}else f[n(1241)](G[j]);E=!1}else{if(e[n(739)](4,$[n(1818)]))if(e.KLiIh(n(1376),e[n(1086)])){let G=p[n(626)+"g"](0,4-$[n(1818)]),j=G[n(456)]($);f[n(1241)](j)}else{let G=s[n(693)](_0x13932f,8192),j=s.wMJzq(G,1),be=null,me=G;return function(Ie){let ft=n;if(s[ft(542)](Ie,1)||s[ft(540)](Ie,j))return s[ft(720)](_0x37a165,Ie);s[ft(637)](me,Ie)>G&&(be=s[ft(720)](_0x3c4324,G),me=0);let va=_0x4e20e3[ft(994)](be,me,me+=Ie);return s[ft(350)](7,me)&&(me=s[ft(637)](s[ft(1590)](7,me),1)),va}}else f[n(1241)]($);E&&(g+=1),w+=1,E=!1}}let L="";for(let B=0;e[n(980)](B,8-w);B++)L=L[n(456)](p);for(let B=0;e[n(1288)](B,f[n(1818)]);B++)B===g&&(l=l[n(456)](L)),l=l[n(456)](f[B]);return l}}{let k=a[n(1414)](":");for(let L=0;e[n(980)](L,k.length);L++){let B=k[L];if(e[n(1235)](4,k[L][n(1818)])){let $=p[n(626)+"g"](0,e[n(386)](4,k[L][n(1818)])),G=$.concat(B);l=l[n(456)](G)}else l=l.concat(B)}return l}}function m(a,n){let s=t,l=a[s(1249)];e[s(965)](void 0,l)&&(ge(n,10),e[s(1721)](U,n,l));let f=a.value;e[s(786)](void 0,f)&&(e[s(1721)](ge,n,18),e[s(707)](U,n,f))}function _(a){let n=t,s={};e:for(;!e[n(1330)](V,a);){let l=e[n(1242)](pe,a);switch(l>>>3){case 0:break e;case 1:s.key=e[n(707)](D,a,e.zYJiD(pe,a));break;case 2:s[n(850)]=e[n(1721)](D,a,e.WRReZ(pe,a));break;default:e[n(1721)](C,a,e[n(1800)](7,l))}}if(e[n(398)](void 0,s.key))throw new Error(n(354)+n(1151)+" field: "+n(1249));if(s[n(850)]===void 0)throw new Error(e[n(1458)]);return s}function S(a){let n=t,s=e[n(1643)](R);return e[n(707)](y,a,s),e[n(302)](N,s)}function y(a,n){let s=t,l=a[s(1750)];e[s(494)](void 0,l)&&(ge(n,8),e[s(707)](wt,n,l));let f=a.LogID;e[s(1235)](void 0,f)&&(e[s(707)](ge,n,16),e[s(639)](wt,n,f));let g=a[s(797)];g!==void 0&&(e[s(659)](ge,n,24),e[s(429)](wt,n,e.gTagN(P,g)));let w=a.method;w!==void 0&&(e[s(1428)](ge,n,32),e[s(429)](wt,n,e[s(353)](P,w)));let E=a[s(1115)];if(e.zqAYl(void 0,E))for(let be of E){e[s(659)](ge,n,42);let me=e[s(1643)](R);m(be,me),ge(n,me[s(1783)]),e[s(773)](W,n,me),e[s(689)](O,me)}let p=a[s(1813)+s(501)];if(p!==void 0)if(e.Zksqy(s(452),e[s(1707)]))e[s(1721)](ge,n,50),e[s(1721)](U,n,p);else return this[s(1226)]?this._ws[s(1239)+"ns"]:"";let k=a["payloadT"+s(529)];e[s(909)](void 0,k)&&(ge(n,58),U(n,k));let L=a[s(1139)];e[s(786)](void 0,L)&&(e.KGLOm(ge,n,66),ge(n,L[s(1818)]),ae(n,L));let B=a[s(1233)];e.FMfNF(void 0,B)&&(e[s(1759)](ge,n,74),e.VrKHQ(U,n,B));let $=a[s(978)+"ming"];$!==void 0&&(e[s(1721)](ge,n,82),U(n,$));let G=a[s(1302)];e[s(331)](void 0,G)&&(e[s(582)](ge,n,90),e[s(1368)](U,n,G));let j=a[s(625)+"e"];e[s(786)](void 0,j)&&(e[s(1298)](ge,n,96),e.woTeS(wt,n,e.fzUCU(P,j)))}function v(a){let n=t;if(e[n(736)](e.IZCYd,n(1141)))return e[n(379)](I,M(a));e[n(1288)](_0x527d8e,65536)?_0x3e7f2e[_0x33c0f3++]=e[n(1792)](e.aQfBY(_0x969319,12)&15,224):(_0x29b904[_0x10bebf++]=e[n(861)](e[n(1305)](_0x1f52ba>>18,7),240),_0x3406b1[_0x50e233++]=e[n(1792)](e[n(1800)](e[n(669)](_0x5d85e3,12),63),128)),_0x43f957[_0x31940f++]=e.zCiEO(e.wOrmA(_0x20cb6c,6),63)|128}function I(a){let n=t,s={};e:for(;!e[n(1055)](V,a);){let l=e[n(302)](pe,a);switch(e[n(1555)](l,3)){case 0:break e;case 1:s[n(1750)]=kt(a,!0);break;case 2:s[n(1292)]=kt(a,!0);break;case 3:s[n(797)]=e[n(767)](pe,a);break;case 4:s[n(826)]=pe(a);break;case 5:{let f=e[n(302)](A,a);(s.headers||(s[n(1115)]=[]))[n(1241)](e[n(580)](_,a)),a[n(1783)]=f;break}case 6:s[n(1813)+n(501)]=e[n(295)](D,a,pe(a));break;case 7:s[n(748)+"ype"]=e.MNKIe(D,a,e[n(767)](pe,a));break;case 8:s.payload=e.DwJqg(se,a,pe(a));break;case 9:s.LogIDNew=D(a,e.MlIbI(pe,a));break;case 10:s.serverTiming=e[n(1721)](D,a,e[n(302)](pe,a));break;case 11:s[n(1302)]=e.ZtGmW(D,a,e[n(689)](pe,a));break;case 12:s[n(625)+"e"]=e[n(1007)](pe,a);break;default:e[n(1650)](C,a,e[n(863)](7,l))}}if(e[n(1039)](void 0,s[n(1750)]))throw new Error(e[n(675)]);if(s[n(1292)]===void 0)throw new Error(e[n(1222)]);if(e[n(398)](void 0,s.service))throw new Error(e[n(1578)]);if(e[n(1625)](void 0,s.method))throw new Error(e[n(1629)]);return s}function A(a){let n=t,s=e[n(302)](pe,a),l=a[n(1783)];return a[n(1783)]=e[n(982)](a[n(663)],s),l}function C(a,n){let s=t;switch(n){case 0:for(;e[s(1305)](128,e[s(1142)](te,a)););break;case 2:e.MvzbZ(J,a,e[s(1107)](pe,a));break;case 5:e.toqgY(J,a,4);break;case 1:e.iFPXW(J,a,8);break;default:throw new Error(e[s(982)](s(979)+"ented ty"+s(1412),n))}}function P(a){let n=t;return a|=0,{low:a,high:a>>31,unsigned:e[n(594)](a,0)}}let b=[];function R(){let a=t,n=b.pop();return n?(n[a(663)]=n[a(1783)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){b[t(1241)](a)}function M(a){return{bytes:a,offset:0,limit:a[t(1818)]}}function N(a){let n=t,s=a.bytes,l=a.limit;return e[n(398)](s[n(1818)],l)?s:s[n(709)](0,l)}function J(a,n){let s=t;if(e.DZlBj(e.VpqFo(a[s(663)],n),a[s(1783)]))throw new Error(e[s(985)]);a[s(663)]+=n}function V(a){let n=t;return e[n(594)](a[n(663)],a.limit)}function re(a,n){let s=t,l=a[s(1484)],f=a[s(663)],g=a.limit,w=e[s(982)](f,n);if(e[s(1515)](w,l.length)){let E=new Uint8Array(2*w);E.set(l),a[s(1484)]=E}return a.offset=w,e[s(940)](w,g)&&(a.limit=w),f}function Y(a,n){let s=t,l=a.offset;if(e[s(940)](e.cCjeT(l,n),a[s(1783)]))throw new Error(e[s(1198)]);return a[s(663)]+=n,l}function se(a,n){let s=t,l=e[s(1759)](Y,a,n);return a[s(1484)].subarray(l,e.XxDVm(l,n))}function ae(a,n){let s=t,l={ZZAVh:function(f,g,w){return e[Z(1759)](f,g,w)},gUWeJ:function(f,g){return e.xrCLT(f,g)}};if(e.Bruoo(s(1134),e[s(784)])){let f=e[s(1050)](re,a,n[s(1818)]);a[s(1484)][s(1172)](n,f)}else _0x558029(_0x131b8d,32),utAswd.ZZAVh(_0x232252,_0x29a2fb,utAswd[s(362)](_0x48ceb7,_0x2a45da))}function D(a,n){let s=t,l={WPsxj:function(k,L){return k(L)}},f=e[s(1788)](Y,a,n),g=String["fromChar"+s(1812)],w=a.bytes,E="\uFFFD",p="";for(let k=0;e.JKvcw(k,n);k++){let L=w[e.GtaKc(k,f)],B,$,G,j;if(e.KaxTp(e.sOJPT(128,L),0))p+=e[s(531)](g,L);else if(e[s(736)](e.sOJPT(224,L),192))e.NGMhG(e[s(982)](k,1),n)?p+=E:(B=w[e[s(1775)](k,f)+1],e.OjiOD(192&B,128)?p+=E:(j=e[s(819)](e[s(629)](e.TvJZV(31,L),6),e[s(1534)](63,B)),e[s(450)](j,128)?p+=E:(p+=g(j),k++)));else if(e.ZUsYz(e[s(363)](240,L),224))e[s(1799)](k,2)>=n?p+=E:(B=w[e[s(1746)](k+f,1)],$=w[e.EcfEX(k,f)+2],e[s(486)](e[s(861)](B,e[s(629)]($,8)),49344)!==32896?p+=E:(j=e[s(1489)](e[s(622)]((15&L)<<12,e[s(629)](e.sOJPT(63,B),6)),e[s(363)](63,$)),e.nbOVI(j,2048)||j>=55296&&e[s(1777)](j,57343)?p+=E:(p+=e[s(729)](g,j),k+=2)));else if(e[s(657)](248,L)==240)if(e[s(655)](e.PkHDA(k,3),n))p+=E;else if(B=w[e[s(949)](e[s(1775)](k,f),1)],$=w[e[s(1382)](k,f)+2],G=w[e[s(1413)](e[s(641)](k,f),3)],e[s(909)](e[s(1423)](e[s(827)](e[s(408)](B,e[s(1128)]($,8)),e[s(685)](G,16)),12632256),8421504))p+=E;else if(j=e.utddW(e.HXNmH(e[s(685)](e[s(863)](7,L),18),e[s(685)](e.dsHLc(63,B),12)),e[s(629)](e.ZfLFN(63,$),6))|e[s(1699)](63,G),e.SvOOD(j,65536)||e[s(883)](j,1114111))p+=E;else{if(s(384)===e.ndMcx)return l.WPsxj(_0x17dac1,_0x1e783e);j-=65536,p+=e[s(1225)](g,(j>>10)+55296,e[s(1799)](1023&j,56320)),k+=3}else p+=E}return p}function U(a,n){let s=t,l={WJQYq:function(p,k,L){return e[Z(1664)](p,k,L)},vPWGL:s(399)},f=n[s(1818)],g=0;for(let p=0;e[s(980)](p,f);p++){let k=n[s(1255)+"At"](p);e.WjWWm(k,55296)&&e.Oytia(k,56319)&&e[s(450)](p+1,f)&&(k=e[s(386)](e[s(1337)](e[s(1128)](k,10),n[s(1255)+"At"](++p)),56613888)),g+=e[s(673)](k,128)?1:e.RTBgT(k,2048)?2:k<65536?3:4}e[s(639)](ge,a,g);let w=e[s(517)](re,a,g),E=a.bytes;for(let p=0;e[s(572)](p,f);p++){let k=n.charCodeAt(p);if(e[s(655)](k,55296)&&k<=56319&&e[s(1712)](e[s(1179)](p,1),f)&&(k=e[s(1036)](k,10)+n[s(1255)+"At"](++p)-56613888),e[s(1288)](k,128))E[w++]=k;else{if(e.jYgNq(k,2048))E[w++]=e[s(622)](e[s(1528)](k>>6,31),192);else if(e[s(1782)](e[s(1763)],s(313)))e[s(673)](k,65536)?E[w++]=e[s(408)](e[s(1511)](e[s(669)](k,12),15),224):(E[w++]=e.UNSWy(k>>18&7,240),E[w++]=e[s(1565)](e[s(1708)](k,12)&63,128)),E[w++]=e.fSotR(e[s(1708)](k,6)&63,128);else{let L=this[s(1464)+s(933)]?.[s(875)+s(1420)+"nt"](),B=this[s(1796)]["reconnectInterce"+s(1815)](_0x4b62bd[s(552)],_0x46bd05[s(1491)]);this["_dispatc"+s(904)+s(1558)](l[s(411)](_0x24f045,l[s(860)],{code:1006,reason:_0xd8b58b[s(1491)]||s(1503)+s(906)+s(403)+s(395)+s(592)+"ame: "+L,willReconnect:B})),B&&this[s(371)]();return}E[w++]=e[s(528)](63,k)|128}}}function W(a,n){let s=t,l=e.kuTJB(re,a,n[s(1783)]),f=a.bytes,g=n[s(1484)];for(let w=0,E=n[s(1783)];e[s(673)](w,E);w++)f[w+l]=g[w]}function te(a){let n=t;return a[n(1484)][e[n(1758)](Y,a,1)]}function nt(a,n){let s=t,l=e.SIfiz(re,a,1);a[s(1484)][l]=n}function pe(a){let n=t,s=0,l=0,f;do f=e[n(1055)](te,a),e[n(1747)](s,32)&&(l|=e[n(1528)](127,f)<<s),s+=7;while(e[n(363)](128,f));return l}function ge(a,n){let s=t;for(n>>>=0;n>=128;)if(e[s(739)](e[s(1224)],e[s(1210)]))nt(a,e.buaWC(127&n,128)),n>>>=7;else{let{url:l}=_0x5beb19||{},f=_0x287c96.isArray(l)?l:e.ZUsYz(e[s(849)],typeof l)?[l]:[];_0x3a916f&&_0x147fe9.assign(this[s(1796)],_0xb41b5),f&&f[s(1818)]?this[s(1464)+s(933)]=new _0x278f53(f,this._options[s(1102)+"es"]):this["_endpoin"+s(933)]?.["resetEnd"+s(646)+"fig"](),this[s(886)+s(1801)]?.[s(1126)+"nter"](this[s(1796)]["pingLoss"+s(680)]),this[s(1580)+s(1108)]=!1,this._ws&&e.Bruoo(this._ws[s(1789)+"te"],this[s(704)])?this[s(1374)+s(383)](1e3,s(1744)+s(1401)+s(881),!0):(this._isInit=!0,this[s(371)]())}e.UpXNq(nt,a,n)}function kt(a,n){let s=t,l=0,f=0,g=0,w;return w=e.MlIbI(te,a),l=e[s(657)](127,w),e.JZScl(128,w)&&(e.wzRjX===s(1530)?(w=e.wwvZA(te,a),l|=e[s(499)](127,w)<<7,e.JZScl(128,w)&&(w=te(a),l|=e.nICkR(e[s(1019)](127,w),14),e.EMHzH(128,w)&&(w=e[s(1674)](te,a),l|=e.mTEal(e.tQxNq(127,w),21),128&w&&(w=e[s(1007)](te,a),f=e[s(1017)](127,w),e[s(363)](128,w)&&(e[s(1165)](e[s(1665)],e[s(1665)])?(w=e[s(689)](te,a),f|=e[s(685)](127&w,7),e[s(731)](128,w)&&(w=e[s(1811)](te,a),f|=e[s(1800)](127,w)<<14,128&w&&(w=e.QyQSf(te,a),f|=e[s(629)](e[s(1534)](127,w),21),e.sWVie(128,w)&&(w=e[s(1307)](te,a),g=e[s(1057)](127,w),128&w&&(w=te(a),g|=e[s(1488)](127,w)<<7))))):this.emit(e.yySxZ,e[s(973)](_0x70c67c,e.yySxZ,{..._0x140f5b}))))))):(e[s(947)](_0x52a366,2048)?_0xc1a259[_0x4a3601++]=e[s(613)](e[s(1797)](e[s(1306)](_0x3c5fbb,6),31),192):(e.jYgNq(_0x47d7da,65536)?_0x23ded4[_0x364306++]=e[s(819)](e[s(1756)](_0x577491,12)&15,224):(_0x13ea58[_0x22382f++]=e.ycCeX(e[s(1105)](_0x759072>>18,7),240),_0x4db8cd[_0x5e7ae1++]=e[s(622)](e[s(1800)](e[s(669)](_0x191cbf,12),63),128)),_0x47c0c9[_0x2ba39e++]=e.HYGFM(_0x5c93e4>>6,63)|128),_0x5c77c2[_0x1555b3++]=e[s(648)](63&_0x275caf,128))),{low:l|e[s(1128)](f,28),high:e[s(435)](e[s(289)](f,4),g<<24),unsigned:n}}function wt(a,n){let s=t,l=e[s(1555)](n[s(1711)],0),f=e[s(289)](e[s(1202)](n[s(1711)]>>>28,n[s(1485)]<<4),0),g=e[s(1728)](n[s(1485)],24),w=e[s(1625)](0,g)?e[s(1123)](0,f)?e[s(279)](l,16384)?l<128?1:2:l<2097152?3:4:e[s(1712)](f,16384)?e[s(309)](f,128)?5:6:e.YlIqB(f,2097152)?7:8:e[s(450)](g,128)?9:10,E=e.MNKIe(re,a,w),p=a[s(1484)];switch(w){case 10:p[e.PkHDA(E,9)]=e[s(1534)](e[s(1728)](g,7),1);case 9:p[e[s(1516)](E,8)]=e[s(331)](9,w)?e[s(557)](128,g):e[s(1122)](127,g);case 8:p[e[s(550)](E,7)]=e[s(331)](8,w)?e[s(1051)](e[s(1728)](f,21),128):e.cgXuV(e[s(868)](f,21),127);case 7:p[e[s(1425)](E,6)]=w!==7?f>>>14|128:e[s(1215)](f,14)&127;case 6:p[E+5]=e.CouHV(6,w)?e.UmyxN(e[s(1555)](f,7),128):e[s(1797)](e[s(1728)](f,7),127);case 5:p[E+4]=e[s(1261)](5,w)?e[s(648)](128,f):e.dycde(127,f);case 4:p[e[s(1425)](E,3)]=e[s(1173)](4,w)?e[s(1792)](e.KNtBd(l,21),128):e[s(776)](l,21)&127;case 3:p[e[s(1179)](E,2)]=e[s(1607)](3,w)?e[s(622)](e[s(776)](l,14),128):e[s(1113)](l>>>14,127);case 2:p[E+1]=w!==2?e.hzqss(e[s(289)](l,7),128):e[s(776)](l,7)&127;case 1:p[E]=e.UGPfP(1,w)?e.papKa(128,l):e[s(1699)](127,l)}}function sn(a){return e[t(809)](v,a)}function qt(a){return e[t(1071)](S,a)}let on=65536,Yr=e.DtBmA,ye=e[t(1430)](on,on),Re=e[t(1163)](ye,ye),nr=Re/2,Me=String[t(1353)+"e"].charCodeAt;class ue{constructor(n,s,l){let f=t;this[f(1063)]=!0,this[f(1711)]=0|n,this[f(1485)]=e.jlVAb(0,s),this[f(1175)]=!!l}static[t(1063)](n){let s=t;return n&&e[s(398)](!0,n[s(1063)])}static[t(963)](n,s,l){return new ue(n,s,l)}static[t(1029)+"s"](n,s,l){return l?ue[t(1029)+"sLE"](n,s):ue.fromBytesBE(n,s)}static[t(1029)+"sLE"](n,s){let l=t;return new ue(e[l(827)](e[l(1406)](n[0]|e[l(1780)](n[1],8),n[2]<<16),n[3]<<24),e[l(1398)](n[4],e[l(741)](n[5],8))|n[6]<<16|e.KwHlk(n[7],24),s)}static["fromByte"+t(628)](n,s){let l=t;return new ue(e[l(672)](e[l(1422)](e.hGKeJ(n[4],24),e[l(1586)](n[5],16)),e.XgBEU(n[6],8))|n[7],e[l(861)](e[l(583)](e[l(1395)](e.fGxZP(n[0],24),e[l(1251)](n[1],16)),n[2]<<8),n[3]),s)}static[t(1318)](n){let s=t,l={Rhany:e.MBSfp,YTeTB:function(f,g){return f+g},XRTBz:function(f,g){return e[Z(1148)](f,g)},lkmnn:function(f,g){return e[Z(1423)](f,g)},yYqZc:function(f,g){return e.uFBLz(f,g)},seeVP:function(f,g){return e.wOrmA(f,g)},rgRYi:function(f,g){return e[Z(585)](f,g)}};if(e[s(742)]!=="kAFdh")return e.ohkOW(n,Yr)?sl:new ue(e.FsYec(e[s(991)](e[s(1451)](e[s(1459)](Me[s(994)](n,0),e[s(629)](Me.call(n,1),8)),e[s(867)](Me[s(994)](n,2),16)),Me.call(n,3)<<24),0),e[s(1002)](e[s(835)](e[s(1477)](Me[s(994)](n,4),e[s(685)](Me[s(994)](n,5),8)),e[s(1280)](Me[s(994)](n,6),16)),Me[s(994)](n,7)<<24)>>>0,!0);{let f=l[s(1234)].split("|"),g=0;for(;;){switch(f[g++]){case"0":_0x1c259d=l[s(406)](65536+l[s(1073)](l[s(968)](1023,_0x1695df),10),1023&_0x93ecb9);continue;case"1":_0x4b983a[_0x38eb6d++]=l[s(968)](63,_0x3e05ec)|128;continue;case"2":_0x394a9e[_0x1c9c94++]=l[s(1514)](l[s(1013)](_0x33bedb,18),240);continue;case"3":_0x2af229[_0x32ef89++]=l[s(968)](_0x2c835>>6,63)|128;continue;case"4":_0x390d44[_0x5952ca++]=l[s(1514)](l[s(968)](l[s(1021)](_0xed19ae,12),63),128);continue;case"5":++_0x59361f;continue}break}}}[t(1702)](){let n=t;if(e[n(1757)](e.CUgCu,n(617)))return String[n(652)+"Code"](e[n(1019)](255,this.low),e.IAbnP(e[n(1067)](this[n(1711)],8),255),this[n(1711)]>>>16&255,e.FsYec(this[n(1711)],24),e[n(316)](255,this[n(1485)]),this[n(1485)]>>>8&255,e.PGKzk(this[n(1485)]>>>16,255),e[n(1362)](this[n(1485)],24));this[n(964)+n(426)]=null}static fromNumber(n,s=!0){let l=t;if(isNaN(n))return s?Up:sl;if(s){if(e.ItMZj!==e[l(869)])e[l(1298)](_0x24ff3c,_0x47963c,74),e[l(478)](_0x5a9e59,_0xa29c09,_0x31bcc8);else if(e[l(1596)](n,Re))return Hp}else{if(e[l(960)](n,-nr))return qp;if(e[l(594)](e[l(1267)](n,1),nr))return Gp}return ue[l(963)](e[l(808)](e[l(1339)](n,ye),0),e.vIHlN(n,ye)|0,s)}[t(1773)](){let n=t;if(e[n(494)](e[n(894)],e[n(894)]))try{return n(1075)!=typeof _0x2bc067&&(e[n(324)](_0x1f1b0f,_0x221a06)||_0x46b48b[n(923)]&&e[n(324)](_0x1a9e54[n(923)],_0x5a7174))||e.Voilw(e[n(849)],typeof _0x635c5b)?"":(_0x1dc4ba[n(591)](_0x368987),e.Eaqyy)}catch{return e.ZUsYz(e[n(849)],typeof _0x8eea21)?e[n(977)]:""}else return this.unsigned?e[n(289)](this.high,0)*ye+e[n(1215)](this[n(1711)],0):e[n(949)](e[n(1163)](this[n(1485)],ye),e.KNtBd(this[n(1711)],0))}[t(899)](){let n=t;return e[n(1156)](0,this.high)&&e[n(1776)](0,this[n(1711)])}add(n){let s=t;if(e[s(1782)](s(277),e[s(274)])){ue[s(1063)](n)||(n=ue[s(1409)+"er"](n));let l=this.high>>>16,f=65535&this[s(1485)],g=e[s(1539)](this[s(1711)],16),w=e[s(1019)](65535,this.low),E=e[s(289)](n.high,16),p=e[s(1049)](65535,n[s(1485)]),k=e[s(1555)](n.low,16),L=65535&n[s(1711)],B=0,$=0,G=0,j=0;return j+=e[s(1425)](w,L),G+=e[s(351)](j,16),j&=65535,G+=g+k,$+=e[s(1539)](G,16),G&=65535,$+=e[s(620)](f,p),B+=e.OOOwN($,16),$&=65535,B+=e.eQnVr(l,E),B&=65535,ue[s(963)](e[s(1540)](e.ZtBXa(G,16),j),B<<16|$,this.unsigned)}else return this[s(1236)][s(1239)+"ns"]}equals(n){let s=t;return ue[s(1063)](n)||(n=ue[s(1409)+"er"](n)),e[s(739)](this.unsigned,n[s(1175)])&&e[s(1355)](e[s(345)](this[s(1485)],31),1)&&e[s(1776)](e[s(1e3)](n.high,31),1)?!1:e.Sgzft(this[s(1485)],n[s(1485)])&&this.low===n[s(1711)]}[t(1394)](){let n=t;if(e[n(736)](e[n(306)],n(1030)))return e[n(481)](-1,this[n(1711)])&&this[n(1485)]===-1?ue[n(963)](0,0,this[n(1175)]):e.CeIdL(-1,this[n(1711)])?ue[n(963)](0,this[n(1485)]+1,this[n(1175)]):ue[n(963)](e.XxDVm(this[n(1711)],1),this[n(1485)],this[n(1175)]);if(e.aHbvs(_0x21eb26,-_0x24cab8))return _0x495e6a;if(e[n(1610)](e[n(1710)](_0x309bac,1),_0x5e3f87))return _0x2620d4}toBytes(n){let s=t;if(e.Sgzft(e[s(992)],e.JiXqr))_0x5a2c19(this[s(1397)+"lTimeoutId"]),this[s(1397)+"lTimeoutId"]=e[s(659)](_0x1ed3ca,()=>{let l=s;this[l(725)+l(993)]()},this._interval);else return n?this[s(1705)+"E"]():this[s(747)+"E"]()}[t(1705)+"E"](){let n=t,s=this.high,l=this[n(1711)];return[e[n(1034)](255,l),e[n(1145)](e.ucjfp(l,8),255),e[n(1539)](l,16)&255,e[n(1061)](l,24),255&s,e[n(1445)](e[n(289)](s,8),255),s>>>16&255,s>>>24]}toBytesBE(){let n=t,s=this[n(1485)],l=this[n(1711)];return[e.pFWJq(s,24),e[n(363)](e[n(879)](s,16),255),e[n(657)](s>>>8,255),e[n(1454)](255,s),e[n(568)](l,24),e[n(1245)](l>>>16,255),e.JZScl(e[n(1018)](l,8),255),e[n(1666)](255,l)]}}let sl=new ue(0,0,!1),Up=new ue(0,0,!0),Gp=ue.fromBits(-1,2147483647,!1),Hp=ue[t(963)](-1,-1,!0),qp=ue[t(963)](0,-2147483648,!1);var an=(function(a){let n=t,s={UlvDV:e[n(914)],NCxig:function(l,f){return e[n(528)](l,f)},ZCCva:function(l,f){return l|f},nkCqc:function(l,f){return l<f},Nsuvu:function(l,f){return e.OOOwN(l,f)},TZnGn:function(l,f){return e[n(629)](l,f)},TnABD:function(l,f){return e.cvAyz(l,f)},dfJet:function(l,f){return e[n(627)](l,f)}};if(e.vYeJh(e[n(1677)],e[n(844)]))return a[a[e.VLOTe]=5001]=n(1618)+n(1624),a[a[e[n(728)]]=5002]=e[n(728)],a[a.MAX_RETRIES_ERROR=5003]=e.YVqPt,a[a[e.XruVe]=5004]=e[n(1483)],a[a[e[n(1006)]]=5005]=n(1046)+"OR",a;{let l={GyRkR:s.UlvDV,PaIge:function(g,w){return g<w},uwvWw:function(g,w){return s[n(1380)](g,w)},ROrnH:function(g,w){return g<w},vVqaB:function(g,w){return s[n(1206)](g,w)},pZAsq:function(g,w){return s[n(1725)](g,w)},aGEEj:function(g,w){return s[n(952)](g,w)},suPuN:function(g,w){return s[n(1509)](g,w)},hFAAA:function(g,w){return s.TnABD(g,w)},RjZcb:function(g,w){return s[n(779)](g,w)},ZyqsW:function(g,w){return g|w},vMgVV:function(g,w){return s.TZnGn(g,w)},EyMmh:function(g,w){return g&w},xZIJa:function(g,w){return s[n(779)](g,w)},FZTno:function(g,w){return g&w}},f=4294967295;return function(g,w,E=!0){let p=n,k=l.GyRkR[p(1414)]("|"),L=0;for(;;){switch(k[L++]){case"0":if(l[p(1333)](g[w++],128))return{value:E?f:0|f,offset:w};continue;case"1":f=l[p(772)](127,g[w])>>>0;continue;case"2":if(l[p(1550)](g[w++],128))return{value:E?f:l[p(284)](0,f),offset:w};continue;case"3":return{value:E?f:l[p(284)](0,f),offset:w};case"4":if((w+=5)>g[p(1818)])throw w=g.length,_0x3cc3e7(w,10,g[p(1818)]);continue;case"5":if(l.pZAsq(g[w++],128))return{value:E?f:l[p(284)](0,f),offset:w};continue;case"6":if(l[p(1550)](g[w++],128))return{value:E?f:l[p(284)](0,f),offset:w};continue;case"7":f=l[p(445)](f|l[p(1517)](15&g[w],28),0);continue;case"8":if(l[p(708)](g[w++],128))return{value:E?f:l[p(284)](0,f),offset:w};continue;case"9":f=l.RjZcb(l[p(1448)](f,l[p(427)](l.uwvWw(127,g[w]),21)),0);continue;case"10":f=l.ZyqsW(f,l[p(427)](l[p(593)](127,g[w]),7))>>>0;continue;case"11":f=l[p(884)](l[p(1448)](f,l.vMgVV(l.FZTno(127,g[w]),14)),0);continue}break}}}})({});class rr{constructor(n){let s=t;this[s(400)]=n,this[s(443)]=null}}class ol extends rr{constructor(n,s){let l=t;super(n),this[l(958)]=s&&s[l(958)]||null}}class al extends rr{constructor(n,s){let l=t,f=(l(798)+l(432))[l(1414)]("|"),g=0;for(;;){switch(f[g++]){case"0":super(n);continue;case"1":this.error=s&&s[l(1473)]||null;continue;case"2":this[l(552)]=s&&s[l(552)]||5001;continue;case"3":this.filename=s&&s[l(1584)]||"";continue;case"4":this[l(534)]=s&&s[l(534)]||0;continue;case"5":this.colno=s&&s.colno||0;continue;case"6":this[l(958)]=s&&s[l(958)]||"";continue}break}}}class cl extends rr{constructor(n,s){let l=t,f="1|2|3|4|0"[l(1414)]("|"),g=0;for(;;){switch(f[g++]){case"0":this[l(1332)+l(789)]=s&&s[l(1332)+l(789)]||!1;continue;case"1":super(n);continue;case"2":this[l(552)]=s&&s.code||0;continue;case"3":this[l(1491)]=s&&s[l(1491)]||"";continue;case"4":this[l(746)]=s&&s.wasClean||!1;continue}break}}}class dl extends rr{constructor(n,s){let l=t;super(n),this[l(1112)]=s&&s[l(1112)]||null}}class ll extends dl{constructor(n,s){let l=t;super(n),this[l(1112)]=s&&s[l(1112)]||null,this[l(958)]=s&&s[l(958)]||null}}class ul extends rr{constructor(n,s){let l=t;super(n),this[l(1112)]=s&&s.data||null}}function ut(a,{message:n,code:s,error:l}){return new al(a,{message:n,code:s,error:l})}function _t(a,{code:n,reason:s,wasClean:l,willReconnect:f}){let g=t;if(e[g(1529)](e[g(654)],"mteyi"))this[g(766)+"T"]?_0x1cd5dc["onNetwor"+g(498)+g(1545)](({isConnected:w})=>{let E=g;this["_miniNav"+E(1671)+"line"]=w,w?this[E(1180)+E(771)]():this[E(1180)+"ffLine"]()}):this[g(1669)+"X"]&&_0x17c92c[g(679)+"kStatusC"+g(1545)](({isConnected:w})=>{let E=g;this[E(1378)+E(1671)+E(1587)]=w,w?this[E(1180)+E(771)]():this[E(1180)+E(1154)]()});else return new cl(a,{code:n,reason:s,wasClean:l,willReconnect:f})}function fl(a,{data:n,message:s}){return new ll(a,{data:n,message:s})}function hl(a,{data:n}){return new ul(a,{data:n})}function pa(a,{message:n}){return new ol(a,{message:n})}class xl{constructor(n,s){let l=t;this.endpoints=n,this[l(1102)+"es"]=s,this[l(719)+l(889)]=0,this[l(1028)+l(519)+l(1269)+"t"]=0}[t(1717)+"pointCon"+t(1146)](){let n=t;this[n(719)+n(889)]=0,this["currentE"+n(519)+n(1269)+"t"]=0}[t(416)+"es"](){let n=t;this[n(1028)+n(519)+n(1269)+"t"]=0}[t(875)+t(1420)+"nt"](){let n=t;return this[n(462)+"s"][this[n(719)+n(889)]]}[t(875)+"ntEndpoi"+t(381)+t(1232)](){let n=t;return this[n(1028)+n(519)+"riesCount"]}[t(1301)+"chMaxTries"](){let n=t;return!!(e[n(377)](this[n(719)+n(889)],this.endpoints[n(1818)])||e.SnpYt(this["currentI"+n(889)],e.UdXgH(this.endpoints.length,1))&&e[n(1218)](this[n(1028)+n(519)+n(1269)+"t"],this.maxRetries))}[t(1410)+t(917)+t(1041)+t(1508)+"tries"](){let n=t;return e.cHTQj(e[n(1293)],e.rOuhT)?this[n(1226)]?this[n(1226)][n(1166)+"pe"]:this[n(640)+n(529)]:e[n(831)](this[n(719)+"ndex"],this[n(462)+"s"][n(1818)])?!0:this[n(1028)+"ndpointTriesCount"]>this[n(1102)+"es"]}["replaceBackupEnd"+t(1101)+t(410)+t(347)](){let n=t;return this[n(1028)+n(519)+n(1269)+"t"]=1,this[n(719)+n(889)]++,this.endpoints[this[n(719)+n(889)]]}[t(875)+t(1420)+t(674)+t(523)](){let n=t;return this["currentE"+n(519)+n(1269)+"t"]++,this[n(875)+"ntEndpoint"]()}}let ir=(e[t(763)](e[t(1287)],typeof globalThis)&&e.aiIWg(e[t(1133)],globalThis["construc"+t(608)].name)||t(1456)+"d"!=typeof window&&e[t(908)](e[t(1133)],window[t(687)+"tor"][t(1502)]))&&e.cCDPx!=typeof document,Pn=e[t(1287)]!=typeof globalThis&&(e[t(1817)](e[t(1588)],globalThis[t(687)+t(608)][t(1502)])||e[t(1069)]("DedicatedWorkerGlobalScope",globalThis[t(687)+t(608)][t(1502)]))&&e[t(1171)](e[t(1287)],typeof tt),Qr=(e[t(936)](t(1456)+"d",typeof globalThis)&&e[t(1588)]===globalThis[t(687)+t(608)][t(1502)]||e[t(1526)](e[t(1287)],typeof globalThis)||e.cCDPx!=typeof globalThis&&!!globalThis[t(1803)+"Bridge"])&&e.yjlJj(e[t(1287)],typeof wx),ei=e[t(423)](e.cCDPx,typeof globalThis)&&(e[t(1176)]("DedicatedWorkerG"+t(397)+"pe",globalThis["construc"+t(608)].name)||e[t(1363)]===globalThis[t(687)+t(608)][t(1502)]||e[t(1729)]("ServiceWorkerGlo"+t(1544),globalThis[t(687)+t(608)][t(1502)]))&&e.EGZTY(e[t(1287)],typeof self),jp=e[t(912)](e[t(1287)],typeof globalThis)&&e.ekRLk(e[t(1588)],globalThis[t(687)+"tor"][t(1502)])&&e[t(854)](e[t(1287)],typeof global)&&e[t(1355)](t(1182),global[t(687)+t(608)][t(1502)])&&e[t(469)](e[t(1287)],typeof process)&&!!process.version;class ga{constructor(){let n=t;this[n(905)+"rs"]={}}[t(1433)](n,...s){let l=t,f=this._listeners[n];if(f)f[l(1573)]().forEach(g=>g.fn.apply(g.ctx,s));else if(e[l(1776)](e[l(364)],n)&&!this.onerror){let g=s.length&&s[0];if(e[l(324)](g,Error))throw g;let w=new Error(e[l(1457)]+(g?e.lnUGS(" ("+g[l(958)],")"):""));throw w[l(1734)]=g,g}return this}[t(1399)](n,s){let l=t;if(e[l(1625)](void 0,n))this._listeners={};else if(e[l(638)](void 0,s))this._listeners[n]=null;else{let f=this[l(905)+"rs"][n];if(f)for(let g=0;e[l(450)](g,f[l(1818)]);)e[l(920)](f[g].fn,s)?f[l(1444)](g,1):++g}return this}on(n,s,l){let f=t;if(e[f(565)](e[f(1212)],e.jfMaF))return(this._listeners[n]||(this[f(905)+"rs"][n]=[]))[f(1241)]({fn:s,ctx:l||this}),this;this[f(1347)]?.[f(399)](),this[f(1347)]=void 0}}class Wp extends ga{["_formatE"+t(892)+"age"](n){let s=t;return n[s(1432)]||n[s(526)]?(s(1262)+" "+(n.errMsg||"")+s(1311)+(n[s(526)]||""))[s(1334)]():JSON.stringify(n)}constructor(n,s,l){let f=t;super(),this._socket=null,Qr&&wx["connectS"+f(1031)]&&(this[f(1236)]=wx[f(1054)+"ocket"]({url:n,protocols:s,header:l,fail:this[f(1450)+"ocketFai"+f(1220)][f(951)](this),success:this[f(1450)+f(1162)+f(476)+f(285)][f(951)](this)})),Pn&&tt.connectSocket&&(this[f(1236)]=tt[f(1054)+"ocket"]({url:n,protocols:s,header:l,fail:this[f(1450)+f(988)+"lHandler"][f(951)](this),success:this[f(1450)+f(1162)+f(476)+f(285)][f(951)](this)}))}[t(1450)+"ocketSuc"+t(476)+t(285)](){let n=t;Promise[n(718)]()[n(1486)](()=>{this["_addWsLi"+n(1434)]()})}[t(1450)+t(988)+t(1220)](n){let s=t,l={CcoEt:function(f,g,w){return f(g,w)},kikui:e[s(364)],MbbON:e.yySxZ};e.uSLQv(s(604),e.mVVyF)?this[s(1399)](_0x4c3d01,_0x2b3a7b):Promise[s(718)]().then(()=>{let f=s,g=l.CcoEt(ut,l[f(317)],{message:this[f(1637)+"rrorMess"+f(1312)](n)});this[f(1433)](l[f(317)],g);let w=l.CcoEt(_t,l[f(1487)],{reason:this[f(1637)+f(892)+"age"](n)});this.emit(l.MbbON,w)})}["_addWsLi"+t(1434)](){let n=t,s={CyfHm:function(l,f){return l!==f},LKZqe:function(l,f){return l!==f},BnvcJ:e[n(312)],GqFid:e[n(1009)],yuhXR:e[n(1431)],sQmWQ:function(l,f,g){return l(f,g)},LhSjn:e[n(1505)],ZUPgO:n(1473)};this[n(1236)][n(1209)](l=>{let f=n;this[f(1433)](e[f(1475)],e[f(937)](hl,f(1556),{...l,data:l[f(1432)]||""}))}),this[n(1236)].onClose(l=>{let f=n;s.LKZqe(s[f(1641)],s[f(1641)])?_0x9beb95.persisted&&(this[f(1025)+f(1469)]()&&(!this[f(1226)]||s[f(670)](this[f(1226)].readyState,this[f(814)])||s[f(1632)](this._ws[f(1789)+"te"],this[f(1688)+"NG"]))&&this[f(1180)+f(771)](),this[f(1571)+"er"]&&_0x350357.addEventListener(s[f(419)],this[f(1180)+f(771)]),this._isBrowser&&_0xb6333d[f(480)+f(1147)](s[f(1161)],this[f(1180)+f(1154)])):this.emit(f(399),s.sQmWQ(_t,s.LhSjn,{...l}))}),this._socket[n(1603)+"e"](l=>{let f=n;this.emit("message",e[f(639)](fl,e[f(1814)],{...l}))}),this[n(1236)][n(1153)](l=>{let f=n;this.emit(s[f(804)],s[f(983)](ut,s[f(804)],{...l,message:l.errMsg||""}))})}[t(925)](n){let s=t,l={JvHSh:function(f,g){return e[Z(863)](f,g)},DbiPz:function(f,g){return f|g},zDemW:function(f,g){return e.vYeJh(f,g)},sZjbI:e[s(1679)],RCikI:e[s(364)]};if(e[s(324)](n,Uint8Array)){let f=n.buffer[s(1573)](n[s(1640)+"et"],n[s(1553)+"th"]+n.byteOffset);this[s(1236)]&&this._socket.send({data:f,fail:g=>{let w=s;this[w(1433)](e[w(364)],e[w(937)](ut,e[w(364)],{message:this[w(1637)+"rrorMessage"](g)}))}})}else this[s(1236)]&&this[s(1236)].send({data:n,fail:f=>{let g=s,w={kgmgM:function(E,p){return E<p},UfMam:function(E,p){return E+p},TdcAK:function(E,p){return l[Z(853)](E,p)},togVD:function(E,p){return E+p},kFJhK:function(E,p){return l[Z(333)](E,p)}};if(l[g(1439)]("Iepkt",l[g(1741)]))this[g(1433)](l[g(1781)],ut(l.RCikI,{message:this["_formatE"+g(892)+g(1312)](f)}));else{if(w[g(1008)](_0x568c7c,1)||_0x10f500>_0x5d2885)return _0x42291f(_0x302959);w.UfMam(_0x6242bd,_0x1b1cc6)>_0x33a318&&(_0x691b17=_0xdc7147(_0x1cec56),_0x7d4dd7=0);let E=_0x59da92.call(_0xd13782,_0x5efbf6,_0x43fcf7+=_0x16d94c);return w[g(810)](7,_0x3843a0)&&(_0x393616=w.togVD(w[g(1646)](7,_0x281d81),1)),E}}})}[t(399)](n,s){let l=t;this._socket&&this._socket[l(399)]({code:n,reason:s})}[t(480)+"Listener"](n,s){this.on(n,s)}[t(475)+t(1327)+t(895)](n,s){this.off(n,s)}get[t(1789)+"te"](){let n=t;return this[n(1236)][n(1789)+"te"]}get binaryType(){let n=t;if(e.FveIV("cNlTd",n(862)))this[n(1226)]&&this[n(1226)][n(399)](_0x546573,_0x53594b);else return this[n(1236)][n(1166)+"pe"]}set[t(1166)+"pe"](n){}get[t(373)](){let n=t;return this[n(1236)][n(373)]}get protocol(){let n=t;return this._socket[n(1768)]}get extensions(){let n=t;return this[n(1236)][n(1239)+"ns"]}get["buffered"+t(1810)](){return 0}}function Kp(a,n){let s=t;if(e.mpsaj!==e.mpsaj)for(var l in _0x33c64b)_0x3bc88c(_0x5d1c23,l,{get:_0x393df2[l],enumerable:!0});else{if(n)return new n(a[s(373)],a[s(1768)]);if(e.VRJto(Qr,Pn))return new Wp(a[s(373)],a[s(1768)],a[s(1115)]);if(e[s(605)](ir,ei)&&e[s(1287)]!=typeof WebSocket&&WebSocket)return new WebSocket(a[s(373)],a[s(1768)+"s"])}}function $p(a){let n=t,s={RMRlX:e[n(692)],DwTeC:"FILE_NOT_EXIST"};if(e[n(1776)](e[n(1366)],e[n(1366)])){let l=e[n(634)].split("|"),f=0;for(;;){switch(l[f++]){case"0":return!1;case"1":if(Pn&&tt[n(1054)+n(1031)])return!0;continue;case"2":if(e[n(605)](ir,ei)&&e.lpDwO(e[n(1287)],typeof WebSocket)&&WebSocket)return!0;continue;case"3":if(Qr&&wx[n(1054)+n(1031)])return!0;continue;case"4":if(a)return!0;continue}break}}else return{frameType:_0x7aff3f,headers:[{key:s[n(558)],value:s.DwTeC}],payload:void 0}}function pl(a,n,s){let l=t,f={TtArc:function(E,p){return E<=p},iITRN:"next() c"+l(527)+"ltiple t"+l(1377)+l(1083),WgjEG:function(E,p){return e[l(533)](E,p)}},g=-1;async function w(E){let p=l;return f[p(1385)](E,g)?Promise[p(1739)](new Error(f[p(1285)])):(g=E,E===s[p(1818)]?Promise[p(718)]():s[E].bind(a)(n,w[p(951)](null,f[p(1320)](E,1))))}e.MlIbI(w,0)}function gl(a){let n=t,s={gbtZM:function(l,f,g){return e.kYwtm(l,f,g)},XiFLS:e.yySxZ};if(e[n(1044)]!==e[n(1662)]){let l=0,f=0;for(let g=0;e.UGHmI(g,a[n(1818)]);++g)if(f=a.charCodeAt(g),e[n(695)](f,128))l+=1;else if(f<2048)l+=2;else if(e[n(1049)](64512,f)===55296&&e[n(1079)](64512,a[n(1255)+"At"](g+1))===56320)if(e[n(777)](e[n(1691)],e.JzyBV))++g,l+=4;else{this[n(1713)+n(904)+n(1558)](s[n(396)](_0x49be45,s[n(834)],{code:1e3,reason:n(1345)})),this[n(1464)+n(933)]?.[n(1717)+n(646)+n(1146)](),this[n(886)+n(1801)]?.[n(1126)+"nter"]();return}else l+=3;return l}else return e[n(1156)](0,this[n(1485)])&&e[n(1510)](0,this[n(1711)])}function ml(a,n,s){let l=t;if(e[l(695)](s-n,1))return"";let f="";for(let g=n;g<s;)if(e.vYeJh(e[l(703)],l(1081))){let w=a[g++];if(e[l(960)](w,127))f+=String[l(652)+l(1812)](w);else if(e[l(1639)](w,192)&&e[l(450)](w,224))f+=String[l(652)+l(1812)](e.hunoO(31,w)<<6|e[l(1704)](63,a[g++]));else if(e[l(1440)](w,224)&&e[l(871)](w,240))f+=String[l(652)+l(1812)](e[l(1805)](e[l(367)]((15&w)<<12,e.tNsGb(e.dsHLc(63,a[g++]),6)),e[l(434)](63,a[g++])));else if(e.EOMAY(w,240)){let E=e[l(1316)](e[l(1202)](e.buaWC(e.lIEhF(e[l(438)](e[l(521)](7,w),18),e.ZtBXa(e.Yuhfx(63,a[g++]),12)),e.ZskHr(e[l(1034)](63,a[g++]),6)),63&a[g++]),65536);f+=String[l(652)+"Code"](e[l(1271)](55296,e[l(1756)](E,10))),f+=String["fromChar"+l(1812)](e[l(1413)](56320,e[l(762)](1023,E)))}}else this[l(320)]=_0x2aa457,this[l(740)]=_0x3b3f44,this[l(1347)]=_0x20e51d?_0x605aae:_0x4fd3f1?_0x6eb008:null;return f}function ma(a,n,s){let l=t,f=s,g,w;for(let E=0;e[l(1022)](E,a[l(1818)]);++E)if(g=a[l(1255)+"At"](E),e[l(1494)](g,128))n[s++]=g;else if(g<2048)n[s++]=e.ETvkd(g>>6,192),n[s++]=e[l(1441)](e.zYvtM(63,g),128);else if(e.gwaUQ(e.nwaIq(64512,g),55296)&&e.PVNND(e[l(1663)](64512,w=a[l(1255)+"At"](e.wkMIS(E,1))),56320)){let p=e[l(1417)][l(1414)]("|"),k=0;for(;;){switch(p[k++]){case"0":n[s++]=e[l(1449)](e[l(1467)](g,18),240);continue;case"1":n[s++]=e[l(1449)](e[l(799)](g,12)&63,128);continue;case"2":n[s++]=e[l(781)](g>>6&63,128);continue;case"3":g=e[l(573)](65536+(e.iHxYc(1023,g)<<10),e[l(1460)](1023,w));continue;case"4":++E;continue;case"5":n[s++]=e.UzLmk(63&g,128);continue}break}}else n[s++]=g>>12|224,n[s++]=e[l(956)](e[l(1090)](e[l(1756)](g,6),63),128),n[s++]=e[l(1805)](e.ufjLR(63,g),128);return e[l(386)](s,f)}async function wl(a){let n=t,s={RdHxx:function(l,f){return e[Z(635)](l,f)}};if(e[n(421)](e[n(1769)],e[n(1769)])){if(e[n(849)]==typeof a){let l=new Uint8Array(e[n(1495)](gl,a));return e.UIdhn(ma,a,l,0),l}return e[n(1200)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a.buffer,a[n(1640)+"et"],a[n(1553)+"th"])}else{let l=this[n(1347)][n(1221)+n(307)+"nc"](this._prefix),f=_0x11902f[n(591)](s[n(495)](l,"{}"));return _0x2833d9[n(287)](f)}}function Vp(a){let n=t,s={LjLqc:e[n(326)]};if(e[n(343)](e[n(1673)],e.jXzVz))try{return e[n(1774)](e[n(849)],typeof a)&&(e[n(1597)](a,ArrayBuffer)||a[n(923)]&&e.KuJmH(a[n(923)],ArrayBuffer))||e[n(1774)](e[n(849)],typeof a)?"":(JSON.parse(a),e[n(1303)])}catch{if(e.OKfSb(e[n(281)],e[n(1056)])){let l=this[n(1464)+n(933)]?.["getCurre"+n(1420)+"nt"]();this[n(1462)](n(1201)+l+" timeout"),this[n(1374)+"ect"](1001,s.LjLqc,!0)}else return e.ZUsYz(n(1075),typeof a)?n(987)+n(1767)+n(461):""}else _0x32c514[n(551)](_0x240115)}let Jp=(a,n)=>{let s=t;switch(a){case e[s(833)]:case s(1048):return{[s(340)+a]:1,"x-tt-env":n};default:return{}}};class Zp{constructor(n){let s=t;this.maxLossCount=n,this[s(1110)]=0}[t(782)](){let n=t;this[n(1110)]++}[t(1301)+t(586)+"nt"](){let n=t;return e[n(1309)](this[n(1110)],this["maxLossC"+n(1232)])}resetCounter(n=0){let s=t;this[s(1559)+s(1232)]=n,this[s(1110)]=0}}async function Xp(a){let n=t,s={RCNoA:function(l,f){return e[Z(1413)](l,f)},IIXpw:function(l,f){return e[Z(1494)](l,f)},OYomC:function(l,f,g){return l(f,g)},MMSUM:function(l,f){return e.hGKeJ(l,f)},qGMGi:function(l,f){return l===f},bGYZC:n(1693),wKVUD:function(l,f){return e.Vbklf(l,f)},TwNEF:e[n(757)],toocn:function(l){return l()},nXeKI:function(l,f,g){return e[n(865)](l,f,g)},vDywr:function(l,f){return e[n(1697)](l,f)},duXiq:e[n(721)],lxjLN:e[n(283)],LcoHF:e[n(1753)],FcDFX:e[n(664)],iYTQe:function(l,f){return e[n(856)](l,f)},wyJfC:n(1304),rNPIa:function(l,f){return e[n(508)](l,f)}};return new Promise(l=>{let f=n,g={oHjTC:function(w,E){return s.qGMGi(w,E)},Hauob:f(1613),APyzS:s[f(842)],GKJUk:function(w,E){return s[f(829)](w,E)},pcFQk:s.TwNEF,HviDY:function(w,E,p){return w(E,p)},eaHZE:function(w){return s[f(536)](w)},UHxgG:function(w,E,p){return s.nXeKI(w,E,p)},irevI:function(w,E,p){return s.OYomC(w,E,p)}};if(s.vDywr(s[f(755)],s[f(1656)])){if(!ir)return s[f(829)](l,s.TwNEF);try{let w=document[f(1140)+f(1276)](s.LcoHF);window["frontier"+f(1124)]=E=>{let p=f;if(g[p(1443)](g[p(1119)],g.APyzS)){if(this[p(1796)][p(1723)+p(1264)+p(422)]||this[p(1580)+"osed"])return;this[p(503)+"econnect"]()}else document[p(1274)]["removeCh"+p(753)](w),window[p(887)+p(1124)]=void 0,g[p(653)](l,E&&E.msg||g.pcFQk)},w[f(400)]=s[f(1599)],w[f(989)]=s[f(1371)](a[f(581)](/^ws/,s.wyJfC),f(1211)+f(463)+f(1472)+"P");try{document[f(1274)][f(1160)+f(753)](w)}catch{document[f(1274)][f(726)+f(753)](w)}}catch{if(f(1787)===f(1787))window[f(887)+"JSONP"]=void 0,s[f(589)](l,s[f(1343)]);else{let w=0,E=_0x21f00c,p=s.RCNoA(_0x3c1a1e,4);for(;s.IIXpw(E,p);){let{value:k,offset:L}=s[f(945)](_0xb534d5,_0x2d01b6,E);E=L,w=s[f(926)](w,8)>>>0,w+=k}return{value:w,offset:p}}}}else{pNOeSp.HviDY(_0xb046c9,_0x12ad36,42);let w=pNOeSp[f(661)](_0x197006);pNOeSp[f(437)](_0x4cd60f,_0x5ec1e5,w),pNOeSp.irevI(_0x142226,_0x5138bd,w[f(1783)]),_0x5c18c2(_0x2d636f,w),pNOeSp.GKJUk(_0x37cb20,w)}})}function cn(a,n,s){let l=t;return!!a?.[l(916)](f=>f[l(1249)]===n&&f[l(850)]===s)}function sr(a,n){let s=t;return a?.[s(916)](l=>l[s(1249)]===n)?.[s(850)]}let wa=null;async function Yp(){let a=t;return wa||(wa=Promise.resolve().then(Gt.bind(Gt,e[a(1589)]))),wa}class Qp extends ga{constructor(n,s){let l=t;super(),this[l(537)]=n,this._keyPath=s,this[l(1347)]=void 0,this[l(964)+l(426)]=null}async openDB(){await this[t(1681)]()}async _init(){let n=t,s={Ynhcp:function(l){return e[Z(681)](l)},BRDfN:function(l,f,g,w){return e[Z(418)](l,f,g,w)}};if(!this[n(1347)]){if(this[n(964)+n(426)])return this[n(964)+"mise"];try{let l=this._dbName,f=this[n(1012)];this[n(964)+n(426)]=(async()=>{let g=n,{openDB:w}=await s[g(1060)](Yp);this[g(1347)]=await s[g(1196)](w,g(887)+"_"+l,1,{upgrade(E){let p=g;E[p(647)+p(1045)+"e"](l,{keyPath:f})}})})(),await this[n(964)+n(426)]}catch(l){console.log(l)}finally{this[n(964)+"mise"]=null}}}async[t(928)](n){let s=t;if(e[s(1189)]===e[s(1189)])try{return e[s(1218)](e[s(525)],e.AbIHa)?(await this[s(1681)](),this[s(1347)]?.[s(928)](this[s(537)],n)):!!_0x3ab1cd?.[s(916)](l=>l.key===_0xc44cc&&l[s(850)]===_0x114275)}catch(l){console[s(551)](l)}else return s(887)+"_"+this[s(320)]}async[t(1172)](n,s){let l=t;return await this[l(1681)](),this[l(1347)]?.[l(490)](this[l(537)],n)}async[t(1415)](n){let s=t,l={rmFid:function(f,g,w,E){return e.UIdhn(f,g,w,E)},tuguI:e[s(364)]};if(e[s(1059)]!==e[s(1059)])try{l.rmFid(_0x2b800e,this,_0x5176fb,[_0x1fdf80,_0x358fea,_0x2d797c])}catch(f){let g=_0x236339(l.tuguI,{message:f[s(958)],code:_0x59f170.OPEN_ERROR,error:f});this[s(1713)+s(430)+"ent"](g)}else try{return await this[s(1681)](),this[s(1347)]?.[s(1480)](this[s(537)],n)}catch(f){e[s(1536)]!==e[s(1536)]?(_0x4cd016[s(1438)+s(575)]="",_0x4b7c61.log(_0x2e83db)):console.log(f)}}async[t(1390)](){let n=t;try{return await this[n(1681)](),this[n(1347)]?.[n(1390)](this._dbName)}catch(s){console[n(551)](s)}}async keys(){let n=t;return await this[n(1681)](),this[n(1347)]?.[n(1099)+"ys"](this._dbName)}async[t(1185)](){let n=t;if(e[n(1235)](e.ptuas,e[n(1010)]))return await this[n(1681)](),this[n(1347)]?.getAll(this[n(537)]);this._messageQueue.shift(),this[n(1581)+n(327)].push(_0xbffa67)}async[t(1203)](){let n=t;try{this[n(1347)]?.close(),this[n(1347)]=void 0}catch(s){console[n(551)](s)}}get[t(1651)](){let n=t;try{return!!this[n(1347)]}catch(s){return console.log(s),!1}}}class eg{constructor(n,s){let l=t;this[l(320)]=n,this[l(740)]=s,this._qosDB=localStorage}async[t(473)](){}get[t(730)](){return t(887)+"_"+this._DBName}async[t(928)](n){let s=t,l=this[s(1347)][s(1582)](this[s(730)]);return JSON[s(591)](e[s(1365)](l,"{}"))[n]}async[t(1172)](n,s){let l=t,f=this[l(1347)][l(1582)](this[l(730)]),g=JSON[l(591)](e[l(1531)](f,"{}"));return g[s||n[this[l(740)]]]=n,this._qosDB.setItem(this[l(730)],JSON[l(361)+"y"](g)),s||n[this[l(740)]]}async del(n){let s=t,l=this[s(1347)].getItem(this[s(730)]),f=JSON[s(591)](e.xGDVs(l,"{}"));return f[n]=void 0,this[s(1347)].setItem(this[s(730)],JSON[s(361)+"y"](f))}async clear(){let n=t;return this[n(1347)][n(1390)]()}async[t(287)](){let n=t,s=this._qosDB[n(1582)](this[n(730)]),l=JSON[n(591)](e[n(1270)](s,"{}"));return Object[n(287)](l)}async getAll(){let n=t,s=this._qosDB.getItem(this[n(730)]),l=JSON.parse(s||"{}");return Object[n(328)](l)}[t(1203)](){let n=t;return e[n(520)]==="igFtS"?0:Promise[n(718)]()}get[t(1651)](){return!!this[t(1347)]}}class tg{constructor(n,s){let l=t;this[l(320)]=n,this[l(740)]=s,this[l(1347)]=Pn?tt:Qr?wx:null}async[t(473)](){}get _prefix(){let n=t;if(e[n(1782)](e[n(1372)],e[n(1372)]))_0x5a8b2c[_0x22cff1++]=e[n(367)](e[n(1467)](_0x465ceb,18)&7,240),_0x10a12d[_0x1d48bb++]=e.HDIlm(e[n(1167)](_0x5bbf87,12)&63,128);else return n(887)+"_"+this[n(320)]}async[t(928)](n){let s=t;if(e.OGBQc(e.ZZApc,e[s(744)]))_0x3906b2=e[s(413)](_0x277ff2,_0x482931),_0x5b527c|=e[s(441)](e[s(505)](127,_0x566419),14),e[s(1611)](128,_0x21ef08)&&(_0x41651b=e[s(1107)](_0x30f861,_0x48f6f6),_0xa33329|=e[s(441)](e[s(330)](127,_0xdfb199),21),e.vhyWr(128,_0x3fd6c3)&&(_0x4d71e5=e[s(1107)](_0x3ca696,_0x4b3398),_0x288908=e.oHlTJ(127,_0x46b644),e.SGpHP(128,_0x3c4bc6)&&(_0xab8ab0=e.fPiKg(_0x1a0382,_0x2dab2c),_0x1a92bc|=(127&_0x4ceb47)<<7)));else{let l=this[s(1347)][s(1221)+s(1213)](this[s(730)]);return JSON[s(591)](e[s(635)](l,"{}"))[n]}}async set(n,s){let l=t,f=this[l(1347)][l(1221)+l(1213)](this[l(730)]),g=JSON[l(591)](f||"{}");return g[s||n[this[l(740)]]]=n,this._qosDB[l(818)+l(1213)](this[l(730)],JSON[l(361)+"y"](g)),s||n[this[l(740)]]}async[t(1415)](n){let s=t,l=this._qosDB[s(1221)+s(1213)](this[s(730)]),f=JSON.parse(e.azFsn(l,"{}"));return f[n]=void 0,this._qosDB.setStorageSync(this[s(730)],JSON[s(361)+"y"](f))}async clear(){let n=t;return this[n(1347)][n(1447)+n(790)]()}async keys(){let n=t,s=this[n(1347)]["getStora"+n(307)+"nc"](this._prefix),l=JSON[n(591)](e[n(477)](s,"{}"));return Object[n(287)](l)}async getAll(){let n=t;if(e[n(442)](e.qOQBp,e[n(845)])){if(_0x209f1b>=_0xa0dea6)return _0xf30161}else{let s=this[n(1347)][n(1221)+"geInfoSync"](this[n(730)]),l=JSON.parse(s||"{}");return Object[n(328)](l)}}[t(1203)](){return Promise.resolve()}get isReady(){return!!this[t(1347)]}}function _l(a,n){let s=t;if(e[s(635)](Pn,Pn))return new tg(a,n);if(e[s(1383)](ir,ei)&&e[s(1287)]!=typeof indexedDB)return new Qp(a,n);if((ir||ei)&&e[s(424)](s(1456)+"d",typeof localStorage))return new eg(a,n);throw new Error("init QoS"+s(1357)+"d")}class ng{constructor(){let n=t;this[n(1397)+n(910)+"Id"]=null,this[n(1397)+"l"]=36e5,this._qosDB=_l(e.xxZrn,e[n(388)])}async[t(1397)+t(1286)](){let n=t;clearInterval(this._intervalTimeoutId),this[n(1397)+"lTimeoutId"]=e[n(360)](setInterval,()=>{this[n(725)+"ired"]()},this[n(1397)+"l"])}async openDB(){let n=t;await this._qosDB.openDB()[n(1486)](()=>{let s=n;this[s(1397)+s(1286)]()})}async[t(725)+t(993)](){let n=t;(await this._qosDB?.[n(1185)]()||[])[n(1187)](({timestamp:f})=>f<Date[n(298)]())[n(1608)](f=>{let g=n;this[g(1347)]?.[g(1415)](f[g(1114)+"id"])})}async[t(1415)](n){return this[t(1347)]?.del(n)}async[t(1172)](n,s){return this[t(1347)]?.set({message_id:n,timestamp:s})}async[t(928)](n){let s=t;return this[s(1347)]?.[s(928)](n)}async[t(1203)](){let n=t;e[n(1007)](clearInterval,this[n(1397)+"lTimeoutId"]),await this[n(1347)]?.[n(1203)]()}get[t(1651)](){return this[t(1347)]?.isReady}}function _a(a){let n=t,s=!!this._options[n(511)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[n(418)](cn,a[n(958)][n(1115)],"x_fronti"+n(656),"2"),f=l&&cn(a[n(958)][n(1115)],e[n(1373)],"1"),g=l&&e[n(418)](cn,a[n(958)][n(1115)],e[n(1062)],"1"),w=g?e.ueaOP(sr,a[n(958)][n(1115)],n(815)+"er_ack_msgid")?.split(",")[n(1187)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:g,ackMsgIds:w}}async function yl(){let a=t;return this[a(518)+a(1125)]||(this[a(518)+a(1125)]=new ng),this[a(518)+a(1125)][a(1651)]||await this[a(518)+a(1125)].openDB(),this[a(518)+a(1125)]}async function rg(a,n){let s=t,{enableAutoAck:l}=this[s(1796)],f=e[s(1720)](cn,a[s(958)].headers,e.fFglu,"1"),g=e[s(610)](cn,a[s(958)][s(1115)],e[s(357)],"1"),w=_a[s(994)](this,a);if(e.BUigt(l,f)){let{SeqID:E,LogID:p,service:k,LogIDNew:L,method:B}=a.message;this._sendAck({SeqID:E,LogID:p,LogIDNew:L,service:k,method:B,headers:[{key:s(878),value:"1"},{key:e[s(372)],value:e.KYMll(L,"")},{key:e[s(590)],value:"0"}]})}g&&!w[s(447)]&&this["_dispatc"+s(1310)+"ageEvent"](a),e[s(1643)](n)}async function ig(a,n){let s=t;this[s(1462)](e[s(619)],a[s(958)]),e[s(1643)](n)}async function sg(a,n){let s=t,l=e[s(1644)](sn,await e[s(413)](wl,a[s(1112)]));try{if(e[s(324)](l.payload,Uint8Array))if(e.qfNTc(e.DvmLD,e[s(1626)])){let f=this[s(1347)][s(1221)+s(1213)](this[s(730)]),g=_0x2256e9[s(591)](e.cxzEA(f,"{}"));return g[_0xaf89d5||_0x208f7a[this._pathKey]]=_0x5efc27,this[s(1347)]["setStora"+s(1213)](this._prefix,_0x15fe8b.stringify(g)),_0x279260||_0x4dbf02[this[s(740)]]}else{let f=e[s(324)](this[s(1796)][s(1813)+s(501)],Object)?{force:!!this._options[s(1813)+s(501)][s(649)],encoding:this[s(1796)][s(1813)+"ncoding"].encoding?this[s(1796)][s(1813)+s(501)].encoding[s(581)](/\s/g,"")["toLowerC"+s(1520)]():""}:{force:!1,encoding:this._options.payloadEncoding?this[s(1796)]["payloadE"+s(501)][s(581)](/\s/g,"")[s(1011)+"ase"]():""},g=l[s(1813)+"ncoding"]?l[s(1813)+s(501)][s(581)](/\s/g,"")[s(1011)+s(1520)]():"",w=this._options[s(748)+s(529)]instanceof Object?{force:!!this[s(1796)][s(748)+s(529)][s(649)],type:this[s(1796)].payloadType[s(400)]?this[s(1796)][s(748)+"ype"].type[s(581)](/\s/g,"").toLowerCase():""}:{force:!1,type:this[s(1796)][s(748)+s(529)]?this._options[s(748)+s(529)].replace(/\s/g,"")[s(1011)+s(1520)]():""},E=l[s(748)+s(529)]?l[s(748)+"ype"][s(581)](/\s/g,"")[s(1011)+s(1520)]():"",p=w[s(649)]?w[s(400)]:E||w.type,k=f.force?f[s(768)]:g||f[s(768)],L=[s(987)+"in;charset=utf-8",e[s(1303)],s(1100)+s(1266)+s(1727)+"=utf-8",e[s(849)]],B=[s(1277)+"e",e.woBRj];this[s(1796)]["enableTr"+s(813)+s(1350)+"ad"]&&L[s(934)](p)&&(!k||B[s(934)](k))?l[s(1438)+s(575)]=e[s(610)](ml,l[s(1139)],0,l.payload[s(1553)+"th"]):l[s(1438)+"oad"]=""}else l[s(1438)+s(575)]=""}catch(f){l["textPayl"+s(575)]="",console[s(551)](f)}a.message=l,e[s(1386)](n)}function og(a,n,s){let l=t,f={IjUHS:function(g,w){return e[Z(491)](g,w)},kFwss:function(g,w){return e.YBLCB(g,w)}};if(e.Sgzft(l(444),e[l(1617)]))return _0x20a449[l(1074)+"8"]?{value:_0x3ffa00.readUInt8(_0x2e7c75),offset:f[l(574)](_0x40bc0e,1)}:{value:f[l(530)](255,_0x219c58[_0xd5a66c]),offset:_0x98137a+1};{let g=e.kKJOa(s,8192),w=e[l(694)](g,1),E=null,p=g;return function(k){let L=l,B={rZqQX:L(1075),GIbkz:function(G,j){return e[L(888)](G,j)},cqStk:function(G,j,be,me){return e[L(418)](G,j,be,me)}};if(e[L(572)](k,1)||e[L(940)](k,w))return a(k);if(e[L(643)](e[L(1516)](p,k),g))if(e[L(611)]===e[L(918)]){if(INJpLR[L(1655)]==typeof _0x1b6d9f){let G=new _0x16034f(INJpLR.GIbkz(_0x50f77b,_0x265a41));return INJpLR[L(1268)](_0xfaf540,_0xd87637,G,0),G}return _0x56504b instanceof _0x692566?new _0xbe2ec2(_0x4e79ca):new _0x1e4e5b(_0xf55b67.buffer,_0x31e50c[L(1640)+"et"],_0x4bea69.byteLength)}else E=e[L(577)](a,g),p=0;let $=n.call(E,p,p+=k);return e[L(1623)](7,p)&&(p=e[L(1237)](e.fRmzk(7,p),1)),$}}}let ag=4294967295;function cg(a,n,s){let l=t;return e.fMLnf(RangeError,e[l(1271)](e[l(745)](e[l(1425)](e.MXkpQ(e[l(650)]+a,l(780)),e[l(1497)](n,1)),e[l(1652)]),s))}function dg(a,n,s){let l=t;if(s>ag)throw new Error(l(566)+l(514)+"e");let f=3;for(;f>=0;){let g=e[l(553)](255,s);e[l(1135)](ba,g,a,e[l(1799)](n,f)),s>>>=8,f--}return e[l(982)](n,4)}function lg(a,n){let s=t,l=0,f=n,g=n+4;for(;e[s(1352)](f,g);){let{value:w,offset:E}=e[s(1664)](ya,a,f);f=E,l=e[s(1728)](e.iduUF(l,8),0),l+=w}return{value:l,offset:g}}function ug(a,n,s){let l=t;if(e.FvLNp(l(684),e[l(1199)])){let f=e[l(385)][l(1414)]("|"),g=0;for(;;){switch(f[g++]){case"0":if(n[l(1093)])return e.iSxyE(n[l(1093)](a,s),s);continue;case"1":if(!a)return s;continue;case"2":if(a.length<40)return e.qJHXN(e.FuYuo(ma,a,n,s),s);continue;case"3":return ma(a,n,s)+s;case"4":if(n[l(743)+"e"])return n[l(743)+"e"](a,s)+s;continue}break}}else _0x113843[l(475)+"entListe"+l(895)](KTBVfb[l(872)],_0x323ca0),_0x1f57d5["removeEventListe"+l(895)](KTBVfb.REQjw,_0x5790d3),_0x49cfc4[l(475)+l(1327)+l(895)](KTBVfb[l(596)],_0x224d74)}function fg(a,n){let s=t,l={BcdrH:function(f,g){return e[Z(1648)](f,g)},oeQXi:s(1384),QptZV:s(1719)};if(e.dxIMo(s(359),e[s(1490)])){let f=new ue(e[s(1477)](e[s(390)](e[s(1047)](a[e[s(1179)](n,4)],24)|e[s(1042)](a[e[s(349)](n,5)],16),e[s(1280)](a[n+6],8)),a[n+7]),e[s(672)](e.nfOJT(e[s(1047)](a[e[s(338)](n,0)],24),e[s(380)](a[e[s(459)](n,1)],16)),e[s(1560)](a[e.OsffD(n,2)],8))|a[n+3],!0);return n+=8,{value:f,offset:e.XYeyc(n,8)}}else this["_navigat"+s(1469)]()&&(!this._ws||this[s(1226)].readyState!==this[s(814)]||l[s(733)](this._ws[s(1789)+"te"],this[s(1688)+"NG"]))&&this[s(1180)+s(771)](),this[s(1571)+"er"]&&_0x16fd95[s(480)+s(1147)](l[s(1761)],this[s(1180)+s(771)]),this._isBrowser&&_0x51acc1[s(480)+"Listener"](l[s(545)],this[s(1180)+"ffLine"])}function hg(a,n,s){let l=t,f=a[l(1711)],g=a[l(1485)];return n[s]=e[l(1067)](g,24),n[e.LFqYk(s,1)]=e[l(489)](g>>>16,255),n[e[l(896)](s,2)]=e[l(774)](g,8)&255,n[e[l(1425)](s,3)]=e[l(1290)](255,g),n[e[l(402)](s,4)]=e.SGqzn(f,24),n[e[l(1223)](s,5)]=f>>>16&255,n[s+6]=e[l(1445)](e[l(776)](f,8),255),n[s+7]=255&f,s+=8,s}function ya(a,n){let s=t;return a[s(1074)+"8"]?{value:a.readUInt8(n),offset:e[s(550)](n,1)}:{value:e[s(1534)](255,a[n]),offset:e[s(550)](n,1)}}function ba(a,n,s){let l=t;if(e.ntTeO(e.jbsBz,e[l(1015)]))return n[l(339)+"t8"]?n[l(339)+"t8"](a,s):n[s]=e.UMeJc(255,a),e.BXWCo(s,1);{let f=new _0xab3be2(e[l(1007)](_0x1d5f28,_0x5c2b36));return e[l(618)](_0x449f60,_0x1263d3,f,0),f}}let xg=function(a){return new Uint8Array(a)},pg=e[t(658)](e[t(1287)],typeof Buffer)?Buffer[t(319)+t(556)]:og(xg,Uint8Array[t(1353)+"e"][t(709)]),gg=16,Ea=32;function mg(a){let n=t,s=0,l={};for(let f=0;f<a[n(1818)];f++)l[a[f]["cursor_n"+n(873)]]=gl(a[f][n(1500)+n(873)]),s+=e[n(1516)](14,l[a[f][n(1500)+n(873)]]);return[s,l]}function bl(a,n,s){let l=t,[f,g]=mg(a),w=e[l(1674)](pg,f),E=0;return a[l(1608)](p=>{let k=l;console[k(551)](e.NNpgz,p,p[k(797)]),E=ba(0,w,E),console[k(551)](e.nlnJh,E),E=dg(w,E,p.service||0),console[k(551)](e[k(1336)],E),E=e[k(610)](ba,g[p[k(1500)+"ame"]],w,E),console[k(551)]("service-"+k(1502),E),E=e.XnHSk(ug,p[k(1500)+k(873)],w,E),console[k(551)](e[k(548)],E),E=e[k(1135)](hg,ue[k(1409)+"er"](p[k(471)]||n),w,E),console.log(e.hHTni,E)}),{frameType:Ea,headers:[{key:e[l(692)],value:s}],payload:w}}function wg(a){let n=t,s={TnLan:e[n(1505)]};if(e.CeIdL(e[n(1442)],e[n(1740)]))this[n(1433)](s[n(1499)],_0x52bf25),this.onclose&&this[n(1701)](_0x2b0364);else{let l=0,f=[];for(;e.VlNFi(l,a[n(1553)+"th"]);){let{offset:g}=e.fSXnq(ya,a,l);l=g;let w={cursor_name:"",cursor:0,service:0},{value:E,offset:p}=e[n(937)](lg,a,l);w[n(797)]=E,l=p;let{value:k,offset:L}=e[n(1020)](ya,a,l);l=L,w[n(1500)+n(873)]=e.XnHSk(ml,a,l,e[n(1349)](l,k)),l+=k;let{value:B,offset:$}=e[n(717)](fg,a,l);w.cursor=B[n(1773)](),l=$,f[n(1241)](w)}return f}}function _g(){let a=t;return{frameType:Ea,headers:[{key:e.QzOBt,value:e[a(1621)]}],payload:void 0}}class yg{constructor(n,s,l){let f=t;this[f(1642)+"ameSpace"]=n,this["_cursorF"+f(288)]=s,this["_message"+f(1549)]=l,this[f(1347)]=e[f(961)](_l,this[f(1642)+"ameSpace"],f(1500)+f(873))}async[t(473)](){let n=t;await this[n(1347)][n(473)]()}async[t(1389)+"rs"](){let n=t;if(!this[n(1347)].isReady)return;let s=this[n(1581)+n(1549)],l=await this[n(1347)][n(1185)]();switch(console[n(551)](e[n(1204)],l),s){case e.aRqgA:return l&&l[n(1818)]?e[n(578)](bl,l,0,this[n(407)+n(288)]):void 0;case"INSTANT":return;case e.rfrUK:return l&&l[n(1818)]?e[n(578)](bl,l,0,this[n(407)+n(288)]):e[n(681)](_g)}}async[t(1172)](n,s,l){let f=t;if(e[f(308)](e.aVJwm,e[f(1692)]))return console[f(551)](e[f(512)],n,s,l),this[f(1347)][f(1172)]({cursor_name:n,cursor:s,service:l});{let g=this[f(1347)][f(1221)+"geSync"](this[f(730)]),w=_0x1551b1[f(591)](e[f(446)](g,"{}"));return w[_0x4dd2e0]=void 0,this[f(1347)]["setStora"+f(1213)](this[f(730)],_0x35973d[f(361)+"y"](w))}}async setCursors(n){let s=t,l={aXRLg:function(g,w){return e.DxQpE(g,w)}},f=e[s(1192)](wg,n);for(let g of f)if(e[s(984)]!==s(549)){let w=_0x574a2c[s(663)];if(pfPfeZ[s(946)](w+_0x3d77ef,_0x3142fe[s(1783)]))throw new _0x1a7ae9(s(1790)+s(1116));return _0xb7fb99[s(663)]+=_0x889bd2,w}else console[s(551)](e[s(666)],f),await this[s(1347)][s(1172)](g)}async get(n){let s=t;return(await this._qosDB[s(928)](n))?.[s(471)]}async[t(1203)](){await this._qosDB.closeDB()}["updateCu"+t(805)+t(1319)](n){let s=t;this["_cursorF"+s(288)]=n}get[t(1651)](){let n=t;return this[n(1347)][n(1651)]}}let bg="__x_msg_"+t(1649);async function El(a){let n=t,s={HBCZH:function(E,p){return E|p},XEeFU:function(E,p){return e[Z(1120)](E,p)},UnMnt:function(E,p){return e[Z(816)](E,p)},mhUeH:function(E,p){return e[Z(1402)](E,p)},dPkHr:function(E,p){return E<<p},aPnZN:function(E,p){return e[Z(1611)](E,p)},jiHdg:function(E,p){return e[Z(1685)](E,p)},ofBbF:function(E,p){return e.WYWqR(E,p)},frRNo:function(E,p){return e[Z(821)](E,p)}};if(!this[n(1796)].enableQoS)return null;let{aID:l,fpID:f,messageStrategy:g}=this[n(1796)],w=e[n(538)](a,bg);try{if(n(759)===n(562))_0xef6e53=aVdKQL.HBCZH(aVdKQL[n(449)](aVdKQL.UnMnt(aVdKQL.mhUeH(7&_0x24f857,18),aVdKQL[n(1299)](aVdKQL[n(1273)](63,_0x351d3c),12)),aVdKQL[n(1273)](63,_0x41be51)<<6),63&_0x53a635),_0x3ea539<65536||aVdKQL[n(1574)](_0x37db01,1114111)?_0x560933+=_0x998faa:(_0x4f0757-=65536,_0x1d7fc5+=_0x281477(aVdKQL[n(1240)](_0x2a695c>>10,55296),aVdKQL[n(975)](1023&_0xc24af1,56320)),_0x13d1e7+=3);else return this[n(636)+n(1246)]?a&&this[n(636)+n(1246)][n(1243)+"rsorFile"+n(1319)](a):this[n(636)+"anager"]=new yg(f+"_"+l+"_"+w,w,g),this[n(636)+n(1246)][n(1651)]||await this[n(636)+n(1246)][n(473)](),this[n(636)+n(1246)]}catch{return null}}async function Eg(a,n){let s=t,l={vIgIe:function(G,j){return e.Voilw(G,j)},TFCfu:e[s(1287)],cxJTF:e[s(924)],LcnjJ:s(1809)+"le"},f=e[s(576)](cn,a.message.headers,e[s(1258)],"-1"),g=e[s(425)](cn,a[s(958)][s(1115)],e[s(357)],"1"),w=e[s(723)](sr,a.message[s(1115)],e[s(1136)]),E=e[s(508)](Number,sr(a[s(958)].headers,e[s(344)]))||0,p=_a[s(994)](this,a),k=e.kSdye(cn,a[s(958)][s(1115)],e[s(454)],"2"),L=e[s(1706)](sr,a[s(958)][s(1115)],e[s(415)]),B=Number(e[s(937)](sr,a[s(958)].headers,e[s(1248)]));if(p.isQoSAck)return n();let $=p[s(1205)+s(1197)]?await yl.call(this):null;if(e.GTsks(a[s(958)][s(797)],0)&&g&&!f||a.message[s(797)]>0){if(e[s(770)](e[s(342)],e[s(378)]))return this[s(1175)]?e[s(959)](e[s(1743)](e[s(837)](this[s(1485)],0),_0x45c83d),e[s(1215)](this[s(1711)],0)):this.high*_0x3b27ec+e[s(1411)](this[s(1711)],0);if(w&&p[s(1205)+s(1197)]&&$)return!!!await $[s(928)](w)&&(this[s(1713)+s(898)+s(1281)](a),await $[s(1172)](w,e.WYWqR(Date.now(),E))),e[s(310)](n);if(k)if(e[s(409)]!==e[s(901)]){let G=await El.call(this);if(!G)return this["_dispatc"+s(898)+"Event"](a),e[s(1294)](n);let j=await G[s(928)](L)??-1;if(e[s(1137)](j,B))if(e[s(1519)](s(500),s(500)))this[s(1713)+s(898)+s(1281)](a),G[s(1172)](L,B,a.message[s(797)]);else{let be={lUeUs:function(me,Ie){return xqGrTX.vIgIe(me,Ie)},DLhog:xqGrTX[s(811)],yDlzq:xqGrTX.cxJTF,Ukmtb:xqGrTX[s(303)]};_0x5322ed.r=me=>{let Ie=s;be[Ie(1658)](be[Ie(1033)],typeof _0x59ab2e)&&_0xee9bd4[Ie(1375)+Ie(1275)]&&_0x437a50["definePr"+Ie(852)](me,_0x3d86a6[Ie(1375)+Ie(1275)],{value:be[Ie(1754)]}),_0x372ffb["definePr"+Ie(852)](me,be[Ie(602)],{value:!0})}}else throw new Error(s(796)+s(1132)+s(1636)+B+(s(1429)+"than loc"+s(944)+"r ")+j);return n()}else{let G=_0x1b5a75(e[s(364)],{message:this["_formatE"+s(892)+s(1312)](_0x18987f)});this.emit(e[s(364)],G);let j=e[s(1706)](_0x4989a8,e[s(1505)],{reason:this[s(1637)+s(892)+"age"](_0x5d3910)});this[s(1433)](e.yySxZ,j)}return this[s(1713)+s(898)+s(1281)](a),e[s(1386)](n)}}async function vg(a,n){let s=t,l=_a[s(994)](this,a);if(!l[s(1205)+s(1197)])return n();let f=await yl[s(994)](this);if(l[s(792)+s(1605)+"age"]&&l.ackMsgIds[s(1818)])for(let g of l[s(1014)+"s"])await f[s(1415)](g);n()}async function Sg(a,n){let s=t,l=e.mTjZo(a[s(958)][s(625)+"e"],gg),f=e[s(539)](a.message[s(625)+"e"],Ea);if(e[s(1437)](!l,!f))return n();let g=e[s(773)](sr,a[s(958)][s(1115)],e[s(692)]);if(!g)return e.SmHYN(n);let w=await El[s(994)](this,g);if(!w)return n();if(l){let E=await w.getCursors(),p={frameType:E?.[s(625)+"e"],SeqID:ue[s(1409)+"er"](this[s(1405)]++),LogID:ue.fromNumber(this[s(1796)][s(296)+s(615)]()),service:9e3,method:5,headers:E?.headers,payload:E?.payload},k=e[s(1242)](S,p);this._ws&&this[s(1226)].readyState&&this[s(1226)][s(925)](k)}if(f){let E=a[s(958)][s(1139)];E&&w[s(1158)+"rs"](E)}}let Ig=async function(a,n){let s=t;this[s(1070)]=!1,e[s(1468)](clearTimeout,this[s(371)+s(915)+s(1408)]),e[s(1386)](n)},Ag=async function(a,n){let s=t;if(!this[s(1226)]||e[s(1757)](this[s(1226)].readyState,this.OPEN))return n();let{pingInterval:l}=this._options;this[s(1464)+"tManager"]?.[s(1717)+s(646)+s(1146)]();for(let g=0;g<this[s(1581)+s(327)].length;g++){let w=this[s(1581)+"Queue"][g];if(e.yFMBk(this[s(1226)][s(1789)+"te"],this[s(814)])&&e[s(1760)](null,w))this._ws&&this[s(1226)][s(925)](w),this[s(1581)+s(327)][g]=null;else break}this[s(1581)+s(327)]=this[s(1581)+s(327)][s(1187)](g=>!!g),this._pingPongTimeoutId=e[s(1788)](setTimeout,()=>this[s(290)](),l),this[s(1713)+s(569)+"nt"](a),this._isBrowser&&this[s(1226)]&&(this[s(1226)][s(1166)+"pe"]=this[s(640)+s(529)]);let f=this[s(1464)+s(933)]?.["getCurre"+s(1420)+"nt"]();this[s(1462)](s(1686)+f+" success"),e[s(607)](n)},kg=async function(a,n){let s=t,l=this[s(1464)+s(933)]?.getCurrentEndpoint();this._debug(s(1686)+l),e[s(310)](n)};class Tg extends ga{constructor(n){let s=t,l={QPJGN:function(E,p,k,L){return e[Z(610)](E,p,k,L)},XSKXc:function(E,p,k){return e[Z(429)](E,p,k)},YOpNw:e.REQjw,cXOUL:function(E,p){return e.zZYIb(E,p)},eGkUy:e[s(1496)],MlNMs:s(1745),bpHLV:function(E,p){return e[s(965)](E,p)},MTaHy:function(E,p,k){return e[s(870)](E,p,k)},mMsty:function(E,p,k,L){return e.oMnOD(E,p,k,L)}};super(),this[s(1378)+s(1671)+s(1587)]=!0,this._isBrowser=ir,this[s(1313)]=jp,this[s(766)+"T"]=Pn,this._isMiniWX=Qr,this[s(1604)+"r"]=ei,this["_message"+s(327)]=[],this[s(1464)+s(933)]=null,this[s(1580)+s(1108)]=!1,this[s(640)+s(529)]=e[s(765)],this[s(371)+s(1703)]=!1,this._connectionTimeoutId=null,this[s(1026)+"ctTimeoutId"]=null,this[s(1737)+s(851)+"Id"]=null,this[s(1405)]=0,this[s(1070)]=!1,this[s(1657)]="",this[s(518)+s(1125)]=null,this[s(636)+s(1246)]=null,this[s(886)+"sCounter"]=null,this[s(1667)+"ls"]=e[s(645)],this.CLOSED=3,this[s(1688)+"NG"]=0,this[s(814)]=1,this[s(1676)]=2,this._onOpen=E=>{let p=s;try{l.QPJGN(pl,this,E,[Ig,Ag,kg])}catch(k){let L=l[p(1143)](ut,l[p(665)],{message:k[p(958)],code:an.OPEN_ERROR,error:k});this[p(1713)+p(430)+p(1558)](L)}},this[s(1751)+"ge"]=async E=>{let p=s,k={CNiqe:function($,G){return l[Z(1537)]($,G)}},{pingInterval:L,pingFrequency:B}=this._options;if(E[p(1112)]==="hi"&&l[p(1630)]===B||l[p(1537)](l[p(817)],B))if(l[p(1724)](p(1217),p(1217))){let $=_0x4af046.bytes,G=_0x477ef8[p(1783)];return nTdZVf[p(1289)]($[p(1818)],G)?$:$[p(709)](0,G)}else this[p(967)+p(732)](),this.emit("ping_onc"+p(1027)+"s","success"),this[p(1737)+p(851)+"Id"]=l[p(938)](setTimeout,this[p(290)][p(951)](this),L);if(!l[p(1537)]("hi",E[p(1112)]))try{l.mMsty(pl,this,E,[sg,rg,vg,Sg,Eg,ig])}catch($){let G=l[p(1143)](ut,l[p(665)],{message:$[p(958)],code:an[p(697)+p(389)],error:$});this[p(1713)+p(430)+p(1558)](G)}},this[s(1738)]=E=>{let p=s,k=this["_endpoin"+p(933)]?.[p(1301)+p(1461)+"es"](),L=this[p(1464)+p(933)]?.[p(875)+p(1420)+"nt"]();if(k&&!E[p(958)]){let B="connect "+L+(" fail, m"+p(1680)+p(722)+"ed");this[p(1713)+p(430)+p(1558)](ut(e.REQjw,{message:B,code:an[p(321)+p(848)+"R"],error:E}));return}this[p(1226)]&&e[p(1335)](this._ws[p(1789)+"te"],this[p(814)])&&this[p(1374)+"ect"](),this[p(1713)+p(430)+p(1558)](e[p(877)](ut,e[p(364)],{message:E.message,code:an.NATIVE_ERROR,error:E}))},this[s(365)]=async E=>{let p=s;this[p(1322)+p(1229)](),this._clearPingTimer(),this[p(1567)+p(1037)+"rs"](),this[p(1226)]=null,this["_connect"+p(1703)]=!1;let k=this[p(1464)+p(933)]?.[p(1301)+p(1461)+"es"]();if(!k&&this[p(1025)+p(1469)]()&&!this._readyClosed){let L=this[p(1464)+p(933)]?.[p(875)+p(1420)+"nt"](),B=this._options[p(1620)+"tInterce"+p(1815)](E.code,E[p(1491)]);this["_dispatc"+p(904)+p(1558)](e[p(360)](_t,p(399),{code:1006,reason:E[p(1491)]||p(1503)+p(906)+p(403)+p(395)+p(592)+p(1317)+L,willReconnect:B})),B&&this[p(371)]();return}if(e[p(1261)](1e3,E[p(552)])&&this[p(1580)+p(1108)]){this["_dispatc"+p(904)+p(1558)](e[p(1478)](_t,p(399),{code:1e3,reason:e[p(942)]})),this[p(1464)+"tManager"]?.[p(1717)+"pointCon"+p(1146)](),this[p(886)+p(1801)]?.["resetCou"+p(1466)]();return}if(e[p(1760)](1e3,E[p(552)])&&k){let L=this["_endpoin"+p(933)]?.[p(875)+p(1420)+"nt"](),B=E[p(1491)];B||(B=await e[p(1807)](Xp,this[p(1657)])),B=p(1503)+p(906)+"d, "+B+(p(1391)+p(336))+L+(", max re"+p(1308)+p(972)),this["_dispatc"+p(904)+"ent"](e[p(1572)](_t,e.yySxZ,{code:E[p(552)],reason:B}));let $="connect "+L+(p(1684)+p(1680)+"es reached");this[p(1713)+p(430)+"ent"](e.VXTgt(ut,e.REQjw,{message:$,code:an[p(321)+p(848)+"R"]})),this[p(1464)+p(933)]?.[p(1717)+p(646)+p(1146)](),this["_pingLos"+p(1801)]?.["resetCou"+p(1466)]();return}if(e[p(698)](1e3,E[p(552)])&&!E.reason){let L=this[p(1464)+"tManager"]?.[p(875)+p(1420)+"nt"]();this[p(1713)+p(904)+"ent"](e.sjFAU(_t,e[p(1505)],{code:E[p(552)],reason:p(1503)+p(906)+"d, unkno"+p(395)+"n, hostn"+p(1317)+L})),this["_endpoin"+p(933)]?.[p(1717)+p(646)+p(1146)](),this[p(886)+p(1801)]?.[p(1126)+p(1466)]();return}this[p(1713)+"hCloseEv"+p(1558)](E),this[p(1464)+p(933)]?.[p(1717)+p(646)+"fig"](),this[p(886)+"sCounter"]?.[p(1126)+"nter"]()},this.onclose=null,this[s(522)]=null,this[s(453)+"e"]=null,this[s(806)]=null,this["onStartR"+s(1401)]=null,this[s(775)+s(1214)]=null,this[s(1592)+s(841)+s(369)+"ct"]=null,this[s(1180)+s(771)]=this["_handleO"+s(771)][s(951)](this),this[s(1180)+s(1154)]=this[s(1180)+s(1154)].bind(this),this[s(356)+s(352)]=this["_handleP"+s(352)].bind(this),this[s(356)+s(801)]=this[s(356)+s(801)][s(951)](this),this[s(1796)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(885)](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:s(1745),pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(440)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:g}=n,w=Array[s(322)](f)?f:e[s(1583)](e[s(849)],typeof f)?[f]:[];if(!w||e[s(1776)](0,w[s(1818)]))throw new Error(e[s(839)]);if(!e[s(1403)]($p,g))throw new Error(e.KXKct);Object[s(1164)](this._options,n),this[s(1464)+"tManager"]=new xl(w,this[s(1796)].maxRetries),this[s(886)+s(1801)]=new Zp(this[s(1796)][s(1326)+s(680)]),this[s(1796)][s(1364)+"cOpen"]&&(this._isInit=!0,this._connect()),this._options[s(1548)+s(1016)+s(1131)]&&(this[s(766)+"T"]||this[s(1669)+"X"]?this[s(488)+s(1387)+s(1250)]():this._isBrowser&&this._initGlobalEventListener())}[t(1180)+t(771)](){let n=t;this[n(1796)][n(1723)+n(1264)+n(422)]||this["_readyCl"+n(1108)]||this[n(503)+n(1401)]()}[t(1180)+"ffLine"](){let n=t;if(e.TlYTr(n(1084),n(1084)))_0x24f850[n(1241)](_0x43ee17);else{this[n(671)+"WebSocket"]();let s=e[n(1788)](pa,"reconnect",{message:n(1388)+"ediately"+n(1191)+"ct"});this[n(1592)+n(841)+n(369)+"ct"]&&this[n(1592)+n(841)+n(369)+"ct"](s)}}[t(893)+t(497)+t(1147)](){let n=t;this._isBrowser&&window[n(480)+n(1147)](e.WAZNV,this[n(1180)+"nLine"]),this._isBrowser&&window[n(480)+n(1147)](e[n(1009)],this[n(1180)+n(1154)]),this[n(1571)+"er"]&&window[n(480)+n(1147)](e[n(1612)],this[n(356)+n(352)]),this[n(1571)+"er"]&&window["addEvent"+n(1147)](e.HbWlA,this[n(356)+n(801)])}["_dropGlo"+t(497)+t(1147)](){let n=t;this[n(1571)+"er"]&&window[n(475)+n(1327)+"ner"](e[n(312)],this[n(1180)+"nLine"]),this[n(1571)+"er"]&&window[n(475)+n(1327)+n(895)]("offline",this[n(1180)+n(1154)]),this[n(1571)+"er"]&&window[n(475)+n(1327)+n(895)](n(1742),this[n(356)+"ageHide"]),this[n(1571)+"er"]&&window["removeEv"+n(1327)+"ner"](e[n(314)],this[n(356)+"ageShow"])}[t(356)+t(352)](n){let s=t;!n[s(466)+"d"]&&(this._isBrowser&&window[s(475)+"entListe"+s(895)](s(1742),this["_handleP"+s(352)]),this[s(1571)+"er"]&&window["removeEv"+s(1327)+s(895)](e[s(314)],this[s(356)+"ageShow"]),this[s(399)]()),this[s(1571)+"er"]&&window[s(475)+"entListe"+s(895)]("online",this[s(1180)+"nLine"]),this[s(1571)+"er"]&&window[s(475)+"entListener"](e.voaPl,this[s(1180)+s(1154)])}[t(356)+t(801)](n){let s=t;e[s(1523)](e[s(300)],s(919))?_0x54bc81.log(_0x37e6b8):n.persisted&&(e.KaxTp(e[s(614)],e[s(1351)])?(_0x498e66=_0x2c2c3c[e.SMVLv(e[s(414)](_0x2c993e,_0x566f85),1)],_0x1b3323=_0x88cd1f[_0x5ac288+_0x46e58d+2],_0x42cc6e=_0x1da210[e[s(349)](e[s(1698)](_0x1942bf,_0x362a0b),3)],e.QYsxz(e.lWPYe(e[s(672)](e.NCCmI(_0x3de9d4,_0x398501<<8),e[s(807)](_0x513b3b,16)),12632256),8421504)?_0x2c03e6+=_0x4f8157:(_0x11b596=e[s(864)](e[s(1449)](e[s(807)](e[s(1800)](7,_0x4cac90),18),e[s(404)](e[s(587)](63,_0x1d9a7e),12)),e[s(863)](63,_0x5a0f37)<<6)|e[s(1245)](63,_0x3d19e3),e.ddhdZ(_0x2c6bb2,65536)||e[s(1344)](_0x369d51,1114111)?_0x14d2d8+=_0x21b842:(_0x5666c6-=65536,_0x8550df+=e[s(866)](_0x265b2a,e[s(1341)](e[s(585)](_0x3ff2a9,10),55296),e[s(1726)](e.oHlTJ(1023,_0x25ea88),56320)),_0x1412b1+=3))):(this["_navigat"+s(1469)]()&&(!this._ws||this[s(1226)].readyState!==this.OPEN||e.OGBQc(this[s(1226)][s(1789)+"te"],this[s(1688)+"NG"]))&&this[s(1180)+s(771)](),this[s(1571)+"er"]&&window.addEventListener(e.WAZNV,this["_handleO"+s(771)]),this._isBrowser&&window[s(480)+s(1147)](e[s(1009)],this[s(1180)+"ffLine"])))}async["_generat"+t(1654)](n){let s=t,{fpID:l,deviceID:f,bddID:g,ttwID:w,accessKey:E,aID:p,customParams:k={},enableAutoAck:L,enableQoS:B,QoSLevel:$,env:G}=this[s(1796)],j,be,me;if(this[s(1571)+"er"]||this[s(1669)+"X"]||this._isMiniTT)j=location&&e.LjRIS==location[s(1768)]?e[s(1053)]:e[s(275)],be=n[s(581)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),me=/^wss(.*:\/\/)/[s(484)](n)?n:""+j+be;else if(e[s(1194)](e[s(370)],"NKyCW"))j=e[s(1053)],be=n[s(581)](/(^http)((?:[s]*:\/\/))/,""),me=/(^ws)((?:[s]*:\/\/))/[s(484)](be)?be:""+j+be;else{let ti=this["_endpoin"+s(933)]?.[s(875)+s(1420)+"nt"]();this[s(1462)](s(1686)+ti),e[s(1228)](_0x26a526)}let Ie=g?e[s(1470)]:w?s(1379):e.WhLAv,ft=g||w||f;if(e[s(1570)](!ft,!Ie))throw new Error(e[s(1770)]);let va=e[s(1358)](s(567),typeof k)?await e[s(1092)](k):k,Cg=G?e.irCEw(Jp,G[s(764)],G[s(787)]):{},Sa=Object[s(1164)]({device_platform:s(1552),version_code:e.Qnxtr,access_key:E,fpid:l,aid:p,[Ie]:ft,xsack:L?1:0,xaack:L?1:0,xsqos:B?1:0,qos_level:B?$:void 0,qos_sdk_version:2,...Cg},va),Rg=Object.keys(Sa).reduce((ti,Ia)=>Sa[Ia]!==void 0?""+ti+(ti?"&":"?")+Ia+"="+Sa[Ia]:ti,"");return me+s(903)+Rg}async[t(371)](){let n=t,s={tCNoP:function(l,f){return e.nGaZS(l,f)},LDXvx:e[n(599)]};if(e[n(1183)](e.dHBsV,e[n(1634)])){let l=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(_0x2935f8),f=/(([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(484)](_0x473a37);return l?_0x567977(_0x3737cc):f?VkDtKC[n(769)](_0x921b8b,_0x33270a):VkDtKC[n(1392)]}else{if(this[n(371)+n(1703)]||this[n(1580)+n(1108)])return;this[n(371)+n(1703)]=!0;try{let l=this[n(1464)+n(933)]?.[n(1410)+n(917)+n(1041)+n(1508)+n(957)](),{timeoutInterval:f}=this[n(1796)];if(l){let w=this[n(1464)+n(933)]?.[n(875)+"ntEndpoint"](),E=this[n(1464)+n(933)]?.[n(1653)+n(1064)+"pointAnd"+n(410)+n(347)](),p=this[n(1464)+"tManager"]?.[n(875)+"ntEndpoi"+n(381)+n(1232)]();if(E){let k=n(1201)+w+(n(417)+n(504)+n(1308)+n(412)+n(1297)+n(1749)+n(897))+E+" to retry",L=e[n(1527)](ut,e[n(364)],{message:k,code:an.MAX_RETRIES_ERROR});this._debug(k),this[n(1713)+"hErrorEv"+n(1558)](L),this[n(1657)]=await this[n(1501)+n(1654)](E),this[n(1462)]("connect "+E+" "+p+n(1314)),this[n(1567)+n(1037)+"rs"]()}else{let k=n(1201)+w+(n(417)+n(504)+"tries re"+n(972));this[n(1462)](k),this[n(1713)+n(430)+n(1558)](ut(e[n(364)],{message:k,code:an[n(321)+"IES_ERROR"]}));return}}else{let w=this["_endpoin"+n(933)]?.[n(875)+n(1420)+n(674)+n(523)](),E=this[n(1464)+n(933)]?.[n(875)+"ntEndpoi"+n(381)+n(1232)]();this[n(1657)]=await this[n(1501)+n(1654)](w||""),this[n(1462)]("connect "+w+" "+E+" times"),this["_removeW"+n(1037)+"rs"]()}if(this._isInit)this[n(1070)]=!1;else{let w=pa(e[n(544)],{message:n(1730)});this[n(1077)+n(1401)]&&this[n(1077)+n(1401)](w)}let g=this[n(1464)+n(933)]?.[n(875)+n(1420)+"ntTriesCount"]()||0;g>1&&await this._wait(e[n(1316)](g,1)),this[n(1462)]("connecti"+n(1435)+this[n(1657)]+(n(1144)+n(1455))+this[n(1667)+"ls"]),this._ws=e[n(517)](Kp,{url:this[n(1657)],protocols:[this._protocols],headers:this[n(1796)][n(749)+"ramParams"]["customHt"+n(1718)]},this[n(1796)].ws),(this[n(1571)+"er"]||this[n(1604)+"r"])&&this._ws&&(this[n(1226)][n(1166)+"pe"]=this[n(640)+n(529)]),this[n(1177)+n(1434)](),this[n(371)+n(915)+n(1408)]=e[n(891)](setTimeout,this[n(1675)+"ut"].bind(this),f)}catch(l){throw this._connectLock=!1,l}}}[t(1322)+"mer"](){let n=t;e[n(1403)](clearTimeout,this[n(371)+n(915)+n(1408)]),this["_connect"+n(915)+n(1408)]=null}["_clearPi"+t(732)](){let n=t;clearTimeout(this[n(1737)+n(851)+"Id"]),clearTimeout(this[n(1026)+"ctTimeou"+n(543)]),this[n(1737)+n(851)+"Id"]=null,this[n(1026)+"ctTimeou"+n(543)]=null}[t(1462)](...n){let s=t,l={vnKou:function(f,g){return e[Z(1090)](f,g)},nlpXK:function(f,g){return f&g},ZjXuJ:function(f,g){return e[Z(1709)](f,g)},ybOVl:function(f,g){return f>>>g}};if(e[s(1039)](e[s(754)],e[s(800)])){let f=this[s(1485)],g=this[s(1711)];return[NsnXnf.vnKou(255,g),NsnXnf[s(1564)](g>>>8,255),NsnXnf[s(713)](g,16)&255,NsnXnf[s(713)](g,24),255&f,NsnXnf[s(1766)](NsnXnf[s(428)](f,8),255),NsnXnf.ZjXuJ(f,16)&255,NsnXnf.ZjXuJ(f,24)]}else this[s(1796)][s(507)]&&console[s(551)][s(832)](console,[e.yACXm,...n])}[t(1521)+t(1628)+"e"](n){let s=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:g}=this[s(1796)],w=e[s(778)](l,Math.pow(g,e[s(1316)](n,1)));return e[s(1685)](w,f)?f:w}[t(290)](){let n=t;if(this[n(1226)]&&e[n(1700)](this._ws.readyState,this[n(1688)+"NG"])){this[n(967)+"ngTimer"](),this["_pingPon"+n(851)+"Id"]=e[n(1561)](setTimeout,this[n(290)][n(951)](this),this[n(1796)].pingInterval);return}if(!this[n(1226)]||this[n(1226)].readyState!==this[n(814)])return void this["_handleR"+n(1401)]();this[n(1226)]&&this._ws.send("hi"),this[n(1026)+n(939)+"tId"]=e[n(1169)](setTimeout,this[n(503)+n(1401)+n(1733)][n(951)](this),this._options[n(700)+n(1340)+n(823)])}[t(503)+t(1401)+t(1733)](){let n=t;this[n(886)+n(1801)]?.[n(782)](),this[n(1433)](e.IKCie,n(1762)),this["_pingLos"+n(1801)]?.[n(1301)+n(586)+"nt"]()?this["_handleR"+n(1401)]():this[n(290)]()}[t(1025)+t(1469)](){let n=t;return this[n(766)+"T"]||this._isMiniWX?this[n(1378)+n(1671)+n(1587)]:(this[n(1571)+"er"]||this[n(1604)+"r"])&&this[n(1796)][n(1548)+n(1016)+"nged"]?navigator[n(1506)]:!0}[t(503)+t(1401)](){let n=t;!this[n(1025)+n(1469)]()||this[n(1580)+n(1108)]||(this[n(1464)+n(933)]?.[n(1717)+"pointCon"+n(1146)](),this[n(886)+n(1801)]?.[n(1126)+"nter"](),this[n(1226)]?this[n(1374)+n(383)](1001,e[n(1396)],!0):this[n(371)]())}[t(488)+t(1387)+t(1250)](){let n=t;this[n(766)+"T"]?tt[n(679)+n(498)+n(1545)](({isConnected:s})=>{let l=n;this["_miniNav"+l(1671)+l(1587)]=s,s?this[l(1180)+l(771)]():this._handleOffLine()}):this[n(1669)+"X"]&&wx["onNetwor"+n(498)+n(1545)](({isConnected:s})=>{let l=n;this[l(1378)+l(1671)+l(1587)]=s,s?this[l(1180)+l(771)]():this[l(1180)+"ffLine"]()})}[t(662)](n){let s=t,l={uBgGH:function(f,g){return f instanceof g},DiclB:function(f,g){return e.FblzK(f,g)},HadMI:e[s(977)],gkXaU:e.Eaqyy,RcnYY:s(1100)+"ion/json"+s(1727)+s(1786),hLHgc:e.yxilM,MjKno:e[s(1772)],SwOkp:function(f,g,w,E){return e[s(391)](f,g,w,E)}};if(e.YvcrV(s(793),e[s(1672)]))return new Promise(f=>{let g=s;e.TNgcB(setTimeout,f,this[g(1521)+g(1628)+"e"](n))});if(iLlvXR[s(1315)](_0x3cad3.payload,_0x1c191d)){let f=iLlvXR[s(335)](this[s(1796)]["payloadE"+s(501)],_0x5e1f10)?{force:!!this[s(1796)][s(1813)+"ncoding"].force,encoding:this[s(1796)][s(1813)+s(501)][s(768)]?this[s(1796)][s(1813)+s(501)][s(768)][s(581)](/\s/g,"")[s(1011)+s(1520)]():""}:{force:!1,encoding:this[s(1796)]["payloadE"+s(501)]?this._options[s(1813)+s(501)][s(581)](/\s/g,"")[s(1011)+s(1520)]():""},g=_0x37305d[s(1813)+s(501)]?_0xdabcf["payloadE"+s(501)][s(581)](/\s/g,"")[s(1011)+s(1520)]():"",w=iLlvXR[s(1315)](this[s(1796)][s(748)+s(529)],_0x64dc04)?{force:!!this._options[s(748)+s(529)][s(649)],type:this._options["payloadT"+s(529)][s(400)]?this[s(1796)]["payloadT"+s(529)][s(400)][s(581)](/\s/g,"")[s(1011)+s(1520)]():""}:{force:!1,type:this[s(1796)]["payloadT"+s(529)]?this._options[s(748)+s(529)].replace(/\s/g,"")[s(1011)+s(1520)]():""},E=_0x3b3aff["payloadT"+s(529)]?_0x1c9589[s(748)+"ype"][s(581)](/\s/g,"")[s(1011)+"ase"]():"",p=w[s(649)]?w.type:E||w[s(400)],k=f[s(649)]?f[s(768)]:g||f[s(768)],L=[iLlvXR[s(1687)],iLlvXR.gkXaU,iLlvXR[s(315)],"string"],B=[iLlvXR[s(606)],iLlvXR.MjKno];this._options.enableTransformTextPayload&&L[s(934)](p)&&(!k||B.includes(k))?_0x30e36b[s(1438)+s(575)]=iLlvXR[s(597)](_0x26a66,_0x1d332c.payload,0,_0x474d7d[s(1139)].byteLength):_0x54d51d[s(1438)+s(575)]=""}else _0x2263c4[s(1438)+s(575)]=""}["_disconn"+t(383)](n=1e3,s="",l=!1){let f=t;if(e[f(1278)](e[f(900)],f(1284))){if(!this[f(1226)])return;this[f(671)+"WebSocket"](n,s,l)}else{if(_0x366d53)return new _0x18b7a0(_0x4f1f3f[f(373)],_0x3666d2[f(1768)]);if(e.bEawr(_0x3f110b,_0x1d5703))return new _0xb592f7(_0x1aff10[f(373)],_0x46d58a.protocol,_0x4b777c.headers);if(e[f(376)](_0x323a05,_0x8bc5f0)&&e.cCDPx!=typeof _0x5c0c3b&&_0x2015b4)return new _0x19e612(_0x1dd24e[f(373)],_0x2b12cd[f(1768)+"s"])}}[t(1675)+"ut"](){let n=t,s=this[n(1464)+n(933)]?.["getCurre"+n(1420)+"nt"]();this._debug(n(1201)+s+n(417)),this["_disconn"+n(383)](1001,e[n(326)],!0)}[t(756)](n){let s=t;if(e[s(1529)]("hGcLD",e[s(1533)])){let l=e[s(1765)](qt,n);if(this._ws&&e[s(343)](this._ws.readyState,this[s(814)]))if(e[s(481)]("kwiFk",s(950))){let f=this[s(1347)][s(1582)](this[s(730)]);return _0x268f50[s(591)](e[s(510)](f,"{}"))[_0x5b74fb]}else this[s(1226)]&&this[s(1226)][s(925)](l),this[s(1462)](e[s(1563)],n)}else this[s(1433)](e.fYFaJ,_0x3ea67a),this[s(453)+"e"]&&this[s(453)+"e"](_0xa6975f)}[t(1567)+t(1037)+"rs"](){let n=t,s={XLfPm:function(l,f){return e.dpoAw(l,f)},GLxyG:function(l){return l()}};if(n(690)===e[n(1594)]){let l=e.LsABw[n(1414)]("|"),f=0;for(;;){switch(l[f++]){case"0":this[n(1226)][n(475)+n(1327)+n(895)](e[n(1505)],this[n(365)]);continue;case"1":this[n(1226)][n(475)+n(1327)+"ner"](e.fYFaJ,this[n(1751)+"ge"]);continue;case"2":if(!this[n(1226)])return;continue;case"3":this[n(1226)]["removeEv"+n(1327)+"ner"](e.REQjw,this[n(1738)]);continue;case"4":this._ws[n(475)+n(1327)+n(895)](e.EaLkz,this._onOpen);continue}break}}else JVDxDZ[n(706)](_0x2f4651,_0x509eed[n(1473)]),JVDxDZ.GLxyG(_0x624afb)}["_addWsLi"+t(1434)](){let n=t;if(e.yFMBk(e[n(970)],n(1525))){if(e[n(493)](e[n(598)](_0x283901.offset,_0x16c509),_0x2d54b9[n(1783)]))throw new _0x294de5(e[n(985)]);_0x1117a7[n(663)]+=_0x8b279b}else{if(!this[n(1226)])return;this[n(1226)][n(480)+n(1147)](e[n(1475)],this[n(1076)]),this[n(1226)][n(480)+n(1147)](e[n(1505)],this[n(365)]),this._ws[n(480)+n(1147)](e[n(1814)],this._onMessage),this[n(1226)]["addEvent"+n(1147)](e[n(364)],this[n(1738)])}}[t(1784)+t(280)](n=1e3,s=""){let l=t;try{this[l(1226)]&&this[l(1226)][l(399)](n,s)}catch{}}_destroyWebSocket(n=1e3,s="",l=!1){let f=t;if(this[f(967)+f(732)](),this[f(1322)+f(1229)](),this["_removeW"+f(1037)+"rs"](),this[f(1784)+f(280)](1e3,s),this[f(371)+f(1703)]=!1,l&&this[f(1025)+f(1469)]()&&!this[f(1580)+f(1108)]){if(this[f(1464)+f(933)]?.[f(1301)+f(1461)+"es"]()){let w=this[f(1464)+f(933)]?.["getCurre"+f(1420)+"nt"]();this[f(1713)+"hCloseEv"+f(1558)](_t(e[f(1505)],{code:1006,reason:f(1201)+w+(f(417)+f(504)+f(1308)+f(972)),wasClean:!0}))}else{let w=this._options["reconnec"+f(1695)+"ptor"](n,s);this["_dispatc"+f(904)+"ent"](_t(e[f(1505)],{code:n,reason:s,wasClean:!0,willReconnect:w})),w&&this[f(371)]()}return}this[f(1025)+f(1469)]()||this["_readyCl"+f(1108)]?this[f(1713)+f(904)+f(1558)](_t(e[f(1505)],{code:n,reason:e.yIAuM})):this["_dispatchCloseEv"+f(1558)](_t(e.yySxZ,{code:1006,reason:e.SCVVP})),this[f(1226)]=null,this["_endpoin"+f(933)]?.[f(1717)+f(646)+f(1146)](),this[f(886)+f(1801)]?.[f(1126)+f(1466)]()}[t(1713)+"hOpenEvent"](n){let s=t;this[s(1433)](e[s(1475)],n),this[s(806)]&&this[s(806)](n)}[t(1713)+t(898)+t(1281)](n){let s=t;this[s(1433)](e[s(1814)],n),this[s(453)+"e"]&&this[s(453)+"e"](n)}[t(1713)+t(1310)+t(496)](n){let s=t;this[s(1433)]("ack",n),this[s(775)+s(1214)]&&this[s(775)+s(1214)](n)}[t(1713)+t(430)+"ent"](n){let s=t;if(e[s(1335)](e[s(1324)],e[s(323)])){let l=this[s(905)+"rs"][_0x2cc6e5];if(l)l[s(1573)]()[s(1608)](f=>f.fn[s(832)](f[s(570)],_0x1d098a));else if(e[s(364)]===_0x561d6a&&!this.onerror){let f=_0x5ee8b8.length&&_0x2e9beb[0];if(e[s(986)](f,_0x346b1f))throw f;let g=new _0x30178f(e[s(667)](e[s(1457)],f?e[s(1710)](" ("+f.message,")"):""));throw g[s(1734)]=f,f}return this}else this.emit(s(1473),n),this[s(522)]&&this.onerror(n)}[t(1713)+"hCloseEv"+t(1558)](n){let s=t;this[s(1433)](e[s(1505)],n),this[s(1701)]&&this[s(1701)](n)}get[t(1166)+"pe"](){let n=t;return this[n(1226)]?this[n(1226)].binaryType:this[n(640)+n(529)]}set binaryType(n){let s=t;if(e.CouHV(e.NuDfN,e[s(1551)])){let l=e[s(1452)](_0x42aa1b,_0x2501a1,_0x7221a9[s(1783)]),f=_0x2572ae[s(1484)],g=_0x56b30c[s(1484)];for(let w=0,E=_0x41e53c.limit;w<E;w++)f[e.HigQG(w,l)]=g[w]}else this._binaryType=n,this[s(1226)]&&(this[s(1226)].binaryType=n)}get[t(1127)+"nt"](){let n=t;return this["_endpoin"+n(933)]?.["getCurre"+n(1420)+n(381)+n(1232)]()||0}get[t(560)+t(1810)](){let n=t,s={IyQTp:function(f,g,w,E){return e[Z(1174)](f,g,w,E)},tyido:e[n(357)],arPer:function(f,g){return e[n(911)](f,g)},fLAWq:n(325),NodAY:function(f,g){return e.AwzIt(f,g)},hucuD:"ack_code",UGgFS:function(f){return e.nEsNf(f)},efjAP:e[n(1615)]},l=this[n(1581)+"Queue"][n(1138)]((f,g)=>{let w=n;if(w(1453)!==s[w(355)])return f+=g&&g[w(1553)+"th"]||0,f;{let{enableAutoAck:E}=this[w(1796)],p=_0xc864c5(_0x43e23f.message.headers,w(1557),"1"),k=jVylDf[w(482)](_0x197a25,_0x479c0b[w(958)][w(1115)],jVylDf[w(1689)],"1"),L=_0xfeba40.call(this,_0x7a230f);if(jVylDf.arPer(E,p)){let{SeqID:B,LogID:$,service:G,LogIDNew:j,method:be}=_0xa6dbe6.message;this[w(756)]({SeqID:B,LogID:$,LogIDNew:j,service:G,method:be,headers:[{key:jVylDf.tyido,value:"1"},{key:jVylDf[w(1348)],value:jVylDf[w(1795)](j,"")},{key:jVylDf[w(1195)],value:"0"}]})}k&&!L[w(447)]&&this[w(1713)+w(1310)+w(496)](_0x30e646),jVylDf[w(535)](_0x430929)}},0);return e.kGOuq(l,this[n(1226)]?this[n(1226)][n(560)+"Amount"]:0)}get[t(1239)+"ns"](){let n=t;return this[n(1226)]?this[n(1226)][n(1239)+"ns"]:""}get[t(1768)](){let n=t,s={JRjzc:n(1742),GbfIO:e.HbWlA,UQrLs:e[n(312)]};if(e[n(1400)](e[n(387)],e[n(387)]))!_0x2d1c59.persisted&&(this[n(1571)+"er"]&&_0x235329[n(475)+n(1327)+"ner"](TJXQdh.JRjzc,this[n(356)+n(352)]),this[n(1571)+"er"]&&_0x5e5f24["removeEventListe"+n(895)](TJXQdh.GbfIO,this[n(356)+n(801)]),this[n(399)]()),this[n(1571)+"er"]&&_0x182ad4[n(475)+n(1327)+"ner"](TJXQdh.UQrLs,this[n(1180)+"nLine"]),this._isBrowser&&_0xd11416[n(475)+n(1327)+n(895)]("offline",this[n(1180)+n(1154)]);else return this[n(1226)]?this[n(1226)].protocol:""}get[t(1789)+"te"](){let n=t;return this[n(1226)]?this[n(1226)][n(1789)+"te"]:this[n(1796)][n(1364)+n(348)]?this[n(1688)+"NG"]:this[n(704)]}get[t(373)](){let n=t,s={oOZsB:function(l,f){return e[Z(291)](l,f)},tNTXG:function(l,f){return l<f},HuBmT:function(l,f){return l(f)}};if(e[n(1427)](e[n(470)],e[n(1554)]))return this[n(1226)]?this._ws[n(373)]:this[n(1657)];_0x1a329f=pyOdin[n(1381)](31&_0x37ac60,6)|63&_0x3fd8e7,pyOdin[n(394)](_0x3ea55a,128)?_0x29be40+=_0x3b295e:(_0x408232+=pyOdin[n(1032)](_0x447fe1,_0x5f145e),_0x58173e++)}[t(399)](n=1e3,s){let l=t,f=e[l(882)][l(1414)]("|"),g=0;for(;;){switch(f[g++]){case"0":if(e[l(1082)](this._ws[l(1789)+"te"],this[l(704)])||e[l(1714)](this[l(1226)][l(1789)+"te"],this[l(1676)]))return void this[l(1462)](e.vUEAm);continue;case"1":this[l(1256)+l(497)+l(1147)]();continue;case"2":this[l(518)+l(1125)]?.[l(1203)]();continue;case"3":this[l(967)+l(732)]();continue;case"4":this["_clearTi"+l(1229)]();continue;case"5":this[l(671)+"WebSocket"](n,s);continue;case"6":this[l(1580)+"osed"]=!0;continue;case"7":if(!this[l(1226)])return void this._debug(l(929)+"s instan"+l(1446)+"nitialized");continue}break}}async[t(925)](n,s){let l=t;if(e[l(1526)](null,n))throw new Error(e[l(621)]);l(1735)==typeof n&&(n=JSON[l(361)+"y"](n)),e[l(1683)](e[l(849)],typeof n)&&!(n instanceof ArrayBuffer)&&!(n[l(923)]&&e.spLBM(n.buffer,ArrayBuffer))&&(n=JSON[l(361)+"y"](n));let f=await e[l(1404)](wl,n),g=e[l(580)](Vp,n),{method:w=0,service:E=this[l(1796)][l(797)],logID:p=this._options[l(296)+l(615)](),headers:k=this[l(1796)][l(1115)],payloadEncoding:L=this._options[l(1813)+"ncoding"],payloadType:B=this._options[l(748)+l(529)],logIDNew:$=this[l(1796)]["logIDNew"+l(1331)][l(1543)+l(876)+"teLogIDNew"]?i(this[l(1796)][l(1259)+l(1331)][l(1252)]):""}=s||{};if(!E)throw new Error(e[l(439)]);let G={SeqID:ue[l(1409)+"er"](this[l(1405)]++),LogID:ue[l(1409)+"er"](p),service:E,method:w,headers:k,payloadEncoding:L instanceof Object?L[l(768)]?L.encoding:"":L,payloadType:e[l(1771)](B,Object)?B.type?B[l(400)]:g:B||g,payload:f,LogIDNew:$},j=e.wUghq(qt,G);return this[l(1226)]&&e[l(1043)](this[l(1226)].readyState,this[l(814)])?(this[l(1226)]&&this[l(1226)][l(925)](j),this[l(1462)](e.EAqIb,G)):e[l(922)](this[l(1581)+l(327)][l(1818)],this[l(1796)][l(686)+l(1342)+"ength"])?(this["_message"+l(327)][l(1241)](j),this[l(1462)](l(375),G)):(this[l(1581)+l(327)].shift(),this["_message"+l(327)].push(j)),{seqID:this[l(1405)],logID:p,logIDNew:$}}async[t(1620)+"t"](n){let s=t,{url:l}=e[s(1078)](n,{}),f=Array[s(322)](l)?l:e[s(822)](e[s(849)],typeof l)?[l]:[];n&&Object[s(1164)](this[s(1796)],n),f&&f.length?this[s(1464)+"tManager"]=new xl(f,this[s(1796)][s(1102)+"es"]):this[s(1464)+s(933)]?.[s(1717)+s(646)+s(1146)](),this[s(886)+"sCounter"]?.[s(1126)+"nter"](this[s(1796)][s(1326)+"Count"]),this[s(1580)+s(1108)]=!1,this[s(1226)]&&e[s(630)](this[s(1226)][s(1789)+"te"],this.CLOSED)?this._disconnect(1e3,e[s(727)],!0):(this._isInit=!0,this[s(371)]())}async[t(678)](){let n=t;if(e[n(318)](e.nFSoy,e[n(1003)]))return _0x5ab49e?.[n(916)](s=>s[n(1249)]===_0x47d9e1)?.[n(850)];if(!this[n(371)+n(1703)]){let s=e[n(1260)][n(1414)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(371)]();continue;case"1":this[n(1070)]=!0;continue;case"2":this[n(1580)+"osed"]=!1;continue;case"3":this[n(1464)+n(933)]?.[n(1717)+"pointConfig"]();continue;case"4":this["_pingLos"+n(1801)]?.["resetCou"+n(1466)]();continue}break}}}[t(480)+"Listener"](n,s){this.on(n,s)}[t(1219)+t(1281)](n){let s=t,{type:l}=n;this[s(1433)](l,n)}["removeEv"+t(1327)+t(895)](n,s){this[t(1399)](n,s)}[t(1690)](){let n=t,s={oWpWk:function(l,f){return e[Z(431)](l,f)},XbJOK:e[n(1779)],weKjc:e[n(820)],iuZAs:e[n(1024)]};return new Promise((l,f)=>{let g=n,w={ikaJl:function(k,L){return e[Z(1307)](k,L)},vTWyM:e[g(1159)],DyJTD:g(1088)+g(1027)+"s"};this[g(967)+g(732)](),this[g(1737)+"gTimeoutId"]=e.sKMdE(setTimeout,this[g(290)][g(951)](this),this[g(1796)][g(1426)+g(1121)]);let E=()=>{let k=g;w[k(1546)](l,w[k(1593)]),this[k(1399)](w[k(999)],E),this.off(k(1088)+k(1325)+"t",p)},p=()=>{let k=g;s[k(1097)](f,s.XbJOK),this[k(1399)](s[k(457)],E),this[k(1399)](s[k(483)],p)};this.on(e[g(820)],E),this.on("ping_onc"+g(1325)+"t",p),this[g(290)]()})}}})(),Ue[F(907)+F(301)]=Oe[F(907)+"oseEvent"],Ue.CustomErrorEvent=Oe.CustomErrorEvent,Ue[F(660)+"e"]=Oe.ErrorCode,Ue[F(1281)]=Oe[F(1281)],Ue.FWS=Oe[F(1058)],Ue[F(1732)+F(1117)+F(600)]=Oe[F(1732)+F(1117)+F(600)],Ue[F(1117)+F(600)]=Oe[F(1117)+"vent"],Ue[F(1149)+"t"]=Oe.OpenEvent,Ue["Reconnec"+F(1418)]=Oe[F(1476)+F(1418)],Ue["createCl"+F(301)]=Oe.createCloseEvent,Ue["createEr"+F(579)]=Oe.createErrorEvent,Ue["createMe"+F(1609)+"nt"]=Oe["createMe"+F(1609)+"nt"],Ue[F(751)+F(955)]=Oe["createOp"+F(955)],Ue[F(276)+F(1764)+F(600)]=Oe["createRe"+F(1764)+F(600)],Ue.decodedFrame=Oe[F(393)+F(1541)],Ue[F(332)+F(873)]=Oe[F(332)+F(873)];for(Ko in Oe)[F(907)+F(301),"CustomEr"+F(579),F(660)+"e","Event","FWS",F(1732)+"MessageE"+F(600),F(1117)+F(600),"OpenEvent",F(1476)+"tEvent",F(847)+F(301),"createEr"+F(579),"createMe"+F(1609)+"nt",F(751)+"enEvent",F(276)+F(1764)+"vent",F(393)+F(1541),F(332)+"ame"][F(1635)](Ko)===-1&&(Ue[Ko]=Oe[Ko]);var Ko;function Z(t,e){t=t-273;let r=Yo(),i=r[t];if(Z.EJXnYs===void 0){var o=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",_="";for(let S=0,y,v,I=0;v=h.charAt(I++);~v&&(y=S%4?y*64+v:v,S++%4)?m+=String.fromCharCode(255&y>>(-2*S&6)):0)v=x.indexOf(v);for(let S=0,y=m.length;S<y;S++)_+="%"+("00"+m.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(_)};Z.yKxlVb=o,Z.nehYNN={},Z.EJXnYs=!0}let c=r[0],d=t+c,u=Z.nehYNN[d];return u?i=u:(i=Z.yKxlVb(i),Z.nehYNN[d]=i),i}Object["definePr"+F(852)](Ue,F(1809)+"le",{value:!0})});import{existsSync as qS,openSync as jS}from"node:fs";import{mkdir as WS}from"node:fs/promises";import{dirname as KS}from"node:path";import{fileURLToPath as $S}from"node:url";function JS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Kd(t=ee()){return qS(t.libEntry)?t.libEntry:$S(new URL("../index.ts",import.meta.url))}async function tp(t={}){let e=t.paths??ee(),r=t.entryOverride??Kd(e),i=JS(e,process.env.COZE_BRIDGE_LOG_MODE);await WS(KS(i),{recursive:!0});let o=jS(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=ot(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[os]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return VS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var VS,os,ra=rt(()=>{"use strict";Xt();ne();Be();VS=H("spawn-daemon"),os="COZE_BRIDGE_DAEMON"});import{spawn as K1}from"node:child_process";import{mkdir as $1,unlink as V1,writeFile as J1}from"node:fs/promises";import{dirname as Z1,join as X1}from"node:path";function Zr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Y1(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Zr(r)}</key>
21
- <string>${Zr(i)}</string>`).join(`
20
+ `+r)}function Qn(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,Qn),t.emit("wsClientError",d,r,e)}else Qi(r,i,o,c)}});var Ux=ce(ze=>{"use strict";var M=H;(function(t,e){let r=H,i=t();for(;;)try{if(-parseInt(r(609))/1+-parseInt(r(214))/2*(-parseInt(r(152))/3)+-parseInt(r(1330))/4*(parseInt(r(565))/5)+-parseInt(r(833))/6*(-parseInt(r(1375))/7)+parseInt(r(1261))/8+-parseInt(r(1117))/9+-parseInt(r(963))/10===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Ko,841012);var e1=Object["definePr"+M(215)],t1=Object[M(1536)+M(1232)+M(1074)],Nx=(t,e)=>function(){return t&&(e=(0,t[t1(t)[0]])(t=0)),e},n1=(t,e)=>{let r={dVBqy:function(o,c,d,u){return o(c,d,u)}};for(var i in e)r.dVBqy(e1,t,i,{get:e[i],enumerable:!0})};function Ko(){let t=["CM92AwrLige","y3jLyxrLrxi","yw5Hz2vY","C2v0y3vYC28","uffTENq","rKL1rKK","qwv2yNK","yM9L","B0XUu3G","sfDUB0K","DcbSAw1PDa","ywXty29Wzq","v3DQs1C","uffdALm","C1nZuw4","zM9YrwfJAa","yMLUyxj5","A3rVDxK","EMvzCfG","DwrSBNm","u2HHCMvKv28","zxq9DxrMltG","CgzYCwK","ihn1y2nLC3m","BIWGAg9ZDg4","Aw9UvgLTzw8","t3jkANK","mdaWmdaWmda","B3jL","vLzKD2y","Aw9Ul2PZB24","EwXcy0W","D3m6lY8","wKTPDfK","CvHXDui","CKToCxm","DMLJzuLeig8","tuf5D0C","B2zMBgLUzq","AufoAem","Bg93","uLb1BvG","AvfWB2u","oti2ogXruK9qEa","B2HSu0i","zgvIDwC","y3vYCMvUDeu","qw1VDw50","x2rLC3rYB3K","DujKzu4","uevVC3a","u1z3AhK","z0vjz0i","CLrWrLa","vfjODwq","rvPKsfa","u1Ptr1q","tK9xC28","yxGGCMv0CMK","uKjUyM8","r0P5q0G","u3ffBxu","rxjYB3jdB2q","ENLYz2i","B25mAw5L","sK5eu0C","BwnyBNu","Ahr0Chm6","Au1by1u","zM5uEu4","yxKSig5LDhC","yNHyChu","ywnOzwq","reTutha","zLj6y3O","zMzKsve","y2fSBa","zMzPqKu","rLbrv2y","zwT5swO","ywDL","y29Uy2f0","CMvZzxrdB3u","zg9Uzq","t1bftG","AgvKtwf4uMu","sM5cugK","sMjytva","mJa0odL2qxHHugi","Aw5N","y3vnDNO","rfLvCfy","x2nSzwfYvgK","ihrPBwvVDxq","B3jRzxjhBg8","DLnIAMC","v0LItw4","s0XVu0i","s3bctxa","sMT2vwm","AgjxDMi","l3DZl3yY","A3vuy08","qxDzwfu","DMfSDwu","yxbWBgLJyxq","AMfjuMm","z2vtEw5J","x2HHBMrSzu8","x3bPBMDqB24","Cujntwy","Dg9cExrLCW","zxj2AwnL","EwHOwNu","q2z2vKm","sKDAAfG","ENjSreW","BfjizuG","zw5HyMXLqxu","y3jLyxrLuMu","u2vXsuq","A2L5zxG","vgnVswO","Ec1TC2CTCw8","ChjVDg9JB2W","Bu5qzfG","renjENq","ohWXFdj8m3W","DgfYz2v0","Aw5KzxHpzG","EhPxqK0","A3jfs1q","EM5VvLy","vK9RwuO","B01pvfG","Ce9iENy","ruvKBxy","DhjPzxm","x1fVu01HBMe","tfDbs2C","vg1vsKS","yu1kDMe","q25juvq","y29UBMvJDca","BvLmwfq","B3jeAKy","sezkEfa","BMrWB2LUDca","AxPWzxa","Bgzev2S","seLorMy","zNLXD0C","x29UugfNzu4","y0vXB2W","x29UtwvZC2e","rLjptLrjrvi","CKXwt2O","Eunotfe","C2HPzNq","z2vjBMzVu3K","r0jquhC","qxfTyMy","De1YEuq","CgLzuvq","senxz3K","yMXVy2TLza","yKfyDMS","wu1KuNa","vLrkyuy","vLD6A08","Ae9Wzw5fDMu","x3bYzwzPEa","q25gAK8","sNH1wgi","r05orNG","wKzAsw4","vKLAzgu","rxrPzvO","C1Pktu4","zxH0zw5ZAw8","DhbzCKe","D0LJBuy","CgjgtuO","zu9Rr3a","yxv0B21HDgK","B25nzxnZywC","BgLTAxq","rLbTCKW","ChvZAa","DgvZDa","tfj5twK","ANftyuu","B25pCgvU","C3bSAxq","tuvtu0fhrv8","DwznD3a","uM14CNC","icSG","z2vY","rwzht1C","yLPTveC","EKL0suq","BM93","q09otKvdveK","yMnfyMy","A2DJAwu","D3zsBhC","sKHPuKm","zLL1wwu","CKnnAhy","wffpq08","twvZC2fNzuu","tfr2uKy","ruTntwC","D2LSBfjLy28","z2u6ia","q29Kzq","B3jpBMXPBMu","zMLUza","ufHWBKm","rgvKAwnHDgu","z2vnyMm","x3bYB3rVy28","yKnlAhm","DgnbEuS","zMLN","whvJAxm","uK9Tzem","AwXLx25HBwu","EKXYufO","v3bWvvm","D0PHuuy","ALjrEvK","A1zmBwi","CYbWyxjHBxm","DgLUzYbZzxi","qufgsvC","vufTyLK","zw5HyMXLvhi","BwfUDwfSihi","y2XLyxjtDg8","yxrLq291BNq","zwTTEM8","rM9kBMy","C0nur3q","y2HnyxHdB3u","D2fZq2XLyw4","m3WWFdj8mxW","B25VCgvU","z2v0t3DUuhi","zxf1ywXZ","y29UBMvJDgK","DwvIAee","D3jPDgu","v1bSrhG","C2vUzf9Hy2S","zNjVBu51Bwi","ugLlwfq","BNvTyMvY","C3rVCMu","CYbPBNn0yw4","C2nYAxb0","rNPRswG","t2PPuwy","BgvdCuG","AxbxCwK","rKfbyw4","zfDVCMTLCKC","qKH5why","ChbL","DxzIEeS","tKvzsvO","BwfnwLi","ywDLrxzLBNq","ywrKq291BNq","u25dD2W","tuHMEuW","AgLNAa","rgPSsNC","CMvHzfvjBNq","qMT4yLe","CNnVCL92ywW","q09fww0","EMr6r3m","Cu1yBNu","uuPTtha","AwXLtMfTzq","uwzAAvu","tLDHBvG","Cgf5Bg9Hzeu","yMHdqKm","z0zZt04","u0Xbq0C","B012t00","CM92AwrLihy","t2zlv0K","AwXSihvZzsa","qKfRC3G","zK15yum","y3r4","y29UC3rYDwm","C3rLBMvYCW","y29TCgXLDgu","ELnxzMS","rxzztgO","sen4B1y","v0LbsNe","zxncqMi","AwDHDg9Yt24","BM9Uzv9UB24","twzeAMC","ywX3yxLZ","zKfRveC","EKfntei","ywWGy3vYC28","v1bSwK4","y29UBMvJDa","vePZy3a","Dg9tDhjPBMC","oxWXmhWXmxW","y3ruAw1LB3u","wuHur2K","y2jZC2u","igzHAwWSig0","uM9OtNO","DuH0tNK","D24GCMvHC28","vu1zr0C","x21PBMLoyxy","id4G","Cg9W","AezquMm","t2v1DMm","BgvY","Efrurw52","x3bPBMDmB3m","DwjXBwy","x2zVCM1HDeu","wefvyuu","DxrVuMvJB24","y3Duuu8","zw5KCg9PBNq","yw1L","y29UBMvJDeu","wMvjEMK","CMv0CNLdB3u","s29Pq3i","B3vUDa","AgvHzgvYCW","C0Peqxe","r05uuwW","CMPuyvm","sMn1D2G","senvr28","qvv2q0q","vwjmyNK","rMX4z2q","Cwzkr0y","svbOyxq","AMXRsfO","CKLXAuS","s0zHCeO","mxWWFdr8nxW","C21bvui","yNL0zuXLBMC","rNzLCfm","Axnby2TdBgu","AwPQAu4","Be9Atuu","zwnVBM5Ly3q","Aw5Lza","EKLfvvO","AevYCM9Yrxy","tNDLthi","DgfIyxnL","t2XPywi","z2v0u3rVCMe","BLfKzgq","x0vysvnu","y09Wzw4","wgXvrxy","CM9YrxzLBNq","AxnmB25N","yw5ZzM9YBvq","Bu9HshC","swnSwKC","B3nLza","Dg9iyxnO","BLrOwfi","Bwv0Ag9K","tKPtB0e","wunoq28","s2DzBu0","twLZC2LUzYa","sgzWuuq","vu1cA0W","DNbZquW","vu1VCxe","Aw5PDcbrB1m","C0DRu1q","y2XVC2veqG","svDlvvq","z1jbq1y","EK5RyNe","ELDfEeS","BgPcCNu","x3bHDgHlzxK","CK52sgu","zxjFBxnNAwq","AMj1A2q","zNjVBuj5Dgu","B2fK","tgffz2q","t1vnv3O","zw1PDa","C2vYDMLJzq","Dg1hDgC","ze1TtM0","B3bLBKrc","otbRrhbttKi","DfvdCg8","su5Yr2y","y3vYC29Yx2y","x3nVy2TLDa","B25ozxr3B3i","vxPgufy","C0TABwy","BNrbBMrvCgq","qLHMz2O","zw5fDMvUDa","nhWW","yM9tEhK","re9vDwK","r09Azfi","rMvdDxq","AePftwG","BwvZC2fNzv8","qwfyr0m","tKDxtwG","uhDrzei","z2v0qwXSs2u","C25yA3G","zgLdyvK","t1bftL9fuLi","x25HDMLNyxq","rxHKq2S","rwreBe8","igzPzwXKoIa","zeHMy1m","reL5Dve","CwnLrw8","tKfusvzfx0u","C21bCeW","B25szwnLAxy","vvH0wK8","z090sxO","uMvhAKi","DxvIyNq","zgvSzxrL","uefNBgi","Defyzxe","yxv0BW","BKTpz0C","BNrLCG","Dg9cExrLC0i","AgfZ","ANjAvwW","DMTjAfq","BKnPyuG","AevKtfe","q0Xpu0ve","ALnJAxa","wxj0CLK","vgXtDwy","Cg93","y3vYC29Y","zuzPB3G","zhj2vhq","CLHWuKC","x3DZ","y2vZC0HHBMq","nta2otHMswz1C1a","B3bLCNr5","x2LZtwLUAvq","tg9Nsuq","yvrKBwi","x2nYzwf0zvm","ChjVDg90Exa","DgHHBIbSB2m","qMXKDvm","zvjiv3i","vLfhD2S","sfrfA3a","BgDPEMe","BM5Ly3q","EvjLy29UBMu","BNruCMLLC0m","zMDcz2e","wMLAA2u","v0HMzwe","r0PAzNi","ExvgC0O","BMvJDa","yw1Lu3bHy2u","B25tDg9Wsw0","z1rPBwvVDxq","uNPUAvi","A213CNK","Bwu6ia","u0PRD0y","CMvZzxruCMK","z2v0q3vYCMu","x2TLEvbHDgG","yMLUyxj5vhK","zwrPyxrLBhK","BMCGDxjSoIa","vfD0AMi","yxzrue0","s2THuKi","zwzJCfa","B2nRzxq","DKHAANC","BuDQEwu","tMfbzLe","AgDNqxu","yvHvtMy","Dhr3Awq","yNL0zxm","CgLUz0LUDgu","Axn1rLG","vNrHzMe","Buf3BKq","ihrPBwvZ","yvvXrei","DeLK","B3jLtMfTzxm","y2HHCKnVzgu","CMvWBgfJzq","CMLLC0nVDw4","D29gtuK","DuPnAeS","DuTyyMC","Dxf1DKu","zurqzNC","yvHou0e","reiGzMfPBgu","ywXSB2nvBNm","yMLUza","vezjsfy","rvz2ugC","A3PPBwu","zvvYBa","y0HvwvK","txbUzw8","AxjLza","Bwf4uMv0CMK","zgLZCgf0y2G","D3nZoI8V","zMLSDgvY","yuXlzK4","zunhCwq","qLrlExq","B2nRzxrgywK","Dgv4Dc9WBge","qNjTtNq","v2vPEgLUsLm","vg5eqMe","qwjVCNrfCNi","Bw9cCfa","vvLxwMe","qMTJzxG","r0fwCMu","yMX0B2q","tLD4rgK","zxjFCw9Zx2e","sM1uwui","quTxwe8","qLLeAum","CM92AwrLihC","rxzPyxO","Cu9LB00","CMD5Eve","yNvMzMvYzwq","quPSEwe","DuzLAvC","CgLUz0XVC3m","rwvzq2m","vuvnwMq","Ahr0Ca","ELvttwy","x2LZtwLUAvC","ywXSzwqGBxu","igXHCMDLCIa","qKXqs2u","zurXyLC","DgLTzw91Da","BhrPCgXLihq","s2TeyuG","whrQz0O","yM9KEq","u2vYDMLJzvC","B2jQzwn0u3q","B3bLBIa","zxH0ugf5Bg8","y1L3Evu","rM52wwy","wM1Jsw0","Bxvmq2e","CxL6se8","u2LpD1O","Dgzqs2C","x2nSzwfYugK","tg9NsurozxC","Aw9U","DuDUuum","q2z3tLC","qvLmsLm","twjJBMm","y3jLyxrLt3a","x2HHBMrSzva","De1LvK8","qK1Qu3G","y3vYCMvUDeK","AwLqCuS","CLPuuve","ugXWvg8","DMvUDa","CgLUz09Uy2u","Dg9mB3DLCKm","rxzLBNq","AxPNv1O","r3vdwwe","tfDrBKe","rMToCfu","thHZtMu","y2f0y2G","qK1vwhy","jMPZy2fSBgi","rgnuwwi","vejVqum","uLPZu3O","rNjVBNrPzxi","BMDuAw1LCG","zw5HyMXLuw8","v0TbExO","wwzfseG","Dxrjza","rLrbwMm","AxnszwfKEq","x2LUAxrqCM8","qLzWDhm","AvLTC3e","t2jQzwn0","zwPwwLC","vM9pzhG","AxmGDw5Kzwy","x3jLy29UBMu","C3vIyxjYyxK","v2HdzMG","Axn0tMi","seXlBeO","uM1tt0q","x29UvgLTzw8","CfHssey","shHgrfO","DxnLCKLW","o2nOyxjZzxq","Bg9NsurozxC","B2nRzxrtDwm","BMnoALa","tufyx1jfvfi","x2LUDgvYDMe","DxrMofDYAxq","ueLeteC","C2vYDMLJzs0","EKDHs2m","x3DZsw5ZDge","tg9JAW","zxjFAxnFywm","zLD5C1G","DhjPBq","zu5Hv2O","sLDlrfO","r2v1zhC","ig1LC3nHz2u","BgLUzq","z2v0q3vYC28","u1fwz3K","zMzLCG","z3PqBgy","vhjnuKe","zw5JB2rPBMC","rwrIAhu","tMTIwhy","v1D4ruu","zv9ZDwnJzxm","zxjYtxnN","x2LZv29YA2u","DNjgvhy","B0j1rw4","zNjVBNrPzxi","q21euwi","B3Deqw8","z1j1Bei","EMv1sfy","zw50tgLZDgu","A1Hpu0S","y3DsAuG","x2DLBMvYyxq","wfbmuNu","B25fCNjVCG","y29UDgv4Da","s3vUrLq","nhWZFdj8mxW","y1DIuK4","C3rhBxG","Cgfzuxa","zgf0yq","uurjswq","rMLSDNG","AuDQBhy","AuTSuw4","C0Xf","CMflq2i","rMvOCeu","u0vkrLe","Axvev3i","B2zM","t2f5rgC","DgvmB2Djre4","lcbTyxGGCMu","zNjVBunOyxi","sKDmEve","CgPgExi","C3fyCMu","qMvIwhm","y1ntyLG","CMXcBLK","zu9dtxm","ywjVCNq","DxjjteO","zMzmAw5L","t2TyAxm","ruHvwNy","ywnR","A3PKuxK","AenSB3nLrxy","q0DZCwe","Dg9hzw5LCMe","DhLWzq","y29UBMvJDfm","ugf2B0C","ywDLsgLKzq","zgrjrcWGzgu","Aw1LCYbPBIa","Bg9IywXty28","z3HJD08","zeHprMq","y3zZChy","u3nPB28","Chfxr0i","BvvfAvC","yw51Ce1LC3m","vxrrzNe","x29WDgLVBNm","CLzHBhvLCW","y2XVC2uSihC","y2n6Deu","wLfbEMy","C29YDa","CMHgvva","yxjOq04","rwXcDwW","zxjFCw9Z","Cw9Zx18","DePUDg0","Dxn5twW","swD5uui","C0XPC3rLBMu","zwvzuvy","ywn3D0C","zNjVBujPDhm","ywrKrxzLBNq","q0LvyvC","vvDhru4","EMHqAMW","vw5PBxbSzw0","r2XsAw8","yMPiv1O","DNPOB2y","t0LPALG","ywnRx2LK","AMH5Ewy","AwH0Ehy","D2XQAw8","thj6Dxy","yxnJCMLWDa","De1HBMfNzxi","z2v0","sNnZweq","Dw5ZAwDUzwq","y0DsEge","q0zXtgW","rKv6D2u","B25JBg9Zzq","zxnsBuK","uurLtLi","BwLUAvbYB2C","x21LC3nHz2u","zcWGDw5RBM8","q29Xz1i","v3DVtLm","yxfrB3m","qLDUDuW","se1ns1i","C0jf","BwvY","yxbWBhK","x29Uq2XVC2u","Dg1TuuC","tKDFrvjst1i","twXnq1u","AKrUAhO","BMvLzf9Hy2S","BgLUzw5V","v2zbCLC","wM9bqva","AhPcAfe","Bwf4twvZC2e","sfvLuuu","rfPRzLm","EeniDu0","mJi1nvbfCg1byW","CMPSBvq","Bg9N","x2rPC2nVBM4","qNrpsxO","CYbHBhjLywq","zxjYB3i","ExbL","yxnL","EK9vqu8","qxvprK4","z3zpA1K","vgTju3a","q291BNq","Dw5KzwzPBMu","yMfJA3vWigu","BxnNsuq","uhnvCLq","y3vZDg9Tshq","BMCGB3iGyw4","tNjzyK0","uwTXsxe","CMvJzwL2zwq","BxnN","ue9Rwvq","vxLPBfO","zxjFywnRx20","BNrfBMrWB2K","Dg9cExrLC0W","y0fju3q","AxnrB1nby2S","C2vYDMvYvgK","Dfbhsxq","v1j6Bfu","r3P1seq","venwq3a","zgvJB2rLzey","yMfSrxzLBNq","s3H4qw0","A1DvD0i","DMrPt2e","vKfTEKm","Bvn3CKq","D2PSvxm","nZaZmZjmrLDiA0G","ywXS","wM14EM8","B2fnr24","s2rtvuW","C0XtEhK","vKvXDhi","uMH3zgu","vMvbs0C","yxHfBu4","D0forM0","qu93zKe","uufkDhG","AMvJDfn0B3i","AgjXqNe","CvHYBeO","Axj6vKe","u0TeExa","y2jgs1e","CMvXDwLYzwq","CgzYAva","z1nNzNa","v3nWsvG","s0HAvfi","sKHvENq","rg55A0W","CLHztuG","ru53A0y","CMfUzg9T","zNDZxZeUmc4","Ec1TC2CTy3u","A0LVzvi","ihzHBgLKigq","yKLcCNG","BxHjAMO","Cg9PBNrdB24","C2v0u3rVCMe","B2PuDfm","AhHyBwq","C1jLBeO","EeDRAfi","se1sDhy","D3jPDgvvAw4","D0fWy2S","wxvxy1K","whrhD2O","C3vJy2vZCW","x3jLBw92zvC","y0DYDuu","y29SBM8","re9AAge","vhfUugS","A3jisLK","CMvZB2X2zq","y3vYC29Yx24","Cgz0txC","zvH3Ae8","yvzks2W","weXNq0G","qNfbCvu","vefMr0S","v1jQCxK","ywrK","ywjSquO","B2ftA24","BMzQuhC","BwvZC2fNztO","ru1rBxm","BMfyuuu","A3fey3u","zhPOt1a","EgzgBfu","BMv3vMvYC2K","uhDJsuK","mxW0Fdj8mhW","yNj1z3C","r29RwM0","y2uGBM90igK","uvHHDwC","C3rVCcbPBw0","u2nOzfC","A01Itvm","CfrtrhK","rKz4y0G","rwfZDMu","zgLZywjSzue","A2v5CW","rxfmq0O","DxPhqwS","BwLZzq","BgPdq2u","v1rdzKm","t3bLBKv2zw4","BwLUzW","B0zcz0u","u2XzAMK","C2DPza","B3vhvwi","t2jqA2u","BMnLq2XVC2u","EgPwsNm","BezSDxnO","BKXPBMu","ve9sswq","C2THvwm","CMvHC29U","x2rYB3bhBg8","rLDt","x3jLywr5q2W","re5ntxG","CNjVCK1LC3m","ignVzgu6ia","BgvUz3rO","rMH3tfi","AMLlvgW","vMvvyuG","vw5Oyw5KBgu","vMHyB3q","z3DJq3O","wvnJsNa","x3nLCuLK","EKD0Bu8","y29Kzq","B3nLrxzLBNq","seLYB2W","zwn0","DxjS","CMvQzwn0","zw1LBNq","z0LiD2C","t3zdAwi","z29PBMCGyxC","x2jPBMfYEvq","AM5Mt3y","x19LC01Vzhu","sKv6swW","CMXpq3a","CMvZzxrfBMq","CLryAxe","C3rYAw5N","svDTB0y","s3bsD3O","txDRtwS","zffHuNe","BhHTC3y","zM9Yy2u","wu1Au3C","ihrVihjLDhi","we9WEKS","CeLuvgy","Be1WANq","zxmGCMvHy2G","AgnhwwK","svrvvMS","Cwvjrvq","D0fOu00","A2v0ignVBNm","DNfnCLi","y0Toy3u","r0zywMy","BgvOr20","r011sNa","x29Ut3bLBG","y3jLyxrLtwu","wKLyAue","x3bPBMC","yKntz20","C2vUza","uLjpuG","x2vUzhbVAw4","B2LUDfjLywm","tw9KDwXL","uvv3qui","uMT0v1u","zxHrwNu","ELvbtuq","zMLSzw5HBwu","t09swe8","Dvrps3O","Egv0Bxa","CK9tqw0","sNjrEwq","tKz6qKG","CMvZDwX0","AwrI","tu1MBxe","C3j1vhi","D2vI","A2PQBeC","uef3tw8","tgLZDgvUzxi","z0P3BgS","v2LUzg93","z2L1z0q","wLPlzKu","vMrYquu","t21VCfO","t2LTC3q","Aw5L","yMjzrwK","CIb0DhDjra","zwTowuC","BMv4DcGPigm","DhDVCMTdAge","zw5XDwv1zq","AgvHzgvY","C3vRsfi","tgTPCwS","shbKuvK","A1n0yxr1C0m","z2z3EKS","t0XVz0i","y3nxzfm","wgnzyxm","x2nVBM5Ly3q","CM92AwrLigi","t2nMALG","x2n1CNnVCKy","z25stuG","zMvY","BeHHBMrSzxi","x2rLyNvN","B3v0sw50zxi","q05YDhm","mti0mNzyELntsq","yuDys1m","uMvJB25Uzwm","uxvLDwu","DhjHBNnHy3q","nhWZFdb8mNW","vNfpwNO","v05HyMi","zhPZv2K","teXyvue","svLeAKy","BNfyzhC","t3vND2O","B0jez0S","AM9PBG","sM1ID1G","zLHXvvO","tfn2uKO","zfffEeG","uKr1zfO","t3bMzLq","zxrxB3jRq2G","quLzy2e","x2XPC3rLBMu","CgvYC2LZDgu","Eg9qvKG","Aw5JBhvKzxm","BML0AwfSAxO","vhjSu1a","B25dBg9Zzq","vwfWtwy","CMvUDevUzha","x3vYBa","shvAswm","C2v0","BhrZtLO","EeDwqK8","DMvYC2LVBG","B2PTrNi","zxHWB3j0CW","yNbev1q","DhjPzxmGCMu","Cuj6Ew8","quzKAKy","qwjmruO","rKjQtuO","D3PNrhu","AejPy0W","BuLqzw8","C1vftvy","ENbOt0C","BwjNueK","zxjHDg9Y","q3rtrKW","u0P6wuS","v0L1AwO","lcbxzwjtB2m","yw1LoIa","q3vZDg9Trxi","B25LCNjVCG","v2vIu29JA2u","AwXK","uhjPBwfYEuS","vwPkDeq","t2HWs04","re1cyKS","BfvhteO","Dgv4DfbHEwW","tfnUy1O","CNnKqwS","y0L1vhG","shHWzuG","yvjiuM0","zMXwsNG","z3fduw0","BvnNDKW","EK5NreK","zw50zwqGDhK","uhffEha","rwHPD2O","CgnRvw4","B3vbs20","CMvTB3zLq2G","t21Xt1i","DNzVwhK","uMX6yMG","s0HNrLK","qK1IzeS","ign1CNnVCIa","BMrLEa","D1rpueW","zcWG","CMfTugfYyw0","sLnptLa","yMjNAM8","C2fNzq","CMvJzxzPzwq","qLHjzxG","igfYCMf5yNu","B3nTqNi","vgLTzw91Da","wwXcuwG","u2DSEvm","tgHTt3G","yxKSihrYEsa","AgvODvG","s05Szhi","ufzfy2m","CwjjuLO","Aw5KzxGGB3u","wMXmDLi","zw5JB2rLrNi","Dw5RBM93BIa","CMvKDwnL","yMvjs20","z25UvLK","mhWYFdf8nhW","ywXSq3vYC28","weL4BKq","ChL6ufy","sg5srvO","EKznALq","Cgf5Bg9Hza","Aw47y2HHCNm","zuL1vey","z3rny3y","DLbiwMe","r2HQtxO","wfzpwKq","y0vbuLa","otuZodK3mgHJu3DhDa","zeLLB1i","wMPNwfq","y2XVC2u","DerprhO","tKTgs08","uhvtv3G","C2v0sxrLBq","BxznC0C","zw50","rgXWzwe","BMrWB2LUDfq","DfLpuw0","uKHrCxy","Ae1LC3nHz2u","BNDXvum","rNfRuuG","CMvWBgfJzui","BMDLza","m3WYFdf8mhW","zxjYtM8","twLkrM4","AvfHqLa","tgzcvLa","ywnOzwqSihC","sgvTt0C","y3vYC29YlNm","x2n1CNnVCK4","A2fzq0e","AvbTB0q","y2HnyxHuCMK","qKn4Awe","vhHuA3q","Cfzlrfy","EvbXAgG","svLZD0S","Cgf5Bg9Hzfq","zNvUy3rPB24","CgjICdi","zw1kz0q","x2LUAxq","DxbKyxrLq3u","t29cEeG","x29UrxjYB3i","zhHZB2e","wK1hqKy","zgvSzxrLrge","ALfXA2u","x3DHAxq","uLjxD0i","zuzvwei","rvjst1i","yw5Nzq","qNjPzgDL","ufHuwfi","C2ntB3m","z2rxtNm","D2Dbzxy","y3rwr1K","x2LZsw5PDa","vu5zsuG","CefQyNy","BMvY","ru5MCMu","CgLUz19VBMm","z2v0sxrLBq","CNnVCKzPBgu","yxPtqwu","ter5rgK","DhbizwfKzxi","AxnrB1nnzxm","Dev2zw50","yNL0zu9MzNm","z2v0s2v5","vwPhELG","yxrHlcbKyxq","tNbcA3y","AfPYC1e","rKDis3O","Au5nBu4","q09oveLovuu","ywnRtxnNswq","CgLUz1rPBwu","Bhbzthi","x2fKzfDZtgK","ywD5t2i","x3nLBMrby2S","zwjtqLi","Ee5Qsxa","q29UzMLN","zMLpCMK","Dhj1y3rVCIa","C2XfwK0","y0HTB0S","v2rQwMS","DgvACNK","ruvdsNy","zfHgrwi","B2zMC2v0","Cw9Z","Ag9LwNm","uKzVse4","zvvqrxq","z2v0qwXS","ANHPy0u","AxPTyvy","zMHKt2O","qK5xugW","rffAvMy","u3rYyxrLz3K","B25SAw5L","BwvZ","wgzrsfK","A2X2Dgy","C3bSAwnL","qvfQyuG","ywzL","yMrFzgLK","yNvMzMvY","BxzlyNK","txflBuy","Dg9VigXHCMC","mhWXFdv8nhW","vurRtvy","zMj5sKu","CxPrtei","BwvKAwf0zwW","C0nVDw50zxi","qxbPCNm","y2resfK","AvD1CKG","suvtx0vsuK8","y291BNq","vKLgy0O","DwvwtgW","Ef9MCM9UDgK","B3jRig9MzMW","CMvTB3zLrxy","BxPTzu0","Dw50","yMz1DLC","sgfYBve","yxnZAwDU","sxLYBwm","Aw50zwDLCIa","Chv0","D2Lpr20","D1PkAfe","DgH6Aum","x2n1CNnVCK0","AfrOthu","rNbXuw0","B3HNtem","qxHUA3y","mtiYmteZogvou2PSAa","AKHozfq","uhLqCgm","AxnbCNjHEq","zMX1C2HfEha","tKLorvm","DxbNCMfKzw4","ue1Yt0C","sKLiDfu","BgXLs1y","yMrJDwm","y3jLyxrLrwW","x3fVC0rc","q09ACMW","B1fjvMy","CNzHBa","DNnrBKe","tKPKu0W","CNzHBfzHBhu","Egvss3O","sLn5quO","x0rctMfTzq","qxjUwLi","DgLir2S","x2rPC3bHDgm","sgX3Cxu","BgLZDgvUtMu","C2XPy2u","zhDUtLi","yu1tq2S","uM9eyuC","BMPZy1i","DwnPAvC","zv90Aw1LB3u","DKXrzeW","ywDLu2HVDW","q1DTshK","z05PEgK","y29UDgLUDwu","CgXLyxnLiha","rKLmrv9ot1q","ruDeD2C","t3PXBwO","ENHQuNm","DNv6Dfm","BMfTzq","AefJA01LC3m","EM9Uzem","ChLSrxu","rvPhEKq","yMfSu2nVCgu","qLDWEgS","EfvZzuvUDG","AxnFywnR","ruDUzgC","thrVA1O","qwniwMW","Dg9Y","zgvMAw5Luhi","x2LZtM9Kzq","x2HHBMrSzvi","AgfUz2u","x2LZqNjVD3m","rgXzveG","zgrmEhG","wKr0Dhq","rNHgwLy","B3bLBG","ihbYB3rVy28","q0Xpu0LorW","m3W0Fdj8mhW","zeXbq0i","B25tDgfYDfi","Cg9PBNrbBMq","D3jdqMu","C3nHz2vfDMu","zufJAW","y2HLy2TdDxi","AfvftLi","C2v0q3vYC28","y3jLyxrLq2W","C2L3C1q","y2XLyxi","t2DHy1m","CKX1De4","ELPUtNi","m3WYFdy","CMfNzvn5BMm","CK5etuS","y3vYDMfSDwu","Cxrwz1u","q3vZDg9Tq2W","CvDOB1e","rwHfCuu","Cgz4BeK","x2DLDeLUDgu","r2vwDfG","yxjYyxLIDwy","BwvZC2fNzq","mdaWma","tgLAwKq","B3DVDMW","txjNyNe","q2njuhy","CgfYC2u","txHjq3y","y1PvtKW","CuLgDMu","yu53vvu","uNzcDgu","Cg9XrgO","lcbOB3n0BMe","y2HLy2Tszwe","Dgvyvey","yxDewvO","B3bLCNr5tMe","C0L4zvu","ChrVCG","C3rYAw5NAwy","tMfTzq","C0nJD2m","zLvytLa","t3rTrKK","C3vIC3rYAw4","Egrhzve","CMvJB25Uzwm","q3bXC04","C3HdzxK","BMnVzgLUzW","yxbWzw5Kq2G","EMLmBLy","sKPjBwG","Ehjdvha","BwfW","zKzPugW","zvbkuvm","zNjHBwvuExa","A2v5","uMLosLC","aaaaaaaaaaa","tuzlt1u","x2LUAxrhBg8","ue5qvgm","v0PnufK","mtm0mZyYndHMquvvyLO","CMvHzhLtDge","BfrPBwvVDxq","x2rItMfTzq","qNDYyw8","B2XKvMvYC2K","zgvS","DvfcDvO","D1ruAvi","wu9csfm","v0vus2q","sg9PCKW","v215Cgm","ywTsEKu","s3bpB0y","tNvht1q","DNDuC0G","t2XMCMq","EsbJBg9Zzwq","DM1IvwW","CgfNzwHPzgu","DeLUDgvYy2u","CMfTzq","v2j3vfO","wgfSseC","DgHLBG"];return Ko=function(){return t},Ko()}function r1(){return Rx||(Rx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function i1(){let t=M;return Px||(Px=[IDBCursor.prototype.advance,IDBCursor[t(220)+"e"].continue,IDBCursor[t(220)+"e"][t(1155)+t(895)+"ey"]])}function s1(t){let e=M,r={SLACG:function(o,c){return o!==c},LSncZ:e(223),zphOG:function(o,c){return o(c)},Oeuvc:function(o){return o()},UjGzX:function(o,c){return o(c)},lMpjt:function(o,c,d){return o(c,d)},pfrqi:function(o,c){return o+c},bxXpu:e(942)+"t of ran"+e(1502),YtFRi:function(o,c){return o||c},mvMsG:e(1616),YMZSw:function(o,c){return o===c},nKOgG:"MMZKH",uzGAk:e(661)},i=new Promise((o,c)=>{let d=e,u={ZFAPf:d(655),hxXmd:function(m,S){return r[d(1037)](m,S)},ZiZke:function(m){return m()},cGruE:function(m,S,y){return r[d(759)](m,S,y)},ebSBR:function(m,S){return m+S}},f=()=>{let m=d;t[m(1100)+m(438)+m(1025)](u.ZFAPf,x),t[m(1100)+m(438)+m(1025)]("error",g)},x=()=>{let m=d;u[m(647)](o,Ut(t[m(792)])),u[m(231)](f)},g=()=>{let m=d;if(r[m(1579)](r[m(901)],m(223))){let S={sCTGt:m(571),GJyCH:function(b,I,A){return u[m(657)](b,I,A)}},y=_0x51cb88.buffer[m(1144)](_0x343771[m(1035)+"et"],u[m(1050)](_0x204c37[m(1651)+"th"],_0x75053f[m(1035)+"et"]));this._socket&&this[m(156)][m(776)]({data:y,fail:b=>{let I=m;this[I(1701)](S.sCTGt,S[I(1347)](_0x120b2f,S[I(1531)],{message:this["_formatE"+I(719)+"age"](b)}))}})}else r[m(883)](c,t[m(571)]),r[m(1619)](f)};t[d(515)+"Listener"](d(655),x),t[d(515)+d(799)](d(571),g)});return i[e(1286)](o=>{let c=e,d={fbZWG:function(u,f){return r[H(1309)](u,f)},zyrgb:function(u,f){return r[H(1309)](u,f)},xdGeQ:function(u,f){return u+f},lpYLr:function(u,f){return r.pfrqi(u,f)},eDqbW:r[c(1358)],MlMCU:c(1484),tAXeq:function(u,f){return r.YtFRi(u,f)},tvgtR:r[c(971)]};if(r[c(755)](r[c(195)],r[c(195)])){if(o instanceof IDBCursor){if(r[c(697)]!==r[c(697)])return _0x51e452(d.fbZWG(d[c(1350)](d[c(1241)](d[c(1046)](d[c(327)],_0x1a8f5b),d[c(554)]),d[c(193)](_0x344185,1))+d.tvgtR,_0x2ddc13));Fd[c(867)](o,t)}}else _0x1def2b[c(1475)](_0x12c650)})[e(368)](()=>{}),Vo[e(867)](i,t),i}function o1(t){let e=M,r={zeuHV:e(1589),WPlDx:e(571),pAjbv:e(472),leCqH:function(o){return o()},oaMGn:function(o,c){return o(c)}};if($o[e(198)](t))return;let i=new Promise((o,c)=>{let d=e,u={KFapJ:function(m){return r[H(1551)](m)},KkaRB:function(m,S){return r[H(612)](m,S)},izpep:"AbortError",bZGwo:function(m){return r[H(1551)](m)}},f=()=>{let m=H;t["removeEventListe"+m(1025)](r[m(437)],x),t["removeEv"+m(438)+"ner"](r[m(1541)],g),t[m(1100)+"entListe"+m(1025)](r[m(1024)],g)},x=()=>{u[H(1648)](o),f()},g=()=>{let m=H;u[m(251)](c,t[m(571)]||new DOMException(u[m(1435)],m(300)+"or")),u.bZGwo(f)};t[d(515)+"Listener"](r[d(437)],x),t[d(515)+"Listener"](r[d(1541)],g),t[d(515)+d(799)](r[d(1024)],g)});$o[e(867)](t,i)}function a1(t){Jo={DIyuQ:function(i,o){return i(o)}}[M(182)](t,Jo)}function c1(t){let e=M,r={nfjPw:function(i,o){return i(o)},VzdYa:function(i,o){return i(o)},OkXis:function(i,o){return i(o)},YlBQh:function(i,o){return i===o},StZQG:function(i,o){return i in o},bfuvW:e(334)+"oreNames",pZulI:function(i){return i()}};return r[e(934)](t,IDBDatabase[e(220)+"e"][e(837)+"ion"])&&!r.StZQG(r[e(1103)],IDBTransaction[e(220)+"e"])?function(i,...o){let c=e,d=t[c(1363)](r[c(674)](es,this),i,...o);return Bd.set(d,i.sort?i[c(502)]():[i]),r.VzdYa(Ut,d)}:r.pZulI(i1).includes(t)?function(...i){let o=e;return t[o(550)](r[o(475)](es,this),i),r.OkXis(Ut,Fd[o(531)](this))}:function(...i){return Ut(t.apply(r.nfjPw(es,this),i))}}function d1(t){let e=M,r={ITnRd:function(i,o){return i===o},krEKT:e(1e3),gRACV:function(i,o){return i instanceof o},ScyWx:function(i,o){return i(o)},csWdS:function(i){return i()}};return r.ITnRd(typeof t,r[e(1418)])?c1(t):(r[e(1689)](t,IDBTransaction)&&r.ScyWx(o1,t),Mx(t,r[e(821)](r1))?new Proxy(t,Jo):t)}function Ut(t){let e=M,r={hggAu:function(o,c){return o instanceof c},eFiox:function(o,c){return o(c)},TNHyQ:function(o,c){return o(c)},vmbUl:function(o,c){return o!==c}};if(r[e(257)](t,IDBRequest))return r[e(209)](s1,t);if(jo[e(198)](t))return jo.get(t);let i=r.TNHyQ(d1,t);return r[e(1280)](i,t)&&(jo[e(867)](t,i),Vo[e(867)](i,t)),i}var Mx,Rx,Px,Fd,$o,Bd,jo,Vo,Jo,es,Dx=Nx({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={rjlmT:t(838)+"1",hqbmt:function(r,i){return r+i},awdUb:function(r,i){return r+i},cbsse:function(r,i,o,c){return r(i,o,c)},aUqDB:function(r,i){return r+i},jjsKm:function(r,i){return r<i},LWAKg:function(r,i,o,c){return r(i,o,c)},ZmcIm:function(r,i){return r===i},ofYrl:t(767),rXpRG:function(r,i){return r instanceof i},ihtxv:function(r,i){return r===i},hehuX:t(1370),efcpP:function(r,i){return r===i},Oliab:function(r,i){return r!==i},QBcme:t(206),QJmLp:t(1647),WbqrU:t(1017),RRWwB:t(654),hcGYi:function(r,i){return r(i)},AhmAO:function(r,i){return r instanceof i},BCxia:function(r,i){return r===i},VqOZz:"store"};Mx=(r,i)=>i.some(o=>r instanceof o),Fd=new WeakMap,$o=new WeakMap,Bd=new WeakMap,jo=new WeakMap,Vo=new WeakMap,Jo={get(r,i,o){let c=t;if(e[c(339)](e.ofYrl,"cKNcu")){if(e[c(211)](r,IDBTransaction)){if(e[c(526)](i,e.hehuX))return $o[c(531)](r);if(e[c(252)](i,c(334)+c(268))){if(e[c(1662)](e.QBcme,e[c(1572)]))return r[c(334)+c(268)]||Bd[c(531)](r);{let d=e[c(566)][c(1480)]("|"),u=0;for(;;){switch(d[u++]){case"0":if(_0x673696[c(405)+"e"])return e.hqbmt(_0x2dd43b[c(405)+"e"](_0x151e66,_0x34e52d),_0x4ec5a5);continue;case"1":return e.awdUb(e[c(1609)](_0x183e98,_0x3a442d,_0x96b6ec,_0x335305),_0x58fe40);case"2":if(_0x2f8407[c(1540)])return e[c(266)](_0x32ef90[c(1540)](_0x1c7084,_0x331c37),_0x46a053);continue;case"3":if(e.jjsKm(_0x3170ab[c(721)],40))return e[c(1426)](_0xd235c8,_0x3cc63b,_0x323e58,_0x1f9257)+_0x516318;continue;case"4":if(!_0x41a114)return _0x4aaca9;continue}break}}}if(e.efcpP(i,c(1546))){if(e[c(1662)](e.WbqrU,e[c(1012)]))return o[c(334)+c(268)][1]?void 0:o[c(334)+c(1315)](o.objectStoreNames[0]);this[c(216)+"T"]?_0x400811[c(157)+"kStatusC"+c(1178)](({isConnected:d})=>{let u=c;this[u(1615)+"igatorOn"+u(418)]=d,d?this[u(1395)+u(711)]():this[u(1395)+u(474)]()}):this[c(323)+"X"]&&_0x4b3bf0[c(157)+c(818)+c(1178)](({isConnected:d})=>{let u=c;this[u(1615)+u(1595)+u(418)]=d,d?this["_handleO"+u(711)]():this[u(1395)+u(474)]()})}}return e[c(761)](Ut,r[i])}else return this._qosDB?.isReady},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return e.AhmAO(r,IDBTransaction)&&(e[o(994)](i,e[o(938)])||e[o(994)](i,e[o(839)]))?!0:i in r}},es=r=>Vo[t(531)](r)}}),Bx={};n1(Bx,{deleteDB:()=>u1,openDB:()=>l1,unwrap:()=>es,wrap:()=>Ut});function l1(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=M,u={smAUB:function(g,m){return g(m)},GJZfr:function(g,m){return g(m)},PNPTc:function(g,m,S){return g(m,S)},fAkTG:function(g,m){return g===m},UEMZd:d(1160),dJiIL:d(966),BVpts:"versionc"+d(1178),wApck:function(g,m){return g(m)},XLgCH:"xVIwV",rOSAm:d(1123)+"eeded"},f=indexedDB[d(1184)](t,e),x=u[d(652)](Ut,f);return i&&(u.fAkTG(u[d(667)],u[d(667)])?f[d(515)+"Listener"](u[d(789)],g=>{let m=d;i(u[m(1650)](Ut,f.result),g[m(1266)+"on"],g[m(681)+"on"],u[m(233)](Ut,f[m(837)+m(346)]))}):(u[d(1259)](_0x164c3e,_0x1f8a60,16),u.PNPTc(_0x5d8ac8,_0x1c01fe,_0x57e939))),r&&f[d(515)+d(799)](d(1452),()=>r()),x[d(1286)](g=>{let m=d;u[m(1599)](u[m(320)],u[m(320)])?(c&&g[m(515)+m(799)](u.dJiIL,()=>c()),o&&g[m(515)+m(799)](u[m(383)],()=>o())):_0xf637d[m(567)](_0x575646)}).catch(()=>{}),x}function H(t,e){t=t-148;let r=Ko(),i=r[t];if(H.sUzEYP===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",m="";for(let S=0,y,b,I=0;b=f.charAt(I++);~b&&(y=S%4?y*64+b:b,S++%4)?g+=String.fromCharCode(255&y>>(-2*S&6)):0)b=x.indexOf(b);for(let S=0,y=g.length;S<y;S++)m+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(m)};H.ENPnCj=o,H.BPQsGQ={},H.sUzEYP=!0}let c=r[0],d=t+c,u=H.BPQsGQ[d];return u?i=u:(i=H.ENPnCj(i),H.BPQsGQ[d]=i),i}function u1(t,{blocked:e}={}){let r=M,i={cEqol:r(1452),xzWBM:function(c,d){return c(d)}},o=indexedDB[r(1009)+r(1661)](t);return e&&o[r(515)+r(799)](i[r(1440)],()=>e()),i[r(1417)](Ut,o).then(()=>{})}function Ox(t,e){let r=M,i={sruTr:function(f,x,g){return f(x,g)},eeYQV:function(f,x,g){return f(x,g)},VIZde:"readwrite",CaXWG:"readonly",ZKitY:function(f,x){return f instanceof x},EGDwg:function(f,x){return f===x},TlUzQ:"string",PKCxR:function(f,x){return f!==x},bdcuc:r(960),Xoanj:function(f,x){return f!==x},ddLxx:function(f,x){return f in x},Xucis:"wdbOR"};if(!(i[r(1320)](t,IDBDatabase)&&!(e in t)&&i[r(1158)](typeof e,i.TlUzQ)))if(i.PKCxR(i[r(1127)],i.bdcuc))i[r(795)](_0x34479b,_0x38ff7d,10),i[r(512)](_0x2d4be6,_0x50d9f7,_0x957585);else return;if(Wo[r(531)](e))return Wo.get(e);let o=e[r(270)](/FromIndex$/,""),c=i.Xoanj(e,o),d=zx.includes(o);if(!i[r(1181)](o,(c?IDBIndex:IDBObjectStore).prototype)||!(d||Fx[r(859)](o))){if(i[r(1513)]===i[r(1513)])return;this["_initPro"+r(698)]=null}let u=async function(f,...x){let g=r,m=this[g(837)+g(346)](f,d?i[g(1463)]:i.CaXWG),S=m[g(1546)];return c&&(S=S.index(x[g(1445)]())),(await Promise[g(610)]([S[o](...x),d&&m.done]))[0]};return Wo[r(867)](e,u),u}var Fx,zx,Wo,f1=Nx({"node_modules/idb/build/index.js"(){let t=M,e={ynWpv:t(671),uPcTX:t(191),qbIRZ:t(1199),RiNJW:function(o,c){return o(c)},FFxcH:t(531),hbqBq:"getAll",awDYZ:t(173)+"ys",pckUn:"count",RohNz:function(o){return o()},iiPqK:function(o){return o()}},r="4|5|3|1|0|2"[t(1480)]("|"),i=0;for(;;){switch(r[i++]){case"0":Wo=new Map;continue;case"1":zx=[t(1108),e.ynWpv,e.uPcTX,e[t(941)]];continue;case"2":e[t(1255)](a1,o=>({...o,get:(c,d,u)=>Ox(c,d)||o[t(531)](c,d,u),has:(c,d)=>!!Ox(c,d)||o[t(198)](c,d)}));continue;case"3":Fx=[e[t(692)],t(1036),e[t(623)],e[t(1231)],e[t(913)]];continue;case"4":e[t(1611)](Dx);continue;case"5":e[t(356)](Dx);continue}break}}}),h1={idb:function(t){let e=M;t[e(872)]=Promise[e(662)]()[e(1286)](()=>(f1(),Bx)).then(function(r){return r})}},Lx={};function zt(t){let e=M,r={Aevby:e(446)+"0"},i=r[e(1293)][e(1480)]("|"),o=0;for(;;){switch(i[o++]){case"0":return c[e(872)];case"1":h1[t](c,c.exports,zt);continue;case"2":var c=Lx[t]={exports:{}};continue;case"3":if(d!==void 0)return d.exports;continue;case"4":var d=Lx[t];continue}break}}zt.d=(t,e)=>{let r=H;for(var i in e)zt.o(e,i)&&!zt.o(t,i)&&Object[r(1175)+r(215)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;zt.o=(e,r)=>Object[t(220)+"e"]["hasOwnPr"+t(215)].call(e,r)})(),(()=>{let t=M,e={uJMhK:function(r,i){return r!=i},VTJaF:t(579)+"d",vHZjw:t(780),KkDaH:t(743)+"le"};zt.r=r=>{let i=t;e[i(273)](e[i(1455)],typeof Symbol)&&Symbol[i(1605)+"Tag"]&&Object[i(1175)+"operty"](r,Symbol[i(1605)+"Tag"],{value:e[i(254)]}),Object["definePr"+i(215)](r,e[i(330)],{value:!0})}})();var De={};(()=>{let t=M,e={KHZTR:function(a,n,s){return a(n,s)},FAAan:function(a,n){return a===n},TkISp:"LimPL",bltod:function(a,n){return a(n)},HMMKR:function(a,n){return a+n},FqkQH:function(a,n){return a*n},PsUrT:function(a,n){return a(n)},hThLu:function(a,n,s){return a(n,s)},smApL:function(a,n){return a(n)},TCVCp:t(1216),ajMZu:"ffff",oLnSx:"timeout",NFzBH:t(1062),FxFZV:"message_id",urILJ:"grXyW",CfwNW:function(a,n){return a>n},JGZhX:function(a,n){return a>n},vsQnA:function(a,n){return a<n},JWKDZ:function(a,n){return a-n},EMQms:function(a,n){return a!==n},KLoSB:t(1151),BAksx:"bYlsH",UMoqq:function(a,n){return a!==n},nThXR:function(a,n){return a-n},ffiBE:function(a,n){return a===n},HnREZ:function(a,n){return a<n},BXIex:function(a,n,s){return a(n,s)},GNTQl:function(a,n,s){return a(n,s)},ipWqi:function(a,n){return a!==n},EtieZ:t(516),CtSFL:function(a,n){return a>>>n},NkbXv:function(a,n){return a(n)},rKNqs:function(a,n){return a&n},MxICv:t(1680)+"required"+t(180)+t(1391),uBdeN:function(a,n){return a!==n},giugD:t(1641),emJgD:function(a){return a()},WHfea:function(a,n){return a(n)},zLrPZ:t(1683),ljBru:function(a,n,s){return a(n,s)},KunFT:function(a,n){return a!==n},BWpxk:function(a,n){return a(n)},CGsqa:function(a,n,s){return a(n,s)},gEIgB:function(a,n,s){return a(n,s)},ccztE:function(a,n){return a!==n},QfZiU:function(a,n,s){return a(n,s)},cdDHY:function(a,n,s){return a(n,s)},eIuTF:function(a,n,s){return a(n,s)},wANFm:function(a,n){return a!==n},wzgDu:function(a,n,s){return a(n,s)},gzPlf:function(a,n,s){return a(n,s)},nqXdw:function(a,n){return a!==n},CfvVC:function(a,n){return a!==n},LSvRJ:function(a,n){return a!==n},znoVV:t(1342),wvRlw:function(a,n){return a!==n},OORXO:function(a,n,s){return a(n,s)},AaXGC:function(a,n,s){return a(n,s)},AIYca:function(a,n,s){return a(n,s)},HFTxW:function(a,n,s){return a(n,s)},WwoNS:function(a,n,s){return a(n,s)},vkIhT:function(a,n,s){return a(n,s)},IclZG:function(a,n){return a(n)},zNkbq:function(a,n,s){return a(n,s)},uGnQC:function(a,n){return a(n)},JmbwX:t(1680)+t(628)+t(180)+t(1407),DcTYb:t(1680)+"required"+t(180)+t(217),lxUYy:t(1680)+t(628)+" field: service",cHUYY:function(a,n){return a===n},HoirL:function(a,n){return a&n},pfriP:function(a,n){return a(n)},UDkMV:function(a,n,s){return a(n,s)},dIeoR:function(a,n){return a(n)},ojTtS:function(a,n,s){return a(n,s)},VIFcJ:function(a,n){return a+n},OfSLo:t(519)+t(910)+"pe: ",PwcII:function(a,n){return a>=n},WhCfh:function(a,n){return a>n},osmBr:"Skip pas"+t(1297),SQVgy:function(a,n){return a*n},SEJFQ:function(a,n){return a>n},OayDg:"Read pas"+t(1297),akRzE:function(a,n,s){return a(n,s)},FehpE:function(a,n){return a&n},OmopZ:function(a,n){return a+n},GFXZf:function(a,n){return a+n},nwqUC:function(a,n){return a&n},MfDjg:function(a,n){return a|n},hbWvb:function(a,n){return a<n},YMdRp:function(a,n){return a==n},zFMjT:function(a,n){return a&n},hzBhQ:function(a,n){return a+n},vPHZa:function(a,n){return a&n},qMXnu:function(a,n){return a|n},UzFPV:function(a,n){return a<<n},muLCa:function(a,n){return a|n},poqDj:function(a,n){return a<<n},cGRxa:function(a,n){return a&n},tPGIt:function(a,n){return a<n},VdrAE:function(a,n){return a>=n},WTCfC:function(a,n){return a<=n},ZeIzi:function(a,n){return a==n},yPqhh:function(a,n){return a&n},tmGtg:function(a,n){return a>=n},aXNSA:function(a,n){return a+n},RvBte:function(a,n){return a+n},zItID:t(763),GMuJp:function(a,n){return a&n},qzQLB:function(a,n){return a<<n},ENwkF:function(a,n){return a&n},UYWZa:function(a,n){return a&n},gFsON:function(a,n){return a<n},dxsoa:function(a,n){return a!==n},fXqUZ:t(1217),aMJva:function(a,n){return a+n},qXrlJ:function(a,n){return a>>n},LLXUA:t(1170),rjTaS:t(524),flVJx:function(a,n){return a||n},JNDSG:"ack_code",CcIPv:function(a,n){return a==n},ObPke:function(a,n){return a(n)},Piuee:function(a,n){return a instanceof n},yhhZu:t(274),fnTyN:"rxgHp",lxmsv:t(536),mHYkO:function(a,n){return a>=n},NaAfQ:function(a,n){return a<=n},slEZM:function(a,n){return a<n},RktWU:function(a,n){return a+n},qIFve:function(a,n){return a<n},esBBb:function(a,n){return a<n},LRyMi:function(a,n){return a<=n},FoJnf:function(a,n){return a+n},FnvYf:function(a,n){return a<<n},ubqmf:function(a,n){return a<n},HfpQD:function(a,n){return a&n},sJDAq:function(a,n){return a|n},BYDiC:function(a,n){return a>>n},BrmNt:function(a,n){return a|n},AcHZl:function(a,n){return a>>n},diCaY:function(a,n){return a&n},MtIIf:function(a,n){return a>>n},qtVgU:function(a,n){return a|n},ueVLl:function(a,n){return a&n},tMeVO:function(a,n){return a>>n},oaSkn:function(a,n){return a+n},PMrOG:function(a,n){return a(n)},vqMrR:function(a,n){return a(n)},SnCwl:function(a,n){return a===n},njscR:t(161),pIoJM:function(a,n,s){return a(n,s)},kzime:function(a,n,s){return a(n,s)},pftMw:function(a,n){return a||n},aVJKl:t(579)+"d",Easve:t(1685)+t(278)+"d",MYnxR:t(178),COZrl:t(521),jhyyf:function(a,n){return a<n},gvOkY:function(a,n){return a>=n},RPumX:function(a,n){return a&n},eSqza:function(a,n){return a&n},gnRMH:function(a,n){return a|n},oMOTX:function(a,n){return a&n},vrFTv:function(a,n){return a(n)},PQCjS:function(a,n){return a&n},ArnZR:"wezrA",HarmQ:t(412),RBnbo:function(a,n){return a<<n},EtZKm:function(a,n){return a&n},eOCMs:function(a,n){return a(n)},maMZR:function(a,n){return a&n},kXOSK:t(783),YCDzP:function(a,n){return a(n)},HSbDj:function(a,n){return a&n},NJSoA:function(a,n){return a<<n},sUEMV:function(a,n){return a&n},pqnXg:function(a,n){return a&n},PuSWx:function(a,n){return a!==n},BebXs:t(494),klvtf:function(a,n){return a(n)},iQaBP:function(a,n){return a&n},DOUui:function(a,n){return a&n},Hlwqu:"jSGea",UtQfq:function(a,n){return a&n},EZGzD:function(a,n){return a+n},BLPKe:function(a,n,s){return a(n,s)},Lkiqk:function(a,n){return a>>>n},bbYEi:function(a,n){return a<<n},nqEcm:"IYFMz",YScJp:function(a,n){return a>>>n},udlns:function(a,n){return a>>>n},HIrol:function(a,n){return a>>>n},SchdW:function(a,n){return a<n},Mpneo:function(a,n,s){return a(n,s)},NWxDi:function(a,n){return a!==n},fMyaC:function(a,n){return a+n},tiHGk:function(a,n){return a>>>n},PlpTo:function(a,n){return a+n},Vycrx:function(a,n){return a>>>n},WspIX:function(a,n){return a!==n},kIoeR:function(a,n){return a|n},OLogB:function(a,n){return a>>>n},ncnKW:function(a,n){return a&n},SqEmu:function(a,n){return a>>>n},oBDgK:function(a,n){return a|n},BlduS:function(a,n){return a!==n},WNabb:function(a,n){return a>>>n},zondC:function(a,n){return a>>>n},Bkcex:function(a,n){return a+n},Zmxzo:function(a,n){return a&n},VpnpH:function(a,n){return a>>>n},pylEu:function(a,n){return a(n)},GAVre:function(a,n){return a|n},cIuTx:function(a,n){return a===n},YfEHH:"VITjf",fbyJE:t(1514),UMYGG:function(a,n){return a===n},ekNYG:function(a,n){return a|n},wrCBe:function(a,n){return a<<n},jHNdT:function(a,n){return a|n},nQddd:function(a,n){return a|n},wIcmF:function(a,n){return a<<n},ltsNZ:function(a,n){return a<<n},IWmoF:function(a,n){return a<<n},TrlSP:function(a,n){return a<<n},ReGjB:function(a,n){return a<<n},jaIRc:function(a,n){return a>>>n},DYUpV:function(a,n){return a|n},nQbVi:function(a,n){return a<<n},gOtIz:function(a,n){return a&n},ZImAg:function(a,n){return a>>>n},TJscp:function(a,n){return a&n},DQZVf:function(a,n){return a(n)},Egnlh:function(a,n){return a<=n},ziLnV:function(a,n){return a+n},LDyDi:function(a,n){return a|n},SglyS:function(a,n){return a%n},owDAo:function(a,n){return a|n},mIPeo:function(a,n){return a/n},rgyyQ:function(a,n){return a+n},xFYud:function(a,n){return a*n},VWzkO:function(a,n){return a===n},ffdIQ:function(a,n){return a>>>n},MNYSX:function(a,n){return a>>>n},teXTF:function(a,n){return a&n},KxxAm:function(a,n){return a+n},eoZLA:function(a,n){return a>>>n},QAJtx:function(a,n){return a<<n},OgacS:"sIETr",bvSfs:function(a,n){return a===n},pnlfP:function(a,n){return a>>>n},fUXNP:function(a,n){return a===n},Aqmbf:function(a,n){return a>=n},NTroB:function(a,n){return a|n},qVHro:function(a,n){return a<<n},HxFDZ:function(a,n){return a&n},Apirs:function(a,n){return a&n},eNaWj:function(a,n){return a>=n},isuFX:function(a,n){return a|n},VEqtr:function(a,n){return a<<n},DjlJw:function(a,n){return a<<n},kqDcu:function(a,n){return a+n},FBjMJ:t(292),vvoXy:function(a,n){return a===n},iIRGY:function(a,n){return a+n},IWKUT:function(a,n){return a+n},CaJGW:function(a,n){return a&n},tfPKg:function(a,n){return a>>>n},ApuKX:function(a,n){return a>>>n},Rlzbh:function(a,n){return a&n},WKAyz:function(a,n){return a>>>n},dXFEb:function(a,n){return a&n},rsdAk:function(a,n){return a>>>n},rXYMH:function(a,n){return a&n},BHyXv:function(a,n){return a>>>n},ZQAzf:function(a,n){return a&n},tUCpo:function(a,n){return a>>>n},gzQrB:t(1065),gfwzK:"5|3|2|1|"+t(163),axEmN:t(1481)+t(1014),BNWPl:t(403)+t(1094)+"R",naXQE:"CONNECTI"+t(553),sLSxy:t(176)+"OR",uHtNy:t(184)+t(777),PKOrn:function(a,n){return a-n},KpBMp:function(a,n){return a>>n},ljCCe:function(a,n){return a|n},VAmzC:function(a,n){return a===n},mSwrD:t(940),OoBxH:t(1649)+t(1203),iuDWr:t(1534)+"4",drvTt:t(1027)+t(428)+"s",ablAJ:"ping_onc"+t(1150)+"t",zNgDI:function(a,n){return a!==n},LxFIB:t(179),PavoG:function(a,n){return a>=n},bIBrx:function(a,n){return a===n},qfJGF:function(a,n){return a!==n},arXHt:t(1161),ekmzo:function(a,n){return a!=n},XPLRu:function(a,n){return a instanceof n},BqAqU:t(1392)+t(1317),fhdOj:t(508),gJwlk:"gvjau",cuMvz:t(571),esRmI:function(a,n){return a+n},YCNCo:function(a,n){return a+n},UCLjy:function(a,n){return a<n},HMRtv:function(a,n){return a===n},UAmbY:function(a,n){return a&n},BTKyt:function(a,n){return a!==n},aTdmb:t(1390),NcqMr:"KRlKa",OfKWI:t(281),EeYCc:function(a,n,s){return a(n,s)},Iyrmc:t(966),bCSgm:function(a,n){return a(n)},jxicE:t(1215),zZnNr:function(a,n,s){return a(n,s)},DQJZN:function(a,n,s){return a(n,s)},xrCTp:function(a,n){return a===n},GNNFx:t(546),EvYLj:function(a,n){return a===n},RDudZ:function(a,n){return a===n},Rmxrw:t(194),lgiza:t(539),AhVLf:t(1285),NWamX:"Yiday",zeYpX:t(1495),zUSMf:function(a,n){return a+n},fyqwG:function(a,n){return a&n},orDjF:function(a,n){return a||n},FTAZc:t(1225),IYswK:t(491),JxuXb:t(769),IgyQB:t(393),zSWfk:t(949)+"3",qBMMf:t(811)+t(324)+t(329)+t(487)+"process",KrPrJ:function(a,n){return a(n)},jbukd:function(a,n){return a<n},qWhoQ:function(a,n){return a<n},FzkIh:function(a,n){return a&n},GBPPw:function(a,n){return a<n},NZkxn:function(a,n){return a<=n},Filvx:function(a,n){return a<n},bZmTG:function(a,n){return a|n},MWxzd:function(a,n){return a&n},lgDnr:function(a,n){return a&n},TcoIj:function(a,n){return a>=n},LhmOx:function(a,n){return a===n},pfxlI:t(337),ojmFr:function(a,n){return a-n},JHUzt:function(a,n){return a|n},zAMLB:function(a,n){return a|n},KgYmM:function(a,n){return a<<n},XlUEv:function(a,n){return a&n},vcRru:function(a,n){return a&n},EqLCJ:function(a,n){return a>>n},DKTLp:function(a,n){return a+n},CoqgR:function(a,n){return a&n},ElBul:function(a,n){return a<n},pOHzv:function(a,n){return a|n},lleKV:function(a,n){return a>>n},dQaRq:function(a,n){return a&n},sZJMN:function(a,n){return a===n},oxgLC:function(a,n){return a===n},dMmNm:function(a,n){return a+n},KpOoF:function(a,n){return a&n},wljio:function(a,n){return a&n},RzniR:function(a,n){return a>>n},hUENR:function(a,n){return a>>n},sqXre:function(a,n){return a&n},JIHtU:function(a,n){return a>>n},oMvOM:t(748),uFeiW:function(a,n){return a(n)},ejVZW:function(a,n,s,l){return a(n,s,l)},aXUNf:function(a,n){return a instanceof n},Mbcnc:function(a,n){return a===n},pdSif:"Lcvaz",CnFjO:function(a,n){return a!=n},MHfyL:function(a,n){return a instanceof n},TWtjb:function(a,n){return a instanceof n},ouGUb:t(296)+t(956)+t(1308),GeVtX:t(1294),NKFKO:t(1556),izmaV:function(a,n){return a===n},CmDQb:t(1470),tMryD:function(a,n){return a>=n},dQExH:t(1340),tDODz:function(a,n){return a(n)},rTXiq:t(945)+"reason",VeAKG:t(1548),HWnoI:t(321),ilGrt:t(370)+"ack=frontierJSONP",ncNjP:t(1344),Dlpea:function(a,n){return a&n},tYOQm:function(a,n){return a>>>n},FPmrL:t(793),stGmx:function(a,n){return a(n)},DlYTH:t(1338),FGHKz:function(a,n){return a(n)},MqKmF:function(a,n,s,l){return a(n,s,l)},JzCfZ:"LmUmd",eDPfw:function(a,n,s){return a(n,s)},WfArW:function(a,n){return a!==n},BkxbQ:"eWBFA",TnDBa:t(834),wZJhQ:function(a,n){return a instanceof n},wjlUs:function(a,n){return a instanceof n},HCxoV:t(1303),TBoAC:function(a,n){return a!==n},wTTiR:"wRKEp",GlRio:function(a,n){return a===n},QHZgY:t(1374),ctVGY:function(a,n){return a===n},WRjqy:t(684),xfFlU:t(1343),dHOFd:function(a,n){return a+n},wgAev:"cvCdo",ITUVk:function(a,n,s){return a(n,s)},WIbMn:"rvZFJ",boSxy:function(a,n){return a!==n},fFiPl:t(1404),jqSaE:function(a,n){return a||n},ziLrm:function(a,n){return a||n},FIuFI:t(724),HpdQY:"ZoqSd",VOkYJ:function(a,n){return a||n},FPQWf:function(a,n){return a!=n},iYmsq:t(1276),AOwfA:function(a,n,s,l){return a(n,s,l)},izgWZ:t(1098)+t(506),UjJtD:t(1098)+t(307)+"ck",JfZSe:function(a,n,s,l){return a(n,s,l)},Geudw:function(a,n,s){return a(n,s)},gNixi:t(1098)+t(591)+t(705),RHQqv:function(a,n,s,l){return a(n,s,l)},dHfcS:t(556),ePJQS:function(a,n){return a&&n},ZZKfE:function(a,n,s){return a(n,s)},FvepS:t(1018),bcEbf:t(587),kuTcO:function(a,n){return a-n},DZkfS:function(a,n){return a(n)},PRboh:function(a,n){return a(n)},sSsQn:"wckBk",QkqIq:function(a,n){return a instanceof n},owovl:"none_none",zrlDL:function(a,n){return a<n},jiKTl:function(a,n){return a>n},Axnkv:function(a,n){return a>n},SlYji:function(a,n){return a+n},AFdjF:t(605),hUQJx:function(a,n){return a(n)},thziC:function(a,n){return a+n},xetmp:function(a,n){return a|n},CtCru:function(a,n){return a(n)},ZoAAP:function(a,n){return a+n},mGjye:function(a,n){return a+n},rhFUP:t(1616),aqQos:function(a,n){return a===n},NEYIZ:function(a,n){return a+n},TrMRA:function(a,n){return a===n},Ougwj:"store",Wmypc:function(a,n){return a!==n},rlOCp:t(1299),qceEo:function(a,n){return a>n},eCGqd:function(a,n){return a!==n},EfGOW:t(1366),RFoHN:function(a,n){return a&n},hEdLQ:function(a,n){return a<n},xeRKz:function(a,n,s){return a(n,s)},PiKXT:function(a,n){return a>>>n},JnBPi:t(1187)+"1",Bwrao:function(a,n){return a+n},LxsNe:function(a,n,s,l){return a(n,s,l)},mXMtu:function(a,n){return a+n},LhOHu:function(a,n){return a<n},mvKby:function(a,n){return a|n},CpqsN:function(a,n){return a<<n},KHgFY:function(a,n){return a<<n},SJkwF:function(a,n){return a+n},vFyka:function(a,n){return a|n},UVXBj:function(a,n){return a+n},JSyAJ:function(a,n){return a+n},AptEb:function(a,n){return a>>>n},AKWXO:function(a,n){return a>>>n},uebhA:function(a,n){return a+n},BMjSx:function(a,n){return a>>>n},VVdwf:function(a,n){return a&n},ijjiN:function(a,n){return a+n},VQGwk:function(a,n){return a+n},iQpoe:function(a,n){return a&n},ZIXiA:function(a,n){return a+n},dkrhv:"6|0|5|7|"+t(1414)+t(1606)+"4",ROpoJ:function(a,n){return a<n},hpTcF:function(a,n){return a|n},POkYT:function(a,n){return a>>>n},bCKhs:function(a,n){return a<<n},qLCOX:function(a,n){return a<n},AJlya:function(a,n){return a|n},JdMVj:function(a,n){return a|n},LWQnA:function(a,n){return a&n},XQOCO:function(a,n){return a&n},LfBVP:function(a,n){return a<n},DOZha:function(a,n){return a>>>n},zOUAO:function(a,n){return a|n},ZlLvR:function(a,n){return a>n},sklEe:function(a,n){return a(n)},RZsSz:t(989)+t(1399),qOeoM:function(a,n,s,l){return a(n,s,l)},hZrsQ:t(814),BMbdK:function(a,n,s,l){return a(n,s,l)},UMBkL:t(148),IwZeO:function(a,n,s,l){return a(n,s,l)},jlkHZ:t(407)+t(1162),YOBHS:t(1162),LTvRF:t(1206),jMgeb:function(a,n){return a(n)},TmUJK:function(a,n){return a(n)},EKMMg:function(a,n,s){return a(n,s)},CNrts:function(a,n){return a+n},vSbjg:t(155)+t(1515),DCIzt:t(1157)+t(1665),JHiRC:"cursor_n"+t(1629),sukHR:t(1526)+"econnect"+t(1376),SJzYK:function(a,n){return a===n},bbgjo:t(1451),JrQyd:t(1608),zGtmO:function(a,n,s,l){return a(n,s,l)},PwQdB:"INSTANT",usyMl:t(1043),xjVJs:function(a,n,s,l){return a(n,s,l)},hoeZs:function(a){return a()},HTLSw:"setdb",sIxeU:function(a,n){return a(n)},CnIQT:function(a,n){return a===n},TTwwo:t(272),tcAyK:function(a,n){return a-n},uTOKz:function(a,n){return a||n},vCbhN:"code",UNYIH:function(a,n,s){return a(n,s)},fgBga:t(1098)+t(1695),tmmQG:function(a,n){return a(n)},acwwG:function(a,n,s){return a(n,s)},qyzHO:t(1098)+"er_ttl",PvddU:t(1410)+"s",mbgPI:function(a,n,s){return a(n,s)},SjorT:"x-msg-cursor_name",EECJv:t(639)+t(1568)+"ue",YRAFX:function(a,n){return a===n},UWGEN:t(1686),pjFyr:t(625),OrJjy:function(a){return a()},jQqke:t(425),kmwry:function(a,n){return a<n},beIKm:function(a){return a()},azSAe:function(a){return a()},PMCev:function(a,n){return a&n},PIDLG:function(a,n){return a<<n},VoOdx:function(a,n){return a&n},XtjgJ:function(a,n){return a<<n},bqcjU:function(a,n){return a&n},aRHRm:function(a,n){return a&n},qdvic:function(a,n){return a===n},OhpKN:function(a){return a()},QUwAB:t(408),VQIVM:function(a,n){return a(n)},geMbc:function(a){return a()},FpqQm:function(a,n){return a!==n},JJImh:t(1640),hdmJk:"eIApk",Ehiwj:function(a,n,s){return a(n,s)},AAFIW:function(a,n){return a!==n},XOpzK:"bye",zJKYK:function(a,n){return a(n)},WppUS:function(a,n,s){return a(n,s)},lUGLJ:function(a,n,s){return a(n,s)},HemOG:function(a,n){return a!==n},yCNLQ:function(a,n){return a<<n},DNMMx:"xqiDX",zhPjl:t(1598),Jcuwh:function(a,n){return a===n},JkvUc:t(1214)+t(828),Ssioo:t(1001),OUMWz:function(a,n){return a/n},zJXDQ:function(a,n){return a===n},RWWZU:"please p"+t(311)+t(1521)+t(889)+t(765)+t(1054)+t(388)+t(1657),OcfjX:t(535),PEosp:function(a,n,s){return a(n,s)},hmDtO:t(688)+t(247)+" reconnect",FeCut:"pageshow",GuCYa:t(1325),bAXvk:t(1281),ENfre:t(1073),Rhwde:function(a,n){return a(n)},ISkJI:function(a,n){return a|n},zdzGs:function(a,n){return a<<n},lOZME:function(a,n){return a<<n},xrLmK:function(a,n){return a<<n},ZMGBF:function(a,n){return a===n},ohlSB:"rLutN",jnfOv:t(1625),CHMXA:"FTUuO",EGndg:t(1354),MFKOU:t(290),CnLKx:t(1319),SkwCB:t(1080),QDIId:t(259),uQBuZ:"device_id",ouAKm:"please p"+t(824)+t(486)+t(1323)+t(809),JOLfr:t(1e3),KpRwz:function(a,n,s){return a(n,s)},rLVOj:t(638)+"0",dLACB:t(1242)+"t",xoPVH:function(a,n){return a-n},yFfjV:function(a,n,s){return a(n,s)},cWbRN:function(a,n){return a!==n},AQjaH:t(877),FntjX:function(a,n){return a(n)},HTEkp:t(1442)+">",rCMhv:function(a,n){return a===n},NGWMh:t(1219),KoiCr:t(703),mOqaI:function(a,n){return a*n},IYDjF:function(a,n){return a>n},lkRSh:function(a,n,s){return a(n,s)},XIxnD:"jThdp",NINES:t(740)+t(937)+t(1242)+t(1522)+"ver",siwsT:"timeout, try reconnecting",Eviaz:function(a,n){return a===n},qXquB:t(1542),fRzcz:"0|3|2|1|4",ufMwp:t(1184),Lrzuv:function(a,n){return a!==n},fhcKE:t(174),rlBnY:t(740)+t(1357)+t(1099)+t(807),cwTQO:t(477),yeklR:function(a,n){return a<n},Oimst:function(a,n){return a===n},zUAMD:t(1660),cHmoK:function(a,n){return a*n},mAwnD:function(a,n){return a-n},paYQp:function(a,n){return a>n},zLusj:"DNHEq",Ihcza:function(a,n){return a>>>n},XLyiq:function(a,n){return a===n},NbYkg:t(1291),gIHwg:t(722),kVLmb:t(634),mzmeM:t(499)+t(1547)+t(686)+t(860)+"ed",xerXK:function(a,n){return a===n},kzdQy:t(499)+t(570)+t(1279),XcYas:t(1156)+t(1287)+t(641)+t(1038)+"a must be a stri"+t(584)+t(931)+t(421),MBLoh:t(1545),UyilZ:function(a,n){return a instanceof n},OtmFI:function(a,n){return a instanceof n},jrZUl:function(a,n){return a(n)},gMBBK:function(a,n){return a(n)},KNldr:t(1156)+"rovide a valid s"+t(1399),uquvE:function(a,n){return a instanceof n},GOZdR:function(a,n){return a(n)},OvCib:"sent",WJMPY:function(a,n){return a<n},PAwsz:t(813),SxxVh:function(a,n){return a||n},gRulB:function(a,n){return a==n},xGkhR:function(a,n){return a(n)},asmZK:function(a,n){return a!==n},cAISt:t(1519),LDYZN:t(1013),pJzUe:function(a,n){return a+n},PyPpc:function(a,n){return a&n},dzhOP:function(a,n){return a|n},sxCey:function(a,n){return a<n},JEzIl:function(a,n){return a===n},ktouy:t(685),wAhSM:function(a,n){return a(n)},TqnPk:t(655),lfDWk:t(1256),JGLyQ:function(a,n){return a===n},xGVBO:t(801),raKCb:function(a,n){return a===n},nCiaH:t(385),HxpeH:t(1507)+t(1554)+t(488)+"pe",pqWGB:function(a,n){return a===n},AIxLp:function(a,n){return a===n},cFEvx:function(a,n){return a===n},UbLby:t(1307)+"rkerGlob"+t(1298),oBuEn:function(a,n){return a!=n},tpYrA:function(a,n){return a!=n},kjjlG:function(a,n){return a===n},DMBbK:function(a,n){return a!=n}};zt.r(De),zt.d(De,{FWS:()=>Ig,CustomErrorEvent:()=>il,createCloseEvent:()=>mt,ReconnectEvent:()=>rl,createErrorEvent:()=>lt,decodedFrame:()=>nn,createOpenEvent:()=>ll,CustomCloseEvent:()=>sl,createReconnectEvent:()=>fa,FrontierMessageEvent:()=>al,encodeFrame:()=>qt,createMessageEvent:()=>dl,OpenEvent:()=>cl,ErrorCode:()=>sn,Event:()=>nr,MessageEvent:()=>ol});let r="";function i(a=""){let n=t;if(e[n(1553)]("LimPL",e[n(577)])){let l=""+Date[n(1489)](),h=r||(r=e.bltod(f,a)),p=Math[n(637)]()[n(1605)](16)[n(1144)](-6);return e[n(547)](e.HMMKR(e[n(547)]("02",l),h),p)}else return _0x307895.bytes[e.KHZTR(_0x487b8c,_0x2b4067,1)]}function o(){let a=t;return e.HMMKR(1e4*Date[a(1489)](),Math.floor(e[a(979)](1e4,Math[a(637)]())))}function c(a){let n=t;return(e[n(582)](Array,8)[n(847)]("0")+e[n(1113)](parseInt,a,10)[n(1605)](2))[n(1144)](-8)}function d(a){let n=t;return e[n(547)](e[n(582)](Array,4)[n(847)]("0"),e.KHZTR(parseInt,a,2)[n(1605)](16))[n(1144)](-4)}function u(a){let n=t,s=a[n(1480)](/\./)[n(1250)](p=>c(p)),l=[];return l[0]=e.smApL(d,s[0]+s[1]),l[1]=e[n(185)](d,s[2]+s[3]),[n(1216),"0000",e[n(600)],n(1216),"0000",e.ajMZu,l[0],l[1]][n(847)]("")}function f(a){let n=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(1476)](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(1476)](a);return s?e[n(582)](u,a):l?x(a):n(1314)+n(1314)+n(1314)+n(1314)}function x(a){let n=t,s={iANhC:n(1027)+n(1150)+"t",MMfmq:e[n(1295)],skaUc:function(l,h,p){return l(h,p)},rZTQQ:e.NFzBH,qBzyo:e[n(1183)]};if(e.urILJ===e[n(473)]){let l="",h=[],p=0,_=0,v=!0,w=n(1216);if(e[n(348)](a[n(1416)]("::"),-1)){let C=a[n(1480)]("::");for(let L=0;L<C[n(721)];L++){let j=C[L];if(e[n(1402)](j[n(1416)](":"),0)){let z=j[n(1480)](":");v&&(p=z.length),_+=z[n(721)];for(let G=0;e[n(1133)](G,z.length);G++)if(z[G][n(721)]!==4){let fe=w[n(1240)+"g"](0,e[n(415)](4,z[G].length)),ie=fe.concat(z[G]);h[n(1475)](ie)}else h[n(1475)](z[G]);v=!1}else if(e[n(676)](e[n(1384)],e[n(1584)])){if(e[n(1684)](4,j.length)){let z=w[n(1240)+"g"](0,e[n(415)](4,j[n(721)])),G=z.concat(j);h[n(1475)](G)}else h.push(j);v&&(p+=1),_+=1,v=!1}else this[n(1622)+"sCounter"]?.addCount(),this.emit(s[n(1326)],s[n(794)]),this[n(1622)+n(1090)]?.[n(1229)+n(1532)+"nt"]()?this["_handleR"+n(1656)]():this._ping()}let N="";for(let L=0;L<e[n(1675)](8,_);L++)N=N[n(1368)](w);for(let L=0;e[n(1133)](L,h[n(721)]);L++)e[n(1364)](L,p)&&(l=l[n(1368)](N)),l=l[n(1368)](h[L]);return l}{let C=a[n(1480)](":");for(let N=0;e[n(953)](N,C[n(721)]);N++){let L=C[N];if(C[N][n(721)]!==4){let j=w[n(1240)+"g"](0,e[n(1675)](4,C[N].length)),z=j[n(1368)](L);l=l.concat(z)}else l=l[n(1368)](L)}return l}}else this._intervalTimeoutId=null,this[n(404)+"l"]=36e5,this[n(1129)]=s[n(713)](_0x38a850,s[n(357)],s[n(875)])}function g(a,n){let s=t,l=a[s(1254)];e[s(676)](void 0,l)&&(e.BXIex(we,n,10),e[s(1113)](q,n,l));let h=a[s(1391)];h!==void 0&&(e[s(1637)](we,n,18),q(n,h))}function m(a){let n=t;if(e[n(1552)](n(1431),e[n(1464)])){let s={};e:for(;!e.PsUrT(J,a);){let l=me(a);switch(e[n(886)](l,3)){case 0:break e;case 1:s.key=e[n(632)](P,a,e[n(305)](me,a));break;case 2:s[n(1391)]=P(a,e[n(426)](me,a));break;default:T(a,e[n(1322)](7,l))}}if(e[n(1364)](void 0,s.key))throw new Error(n(1680)+n(628)+" field: key");if(e.ffiBE(void 0,s[n(1391)]))throw new Error(e[n(1222)]);return s}else return _0x287213[n(429)]||_0x231aec.errNo?(n(675)+" "+(_0x33fd41.errMsg||"")+n(720)+(_0xf99bb0[n(983)]||""))[n(413)]():_0x3dbdd8.stringify(_0x244975)}function S(a){let n=t;if(e[n(1336)](n(369),e[n(802)])){let s=e[n(1002)](R);return e[n(1113)](y,a,s),e.WHfea(B,s)}else{let s=(n(683)+"3")[n(1480)]("|"),l=0;for(;;){switch(s[l++]){case"0":this._isInit=!0;continue;case"1":this[n(778)+n(530)]?.["resetEnd"+n(644)+n(1512)]();continue;case"2":this[n(717)+n(1673)]=!1;continue;case"3":this[n(823)]();continue;case"4":this["_pingLos"+n(1090)]?.[n(1369)+n(196)]();continue}break}}}function y(a,n){let s=t,l={WrOHQ:function(ie,wt){return e[H(582)](ie,wt)},YuWcY:function(ie){return e[H(1002)](ie)}},h=a.SeqID;e[s(1684)](void 0,h)&&(we(n,8),gt(n,h));let p=a[s(217)];p!==void 0&&(we(n,16),gt(n,p));let _=a[s(148)];if(e[s(1336)](void 0,_))if(e[s(1553)](e[s(1516)],e.zLrPZ))we(n,24),e.ljBru(gt,n,D(_));else return s(433)+"_"+this._DBName;let v=a[s(1676)];e.KunFT(void 0,v)&&(we(n,32),gt(n,e[s(1168)](D,v)));let w=a[s(1635)];if(e[s(445)](void 0,w))for(let ie of w){e[s(1692)](we,n,42);let wt=e[s(1002)](R);e[s(480)](g,ie,wt),e[s(1339)](we,n,wt[s(1473)]),e[s(480)]($,n,wt),O(wt)}let C=a[s(1576)+s(1245)];e[s(500)](void 0,C)&&(e[s(1574)](we,n,50),e[s(1092)](q,n,C));let N=a[s(999)+"ype"];e[s(445)](void 0,N)&&(we(n,58),e[s(957)](q,n,N));let L=a[s(955)];e[s(619)](void 0,L)&&(we(n,66),e[s(879)](we,n,L[s(721)]),e[s(422)](ae,n,L));let j=a.LogIDNew;e.nqXdw(void 0,j)&&(we(n,74),e[s(957)](q,n,j));let z=a[s(596)+s(702)];e[s(1401)](void 0,z)&&(e[s(850)](e[s(1419)],s(1342))?(this[s(1022)]=!1,l.WrOHQ(_0x27c8c2,this[s(823)+s(1312)+s(379)]),l[s(653)](_0x1b3a90)):(e[s(957)](we,n,82),q(n,z)));let G=a[s(581)];e[s(1493)](void 0,G)&&(e[s(786)](we,n,90),e[s(170)](q,n,G));let fe=a.frameType;e[s(850)](void 0,fe)&&(we(n,96),e.GNTQl(gt,n,e[s(1168)](D,fe)))}function b(a){return e[t(582)](I,F(a))}function I(a){let n=t,s={};e:for(;!e[n(185)](J,a);){let l=e.PsUrT(me,a);switch(e[n(886)](l,3)){case 0:break e;case 1:s.SeqID=e[n(855)](At,a,!0);break;case 2:s[n(217)]=e.HFTxW(At,a,!0);break;case 3:s.service=e[n(426)](me,a);break;case 4:s[n(1676)]=e[n(426)](me,a);break;case 5:{let h=e[n(1168)](A,a);(s[n(1635)]||(s.headers=[]))[n(1475)](e[n(426)](m,a)),a[n(1473)]=h;break}case 6:s["payloadE"+n(1245)]=e[n(544)](P,a,me(a));break;case 7:s[n(999)+n(572)]=P(a,e[n(185)](me,a));break;case 8:s[n(955)]=e[n(1113)](oe,a,me(a));break;case 9:s[n(345)]=e[n(200)](P,a,e[n(232)](me,a));break;case 10:s[n(596)+n(702)]=P(a,e[n(1672)](me,a));break;case 11:s[n(581)]=e.zNkbq(P,a,me(a));break;case 12:s[n(1253)+"e"]=e[n(347)](me,a);break;default:e.gEIgB(T,a,e[n(1322)](7,l))}}if(e.FAAan(void 0,s[n(1407)]))throw new Error(e[n(848)]);if(e.ffiBE(void 0,s[n(217)]))throw new Error(e[n(371)]);if(e[n(1364)](void 0,s[n(148)]))throw new Error(e.lxUYy);if(e.cHUYY(void 0,s[n(1676)]))throw new Error(n(1680)+"required"+n(180)+"method");return s}function A(a){let n=t,s=me(a),l=a[n(1473)];return a.limit=e[n(547)](a[n(1061)],s),l}function T(a,n){let s=t;switch(n){case 0:for(;e.HoirL(128,e[s(629)](te,a)););break;case 2:e[s(1086)](Z,a,e.dIeoR(me,a));break;case 5:e[s(480)](Z,a,4);break;case 1:e[s(646)](Z,a,8);break;default:throw new Error(e[s(1096)](e.OfSLo,n))}}function D(a){let n=t;return a|=0,{low:a,high:a>>31,unsigned:e[n(682)](a,0)}}let E=[];function R(){let a=t,n=E[a(1617)]();return n?(n[a(1061)]=n[a(1473)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){E[t(1475)](a)}function F(a){return{bytes:a,offset:0,limit:a[t(721)]}}function B(a){let n=t,s=a[n(260)],l=a[n(1473)];return e.ffiBE(s[n(721)],l)?s:s[n(390)](0,l)}function Z(a,n){let s=t;if(e[s(391)](e.HMMKR(a.offset,n),a[s(1473)]))throw new Error(e[s(932)]);a[s(1061)]+=n}function J(a){let n=t;return e.PwcII(a.offset,a[n(1473)])}function re(a,n){let s=t,l=a[s(260)],h=a[s(1061)],p=a[s(1473)],_=e.HMMKR(h,n);if(_>l[s(721)]){let v=new Uint8Array(e[s(420)](2,_));v[s(867)](l),a[s(260)]=v}return a[s(1061)]=_,e[s(458)](_,p)&&(a.limit=_),h}function X(a,n){let s=t,l=a[s(1061)];if(e[s(547)](l,n)>a[s(1473)])throw new Error(e[s(461)]);return a[s(1061)]+=n,l}function oe(a,n){let s=t,l=X(a,n);return a[s(260)][s(390)](l,l+n)}function ae(a,n){let s=t,l=e.akRzE(re,a,n[s(721)]);a[s(260)][s(867)](n,l)}function P(a,n){let s=t,l=e[s(1274)](X,a,n),h=String[s(464)+s(1503)],p=a[s(260)],_="\uFFFD",v="";for(let w=0;w<n;w++){let C=p[e.VIFcJ(w,l)],N,L,j,z;if(e[s(285)](e[s(1322)](128,C),0))v+=h(C);else if(e.FAAan(e[s(457)](224,C),192))e[s(682)](e[s(805)](w,1),n)?v+=_:(N=p[e.GFXZf(e[s(547)](w,l),1)],e[s(978)](192,N)!==128?v+=_:(z=e.MfDjg(e[s(1272)](31,C)<<6,e[s(978)](63,N)),e[s(1387)](z,128)?v+=_:(v+=h(z),w++)));else if(e[s(1454)](e[s(954)](240,C),224))e[s(682)](e[s(768)](w,2),n)?v+=_:(N=p[e[s(560)](w,l)+1],L=p[w+l+2],e[s(959)](e[s(1571)](N,e[s(158)](L,8)),49344)!==32896?v+=_:(z=e[s(340)](e[s(1227)](e[s(534)](15,C),12),(63&N)<<6)|e.nwqUC(63,L),e[s(597)](z,2048)||e.VdrAE(z,55296)&&e[s(700)](z,57343)?v+=_:(v+=h(z),w+=2)));else if(e.ZeIzi(e[s(997)](248,C),240))if(e[s(149)](w+3,n))v+=_;else if(N=p[e[s(1096)](e.aXNSA(w,l),1)],L=p[e.OmopZ(e[s(1226)](w,l),2)],j=p[e[s(1226)](w+l,3)],e[s(619)](e[s(457)](e.qMXnu(N,L<<8)|e[s(1227)](j,16),12632256),8421504))v+=_;else if(e[s(1488)]==="MYTiZ")_0x38ab4d[s(867)](_0x45132b,_0x77018d);else if(z=e[s(340)](e[s(770)](7,C)<<18|e.rKNqs(63,N)<<12,e[s(1088)](e[s(636)](63,L),6))|e[s(302)](63,j),e[s(1578)](z,65536)||e[s(391)](z,1114111))v+=_;else if(e[s(1007)](e[s(849)],s(440)))z-=65536,v+=e.eIuTF(h,e[s(1428)](e[s(624)](z,10),55296),e[s(1226)](e[s(1272)](1023,z),56320)),w+=3;else{let G=this._endpointManager?.[s(244)+"ntEndpoint"]();this._debug(s(335)+G),e.emJgD(_0x153c18)}else v+=_}return v}function q(a,n){let s=t,l={YrtrY:function(h,p){return e.CcIPv(h,p)},UQGRB:function(h,p){return e[H(707)](h,p)},BtOIz:function(h,p){return e.Piuee(h,p)}};if(e[s(500)](e[s(1400)],"uKXbg")){let{SeqID:h,LogID:p,service:_,LogIDNew:v,method:w}=_0x4e81ea[s(1215)];this[s(1049)]({SeqID:h,LogID:p,LogIDNew:v,service:_,method:w,headers:[{key:e[s(842)],value:"1"},{key:e[s(1638)],value:e.flVJx(v,"")},{key:e[s(1352)],value:"0"}]})}else{let h=n[s(721)],p=0;for(let w=0;w<h;w++)if(e[s(285)](e[s(1356)],e[s(753)])){if(l[s(205)](s(748),typeof _0x2d1d96)){let C=new _0x2cf1cc(l.UQGRB(_0xbc5bf,_0x39825b));return _0x222207(_0x38c107,C,0),C}return l[s(569)](_0xa13588,_0xef79f4)?new _0x503939(_0x5e40d5):new _0x331fea(_0x4ced73[s(1081)],_0x150c41[s(1035)+"et"],_0x5bb8b0[s(1651)+"th"])}else{let C=n[s(269)+"At"](w);e.mHYkO(C,55296)&&e[s(256)](C,56319)&&e.slEZM(e[s(1428)](w,1),h)&&(C=e[s(782)](e[s(1088)](C,10),n[s(269)+"At"](++w))-56613888),p+=C<128?1:e[s(1224)](C,2048)?2:C<65536?3:4}e[s(170)](we,a,p);let _=e[s(786)](re,a,p),v=a[s(260)];for(let w=0;e[s(1594)](w,h);w++){let C=n[s(269)+"At"](w);e[s(682)](C,55296)&&e[s(1477)](C,56319)&&e[s(1530)](w,1)<h&&(C=e.JWKDZ(e[s(1428)](e[s(338)](C,10),n[s(269)+"At"](++w)),56613888)),e.vsQnA(C,128)?v[_++]=C:(e[s(1623)](C,2048)?v[_++]=e[s(1681)](e[s(624)](C,6),31)|192:(e[s(1594)](C,65536)?v[_++]=e.sJDAq(e[s(310)](C,12)&15,224):(v[_++]=e[s(297)](e.UYWZa(e[s(1173)](C,18),7),240),v[_++]=e.qMXnu(e[s(175)](e.MtIIf(C,12),63),128)),v[_++]=e.qtVgU(e.ueVLl(e[s(353)](C,6),63),128)),v[_++]=e[s(1636)](63&C,128))}}}function $(a,n){let s=t,l=e[s(1274)](re,a,n.limit),h=a[s(260)],p=n[s(260)];for(let _=0,v=n.limit;e.esBBb(_,v);_++)h[e[s(673)](_,l)]=p[_]}function te(a){let n=t;if(e[n(1562)](e[n(1148)],n(604)))e[n(1124)](_0x3414ca,this[n(1396)+n(238)+"Id"]),e[n(766)](_0x1fd609,this[n(389)+n(1607)+n(267)]),this[n(1396)+n(238)+"Id"]=null,this[n(389)+n(1607)+n(267)]=null;else return a[n(260)][e.pIoJM(X,a,1)]}function et(a,n){let s=t,l=e.kzime(re,a,1);a[s(260)][l]=n}function me(a){let n=t,s={ZFZIn:function(_,v){return e[H(664)](_,v)},agyOb:function(_,v){return _!=v},AuOFN:e[n(666)],pVKDV:function(_,v){return e[n(906)](_,v)},vwTsH:e[n(693)]},l=0,h=0,p;do if(e.MYnxR===e[n(1130)]){if(s[n(1462)](_0x7af527,_0x2c84a6))return new _0x5ac317(_0x5b4fac,_0x29e191);if(s.ZFZIn(_0x52233a,_0x37a206)&&s[n(1048)](s[n(575)],typeof _0x193ff3))return new _0x14242d(_0x571279,_0xb35422);if(s[n(996)](_0x3d17d7,_0xe8c78)&&s[n(575)]!=typeof _0xab2153)return new _0x3e8e9f(_0x1de0a0,_0x126833);throw new _0x208187(s[n(1277)])}else p=e[n(629)](te,a),e[n(525)](l,32)&&(h|=e[n(1088)](e[n(636)](127,p),l)),l+=7;while(e.FehpE(128,p));return h}function we(a,n){let s=t;for(n>>>=0;e[s(576)](n,128);)e[s(1637)](et,a,e.MfDjg(e[s(1328)](127,n),128)),n>>>=7;e[s(422)](et,a,n)}function At(a,n){let s=t,l={Vtafa:function(w,C){return e[H(1224)](w,C)},HUeQE:function(w,C){return w|C},QXaug:function(w,C){return w&C},ZDttt:function(w,C){return e[H(1224)](w,C)},AYLJS:function(w,C){return e.eSqza(w,C)},NJdSL:function(w,C){return e.MtIIf(w,C)},sRelJ:function(w,C){return e[H(827)](w,C)},Flxgd:function(w,C){return e[H(1421)](w,C)},NpBkv:function(w,C){return e[H(1272)](w,C)},OIijX:function(w,C,N){return e.vkIhT(w,C,N)},WWxEE:s(571)},h=0,p=0,_=0,v;if(v=e.vrFTv(te,a),h=e[s(1300)](127,v),e[s(636)](128,v))if(e[s(1139)]!==e[s(1104)]){if(v=e[s(707)](te,a),h|=e[s(1346)](e[s(1421)](127,v),7),128&v&&(v=e[s(1168)](te,a),h|=e[s(1227)](e[s(534)](127,v),14),e.EtZKm(128,v)&&(v=e[s(471)](te,a),h|=e[s(338)](e[s(1559)](127,v),21),e.ueVLl(128,v)))){if(e.ccztE(e[s(439)],e[s(439)]))e[s(283)](_0x851883,_0x38ccfa,24),e[s(1092)](_0xdf3e53,_0x123028,_0x3461f3(_0x115420));else if(v=e.YCDzP(te,a),p=e.HSbDj(127,v),128&v&&(v=e[s(1672)](te,a),p|=e.NJSoA(e[s(882)](127,v),7),128&v&&(v=e[s(964)](te,a),p|=e.pqnXg(127,v)<<14,128&v))){if(e[s(969)](e[s(468)],e[s(468)]))BYFhlz[s(263)](_0x3ed5bd,2048)?_0x332c3f[_0x4f225a++]=BYFhlz[s(562)](BYFhlz[s(687)](_0x599f3c>>6,31),192):(BYFhlz[s(1182)](_0x5d73ba,65536)?_0x5883d[_0x30ba7a++]=BYFhlz[s(349)](BYFhlz[s(1134)](_0x5e1e82,12),15)|224:(_0x4da0fd[_0x18ea9c++]=BYFhlz[s(648)](BYFhlz.QXaug(BYFhlz.NJdSL(_0x26bd27,18),7),240),_0x2d5d48[_0x1a1848++]=BYFhlz[s(1643)](BYFhlz[s(1134)](_0x1cedf2,12),63)|128),_0x5918a8[_0x231159++]=BYFhlz[s(349)](BYFhlz[s(1134)](_0x307fef,6),63)|128),_0x542524[_0x21a975++]=BYFhlz[s(648)](BYFhlz[s(1039)](63,_0x41802a),128);else if(v=e.PsUrT(te,a),p|=(127&v)<<21,e[s(175)](128,v)&&(v=e.klvtf(te,a),_=e[s(985)](127,v),e[s(165)](128,v)))if(e[s(1553)](e[s(1142)],e[s(1142)]))v=e[s(426)](te,a),_|=e[s(496)](127,v)<<7;else return this[s(1129)][s(1527)+s(1204)]()}}}else{let w=l[s(523)](_0x76301f,l[s(427)],{message:_0x5806e0.message,code:_0x251424[s(1481)+s(1014)],error:_0x20beba});this["_dispatc"+s(1659)+s(972)](w)}return{low:h|e[s(338)](p,28),high:e[s(1571)](e[s(886)](p,4),e[s(158)](_,24)),unsigned:n}}function gt(a,n){let s=t;if(e[s(445)](e.nqEcm,"klEmH")){let l=e.YScJp(n.low,0),h=e[s(1306)](e.muLCa(e.Lkiqk(n.low,28),e[s(1677)](n.high,4)),0),p=e.HIrol(n[s(1564)],24),_=e[s(1562)](0,p)?e.cHUYY(0,h)?e[s(953)](l,16384)?e.hbWvb(l,128)?1:2:e[s(1055)](l,2097152)?3:4:e.vsQnA(h,16384)?e[s(1055)](h,128)?5:6:h<2097152?7:8:e[s(689)](p,128)?9:10,v=e[s(286)](re,a,_),w=a[s(260)];switch(_){case 10:w[e[s(1530)](v,9)]=e[s(165)](p>>>7,1);case 9:w[e[s(768)](v,8)]=e[s(306)](9,_)?128|p:e.HSbDj(127,p);case 8:w[e[s(1585)](v,7)]=_!==8?e[s(1597)](e[s(1140)](h,21),128):e[s(1559)](h>>>21,127);case 7:w[e[s(358)](v,6)]=e[s(1336)](7,_)?e[s(1207)](e.YScJp(h,14),128):e[s(1328)](e.Vycrx(h,14),127);case 6:w[e[s(1428)](v,5)]=e.WspIX(6,_)?e[s(640)](e[s(820)](h,7),128):e.ncnKW(e[s(1348)](h,7),127);case 5:w[e[s(358)](v,4)]=e.ipWqi(5,_)?e[s(846)](128,h):e[s(1272)](127,h);case 4:w[e[s(277)](v,3)]=_!==4?e[s(728)](l,21)|128:e.HoirL(l>>>21,127);case 3:w[e[s(1530)](v,2)]=e[s(222)](3,_)?e.kIoeR(e[s(840)](l,14),128):e[s(1097)](e[s(1164)](l,14),127);case 2:w[e[s(303)](v,1)]=_!==2?e[s(1207)](e[s(1140)](l,7),128):e[s(611)](e.VpnpH(l,7),127);case 1:w[v]=_!==1?128|l:e[s(1421)](127,l)}}else{let l=0,h=_0x5748c7,p=e[s(1166)](_0xe2f5d8,4);for(;h<p;){let{value:_,offset:v}=e[s(326)](_0x4f7850,_0x471a05,h);h=v,l=e[s(816)](e[s(808)](l,8),0),l+=_}return{value:l,offset:p}}}function nn(a){return e[t(707)](b,a)}function qt(a){return e[t(1165)](S,a)}let rn=65536,Yr=e[t(1436)],Ee=e[t(1056)](rn,rn),Te=Ee*Ee,tr=e[t(881)](Te,2),Ne=String[t(220)+"e"][t(269)+"At"];class xe{constructor(n,s,l){let h=t;this[h(1669)]=!0,this[h(1327)]=e[h(1571)](0,n),this[h(1564)]=e[h(304)](0,s),this[h(533)]=!!l}static[t(1669)](n){let s=t;if(e[s(903)](e[s(378)],e[s(1087)]))this[s(404)+s(710)]();else return n&&e[s(1614)](!0,n[s(1669)])}static fromBits(n,s,l){return new xe(n,s,l)}static[t(1697)+"s"](n,s,l){let h=t;return l?xe["fromByte"+h(455)](n,s):xe["fromByte"+h(548)](n,s)}static[t(1697)+t(455)](n,s){let l=t;return new xe(e[l(810)](e[l(1636)](n[0]|n[1]<<8,n[2]<<16),e[l(1191)](n[3],24)),e.jHNdT(e[l(1664)](n[4],e[l(1468)](n[5],8)),n[6]<<16)|e.ltsNZ(n[7],24),s)}static[t(1697)+t(548)](n,s){let l=t;return new xe(e[l(340)](n[4]<<24|e[l(749)](n[5],16)|n[6]<<8,n[7]),e[l(1118)](e[l(1118)](e[l(868)](n[0],24),e.qzQLB(n[1],16)),e[l(861)](n[2],8))|n[3],s)}static fromHash(n){let s=t;return e[s(1364)](n,Yr)?nl:new xe(e.BrmNt(e[s(304)](Ne[s(1363)](n,0),e[s(1468)](Ne.call(n,1),8))|e[s(868)](Ne[s(1363)](n,2),16),e[s(189)](Ne[s(1363)](n,3),24))>>>0,e[s(1393)](e[s(640)](e.BrmNt(e[s(1378)](Ne[s(1363)](n,4),e[s(868)](Ne.call(n,5),8)),e.nQbVi(Ne.call(n,6),16)),Ne[s(1363)](n,7)<<24),0),!0)}[t(1674)](){let n=t;return String[n(464)+"Code"](255&this[n(1327)],e[n(1272)](e[n(1164)](this[n(1327)],8),255),e[n(188)](this[n(1327)]>>>16,255),e.ZImAg(this.low,24),e[n(959)](255,this[n(1564)]),e[n(1604)](this[n(1564)]>>>8,255),e[n(636)](e[n(1348)](this[n(1564)],16),255),e[n(1306)](this[n(1564)],24))}static[t(1543)+"er"](n,s=!0){let l=t;if(e[l(1071)](isNaN,n))return s?Bp:nl;if(s){if(e[l(682)](n,Te))return zp}else{if(e.Egnlh(n,-tr))return Up;if(e[l(804)](e[l(1247)](n,1),tr))return Fp}return xe[l(514)](e.LDyDi(e[l(935)](n,Ee),0),e[l(435)](e.mIPeo(n,Ee),0),s)}toNumber(){let n=t;return this[n(533)]?e[n(1226)](e.SQVgy(e.tiHGk(this[n(1564)],0),Ee),this[n(1327)]>>>0):e.rgyyQ(e.xFYud(this[n(1564)],Ee),e[n(816)](this[n(1327)],0))}isZero(){let n=t;return e[n(285)](0,this[n(1564)])&&e[n(1456)](0,this[n(1327)])}[t(671)](n){let s=t;xe.isLong(n)||(n=xe[s(1543)+"er"](n));let l=e[s(1362)](this.high,16),h=65535&this[s(1564)],p=e.MNYSX(this[s(1327)],16),_=65535&this.low,v=e[s(816)](n[s(1564)],16),w=e[s(1230)](65535,n.high),C=n.low>>>16,N=65535&n[s(1327)],L=0,j=0,z=0,G=0;return G+=e[s(782)](_,N),z+=e[s(733)](G,16),G&=65535,z+=e[s(603)](p,C),j+=z>>>16,z&=65535,j+=e.EZGzD(h,w),L+=e.eoZLA(j,16),j&=65535,L+=e[s(547)](l,v),L&=65535,xe[s(514)](e[s(846)](e[s(1677)](z,16),G),e[s(621)](L,16)|j,this.unsigned)}[t(1537)](n){let s=t,l={WETKd:s(1184)};if(e[s(445)](e[s(1200)],e[s(1200)]))this.emit(l[s(1271)],_0x11a011),this.onopen&&this.onopen(_0x36184a);else return xe[s(1669)](n)||(n=xe.fromNumber(n)),e[s(619)](this.unsigned,n.unsigned)&&e.bvSfs(this[s(1564)]>>>31,1)&&e[s(285)](e.pnlfP(n[s(1564)],31),1)?!1:e[s(1238)](this.high,n[s(1564)])&&this[s(1327)]===n.low}addOne(){let n=t;if(e[n(285)](n(599),e[n(878)])){let s=_0x3332b0[_0x44e79f++];if(e.WTCfC(s,127))_0x17be62+=_0x4a15ff[n(464)+n(1503)](s);else if(e[n(1448)](s,192)&&e[n(597)](s,224))_0x52998d+=_0x1f32bd["fromChar"+n(1503)](e.NTroB(e.qVHro(e[n(165)](31,s),6),e.ncnKW(63,_0x23147a[_0x290904++])));else if(s>=224&&s<240)_0x4f366e+=_0x36532b[n(464)+n(1503)](e[n(1636)](e[n(397)](15,s)<<12|e.poqDj(e.cGRxa(63,_0x4e9518[_0x32b2a7++]),6),e[n(1091)](63,_0x2b4857[_0x4dba87++])));else if(e[n(414)](s,240)){let l=(e[n(640)](e[n(262)](e[n(615)](e[n(1604)](7,s),18),e.DjlJw(e[n(534)](63,_0x5a5fa9[_0x12ee3d++]),12)),e[n(749)](e[n(1091)](63,_0x136ee7[_0x2aa700++]),6))|63&_0x27260c[_0x5349f6++])-65536;_0x56ccc0+=_0x43fa28[n(464)+n(1503)](e[n(678)](55296,l>>10)),_0x585711+=_0x47afe0[n(464)+"Code"](56320+e[n(959)](1023,l))}}else return e[n(1553)](-1,this[n(1327)])&&e[n(285)](-1,this[n(1564)])?xe.fromBits(0,0,this[n(533)]):e[n(917)](-1,this.low)?xe[n(514)](0,e.iIRGY(this[n(1564)],1),this.unsigned):xe[n(514)](e[n(1688)](this[n(1327)],1),this.high,this[n(533)])}[t(1398)](n){let s=t;return n?this[s(593)+"E"]():this[s(197)+"E"]()}[t(593)+"E"](){let n=t,s=this[n(1564)],l=this.low;return[e.CaJGW(255,l),l>>>8&255,e[n(997)](e[n(343)](l,16),255),e.ApuKX(l,24),255&s,e.tiHGk(s,8)&255,e[n(918)](s>>>16,255),e[n(377)](s,24)]}[t(197)+"E"](){let n=t,s=this[n(1564)],l=this[n(1327)];return[e[n(377)](s,24),e[n(918)](e[n(886)](s,16),255),e.dXFEb(e[n(902)](s,8),255),e[n(635)](255,s),e[n(1555)](l,24),e[n(165)](e[n(886)](l,16),255),e[n(501)](e[n(153)](l,8),255),255&l]}}let nl=new xe(0,0,!1),Bp=new xe(0,0,!0),Fp=xe[t(514)](-1,2147483647,!1),zp=xe[t(514)](-1,-1,!0),Up=xe[t(514)](0,-2147483648,!1);var sn=(function(a){let n=t;if(e.dxsoa(e.gzQrB,"LNPgt")){let s=e[n(819)][n(1480)]("|"),l=0;for(;;){switch(s[l++]){case"0":return a;case"1":a[a[e[n(618)]]=5004]=e[n(618)];continue;case"2":a[a[e[n(1070)]]=5003]=e[n(1070)];continue;case"3":a[a[e[n(677)]]=5002]=e[n(677)];continue;case"4":a[a[e[n(614)]]=5005]=e[n(614)];continue;case"5":a[a[e[n(1612)]]=5001]=e[n(1612)];continue}break}}else return this[n(216)+"T"]||this[n(323)+"X"]?this["_miniNav"+n(1595)+n(418)]:(this[n(1179)+"er"]||this._isWorker)&&this[n(497)][n(1143)+"tworkCha"+n(981)]?_0x129c16[n(1351)]:!0})({});class nr{constructor(n){let s=t;this[s(482)]=n,this[s(1415)]=null}}class rl extends nr{constructor(n,s){let l=t,h={VhXot:function(p,_){return e.Aqmbf(p,_)},gtMcv:function(p,_){return e.SchdW(p,_)},uvbxK:function(p,_){return e.PKOrn(p,_)},cnhof:function(p,_){return p<<_},YTqft:function(p,_){return e[H(1060)](p,_)},moBpP:function(p,_){return e[H(1385)](p,_)},HFJxP:function(p,_){return p|_},jScip:function(p,_){return e[H(699)](p,_)},mOaHw:function(p,_){return e[H(611)](p,_)}};if(e[l(606)](e[l(607)],l(712))){let p=_0x4f8e60[l(269)+"At"](_0x526366);OZdaIC[l(726)](p,55296)&&p<=56319&&OZdaIC[l(958)](_0x4aa354+1,_0x4d3192)&&(p=OZdaIC[l(1557)](OZdaIC.cnhof(p,10)+_0x2aa732[l(269)+"At"](++_0x19a808),56613888)),OZdaIC[l(958)](p,128)?_0x93ed48[_0x250bb9++]=p:(p<2048?_0x32b76d[_0x24bd87++]=OZdaIC.YTqft(OZdaIC[l(301)](p,6),31)|192:(p<65536?_0x197d3b[_0x31dd82++]=OZdaIC[l(1433)](OZdaIC.moBpP(p,12)&15,224):(_0x2dcee5[_0x22a068++]=OZdaIC[l(204)](OZdaIC[l(1671)](OZdaIC[l(301)](p,18),7),240),_0x1ca8c6[_0x3037d2++]=OZdaIC[l(204)](OZdaIC.moBpP(p,12)&63,128)),_0x492ebc[_0xcfbed6++]=OZdaIC[l(301)](p,6)&63|128),_0x41da74[_0xa1c6d0++]=OZdaIC.YTqft(63,p)|128)}else super(n),this[l(1215)]=s&&s[l(1215)]||null}}class il extends nr{constructor(n,s){let l=t,h=e[l(1005)][l(1480)]("|"),p=0;for(;;){switch(h[p++]){case"0":this.error=s&&s.error||null;continue;case"1":super(n);continue;case"2":this[l(1215)]=s&&s.message||"";continue;case"3":this[l(557)]=s&&s.lineno||0;continue;case"4":this[l(658)]=s&&s[l(658)]||0;continue;case"5":this[l(785)]=s&&s[l(785)]||"";continue;case"6":this[l(731)]=s&&s[l(731)]||5001;continue}break}}}class sl extends nr{constructor(n,s){let l=t,h=e[l(459)][l(1480)]("|"),p=0;for(;;){switch(h[p++]){case"0":this[l(731)]=s&&s.code||0;continue;case"1":this[l(1533)]=s&&s[l(1533)]||!1;continue;case"2":this[l(714)]=s&&s[l(714)]||"";continue;case"3":super(n);continue;case"4":this["willReco"+l(227)]=s&&s[l(1501)+l(227)]||!1;continue}break}}}class ol extends nr{constructor(n,s){let l=t,h={dwnNR:"success",TxTkt:e[l(210)],Olfrd:e[l(672)]};e[l(909)](l(179),e.LxFIB)?(_0x21fb9e(h[l(1145)]),this[l(460)](h[l(995)],_0x3802e1),this[l(460)](h[l(1278)],_0x4ae3c7)):(super(n),this[l(450)]=s&&s[l(450)]||null)}}class al extends ol{constructor(n,s){let l=t;super(n),this[l(450)]=s&&s[l(450)]||null,this.message=s&&s[l(1215)]||null}}class cl extends nr{constructor(n,s){let l=t;super(n),this[l(450)]=s&&s.data||null}}function lt(a,{message:n,code:s,error:l}){return new il(a,{message:n,code:s,error:l})}function mt(a,{code:n,reason:s,wasClean:l,willReconnect:h}){return new sl(a,{code:n,reason:s,wasClean:l,willReconnect:h})}function dl(a,{data:n,message:s}){return new al(a,{data:n,message:s})}function ll(a,{data:n}){return new cl(a,{data:n})}function fa(a,{message:n}){return new rl(a,{message:n})}class ul{constructor(n,s){let l=t;this[l(1628)+"s"]=n,this[l(288)+"es"]=s,this["currentI"+l(922)]=0,this[l(1333)+l(974)+l(271)+"t"]=0}[t(746)+"pointCon"+t(1512)](){let n=t;this["currentI"+n(922)]=0,this[n(1333)+"ndpointT"+n(271)+"t"]=0}[t(243)+"es"](){let n=t;this["currentE"+n(974)+n(271)+"t"]=0}[t(244)+t(592)+"nt"](){let n=t;return this[n(1628)+"s"][this[n(355)+n(922)]]}["getCurre"+t(592)+t(229)+t(1634)](){let n=t;return this[n(1333)+n(974)+n(271)+"t"]}[t(1229)+t(993)+"es"](){let n=t;return!!(e[n(484)](this[n(355)+"ndex"],this[n(1628)+"s"][n(721)])||this[n(355)+n(922)]===e[n(415)](this[n(1628)+"s"][n(721)],1)&&e[n(642)](this[n(1333)+"ndpointT"+n(271)+"t"],this[n(288)+"es"]))}[t(1194)+"rentEndp"+t(779)+t(1372)+t(1424)](){let n=t;return this.currentIndex==this[n(1628)+"s"][n(721)]?!0:this["currentE"+n(974)+n(271)+"t"]>this.maxRetries}[t(980)+"ackupEnd"+t(1190)+"UpdateCo"+t(1102)](){let n=t;if(e[n(1644)](e.arXHt,n(453)))return this[n(1333)+"ndpointTriesCount"]=1,this[n(355)+n(922)]++,this[n(1628)+"s"][this[n(355)+n(922)]];if(this._options["disableAutoRecon"+n(235)]||this[n(717)+n(1673)])return;this[n(1177)+"econnect"]()}["getCurre"+t(592)+t(160)+"ateCount"](){let n=t,s={XWCHf:function(l,h){return e.ekmzo(l,h)},mNPdX:function(l,h){return l instanceof h},PqExp:function(l,h){return e[H(442)](l,h)},zWExK:e[n(668)]};return e[n(1069)]!==e[n(800)]?(this[n(1333)+n(974)+n(271)+"t"]++,this[n(244)+"ntEndpoint"]()):s.XWCHf(n(748),typeof _0xbf6f2d)&&(s[n(1412)](_0x57f342,_0x65ce3e)||_0x3d7f11[n(1081)]&&s[n(911)](_0x4380ab[n(1081)],_0x27f08a))||typeof _0x111eea!="string"?"":(_0x5acc92[n(1221)](_0x12fe06),s[n(1691)])}}let rr=(e[t(666)]!=typeof globalThis&&e[t(465)](e.xGVBO,globalThis[t(1587)+t(1174)].name)||e[t(1459)](e[t(666)],typeof window)&&e.RDudZ(e[t(869)],window["construc"+t(1174)][t(1162)]))&&e.FPQWf("undefined",typeof document),Pn=e.FPQWf(e[t(666)],typeof globalThis)&&(e[t(456)](e.nCiaH,globalThis[t(1587)+t(1174)][t(1162)])||e[t(904)]===globalThis[t(1587)+t(1174)][t(1162)])&&e.aVJKl!=typeof tt,Xr=(e[t(1365)]("undefined",typeof globalThis)&&e[t(493)](e[t(201)],globalThis[t(1587)+"tor"][t(1162)])||e[t(1631)](e.aVJKl,typeof globalThis)||e[t(1529)](t(579)+"d",typeof globalThis)&&!!globalThis[t(298)+t(1016)])&&e[t(666)]!=typeof wx,Qr=e[t(1459)](t(579)+"d",typeof globalThis)&&(e.AIxLp(e[t(904)],globalThis[t(1587)+"tor"][t(1162)])||e.cFEvx(e[t(1642)],globalThis[t(1587)+t(1174)][t(1162)])||t(333)+t(1381)+t(1167)===globalThis["construc"+t(1174)].name)&&e.oBuEn(e[t(666)],typeof self),qp=e[t(1467)](e[t(666)],typeof globalThis)&&e[t(201)]===globalThis[t(1587)+t(1174)][t(1162)]&&e[t(432)](e.aVJKl,typeof global)&&e[t(797)](e.nCiaH,global[t(1587)+"tor"].name)&&e[t(666)]!=typeof process&&!!process[t(870)];class ha{constructor(){let n=t;this[n(856)+"rs"]={}}[t(1701)](n,...s){let l=t,h=this[l(856)+"rs"][n];if(h)h[l(1144)]()[l(1302)](p=>p.fn[l(550)](p[l(1586)],s));else if(e[l(903)](e[l(1377)],n)&&!this[l(892)]){let p=s.length&&s[0];if(p instanceof Error)throw p;let _=new Error(e[l(538)](l(725)+"d error.",p?e[l(1678)](e[l(1678)](" (",p.message),")"):""));throw _[l(444)]=p,p}return this}off(n,s){let l=t;if(n===void 0)this._listeners={};else if(e[l(1614)](void 0,s))this[l(856)+"rs"][n]=null;else{let h=this._listeners[n];if(h)for(let p=0;e.UCLjy(p,h[l(721)]);)e[l(650)](h[p].fn,s)?h[l(1077)](p,1):++p}return this}on(n,s,l){let h=t;return(this[h(856)+"rs"][n]||(this[h(856)+"rs"][n]=[]))[h(1475)]({fn:s,ctx:l||this}),this}}class Gp extends ha{[t(1624)+t(719)+t(1367)](n){let s=t;return n[s(429)]||n.errNo?(s(675)+" "+(n[s(429)]||"")+s(720)+(n[s(983)]||""))[s(413)]():JSON[s(1235)+"y"](n)}constructor(n,s,l){let h=t;super(),this[h(156)]=null,Xr&&wx[h(483)+h(253)]&&(this[h(156)]=wx[h(483)+h(253)]({url:n,protocols:s,header:l,fail:this["_createS"+h(295)+h(829)][h(280)](this),success:this[h(219)+h(401)+h(213)+"ler"].bind(this)})),Pn&&tt[h(483)+h(253)]&&(this[h(156)]=tt[h(483)+h(253)]({url:n,protocols:s,header:l,fail:this[h(219)+h(295)+h(829)].bind(this),success:this[h(219)+h(401)+h(213)+"ler"][h(280)](this)}))}[t(219)+t(401)+t(213)+t(1620)](){let n=t;e.NcqMr!==e.NcqMr?(_0x1aa0b1[n(867)](_0x2a4100,_0x307568),_0x226fdd[n(867)](_0x16d6b0,_0x5f4424)):Promise.resolve().then(()=>{let s=n,l={MiJFn:function(h,p){return e[H(682)](h,p)},kmPPP:function(h,p){return e[H(1524)](h,p)}};if(e[s(294)](e[s(218)],s(469)))this["_addWsLi"+s(1588)]();else{for(_0x74c149>>>=0;xlPMex[s(984)](_0x2fc09,128);)_0x8506a1(_0x59a14d,xlPMex.kmPPP(127,_0x56e920)|128),_0x24f8a9>>>=7;_0x3571f7(_0x6542d,_0x46afce)}})}[t(219)+"ocketFai"+t(829)](n){let s=t,l={LCjQa:function(h,p){return e[H(775)](h,p)},iWurH:function(h){return h()}};Promise[s(662)]()[s(1286)](()=>{let h=s;if(e[h(1582)]!=="OFoQw"){let p=lt(e[h(1377)],{message:this[h(1624)+"rrorMessage"](n)});this[h(1701)](e[h(1377)],p);let _=e[h(319)](mt,h(966),{reason:this[h(1624)+"rrorMess"+h(1367)](n)});this.emit(e.Iyrmc,_)}else AOpVKG.LCjQa(_0x37668d,_0x1cbb16(_0x4f1dae[h(792)])),AOpVKG[h(1093)](_0x848a48)})}[t(1047)+t(1588)](){let n=t,s={pTSDy:function(l){return e.emJgD(l)},avQPM:function(l,h,p){return e[H(930)](l,h,p)},dzsWi:"close",gxcwO:function(l,h,p){return e.DQJZN(l,h,p)},OmqOR:e[n(1377)]};e.xrCTp(e[n(1461)],n(863))?(_0x328069(_0x23e125.error),XzBrSL[n(691)](_0x44ef52)):(this[n(156)][n(1479)](l=>{let h=n;this[h(1701)](h(1184),s[h(250)](ll,h(1184),{...l,data:l[h(429)]||""}))}),this[n(156)][n(862)](l=>{let h=n;this[h(1701)](s[h(841)],s.gxcwO(mt,s[h(841)],{...l}))}),this[n(156)][n(1472)+"e"](l=>{let h=n;this[h(1701)](e.jxicE,e[h(1202)](dl,e[h(1067)],{...l}))}),this[n(156)][n(443)](l=>{let h=n;this[h(1701)](s[h(916)],s[h(489)](lt,s[h(916)],{...l,message:l.errMsg||""}))}))}send(n){let s=t,l={WSTXk:function(h,p){return h===p},gSgfp:function(h,p){return e[H(1591)](h,p)},gdWNs:function(h,p){return e[H(852)](h,p)},UXtZO:e[s(1483)],FlWDp:e[s(210)],aMSCk:function(h,p,_){return e[s(422)](h,p,_)},OpffT:e[s(1377)],vzhof:e[s(226)],Ozqmj:function(h,p,_){return h(p,_)}};if(e[s(442)](n,Uint8Array))if(e.FAAan(e.AhVLf,s(1285))){let h=n[s(1081)].slice(n[s(1035)+"et"],n.byteLength+n[s(1035)+"et"]);this._socket&&this[s(156)].send({data:h,fail:p=>{let _=s;if(l[_(1019)](l[_(522)],l[_(522)]))this.emit(l.OpffT,l.aMSCk(lt,"error",{message:this["_formatE"+_(719)+_(1367)](p)}));else{let{pingInterval:v,pingFrequency:w}=this[_(497)];if((l.WSTXk("hi",_0x2b3c9d[_(450)])&&l[_(630)](_(1598),w)||l[_(1019)](l[_(187)],w))&&(this[_(344)+_(375)](),this[_(1701)](l.FlWDp,"success"),this[_(1396)+_(238)+"Id"]=l[_(1146)](_0x84b7c2,this._ping[_(280)](this),v)),l[_(630)]("hi",_0x222b6f[_(450)]))return;try{_0x563688(this,_0x66b307,[_0x4d1f5a,_0x4b3198,_0x125e50,_0x887e72,_0x188795,_0x2a9499])}catch(C){let N=_0x3ac4bf(l.OpffT,{message:C.message,code:_0x2e40f0[_(1481)+_(1014)],error:C});this[_(1141)+_(1659)+_(972)](N)}}}})}else this["_message"+s(836)][s(1445)](),this[s(541)+s(836)][s(1475)](_0x12a370);else this[s(156)]&&this[s(156)][s(776)]({data:n,fail:h=>{let p=s;this.emit(l[p(853)],l[p(1159)](lt,l[p(853)],{message:this[p(1624)+"rrorMess"+p(1367)](h)}))}})}[t(966)](n,s){let l=t;if(e.ipWqi(e[l(1575)],e[l(1305)]))this[l(156)]&&this._socket[l(966)]({code:n,reason:s});else return this[l(1333)+l(974)+"riesCount"]=1,this["currentI"+l(922)]++,this.endpoints[this[l(355)+l(922)]]}[t(515)+t(799)](n,s){let l=t,h={piYQT:function(p,_){return e[H(1133)](p,_)},SsRAG:function(p,_){return e[H(348)](p,_)},mSgvL:function(p,_){return p(_)},xCHuM:function(p,_){return e[H(322)](p,_)},iPmoD:function(p,_){return e[H(1438)](p,_)},HINFf:function(p,_){return e[H(768)](p,_)},iMAcU:function(p,_){return e.orDjF(p,_)}};if(e[l(642)](e[l(380)],e[l(998)])){let p=h[l(1355)](_0x424733,8192),_=p>>>1,v=null,w=p;return function(C){let N=l;if(h[N(1450)](C,1)||h.SsRAG(C,_))return h.mSgvL(_0x325325,C);h[N(564)](w,C)>p&&(v=h[N(908)](_0x3405d5,p),w=0);let L=_0xbbe1cf[N(1363)](v,w,w+=C);return h[N(992)](7,w)&&(w=h[N(1437)](7|w,1)),L}}else this.on(n,s)}["removeEventListe"+t(1025)](n,s){this[t(460)](n,s)}get[t(1262)+"te"](){let n=t;return this[n(156)][n(1262)+"te"]}get[t(246)+"pe"](){let n=t;return this[n(156)][n(246)+"pe"]}set[t(246)+"pe"](n){}get[t(735)](){let n=t;if(e.zNgDI(e[n(1460)],e[n(1460)]))this["flushExp"+n(287)]();else return this[n(156)][n(735)]}get[t(1411)](){let n=t;if(e.KunFT(e[n(510)],e[n(510)]))++_0xb060ba,_0x4194c8+=4;else return this[n(156)][n(1411)]}get[t(1466)+"ns"](){let n=t;return this[n(156)][n(1466)+"ns"]}get[t(315)+"Amount"](){return 0}}function Hp(a,n){let s=t;if(n)return new n(a.url,a[s(1411)]);if(e[s(664)](Xr,Pn))return new Gp(a[s(735)],a[s(1411)],a[s(1635)]);if(e[s(664)](rr,Qr)&&s(579)+"d"!=typeof WebSocket&&WebSocket)return new WebSocket(a[s(735)],a[s(1411)+"s"])}function jp(a){let n=t,s=e[n(1590)].split("|"),l=0;for(;;){switch(s[l++]){case"0":if(a)return!0;continue;case"1":if(Pn&&tt["connectS"+n(253)])return!0;continue;case"2":if(Xr&&wx[n(483)+n(253)])return!0;continue;case"3":return!1;case"4":if(e.flVJx(rr,Qr)&&e[n(1529)](e[n(666)],typeof WebSocket)&&WebSocket)return!0;continue}break}}function fl(a,n,s){let l=-1;async function h(p){let _=H;return p<=l?Promise[_(736)](new Error(e[_(1397)])):(l=p,p===s.length?Promise[_(662)]():s[p][_(280)](a)(n,h[_(280)](null,p+1)))}e.KrPrJ(h,0)}function hl(a){let n=t,s=0,l=0;for(let h=0;e[n(689)](h,a[n(721)]);++h)l=a[n(269)+"At"](h),e[n(1696)](l,128)?s+=1:e.qWhoQ(l,2048)?s+=2:e[n(1249)](e.HoirL(64512,l),55296)&&e[n(642)](e[n(1549)](64512,a[n(269)+"At"](h+1)),56320)?(++h,s+=4):s+=3;return s}function xl(a,n,s){let l=t;if(e[l(1447)](e[l(415)](s,n),1))return"";let h="";for(let p=n;e[l(1696)](p,s);){let _=a[p++];if(e.NZkxn(_,127))h+=String[l(464)+l(1503)](_);else if(_>=192&&e[l(452)](_,224))h+=String["fromChar"+l(1503)](e[l(1487)](e[l(1088)](e.UtQfq(31,_),6),63&a[p++]));else if(_>=224&&e[l(1209)](_,240))h+=String[l(464)+l(1503)](e[l(808)](e.MWxzd(15,_),12)|e.lgDnr(63,a[p++])<<6|e[l(1097)](63,a[p++]));else if(e[l(1409)](_,240))if(e[l(936)](e[l(1211)],l(962))){let v=_0x584492[l(1215)][l(955)];v&&_0x44e813[l(1196)+"rs"](v)}else{let v=e.ojmFr(e[l(633)](e[l(1600)](e[l(435)](e[l(1679)](7&_,18),e[l(1191)](e[l(1667)](63,a[p++]),12)),e[l(1346)](63&a[p++],6)),e.vcRru(63,a[p++])),65536);h+=String[l(464)+"Code"](e[l(314)](55296,e[l(696)](v,10))),h+=String[l(464)+l(1503)](e.DKTLp(56320,e[l(543)](1023,v)))}}return h}function xa(a,n,s){let l=t,h=s,p,_;for(let v=0;e.hbWvb(v,a[l(721)]);++v)if(p=a[l(269)+"At"](v),p<128)n[s++]=p;else if(e[l(505)](p,2048))n[s++]=e[l(1422)](e[l(1126)](p,6),192),n[s++]=e[l(640)](e[l(752)](63,p),128);else if(e[l(1465)](e[l(770)](64512,p),55296)&&e[l(1115)](64512&(_=a[l(269)+"At"](v+1)),56320)){let w=(l(1085)+"3|2")[l(1480)]("|"),C=0;for(;;){switch(w[C++]){case"0":p=e[l(150)](e[l(277)](65536,e[l(1565)](1023&p,10)),e[l(1275)](1023,_));continue;case"1":++v;continue;case"2":n[s++]=e[l(1207)](e.Zmxzo(63,p),128);continue;case"3":n[s++]=e[l(1487)](e[l(1438)](e[l(353)](p,6),63),128);continue;case"4":n[s++]=e[l(527)](p>>12,63)|128;continue;case"5":n[s++]=e[l(1031)](e[l(239)](p,18),240);continue}break}}else n[s++]=e[l(1378)](e[l(1195)](p,12),224),n[s++]=e[l(467)](e[l(1125)](p,6),63)|128,n[s++]=63&p|128;return e[l(1675)](s,h)}async function pl(a){let n=t;if(e.oMvOM==typeof a){let s=new Uint8Array(e[n(317)](hl,a));return e[n(386)](xa,a,s,0),s}return e[n(258)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a.buffer,a[n(1035)+"et"],a[n(1651)+"th"])}function Wp(a){let n=t,s={CWmHy:function(h,p,_,v){return h(p,_,v)}};if(e[n(350)](e.pdSif,"CxTXQ"))for(var l in _0x3e928a)bFitjK[n(1153)](_0x234a2f,_0x339a39,l,{get:_0x1cc1b2[l],enumerable:!0});else try{return e[n(1459)](e.oMvOM,typeof a)&&(e[n(1563)](a,ArrayBuffer)||a[n(1081)]&&e[n(249)](a.buffer,ArrayBuffer))||e[n(1529)](e.oMvOM,typeof a)?"":(JSON[n(1221)](a),e.BqAqU)}catch{return e[n(1220)](e[n(1580)],typeof a)?e[n(706)]:""}}let Kp=(a,n)=>{let s=t;switch(a){case e[s(1213)]:case e[s(968)]:return{["x-use-"+a]:1,"x-tt-env":n};default:return{}}};class $p{constructor(n){let s=t;this["maxLossC"+s(1634)]=n,this[s(1095)]=0}[t(1561)](){let n=t;e[n(1068)](e[n(434)],n(1470))?this.count++:this.emit(e[n(1106)],e.ljBru(_0x19f84b,n(966),{..._0x1385f8}))}["checkRea"+t(1532)+"nt"](){let n=t;return e[n(1449)](this[n(1095)],this.maxLossCount)}[t(1369)+t(196)](n=0){let s=t;this.maxLossCount=n,this[s(1095)]=0}}async function Vp(a){let n=t,s={uubbt:function(l,h){return e[H(973)](l,h)},pITTf:function(l,h){return l>>>h},xtzzV:function(l,h){return l>>>h},SiOwZ:function(l,h){return e.UYWZa(l,h)},kMbMS:function(l,h){return e[H(975)](l,h)},EVvPg:e[n(747)],wiOGm:function(l,h){return e[n(431)](l,h)},istNb:n(1314)+n(1314)+n(1314)+n(1314)};return new Promise(l=>{let h=n;if(e[h(445)](e.dQExH,e[h(851)])){let p=this.high,_=this[h(1327)];return[RliNNi[h(190)](255,_),RliNNi.pITTf(_,8)&255,RliNNi.pITTf(_,16)&255,RliNNi[h(758)](_,24),RliNNi.uubbt(255,p),RliNNi.xtzzV(p,8)&255,RliNNi[h(342)](p>>>16,255),RliNNi[h(690)](p,24)]}else{if(!rr)return e[h(967)](l,e[h(747)]);try{let p=document[h(1128)+h(737)](e[h(617)]);window[h(433)+h(926)]=_=>{let v=h;document[v(332)]["removeCh"+v(894)](p),window.frontierJSONP=void 0,l(_&&_[v(588)]||s[v(282)])},p.type="text/jav"+h(529),p.src=e[h(322)](a[h(270)](/^ws/,e[h(1296)]),e.ilGrt);try{document[h(332)][h(1246)+h(894)](p)}catch{document[h(332)][h(915)+h(894)](p)}}catch{if(e.ipWqi(e[h(402)],h(159)))window[h(433)+h(926)]=void 0,e[h(185)](l,h(945)+h(714));else{let p=/(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}/[h(1476)](_0x42bc40),_=/(([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]))/[h(1476)](_0x8e0ada);return p?RliNNi[h(1109)](_0x3a7a51,_0x27d442):_?_0x59a8c4(_0x66cf95):RliNNi[h(392)]}}}})}function on(a,n,s){let l=t;return!!a?.[l(1505)](h=>h[l(1254)]===n&&h[l(1391)]===s)}function ir(a,n){let s=t;return a?.[s(1505)](l=>l[s(1254)]===n)?.[s(1391)]}let pa=null;async function Jp(){let a=t;return pa||(pa=Promise.resolve().then(zt[a(280)](zt,e[a(1474)]))),pa}class Zp extends ha{constructor(n,s){let l=t;super(),this._dbName=n,this[l(245)]=s,this[l(1129)]=void 0,this[l(382)+l(698)]=null}async[t(151)](){let n=t;if(e[n(1591)](e[n(1180)],e.DlYTH))await this[n(1003)]();else return _0x1567a1(_0x22d520[n(550)](xJiVKM.stGmx(_0x390900,this),_0x175958))}async[t(1003)](){let n=t,s={rNDMK:function(l){return e[H(1002)](l)},IPhat:function(l,h,p,_){return e[H(1083)](l,h,p,_)}};if(!this[n(1129)]){if(this[n(382)+n(698)])return this[n(382)+n(698)];try{if(n(476)===e.JzCfZ)return _0x3f82f0(e[n(1041)](_0x4bd9bc,_0x47ce5f));{let l=this[n(1264)],h=this[n(245)];this[n(382)+"mise"]=(async()=>{let p=n,{openDB:_}=await s[p(1205)](Jp);this[p(1129)]=await s[p(1645)](_,"frontier_"+l,1,{upgrade(v){v["createOb"+p(622)+"e"](l,{keyPath:h})}})})(),await this[n(382)+"mise"]}}catch(l){console[n(567)](l)}finally{this[n(382)+n(698)]=null}}}async[t(531)](n){let s=t,l={XVOZD:function(h,p,_){return h(p,_)},kWCuQ:function(h,p,_){return e[H(1690)](h,p,_)},kaYCA:function(h,p){return e[H(631)](h,p)},COEYm:function(h,p,_){return e[H(276)](h,p,_)},mcXnu:function(h,p,_){return h(p,_)}};if(e[s(558)](e[s(1567)],e[s(1567)])){let h=_0x4e8f41[s(1254)];h!==void 0&&(WHxIJg[s(961)](_0xafb47d,_0x3eb4ff,10),WHxIJg.kWCuQ(_0x1b364f,_0x26d70b,h));let p=_0x8c2518[s(1391)];WHxIJg[s(991)](void 0,p)&&(WHxIJg[s(1569)](_0x18d5ac,_0x58fd50,18),WHxIJg[s(1353)](_0x1b5375,_0x15a8a1,p))}else try{return await this[s(1003)](),this[s(1129)]?.[s(531)](this[s(1264)],n)}catch(h){if(e[s(1493)](e[s(299)],e.TnDBa))return this._socket.protocol;console[s(567)](h)}}async set(n,s){let l=t;return await this._init(),this[l(1129)]?.[l(1108)](this[l(1264)],n)}async[t(1267)](n){let s=t,l={FkNpU:function(h,p){return e[H(1110)](h,p)},NrYbM:function(h,p){return e[H(608)](h,p)},bpDWT:e[s(706)],FJgVy:e[s(668)],kgcie:"applicat"+s(1317)+s(399)+"=utf-8",HuZIc:"string",PAglb:e[s(1592)]};try{if(e[s(372)](e[s(1269)],e[s(1269)]))if(l[s(366)](_0x1a8138[s(955)],_0x246b5e)){let h=this[s(497)][s(1576)+"ncoding"]instanceof _0x5b5721?{force:!!this[s(497)]["payloadE"+s(1245)][s(754)],encoding:this[s(497)].payloadEncoding.encoding?this[s(497)]["payloadE"+s(1245)][s(424)][s(270)](/\s/g,"")[s(361)+s(573)]():""}:{force:!1,encoding:this._options[s(1576)+"ncoding"]?this[s(497)][s(1576)+s(1245)].replace(/\s/g,"")[s(361)+"ase"]():""},p=_0x687bc5["payloadE"+s(1245)]?_0x316f59["payloadE"+s(1245)][s(270)](/\s/g,"")["toLowerC"+s(573)]():"",_=l[s(585)](this[s(497)][s(999)+"ype"],_0x83b718)?{force:!!this[s(497)][s(999)+s(572)].force,type:this[s(497)][s(999)+s(572)].type?this[s(497)][s(999)+s(572)][s(482)][s(270)](/\s/g,"")[s(361)+s(573)]():""}:{force:!1,type:this[s(497)]["payloadT"+s(572)]?this._options[s(999)+s(572)][s(270)](/\s/g,"")[s(361)+s(573)]():""},v=_0x2fa944[s(999)+s(572)]?_0x1fb1bb[s(999)+s(572)][s(270)](/\s/g,"")["toLowerC"+s(573)]():"",w=_[s(754)]?_.type:v||_[s(482)],C=h[s(754)]?h[s(424)]:p||h[s(424)],N=[l[s(873)],l.FJgVy,l[s(1492)],l[s(866)]],L=[s(1596)+"e",l[s(192)]];this[s(497)][s(1525)+s(1670)+s(336)+"ad"]&&N[s(859)](w)&&(!C||L.includes(C))?_0x4e6c8d["textPayl"+s(1698)]=_0x3e9739(_0x1dc301[s(955)],0,_0x5862a9[s(955)][s(1651)+"th"]):_0x59df46[s(900)+s(1698)]=""}else _0x540934[s(900)+s(1698)]="";else return await this[s(1003)](),this._qosDB?.[s(191)](this._dbName,n)}catch(h){console.log(h)}}async[t(1199)](){let n=t;try{return await this[n(1003)](),this[n(1129)]?.clear(this[n(1264)])}catch(s){console[n(567)](s)}}async[t(695)](){let n=t;return await this._init(),this[n(1129)]?.getAllKeys(this[n(1264)])}async getAll(){let n=t;return e[n(520)]("JbXMP",e.QHZgY)?(await this[n(1003)](),this._qosDB?.[n(1066)](this[n(1264)])):this._qosDB?.[n(1267)](_0x445044)}async closeDB(){let n=t;try{this[n(1129)]?.[n(966)](),this._qosDB=void 0}catch(s){console[n(567)](s)}}get[t(381)](){let n=t;if(e[n(1021)]("AEnUb",e[n(670)]))_0x431dae instanceof _0xdab201&&_0x103397[n(867)](_0x24f853,_0x1be908);else try{return!!this[n(1129)]}catch(s){return console[n(567)](s),!1}}}class Yp{constructor(n,s){let l=t;this._DBName=n,this[l(1693)]=s,this._qosDB=localStorage}async openDB(){}get[t(1458)](){let n=t;return n(433)+"_"+this[n(1138)]}async[t(531)](n){let s=t,l=this._qosDB.getItem(this[s(1458)]);return JSON[s(1221)](l||"{}")[n]}async[t(867)](n,s){let l=t,h=this._qosDB[l(1028)](this[l(1458)]),p=JSON[l(1221)](h||"{}");return p[s||n[this[l(1693)]]]=n,this[l(1129)][l(970)](this[l(1458)],JSON[l(1235)+"y"](p)),s||n[this[l(1693)]]}async[t(1267)](n){let s=t;if(e[s(680)]!=="PkBUq"){let l=this._qosDB[s(1028)](this[s(1458)]),h=JSON.parse(e[s(1432)](l,"{}"));return h[n]=void 0,this[s(1129)][s(970)](this[s(1458)],JSON[s(1235)+"y"](h))}else{let l=this[s(1129)][s(1663)+"geSync"](this[s(1458)]),h=_0xde8d85[s(1221)](e[s(664)](l,"{}"));return h[_0x2e3e59]=void 0,this[s(1129)][s(645)+s(1394)](this._prefix,_0xf02c81.stringify(h))}}async[t(1199)](){return this[t(1129)].clear()}async[t(695)](){let n=t;if(e[n(1020)]!==e[n(1020)]){let s=this[n(541)+n(836)][n(946)]((l,h)=>(l+=h&&h[n(1651)+"th"]||0,l),0);return e[n(490)](s,this._ws?this[n(212)][n(315)+n(1334)]:0)}else{let s=this[n(1129)].getItem(this._prefix),l=JSON[n(1221)](e[n(664)](s,"{}"));return Object[n(695)](l)}}async[t(1066)](){let n=t,s=this[n(1129)][n(1028)](this._prefix),l=JSON[n(1221)](e[n(664)](s,"{}"));return Object.values(l)}[t(1687)](){let n=t;if(e.xrCTp(e[n(1383)],e.WIbMn))return Promise[n(662)]();{let s=n(1430)+_0x242cff+(n(1610)+n(1345)+"es reached");this[n(1141)+"hErrorEv"+n(972)](e.ITUVk(_0x58b72c,n(571),{message:s,code:_0x5138fc[n(403)+n(1094)+"R"],error:_0x6665aa}));return}}get[t(381)](){return!!this[t(1129)]}}class Xp{constructor(n,s){let l=t;if(e.boSxy(e[l(1251)],e[l(1251)]))return this[l(212)]?this._ws.readyState:this._options[l(1471)+"cOpen"]?this[l(1490)+"NG"]:this[l(203)];this[l(1138)]=n,this._pathKey=s,this[l(1129)]=Pn?tt:Xr?wx:null}async[t(151)](){}get[t(1458)](){return t(433)+"_"+this._DBName}async[t(531)](n){let s=t,l=this[s(1129)][s(1663)+"geSync"](this._prefix);return JSON.parse(e[s(1478)](l,"{}"))[n]}async[t(867)](n,s){let l=t,h=this._qosDB[l(1663)+l(1394)](this[l(1458)]),p=JSON[l(1221)](e[l(1432)](h,"{}"));return p[s||n[this[l(1693)]]]=n,this._qosDB[l(645)+l(1394)](this[l(1458)],JSON.stringify(p)),s||n[this._pathKey]}async del(n){let s=t,l=this[s(1129)][s(1663)+s(1394)](this[s(1458)]),h=JSON[s(1221)](e[s(1432)](l,"{}"));return h[n]=void 0,this[s(1129)][s(645)+s(1394)](this[s(1458)],JSON[s(1235)+"y"](h))}async[t(1199)](){let n=t;return this[n(1129)][n(1527)+n(1204)]()}async[t(695)](){let n=t,s=this[n(1129)][n(1663)+n(1446)+"nc"](this._prefix),l=JSON[n(1221)](e.ziLrm(s,"{}"));return Object[n(695)](l)}async getAll(){let n=t,s={ZjgXT:function(l,h){return e.jHNdT(l,h)}};if(n(1506)===n(948))this[n(1669)]=!0,this[n(1327)]=FNgKpG[n(965)](0,_0xbf722e),this.high=0|_0x3f938a,this[n(533)]=!!_0x4e4ee9;else{let l=this[n(1129)][n(1663)+n(1446)+"nc"](this._prefix),h=JSON[n(1221)](l||"{}");return Object.values(h)}}[t(1687)](){let n=t;if(e[n(850)](e[n(1292)],e[n(817)]))return Promise.resolve();this[n(1701)](n(1184),e[n(762)](_0x5b176b,"open",{..._0x24929a,data:_0x1cf07a.errMsg||""}))}get[t(381)](){return!!this[t(1129)]}}function gl(a,n){let s=t;if(e[s(1420)](Pn,Pn))return new Xp(a,n);if((rr||Qr)&&e[s(1365)](e[s(666)],typeof indexedDB))return new Zp(a,n);if((rr||Qr)&&e[s(1365)](e[s(666)],typeof localStorage))return new Yp(a,n);throw new Error(e[s(693)])}class Qp{constructor(){let n=t;this[n(404)+n(1263)+"Id"]=null,this[n(404)+"l"]=36e5,this._qosDB=gl(e[n(791)],e[n(1183)])}async[t(404)+t(710)](){let n=t;e[n(1076)](clearInterval,this._intervalTimeoutId),this[n(404)+n(1263)+"Id"]=setInterval(()=>{let s=n;this[s(1121)+s(287)]()},this._interval)}async openDB(){let n=t;await this[n(1129)][n(151)]()[n(1286)](()=>{let s=n;this[s(404)+s(710)]()})}async[t(1121)+"ired"](){let n=t;(await this[n(1129)]?.[n(1066)]()||[])[n(291)](({timestamp:h})=>h<Date[n(1489)]())[n(1302)](h=>{let p=n;this[p(1129)]?.[p(1267)](h[p(169)+"id"])})}async del(n){let s=t;return this[s(1129)]?.[s(1267)](n)}async[t(867)](n,s){let l=t;return this._qosDB?.[l(867)]({message_id:n,timestamp:s})}async[t(531)](n){let s=t;return this[s(1129)]?.[s(531)](n)}async[t(1687)](){let n=t;e[n(1165)](clearInterval,this[n(404)+n(1263)+"Id"]),await this[n(1129)]?.[n(1687)]()}get[t(381)](){return this[t(1129)]?.isReady}}function ga(a){let n=t;if(e[n(384)]!=="NuGOT")!this[n(823)+"Lock"]&&(this[n(778)+n(530)]?.["resetEnd"+n(644)+"fig"](),this[n(1622)+n(1090)]?.[n(1369)+"nter"](),this[n(717)+n(1673)]=!1,this[n(1022)]=!0,this._connect());else{let s=!!this[n(497)][n(376)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[n(620)](on,a[n(1215)][n(1635)],e[n(363)],"2"),h=l&&on(a[n(1215)][n(1635)],e[n(896)],"1"),p=l&&e.JfZSe(on,a.message.headers,n(1098)+n(411)+"k","1"),_=p?e[n(416)](ir,a[n(1215)][n(1635)],e[n(1154)])?.[n(1480)](",")[n(291)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:p,ackMsgIds:_}}}async function ml(){let a=t;return this[a(1425)+a(1485)]||(this[a(1425)+a(1485)]=new Qp),this[a(1425)+a(1485)][a(381)]||await this[a(1425)+a(1485)][a(151)](),this._QoSManager}async function eg(a,n){let s=t,{enableAutoAck:l}=this._options,h=e[s(976)](on,a[s(1215)][s(1635)],e[s(181)],"1"),p=on(a[s(1215)].headers,e.LLXUA,"1"),_=ga.call(this,a);if(e[s(1252)](l,h)){let{SeqID:v,LogID:w,service:C,LogIDNew:N,method:L}=a.message;this[s(1049)]({SeqID:v,LogID:w,LogIDNew:N,service:C,method:L,headers:[{key:e.LLXUA,value:"1"},{key:s(524),value:N||""},{key:e[s(1352)],value:"0"}]})}p&&!_[s(595)]&&this[s(1141)+s(1163)+s(1560)](a),n()}async function tg(a,n){let s=t;if(e.EvYLj(s(1018),e[s(1652)]))this[s(830)](e[s(1491)],a[s(1215)]),n();else{let l=e[s(803)](_0x47d78a,_0x2a5fe5,1);_0x21dc60.bytes[l]=_0x507b0e}}async function ng(a,n){let s=t,l={LtokZ:function(p,_){return e[H(1449)](p,_)},OjiQf:function(p,_){return p===_},TRhud:function(p,_){return e[H(1389)](p,_)}},h=e[s(563)](nn,await e.PRboh(pl,a.data));try{if(e[s(258)](h[s(955)],Uint8Array))if(e[s(1301)]!=="ZZLFE"){let p=e[s(1563)](this[s(497)]["payloadE"+s(1245)],Object)?{force:!!this[s(497)][s(1576)+s(1245)].force,encoding:this[s(497)][s(1576)+"ncoding"][s(424)]?this._options[s(1576)+s(1245)].encoding[s(270)](/\s/g,"")[s(361)+s(573)]():""}:{force:!1,encoding:this._options["payloadE"+s(1245)]?this[s(497)][s(1576)+s(1245)][s(270)](/\s/g,"")[s(361)+s(573)]():""},_=h[s(1576)+"ncoding"]?h[s(1576)+s(1245)][s(270)](/\s/g,"")[s(361)+s(573)]():"",v=e[s(586)](this[s(497)][s(999)+s(572)],Object)?{force:!!this[s(497)][s(999)+s(572)][s(754)],type:this[s(497)][s(999)+s(572)].type?this[s(497)]["payloadT"+s(572)][s(482)][s(270)](/\s/g,"")["toLowerC"+s(573)]():""}:{force:!1,type:this._options[s(999)+s(572)]?this[s(497)]["payloadT"+s(572)][s(270)](/\s/g,"")["toLowerC"+s(573)]():""},w=h[s(999)+"ype"]?h[s(999)+s(572)].replace(/\s/g,"")[s(361)+s(573)]():"",C=v[s(754)]?v[s(482)]:w||v[s(482)],N=p[s(754)]?p[s(424)]:_||p[s(424)],L=[e.ouGUb,e[s(668)],s(1392)+"ion/json"+s(399)+"=utf-8",e[s(1580)]],j=[e[s(1218)],s(1303)];this[s(497)]["enableTransformT"+s(336)+"ad"]&&L[s(859)](C)&&(!N||j.includes(N))?h["textPayl"+s(1698)]=e[s(386)](xl,h.payload,0,h.payload.byteLength):h.textPayload=""}else return!!(cJlcOQ[s(1172)](this[s(355)+s(922)],this[s(1628)+"s"].length)||cJlcOQ[s(1550)](this[s(355)+s(922)],cJlcOQ[s(1341)](this[s(1628)+"s"][s(721)],1))&&cJlcOQ[s(1550)](this[s(1333)+s(974)+"riesCount"],this[s(288)+"es"]));else h["textPayl"+s(1698)]=""}catch(p){h[s(900)+s(1698)]="",console[s(567)](p)}a[s(1215)]=h,e[s(1002)](n)}function rg(a,n,s){let l=t,h=e[l(906)](s,8192),p=e.YScJp(h,1),_=null,v=h;return function(w){let C=l;if(e[C(1403)](w,1)||e[C(723)](w,p))return a(w);e[C(1116)](e.SlYji(v,w),h)&&(e[C(1456)](e[C(876)],e[C(876)])?(_=e.hUQJx(a,h),v=0):_0x49d3ee(this,_0x11df44,[_0x2c2065,_0x507315,_0x5427f2,_0x23ee74,_0x93f839,_0x49b4f9]));let N=n[C(1363)](_,v,v+=w);return e[C(165)](7,v)&&(v=e[C(1111)](e[C(788)](7,v),1)),N}}let ig=4294967295;function sg(a,n,s){let l=t;return e.CtCru(RangeError,e[l(559)](e[l(277)](e[l(1360)](e[l(255)](l(942)+"t of range: ",a),l(1484)),e[l(1432)](n,1))+e[l(503)],s))}function og(a,n,s){let l=t;if(e.Wmypc(l(598),e[l(745)])){if(e[l(183)](s,ig))throw new Error(l(1107)+l(1084)+"e");let h=3;for(;h>=0;){if(e[l(293)](e[l(1486)],e.EfGOW))return e[l(606)](-1,this[l(1327)])&&e[l(545)](-1,this.high)?_0x14b32f.fromBits(0,0,this[l(533)]):this[l(1327)]===-1?_0x4078e0[l(514)](0,e[l(1558)](this[l(1564)],1),this.unsigned):_0x468b0c.fromBits(e[l(673)](this.low,1),this[l(1564)],this[l(533)]);{let p=e[l(1064)](255,s);e[l(386)](wa,p,a,n+h),s>>>=8,h--}}return e[l(782)](n,4)}else{if(xJiVKM[l(423)](_0x252d9e,l(1370)))return _0x16a639.get(_0x49fe87);if(_0x3976a6===l(334)+l(268))return _0x50f042["objectSt"+l(268)]||_0x55ed46[l(531)](_0x48a3c3);if(_0x212112===xJiVKM[l(845)])return _0x1f0f64[l(334)+l(268)][1]?void 0:_0x46d1f1[l(334)+l(1315)](_0x4a55ac["objectSt"+l(268)][0])}}function ag(a,n){let s=t,l=0,h=n,p=n+4;for(;e[s(202)](h,p);){let{value:_,offset:v}=e[s(1136)](ma,a,h);h=v,l=e[s(1544)](e[s(1227)](l,8),0),l+=_}return{value:l,offset:p}}function cg(a,n,s){let l=t,h=e[l(1373)].split("|"),p=0;for(;;){switch(h[p++]){case"0":if(n[l(1540)])return n[l(1540)](a,s)+s;continue;case"1":return e[l(1265)](e[l(367)](xa,a,n,s),s);case"2":if(n[l(405)+"e"])return e.mXMtu(n.utf8Write(a,s),s);continue;case"3":if(!a)return s;continue;case"4":if(e.LhOHu(a[l(721)],40))return e.RHQqv(xa,a,n,s)+s;continue}break}}function dg(a,n){let s=t,l=new xe(e[s(1487)](e.mvKby(e[s(1243)](a[e[s(322)](n,4)],24),e[s(919)](a[e[s(242)](n,5)],16)),e[s(621)](a[e[s(704)](n,6)],8))|a[n+7],e.bZmTG(e.vFyka(e[s(1600)](e.KHgFY(a[n+0],24),e[s(621)](a[e[s(1428)](n,1)],16)),e[s(749)](a[n+2],8)),a[e[s(1428)](n,3)]),!0);return n+=8,{value:l,offset:e.UVXBj(n,8)}}function lg(a,n,s){let l=t,h=a[l(1327)],p=a[l(1564)];return n[s]=p>>>24,n[e[l(1137)](s,1)]=e.AptEb(p,16)&255,n[s+2]=e[l(309)](p,8)&255,n[s+3]=255&p,n[e[l(1539)](s,4)]=e[l(354)](h,24),n[s+5]=e[l(1316)](e[l(1362)](h,16),255),n[e[l(1654)](s,6)]=h>>>8&255,n[e[l(1247)](s,7)]=255&h,s+=8,s}function ma(a,n){let s=t;return a[s(1566)+"8"]?{value:a[s(1566)+"8"](n),offset:n+1}:{value:e[s(1064)](255,a[n]),offset:e[s(224)](n,1)}}function wa(a,n,s){let l=t;return n[l(651)+"t8"]?n[l(651)+"t8"](a,s):n[s]=e[l(1329)](255,a),e[l(773)](s,1)}let ug=function(a){return new Uint8Array(a)},fg=e[t(898)](e[t(666)],typeof Buffer)?Buffer[t(279)+t(1079)]:rg(ug,Uint8Array[t(220)+"e"][t(390)]),hg=16,_a=32;function xg(a){let n=t,s=0,l={};for(let h=0;h<a[n(721)];h++)l[a[h][n(663)+n(1629)]]=e.sklEe(hl,a[h][n(663)+n(1629)]),s+=14+l[a[h]["cursor_n"+n(1629)]];return[s,l]}function wl(a,n,s){let l=t,[h,p]=e.jMgeb(xg,a),_=e[l(1427)](fg,h),v=0;return a[l(1302)](w=>{let C=l;console.log(e[C(373)],w,w[C(148)]),v=e[C(313)](wa,0,_,v),console[C(567)](e[C(1040)],v),v=e[C(920)](og,_,v,w[C(148)]||0),console[C(567)](e[C(1682)],v),v=e.IwZeO(wa,p[w[C(663)+C(1629)]],_,v),console[C(567)](e[C(1646)],v),v=e[C(920)](cg,w[C(663)+C(1629)],_,v),console.log(e[C(1270)],v),v=e.JfZSe(lg,xe[C(1543)+"er"](w.cursor||n),_,v),console[C(567)](e[C(1499)],v)}),{frameType:_a,headers:[{key:l(155)+l(1515),value:s}],payload:_}}function pg(a){let n=t,s=0,l=[];for(;e[n(1623)](s,a[n(1651)+"th"]);){let{offset:h}=ma(a,s);s=h;let p={cursor_name:"",cursor:0,service:0},{value:_,offset:v}=ag(a,s);p[n(148)]=_,s=v;let{value:w,offset:C}=e[n(1500)](ma,a,s);s=C,p[n(663)+"ame"]=xl(a,s,e[n(832)](s,w)),s+=w;let{value:N,offset:L}=e[n(930)](dg,a,s);p[n(208)]=N.toNumber(),s=L,l.push(p)}return l}function gg(){let a=t;return{frameType:_a,headers:[{key:e[a(1382)],value:e[a(1413)]}],payload:void 0}}class mg{constructor(n,s,l){let h=t;this[h(990)+h(236)]=n,this["_cursorF"+h(1573)]=s,this[h(541)+"Strategy"]=l,this[h(1129)]=e[h(416)](gl,this[h(990)+h(236)],e[h(1494)])}async[t(151)](){let n=t;await this[n(1129)][n(151)]()}async getCursors(){let n=t;if(e[n(887)](e[n(927)],e[n(790)])){let{url:s}=e.jqSaE(_0x447f67,{}),l=_0x54db97[n(1120)](s)?s:e[n(1580)]==typeof s?[s]:[];_0x522739&&_0x24f296.assign(this[n(497)],_0x51c9ed),l&&l[n(721)]?this[n(778)+n(530)]=new _0x3cd0f9(l,this._options[n(288)+"es"]):this["_endpoin"+n(530)]?.[n(746)+n(644)+n(1512)](),this[n(1622)+n(1090)]?.[n(1369)+n(196)](this[n(497)][n(318)+"Count"]),this["_readyCl"+n(1673)]=!1,this[n(212)]&&this[n(212)][n(1262)+"te"]!==this[n(203)]?this["_disconn"+n(734)](1e3,e[n(815)],!0):(this[n(1022)]=!0,this[n(823)]())}else{if(!this[n(1129)][n(381)])return;let s=this["_message"+n(1072)],l=await this[n(1129)][n(1066)]();switch(console.log(n(950)+n(498),l),s){case"ALL":return l&&l[n(721)]?e[n(730)](wl,l,0,this["_cursorF"+n(1573)]):void 0;case e[n(172)]:return;case e[n(509)]:return l&&l[n(721)]?e[n(709)](wl,l,0,this[n(826)+n(1573)]):e[n(1063)](gg)}}}async set(n,s,l){let h=t;return console[h(567)](e.HTLSw,n,s,l),this[h(1129)][h(867)]({cursor_name:n,cursor:s,service:l})}async[t(1196)+"rs"](n){let s=t,l=e[s(1233)](pg,n);for(let h of l)console[s(567)](s(1290)+"r",l),await this[s(1129)][s(867)](h)}async[t(531)](n){let s=t;return(await this[s(1129)][s(531)](n))?.cursor}async[t(1687)](){let n=t;await this[n(1129)][n(1687)]()}[t(1004)+t(1029)+t(1236)](n){let s=t;this[s(826)+s(1573)]=n}get[t(381)](){let n=t;return this._qosDB[n(381)]}}let wg="__x_msg_"+t(507);async function _l(a){let n=t;if(!this[n(497)][n(376)+"S"])return null;let{aID:s,fpID:l,messageStrategy:h}=this[n(497)],p=e.ziLrm(a,wg);try{return this[n(1112)+n(1289)]?a&&this[n(1112)+n(1289)]["updateCursorFile"+n(1236)](a):this._cursorManager=new mg(l+"_"+s+"_"+p,p,h),this["_cursorM"+n(1289)].isReady||await this[n(1112)+n(1289)].openDB(),this["_cursorM"+n(1289)]}catch{return e[n(1429)](n(272),e.TTwwo)?null:this[n(1129)]?.[n(531)](_0x24d376)}}async function _g(a,n){let s=t,l=on(a.message.headers,e.vCbhN,"-1"),h=e[s(620)](on,a[s(1215)][s(1635)],s(1170),"1"),p=e.UNYIH(ir,a[s(1215)][s(1635)],e[s(230)]),_=e[s(552)](Number,e[s(513)](ir,a[s(1215)][s(1635)],e[s(341)]))||0,v=ga.call(this,a),w=e[s(976)](on,a[s(1215)].headers,e.PvddU,"2"),C=e[s(884)](ir,a[s(1215)][s(1635)],e.SjorT),N=e[s(305)](Number,e[s(632)](ir,a[s(1215)][s(1635)],e[s(1059)]));if(v[s(595)])return n();let L=v[s(1033)+"sage"]?await ml[s(1363)](this):null;if(a[s(1215)][s(148)]>0&&h&&!l||e[s(943)](a[s(1215)][s(148)],0)){if(p&&v[s(1033)+s(928)]&&L){if(!!!await L[s(531)](p))if(e.YRAFX(e[s(517)],e[s(466)])){if(_0x458483.length!==4){let z=_0x1a590c.substring(0,e[s(1511)](4,_0x3a285b[s(721)])),G=z.concat(_0x13453e);_0x2faf16.push(G)}else _0x1b1712[s(1475)](_0x5b4f8e);_0x3141e8&&(_0x4f373b+=1),_0x550bdb+=1,_0x247075=!1}else this[s(1141)+s(977)+s(362)](a),await L[s(867)](p,e[s(255)](Date.now(),_));return e.OrJjy(n)}if(w)if(e[s(1010)]!==e[s(1010)]){let j=this._qosDB[s(1028)](this[s(1458)]),z=_0x16ee88[s(1221)](e[s(787)](j,"{}"));return _0x2e97b8[s(695)](z)}else{let j=await _l.call(this);if(!j)return this[s(1141)+"hMessage"+s(362)](a),e[s(1002)](n);let z=await j[s(531)](C)??-1;if(e[s(240)](z,N))this[s(1141)+"hMessage"+s(362)](a),j[s(867)](C,N,a[s(1215)][s(148)]);else throw new Error(s(929)+s(417)+s(921)+N+(s(325)+s(221)+s(1601)+"r ")+z);return e[s(1002)](n)}return this[s(1141)+s(977)+s(362)](a),e[s(947)](n)}}async function yg(a,n){let s=t,l=ga.call(this,a);if(!l[s(1033)+s(928)])return e[s(1030)](n);let h=await ml.call(this);if(l[s(1653)+s(495)+"age"]&&l[s(1044)+"s"][s(721)])for(let p of l[s(1044)+"s"])await h.del(p);n()}async function Eg(a,n){let s=t,l=e.qdvic(a[s(1215)][s(1253)+"e"],hg),h=a[s(1215)][s(1253)+"e"]===_a;if(e[s(1252)](!l,!h))return e[s(1063)](n);let p=e[s(170)](ir,a.message[s(1635)],e[s(1382)]);if(!p)return e[s(897)](n);let _=await _l[s(1363)](this,p);if(!_)return e.emJgD(n);if(l)if(e[s(903)](e[s(781)],e[s(781)])){let v=await _[s(419)+"rs"](),w={frameType:v?.[s(1253)+"e"],SeqID:xe[s(1543)+"er"](this[s(729)]++),LogID:xe.fromNumber(this[s(497)]["logIDGen"+s(885)]()),service:9e3,method:5,headers:v?.headers,payload:v?.[s(955)]},C=S(w);this[s(212)]&&this[s(212)][s(1262)+"te"]&&this[s(212)].send(C)}else{let v=e[s(297)](e[s(435)](e.PMCev(7,_0x38cc46)<<18|e[s(406)](e[s(387)](63,_0x56918f[_0x6d11dd++]),12),e[s(331)](63&_0xeaca21[_0x44f1ca++],6)),e.bqcjU(63,_0x36229f[_0x3f02ff++]))-65536;_0x4a99f3+=_0x2da415["fromChar"+s(1503)](e[s(490)](55296,v>>10)),_0x1023b4+=_0x1b3ee8[s(464)+s(1503)](e.ZIXiA(56320,e[s(905)](1023,v)))}if(h){let v=a[s(1215)][s(955)];v&&_[s(1196)+"rs"](v)}}let bg=async function(a,n){let s=t;this[s(1022)]=!1,e.VQIVM(clearTimeout,this["_connect"+s(1312)+s(379)]),e[s(1508)](n)},vg=async function(a,n){let s=t;if(!this[s(212)]||this[s(212)][s(1262)+"te"]!==this[s(1371)])return e[s(1313)](n);let{pingInterval:l}=this._options;this[s(778)+"tManager"]?.[s(746)+s(644)+s(1512)]();for(let p=0;p<this[s(541)+"Queue"][s(721)];p++)if(e[s(1114)](e[s(1248)],e.hdmJk)){let _=this[s(541)+"Queue"][p];if(this._ws[s(1262)+"te"]===this.OPEN&&e.uBdeN(null,_))this[s(212)]&&this[s(212)][s(776)](_),this["_message"+s(836)][p]=null;else break}else return new _0x2d1964(_0x1d010b,{message:_0x3eadcf,code:_0x43eaf1,error:_0x5277ae});this[s(541)+s(836)]=this[s(541)+s(836)][s(291)](p=>!!p),this["_pingPon"+s(238)+"Id"]=e.gEIgB(setTimeout,()=>this[s(774)](),l),this[s(1141)+s(1457)+"nt"](a),this._isBrowser&&this[s(212)]&&(this[s(212)].binaryType=this[s(741)+s(572)]);let h=this["_endpoin"+s(530)]?.[s(244)+"ntEndpoint"]();this[s(830)](s(335)+h+s(1310)),n()},Sg=async function(a,n){let s=t,l=this[s(778)+s(530)]?.[s(244)+s(592)+"nt"]();this[s(830)]("open "+l),e.geMbc(n)};class Ig extends ha{constructor(n){let s=t,l={kiyex:function(v,w){return v>>>w},oQIVf:function(v,w){return e[H(1209)](v,w)},bhCBC:function(v,w){return e[H(1444)](v,w)},PAwMo:function(v,w,C,N){return v(w,C,N)},WIAJq:function(v,w){return v===w},MwkMk:s(1053),bpXqh:e[s(718)],KdSUL:e[s(1377)],iKlQn:e[s(518)],WIuij:function(v,w){return e[s(1639)](v,w)},LaEgd:e[s(1483)],WbwTZ:e.drvTt,EhEqE:"success",yuFsJ:function(v,w,C){return e[s(1023)](v,w,C)}};super(),this[s(1615)+s(1595)+s(418)]=!0,this._isBrowser=rr,this[s(1176)]=qp,this[s(216)+"T"]=Pn,this[s(323)+"X"]=Xr,this[s(430)+"r"]=Qr,this[s(541)+s(836)]=[],this[s(778)+s(530)]=null,this[s(717)+s(1673)]=!1,this[s(741)+s(572)]=e[s(1386)],this._connectLock=!1,this[s(823)+s(1312)+"utId"]=null,this[s(389)+s(1607)+"tId"]=null,this[s(1396)+s(238)+"Id"]=null,this[s(729)]=0,this[s(1022)]=!1,this[s(865)]="",this[s(1425)+s(1485)]=null,this[s(1112)+s(1289)]=null,this[s(1622)+"sCounter"]=null,this[s(1509)+"ls"]=e[s(492)],this[s(203)]=3,this[s(1490)+"NG"]=0,this[s(1371)]=1,this[s(1186)]=2,this[s(771)]=v=>{let w=s,C={RoDaG:function(N,L){return l[H(1408)](N,L)},iNMmN:function(N,L){return N&L},eXwhO:function(N,L){return l[H(1131)](N,L)},sCcwc:function(N,L){return N|L},xhxHG:function(N,L){return l[H(1577)](N,L)},gwcCz:function(N,L){return N<L}};try{l.PAwMo(fl,this,v,[bg,vg,Sg])}catch(N){if(l[w(1593)](l[w(751)],l.bpXqh)){let L={EEdmv:function(z,G){let fe=w;return lOqklo[fe(1147)](z,G)},WPlZN:function(z,G){let fe=w;return lOqklo[fe(1042)](z,G)},gqCQm:function(z,G){let fe=w;return lOqklo[fe(665)](z,G)},pbFMJ:function(z,G){let fe=w;return lOqklo[fe(1237)](z,G)},rNvHe:function(z,G){return lOqklo.iNMmN(z,G)},teZry:function(z,G){return lOqklo.sCcwc(z,G)},xNjIp:function(z,G){return lOqklo.xhxHG(z,G)},jEsOP:function(z,G){let fe=w;return lOqklo[fe(727)](z,G)},pXRHF:function(z,G){let fe=w;return lOqklo[fe(727)](z,G)},JmTYB:function(z,G){return z>G},uciiW:function(z,G){return z|G}},j=4294967295;return function(z,G,fe=!0){let ie=w;if(j=L[ie(1423)](L[ie(1602)](127,z[G]),0),L[ie(907)](z[G++],128))return{value:fe?j:0|j,offset:G};if(j=L[ie(1423)](j|(127&z[G])<<7,0),L.gqCQm(z[G++],128))return{value:fe?j:0|j,offset:G};if(j=L[ie(1469)](j,L[ie(1694)](127,z[G])<<14)>>>0,z[G++]<128)return{value:fe?j:L[ie(1058)](0,j),offset:G};if(j=(j|L[ie(1051)](L[ie(1602)](127,z[G]),21))>>>0,L.jEsOP(z[G++],128))return{value:fe?j:L[ie(1469)](0,j),offset:G};if(j=L[ie(1423)](L[ie(1469)](j,L[ie(1051)](15&z[G],28)),0),L[ie(396)](z[G++],128))return{value:fe?j:L[ie(1469)](0,j),offset:G};if(L[ie(308)](G+=5,z[ie(721)]))throw G=z.length,_0x2cddca(G,10,z[ie(721)]);return{value:fe?j:L[ie(1149)](0,j),offset:G}}}else{let L=lt(l.KdSUL,{message:N[w(1215)],code:sn[w(176)+"OR"],error:N});this[w(1141)+w(1659)+w(972)](L)}}},this[s(1441)+"ge"]=async v=>{let w=s,{pingInterval:C,pingFrequency:N}=this[w(497)];if((l[w(1593)]("hi",v[w(450)])&&l[w(1593)](l[w(454)],N)||l[w(888)](l[w(1699)],N))&&(this[w(344)+"ngTimer"](),this[w(1701)](l[w(1284)],l[w(1210)]),this["_pingPon"+w(238)+"Id"]=l[w(234)](setTimeout,this._ping[w(280)](this),C)),!l.WIuij("hi",v[w(450)]))try{l[w(798)](fl,this,v,[ng,eg,yg,Eg,_g,tg])}catch(L){let j=l[w(234)](lt,l.KdSUL,{message:L[w(1215)],code:sn[w(1481)+w(1014)],error:L});this["_dispatc"+w(1659)+w(972)](j)}},this._onError=v=>{let w=s,C=this[w(778)+w(530)]?.[w(1229)+w(993)+"es"](),N=this[w(778)+w(530)]?.[w(244)+"ntEndpoint"]();if(C&&!v.message){let L="connect "+N+(" fail, m"+w(1345)+w(760)+"ed");this[w(1141)+w(1659)+w(972)](lt(l[w(613)],{message:L,code:sn["MAX_RETR"+w(1094)+"R"],error:v}));return}this._ws&&this[w(212)][w(1262)+"te"]===this[w(1371)]&&this["_disconn"+w(734)](),this[w(1141)+"hErrorEvent"](lt(l[w(613)],{message:v[w(1215)],code:sn[w(184)+w(777)],error:v}))},this._onClose=async v=>{let w=s;this[w(1379)+w(549)](),this[w(344)+w(375)](),this[w(656)+w(511)+"rs"](),this[w(212)]=null,this[w(823)+w(410)]=!1;let C=this[w(778)+w(530)]?.[w(1229)+w(993)+"es"]();if(!C&&this[w(177)+w(1504)]()&&!this[w(717)+"osed"]){let N=this._endpointManager?.["getCurre"+w(592)+"nt"](),L=this[w(497)][w(1242)+w(1282)+w(1234)](v[w(731)],v[w(714)]);this[w(1141)+w(479)+"ent"](e[w(912)](mt,e[w(1106)],{code:1006,reason:v[w(714)]||w(1538)+"ng faile"+w(542)+"wn reaso"+w(1311)+w(890)+N,willReconnect:L})),L&&this[w(823)]();return}if(e[w(1523)](1e3,v.code)&&this[w(717)+w(1673)]){this[w(1141)+w(479)+w(972)](mt(e[w(1106)],{code:1e3,reason:e[w(757)]})),this[w(778)+w(530)]?.[w(746)+"pointCon"+w(1512)](),this[w(1622)+w(1090)]?.[w(1369)+"nter"]();return}if(e[w(619)](1e3,v.code)&&C){let N=this[w(778)+w(530)]?.[w(244)+w(592)+"nt"](),L=v.reason;L||(L=await e.zJKYK(Vp,this[w(865)])),L=w(1538)+"ng faile"+w(924)+L+(w(1228)+w(241))+N+(", max re"+w(874)+"ached"),this["_dispatc"+w(479)+"ent"](e.WppUS(mt,"close",{code:v[w(731)],reason:L}));let j=w(1430)+N+(w(1610)+"ax retries reached");this[w(1141)+w(1659)+w(972)](e[w(899)](lt,e[w(1377)],{message:j,code:sn["MAX_RETR"+w(1094)+"R"]})),this["_endpoin"+w(530)]?.[w(746)+w(644)+"fig"](),this[w(1622)+"sCounter"]?.[w(1369)+"nter"]();return}if(e[w(988)](1e3,v[w(731)])&&!v.reason){let N=this[w(778)+w(530)]?.["getCurre"+w(592)+"nt"]();this[w(1141)+w(479)+w(972)](e[w(200)](mt,e[w(1106)],{code:v[w(731)],reason:w(1538)+"ng failed, unkno"+w(1613)+w(1311)+w(890)+N})),this[w(778)+w(530)]?.["resetEnd"+w(644)+w(1512)](),this[w(1622)+w(1090)]?.[w(1369)+w(196)]();return}this[w(1141)+w(479)+w(972)](v),this[w(778)+w(530)]?.[w(746)+"pointCon"+w(1512)](),this[w(1622)+w(1090)]?.[w(1369)+"nter"]()},this[s(537)]=null,this[s(892)]=null,this.onmessage=null,this.onopen=null,this["onStartR"+s(1656)]=null,this[s(186)+s(1193)]=null,this[s(237)+s(1089)+"yReconnect"]=null,this["_handleO"+s(711)]=this[s(1395)+s(711)].bind(this),this["_handleO"+s(474)]=this["_handleO"+s(474)].bind(this),this[s(352)+"ageHide"]=this["_handleP"+s(485)][s(280)](this),this["_handleP"+s(1152)]=this["_handleP"+s(1152)][s(280)](this),this[s(497)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1700)](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(1483)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:p}=n,_=Array[s(1120)](h)?h:e.oMvOM==typeof h?[h]:[];if(!_||e.zJXDQ(0,_[s(721)]))throw new Error(s(1156)+s(1581)+"alid url");if(!e.sklEe(jp,p))throw new Error(e.RWWZU);Object[s(1105)](this[s(497)],n),this[s(778)+s(530)]=new ul(_,this[s(497)][s(288)+"es"]),this["_pingLos"+s(1090)]=new $p(this[s(497)][s(318)+s(578)]),this[s(497)][s(1471)+s(1666)]&&(this[s(1022)]=!0,this[s(823)]()),this[s(497)][s(1143)+"tworkCha"+s(981)]&&(this._isMiniTT||this[s(323)+"X"]?this[s(1439)+s(854)+s(1015)]():this._isBrowser&&this[s(1258)+"balEventListener"]())}[t(1395)+t(711)](){let n=t;this[n(497)][n(694)+n(1626)+n(235)]||this[n(717)+n(1673)]||this["_handleR"+n(1656)]()}[t(1395)+t(474)](){let n=t;if(e[n(844)](e.OcfjX,e[n(825)]))this.on(_0x3c28a6,_0x9daf16);else{this["_destroy"+n(893)+"t"]();let s=e[n(1337)](fa,n(1242)+"t",{message:e.hmDtO});this["onStopImmediatel"+n(228)+"ct"]&&this[n(237)+n(1089)+n(228)+"ct"](s)}}[t(1258)+t(602)+t(799)](){let n=t;this._isBrowser&&window[n(515)+"Listener"](n(1073),this[n(1395)+n(711)]),this._isBrowser&&window[n(515)+n(799)](n(1325),this[n(1395)+n(474)]),this[n(1179)+"er"]&&window[n(515)+"Listener"](n(1281),this[n(352)+"ageHide"]),this._isBrowser&&window.addEventListener(e[n(167)],this[n(352)+"ageShow"])}[t(715)+t(602)+t(799)](){let n=t;this[n(1179)+"er"]&&window[n(1100)+n(438)+n(1025)](n(1073),this[n(1395)+n(711)]),this[n(1179)+"er"]&&window["removeEv"+n(438)+n(1025)](e[n(364)],this[n(1395)+n(474)]),this[n(1179)+"er"]&&window[n(1100)+n(438)+n(1025)](e[n(1453)],this["_handleP"+n(485)]),this[n(1179)+"er"]&&window[n(1100)+n(438)+n(1025)](e[n(167)],this._handlePageShow)}[t(352)+t(485)](n){let s=t;!n[s(857)+"d"]&&(this[s(1179)+"er"]&&window[s(1100)+s(438)+s(1025)](s(1281),this[s(352)+s(485)]),this[s(1179)+"er"]&&window[s(1100)+s(438)+s(1025)](e[s(167)],this[s(352)+"ageShow"]),this[s(966)]()),this._isBrowser&&window[s(1100)+"entListener"](e[s(1026)],this["_handleO"+s(711)]),this._isBrowser&&window[s(1100)+s(438)+s(1025)](e.GuCYa,this[s(1395)+s(474)])}[t(352)+"ageShow"](n){let s=t;n[s(857)+"d"]&&(this[s(177)+s(1504)]()&&(!this[s(212)]||this[s(212)].readyState!==this.OPEN||e[s(1552)](this[s(212)].readyState,this[s(1490)+"NG"]))&&this[s(1395)+s(711)](),this._isBrowser&&window[s(515)+s(799)](e[s(1026)],this["_handleO"+s(711)]),this[s(1179)+"er"]&&window["addEvent"+s(799)]("offline",this[s(1395)+"ffLine"]))}async[t(441)+t(284)](n){let s=t,l={aPtaT:function(h,p){return h===p},myHJu:function(h,p){return e.Vycrx(h,p)},jDnhz:function(h,p){return e.ISkJI(h,p)},wJaQF:function(h,p){return e[H(1570)](h,p)},TAfGK:function(h,p){return e[H(316)](h,p)},hFPRc:function(h,p){return h|p},JpVDk:function(h,p){return e[H(1655)](h,p)},eVSVn:function(h,p){return e.xrLmK(h,p)},RmSOD:function(h,p){return e[H(868)](h,p)}};if(e[s(1008)](e[s(1331)],s(1201))){let{fpID:h,deviceID:p,bddID:_,ttwID:v,accessKey:w,aID:C,customParams:N={},enableAutoAck:L,enableQoS:j,QoSLevel:z,env:G}=this[s(497)],fe,ie,wt;if(this[s(1179)+"er"]||this[s(323)+"X"]||this[s(216)+"T"])if(e[s(742)]!==e.CHMXA)fe=location&&e[s(1631)](e[s(1171)],location[s(1411)])?e[s(1257)]:e.CnLKx,ie=n.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),wt=/^wss(.*:\/\/)/.test(n)?n:""+fe+ie;else return wWeRxR.aPtaT(_0x5c21d2,_0x42cbd4)?_0x419e43:new _0x2851a6(wWeRxR.myHJu(wWeRxR[s(555)](wWeRxR[s(555)](wWeRxR.jDnhz(_0x47adef[s(1363)](_0x522c23,0),wWeRxR[s(1518)](_0x1aec5e[s(1363)](_0x124162,1),8)),wWeRxR[s(1518)](_0x447f01[s(1363)](_0x38f976,2),16)),_0x53e4ac[s(1363)](_0x29531a,3)<<24),0),wWeRxR.myHJu(wWeRxR.TAfGK(wWeRxR[s(669)](wWeRxR[s(1618)](_0x2c0db5[s(1363)](_0x5a2d15,4),wWeRxR.JpVDk(_0x3fd245[s(1363)](_0x836ade,5),8)),wWeRxR.eVSVn(_0x360bdd[s(1363)](_0x26b537,6),16)),wWeRxR[s(394)](_0x4bbbfe[s(1363)](_0x3c43ad,7),24)),0),!0);else fe=e.MFKOU,ie=n[s(270)](/(^http)((?:[s]*:\/\/))/,""),wt=/(^ws)((?:[s]*:\/\/))/.test(ie)?ie:""+fe+ie;let ya=_?e.SkwCB:v?e[s(451)]:e[s(1268)],yl=_||v||p;if(!yl||!ya)throw new Error(e[s(914)]);let Ag=e[s(1631)](e.JOLfr,typeof N)?await e.hoeZs(N):N,kg=G?e.KpRwz(Kp,G[s(1169)],G[s(1621)]):{},Ea=Object[s(1105)]({device_platform:s(796),version_code:e[s(1443)],access_key:w,fpid:h,aid:C,[ya]:yl,xsack:L?1:0,xaack:L?1:0,xsqos:j?1:0,qos_level:j?z:void 0,qos_sdk_version:2,...kg},Ag),Tg=Object.keys(Ea)[s(946)]((ba,va)=>Ea[va]!==void 0?""+ba+(ba?"&":"?")+va+"="+Ea[va]:ba,"");return wt+s(1388)+Tg}else _0x506a19(xJiVKM[s(1233)](_0x8238e0,_0x4afb80[s(792)]),_0x58dbf2[s(1266)+"on"],_0x3c4b20.newVersion,xJiVKM[s(616)](_0xd303eb,_0x38b01d[s(837)+s(346)]))}async[t(823)](){let n=t;if(!(this[n(823)+"Lock"]||this[n(717)+n(1673)])){this[n(823)+"Lock"]=!0;try{let s=this["_endpoin"+n(530)]?.["checkCur"+n(864)+n(779)+n(1372)+n(1424)](),{timeoutInterval:l}=this._options;if(s){let p=this[n(778)+"tManager"]?.[n(244)+"ntEndpoint"](),_=this[n(778)+n(530)]?.[n(980)+"ackupEnd"+n(1190)+"UpdateCo"+n(1102)](),v=this[n(778)+"tManager"]?.["getCurrentEndpoi"+n(229)+n(1634)]();if(_){let w="connect "+p+(n(1380)+n(463)+n(874)+n(987)+n(1583)+n(580)+n(1434))+_+(n(756)+"y"),C=e[n(750)](lt,n(571),{message:w,code:sn[n(403)+"IES_ERROR"]});this[n(830)](w),this["_dispatchErrorEv"+n(972)](C),this[n(865)]=await this[n(441)+n(284)](_),this._debug("connect "+_+" "+v+n(265)),this["_removeW"+n(511)+"rs"]()}else{let w="connect "+p+(n(1380)+", max re"+n(874)+n(1359));this[n(830)](w),this[n(1141)+"hErrorEv"+n(972)](e.UNYIH(lt,e[n(1377)],{message:w,code:sn[n(403)+"IES_ERROR"]}));return}}else{let p=this[n(778)+n(530)]?.[n(244)+"ntEndpoi"+n(160)+n(1528)](),_=this[n(778)+n(530)]?.[n(244)+"ntEndpoi"+n(229)+n(1634)]();this[n(865)]=await this[n(441)+n(284)](p||""),this[n(830)](n(1430)+p+" "+_+" times"),this[n(656)+n(511)+"rs"]()}if(this[n(1022)])this._isInit=!1;else{let p=e.UDkMV(fa,e[n(1188)],{message:"start"});this[n(1189)+n(1656)]&&this["onStartR"+n(1656)](p)}let h=this[n(778)+n(530)]?.[n(244)+n(592)+"ntTriesC"+n(1634)]()||0;h>1&&await this[n(1011)](e[n(858)](h,1)),this._debug(n(1538)+n(248)+this[n(865)]+(n(1185)+"ls: ")+this[n(1509)+"ls"]),this[n(212)]=e.KHZTR(Hp,{url:this[n(865)],protocols:[this[n(1509)+"ls"]],headers:this[n(497)][n(540)+n(925)+"s"][n(583)+n(1032)]},this[n(497)].ws),(this._isBrowser||this[n(430)+"r"])&&this[n(212)]&&(this[n(212)][n(246)+"pe"]=this._binaryType),this["_addWsLi"+n(1588)](),this[n(823)+n(1312)+n(379)]=e.yFfjV(setTimeout,this._onTimeout[n(280)](this),l)}catch(s){throw this[n(823)+n(410)]=!1,s}}}["_clearTi"+t(549)](){let n=t;e[n(447)](e[n(1078)],e[n(1078)])?this.emit(e[n(1377)],_0x30258f(e.cuMvz,{message:this[n(1624)+n(719)+n(1367)](_0x4d1f53)})):(e[n(448)](clearTimeout,this["_connect"+n(1312)+n(379)]),this[n(823)+n(1312)+"utId"]=null)}_clearPingTimer(){let n=t;e.FntjX(clearTimeout,this[n(1396)+"gTimeoutId"]),e[n(582)](clearTimeout,this[n(389)+n(1607)+n(267)]),this[n(1396)+n(238)+"Id"]=null,this["_reconne"+n(1607)+n(267)]=null}[t(830)](...n){let s=t;this[s(497)][s(1332)]&&console[s(567)][s(550)](console,[e[s(225)],...n])}[t(1212)+t(1135)+"e"](n){let s=t;if(e[s(1496)](e[s(171)],e[s(1633)]))this[s(1615)+s(1595)+s(418)]=_0x5655a0,_0x1b8bff?this[s(1395)+s(711)]():this[s(1395)+s(474)]();else{let{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:p}=this._options,_=e.mOqaI(l,Math[s(207)](p,n-1));return e[s(843)](_,h)?h:_}}[t(774)](){let n=t;if(e[n(164)](n(1324),"MAywG"))return this["_dispatc"+n(977)+n(362)](_0xeabf4f),_0x49f964();if(this._ws&&e[n(887)](this[n(212)][n(1262)+"te"],this.CONNECTING)){this[n(344)+n(375)](),this[n(1396)+n(238)+"Id"]=e.lkRSh(setTimeout,this[n(774)][n(280)](this),this[n(497)][n(261)+n(1132)]);return}if(!this[n(212)]||e[n(676)](this._ws[n(1262)+"te"],this.OPEN))return void this[n(1177)+"econnect"]();this[n(212)]&&this[n(212)][n(776)]("hi"),this[n(389)+n(1607)+n(267)]=e[n(422)](setTimeout,this["_handleReconnect"+n(933)][n(280)](this),this[n(497)][n(1045)+n(831)+"val"])}[t(1177)+t(1656)+t(933)](){let n=t;this[n(1622)+n(1090)]?.addCount(),this[n(1701)](e[n(672)],e[n(1295)]),this[n(1622)+"sCounter"]?.checkReachMaxCount()?this[n(1177)+n(1656)]():this._ping()}[t(177)+"orOnline"](){let n=t,s={WdjZk:function(l){return e.geMbc(l)}};if(e[n(951)]!==e.XIxnD)uDbglv[n(1057)](_0x3b7513),_0x217480();else return this[n(216)+"T"]||this[n(323)+"X"]?this["_miniNav"+n(1595)+n(418)]:(this._isBrowser||this[n(430)+"r"])&&this[n(497)][n(1143)+n(812)+n(981)]?navigator[n(1351)]:!0}[t(1177)+t(1656)](){let n=t;!this._navigatorOnline()||this["_readyCl"+n(1673)]||(this[n(778)+n(530)]?.["resetEnd"+n(644)+"fig"](),this[n(1622)+n(1090)]?.[n(1369)+"nter"](),this[n(212)]?this[n(568)+n(734)](1001,e[n(1122)],!0):this._connect())}["_onPageN"+t(854)+t(1015)](){let n=t;this[n(216)+"T"]?tt["onNetwor"+n(818)+n(1178)](({isConnected:s})=>{let l=n;this[l(1615)+l(1595)+"line"]=s,s?this[l(1395)+l(711)]():this[l(1395)+l(474)]()}):this[n(323)+"X"]&&wx[n(157)+"kStatusC"+n(1178)](({isConnected:s})=>{let l=n;this[l(1615)+l(1595)+"line"]=s,s?this["_handleO"+l(711)]():this[l(1395)+l(474)]()})}[t(1011)](n){return new Promise(s=>{let l=H;e[l(1086)](setTimeout,s,this["_getInte"+l(1135)+"e"](n))})}[t(568)+t(734)](n=1e3,s="",l=!1){let h=t;this[h(212)]&&this[h(1335)+h(893)+"t"](n,s,l)}[t(395)+"ut"](){let n=t,s=this[n(778)+n(530)]?.[n(244)+n(592)+"nt"]();this[n(830)]("connect "+s+n(1380)),this[n(568)+n(734)](1001,e[n(1198)],!0)}_sendAck(n){let s=t,l=qt(n);this[s(212)]&&e[s(312)](this[s(212)][s(1262)+"te"],this.OPEN)&&(this[s(212)]&&this[s(212)][s(776)](l),this[s(830)](e[s(1321)],n))}[t(656)+t(511)+"rs"](){let n=t,s=e[n(1361)][n(1480)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[n(212)])return;continue;case"1":this[n(212)][n(1100)+n(438)+n(1025)](e.jxicE,this[n(1441)+"ge"]);continue;case"2":this[n(212)]["removeEv"+n(438)+n(1025)](e.Iyrmc,this[n(551)]);continue;case"3":this[n(212)]["removeEv"+n(438)+"ner"](e[n(1482)],this._onOpen);continue;case"4":this[n(212)]["removeEventListe"+n(1025)](e[n(1377)],this[n(1006)]);continue}break}}[t(1047)+t(1588)](){let n=t;if(e[n(528)](e.fhcKE,n(880))){if(!this[n(212)])return;this[n(212)][n(515)+"Listener"](e.ufMwp,this[n(771)]),this[n(212)]["addEvent"+n(799)](e[n(1106)],this[n(551)]),this[n(212)]["addEvent"+n(799)](e[n(1067)],this._onMessage),this[n(212)]["addEvent"+n(799)](e[n(1377)],this._onError)}else this["_addWsLi"+n(1588)]()}[t(409)+"nceClose"](n=1e3,s=""){let l=t;try{this[l(212)]&&this._ws.close(n,s)}catch{}}[t(1335)+t(893)+"t"](n=1e3,s="",l=!1){let h=t;if(this["_clearPi"+h(375)](),this[h(1379)+"mer"](),this[h(656)+h(511)+"rs"](),this[h(409)+h(708)](1e3,s),this[h(823)+"Lock"]=!1,l&&this[h(177)+h(1504)]()&&!this._readyClosed){if(this["_endpoin"+h(530)]?.[h(1229)+"chMaxTries"]()){let _=this[h(778)+h(530)]?.["getCurre"+h(592)+"nt"]();this[h(1141)+h(479)+h(972)](e[h(422)](mt,e.Iyrmc,{code:1006,reason:h(1430)+_+(h(1380)+h(463)+h(874)+h(1359)),wasClean:!0}))}else if(h(643)===h(643)){let _=this[h(497)][h(1242)+h(1282)+h(1234)](n,s);this[h(1141)+"hCloseEvent"](e[h(1517)](mt,e.Iyrmc,{code:n,reason:s,wasClean:!0,willReconnect:_})),_&&this[h(823)]()}else this[h(1138)]=_0x2a82ef,this[h(1693)]=_0x41e234,this[h(1129)]=_0x27d5b2?_0x18d3b2:_0xa76023?_0x220500:null;return}this[h(177)+"orOnline"]()||this["_readyCl"+h(1673)]?this["_dispatc"+h(479)+"ent"](e[h(646)](mt,e[h(1106)],{code:n,reason:e[h(757)]})):this[h(1141)+"hCloseEv"+h(972)](mt(e[h(1106)],{code:1006,reason:e[h(470)]})),this[h(212)]=null,this["_endpoin"+h(530)]?.[h(746)+"pointCon"+h(1512)](),this["_pingLos"+h(1090)]?.[h(1369)+h(196)]()}[t(1141)+t(1457)+"nt"](n){let s=t;this[s(1701)](s(1184),n),this[s(1535)]&&this.onopen(n)}["_dispatc"+t(977)+"Event"](n){let s=t;this[s(1701)](e[s(1067)],n),this.onmessage&&this.onmessage(n)}["_dispatc"+t(1163)+"ageEvent"](n){let s=t;this.emit(e[s(1627)],n),this[s(186)+s(1193)]&&this[s(186)+s(1193)](n)}["_dispatchErrorEv"+t(972)](n){let s=t;this.emit(e.cuMvz,n),this[s(892)]&&this[s(892)](n)}[t(1141)+t(479)+t(972)](n){let s=t;this[s(1701)](s(966),n),this[s(537)]&&this[s(537)](n)}get[t(246)+"pe"](){let n=t;if(e[n(806)](n(1660),e[n(784)]))return this[n(212)]?this._ws.binaryType:this[n(741)+"ype"];{let s=_0x1c0f01.split(":");_0x490307&&(_0x185e85=s[n(721)]),_0x3fd069+=s[n(721)];for(let l=0;e.yeklR(l,s.length);l++)if(e[n(164)](4,s[l].length)){let h=_0x104670[n(1240)+"g"](0,e[n(871)](4,s[l][n(721)])),p=h.concat(s[l]);_0x1203f4[n(1475)](p)}else _0x3d83b9[n(1475)](s[l]);_0x3f201d=!1}}set[t(246)+"pe"](n){let s=t;this[s(741)+s(572)]=n,this[s(212)]&&(this._ws[s(246)+"pe"]=n)}get[t(1632)+"nt"](){let n=t;if(e[n(650)](e.zLusj,n(1658))){let{initReconnectInterval:s,maxReconnectInterval:l,reconnectIntervalGrowFactor:h}=this[n(497)],p=e[n(1056)](s,_0x11c546[n(207)](h,e[n(264)](_0x45e6c2,1)));return e[n(449)](p,l)?l:p}else return this["_endpoin"+n(530)]?.[n(244)+n(592)+n(229)+n(1634)]()||0}get[t(315)+t(1334)](){let n=t,s={INrGf:function(l,h){return l===h},cZUNL:function(l,h){return e.Ihcza(l,h)},Wdskw:function(l,h){return e[H(1115)](l,h)},wTOPL:"yLZTY",salCW:"ngKTk"};if(e.XLyiq(e.NbYkg,e[n(738)]))_0x28bc41[n(567)](_0x1da1d2);else return this[n(541)+n(836)].reduce((h,p)=>{let _=n;return s[_(154)](s[_(923)],s.salCW)?(_0x4fcc51[_(1669)](_0x325774)||(_0x455a0c=_0x3d0169[_(1543)+"er"](_0x3f7a2e)),this[_(533)]!==_0x48813a[_(533)]&&oCVxkM[_(154)](oCVxkM[_(1223)](this[_(1564)],31),1)&&oCVxkM.Wdskw(_0x544b91.high>>>31,1)?!1:this[_(1564)]===_0x32b485[_(1564)]&&oCVxkM[_(154)](this[_(1327)],_0x21726a[_(1327)])):(h+=p&&p.byteLength||0,h)},0)+(this._ws?this[n(212)][n(315)+"Amount"]:0)}get[t(1466)+"ns"](){let n=t;return this[n(212)]?this[n(212)][n(1466)+"ns"]:""}get[t(1411)](){let n=t;return this[n(212)]?this[n(212)][n(1411)]:""}get readyState(){let n=t;return this[n(212)]?this._ws[n(1262)+"te"]:this[n(497)].automaticOpen?this[n(1490)+"NG"]:this[n(203)]}get[t(735)](){let n=t;return this[n(212)]?this[n(212)][n(735)]:this[n(865)]}[t(966)](n=1e3,s){let l=t;if(e[l(445)](l(634),e[l(1520)]))_0x47d4ae="wss://",_0x46c1bf=_0x1b225d.replace(/(^http)((?:[s]*:\/\/))/,""),_0x8aec2b=/(^ws)((?:[s]*:\/\/))/[l(1476)](_0x53d845)?_0x382aa7:""+_0x43311c+_0x504de3;else{if(this._readyClosed=!0,this["_clearTi"+l(549)](),this[l(344)+"ngTimer"](),this["_dropGlo"+l(602)+l(799)](),this[l(1425)+l(1485)]?.[l(1687)](),!this[l(212)])return void this[l(830)](e[l(1101)]);if(this[l(212)][l(1262)+"te"]===this[l(203)]||e.xerXK(this[l(212)][l(1262)+"te"],this[l(1186)]))return void this[l(830)](e[l(478)]);this[l(1335)+l(893)+"t"](n,s)}}async[t(776)](n,s){let l=t;if(e[l(1273)]("dfJok","DNfjI")){if(e[l(1454)](null,n))throw new Error(e[l(822)]);e.MBLoh==typeof n&&(n=JSON[l(1235)+"y"](n)),typeof n!="string"&&!e.UyilZ(n,ArrayBuffer)&&!(n[l(1081)]&&e[l(1239)](n[l(1081)],ArrayBuffer))&&(n=JSON.stringify(n));let h=await e[l(199)](pl,n),p=e.gMBBK(Wp,n),{method:_=0,service:v=this._options[l(148)],logID:w=this[l(497)]["logIDGen"+l(885)](),headers:C=this[l(497)].headers,payloadEncoding:N=this[l(497)][l(1576)+l(1245)],payloadType:L=this[l(497)].payloadType,logIDNew:j=this[l(497)][l(400)+l(1052)][l(1405)+l(481)+l(462)+"ew"]?i(this[l(497)][l(400)+l(1052)][l(398)]):""}=s||{};if(!v)throw new Error(e[l(939)]);let z={SeqID:xe[l(1543)+"er"](this[l(729)]++),LogID:xe[l(1543)+"er"](w),service:v,method:_,headers:C,payloadEncoding:e[l(590)](N,Object)?N[l(424)]?N[l(424)]:"":N,payloadType:e[l(275)](L,Object)?L[l(482)]?L.type:p:L||p,payload:h,LogIDNew:j},G=e[l(166)](qt,z);return this[l(212)]&&e.FAAan(this._ws[l(1262)+"te"],this[l(1371)])?(this[l(212)]&&this[l(212)][l(776)](G),this[l(830)](e[l(739)],z)):e[l(1260)](this[l(541)+l(836)].length,this[l(497)][l(561)+"geQueueLength"])?(this[l(541)+l(836)][l(1475)](G),this[l(830)](e.PAwsz,z)):(this["_message"+l(836)][l(1445)](),this[l(541)+"Queue"].push(G)),{seqID:this[l(729)],logID:w,logIDNew:j}}else return this[l(212)]?this[l(212)][l(1411)]:""}async[t(1242)+"t"](n){let s=t,{url:l}=e.SxxVh(n,{}),h=Array[s(1120)](l)?l:e[s(436)](s(748),typeof l)?[l]:[];n&&Object[s(1105)](this[s(497)],n),h&&h[s(721)]?this[s(778)+s(530)]=new ul(h,this._options.maxRetries):this._endpointManager?.[s(746)+s(644)+s(1512)](),this._pingLossCounter?.[s(1369)+s(196)](this._options[s(318)+s(578)]),this["_readyCl"+s(1673)]=!1,this[s(212)]&&this[s(212)][s(1262)+"te"]!==this[s(203)]?this._disconnect(1e3,e[s(815)],!0):(this[s(1022)]=!0,this._connect())}async[t(1603)](){let n=t;if(e.asmZK(e[n(594)],e.LDYZN)){if(!this[n(823)+"Lock"]){let s=(n(982)+"4").split("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(1022)]=!0;continue;case"1":this[n(717)+n(1673)]=!1;continue;case"2":this["_pingLos"+n(1090)]?.[n(1369)+n(196)]();continue;case"3":this["_endpoin"+n(530)]?.[n(746)+n(644)+n(1512)]();continue;case"4":this[n(823)]();continue}break}}}else _0x53caf8=xJiVKM[n(649)](_0x3e29df,_0x349543)}[t(515)+t(799)](n,s){let l=t;e[l(744)](e[l(1304)],e[l(1304)])?this.on(n,s):(_0x576a58=_0x193ab5[e.pJzUe(_0x4db3ef+_0x17797d,1)],_0x1f9602=_0x40ac74[e[l(704)](_0x350ede,_0x2ea1a4)+2],e.CfvVC(e[l(1119)](_0xb73580|e[l(1227)](_0x444e40,8),49344),32896)?_0x52167e+=_0x225083:(_0x39a5b5=e[l(679)](e[l(1636)](e[l(978)](15,_0x18ffa4)<<12,e[l(189)](e[l(1091)](63,_0x500134),6)),e[l(1272)](63,_0x4d3feb)),e[l(1244)](_0x334f9c,2048)||e.tmGtg(_0x4552a8,55296)&&_0x570f07<=57343?_0xeb2c32+=_0x442623:(_0x5b7153+=_0x174c9e(_0x31edd8),_0x2e05a1+=2)))}[t(289)+"Event"](n){let{type:s}=n;this.emit(s,n)}[t(1100)+"entListener"](n,s){this[t(460)](n,s)}[t(360)](){let n=t,s={HUXGA:function(l,h){return e[H(764)](l,h)},hJEMh:e[n(660)],arhCN:e[n(210)],JssXD:n(328),BYHVa:function(l,h,p){return l(h,p)},cbFKQ:e[n(672)]};return new Promise((l,h)=>{let p=n,_={pyzPV:function(C,N){return s.HUXGA(C,N)},ylBcL:s[p(168)],uRKDm:s.arhCN,SKDyp:p(1027)+p(1150)+"t",XfQHY:s[p(532)]};this[p(344)+p(375)](),this["_pingPon"+p(238)+"Id"]=s.BYHVa(setTimeout,this[p(774)][p(280)](this),this[p(497)][p(261)+p(1132)]);let v=()=>{let C=p;_.pyzPV(l,_[C(1318)]),this[C(460)](_.uRKDm,v),this[C(460)](_[C(626)],w)},w=()=>{let C=p;_[C(952)](h,_[C(1075)]),this.off(_.uRKDm,v),this.off(C(1027)+"e_timeout",w)};this.on(s[p(504)],v),this.on(s[p(627)],w),this[p(774)]()})}}})(),ze[M(1208)+M(732)]=De[M(1208)+M(732)],ze.CustomErrorEvent=De[M(891)+M(1668)],ze[M(1349)+"e"]=De[M(1349)+"e"],ze.Event=De[M(362)],ze[M(716)]=De[M(716)],ze[M(374)+"MessageE"+M(359)]=De.FrontierMessageEvent,ze[M(1498)+"vent"]=De[M(1498)+M(359)],ze[M(701)+"t"]=De[M(701)+"t"],ze["Reconnec"+M(1034)]=De[M(835)+"tEvent"],ze[M(1197)+"oseEvent"]=De[M(1197)+"oseEvent"],ze[M(1288)+M(1668)]=De[M(1288)+M(1668)],ze[M(772)+M(1192)+"nt"]=De.createMessageEvent,ze[M(351)+M(162)]=De[M(351)+M(162)],ze["createRe"+M(1630)+M(359)]=De[M(1406)+M(1630)+M(359)],ze[M(601)+M(1283)]=De[M(601)+M(1283)],ze[M(944)+"ame"]=De[M(944)+M(1629)];for(Ho in De)[M(1208)+M(732),"CustomEr"+M(1668),M(1349)+"e","Event",M(716),M(374)+M(1498)+"vent",M(1498)+"vent",M(701)+"t",M(835)+M(1034),"createCloseEvent",M(1288)+M(1668),M(772)+M(1192)+"nt",M(351)+M(162),M(1406)+M(1630)+M(359),M(601)+M(1283),M(944)+M(1629)][M(1416)](Ho)===-1&&(ze[Ho]=De[Ho]);var Ho;Object[M(1175)+M(215)](ze,M(743)+"le",{value:!0})});import{existsSync as L1,openSync as N1}from"node:fs";import{mkdir as M1}from"node:fs/promises";import{dirname as B1}from"node:path";import{fileURLToPath as F1}from"node:url";function U1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Hd(t=ee()){return L1(t.libEntry)?t.libEntry:F1(new URL("../index.ts",import.meta.url))}async function Xx(t={}){let e=t.paths??ee(),r=t.entryOverride??Hd(e),i=U1(e,process.env.COZE_BRIDGE_LOG_MODE);await M1(B1(i),{recursive:!0});let o=N1(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=st(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[rs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return z1.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var z1,rs,ea=nt(()=>{"use strict";Jt();ne();Me();z1=W("spawn-daemon"),rs="COZE_BRIDGE_DAEMON"});import{spawn as BS}from"node:child_process";import{mkdir as FS,unlink as zS,writeFile as US}from"node:fs/promises";import{dirname as qS,join as GS}from"node:path";function Jr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function HS(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Jr(r)}</key>
21
+ <string>${Jr(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function Q1(t,e){return new Promise((r,i)=>{let o=K1(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 Jr,ds,da,tl,Sp=rt(()=>{"use strict";ne();Jr=H("supervisor.launchd"),ds="ai.coze.bridge",da=Q1,tl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function jS(t,e){return new Promise((r,i)=>{let o=BS(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 Vr,os,oa,Xd,Ep=nt(()=>{"use strict";ne();Vr=W("supervisor.launchd"),os="ai.coze.bridge",oa=jS,Xd={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
27
27
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28
28
  <plist version="1.0">
29
29
  <dict>
30
30
  <key>Label</key>
31
- <string>${ds}</string>
31
+ <string>${os}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Zr(t.nodeBin)}</string>
35
- <string>${Zr(t.entry)}</string>
34
+ <string>${Jr(t.nodeBin)}</string>
35
+ <string>${Jr(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>${Zr(t.logFile)}</string>
45
+ <string>${Jr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Zr(t.logFile)}</string>${Y1(t.env)}
47
+ <string>${Jr(t.logFile)}</string>${HS(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return X1(t.homeDir,"Library","LaunchAgents",`${ds}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await $1(Z1(i),{recursive:!0}),await J1(i,this.renderConfig(t),"utf8"),Jr.info("plist written",{plistPath:i,activate:r}),!r)return;await da("launchctl",["unload","-w",i]).catch(c=>Jr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await da("launchctl",["load","-w",i]),Jr.info("launchd job loaded",{label:ds});let o=process.getuid?.()??0;await da("launchctl",["kickstart","-k",`gui/${o}/${ds}`]),Jr.info("launchd job kickstarted",{label:ds,uid:o})},async uninstall(t){let e=this.configPath(t);await da("launchctl",["unload","-w",e]).catch(r=>Jr.warn("launchctl unload failed (ignored)",{err:String(r)})),await V1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Jr.info("launchd job removed",{plistPath:e})}}});import{spawn as eI}from"node:child_process";import{mkdir as tI,unlink as nI,writeFile as rI}from"node:fs/promises";import{dirname as iI,join as Ip}from"node:path";function ua(t,e){return t.isRoot?e:["--user",...e]}function oI(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function fa(t,e){return new Promise((r,i)=>{let o=eI(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 la,Xr,sI,nl,Ap=rt(()=>{"use strict";ne();la=H("supervisor.systemd"),Xr="coze-bridge.service",sI="/etc/systemd/system";nl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return GS(t.homeDir,"Library","LaunchAgents",`${os}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await FS(qS(i),{recursive:!0}),await US(i,this.renderConfig(t),"utf8"),Vr.info("plist written",{plistPath:i,activate:r}),!r)return;await oa("launchctl",["unload","-w",i]).catch(c=>Vr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await oa("launchctl",["load","-w",i]),Vr.info("launchd job loaded",{label:os});let o=process.getuid?.()??0;await oa("launchctl",["kickstart","-k",`gui/${o}/${os}`]),Vr.info("launchd job kickstarted",{label:os,uid:o})},async uninstall(t){let e=this.configPath(t);await oa("launchctl",["unload","-w",e]).catch(r=>Vr.warn("launchctl unload failed (ignored)",{err:String(r)})),await zS(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Vr.info("launchd job removed",{plistPath:e})}}});import{spawn as WS}from"node:child_process";import{mkdir as KS,unlink as $S,writeFile as VS}from"node:fs/promises";import{dirname as JS,join as bp}from"node:path";function ca(t,e){return t.isRoot?e:["--user",...e]}function YS(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function da(t,e){return new Promise((r,i)=>{let o=WS(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 aa,Zr,ZS,Qd,vp=nt(()=>{"use strict";ne();aa=W("supervisor.systemd"),Zr="coze-bridge.service",ZS="/etc/systemd/system";Qd={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
- ${oI(t.env)}
62
+ ${YS(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Ip(sI,Xr):Ip(t.homeDir,".config","systemd","user",Xr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await tI(iI(i),{recursive:!0}),await rI(i,this.renderConfig(t),"utf8"),la.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await fa("systemctl",ua(t,["daemon-reload"])),await fa("systemctl",ua(t,r?["enable","--now",Xr]:["enable",Xr])),la.info("systemd unit enabled",{unitName:Xr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await fa("systemctl",ua(t,["disable","--now",Xr])).catch(r=>la.warn("systemctl disable failed (ignored)",{err:String(r)})),await nI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await fa("systemctl",ua(t,["daemon-reload"])).catch(()=>{}),la.info("systemd unit removed",{unitPath:e})}}});import{spawn as aI}from"node:child_process";import{join as cI}from"node:path";function kp(t,e){return new Promise((r,i)=>{let o=aI(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 rl,ha,il,Tp=rt(()=>{"use strict";ne();rl=H("supervisor.taskscheduler"),ha="CozeBridge",il={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?bp(ZS,Zr):bp(t.homeDir,".config","systemd","user",Zr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await KS(JS(i),{recursive:!0}),await VS(i,this.renderConfig(t),"utf8"),aa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await da("systemctl",ca(t,["daemon-reload"])),await da("systemctl",ca(t,r?["enable","--now",Zr]:["enable",Zr])),aa.info("systemd unit enabled",{unitName:Zr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await da("systemctl",ca(t,["disable","--now",Zr])).catch(r=>aa.warn("systemctl disable failed (ignored)",{err:String(r)})),await $S(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await da("systemctl",ca(t,["daemon-reload"])).catch(()=>{}),aa.info("systemd unit removed",{unitPath:e})}}});import{spawn as XS}from"node:child_process";import{join as QS}from"node:path";function Sp(t,e){return new Promise((r,i)=>{let o=XS(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 el,la,tl,Ip=nt(()=>{"use strict";ne();el=W("supervisor.taskscheduler"),la="CozeBridge",tl={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,56 +86,50 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return cI(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 kp("schtasks",["/Create","/SC","ONLOGON","/TN",ha,"/TR",r,"/RU",t.userName,"/F"]),rl.info("task scheduler entry created",{task:ha,logFile:t.logFile})},async uninstall(t){await kp("schtasks",["/Delete","/TN",ha,"/F"]).catch(e=>rl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),rl.info("task scheduler entry removed",{task:ha})}}});var Cp={};ka(Cp,{buildContext:()=>xI,getSupervisor:()=>uI,launchdSupervisor:()=>tl,systemdSupervisor:()=>nl,taskSchedulerSupervisor:()=>il});import{homedir as dI,userInfo as lI}from"node:os";function uI(t=process.platform){switch(t){case"darwin":return tl;case"linux":return nl;case"win32":return il;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function hI(){let t={};for(let e of fI){let r=process.env[e];r&&(t[e]=r)}return t}function xI(){let t=ee();return{nodeBin:process.execPath,entry:Kd(t),logFile:t.logFile,homeDir:dI(),userName:lI().username,isRoot:process.getuid?.()===0,env:hI()}}var fI,Rp=rt(()=>{"use strict";Be();ra();Sp();Ap();Tp();fI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();dn();var Ll=H("acp-installer-warmup"),rm=["claude-code","codex"];async function Nl(t={}){let e=t.ensure??dr,i=(await Promise.allSettled(rm.map(async o=>{let c=await e(o);Ll.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Ll.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}fn();ne();import{readdir as _m}from"node:fs/promises";import{mkdir as zl,readFile as mm,writeFile as Ul}from"node:fs/promises";import{join as La}from"node:path";var wm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function fr(t,e,r){await zl(t,{recursive:!0});let i=wm[e],o=La(t,i);return await Ul(o,r??"","utf8"),o}async function Na(t,e,r){let i=La(t,".claude");await zl(i,{recursive:!0});let o=La(i,"settings.local.json"),c={};try{let u=await mm(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 Ul(o,JSON.stringify(c,null,2),"utf8"),o}var Qe=H("agent-detail-sync"),ym=6e4,bm=5*6e4,ys=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await _m(r)}catch(o){Qe.info("agents dir not found, skip detail sync",{root:r,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(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Qe.info("retrying pending detail syncs",{count:r.length});for(let i of r)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,r){let i=r??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(h){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),m=x?Math.min(x.currentDelay*2,bm):ym;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});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 fr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var od=jt(_u(),1);import{createHash as ry}from"node:crypto";import{lstat as Yc,mkdir as Qc,readFile as ho,readdir as s0,rm as ed,stat as id,writeFile as td}from"node:fs/promises";import{homedir as iy}from"node:os";import{basename as n0,dirname as sy,join as xe,normalize as oy,relative as sd,resolve as nd,sep as o0}from"node:path";import{Readable as a0}from"node:stream";import{pipeline as c0}from"node:stream/promises";import qm from"events";import st from"fs";import{EventEmitter as Nc}from"node:events";import tf from"node:stream";import{StringDecoder as jm}from"node:string_decoder";import sf from"node:path";import Sr from"node:fs";import{dirname as rw,parse as iw}from"path";import{EventEmitter as fw}from"events";import gc from"assert";import{Buffer as jn}from"buffer";import*as Su from"zlib";import hw from"zlib";import{posix as mr}from"node:path";import{basename as Gw}from"node:path";import Ys from"fs";import Pt from"fs";import Pu from"path";import{win32 as e_}from"node:path";import zu from"path";import yf from"node:fs";import m_ from"node:assert";import{randomBytes as bf}from"node:crypto";import ie from"node:fs";import ze from"node:path";import Ef from"fs";import ao from"node:fs";import ki from"node:path";import dt from"node:fs";import S_ from"node:fs/promises";import to from"node:path";import{join as Of}from"node:path";import ct from"node:fs";import Mf from"node:path";var Gm=Object.defineProperty,Hm=(t,e)=>{for(var r in e)Gm(t,r,{get:e[r],enumerable:!0})},yu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Wm=t=>!!t&&typeof t=="object"&&(t instanceof $n||t instanceof tf||Km(t)||$m(t)),Km=t=>!!t&&typeof t=="object"&&t instanceof Nc&&typeof t.pipe=="function"&&t.pipe!==tf.Writable.prototype.pipe,$m=t=>!!t&&typeof t=="object"&&t instanceof Nc&&typeof t.write=="function"&&typeof t.end=="function",Wt=Symbol("EOF"),Kt=Symbol("maybeEmitEnd"),xn=Symbol("emittedEnd"),Is=Symbol("emittingEnd"),di=Symbol("emittedError"),As=Symbol("closed"),bu=Symbol("read"),ks=Symbol("flush"),Eu=Symbol("flushChunk"),yt=Symbol("encoding"),gr=Symbol("decoder"),He=Symbol("flowing"),li=Symbol("paused"),br=Symbol("resume"),qe=Symbol("buffer"),et=Symbol("pipes"),je=Symbol("bufferLength"),Ga=Symbol("bufferPush"),Ts=Symbol("bufferShift"),Ye=Symbol("objectMode"),Ce=Symbol("destroyed"),Ha=Symbol("error"),qa=Symbol("emitData"),vu=Symbol("emitEnd"),ja=Symbol("emitEnd2"),Tt=Symbol("async"),Wa=Symbol("abort"),Cs=Symbol("aborted"),ui=Symbol("signal"),Nn=Symbol("dataListeners"),at=Symbol("discarded"),fi=t=>Promise.resolve().then(t),Vm=t=>t(),Jm=t=>t==="end"||t==="finish"||t==="prefinish",Zm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Xm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),nf=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[br](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ym=class extends nf{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)}},Qm=t=>!!t.objectMode,ew=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",$n=class extends Nc{[He]=!1;[li]=!1;[et]=[];[qe]=[];[Ye];[yt];[Tt];[gr];[Wt]=!1;[xn]=!1;[Is]=!1;[As]=!1;[di]=null;[je]=0;[Ce]=!1;[ui];[Cs]=!1;[Nn]=0;[at]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Qm(e)?(this[Ye]=!0,this[yt]=null):ew(e)?(this[yt]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[yt]=null),this[Tt]=!!e.async,this[gr]=this[yt]?new jm(this[yt]):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:r}=e;r&&(this[ui]=r,r.aborted?this[Wa]():r.addEventListener("abort",()=>this[Wa]()))}get bufferLength(){return this[je]}get encoding(){return this[yt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Tt]}set async(t){this[Tt]=this[Tt]||!!t}[Wa](){this[Cs]=!0,this.emit("abort",this[ui]?.reason),this.destroy(this[ui]?.reason)}get aborted(){return this[Cs]}set aborted(t){}write(t,e,r){if(this[Cs])return!1;if(this[Wt])throw new Error("write after end");if(this[Ce])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[Tt]?fi:Vm;if(!this[Ye]&&!Buffer.isBuffer(t)){if(Xm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Zm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ye]?(this[He]&&this[je]!==0&&this[ks](!0),this[He]?this.emit("data",t):this[Ga](t),this[je]!==0&&this.emit("readable"),r&&i(r),this[He]):t.length?(typeof t=="string"&&!(e===this[yt]&&!this[gr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[yt]&&(t=this[gr].write(t)),this[He]&&this[je]!==0&&this[ks](!0),this[He]?this.emit("data",t):this[Ga](t),this[je]!==0&&this.emit("readable"),r&&i(r),this[He]):(this[je]!==0&&this.emit("readable"),r&&i(r),this[He])}read(t){if(this[Ce])return null;if(this[at]=!1,this[je]===0||t===0||t&&t>this[je])return this[Kt](),null;this[Ye]&&(t=null),this[qe].length>1&&!this[Ye]&&(this[qe]=[this[yt]?this[qe].join(""):Buffer.concat(this[qe],this[je])]);let e=this[bu](t||null,this[qe][0]);return this[Kt](),e}[bu](t,e){if(this[Ye])this[Ts]();else{let r=e;t===r.length||t===null?this[Ts]():typeof r=="string"?(this[qe][0]=r.slice(t),e=r.slice(0,t),this[je]-=t):(this[qe][0]=r.subarray(t),e=r.subarray(0,t),this[je]-=t)}return this.emit("data",e),!this[qe].length&&!this[Wt]&&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[Wt]=!0,this.writable=!1,(this[He]||!this[li])&&this[Kt](),this}[br](){this[Ce]||(!this[Nn]&&!this[et].length&&(this[at]=!0),this[li]=!1,this[He]=!0,this.emit("resume"),this[qe].length?this[ks]():this[Wt]?this[Kt]():this.emit("drain"))}resume(){return this[br]()}pause(){this[He]=!1,this[li]=!0,this[at]=!1}get destroyed(){return this[Ce]}get flowing(){return this[He]}get paused(){return this[li]}[Ga](t){this[Ye]?this[je]+=1:this[je]+=t.length,this[qe].push(t)}[Ts](){return this[Ye]?this[je]-=1:this[je]-=this[qe][0].length,this[qe].shift()}[ks](t=!1){do;while(this[Eu](this[Ts]())&&this[qe].length);!t&&!this[qe].length&&!this[Wt]&&this.emit("drain")}[Eu](t){return this.emit("data",t),this[He]}pipe(t,e){if(this[Ce])return t;this[at]=!1;let r=this[xn];return e=e||{},t===yu.stdout||t===yu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[et].push(e.proxyErrors?new Ym(this,t,e):new nf(this,t,e)),this[Tt]?fi(()=>this[br]()):this[br]()),t}unpipe(t){let e=this[et].find(r=>r.dest===t);e&&(this[et].length===1?(this[He]&&this[Nn]===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 r=super.on(t,e);if(t==="data")this[at]=!1,this[Nn]++,!this[et].length&&!this[He]&&this[br]();else if(t==="readable"&&this[je]!==0)super.emit("readable");else if(Jm(t)&&this[xn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[di]){let i=e;this[Tt]?fi(()=>i.call(this,this[di])):i.call(this,this[di])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Nn]=this.listeners("data").length,this[Nn]===0&&!this[at]&&!this[et].length&&(this[He]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Nn]=0,!this[at]&&!this[et].length&&(this[He]=!1)),e}get emittedEnd(){return this[xn]}[Kt](){!this[Is]&&!this[xn]&&!this[Ce]&&this[qe].length===0&&this[Wt]&&(this[Is]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[As]&&this.emit("close"),this[Is]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Ce&&this[Ce])return!1;if(t==="data")return!this[Ye]&&!r?!1:this[Tt]?(fi(()=>this[qa](r)),!0):this[qa](r);if(t==="end")return this[vu]();if(t==="close"){if(this[As]=!0,!this[xn]&&!this[Ce])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[di]=r,super.emit(Ha,r);let o=!this[ui]||this.listeners("error").length?super.emit("error",r):!1;return this[Kt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Kt](),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[Kt](),i}[qa](t){for(let r of this[et])r.dest.write(t)===!1&&this.pause();let e=this[at]?!1:super.emit("data",t);return this[Kt](),e}[vu](){return this[xn]?!1:(this[xn]=!0,this.readable=!1,this[Tt]?(fi(()=>this[ja]()),!0):this[ja]())}[ja](){if(this[gr]){let e=this[gr].end();if(e){for(let r of this[et])r.dest.write(e);this[at]||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[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[yt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Ce,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[at]=!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[Wt])return e();let i,o,c=x=>{this.off("data",d),this.off("end",u),this.off(Ce,h),e(),o(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(Ce,h),this.pause(),i({value:x,done:!!this[Wt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Ce,h),e(),i({done:!0,value:void 0})},h=()=>c(new Error("stream destroyed"));return new Promise((x,m)=>{o=m,i=x,this.once(Ce,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[at]=!1;let t=!1,e=()=>(this.pause(),this.off(Ha,e),this.off(Ce,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(Ha,e),this.once(Ce,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Ce])return t?this.emit("error",t):this.emit(Ce),this;this[Ce]=!0,this[at]=!0,this[qe].length=0,this[je]=0;let e=this;return typeof e.close=="function"&&!this[As]&&e.close(),t?this.emit("error",t):this.emit(Ce),this}static get isStream(){return Wm}},tw=st.writev,vn=Symbol("_autoClose"),St=Symbol("_close"),hi=Symbol("_ended"),le=Symbol("_fd"),Ka=Symbol("_finished"),Zt=Symbol("_flags"),$a=Symbol("_flush"),xc=Symbol("_handleChunk"),pc=Symbol("_makeBuf"),Ii=Symbol("_mode"),Rs=Symbol("_needDrain"),Ar=Symbol("_onerror"),kr=Symbol("_onopen"),Va=Symbol("_onread"),Er=Symbol("_onwrite"),Sn=Symbol("_open"),vt=Symbol("_path"),wn=Symbol("_pos"),Ct=Symbol("_queue"),vr=Symbol("_read"),Ja=Symbol("_readSize"),Jt=Symbol("_reading"),xi=Symbol("_remain"),Za=Symbol("_size"),Us=Symbol("_write"),Mn=Symbol("_writing"),Gs=Symbol("_defaultFlag"),qn=Symbol("_errored"),Mc=class extends $n{[qn]=!1;[le];[vt];[Ja];[Jt]=!1;[Za];[xi];[vn];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[qn]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[vt]=t,this[Ja]=e.readSize||16*1024*1024,this[Jt]=!1,this[Za]=typeof e.size=="number"?e.size:1/0,this[xi]=this[Za],this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[vr]():this[Sn]()}get fd(){return this[le]}get path(){return this[vt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Sn](){st.open(this[vt],"r",(t,e)=>this[kr](t,e))}[kr](t,e){t?this[Ar](t):(this[le]=e,this.emit("open",e),this[vr]())}[pc](){return Buffer.allocUnsafe(Math.min(this[Ja],this[xi]))}[vr](){if(!this[Jt]){this[Jt]=!0;let t=this[pc]();if(t.length===0)return process.nextTick(()=>this[Va](null,0,t));st.read(this[le],t,0,t.length,null,(e,r,i)=>this[Va](e,r,i))}}[Va](t,e,r){this[Jt]=!1,t?this[Ar](t):this[xc](e,r)&&this[vr]()}[St](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,st.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ar](t){this[Jt]=!0,this[St](),this.emit("error",t)}[xc](t,e){let r=!1;return this[xi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[xi]<=0)&&(r=!1,this[St](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[vr](),!1;case"error":return this[qn]?!1:(this[qn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},nw=class extends Mc{[Sn](){let t=!0;try{this[kr](null,st.openSync(this[vt],"r")),t=!1}finally{t&&this[St]()}}[vr](){let t=!0;try{if(!this[Jt]){this[Jt]=!0;do{let e=this[pc](),r=e.length===0?0:st.readSync(this[le],e,0,e.length,null);if(!this[xc](r,e))break}while(!0);this[Jt]=!1}t=!1}finally{t&&this[St]()}}[St](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,st.closeSync(t),this.emit("close")}}},no=class extends qm{readable=!1;writable=!0;[qn]=!1;[Mn]=!1;[hi]=!1;[Ct]=[];[Rs]=!1;[vt];[Ii];[vn];[le];[Gs];[Zt];[Ka]=!1;[wn];constructor(t,e){e=e||{},super(e),this[vt]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Ii]=e.mode===void 0?438:e.mode,this[wn]=typeof e.start=="number"?e.start:void 0,this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[wn]!==void 0?"r+":"w";this[Gs]=e.flags===void 0,this[Zt]=e.flags===void 0?r:e.flags,this[le]===void 0&&this[Sn]()}emit(t,...e){if(t==="error"){if(this[qn])return!1;this[qn]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[vt]}[Ar](t){this[St](),this[Mn]=!0,this.emit("error",t)}[Sn](){st.open(this[vt],this[Zt],this[Ii],(t,e)=>this[kr](t,e))}[kr](t,e){this[Gs]&&this[Zt]==="r+"&&t&&t.code==="ENOENT"?(this[Zt]="w",this[Sn]()):t?this[Ar](t):(this[le]=e,this.emit("open",e),this[Mn]||this[$a]())}end(t,e){return t&&this.write(t,e),this[hi]=!0,!this[Mn]&&!this[Ct].length&&typeof this[le]=="number"&&this[Er](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[hi]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[Mn]||this[Ct].length?(this[Ct].push(t),this[Rs]=!0,!1):(this[Mn]=!0,this[Us](t),!0)}[Us](t){st.write(this[le],t,0,t.length,this[wn],(e,r)=>this[Er](e,r))}[Er](t,e){t?this[Ar](t):(this[wn]!==void 0&&typeof e=="number"&&(this[wn]+=e),this[Ct].length?this[$a]():(this[Mn]=!1,this[hi]&&!this[Ka]?(this[Ka]=!0,this[St](),this.emit("finish")):this[Rs]&&(this[Rs]=!1,this.emit("drain"))))}[$a](){if(this[Ct].length===0)this[hi]&&this[Er](null,0);else if(this[Ct].length===1)this[Us](this[Ct].pop());else{let t=this[Ct];this[Ct]=[],tw(this[le],t,this[wn],(e,r)=>this[Er](e,r))}}[St](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,st.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},rf=class extends no{[Sn](){let t;if(this[Gs]&&this[Zt]==="r+")try{t=st.openSync(this[vt],this[Zt],this[Ii])}catch(e){if(e?.code==="ENOENT")return this[Zt]="w",this[Sn]();throw e}else t=st.openSync(this[vt],this[Zt],this[Ii]);this[kr](null,t)}[St](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,st.closeSync(t),this.emit("close")}}[Us](t){let e=!0;try{this[Er](null,st.writeSync(this[le],t,0,t.length,this[wn])),e=!1}finally{if(e)try{this[St]()}catch{}}}},sw=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"]]),ow=t=>!!t.sync&&!!t.file,aw=t=>!t.sync&&!!t.file,cw=t=>!!t.sync&&!t.file,dw=t=>!t.sync&&!t.file,lw=t=>!!t.file,uw=t=>sw.get(t)||t,Bc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=uw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Li=(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=Bc(c);if(o?.(h,d),ow(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(aw(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(cw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(h,d)}else if(dw(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}),xw=hw.constants||{ZLIB_VERNUM:4736},Lt=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},xw)),pw=jn.concat,Iu=Object.getOwnPropertyDescriptor(jn,"concat"),gw=t=>t,Xa=Iu?.writable===!0||Iu?.set!==void 0?t=>{jn.concat=t?gw:pw}:t=>{},Wn=Symbol("_superWrite"),Ds=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Ya=Symbol("flushFlag"),Fc=class extends $n{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Su[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Su[e](t)}catch(r){throw new Ds(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new Ds(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return gc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(jn.alloc(0),{[Ya]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[Wn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=jn.from(t,e)),this.#e)return;gc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Xa(!0);let d;try{let h=typeof t[Ya]=="number"?t[Ya]:this.#r;d=this.#t._processChunk(t,h),Xa(!1)}catch(h){Xa(!1),this.#o(new Ds(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 Ds(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[Wn](jn.from(h));for(let x=1;x<d.length;x++)u=this[Wn](d[x])}else u=this[Wn](jn.from(d));return r&&r(),u}},of=class extends Fc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Lt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Lt.Z_FINISH,t.fullFlushFlag=Lt.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(Lt.Z_SYNC_FLUSH),gc(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)}}}},mw=class extends of{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Wn](t){return this.#e?(this.#e=!1,t[9]=255,super[Wn](t)):super[Wn](t)}},ww=class extends of{constructor(t){super(t,"Unzip")}},af=class extends Fc{constructor(t,e){t=t||{},t.flush=t.flush||Lt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Lt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Lt.BROTLI_OPERATION_FLUSH,super(t,e)}},_w=class extends af{constructor(t){super(t,"BrotliCompress")}},yw=class extends af{constructor(t){super(t,"BrotliDecompress")}},cf=class extends Fc{constructor(t,e){t=t||{},t.flush=t.flush||Lt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Lt.ZSTD_e_end,t.fullFlushFlag=Lt.ZSTD_e_flush,super(t,e)}},bw=class extends cf{constructor(t){super(t,"ZstdCompress")}},Ew=class extends cf{constructor(t){super(t,"ZstdDecompress")}},vw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Iw(t,e):Sw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Sw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Iw=(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]=df(o):o===0?e[i-1]=0:(r=!0,e[i-1]=lf(o))}},Aw=t=>{let e=t[0],r=e===128?Tw(t.subarray(1,t.length)):e===255?kw(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},kw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=df(c):c===0?d=c:(i=!0,d=lf(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},Tw=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},df=t=>(255^t)&255,lf=t=>(255^t)+1&255,Cw={};Hm(Cw,{code:()=>zc,isCode:()=>Hs,isName:()=>Rw,name:()=>ro,normalFsTypes:()=>uf});var Hs=t=>ro.has(t),Rw=t=>zc.has(t),uf=new Set(["0","","1","2","3","4","5","6","7","D"]),ro=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),zc=new Map(Array.from(ro).map(t=>[t[1],t[0]])),Dw=t=>t===void 0||t<0?void 0:t,Kn=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=Bn(t,e+156,1),c=uf.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??Bn(t,e,100),this.mode=d?.mode??u?.mode??_n(t,e+100,8),this.uid=d?.uid??u?.uid??_n(t,e+108,8),this.gid=d?.gid??u?.gid??_n(t,e+116,8),this.size=Dw(d?.size??u?.size??_n(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??Qa(t,e+136,12),this.cksum=_n(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Hs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Bn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Bn(t,e+265,32),this.gname=d?.gname??u?.gname??Bn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??_n(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??_n(t,e+337,8)??0,t[e+475]!==0){let x=Bn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Bn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=r?.atime??i?.atime??Qa(t,e+476,12),this.ctime=r?.ctime??i?.ctime??Qa(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=Pw(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Fn(t,e,100,o)||this.needPax,this.needPax=yn(t,e+100,8,this.mode)||this.needPax,this.needPax=yn(t,e+108,8,this.uid)||this.needPax,this.needPax=yn(t,e+116,8,this.gid)||this.needPax,this.needPax=yn(t,e+124,12,this.size)||this.needPax,this.needPax=ec(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Fn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Fn(t,e+265,32,this.uname)||this.needPax,this.needPax=Fn(t,e+297,32,this.gname)||this.needPax,this.needPax=yn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=yn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Fn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Fn(t,e+345,155,c)||this.needPax:(this.needPax=Fn(t,e+345,130,c)||this.needPax,this.needPax=ec(t,e+476,12,this.atime)||this.needPax,this.needPax=ec(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,yn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:ro.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(zc.get(t));if(Hs(e)||e==="Unsupported")this.#e=e;else if(Hs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Pw=(t,e)=>{let r=t,i="",o,c=mr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=mr.dirname(r),r=mr.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=mr.join(mr.basename(i),r),i=mr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Bn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),Qa=(t,e,r)=>Ow(_n(t,e,r)),Ow=t=>t===void 0?void 0:new Date(t*1e3),_n=(t,e,r)=>Number(t[e])&128?Aw(t.subarray(e,e+r)):Nw(t,e,r),Lw=t=>isNaN(t)?void 0:t,Nw=(t,e,r)=>Lw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Mw={12:8589934591,8:2097151},yn=(t,e,r,i)=>i===void 0?!1:i>Mw[r]||i<0?(vw(i,t.subarray(e,e+r)),!0):(Bw(t,e,r,i),!1),Bw=(t,e,r,i)=>t.write(Fw(i,r),e,r,"ascii"),Fw=(t,e)=>zw(Math.floor(t).toString(8),e),zw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",ec=(t,e,r,i)=>i===void 0?!1:yn(t,e,r,i.getTime()/1e3),Uw=new Array(156).join("\0"),Fn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Uw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Xs=class ff{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 Kn({path:("PaxHeader/"+Gw(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 ff(Hw(qw(e),r),i)}},Hw=(t,e)=>e?Object.assign({},e,t):t,qw=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(jw,Object.create(null)),jw=(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},Ww=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=Ww!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),Kw=class extends $n{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))))}},io=(t,e,r,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=r instanceof Error&&r.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),t.emit("warn",e,r,i)):r instanceof Error?t.emit("error",Object.assign(r,i)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),i))},$w=1024*1024,mc=Buffer.from([31,139]),wc=Buffer.from([40,181,47,253]),Vw=Math.max(mc.length,wc.length),ht=Symbol("state"),zn=Symbol("writeEntry"),$t=Symbol("readEntry"),tc=Symbol("nextEntry"),Au=Symbol("processEntry"),Rt=Symbol("extendedHeader"),pi=Symbol("globalExtendedHeader"),pn=Symbol("meta"),ku=Symbol("emitMeta"),we=Symbol("buffer"),Vt=Symbol("queue"),gn=Symbol("ended"),nc=Symbol("emittedEnd"),Un=Symbol("emit"),Te=Symbol("unzip"),Ps=Symbol("consumeChunk"),Os=Symbol("consumeChunkSub"),rc=Symbol("consumeBody"),Tu=Symbol("consumeMeta"),Cu=Symbol("consumeHeader"),gi=Symbol("consuming"),ic=Symbol("bufferConcat"),Ls=Symbol("maybeEnd"),wr=Symbol("writing"),Dt=Symbol("aborted"),Ns=Symbol("onDone"),Gn=Symbol("sawValidEntry"),Ms=Symbol("sawNullBlock"),Bs=Symbol("sawEOF"),Ru=Symbol("closeStream"),Jw=1e3,mi=Symbol("compressedBytesRead"),sc=Symbol("decompressedBytesRead"),Du=Symbol("checkDecompressionRatio"),Zw=()=>!0,Oi=class extends fw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[Vt]=[];[we];[$t];[zn];[ht]="begin";[pn]="";[Rt];[pi];[gn]=!1;[Te];[Dt]=!1;[Gn];[Ms]=!1;[Bs]=!1;[wr]=!1;[gi]=!1;[nc]=!1;[mi]=0;[sc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Ns,()=>{(this[ht]==="begin"||this[Gn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ns,t.ondone):this.on(Ns,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:Jw,this.maxMetaEntrySize=t.maxMetaEntrySize||$w,this.filter=typeof t.filter=="function"?t.filter:Zw;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[Ru]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){io(this,t,e,r)}[Cu](t,e){this[Gn]===void 0&&(this[Gn]=!1);let r;try{r=new Kn(t,e,this[Rt],this[pi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Ms]?(this[Bs]=!0,this[ht]==="begin"&&(this[ht]="header"),this[Un]("eof")):(this[Ms]=!0,this[Un]("nullBlock"));else if(this[Ms]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let i=r.type;if(/^(Symbolic)?Link$/.test(i)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let o=this[zn]=new Kw(r,this[Rt],this[pi]);if(!this[Gn])if(o.remain){let c=()=>{o.invalid||(this[Gn]=!0)};o.on("end",c)}else this[Gn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Un]("ignoredEntry",o),this[ht]="ignore",o.resume()):o.size>0&&(this[pn]="",o.on("data",c=>this[pn]+=c),this[ht]="meta"):(this[Rt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Un]("ignoredEntry",o),this[ht]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ht]="body":(this[ht]="header",o.end()),this[$t]?this[Vt].push(o):(this[Vt].push(o),this[tc]())))}}}[Ru](){queueMicrotask(()=>this.emit("close"))}[Au](t){let e=!0;if(!t)this[$t]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[$t]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[tc]()),e=!1);return e}[tc](){do;while(this[Au](this[Vt].shift()));if(this[Vt].length===0){let t=this[$t];!t||t.flowing||t.size===t.remain?this[wr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[rc](t,e){let r=this[zn];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[ht]="header",this[zn]=void 0,r.end()),o.length}[Tu](t,e){let r=this[zn],i=this[rc](t,e);return!this[zn]&&r&&this[ku](r),i}[Un](t,e,r){this[Vt].length===0&&!this[$t]?this.emit(t,e,r):this[Vt].push([t,e,r])}[ku](t){switch(this[Un]("meta",this[pn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Rt]=Xs.parse(this[pn],this[Rt],!1);break;case"GlobalExtendedHeader":this[pi]=Xs.parse(this[pn],this[pi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Rt]??Object.create(null);this[Rt]=e,e.path=this[pn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Rt]||Object.create(null);this[Rt]=e,e.linkpath=this[pn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Dt]){if(this[Te]){let e=this[Te];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Dt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[Du](t){this[sc]+=t.length;let e=this[sc]/this[mi];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[Dt])return r?.(),!1;if((this[Te]===void 0||this.brotli===void 0&&this[Te]===!1)&&t){if(this[we]&&(t=Buffer.concat([this[we],t]),this[we]=void 0),t.length<Vw)return this[we]=t,r?.(),!0;for(let d=0;this[Te]===void 0&&d<mc.length;d++)t[d]!==mc[d]&&(this[Te]=!1);let o=!1;if(this[Te]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<wc.length;d++)if(t[d]!==wc[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Te]===!1&&c)if(t.length<512)if(this[gn])this.brotli=!0;else return this[we]=t,r?.(),!0;else try{new Kn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Te]===void 0||this[Te]===!1&&(this.brotli||o)){let d=this[gn];this[gn]=!1,this[Te]=this[Te]===void 0?new ww({}):o?new Ew({}):new yw({}),this[Te].on("data",h=>{this[Du](h)&&this[Ps](h)}),this[Te].on("error",h=>{this[Dt]||this.abort(h)}),this[Te].on("end",()=>{this[gn]=!0,this[Ps]()}),this[wr]=!0,this[mi]+=t.length;let u=!!this[Te][d?"end":"write"](t);return this[wr]=!1,r?.(),u}}this[wr]=!0,this[Te]?(this[mi]+=t.length,this[Te].write(t)):this[Ps](t),this[wr]=!1;let i=this[Vt].length>0?!1:this[$t]?this[$t].flowing:!0;return!i&&this[Vt].length===0&&this[$t]?.once("drain",()=>this.emit("drain")),r?.(),i}[ic](t){t&&!this[Dt]&&(this[we]=this[we]?Buffer.concat([this[we],t]):t)}[Ls](){if(this[gn]&&!this[nc]&&!this[Dt]&&!this[gi]){this[nc]=!0;let t=this[zn];if(t?.blockRemain){let e=this[we]?this[we].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[we]&&t.write(this[we]),t.end()}this[Un](Ns)}}[Ps](t){if(this[gi]&&t)this[ic](t);else if(!t&&!this[we])this[Ls]();else if(t){if(this[gi]=!0,this[we]){this[ic](t);let e=this[we];this[we]=void 0,this[Os](e)}else this[Os](t);for(;this[we]&&this[we]?.length>=512&&!this[Dt]&&!this[Bs];){let e=this[we];this[we]=void 0,this[Os](e)}this[gi]=!1}(!this[we]||this[gn])&&this[Ls]()}[Os](t){let e=0,r=t.length;for(;e+512<=r&&!this[Dt]&&!this[Bs];)switch(this[ht]){case"begin":case"header":this[Cu](t,e),e+=512;break;case"ignore":case"body":e+=this[rc](t,e);break;case"meta":e+=this[Tu](t,e);break;default:throw new Error("invalid state: "+this[ht])}e<r&&(this[we]=this[we]?Buffer.concat([t.subarray(e),this[we]]):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[Dt]||(this[Te]?(t&&(this[mi]+=t.length,this[Te].write(t)),this[Te].end()):(this[gn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ls]())),this}},Ai=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},Xw=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},hf=(t,e)=>{let r=new Map(e.map(c=>[Ai(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||iw(c).root||".",h;if(c===u)h=!1;else{let x=r.get(c);h=x!==void 0?x:o(rw(c),u)}return r.set(c,h),h};t.filter=i?(c,d)=>i(c,d)&&o(Ai(c)):c=>o(Ai(c))},Yw=t=>{let e=new Oi(t),r=t.file,i;try{i=Sr.openSync(r,"r");let o=Sr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Sr.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=Sr.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{Sr.closeSync(i)}catch{}}},Qw=(t,e)=>{let r=new Oi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),Sr.stat(o,(u,h)=>{if(u)d(u);else{let x=new Mc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},Tr=Li(Yw,Qw,t=>new Oi(t),t=>new Oi(t),(t,e)=>{e?.length&&hf(t,e),t.noResume||Xw(t)}),xf=(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:t_,parse:Ou}=e_,Uc=t=>{let e="",r=Ou(t);for(;t_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Ou(t)}return[e,t]},so=["|","<",">","?",":"],Gc=so.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),n_=new Map(so.map((t,e)=>[t,Gc[e]])),r_=new Map(Gc.map((t,e)=>[t,so[e]])),Lu=t=>so.reduce((e,r)=>e.split(r).join(n_.get(r)),t),i_=t=>Gc.reduce((e,r)=>e.split(r).join(r_.get(r)),t),pf=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Ai(e)+"/"+t):Q(t),s_=16*1024*1024,Nu=Symbol("process"),Mu=Symbol("file"),Bu=Symbol("directory"),_c=Symbol("symlink"),Fu=Symbol("hardlink"),wi=Symbol("header"),qs=Symbol("read"),yc=Symbol("lstat"),js=Symbol("onlstat"),bc=Symbol("onread"),Ec=Symbol("onreadlink"),vc=Symbol("openfile"),Sc=Symbol("onopenfile"),bn=Symbol("close"),Qs=Symbol("mode"),Ic=Symbol("awaitDrain"),oc=Symbol("ondrain"),Ot=Symbol("prefix"),gf=class extends $n{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=Bc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||s_,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]=Uc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=i_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||Pu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[js](o):this[yc]()}warn(t,e,r={}){return io(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[yc](){Pt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[js](e)})}[js](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=c_(t),this.emit("stat",t),this[Nu]()}[Nu](){switch(this.type){case"File":return this[Mu]();case"Directory":return this[Bu]();case"SymbolicLink":return this[_c]();default:return this.end()}}[Qs](t){return xf(t,this.type==="Directory",this.portable)}[Ot](t){return pf(t,this.prefix)}[wi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Kn({path:this[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](this.linkpath):this.linkpath,mode:this[Qs](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new Xs({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[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](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)}[Bu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[wi](),this.end()}[_c](){Pt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Ec](e)})}[Ec](t){this.linkpath=Q(t),this[wi](),this.end()}[Fu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Pu.relative(this.cwd,t)),this.stat.size=0,this[wi](),this.end()}[Mu](){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[Fu](e);this.linkCache.set(t,this.absolute)}if(this[wi](),this.stat.size===0)return this.end();this[vc]()}[vc](){Pt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Sc](e)})}[Sc](t){if(this.fd=t,this.#e)return this[bn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[qs]()}[qs](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Pt.read(t,e,r,i,o,(c,d)=>{if(c)return this[bn](()=>this.emit("error",c));this[bc](d)})}[bn](t=()=>{}){this.fd!==void 0&&Pt.close(this.fd,t)}[bc](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[bn](()=>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[bn](()=>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[oc]():this[Ic](()=>this[oc]())}[Ic](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)}[oc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[bn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[qs]()}},o_=class extends gf{sync=!0;[yc](){this[js](Pt.lstatSync(this.absolute))}[_c](){this[Ec](Pt.readlinkSync(this.absolute))}[vc](){this[Sc](Pt.openSync(this.absolute,"r"))}[qs](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let d=Pt.readSync(e,r,i,o,c);this[bc](d),t=!1}finally{if(t)try{this[bn](()=>{})}catch{}}}[Ic](t){t()}[bn](t=()=>{}){this.fd!==void 0&&Pt.closeSync(this.fd),t()}},a_=class extends $n{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return io(this,t,e,r)}constructor(t,e={}){let r=Bc(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[Qs](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Uc(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 Kn({path:this[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](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 Xs({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[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](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)}[Ot](t){return pf(t,this.prefix)}[Qs](t){return xf(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}},c_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",d_=class Ir{tail;head;length=0;static create(e=[]){return new Ir(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++)u_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)f_(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 Ir;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 Ir;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 Ir;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 Ir;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=l_(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 l_(t,e,r){let i=e,o=e?e.next:t.head,c=new Hc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function u_(t,e){t.tail=new Hc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function f_(t,e){t.head=new Hc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Hc=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}},Uu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Gu=Buffer.alloc(1024),Ws=Symbol("onStat"),_i=Symbol("ended"),bt=Symbol("queue"),yi=Symbol("pendingLinks"),mn=Symbol("current"),Hn=Symbol("process"),bi=Symbol("processing"),Fs=Symbol("processJob"),Et=Symbol("jobs"),ac=Symbol("jobDone"),Ks=Symbol("addFSEntry"),Hu=Symbol("addTarEntry"),Ac=Symbol("stat"),kc=Symbol("readdir"),$s=Symbol("onreaddir"),Vs=Symbol("pipe"),qu=Symbol("entry"),cc=Symbol("entryOpt"),Js=Symbol("writeEntryClass"),mf=Symbol("write"),dc=Symbol("ondrain"),oo=class extends $n{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Js];onWriteEntry;[bt];[yi]=new Map;[Et]=0;[bi]=!1;[_i]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=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[Js]=gf,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 mw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new _w(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new bw(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[dc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[dc]);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[bt]=new d_,this[Et]=0,this.jobs=Number(t.jobs)||4,this[bi]=!1,this[_i]=!1}[mf](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[_i]=!0,this[Hn](),r&&r(),this}write(t){if(this[_i])throw new Error("write after end");return typeof t=="string"?this[Ks](t):this[Hu](t),this.flowing}[Hu](t){let e=Q(zu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Uu(t.path,e);r.entry=new a_(t,this[cc](r)),r.entry.on("end",()=>this[ac](r)),this[Et]+=1,this[bt].push(r)}this[Hn]()}[Ks](t){let e=Q(zu.resolve(this.cwd,t));this[bt].push(new Uu(t,e)),this[Hn]()}[Ac](t){t.pending=!0,this[Et]+=1;let e=this.follow?"stat":"lstat";Ys[e](t.absolute,(r,i)=>{t.pending=!1,this[Et]-=1,r?this.emit("error",r):this[Ws](t,i)})}[Ws](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[mn])this[Fs](t);else{let r=`${e.dev}:${e.ino}`,i=this[yi].get(r);i?i.push(t):this[yi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[Hn]()}[kc](t){t.pending=!0,this[Et]+=1,Ys.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[Et]-=1,e)return this.emit("error",e);this[$s](t,r)})}[$s](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Hn]()}[Hn](){if(!this[bi]){this[bi]=!0;for(let t=this[bt].head;t&&this[Et]<this.jobs;t=t.next)if(this[Fs](t.value),t.value.ignore){let e=t.next;this[bt].removeNode(t),t.next=e}this[bi]=!1,this[_i]&&this[bt].length===0&&this[Et]===0&&(this.zip?this.zip.end(Gu):(super.write(Gu),super.end()))}}get[mn](){return this[bt]&&this[bt].head&&this[bt].head.value}[ac](t){this[bt].shift(),this[Et]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[yi].get(r);if(i){this[yi].delete(r);for(let o of i)o.pending=!1,this[Fs](o)}}this[Hn]()}[Fs](t){if(t.pending&&t.pendingLink&&t===this[mn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[mn]&&!t.piped&&this[Vs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Ws](t,e):this[Ac](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[$s](t,e):this[kc](t),!t.readdir)return}if(t.entry=this[qu](t),!t.entry){t.ignore=!0;return}t===this[mn]&&!t.piped&&this[Vs](t)}}}[cc](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}}[qu](t){this[Et]+=1;try{return new this[Js](t.path,this[cc](t)).on("end",()=>this[ac](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[dc](){this[mn]&&this[mn].entry&&this[mn].entry.resume()}[Vs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ks](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){io(this,t,e,r)}},qc=class extends oo{sync=!0;constructor(t){super(t),this[Js]=o_}pause(){}resume(){}[Ac](t){let e=this.follow?"statSync":"lstatSync";this[Ws](t,Ys[e](t.absolute))}[kc](t){this[$s](t,Ys.readdirSync(t.absolute))}[Vs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ks](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[mf](i)})}},h_=(t,e)=>{let r=new qc(t),i=new rf(t.file,{mode:t.mode||438});r.pipe(i),wf(r,e)},x_=(t,e)=>{let r=new oo(t),i=new no(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 _f(r,e).catch(c=>r.emit("error",c)),o},wf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Tr({file:sf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},_f=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Tr({file:sf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},p_=(t,e)=>{let r=new qc(t);return wf(r,e),r},g_=(t,e)=>{let r=new oo(t);return _f(r,e).catch(i=>r.emit("error",i)),r},Z2=Li(h_,x_,p_,g_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),w_=process.env.__FAKE_PLATFORM__||process.platform,vf=w_==="win32",{O_CREAT:Sf,O_NOFOLLOW:ju,O_TRUNC:If,O_WRONLY:Af}=Ef.constants,kf=Number(process.env.__FAKE_FS_O_FILENAME__)||Ef.constants.UV_FS_O_FILEMAP||0,__=vf&&!!kf,y_=512*1024,b_=kf|If|Sf|Af,Wu=!vf&&typeof ju=="number"?ju|If|Sf|Af:null,Tf=Wu!==null?()=>Wu:__?t=>t<y_?b_:"w":()=>"w",Tc=(t,e,r)=>{try{return ao.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},eo=(t,e,r,i)=>{ao.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},E_=(t,e,r,i,o)=>{if(e.isDirectory())Cf(ki.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=ki.resolve(t,e.name);eo(d,r,i,o)});else{let c=ki.resolve(t,e.name);eo(c,r,i,o)}},Cf=(t,e,r,i)=>{ao.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return eo(t,e,r,i);let d=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return eo(t,e,r,i)}};for(let x of c)E_(t,x,e,r,h)})},v_=(t,e,r,i)=>{e.isDirectory()&&Rf(ki.resolve(t,e.name),r,i),Tc(ki.resolve(t,e.name),r,i)},Rf=(t,e,r)=>{let i;try{i=ao.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Tc(t,e,r);throw c}for(let o of i)v_(t,o,e,r);return Tc(t,e,r)},Df=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},co=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},I_=(t,e)=>{dt.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Df(t,r?.code||"ENOTDIR")),e(r)})},A_=(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,m=e.unlink,_=Q(e.cwd),S=(v,I)=>{v?r(v):I&&h?Cf(I,d,u,A=>S(A)):c?dt.chmod(t,o,r):r()};if(t===_)return I_(t,S);if(x)return S_.mkdir(t,{mode:o,recursive:!0}).then(v=>S(null,v??void 0),S);let y=Q(to.relative(_,t)).split("/");Cc(_,y,o,m,_,void 0,S)},Cc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),h=Q(to.resolve(t+"/"+u));dt.mkdir(h,r,Pf(h,e,r,i,o,c,d))},Pf=(t,e,r,i,o,c,d)=>u=>{u?dt.lstat(t,(h,x)=>{if(h)h.path=h.path&&Q(h.path),d(h);else if(x.isDirectory())Cc(t,e,r,i,o,c,d);else if(i)dt.unlink(t,m=>{if(m)return d(m);dt.mkdir(t,r,Pf(t,e,r,i,o,c,d))});else{if(x.isSymbolicLink())return d(new co(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Cc(t,e,r,i,o,c,d))},k_=t=>{let e=!1,r;try{e=dt.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Df(t,r??"ENOTDIR")}},T_=(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,m=Q(e.cwd),_=v=>{v&&u&&Rf(v,c,d),o&&dt.chmodSync(t,i)};if(t===m)return k_(m),_();if(h)return _(dt.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(to.relative(m,t)).split("/"),y;for(let v=S.shift(),I=m;v&&(I+="/"+v);v=S.shift()){I=Q(to.resolve(I));try{dt.mkdirSync(I,i),y=y||I}catch{let A=dt.lstatSync(I);if(A.isDirectory())continue;if(x){dt.unlinkSync(I),dt.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new co(I,I+"/"+S.join("/"))}}return _(y)},lc=Object.create(null),Ku=1e4,_r=new Set,C_=t=>{_r.has(t)?_r.delete(t):lc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),_r.add(t);let e=lc[t],r=_r.size-Ku;if(r>Ku/10){for(let i of _r)if(_r.delete(i),delete lc[i],--r<=0)break}return e},R_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,D_=R_==="win32",P_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Of(i,r)),e.push(r||"/"),e},[]),O_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=D_?["win32 parallelization disabled"]:t.map(i=>Ai(Of(C_(i))));let r=new Set(t.map(i=>P_(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}},L_=()=>process.umask(),$u=Symbol("onEntry"),Rc=Symbol("checkFs"),Vu=Symbol("checkFs2"),Dc=Symbol("isReusable"),xt=Symbol("makeFs"),Pc=Symbol("file"),Oc=Symbol("directory"),Zs=Symbol("link"),Ju=Symbol("symlink"),Zu=Symbol("hardlink"),Si=Symbol("ensureNoSymlink"),Xu=Symbol("unsupported"),Yu=Symbol("checkPath"),uc=Symbol("stripAbsolutePath"),En=Symbol("mkdir"),We=Symbol("onError"),zs=Symbol("pending"),Qu=Symbol("pend"),yr=Symbol("unpend"),fc=Symbol("ended"),hc=Symbol("maybeClose"),Lc=Symbol("skip"),Ti=Symbol("doChown"),Ci=Symbol("uid"),Ri=Symbol("gid"),Di=Symbol("checkedCwd"),N_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Pi=N_==="win32",M_=1024,B_=(t,e)=>{if(!Pi)return ie.unlink(t,e);let r=t+".DELETE."+bf(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},F_=t=>{if(!Pi)return ie.unlinkSync(t);let e=t+".DELETE."+bf(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},ef=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,jc=class extends Oi{[fc]=!1;[Di]=!1;[zs]=0;reservations=new O_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[fc]=!0,this[hc]()},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:M_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Pi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(ze.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:L_():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[$u](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[hc](){this[fc]&&this[zs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[uc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Uc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Pi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=ze.posix.dirname(t.path),h=ze.posix.normalize(ze.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[Yu](t){let e=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[uc](t,"path")||!this[uc](t,"linkpath"))return!1;if(t.absolute=ze.isAbsolute(t.path)?Q(ze.resolve(t.path)):Q(ze.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path: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}=ze.win32.parse(String(t.absolute));t.absolute=i+Lu(String(t.absolute).slice(i.length));let{root:o}=ze.win32.parse(t.path);t.path=o+Lu(t.path.slice(o.length))}return!0}[$u](t){if(!this[Yu](t))return t.resume();switch(m_.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[Rc](t);default:return this[Xu](t)}}[We](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[yr](),e.resume())}[En](t,e,r){A_(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)}[Ti](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ci](t){return ef(this.uid,t.uid,this.processUid)}[Ri](t){return ef(this.gid,t.gid,this.processGid)}[Pc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new no(String(t.absolute),{flags:Tf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[We](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[We](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,h=>{h?this[We](h,t):this[yr](),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,m=t.mtime;ie.futimes(h,x,m,_=>_?ie.utimes(u,x,m,S=>c(S&&_)):c())}if(typeof h=="number"&&this[Ti](t)){o++;let x=this[Ci](t),m=this[Ri](t);typeof x=="number"&&typeof m=="number"&&ie.fchown(h,x,m,_=>_?ie.chown(u,x,m,S=>c(S&&_)):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)}[Oc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[En](String(t.absolute),r,i=>{if(i){this[We](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[yr](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ti](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ci](t)),Number(this[Ri](t)),c)),c()})}[Xu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ju](t,e){let r=Q(ze.relative(this.cwd,ze.resolve(ze.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Si](t,this.cwd,r,()=>this[Zs](t,String(t.linkpath),"symlink",e),i=>{this[We](i,t),e()})}[Zu](t,e){let r=Q(ze.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Si](t,this.cwd,i,()=>this[Zs](t,r,"link",e),o=>{this[We](o,t),e()})}[Si](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=ze.resolve(e,c);ie.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new co(d,ze.resolve(d,r.join("/"))));this[Si](t,d,r,i,o)})}[Qu](){this[zs]++}[yr](){this[zs]--,this[hc]()}[Lc](t){this[yr](),t.resume()}[Dc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Pi}[Rc](t){this[Qu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Vu](t,r))}[Vu](t,e){let r=d=>{e(d)},i=()=>{this[En](this.cwd,this.dmode,d=>{if(d){this[We](d,t),r();return}this[Di]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(ze.dirname(String(t.absolute)));if(d!==this.cwd)return this[En](d,this.dmode,u=>{if(u){this[We](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[Lc](t),r();return}if(d||this[Dc](t,u))return this[xt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=m=>this[xt](m??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[xt](h??null,t,r))}if(t.absolute===this.cwd)return this[xt](null,t,r);B_(String(t.absolute),h=>this[xt](h??null,t,r))})};this[Di]?o():i()}[xt](t,e,r){if(t){this[We](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Pc](e,r);case"Link":return this[Zu](e,r);case"SymbolicLink":return this[Ju](e,r);case"Directory":case"GNUDumpDir":return this[Oc](e,r)}}[Zs](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[We](o,t):(this[yr](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},Lf=class extends jc{sync=!0;[xt](t,e){return super[xt](t,e,()=>{})}[Rc](t){if(!this[Di]){let o=this[En](this.cwd,this.dmode);if(o)return this[We](o,t);this[Di]=!0}if(t.absolute!==this.cwd){let o=Q(ze.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[En](o,this.dmode);if(c)return this[We](c,t)}}let[e,r]=Ei(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Lc](t);if(e||this[Dc](t,r))return this[xt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?Ei(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[xt](d,t)}let[o]=Ei(()=>ie.rmdirSync(String(t.absolute)));this[xt](o,t)}let[i]=t.absolute===this.cwd?[]:Ei(()=>F_(String(t.absolute)));this[xt](i,t)}[Pc](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[We](d||u,t),e()},o;try{o=ie.openSync(String(t.absolute),Tf(t.size),r)}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{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[Ti](t)){let u=this[Ci](t),h=this[Ri](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)})}[Oc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[En](String(t.absolute),r);if(i){this[We](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ti](t))try{ie.chownSync(String(t.absolute),Number(this[Ci](t)),Number(this[Ri](t)))}catch{}e(),t.resume()}[En](t,e){try{return T_(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}}[Si](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=ze.resolve(c,d);let[u,h]=Ei(()=>ie.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return o(new co(c,ze.resolve(e,r.join("/"))))}i()}[Zs](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[We](c,t)}}},z_=t=>{let e=new Lf(t),r=t.file,i=yf.statSync(r),o=t.maxReadSize||16*1024*1024;new nw(r,{readSize:o,size:i.size}).pipe(e)},U_=(t,e)=>{let r=new jc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),yf.stat(o,(u,h)=>{if(u)d(u);else{let x=new Mc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},Nf=Li(z_,U_,t=>new Lf(t),t=>new jc(t),(t,e)=>{e?.length&&hf(t,e)}),G_=(t,e)=>{let r=new qc(t),i=!0,o,c;try{try{o=ct.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=ct.openSync(t.file,"w+");else throw h}let d=ct.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let m=0,_=0;m<512;m+=_){if(_=ct.readSync(o,u,m,u.length-m,c+m),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!_)break e}let h=new Kn(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,H_(t,r,c,o,e)}finally{if(i)try{ct.closeSync(o)}catch{}}},H_=(t,e,r,i,o)=>{let c=new rf(t.file,{fd:i,start:r});e.pipe(c),j_(e,o)},q_=(t,e)=>{e=Array.from(e);let r=new oo(t),i=(o,c,d)=>{let u=(S,y)=>{S?ct.close(o,v=>d(S)):d(null,y)},h=0;if(c===0)return u(null,0);let x=0,m=Buffer.alloc(512),_=(S,y)=>{if(S||y===void 0)return u(S);if(x+=y,x<512&&y)return ct.read(o,m,x,m.length-x,h+x,_);if(h===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let v=new Kn(m);if(!v.cksumValid)return u(null,h);let I=512*Math.ceil((v.size??0)/512);if(h+I+512>c||(h+=I+512,h>=c))return u(null,h);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,ct.read(o,m,0,512,h,_)};ct.read(o,m,0,512,h,_)};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+",ct.open(t.file,d,u);if(h||!x)return c(h);ct.fstat(x,(m,_)=>{if(m)return ct.close(x,()=>c(m));i(x,_.size,(S,y)=>{if(S)return c(S);let v=new no(t.file,{fd:x,start:y});r.pipe(v),v.on("error",c),v.on("close",o),W_(r,e)})})};ct.open(t.file,d,u)})},j_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Tr({file:Mf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},W_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Tr({file:Mf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},vi=Li(G_,q_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!lw(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")}),uA=Li(vi.syncFile,vi.asyncFile,vi.syncNoFile,vi.asyncNoFile,(t,e=[])=>{vi.validate?.(t,e),K_(t)}),K_=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))};fn();var pt={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function lo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Bf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function uo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Ff(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 Vn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Xt();Ve();ne();Be();Ve();function Cr(t,e){if(lo(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ni(t){return t.startsWith("http://")||t.startsWith("https://")}function Rr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as nk}from"node:fs";import{dirname as ik,join as sk}from"node:path";import{fileURLToPath as ak}from"node:url";var Nt="0.2.4";Ve();ne();var fo="1008033",qf="1289";var jf="pbbp2",Wf="https://www.coze.cn",Kf="/api/coze_claw/resource/get_frontier_key",ey="https://www.coze.cn",ty="wss://frontier.coze.cn";function Dr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??ey}function $f(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??ty}function In(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Bi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Mi=H("handshake");async function Wc(t){let e=Dr(t.endpoint),r=t.timeoutMs??1e4,i=`${Rr(e)}${Kf}?aid=${encodeURIComponent(fo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...In(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Mi.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 v=await u.text().catch(()=>"");throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${v.slice(0,200)}`)}let m=await u.json();if(m.code!==void 0&&m.code!==0)throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${m.code} msg=${m.msg??"-"} logid=${h}`);let _=m.data??{},S=typeof _.access_key=="string"&&_.access_key||typeof _.accessKey=="string"&&_.accessKey||void 0,y=typeof _.device_id=="string"&&_.device_id||typeof _.deviceId=="string"&&_.deviceId||void 0;if(!S||!y){let v=JSON.stringify(m).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${v}`)}return Mi.info("handshake ok",{remoteDeviceId:y,logid:h,traceId:x}),{accessKey:S,deviceId:y}}catch(u){if(u instanceof T)throw Mi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Mi.warn("handshake timeout",{base:e,timeoutMs:r}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let h=u.cause;throw Mi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:h?.code,syscall:h?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var $c=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Mt="auto",Kc=15e4;function Jf(t){return{model:Vc(t.model)??Mt,...t.modelToken?{modelToken:t.modelToken}:{}}}function Zf(t){return!t||t===Mt}var ny=new Set(["auto","\u81EA\u52A8"]);function Vc(t){let e=t?.trim();if(e)return ny.has(e.toLowerCase())?Mt:e}function Xf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=$c,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||Mt;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else Zf(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Yf(t,e,r){let i={};if(t.modelToken?i.model=t.model||Mt:Zf(t.model)||(i.model=t.model),t.modelToken){let o={name:"coze",base_url:`${$c}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},c=Jc(e,r);Object.keys(c).length>0&&(o.http_headers=c),i.model_providers={coze:o},i.model_context_window=t.modelInfo?.contextWindow??Kc}return Object.keys(i).length===0?{}:{CODEX_CONFIG:JSON.stringify(i),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function Qf(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Jc(t,e){let{ttEnv:r,usePpe:i}=Bi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function e0(t,e,r){if(!t.modelToken)return{};let i=Jc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
92
- `)}}function Zc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Xc(t){return t.model||Mt}function Vf(t,e,r){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:r,maxTokens:8192,api:"openai-completions"}}function t0(t,e,r,i){if(!t.modelToken)return null;let o=Xc(t),c=Jc(e,r),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[Vf(o,d,t.modelInfo?.contextWindow??Kc)],h=new Set([o]);for(let m of i??[])!m||h.has(m)||(h.add(m),u.push(Vf(m,["text"],Kc)));let x={baseUrl:`${$c}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(x.headers=c),x}var he=H("agent-handlers"),r0=5*1024*1024,ay=1,cy=6,dy=new Set(["node_modules",".git",".coze","dist","build",".next"]),ly=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,uy=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,fy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function hy(t){let e=t?.trim();return e?fy.test(e)||uy.test(e)?e:(he.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function xy(t){return new Promise((e,r)=>{let i=ot("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 xo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Vn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Xe(r).workspace,c=i?.skills??[],d=[],u=new Set;for(let h of c){let x=xe(o,h.relPath,"SKILL.md");await id(x).then(_=>_.isFile()).catch(()=>!1)&&(d.push(_y(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",x=await x0(r,o,h),m=await p0(r,h);for(let _ of[...x,...m])u.has(_.relPath)||(u.add(_.relPath),d.push(_.skill))}return{skills:d}}async addSkills(e){e._meta;let r=Vn(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 po({agentId:r,workspace:i.workspace,framework:i.framework,skill:h});go(c,d,x),u.push(h)}return await ai(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Vn(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 ed(h,{recursive:!0,force:!0}),he.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await ai(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Vn(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??Xe(r).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=await gy(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:m}=u,_=xe(h,"SKILL.md"),S=new od.default;S.addLocalFolder(h,m);let y=S.toBuffer();if(y.length>i0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${i0}`);let v=await ho(_,{encoding:"utf8"}).then(P=>f0(P).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},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 A=I.version??"v1.0",C=I.skillId??e.skillId??u0(r,x);if(i&&!d){let P=i.skills??[],b=P.find(R=>R.relPath===x);b?(b.version=A,b.skillId=C):P.push({skillId:C,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await ai(r,P)}return he.info("skill published",{agentId:r,skillName:e.skillName,relPath:x,zipBytes:y.length,skillId:C,version:A}),{ok:!0,skillId:C,version:A}}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 Pe(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 fr(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 Ge(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 Pe(r))throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Ni(e.registry)&&o.push(`--registry=${e.registry}`);let c=hy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&ly.test(d)&&o.push("--env",d);let u=await xy(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 Pe(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ge(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",`${pt.DELETE}: missing agentId`);let i=await Pe(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=Xe(r);return c==="cloud"?await ed(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ge(i)),he.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Cr(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Vc(e.model)??Mt,i=await Pe(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 Ge(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(Cr(e._meta,pt.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${pt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,pt.RESET),await this.runDetailSync(e.agentId,pt.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 oi(e,o)}async clearPersistedAcpSessionIds(e){let r=await Pe(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 Ge(r)}async repairAgent(e){if(Cr(e._meta,pt.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${pt.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${pt.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,pt.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){Cr(e._meta,"_agent/getFileTree");let r=e._meta,i=Vn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await Yc(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 si(d,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=Dy(e.depth);return u.isDirectory()?{tree:await Ry(o,d,c,h)}:{tree:[{name:Py(c),path:w0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Cr(e._meta,"_agent/getFileContent");let r=Vn(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 Yc(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 si(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>r0)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${r0})`);let d=await ho(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 Pe(e).catch(()=>null))?.workspace??Xe(e).workspace}safeJoin(e,r){let i=nd(e,r||"."),o=sd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${o0}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Pe(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 d0(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 ad(t){return t==="claude-code"?xe(".claude","skills"):xe(".agents","skills")}function l0(t){let e=iy();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 py(t,e,r,i){let o=async c=>id(xe(c,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let c=xe(ad(e),r),d=xe(t,c);return await o(d)?{absDir:d,relPath:c}:null}for(let c of l0(e)){let d=xe(c,r);if(await o(d))return{absDir:d,relPath:d}}return null}async function gy(t,e,r,i,o){let c=d0(i),d=await py(e,r,c,o);if(d)return{...d,dirName:c};let h=(o?await p0(t,r):await x0(t,e,r)).filter(_=>_.skill.skillName===i);if(h.length>1)throw new T("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${h.map(_=>n0(_.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:n0(x.relPath)}:null}function u0(t,e){return(ry("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function f0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
89
+ `},configPath(t){return QS(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 Sp("schtasks",["/Create","/SC","ONLOGON","/TN",la,"/TR",r,"/RU",t.userName,"/F"]),el.info("task scheduler entry created",{task:la,logFile:t.logFile})},async uninstall(t){await Sp("schtasks",["/Delete","/TN",la,"/F"]).catch(e=>el.warn("schtasks /Delete failed (ignored)",{err:String(e)})),el.info("task scheduler entry removed",{task:la})}}});var Ap={};Ia(Ap,{buildContext:()=>s2,getSupervisor:()=>n2,launchdSupervisor:()=>Xd,systemdSupervisor:()=>Qd,taskSchedulerSupervisor:()=>tl});import{homedir as e2,userInfo as t2}from"node:os";function n2(t=process.platform){switch(t){case"darwin":return Xd;case"linux":return Qd;case"win32":return tl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function i2(){let t={};for(let e of r2){let r=process.env[e];r&&(t[e]=r)}return t}function s2(){let t=ee();return{nodeBin:process.execPath,entry:Hd(t),logFile:t.logFile,homeDir:e2(),userName:t2().username,isRoot:process.getuid?.()===0,env:i2()}}var r2,kp=nt(()=>{"use strict";Me();ea();Ep();vp();Ip();r2=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();an();var Dl=W("acp-installer-warmup"),tm=["claude-code","codex"];async function Ol(t={}){let e=t.ensure??cr,i=(await Promise.allSettled(tm.map(async o=>{let c=await e(o);Dl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Dl.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))})}ln();ne();import{readdir as mm}from"node:fs/promises";import{mkdir as Bl,readFile as pm,writeFile as Fl}from"node:fs/promises";import{join as Da}from"node:path";var gm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function ur(t,e,r){await Bl(t,{recursive:!0});let i=gm[e],o=Da(t,i);return await Fl(o,r??"","utf8"),o}async function Oa(t,e,r){let i=Da(t,".claude");await Bl(i,{recursive:!0});let o=Da(i,"settings.local.json"),c={};try{let u=await pm(o,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}catch{}let d=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=r)}return c.permissions=d,await Fl(o,JSON.stringify(c,null,2),"utf8"),o}var Xe=W("agent-detail-sync"),wm=6e4,_m=5*6e4,ms=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await mm(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 Re(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 Re(e,this.opts.paths);if(!i){Xe.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),g=x?Math.min(x.currentDelay*2,_m):wm;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 Ue(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 ur(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var rd=Gt(mu(),1);import{createHash as Q_}from"node:crypto";import{lstat as Jc,mkdir as Zc,readFile as lo,readdir as r0,rm as Yc,stat as td,writeFile as Xc}from"node:fs/promises";import{homedir as ey}from"node:os";import{basename as e0,dirname as ty,join as ge,normalize as ny,relative as nd,resolve as Qc,sep as i0}from"node:path";import{Readable as s0}from"node:stream";import{pipeline as o0}from"node:stream/promises";import qm from"events";import it from"fs";import{EventEmitter as Dc}from"node:events";import Xu from"node:stream";import{StringDecoder as Gm}from"node:string_decoder";import tf from"node:path";import vr from"node:fs";import{dirname as tw,parse as nw}from"path";import{EventEmitter as lw}from"events";import hc from"assert";import{Buffer as Hn}from"buffer";import*as bu from"zlib";import uw from"zlib";import{posix as gr}from"node:path";import{basename as Fw}from"node:path";import Js from"fs";import Rt from"fs";import Cu from"path";import{win32 as Zw}from"node:path";import Mu from"path";import mf from"node:fs";import h_ from"node:assert";import{randomBytes as wf}from"node:crypto";import se from"node:fs";import Fe from"node:path";import _f from"fs";import io from"node:fs";import Si from"node:path";import ct from"node:fs";import y_ from"node:fs/promises";import Xs from"node:path";import{join as Rf}from"node:path";import at from"node:fs";import Of from"node:path";var zm=Object.defineProperty,Um=(t,e)=>{for(var r in e)zm(t,r,{get:e[r],enumerable:!0})},wu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Hm=t=>!!t&&typeof t=="object"&&(t instanceof Kn||t instanceof Xu||jm(t)||Wm(t)),jm=t=>!!t&&typeof t=="object"&&t instanceof Dc&&typeof t.pipe=="function"&&t.pipe!==Xu.Writable.prototype.pipe,Wm=t=>!!t&&typeof t=="object"&&t instanceof Dc&&typeof t.write=="function"&&typeof t.end=="function",Ht=Symbol("EOF"),jt=Symbol("maybeEmitEnd"),fn=Symbol("emittedEnd"),bs=Symbol("emittingEnd"),ai=Symbol("emittedError"),vs=Symbol("closed"),_u=Symbol("read"),Ss=Symbol("flush"),yu=Symbol("flushChunk"),_t=Symbol("encoding"),pr=Symbol("decoder"),qe=Symbol("flowing"),ci=Symbol("paused"),yr=Symbol("resume"),Ge=Symbol("buffer"),Qe=Symbol("pipes"),He=Symbol("bufferLength"),za=Symbol("bufferPush"),Is=Symbol("bufferShift"),Ye=Symbol("objectMode"),ke=Symbol("destroyed"),Ua=Symbol("error"),qa=Symbol("emitData"),Eu=Symbol("emitEnd"),Ga=Symbol("emitEnd2"),kt=Symbol("async"),Ha=Symbol("abort"),As=Symbol("aborted"),di=Symbol("signal"),Ln=Symbol("dataListeners"),ot=Symbol("discarded"),li=t=>Promise.resolve().then(t),Km=t=>t(),$m=t=>t==="end"||t==="finish"||t==="prefinish",Vm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Jm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Qu=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[yr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Zm=class extends Qu{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)}},Ym=t=>!!t.objectMode,Xm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Kn=class extends Dc{[qe]=!1;[ci]=!1;[Qe]=[];[Ge]=[];[Ye];[_t];[kt];[pr];[Ht]=!1;[fn]=!1;[bs]=!1;[vs]=!1;[ai]=null;[He]=0;[ke]=!1;[di];[As]=!1;[Ln]=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");Ym(e)?(this[Ye]=!0,this[_t]=null):Xm(e)?(this[_t]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[_t]=null),this[kt]=!!e.async,this[pr]=this[_t]?new Gm(this[_t]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ge]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:r}=e;r&&(this[di]=r,r.aborted?this[Ha]():r.addEventListener("abort",()=>this[Ha]()))}get bufferLength(){return this[He]}get encoding(){return this[_t]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}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}[Ha](){this[As]=!0,this.emit("abort",this[di]?.reason),this.destroy(this[di]?.reason)}get aborted(){return this[As]}set aborted(t){}write(t,e,r){if(this[As])return!1;if(this[Ht])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[kt]?li:Km;if(!this[Ye]&&!Buffer.isBuffer(t)){if(Jm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vm(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[qe]&&this[He]!==0&&this[Ss](!0),this[qe]?this.emit("data",t):this[za](t),this[He]!==0&&this.emit("readable"),r&&i(r),this[qe]):t.length?(typeof t=="string"&&!(e===this[_t]&&!this[pr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[_t]&&(t=this[pr].write(t)),this[qe]&&this[He]!==0&&this[Ss](!0),this[qe]?this.emit("data",t):this[za](t),this[He]!==0&&this.emit("readable"),r&&i(r),this[qe]):(this[He]!==0&&this.emit("readable"),r&&i(r),this[qe])}read(t){if(this[ke])return null;if(this[ot]=!1,this[He]===0||t===0||t&&t>this[He])return this[jt](),null;this[Ye]&&(t=null),this[Ge].length>1&&!this[Ye]&&(this[Ge]=[this[_t]?this[Ge].join(""):Buffer.concat(this[Ge],this[He])]);let e=this[_u](t||null,this[Ge][0]);return this[jt](),e}[_u](t,e){if(this[Ye])this[Is]();else{let r=e;t===r.length||t===null?this[Is]():typeof r=="string"?(this[Ge][0]=r.slice(t),e=r.slice(0,t),this[He]-=t):(this[Ge][0]=r.subarray(t),e=r.subarray(0,t),this[He]-=t)}return this.emit("data",e),!this[Ge].length&&!this[Ht]&&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[Ht]=!0,this.writable=!1,(this[qe]||!this[ci])&&this[jt](),this}[yr](){this[ke]||(!this[Ln]&&!this[Qe].length&&(this[ot]=!0),this[ci]=!1,this[qe]=!0,this.emit("resume"),this[Ge].length?this[Ss]():this[Ht]?this[jt]():this.emit("drain"))}resume(){return this[yr]()}pause(){this[qe]=!1,this[ci]=!0,this[ot]=!1}get destroyed(){return this[ke]}get flowing(){return this[qe]}get paused(){return this[ci]}[za](t){this[Ye]?this[He]+=1:this[He]+=t.length,this[Ge].push(t)}[Is](){return this[Ye]?this[He]-=1:this[He]-=this[Ge][0].length,this[Ge].shift()}[Ss](t=!1){do;while(this[yu](this[Is]())&&this[Ge].length);!t&&!this[Ge].length&&!this[Ht]&&this.emit("drain")}[yu](t){return this.emit("data",t),this[qe]}pipe(t,e){if(this[ke])return t;this[ot]=!1;let r=this[fn];return e=e||{},t===wu.stdout||t===wu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Qe].push(e.proxyErrors?new Zm(this,t,e):new Qu(this,t,e)),this[kt]?li(()=>this[yr]()):this[yr]()),t}unpipe(t){let e=this[Qe].find(r=>r.dest===t);e&&(this[Qe].length===1?(this[qe]&&this[Ln]===0&&(this[qe]=!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[ot]=!1,this[Ln]++,!this[Qe].length&&!this[qe]&&this[yr]();else if(t==="readable"&&this[He]!==0)super.emit("readable");else if($m(t)&&this[fn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ai]){let i=e;this[kt]?li(()=>i.call(this,this[ai])):i.call(this,this[ai])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Ln]=this.listeners("data").length,this[Ln]===0&&!this[ot]&&!this[Qe].length&&(this[qe]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[ot]&&!this[Qe].length&&(this[qe]=!1)),e}get emittedEnd(){return this[fn]}[jt](){!this[bs]&&!this[fn]&&!this[ke]&&this[Ge].length===0&&this[Ht]&&(this[bs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[vs]&&this.emit("close"),this[bs]=!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[kt]?(li(()=>this[qa](r)),!0):this[qa](r);if(t==="end")return this[Eu]();if(t==="close"){if(this[vs]=!0,!this[fn]&&!this[ke])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ai]=r,super.emit(Ua,r);let o=!this[di]||this.listeners("error").length?super.emit("error",r):!1;return this[jt](),o}else if(t==="resume"){let o=super.emit("resume");return this[jt](),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[jt](),i}[qa](t){for(let r of this[Qe])r.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[jt](),e}[Eu](){return this[fn]?!1:(this[fn]=!0,this.readable=!1,this[kt]?(li(()=>this[Ga]()),!0):this[Ga]())}[Ga](){if(this[pr]){let e=this[pr].end();if(e){for(let r of this[Qe])r.dest.write(e);this[ot]||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[_t]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ke,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),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 r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Ht])return e();let i,o,c=x=>{this.off("data",d),this.off("end",u),this.off(ke,f),e(),o(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(ke,f),this.pause(),i({value:x,done:!!this[Ht]})},u=()=>{this.off("error",c),this.off("data",d),this.off(ke,f),e(),i({done:!0,value:void 0})},f=()=>c(new Error("stream destroyed"));return new Promise((x,g)=>{o=g,i=x,this.once(ke,f),this.once("error",c),this.once("end",u),this.once("data",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(Ua,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(Ua,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[ot]=!0,this[Ge].length=0,this[He]=0;let e=this;return typeof e.close=="function"&&!this[vs]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return Hm}},Qm=it.writev,bn=Symbol("_autoClose"),vt=Symbol("_close"),ui=Symbol("_ended"),le=Symbol("_fd"),ja=Symbol("_finished"),Vt=Symbol("_flags"),Wa=Symbol("_flush"),uc=Symbol("_handleChunk"),fc=Symbol("_makeBuf"),bi=Symbol("_mode"),ks=Symbol("_needDrain"),Ir=Symbol("_onerror"),Ar=Symbol("_onopen"),Ka=Symbol("_onread"),Er=Symbol("_onwrite"),vn=Symbol("_open"),bt=Symbol("_path"),mn=Symbol("_pos"),Tt=Symbol("_queue"),br=Symbol("_read"),$a=Symbol("_readSize"),$t=Symbol("_reading"),fi=Symbol("_remain"),Va=Symbol("_size"),Bs=Symbol("_write"),Nn=Symbol("_writing"),Fs=Symbol("_defaultFlag"),Gn=Symbol("_errored"),Oc=class extends Kn{[Gn]=!1;[le];[bt];[$a];[$t]=!1;[Va];[fi];[bn];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Gn]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[bt]=t,this[$a]=e.readSize||16*1024*1024,this[$t]=!1,this[Va]=typeof e.size=="number"?e.size:1/0,this[fi]=this[Va],this[bn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[br]():this[vn]()}get fd(){return this[le]}get path(){return this[bt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[vn](){it.open(this[bt],"r",(t,e)=>this[Ar](t,e))}[Ar](t,e){t?this[Ir](t):(this[le]=e,this.emit("open",e),this[br]())}[fc](){return Buffer.allocUnsafe(Math.min(this[$a],this[fi]))}[br](){if(!this[$t]){this[$t]=!0;let t=this[fc]();if(t.length===0)return process.nextTick(()=>this[Ka](null,0,t));it.read(this[le],t,0,t.length,null,(e,r,i)=>this[Ka](e,r,i))}}[Ka](t,e,r){this[$t]=!1,t?this[Ir](t):this[uc](e,r)&&this[br]()}[vt](){if(this[bn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ir](t){this[$t]=!0,this[vt](),this.emit("error",t)}[uc](t,e){let r=!1;return this[fi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[fi]<=0)&&(r=!1,this[vt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[br](),!1;case"error":return this[Gn]?!1:(this[Gn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},ew=class extends Oc{[vn](){let t=!0;try{this[Ar](null,it.openSync(this[bt],"r")),t=!1}finally{t&&this[vt]()}}[br](){let t=!0;try{if(!this[$t]){this[$t]=!0;do{let e=this[fc](),r=e.length===0?0:it.readSync(this[le],e,0,e.length,null);if(!this[uc](r,e))break}while(!0);this[$t]=!1}t=!1}finally{t&&this[vt]()}}[vt](){if(this[bn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}},Qs=class extends qm{readable=!1;writable=!0;[Gn]=!1;[Nn]=!1;[ui]=!1;[Tt]=[];[ks]=!1;[bt];[bi];[bn];[le];[Fs];[Vt];[ja]=!1;[mn];constructor(t,e){e=e||{},super(e),this[bt]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[bi]=e.mode===void 0?438:e.mode,this[mn]=typeof e.start=="number"?e.start:void 0,this[bn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[mn]!==void 0?"r+":"w";this[Fs]=e.flags===void 0,this[Vt]=e.flags===void 0?r:e.flags,this[le]===void 0&&this[vn]()}emit(t,...e){if(t==="error"){if(this[Gn])return!1;this[Gn]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[bt]}[Ir](t){this[vt](),this[Nn]=!0,this.emit("error",t)}[vn](){it.open(this[bt],this[Vt],this[bi],(t,e)=>this[Ar](t,e))}[Ar](t,e){this[Fs]&&this[Vt]==="r+"&&t&&t.code==="ENOENT"?(this[Vt]="w",this[vn]()):t?this[Ir](t):(this[le]=e,this.emit("open",e),this[Nn]||this[Wa]())}end(t,e){return t&&this.write(t,e),this[ui]=!0,!this[Nn]&&!this[Tt].length&&typeof this[le]=="number"&&this[Er](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[ui]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[Nn]||this[Tt].length?(this[Tt].push(t),this[ks]=!0,!1):(this[Nn]=!0,this[Bs](t),!0)}[Bs](t){it.write(this[le],t,0,t.length,this[mn],(e,r)=>this[Er](e,r))}[Er](t,e){t?this[Ir](t):(this[mn]!==void 0&&typeof e=="number"&&(this[mn]+=e),this[Tt].length?this[Wa]():(this[Nn]=!1,this[ui]&&!this[ja]?(this[ja]=!0,this[vt](),this.emit("finish")):this[ks]&&(this[ks]=!1,this.emit("drain"))))}[Wa](){if(this[Tt].length===0)this[ui]&&this[Er](null,0);else if(this[Tt].length===1)this[Bs](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],Qm(this[le],t,this[mn],(e,r)=>this[Er](e,r))}}[vt](){if(this[bn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},ef=class extends Qs{[vn](){let t;if(this[Fs]&&this[Vt]==="r+")try{t=it.openSync(this[bt],this[Vt],this[bi])}catch(e){if(e?.code==="ENOENT")return this[Vt]="w",this[vn]();throw e}else t=it.openSync(this[bt],this[Vt],this[bi]);this[Ar](null,t)}[vt](){if(this[bn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}[Bs](t){let e=!0;try{this[Er](null,it.writeSync(this[le],t,0,t.length,this[mn])),e=!1}finally{if(e)try{this[vt]()}catch{}}}},rw=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"]]),iw=t=>!!t.sync&&!!t.file,sw=t=>!t.sync&&!!t.file,ow=t=>!!t.sync&&!t.file,aw=t=>!t.sync&&!t.file,cw=t=>!!t.file,dw=t=>rw.get(t)||t,Lc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=dw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Pi=(t,e,r,i,o)=>Object.assign((c=[],d,u)=>{Array.isArray(c)&&(d=c,c={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let f=Lc(c);if(o?.(f,d),iw(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(ow(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(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:r,asyncNoFile:i,validate:o}),fw=uw.constants||{ZLIB_VERNUM:4736},Dt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},fw)),hw=Hn.concat,vu=Object.getOwnPropertyDescriptor(Hn,"concat"),xw=t=>t,Ja=vu?.writable===!0||vu?.set!==void 0?t=>{Hn.concat=t?xw:hw}:t=>{},jn=Symbol("_superWrite"),Ts=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Za=Symbol("flushFlag"),Nc=class extends Kn{#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 bu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new bu[e](t)}catch(r){throw new Ts(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 Ts(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return hc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Hn.alloc(0),{[Za]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[jn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Hn.from(t,e)),this.#e)return;hc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Ja(!0);let d;try{let f=typeof t[Za]=="number"?t[Za]:this.#r;d=this.#t._processChunk(t,f),Ja(!1)}catch(f){Ja(!1),this.#o(new Ts(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 Ts(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[jn](Hn.from(f));for(let x=1;x<d.length;x++)u=this[jn](d[x])}else u=this[jn](Hn.from(d));return r&&r(),u}},nf=class extends Nc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Dt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Dt.Z_FINISH,t.fullFlushFlag=Dt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Dt.Z_SYNC_FLUSH),hc(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)}}}},pw=class extends nf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[jn](t){return this.#e?(this.#e=!1,t[9]=255,super[jn](t)):super[jn](t)}},gw=class extends nf{constructor(t){super(t,"Unzip")}},rf=class extends Nc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Dt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Dt.BROTLI_OPERATION_FLUSH,super(t,e)}},mw=class extends rf{constructor(t){super(t,"BrotliCompress")}},ww=class extends rf{constructor(t){super(t,"BrotliDecompress")}},sf=class extends Nc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Dt.ZSTD_e_end,t.fullFlushFlag=Dt.ZSTD_e_flush,super(t,e)}},_w=class extends sf{constructor(t){super(t,"ZstdCompress")}},yw=class extends sf{constructor(t){super(t,"ZstdDecompress")}},Ew=(t,e)=>{if(Number.isSafeInteger(t))t<0?vw(t,e):bw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},bw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},vw=(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]=of(o):o===0?e[i-1]=0:(r=!0,e[i-1]=af(o))}},Sw=t=>{let e=t[0],r=e===128?Aw(t.subarray(1,t.length)):e===255?Iw(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},Iw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=of(c):c===0?d=c:(i=!0,d=af(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},Aw=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},of=t=>(255^t)&255,af=t=>(255^t)+1&255,kw={};Um(kw,{code:()=>Mc,isCode:()=>zs,isName:()=>Tw,name:()=>eo,normalFsTypes:()=>cf});var zs=t=>eo.has(t),Tw=t=>Mc.has(t),cf=new Set(["0","","1","2","3","4","5","6","7","D"]),eo=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"]]),Mc=new Map(Array.from(eo).map(t=>[t[1],t[0]])),Wn=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=Mn(t,e+156,1),c=cf.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??Mn(t,e,100),this.mode=d?.mode??u?.mode??wn(t,e+100,8),this.uid=d?.uid??u?.uid??wn(t,e+108,8),this.gid=d?.gid??u?.gid??wn(t,e+116,8),this.size=d?.size??u?.size??wn(t,e+124,12),this.mtime=d?.mtime??u?.mtime??Ya(t,e+136,12),this.cksum=wn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),zs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Mn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Mn(t,e+265,32),this.gname=d?.gname??u?.gname??Mn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??wn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??wn(t,e+337,8)??0,t[e+475]!==0){let x=Mn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Mn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=r?.atime??i?.atime??Ya(t,e+476,12),this.ctime=r?.ctime??i?.ctime??Ya(t,e+488,12)}let f=256;for(let x=e;x<e+148;x++)f+=t[x];for(let x=e+156;x<e+512;x++)f+=t[x];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,i=Cw(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Bn(t,e,100,o)||this.needPax,this.needPax=_n(t,e+100,8,this.mode)||this.needPax,this.needPax=_n(t,e+108,8,this.uid)||this.needPax,this.needPax=_n(t,e+116,8,this.gid)||this.needPax,this.needPax=_n(t,e+124,12,this.size)||this.needPax,this.needPax=Xa(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Bn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Bn(t,e+265,32,this.uname)||this.needPax,this.needPax=Bn(t,e+297,32,this.gname)||this.needPax,this.needPax=_n(t,e+329,8,this.devmaj)||this.needPax,this.needPax=_n(t,e+337,8,this.devmin)||this.needPax,this.needPax=Bn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Bn(t,e+345,155,c)||this.needPax:(this.needPax=Bn(t,e+345,130,c)||this.needPax,this.needPax=Xa(t,e+476,12,this.atime)||this.needPax,this.needPax=Xa(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,_n(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:eo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Mc.get(t));if(zs(e)||e==="Unsupported")this.#e=e;else if(zs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Cw=(t,e)=>{let r=t,i="",o,c=gr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=gr.dirname(r),r=gr.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=gr.join(gr.basename(i),r),i=gr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Mn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),Ya=(t,e,r)=>Rw(wn(t,e,r)),Rw=t=>t===void 0?void 0:new Date(t*1e3),wn=(t,e,r)=>Number(t[e])&128?Sw(t.subarray(e,e+r)):Dw(t,e,r),Pw=t=>isNaN(t)?void 0:t,Dw=(t,e,r)=>Pw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Ow={12:8589934591,8:2097151},_n=(t,e,r,i)=>i===void 0?!1:i>Ow[r]||i<0?(Ew(i,t.subarray(e,e+r)),!0):(Lw(t,e,r,i),!1),Lw=(t,e,r,i)=>t.write(Nw(i,r),e,r,"ascii"),Nw=(t,e)=>Mw(Math.floor(t).toString(8),e),Mw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Xa=(t,e,r,i)=>i===void 0?!1:_n(t,e,r,i.getTime()/1e3),Bw=new Array(156).join("\0"),Bn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Bw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Vs=class df{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 Wn({path:("PaxHeader/"+Fw(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 df(zw(Uw(e),r),i)}},zw=(t,e)=>e?Object.assign({},e,t):t,Uw=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(qw,Object.create(null)),qw=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(d)*1e3):/^[0-9]+$/.test(d)?+d:d,t},Gw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=Gw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Hw=class extends Kn{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))))}},to=(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))},jw=1024*1024,xc=Buffer.from([31,139]),pc=Buffer.from([40,181,47,253]),Ww=Math.max(xc.length,pc.length),ut=Symbol("state"),Fn=Symbol("writeEntry"),Wt=Symbol("readEntry"),Qa=Symbol("nextEntry"),Su=Symbol("processEntry"),Ct=Symbol("extendedHeader"),hi=Symbol("globalExtendedHeader"),hn=Symbol("meta"),Iu=Symbol("emitMeta"),_e=Symbol("buffer"),Kt=Symbol("queue"),xn=Symbol("ended"),ec=Symbol("emittedEnd"),zn=Symbol("emit"),Pe=Symbol("unzip"),Cs=Symbol("consumeChunk"),Rs=Symbol("consumeChunkSub"),tc=Symbol("consumeBody"),Au=Symbol("consumeMeta"),ku=Symbol("consumeHeader"),xi=Symbol("consuming"),nc=Symbol("bufferConcat"),Ps=Symbol("maybeEnd"),mr=Symbol("writing"),pn=Symbol("aborted"),Ds=Symbol("onDone"),Un=Symbol("sawValidEntry"),Os=Symbol("sawNullBlock"),Ls=Symbol("sawEOF"),Tu=Symbol("closeStream"),Kw=()=>!0,Ri=class extends lw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Kt]=[];[_e];[Wt];[Fn];[ut]="begin";[hn]="";[Ct];[hi];[xn]=!1;[Pe];[pn]=!1;[Un];[Os]=!1;[Ls]=!1;[mr]=!1;[xi]=!1;[ec]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ds,()=>{(this[ut]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ds,t.ondone):this.on(Ds,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||jw,this.filter=typeof t.filter=="function"?t.filter:Kw;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[Tu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){to(this,t,e,r)}[ku](t,e){this[Un]===void 0&&(this[Un]=!1);let r;try{r=new Wn(t,e,this[Ct],this[hi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Os]?(this[Ls]=!0,this[ut]==="begin"&&(this[ut]="header"),this[zn]("eof")):(this[Os]=!0,this[zn]("nullBlock"));else if(this[Os]=!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[Fn]=new Hw(r,this[Ct],this[hi]);if(!this[Un])if(o.remain){let c=()=>{o.invalid||(this[Un]=!0)};o.on("end",c)}else this[Un]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[zn]("ignoredEntry",o),this[ut]="ignore",o.resume()):o.size>0&&(this[hn]="",o.on("data",c=>this[hn]+=c),this[ut]="meta"):(this[Ct]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[ut]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ut]="body":(this[ut]="header",o.end()),this[Wt]?this[Kt].push(o):(this[Kt].push(o),this[Qa]())))}}}[Tu](){queueMicrotask(()=>this.emit("close"))}[Su](t){let e=!0;if(!t)this[Wt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Wt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Qa]()),e=!1);return e}[Qa](){do;while(this[Su](this[Kt].shift()));if(this[Kt].length===0){let t=this[Wt];!t||t.flowing||t.size===t.remain?this[mr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[tc](t,e){let r=this[Fn];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[ut]="header",this[Fn]=void 0,r.end()),o.length}[Au](t,e){let r=this[Fn],i=this[tc](t,e);return!this[Fn]&&r&&this[Iu](r),i}[zn](t,e,r){this[Kt].length===0&&!this[Wt]?this.emit(t,e,r):this[Kt].push([t,e,r])}[Iu](t){switch(this[zn]("meta",this[hn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=Vs.parse(this[hn],this[Ct],!1);break;case"GlobalExtendedHeader":this[hi]=Vs.parse(this[hn],this[hi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[hn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[hn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[pn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[pn])return r?.(),!1;if((this[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[_e]&&(t=Buffer.concat([this[_e],t]),this[_e]=void 0),t.length<Ww)return this[_e]=t,r?.(),!0;for(let d=0;this[Pe]===void 0&&d<xc.length;d++)t[d]!==xc[d]&&(this[Pe]=!1);let o=!1;if(this[Pe]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<pc.length;d++)if(t[d]!==pc[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Pe]===!1&&c)if(t.length<512)if(this[xn])this.brotli=!0;else return this[_e]=t,r?.(),!0;else try{new Wn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Pe]===void 0||this[Pe]===!1&&(this.brotli||o)){let d=this[xn];this[xn]=!1,this[Pe]=this[Pe]===void 0?new gw({}):o?new yw({}):new ww({}),this[Pe].on("data",f=>this[Cs](f)),this[Pe].on("error",f=>this.abort(f)),this[Pe].on("end",()=>{this[xn]=!0,this[Cs]()}),this[mr]=!0;let u=!!this[Pe][d?"end":"write"](t);return this[mr]=!1,r?.(),u}}this[mr]=!0,this[Pe]?this[Pe].write(t):this[Cs](t),this[mr]=!1;let i=this[Kt].length>0?!1:this[Wt]?this[Wt].flowing:!0;return!i&&this[Kt].length===0&&this[Wt]?.once("drain",()=>this.emit("drain")),r?.(),i}[nc](t){t&&!this[pn]&&(this[_e]=this[_e]?Buffer.concat([this[_e],t]):t)}[Ps](){if(this[xn]&&!this[ec]&&!this[pn]&&!this[xi]){this[ec]=!0;let t=this[Fn];if(t&&t.blockRemain){let e=this[_e]?this[_e].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[_e]&&t.write(this[_e]),t.end()}this[zn](Ds)}}[Cs](t){if(this[xi]&&t)this[nc](t);else if(!t&&!this[_e])this[Ps]();else if(t){if(this[xi]=!0,this[_e]){this[nc](t);let e=this[_e];this[_e]=void 0,this[Rs](e)}else this[Rs](t);for(;this[_e]&&this[_e]?.length>=512&&!this[pn]&&!this[Ls];){let e=this[_e];this[_e]=void 0,this[Rs](e)}this[xi]=!1}(!this[_e]||this[xn])&&this[Ps]()}[Rs](t){let e=0,r=t.length;for(;e+512<=r&&!this[pn]&&!this[Ls];)switch(this[ut]){case"begin":case"header":this[ku](t,e),e+=512;break;case"ignore":case"body":e+=this[tc](t,e);break;case"meta":e+=this[Au](t,e);break;default:throw new Error("invalid state: "+this[ut])}e<r&&(this[_e]=this[_e]?Buffer.concat([t.subarray(e),this[_e]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[pn]||(this[Pe]?(t&&this[Pe].write(t),this[Pe].end()):(this[xn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ps]())),this}},vi=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},$w=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},lf=(t,e)=>{let r=new Map(e.map(c=>[vi(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||nw(c).root||".",f;if(c===u)f=!1;else{let x=r.get(c);f=x!==void 0?x:o(tw(c),u)}return r.set(c,f),f};t.filter=i?(c,d)=>i(c,d)&&o(vi(c)):c=>o(vi(c))},Vw=t=>{let e=new Ri(t),r=t.file,i;try{i=vr.openSync(r,"r");let o=vr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=vr.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=vr.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{vr.closeSync(i)}catch{}}},Jw=(t,e)=>{let r=new Ri(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),vr.stat(o,(u,f)=>{if(u)d(u);else{let x=new Oc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(r)}})})},kr=Pi(Vw,Jw,t=>new Ri(t),t=>new Ri(t),(t,e)=>{e?.length&&lf(t,e),t.noResume||$w(t)}),uf=(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:Yw,parse:Ru}=Zw,Bc=t=>{let e="",r=Ru(t);for(;Yw(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Ru(t)}return[e,t]},no=["|","<",">","?",":"],Fc=no.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Xw=new Map(no.map((t,e)=>[t,Fc[e]])),Qw=new Map(Fc.map((t,e)=>[t,no[e]])),Pu=t=>no.reduce((e,r)=>e.split(r).join(Xw.get(r)),t),e_=t=>Fc.reduce((e,r)=>e.split(r).join(Qw.get(r)),t),ff=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),vi(e)+"/"+t):Q(t),t_=16*1024*1024,Du=Symbol("process"),Ou=Symbol("file"),Lu=Symbol("directory"),gc=Symbol("symlink"),Nu=Symbol("hardlink"),pi=Symbol("header"),Us=Symbol("read"),mc=Symbol("lstat"),qs=Symbol("onlstat"),wc=Symbol("onread"),_c=Symbol("onreadlink"),yc=Symbol("openfile"),Ec=Symbol("onopenfile"),yn=Symbol("close"),Zs=Symbol("mode"),bc=Symbol("awaitDrain"),rc=Symbol("ondrain"),Pt=Symbol("prefix"),hf=class extends Kn{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=Lc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||t_,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]=Bc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=e_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||Cu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[qs](o):this[mc]()}warn(t,e,r={}){return to(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[mc](){Rt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[qs](e)})}[qs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=i_(t),this.emit("stat",t),this[Du]()}[Du](){switch(this.type){case"File":return this[Ou]();case"Directory":return this[Lu]();case"SymbolicLink":return this[gc]();default:return this.end()}}[Zs](t){return uf(t,this.type==="Directory",this.portable)}[Pt](t){return ff(t,this.prefix)}[pi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Wn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this[Zs](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new Vs({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)}[Lu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[pi](),this.end()}[gc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[_c](e)})}[_c](t){this.linkpath=Q(t),this[pi](),this.end()}[Nu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Cu.relative(this.cwd,t)),this.stat.size=0,this[pi](),this.end()}[Ou](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[Nu](e);this.linkCache.set(t,this.absolute)}if(this[pi](),this.stat.size===0)return this.end();this[yc]()}[yc](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ec](e)})}[Ec](t){if(this.fd=t,this.#e)return this[yn]();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[Us]()}[Us](){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[yn](()=>this.emit("error",c));this[wc](d)})}[yn](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[wc](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[yn](()=>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[yn](()=>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[rc]():this[bc](()=>this[rc]())}[bc](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)}[rc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[yn](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[Us]()}},n_=class extends hf{sync=!0;[mc](){this[qs](Rt.lstatSync(this.absolute))}[gc](){this[_c](Rt.readlinkSync(this.absolute))}[yc](){this[Ec](Rt.openSync(this.absolute,"r"))}[Us](){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[wc](d),t=!1}finally{if(t)try{this[yn](()=>{})}catch{}}}[bc](t){t()}[yn](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},r_=class extends Kn{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 to(this,t,e,r)}constructor(t,e={}){let r=Lc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[Zs](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Bc(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 Wn({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 Vs({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 ff(t,this.prefix)}[Zs](t){return uf(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}},i_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",s_=class Sr{tail;head;length=0;static create(e=[]){return new Sr(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++)a_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)c_(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 Sr;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 Sr;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 Sr;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 Sr;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=o_(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 o_(t,e,r){let i=e,o=e?e.next:t.head,c=new zc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function a_(t,e){t.tail=new zc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function c_(t,e){t.head=new zc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var zc=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}},Bu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Fu=Buffer.alloc(1024),Gs=Symbol("onStat"),gi=Symbol("ended"),yt=Symbol("queue"),mi=Symbol("pendingLinks"),gn=Symbol("current"),qn=Symbol("process"),wi=Symbol("processing"),Ns=Symbol("processJob"),Et=Symbol("jobs"),ic=Symbol("jobDone"),Hs=Symbol("addFSEntry"),zu=Symbol("addTarEntry"),vc=Symbol("stat"),Sc=Symbol("readdir"),js=Symbol("onreaddir"),Ws=Symbol("pipe"),Uu=Symbol("entry"),sc=Symbol("entryOpt"),Ks=Symbol("writeEntryClass"),xf=Symbol("write"),oc=Symbol("ondrain"),ro=class extends Kn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Ks];onWriteEntry;[yt];[mi]=new Map;[Et]=0;[wi]=!1;[gi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[Ks]=hf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new pw(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 _w(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[oc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[oc]);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 s_,this[Et]=0,this.jobs=Number(t.jobs)||4,this[wi]=!1,this[gi]=!1}[xf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[gi]=!0,this[qn](),r&&r(),this}write(t){if(this[gi])throw new Error("write after end");return typeof t=="string"?this[Hs](t):this[zu](t),this.flowing}[zu](t){let e=Q(Mu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Bu(t.path,e);r.entry=new r_(t,this[sc](r)),r.entry.on("end",()=>this[ic](r)),this[Et]+=1,this[yt].push(r)}this[qn]()}[Hs](t){let e=Q(Mu.resolve(this.cwd,t));this[yt].push(new Bu(t,e)),this[qn]()}[vc](t){t.pending=!0,this[Et]+=1;let e=this.follow?"stat":"lstat";Js[e](t.absolute,(r,i)=>{t.pending=!1,this[Et]-=1,r?this.emit("error",r):this[Gs](t,i)})}[Gs](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[gn])this[Ns](t);else{let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);i?i.push(t):this[mi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[qn]()}[Sc](t){t.pending=!0,this[Et]+=1,Js.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[Et]-=1,e)return this.emit("error",e);this[js](t,r)})}[js](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[qn]()}[qn](){if(!this[wi]){this[wi]=!0;for(let t=this[yt].head;t&&this[Et]<this.jobs;t=t.next)if(this[Ns](t.value),t.value.ignore){let e=t.next;this[yt].removeNode(t),t.next=e}this[wi]=!1,this[gi]&&this[yt].length===0&&this[Et]===0&&(this.zip?this.zip.end(Fu):(super.write(Fu),super.end()))}}get[gn](){return this[yt]&&this[yt].head&&this[yt].head.value}[ic](t){this[yt].shift(),this[Et]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);if(i){this[mi].delete(r);for(let o of i)o.pending=!1,this[Ns](o)}}this[qn]()}[Ns](t){if(t.pending&&t.pendingLink&&t===this[gn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[gn]&&!t.piped&&this[Ws](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Gs](t,e):this[vc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[js](t,e):this[Sc](t),!t.readdir)return}if(t.entry=this[Uu](t),!t.entry){t.ignore=!0;return}t===this[gn]&&!t.piped&&this[Ws](t)}}}[sc](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}}[Uu](t){this[Et]+=1;try{return new this[Ks](t.path,this[sc](t)).on("end",()=>this[ic](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[oc](){this[gn]&&this[gn].entry&&this[gn].entry.resume()}[Ws](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Hs](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){to(this,t,e,r)}},Uc=class extends ro{sync=!0;constructor(t){super(t),this[Ks]=n_}pause(){}resume(){}[vc](t){let e=this.follow?"statSync":"lstatSync";this[Gs](t,Js[e](t.absolute))}[Sc](t){this[js](t,Js.readdirSync(t.absolute))}[Ws](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Hs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[xf](i)})}},d_=(t,e)=>{let r=new Uc(t),i=new ef(t.file,{mode:t.mode||438});r.pipe(i),pf(r,e)},l_=(t,e)=>{let r=new ro(t),i=new Qs(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 gf(r,e).catch(c=>r.emit("error",c)),o},pf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?kr({file:tf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},gf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await kr({file:tf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},u_=(t,e)=>{let r=new Uc(t);return pf(r,e),r},f_=(t,e)=>{let r=new ro(t);return gf(r,e).catch(i=>r.emit("error",i)),r},qI=Pi(d_,l_,u_,f_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),x_=process.env.__FAKE_PLATFORM__||process.platform,yf=x_==="win32",{O_CREAT:Ef,O_NOFOLLOW:qu,O_TRUNC:bf,O_WRONLY:vf}=_f.constants,Sf=Number(process.env.__FAKE_FS_O_FILENAME__)||_f.constants.UV_FS_O_FILEMAP||0,p_=yf&&!!Sf,g_=512*1024,m_=Sf|bf|Ef|vf,Gu=!yf&&typeof qu=="number"?qu|bf|Ef|vf:null,If=Gu!==null?()=>Gu:p_?t=>t<g_?m_:"w":()=>"w",Ic=(t,e,r)=>{try{return io.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},Ys=(t,e,r,i)=>{io.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},w_=(t,e,r,i,o)=>{if(e.isDirectory())Af(Si.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=Si.resolve(t,e.name);Ys(d,r,i,o)});else{let c=Si.resolve(t,e.name);Ys(c,r,i,o)}},Af=(t,e,r,i)=>{io.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return Ys(t,e,r,i);let d=c.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--d===0)return Ys(t,e,r,i)}};for(let x of c)w_(t,x,e,r,f)})},__=(t,e,r,i)=>{e.isDirectory()&&kf(Si.resolve(t,e.name),r,i),Ic(Si.resolve(t,e.name),r,i)},kf=(t,e,r)=>{let i;try{i=io.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Ic(t,e,r);throw c}for(let o of i)__(t,o,e,r);return Ic(t,e,r)},Tf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},so=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},E_=(t,e)=>{ct.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Tf(t,r?.code||"ENOTDIR")),e(r)})},b_=(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,f=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,g=e.unlink,m=Q(e.cwd),S=(b,I)=>{b?r(b):I&&f?Af(I,d,u,A=>S(A)):c?ct.chmod(t,o,r):r()};if(t===m)return E_(t,S);if(x)return y_.mkdir(t,{mode:o,recursive:!0}).then(b=>S(null,b??void 0),S);let y=Q(Xs.relative(m,t)).split("/");Ac(m,y,o,g,m,void 0,S)},Ac=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),f=Q(Xs.resolve(t+"/"+u));ct.mkdir(f,r,Cf(f,e,r,i,o,c,d))},Cf=(t,e,r,i,o,c,d)=>u=>{u?ct.lstat(t,(f,x)=>{if(f)f.path=f.path&&Q(f.path),d(f);else if(x.isDirectory())Ac(t,e,r,i,o,c,d);else if(i)ct.unlink(t,g=>{if(g)return d(g);ct.mkdir(t,r,Cf(t,e,r,i,o,c,d))});else{if(x.isSymbolicLink())return d(new so(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Ac(t,e,r,i,o,c,d))},v_=t=>{let e=!1,r;try{e=ct.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Tf(t,r??"ENOTDIR")}},S_=(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),f=e.preserve,x=e.unlink,g=Q(e.cwd),m=b=>{b&&u&&kf(b,c,d),o&&ct.chmodSync(t,i)};if(t===g)return v_(g),m();if(f)return m(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(Xs.relative(g,t)).split("/"),y;for(let b=S.shift(),I=g;b&&(I+="/"+b);b=S.shift()){I=Q(Xs.resolve(I));try{ct.mkdirSync(I,i),y=y||I}catch{let A=ct.lstatSync(I);if(A.isDirectory())continue;if(x){ct.unlinkSync(I),ct.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new so(I,I+"/"+S.join("/"))}}return m(y)},ac=Object.create(null),Hu=1e4,wr=new Set,I_=t=>{wr.has(t)?wr.delete(t):ac[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),wr.add(t);let e=ac[t],r=wr.size-Hu;if(r>Hu/10){for(let i of wr)if(wr.delete(i),delete ac[i],--r<=0)break}return e},A_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,k_=A_==="win32",T_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Rf(i,r)),e.push(r||"/"),e},[]),C_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=k_?["win32 parallelization disabled"]:t.map(i=>vi(Rf(I_(i))));let r=new Set(t.map(i=>T_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let d=this.#e.get(c);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(c);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let f of u)o.add(f)}for(let c of i){let d=this.#e.get(c),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(c);continue}else if(u.size===1){d.shift();let f=d[0];typeof f=="function"&&o.add(f)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},R_=()=>process.umask(),ju=Symbol("onEntry"),kc=Symbol("checkFs"),Wu=Symbol("checkFs2"),Tc=Symbol("isReusable"),ft=Symbol("makeFs"),Cc=Symbol("file"),Rc=Symbol("directory"),$s=Symbol("link"),Ku=Symbol("symlink"),$u=Symbol("hardlink"),Ei=Symbol("ensureNoSymlink"),Vu=Symbol("unsupported"),Ju=Symbol("checkPath"),cc=Symbol("stripAbsolutePath"),En=Symbol("mkdir"),je=Symbol("onError"),Ms=Symbol("pending"),Zu=Symbol("pend"),_r=Symbol("unpend"),dc=Symbol("ended"),lc=Symbol("maybeClose"),Pc=Symbol("skip"),Ii=Symbol("doChown"),Ai=Symbol("uid"),ki=Symbol("gid"),Ti=Symbol("checkedCwd"),P_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ci=P_==="win32",D_=1024,O_=(t,e)=>{if(!Ci)return se.unlink(t,e);let r=t+".DELETE."+wf(16).toString("hex");se.rename(t,r,i=>{if(i)return e(i);se.unlink(r,e)})},L_=t=>{if(!Ci)return se.unlinkSync(t);let e=t+".DELETE."+wf(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},Yu=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,qc=class extends Ri{[dc]=!1;[Ti]=!1;[Ms]=0;reservations=new C_;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[dc]=!0,this[lc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:D_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ci,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Fe.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:R_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[ju](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[lc](){this[dc]&&this[Ms]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[cc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Bc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Ci&&/^[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=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]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[Ju](t){let e=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[cc](t,"path")||!this[cc](t,"linkpath"))return!1;if(t.absolute=Fe.isAbsolute(t.path)?Q(Fe.resolve(t.path)):Q(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: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}=Fe.win32.parse(String(t.absolute));t.absolute=i+Pu(String(t.absolute).slice(i.length));let{root:o}=Fe.win32.parse(t.path);t.path=o+Pu(t.path.slice(o.length))}return!0}[ju](t){if(!this[Ju](t))return t.resume();switch(h_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[kc](t);default:return this[Vu](t)}}[je](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[_r](),e.resume())}[En](t,e,r){b_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Ii](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ai](t){return Yu(this.uid,t.uid,this.processUid)}[ki](t){return Yu(this.gid,t.gid,this.processGid)}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new Qs(String(t.absolute),{flags:If(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[je](u,t),e()});let o=1,c=u=>{if(u){i.fd&&se.close(i.fd,()=>{}),this[je](u,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,f=>{f?this[je](f,t):this[_r](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,g=t.mtime;se.futimes(f,x,g,m=>m?se.utimes(u,x,g,S=>c(S&&m)):c())}if(typeof f=="number"&&this[Ii](t)){o++;let x=this[Ai](t),g=this[ki](t);typeof x=="number"&&typeof g=="number"&&se.fchown(f,x,g,m=>m?se.chown(u,x,g,S=>c(S&&m)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[je](u,t),e()}),t.pipe(d)),d.pipe(i)}[Rc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[En](String(t.absolute),r,i=>{if(i){this[je](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[_r](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ii](t)&&(o++,se.chown(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)),c)),c()})}[Vu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ku](t,e){let r=Q(Fe.relative(this.cwd,Fe.resolve(Fe.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ei](t,this.cwd,r,()=>this[$s](t,String(t.linkpath),"symlink",e),i=>{this[je](i,t),e()})}[$u](t,e){let r=Q(Fe.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Ei](t,this.cwd,i,()=>this[$s](t,r,"link",e),o=>{this[je](o,t),e()})}[Ei](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Fe.resolve(e,c);se.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new so(d,Fe.resolve(d,r.join("/"))));this[Ei](t,d,r,i,o)})}[Zu](){this[Ms]++}[_r](){this[Ms]--,this[lc]()}[Pc](t){this[_r](),t.resume()}[Tc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ci}[kc](t){this[Zu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Wu](t,r))}[Wu](t,e){let r=d=>{e(d)},i=()=>{this[En](this.cwd,this.dmode,d=>{if(d){this[je](d,t),r();return}this[Ti]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Fe.dirname(String(t.absolute)));if(d!==this.cwd)return this[En](d,this.dmode,u=>{if(u){this[je](u,t),r();return}c()})}c()},c=()=>{se.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Pc](t),r();return}if(d||this[Tc](t,u))return this[ft](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[ft](g??null,t,r);return f?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),f=>this[ft](f??null,t,r))}if(t.absolute===this.cwd)return this[ft](null,t,r);O_(String(t.absolute),f=>this[ft](f??null,t,r))})};this[Ti]?o():i()}[ft](t,e,r){if(t){this[je](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Cc](e,r);case"Link":return this[$u](e,r);case"SymbolicLink":return this[Ku](e,r);case"Directory":case"GNUDumpDir":return this[Rc](e,r)}}[$s](t,e,r,i){se[r](e,String(t.absolute),o=>{o?this[je](o,t):(this[_r](),t.resume()),i()})}},_i=t=>{try{return[null,t()]}catch(e){return[e,null]}},Pf=class extends qc{sync=!0;[ft](t,e){return super[ft](t,e,()=>{})}[kc](t){if(!this[Ti]){let o=this[En](this.cwd,this.dmode);if(o)return this[je](o,t);this[Ti]=!0}if(t.absolute!==this.cwd){let o=Q(Fe.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[En](o,this.dmode);if(c)return this[je](c,t)}}let[e,r]=_i(()=>se.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Pc](t);if(e||this[Tc](t,r))return this[ft](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?_i(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ft](d,t)}let[o]=_i(()=>se.rmdirSync(String(t.absolute)));this[ft](o,t)}let[i]=t.absolute===this.cwd?[]:_i(()=>L_(String(t.absolute)));this[ft](i,t)}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{se.closeSync(o)}catch(f){u=f}(d||u)&&this[je](d||u,t),e()},o;try{o=se.openSync(String(t.absolute),If(t.size),r)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[je](d,t)),t.pipe(c)),c.on("data",d=>{try{se.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{se.futimesSync(o,u,f)}catch(x){try{se.utimesSync(String(t.absolute),u,f)}catch{d=x}}}if(this[Ii](t)){let u=this[Ai](t),f=this[ki](t);try{se.fchownSync(o,Number(u),Number(f))}catch(x){try{se.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||x}}}i(d)})}[Rc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[En](String(t.absolute),r);if(i){this[je](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ii](t))try{se.chownSync(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)))}catch{}e(),t.resume()}[En](t,e){try{return S_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[Ei](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Fe.resolve(c,d);let[u,f]=_i(()=>se.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new so(c,Fe.resolve(e,r.join("/"))))}i()}[$s](t,e,r,i){let o=`${r}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[je](c,t)}}},N_=t=>{let e=new Pf(t),r=t.file,i=mf.statSync(r),o=t.maxReadSize||16*1024*1024;new ew(r,{readSize:o,size:i.size}).pipe(e)},M_=(t,e)=>{let r=new qc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),mf.stat(o,(u,f)=>{if(u)d(u);else{let x=new Oc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(r)}})})},Df=Pi(N_,M_,t=>new Pf(t),t=>new qc(t),(t,e)=>{e?.length&&lf(t,e)}),B_=(t,e)=>{let r=new Uc(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 g=0,m=0;g<512;g+=m){if(m=at.readSync(o,u,g,u.length-g,c+g),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!m)break e}let f=new Wn(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,F_(t,r,c,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},F_=(t,e,r,i,o)=>{let c=new ef(t.file,{fd:i,start:r});e.pipe(c),U_(e,o)},z_=(t,e)=>{e=Array.from(e);let r=new ro(t),i=(o,c,d)=>{let u=(S,y)=>{S?at.close(o,b=>d(S)):d(null,y)},f=0;if(c===0)return u(null,0);let x=0,g=Buffer.alloc(512),m=(S,y)=>{if(S||y===void 0)return u(S);if(x+=y,x<512&&y)return at.read(o,g,x,g.length-x,f+x,m);if(f===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let b=new Wn(g);if(!b.cksumValid)return u(null,f);let I=512*Math.ceil((b.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&b.mtime&&t.mtimeCache.set(String(b.path),b.mtime),x=0,at.read(o,g,0,512,f,m)};at.read(o,g,0,512,f,m)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",at.open(t.file,d,u);if(f||!x)return c(f);at.fstat(x,(g,m)=>{if(g)return at.close(x,()=>c(g));i(x,m.size,(S,y)=>{if(S)return c(S);let b=new Qs(t.file,{fd:x,start:y});r.pipe(b),b.on("error",c),b.on("close",o),q_(r,e)})})};at.open(t.file,d,u)})},U_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?kr({file:Of.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},q_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await kr({file:Of.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},yi=Pi(B_,z_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!cw(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")}),nA=Pi(yi.syncFile,yi.asyncFile,yi.syncNoFile,yi.asyncNoFile,(t,e=[])=>{yi.validate?.(t,e),G_(t)}),G_=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))};ln();var ht={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 oo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Lf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ao(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Nf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Mf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function $n(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Jt();$e();ne();Me();$e();function Tr(t,e){if(oo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Di(t){return t.startsWith("http://")||t.startsWith("https://")}function Cr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as $A}from"node:fs";import{dirname as JA,join as ZA}from"node:path";import{fileURLToPath as XA}from"node:url";var Ot="0.2.5";$e();ne();var co="1008033",Uf="1289";var qf="pbbp2",Gf="https://www.coze.cn",Hf="/api/coze_claw/resource/get_frontier_key",Z_="https://www.coze.cn",Y_="wss://frontier.coze.cn";function Rr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??Z_}function jf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Y_}function Sn(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Li(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Oi=W("handshake");async function Gc(t){let e=Rr(t.endpoint),r=t.timeoutMs??1e4,i=`${Cr(e)}${Hf}?aid=${encodeURIComponent(co)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Sn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Oi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),f=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let b=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${b.slice(0,200)}`)}let g=await u.json();if(g.code!==void 0&&g.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${g.code} msg=${g.msg??"-"} logid=${f}`);let m=g.data??{},S=typeof m.access_key=="string"&&m.access_key||typeof m.accessKey=="string"&&m.accessKey||void 0,y=typeof m.device_id=="string"&&m.device_id||typeof m.deviceId=="string"&&m.deviceId||void 0;if(!S||!y){let b=JSON.stringify(g).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${b}`)}return Oi.info("handshake ok",{remoteDeviceId:y,logid:f,traceId:x}),{accessKey:S,deviceId:y}}catch(u){if(u instanceof k)throw Oi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Oi.warn("handshake timeout",{base:e,timeoutMs:r}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let f=u.cause;throw Oi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var jc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Lt="auto",Hc=15e4,Wf=8192;function $f(t){return{model:Wc(t.model)??Lt,...t.modelToken?{modelToken:t.modelToken}:{}}}function Vf(t){return!t||t===Lt}var X_=new Set(["auto","\u81EA\u52A8"]);function Wc(t){let e=t?.trim();if(e)return X_.has(e.toLowerCase())?Lt:e}function Jf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=jc,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 Vf(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Zf(t,e,r){let i={};if(t.modelToken?i.model=t.model||Lt:Vf(t.model)||(i.model=t.model),t.modelToken){let o={name:"coze",base_url:`${jc}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},c=Kc(e,r);Object.keys(c).length>0&&(o.http_headers=c),i.model_providers={coze:o},i.model_context_window=t.modelInfo?.contextWindow??Hc}return Object.keys(i).length===0?{}:{CODEX_CONFIG:JSON.stringify(i),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function Yf(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Kc(t,e){let{ttEnv:r,usePpe:i}=Li(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function Xf(t,e,r){if(!t.modelToken)return{};let i=Kc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
92
+ `)}}function $c(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Vc(t){return t.model||Lt}function Kf(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 Qf(t,e,r,i){if(!t.modelToken)return null;let o=Vc(t),c=Kc(e,r),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[Kf(o,d,t.modelInfo?.contextWindow??Hc,t.modelInfo?.maxOutput??Wf)],f=new Set([o]);for(let g of i??[])!g||f.has(g)||(f.add(g),u.push(Kf(g,["text"],Hc,Wf)));let x={baseUrl:`${jc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(x.headers=c),x}var pe=W("agent-handlers"),t0=5*1024*1024,ry=1,iy=6,sy=new Set(["node_modules",".git",".coze","dist","build",".next"]),oy=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,ay=/^[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 dy(t){let e=t?.trim();return e?cy.test(e)||ay.test(e)?e:(pe.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function ly(t){return new Promise((e,r)=>{let i=st("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 uo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=$n(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ze(r).workspace,c=i?.skills??[],d=[],u=new Set;for(let f of c){let x=ge(o,f.relPath,"SKILL.md");await td(x).then(m=>m.isFile()).catch(()=>!1)&&(d.push(py(f)),u.add(f.relPath))}if(e.scanLocal){let f=i?.framework??"claude-code",x=await f0(r,o,f),g=await h0(r,f);for(let m of[...x,...g])u.has(m.relPath)||(u.add(m.relPath),d.push(m.skill))}return{skills:d}}async addSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await fo({agentId:r,workspace:i.workspace,framework:i.framework,skill:f});ho(c,d,x),u.push(f)}return await si(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],d=[];for(let u of c){if(!o.has(u.skillId)){d.push(u);continue}let f=ge(i.workspace,u.relPath);await Yc(f,{recursive:!0,force:!0}),pe.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await si(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=$n(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");pe.info("_agent/publishSkill start",{agentId:r,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(r),o=i?.workspace??Ze(r).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=await fy(r,o,c,e.skillName,d);if(!u){let D=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${D}: ${e.skillName}`)}let{absDir:f,relPath:x,dirName:g}=u,m=ge(f,"SKILL.md"),S=new rd.default;S.addLocalFolder(f,g);let y=S.toBuffer();if(y.length>n0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${n0}`);let b=await lo(m,{encoding:"utf8"}).then(D=>l0(D).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...b?{description:b}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):pe.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??d0(r,x);if(i&&!d){let D=i.skills??[],E=D.find(R=>R.relPath===x);E?(E.version=A,E.skillId=T):D.push({skillId:T,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...b?{description:b}:{}}),await si(r,D)}return pe.info("skill published",{agentId:r,skillName:e.skillName,relPath:x,zipBytes:y.length,skillId:T,version:A}),{ok:!0,skillId:T,version:A}}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,pe.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let f=c.downstream;c.downstream=void 0,pe.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(r).catch(x=>pe.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return pe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await Re(r);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return pe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await ur(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw pe.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Ue(i),pe.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Re(r))throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Di(e.registry)&&o.push(`--registry=${e.registry}`);let c=dy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&oy.test(d)&&o.push("--env",d);let u=await ly(o);return pe.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Re(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ue(i),pe.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(pe.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST",`${ht.DELETE}: missing agentId`);let i=await Re(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=Ze(r);return c==="cloud"?await Yc(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ue(i)),pe.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Tr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Wc(e.model)??Lt,i=await Re(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ue(i),pe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return pe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model;o.model=r,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: ${r}`).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:r,cloudSessions:d.length}),{ok:!0}}async resetAgent(e){if(Tr(e._meta,ht.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ht.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ht.RESET),await this.runDetailSync(e.agentId,ht.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),pe.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await ii(e,o)}async clearPersistedAcpSessionIds(e){let r=await Re(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 Ue(r)}async repairAgent(e){if(Tr(e._meta,ht.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ht.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${ht.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){pe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ht.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){pe.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){pe.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Tr(e._meta,"_agent/getFileTree");let r=e._meta,i=$n(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await Jc(d).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await ri(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=ky(e.depth);return u.isDirectory()?{tree:await Ay(o,d,c,f)}:{tree:[{name:Ty(c),path:g0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Tr(e._meta,"_agent/getFileContent");let r=$n(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await Jc(o).catch(()=>null);if(!c||!c.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await ri(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>t0)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${t0})`);let d=await lo(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 Re(e).catch(()=>null))?.workspace??Ze(e).workspace}safeJoin(e,r){let i=Qc(e,r||"."),o=nd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${i0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Re(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function a0(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 id(t){return t==="claude-code"?ge(".claude","skills"):ge(".agents","skills")}function c0(t){let e=ey();return t==="claude-code"?[ge(e,".claude","skills")]:t==="codex"?[ge(e,".agents","skills"),ge(e,".codex","skills")]:[ge(e,".agents","skills"),ge(e,".openclaw","skills")]}async function uy(t,e,r,i){let o=async c=>td(ge(c,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let c=ge(id(e),r),d=ge(t,c);return await o(d)?{absDir:d,relPath:c}:null}for(let c of c0(e)){let d=ge(c,r);if(await o(d))return{absDir:d,relPath:d}}return null}async function fy(t,e,r,i,o){let c=a0(i),d=await uy(e,r,c,o);if(d)return{...d,dirName:c};let f=(o?await h0(t,r):await f0(t,e,r)).filter(m=>m.skill.skillName===i);if(f.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${f.map(m=>e0(m.relPath)).join(", ")} \u2014 rename or remove duplicates`);let x=f[0];return x?{absDir:o?x.relPath:ge(e,x.relPath),relPath:x.relPath,dirName:e0(x.relPath)}:null}function d0(t,e){return(Q_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function l0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
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 h0(t,e,r,i){let o=await s0(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 id(xe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=d.name,x=xe(r,h),m=xe(e,h,"SKILL.md"),_=await ho(m,{encoding:"utf8"}).catch(()=>null);if(_===null)continue;let S=f0(_);c.push({relPath:x,skill:{skillId:u0(t,x),skillName:S.name||h,...S.description?{description:S.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function x0(t,e,r){let i=ad(r);return h0(t,xe(e,i),i,!1)}async function p0(t,e){let r=[],i=new Set;for(let o of l0(e)){let c=await h0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var my=3e4,wy=50*1024*1024,i0=10*1024*1024,Pr=3e4;async function po(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=d0(o.skillName),h=ad(i),x=xe(h,u),m=xe(r,x);if(await Qc(m,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");Fi(S.length),await td(xe(m,"SKILL.md"),S,"utf8")}else{let S=await by(o.downloadUrl);vy(S)?await ky(S,m):Sy(S)?await Iy(S,m):await td(xe(m,"SKILL.md"),S.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:x,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return he.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:c?"content":"downloadUrl"}),_}function go(t,e,r){let i=e.get(r.skillId);if(i!==void 0){t[i]=r;return}e.set(r.skillId,t.length),t.push(r)}function _y(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 yy(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 g0(t,e){let r=await Pe(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Nt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await Ge(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=new Map(c.map((m,_)=>[m.skillId,_])),u=c.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Ge(r,e),{status:"noop",count:0};let h=0,x=0;for(let m of u)try{await ed(xe(r.workspace,m.relPath),{recursive:!0,force:!0});let _=await po({agentId:t,workspace:r.workspace,framework:r.framework,skill:yy(m)});go(c,d,_),h+=1}catch(_){x+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(_)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await Ge(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 by(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Fi(e);let r=Ey(t);return Fi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await ho(e);return Fi(r.length),r}if(Ni(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),my);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 Fi(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 Fi(t){if(t>wy)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Ey(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 vy(t){return t.length>=2&&t[0]===31&&t[1]===139}function Sy(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 rd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Iy(t,e){let r,i;try{r=new od.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||rd(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=Ay(i),c=nd(e);for(let d of i){if(rd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=nd(e,u),x=sd(c,h);if(x.startsWith("..")||x==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Qc(h,{recursive:!0});continue}await Qc(sy(h),{recursive:!0});let m;try{m=d.getData()}catch(_){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${_.message}`,{cause:_})}await td(h,m)}}function Ay(t){let e;for(let r of t){let i=r.entryName;if(!i||rd(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 ky(t,e){await Ty(t);let r=Nf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`))},Pr);try{await c0(a0.from(t),r)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Ty(t){let e=[],r=Tr({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 (${Pr}ms)`))},Pr);try{await c0(a0.from(t),r)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Pr}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 Cy=5e3;async function Ry(t,e,r,i){return m0(t,e,r,i,{count:0})}async function m0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await s0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(dy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Cy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=xe(e,u.name),x=oy(xe(r,u.name)),m=null;try{m=await Yc(h)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let _={name:u.name,path:w0(sd(t,h)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(_.children=await m0(t,h,x,i-1,o)),d.push(_)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function Dy(t){return!t||t<=0?ay:Math.min(t,cy)}function Py(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function w0(t){return t.split(o0).join("/")}ne();var An=H("agent-health-reporter"),Oy=1e4,Ly=3,zi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Oy,this.livenessFailureThreshold=e.livenessFailureThreshold??Ly}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),An.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),An.info("heartbeat stopped"))}async tick(){if(this.inFlight){An.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,An.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let d of this.opts.core.agents.values()){let u=Ny(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:Nt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,An.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(An.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(d){An.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){An.warn("onTickEnd hook failed",{err:String(r)})}}};function Ny(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}fn();import{mkdir as hd,rm as Ob,stat as Lb}from"node:fs/promises";import{homedir as Nb}from"node:os";import{join as J0}from"node:path";dn();import{existsSync as Vy}from"node:fs";import{release as Jy}from"node:os";import{basename as Zy,isAbsolute as Xy}from"node:path";function Ui(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Or(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Lr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function kn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ve();var mo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},X={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function _0(t){return"method"in t&&"id"in t&&t.id!==void 0}function y0(t){return"method"in t&&!("id"in t)}function wo(t){return!("method"in t)&&"id"in t}var My={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 By(t){if(t!=null)return t instanceof Error?{name:t.name,message:Gi(t.message)}:typeof t=="string"?Gi(t):typeof t=="object"?zy(t):t}var Fy=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Gi(t){let e=t;for(let[r,i]of Fy)e=e.replace(r,i);return e}function zy(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Gi(i):e[r]=i;return e}function Hi(t){if(t instanceof T){let e=By(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:My[t.code]??X.INTERNAL_ERROR,message:Gi(t.message),data:r}}return{code:X.INTERNAL_ERROR,message:Gi(t instanceof Error?t.message:String(t))}}function b0(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 v0(t){return`${JSON.stringify(t)}
95
- `}var E0=10*1024*1024,_o=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>E0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${E0} 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 I0={"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"},Kk=Object.fromEntries(Object.entries(I0).map(([t,e])=>[e,t])),Uy={"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:[]},Nr=class{seq=0;next(e,r){this.seq+=1;let i=I0[e]??Gy(e),o=Uy[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(h=>S0(r?.[h]??"")),u=Hy(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>S0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function Gy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function S0(t){return t.replace(/[:_\s]+/g,"-")}function Hy(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}un();import{readFileSync as qy}from"node:fs";var jy=384;async function cd(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await ur(t.agentEnvFile,r,{mode:jy})}function dd(t){try{let e=JSON.parse(qy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function A0(t,e,r={},i=o=>o){return{...i({...t,...dd(e)}),...r}}Xt();or();Ve();ne();Be();import{execFileSync as Wy,spawnSync as Ky}from"node:child_process";function qi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function ji(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Ky("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ld=new Set;function k0(t){typeof t=="number"&&t>0&&ld.add(t)}function T0(t){typeof t=="number"&&ld.delete(t)}function C0(){for(let t of ld)ji(t,"SIGKILL")}var Mr="coze-bridge-daemon";function R0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return Wy("pgrep",["-U",String(o),"-f",Mr],{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 D0(t,e){if(t.length===0)return;let r=e?.killFn??ji,i=e?.isAliveFn??qi,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 $y=[{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 P0(t,e){if(!e)return null;for(let r of $y)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function O0(t,e){return P0(t,e)}function L0(t,e){return P0(t,e)}function Br(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 N0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,m=r-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Br(m,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:Br(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Br(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Br(c,!1,e)}}var M0=Ze("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Yy=200,Qy=40,eb=Ze("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),tb=Ze("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),nb=Ze("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),rb=Ze("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),ib=Ze("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),sb=Ze("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),B0=500;function ob(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=B0?t:`${e.slice(0,B0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function ab(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 F0(t){try{return Vy(t)}catch{return}}function cb(t,e){return{platform:process.platform,osRelease:Jy(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Xy(e.command)?F0(e.command):void 0,cwd:e.cwd,cwdExists:F0(e.cwd),envKeys:e.envKeys}}function db(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Zy(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Bt=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new _o({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Nr;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=A0(process.env,this.opts.agentEnvFile??ee().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=ot(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,k0(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>Yy&&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,T0(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=cb(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",db(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()));ji(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||ji(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r){let i={firstUpdateMs:ib,phase2GateMs:eb,livenessWindowMs:tb,absoluteMaxMs:nb,approvalMaxMs:sb,suspendThresholdMs:rb,...r};return this.call("session/prompt",e,M0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Or("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(Lr(e,r))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(kn(e,r))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,r,i=M0,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Ui(c,e,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 m={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(o){let _=this.now(),S={cfg:o,startedAt:_,lastActivityAt:_,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:_,expectedIntervalMs:Br(0,!1,o),sessionId:u};m.promptTimeout=S;let y=()=>{let v={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=N0(v,S.cfg,I),C=P=>{S.armedAt=I,S.expectedIntervalMs=P,m.timer=setTimeout(y,P)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),C(A.rearmMs);return}if(A.action==="continue"){C(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(y,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(d)}catch(_){m.timer&&clearTimeout(m.timer),this.pending.delete(c),x(_)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(v0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(wo(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new 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:ob(e.result)}),r.resolve(e.result));return}if(y0(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(_0(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(kn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let r of this.agentRequestHandlers)try{await r(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(kn(e.id,Hi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=b0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=L0(this.framework,ab(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(Qy).join(`
98
- `),o=O0(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 lb(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 yo=class extends Bt{framework="claude-code";constructor(e){let{command:r,args:i}=ii("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return lb(e)}};dn();import{mkdtempSync as ub,rmSync as fb}from"node:fs";import{tmpdir as hb}from"node:os";import{join as xb}from"node:path";var z0=["default","acceptEdits","plan","auto","bypassPermissions"],U0=["read-only","auto","full-access"];function Ft(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return z0.includes(e);case"codex":return U0.includes(e);case"openclaw":return!1}}function bo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function G0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function ud(t){switch(t){case"claude-code":return z0.join("/");case"codex":return U0.join("/");case"openclaw":return""}}var Eo=class extends Bt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ii("codex",e.command,i),d=e.isolateCodexHome?ub(xb(hb(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,h={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(h),this.authMethodId=e.authMethodId,this.codexHomeDir=d}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}setSessionMode(e){let r=Ft("codex",e.modeId)?bo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e(pb(r)))}async stop(e){if(await super.stop(e),this.codexHomeDir)try{fb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function pb(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=G0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}Ve();var gb=3e4,Fr=class extends Bt{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}`}]},gb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};un();Ve();ne();Be();function fd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}dn();var Tn=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((r,i)=>{this.slots.push({task:e,resolve:r,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let r=await e.task();e.resolve(r)}catch(r){e.reject(r)}}}finally{this.running=!1}}}};var vo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new Tn,this.sessionQueues.set(e,r)),r}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let r=this.sessionQueues.get(e);return!!r&&!r.isDisposed}async dispose(e){this.status="stopped";let r=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(r);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let r=[];for(let[,i]of this.sessions)Wi(i),i.downstream&&(r.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(r),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Wi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Yt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Xt();ne();import{constants as H0}from"node:fs";import{access as mb}from"node:fs/promises";import{delimiter as wb,join as _b}from"node:path";var It=H("framework-detector"),q0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},yb=[".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??ot,access:e.access??mb}}async detect(e){let r=q0[e],i=await this.which(r);if(!i)return It.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(q0).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(wb).filter(Boolean),i=this.env.platform==="win32"?["",...yb]:[""];for(let o of r)for(let c of i){let d=_b(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?H0.F_OK:H0.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 It.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return It.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 It.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 It.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?(It.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}:(It.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return It.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 It.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||It.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){It.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&&(Eb(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)}})}},bb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Eb(t){return t.replace(bb,"")}import{homedir as vb}from"node:os";import{join as Sb}from"node:path";un();Xt();or();Ve();ne();async function K0(){let t=Sb(vb(),".openclaw/openclaw.json");return lr(t)}async function $0(){return(await K0())?.gateway?.auth?.token??""}var j0=H("openclaw.config"),Ib=[0,5e3,5e3],Ab=Ze("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),W0="models.providers.",So="agents.defaults.models",Io=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new Tn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Ib,this.cliTimeoutMs=e.cliTimeoutMs??Ab}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,j0.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=ot(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.runCli(["config","unset",r])))}catch(i){j0.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",`${W0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${W0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${So}[${e}]`,()=>this.runCli(["config","set",So,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${So}[${e}]`,`${So}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await K0())?.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"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};import{readFile as kb,writeFile as Tb}from"node:fs/promises";import{join as Cb}from"node:path";var Rb=["```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(`
99
- `),Db=["# 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(`
100
- `);function Pb(t){return t.length===0?t:`${(t.endsWith(`
101
- `)?t.slice(0,-1):t).split(`
102
- `).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
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 u0(t,e,r,i){let o=await r0(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 td(ge(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,x=ge(r,f),g=ge(e,f,"SKILL.md"),m=await lo(g,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let S=l0(m);c.push({relPath:x,skill:{skillId:d0(t,x),skillName:S.name||f,...S.description?{description:S.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function f0(t,e,r){let i=id(r);return u0(t,ge(e,i),i,!1)}async function h0(t,e){let r=[],i=new Set;for(let o of c0(e)){let c=await u0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var hy=3e4,xy=50*1024*1024,n0=10*1024*1024,Pr=3e4;async function fo(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let c=typeof o.content=="string"&&o.content.length>0,d=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!d)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=a0(o.skillName),f=id(i),x=ge(f,u),g=ge(r,x);if(await Zc(g,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");Ni(S.length),await Xc(ge(g,"SKILL.md"),S,"utf8")}else{let S=await my(o.downloadUrl);_y(S)?await vy(S,g):yy(S)?await Ey(S,g):await Xc(ge(g,"SKILL.md"),S.toString("utf8"),"utf8")}let m={skillId:o.skillId,skillName:o.skillName,relPath:x,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return pe.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:c?"content":"downloadUrl"}),m}function ho(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 py(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 gy(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 x0(t,e){let r=await Re(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 Ue(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=new Map(c.map((g,m)=>[g.skillId,m])),u=c.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Ue(r,e),{status:"noop",count:0};let f=0,x=0;for(let g of u)try{await Yc(ge(r.workspace,g.relPath),{recursive:!0,force:!0});let m=await fo({agentId:t,workspace:r.workspace,framework:r.framework,skill:gy(g)});ho(c,d,m),f+=1}catch(m){x+=1,pe.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(m)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await Ue(r,e),pe.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function my(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ni(e);let r=wy(t);return Ni(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await lo(e);return Ni(r.length),r}if(Di(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),hy);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Ni(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Ni(t){if(t>xy)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function wy(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function _y(t){return t.length>=2&&t[0]===31&&t[1]===139}function yy(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 ed(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Ey(t,e){let r,i;try{r=new rd.default(t),i=r.getEntries()}catch(d){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||ed(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=by(i),c=Qc(e);for(let d of i){if(ed(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=Qc(e,u),x=nd(c,f);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Zc(f,{recursive:!0});continue}await Zc(ty(f),{recursive:!0});let g;try{g=d.getData()}catch(m){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${m.message}`,{cause:m})}await Xc(f,g)}}function by(t){let e;for(let r of t){let i=r.entryName;if(!i||ed(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 vy(t,e){await Sy(t);let r=Df({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`))},Pr);try{await o0(s0.from(t),r)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Sy(t){let e=[],r=kr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Pr}ms)`))},Pr);try{await o0(s0.from(t),r)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Pr}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 Iy=5e3;async function Ay(t,e,r,i){return p0(t,e,r,i,{count:0})}async function p0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await r0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(sy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Iy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=ge(e,u.name),x=ny(ge(r,u.name)),g=null;try{g=await Jc(f)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let m={name:u.name,path:g0(nd(t,f)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(m.children=await p0(t,f,x,i-1,o)),d.push(m)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function ky(t){return!t||t<=0?ry:Math.min(t,iy)}function Ty(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function g0(t){return t.split(i0).join("/")}ne();var In=W("agent-health-reporter"),Cy=1e4,Ry=3,Mi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Cy,this.livenessFailureThreshold=e.livenessFailureThreshold??Ry}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()}),In.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),In.info("heartbeat stopped"))}async tick(){if(this.inFlight){In.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,In.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=Py(d);if(!u)continue;let f={agentId:d.agentId,status:u};d.patToken&&(f.patToken=d.patToken),d.accountId&&(f.accountId=d.accountId),r.push(f)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Ot,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,In.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(In.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){In.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){In.warn("onTickEnd hook failed",{err:String(r)})}}};function Py(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}ln();import{mkdir as ld,rm as vE,stat as SE}from"node:fs/promises";import{homedir as IE}from"node:os";import{join as K0}from"node:path";an();import{existsSync as jy}from"node:fs";import{release as Wy}from"node:os";import{basename as Ky,isAbsolute as $y}from"node:path";function Bi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Dr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Or(t,e){return{jsonrpc:"2.0",id:t,result:e}}function An(t,e){return{jsonrpc:"2.0",id:t,error:e}}$e();var xo=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 m0(t){return"method"in t&&"id"in t&&t.id!==void 0}function w0(t){return"method"in t&&!("id"in t)}function po(t){return!("method"in t)&&"id"in t}var Dy={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 Oy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Fi(t.message)}:typeof t=="string"?Fi(t):typeof t=="object"?Ny(t):t}var Ly=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Fi(t){let e=t;for(let[r,i]of Ly)e=e.replace(r,i);return e}function Ny(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Fi(i):e[r]=i;return e}function zi(t){if(t instanceof k){let e=Oy(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:Dy[t.code]??Y.INTERNAL_ERROR,message:Fi(t.message),data:r}}return{code:Y.INTERNAL_ERROR,message:Fi(t instanceof Error?t.message:String(t))}}function _0(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:d,...u}=e;c=u}return new k(r,o,{retriable:e?.retriable??!1,cause:c})}function E0(t){return`${JSON.stringify(t)}
95
+ `}var y0=10*1024*1024,go=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>y0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${y0} 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 v0={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission","session/set_mode":"session.setMode",initialize:"initialize"},Bk=Object.fromEntries(Object.entries(v0).map(([t,e])=>[e,t])),My={"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:[]},Lr=class{seq=0;next(e,r){this.seq+=1;let i=v0[e]??By(e),o=My[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>b0(r?.[f]??"")),u=Fy(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>b0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function By(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function b0(t){return t.replace(/[:_\s]+/g,"-")}function Fy(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}dn();import{readFileSync as zy}from"node:fs";var Uy=384;async function sd(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await lr(t.agentEnvFile,r,{mode:Uy})}function od(t){try{let e=JSON.parse(zy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function S0(t,e,r={},i=o=>o){return{...i({...t,...od(e)}),...r}}Jt();sr();$e();ne();Me();import{execFileSync as qy,spawnSync as Gy}from"node:child_process";function Ui(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function qi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Gy("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ad=new Set;function I0(t){typeof t=="number"&&t>0&&ad.add(t)}function A0(t){typeof t=="number"&&ad.delete(t)}function k0(){for(let t of ad)qi(t,"SIGKILL")}var Nr="coze-bridge-daemon";function T0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return qy("pgrep",["-U",String(o),"-f",Nr],{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 C0(t,e){if(t.length===0)return;let r=e?.killFn??qi,i=e?.isAliveFn??Ui,o=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),c=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(f=>i(f));u+=d)await o(Math.min(d,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var Hy=[{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 R0(t,e){if(!e)return null;for(let r of Hy)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function P0(t,e){return R0(t,e)}function D0(t,e){return R0(t,e)}function Mr(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 O0(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:Mr(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:Mr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Mr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Mr(c,!1,e)}}var L0=Je("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Vy=200,Jy=40,Zy=Je("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Yy=Je("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Xy=Je("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Qy=Je("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),eE=Je("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),tE=Je("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),N0=500;function nE(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=N0?t:`${e.slice(0,N0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function rE(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 M0(t){try{return jy(t)}catch{return}}function iE(t,e){return{platform:process.platform,osRelease:Wy(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:$y(e.command)?M0(e.command):void 0,cwd:e.cwd,cwdExists:M0(e.cwd),envKeys:e.envKeys}}function sE(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Ky(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Nt=class{constructor(e){this.opts=e;this.log=W(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new go({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Lr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=S0(process.env,this.opts.agentEnvFile??ee().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=st(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,I0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>Vy&&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,A0(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=iE(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new k("AGENT_SPAWN_FAILED",sE(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()));qi(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||qi(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:eE,phase2GateMs:Zy,livenessWindowMs:Yy,absoluteMaxMs:Xy,approvalMaxMs:tE,suspendThresholdMs:Qy,...r};return this.call("session/prompt",e,L0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Dr("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(Or(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(An(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=L0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Bi(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let f=r.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,x)=>{let g={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let m=this.now(),S={cfg:o,startedAt:m,lastActivityAt:m,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:m,expectedIntervalMs:Mr(0,!1,o),sessionId:u};g.promptTimeout=S;let y=()=>{let b={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=O0(b,S.cfg,I),T=D=>{S.armedAt=I,S.expectedIntervalMs=D,g.timer=setTimeout(y,D)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};g.timer=setTimeout(y,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(g.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,g);try{this.writeFrame(d)}catch(m){g.timer&&clearTimeout(g.timer),this.pending.delete(c),x(m)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(E0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(po(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new k("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:nE(e.result)}),r.resolve(e.result));return}if(w0(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(m0(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(An(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(An(e.id,zi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=_0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=D0(this.framework,rE(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):r}buildExitError(e,r){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(Jy).join(`
98
+ `),o=P0(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${r})`,{cause:{code:e,signal:r,stderrTail:i}})}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function oE(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 mo=class extends Nt{framework="claude-code";constructor(e){let{command:r,args:i}=ni("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return oE(e)}};an();import{mkdtempSync as aE,rmSync as cE}from"node:fs";import{tmpdir as dE}from"node:os";import{join as lE}from"node:path";var B0=["default","acceptEdits","plan","auto","bypassPermissions"],F0=["read-only","auto","full-access"];function Mt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return B0.includes(e);case"codex":return F0.includes(e);case"openclaw":return!1}}function wo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function z0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function cd(t){switch(t){case"claude-code":return B0.join("/");case"codex":return F0.join("/");case"openclaw":return""}}var _o=class extends Nt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ni("codex",e.command,i),d=e.isolateCodexHome?aE(lE(dE(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,f={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(f),this.authMethodId=e.authMethodId,this.codexHomeDir=d}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}setSessionMode(e){let r=Mt("codex",e.modeId)?wo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e(uE(r)))}async stop(e){if(await super.stop(e),this.codexHomeDir)try{cE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function uE(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=z0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}$e();var fE=3e4,Br=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}`}]},fE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};dn();$e();ne();Me();function dd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}an();var kn=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 yo=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 kn,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)Gi(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 Gi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Zt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Jt();ne();import{constants as U0}from"node:fs";import{access as hE}from"node:fs/promises";import{delimiter as xE,join as pE}from"node:path";var St=W("framework-detector"),q0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},gE=[".exe",".cmd",".bat",".ps1"],Vn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??st,access:e.access??hE}}async detect(e){let r=q0[e],i=await this.which(r);if(!i)return St.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(q0).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(xE).filter(Boolean),i=this.env.platform==="win32"?["",...gE]:[""];for(let o of r)for(let c of i){let d=pE(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?U0.F_OK:U0.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 St.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return St.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 St.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 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 r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return St.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||St.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){St.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&&(wE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,d,u=f=>{c||(c=!0,d&&clearTimeout(d),i(f))};try{let f=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{o+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},mE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function wE(t){return t.replace(mE,"")}import{homedir as _E}from"node:os";import{join as yE}from"node:path";dn();Jt();sr();$e();ne();async function j0(){let t=yE(_E(),".openclaw/openclaw.json");return dr(t)}async function W0(){return(await j0())?.gateway?.auth?.token??""}var G0=W("openclaw.config"),EE=[0,5e3,5e3],bE=Je("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),H0="models.providers.",Eo="agents.defaults.models",bo=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new kn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??EE,this.cliTimeoutMs=e.cliTimeoutMs??bE}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,G0.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=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?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){G0.warn(`${e} failed (best-effort)`,{configPath:r,err:String(i)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${H0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${H0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Eo}[${e}]`,()=>this.runCli(["config","set",Eo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Eo}[${e}]`,`${Eo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await j0())?.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"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var ue=W("agent-manager"),fd="acceptEdits",J0="full-access",Z0="read-only";function AE(t){return{INITIAL_AGENT_MODE:wo(t)}}var kE=(t,e,r,i,o,c,d,u,f,x)=>{switch(t){case"claude-code":{let g={...o?{...Jf(o),...Xf(o,d,u)}:{},...f??{},IS_SANDBOX:"1"};return new mo({cwd:r,env:g,agentId:i})}case"codex":{let g=J0;x!==void 0&&(Mt("codex",x)?g=x:ue.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let m=!!o,S={...o?{...Yf(o),...Zf(o,d,u)}:{},...AE(g),...m?{NO_BROWSER:"1"}:{},...f??{}};return new _o({cwd:r,agentId:i,...Object.keys(S).length>0?{env:S}:{},...m?{authMethodId:"api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Br({command:e,cwd:r,agentId:i,...c?{sessionName:dd(c)}:{}})}};function ud(t){return t==="claude-code"||t==="codex"}function TE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(CE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
103
99
  `)}
104
- `}async function V0(t){let e=Cb(t,"HEARTBEAT.md"),r=await kb(e,"utf8");return Pb(r)!==Rb?!1:(await Tb(e,Db),!0)}var oe=H("agent-manager"),pd="acceptEdits",Y0="full-access",Q0="read-only";function Mb(t){return{INITIAL_AGENT_MODE:bo(t)}}var Bb=(t,e,r,i,o,c,d,u,h,x)=>{switch(t){case"claude-code":{let m={...o?{...Xf(o),...e0(o,d,u)}:{},...h??{},IS_SANDBOX:"1"};return new yo({cwd:r,env:m,agentId:i})}case"codex":{let m=Y0;x!==void 0&&(Ft("codex",x)?m=x:oe.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _=!!o,S={...o?{...Qf(o),...Yf(o,d,u)}:{},...Mb(m),..._?{NO_BROWSER:"1"}:{},...h??{}};return new Eo({cwd:r,agentId:i,...Object.keys(S).length>0?{env:S}:{},..._?{authMethodId:"api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Fr({command:e,cwd:r,agentId:i,...c?{sessionName:fd(c)}:{}})}};function xd(t){return t==="claude-code"||t==="codex"}function Fb(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(zb(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
105
- `)}
106
- `}function zb(t){if(t.includes(`
107
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var Ub={path:"",version:"cloud-deployed"},Z0="openclaw_gateway_unavailable",Gb="openclaw_default_agent_missing";function X0(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 Hb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},qb=6e4,Ao=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??Bb,this.createTimeoutMs=e.createTimeoutMs??qb,this.detectorFactory=e.detectorFactory??(()=>new Jn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Io({command:r})),this.openclawConfigDir=e.openclawConfigDir??J0(Nb(),".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=J0(e,".env");if(await Lb(r).then(c=>c.isFile()).catch(()=>!1)){oe.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=Fb({...process.env,...dd(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 Pe(e.agentId,this.paths).catch(()=>null),o=lo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new 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 Pe(e.agentId,this.paths).catch(()=>null);C&&(C.patToken=e.patToken,await Ge(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 Pe(e.agentId,this.paths).catch(()=>null);C&&(C.modelInfo=e.modelInfo,await Ge(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=Xe(e.agentId,this.paths),h=o?"cloud":"local",x=e.framework==="openclaw"&&h==="local",m;x&&!r?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let _=m??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??_??u.workspace,y=new AbortController,v=setTimeout(()=>y.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&xd(e.framework)&&await dr(e.framework,y.signal);let C=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await hd(u.root,{recursive:!0}),await hd(S,{recursive:!0}),await hd(u.logs,{recursive:!0}),C(),x||await fr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await Na(S,"cloud"):await Na(S,"local",pd)),C();let P=i,b=Jf({model:e.model??P?.model}),R=Bf(e._meta)??P?.accountId,O=e.patToken??P?.patToken,M=h==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new vo({agentId:e.agentId,framework:e.framework,workspace:S,model:b.model??Mt,deployType:h,...R?{accountId:R}:{},...O?{patToken:O}:{},...M?{modelInfo:M}:{}}),I.status="ok",P?.sessions){let V=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Y,se]of Object.entries(P.sessions)){let ae={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?se.permissionMode===void 0?(ae.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:Y,framework:e.framework,fallback:ae.permissionMode})):Ft(e.framework,se.permissionMode)?ae.permissionMode=se.permissionMode:oe.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Y,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&oe.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Y,framework:e.framework,deployType:h}),se.cozeGroupId&&(ae.cozeGroupId=se.cozeGroupId),I.sessions.set(Y,ae)}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),A=!0;let N={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"&&(N.deployType="cloud"),R&&(N.accountId=R),O&&(N.patToken=O),M&&(N.modelInfo=M),P?.skills&&(N.skills=P.skills),P?.agentName&&(N.agentName=P.agentName),P?.description&&(N.description=P.description),N.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Nt,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 V0(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 J=e.initialSkills??[];if(J.length>0){let V=[...N.skills??[]],re=new Map(V.map((ae,D)=>[ae.skillId,D])),Y=await Promise.allSettled(J.map(ae=>po({agentId:e.agentId,workspace:S,framework:e.framework,skill:ae}))),se=0;for(let[ae,D]of Y.entries()){let U=J[ae];U&&(D.status==="fulfilled"?(go(V,re,D.value),se++):oe.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(D.reason)}))}se>0&&(N.skills=V,oe.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:J.length}))}return await Ge(N,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)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Ob(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(v)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&xd(e.framework))u=Ub;else throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);xd(e.framework)&&!gs(e.framework)&&(oe.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await dr(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else{let m=e.sessions.get(i),_=Yt(e)?m?.permissionMode??Y0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,o,c,this.buildBinShimPathEnv(),_)}try{return await x.start(),await x.initialize(Hb),x}catch(m){let _=x instanceof Bt?x.getStderrTail():[];throw _.length>0&&oe.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof T?m.code:"unknown",recentStderr:_}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,m)}}async resolveSpawnFailure(e,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",X0(o),{cause:{reason:Z0}})}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:Gb}})}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",X0(r),{cause:{reason:Z0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,h=fd(o);if(r.deployType==="local"){let _=await this.ensureOpenclawDefaultAgent();return new Fr({command:u,cwd:_.workspace,agentId:_.id,sessionName:h})}let x=await $0(),m;if(i?.modelToken){let _=Zc(o),S=Xc(i),y=`${_}/${S}`;if(!this.ensuredProviders.has(y)){let v=this.getOpenclawConfig(),I=await v.getAllowlistModelsForProvider(_),A=t0(i,c,d,I);A&&(await v.ensureProvider(_,A),await v.addModelToAllowlist(y),this.ensuredProviders.add(y))}m=y}return new Fr({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:h,...x?{gatewayToken:x}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e,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=Zc(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 ih}from"node:crypto";import{promises as Zb}from"node:fs";import{basename as sh}from"node:path";Ve();ne();import{promises as jb}from"node:fs";import{basename as Wb}from"node:path";var eh=H("file-upload"),Kb="/api/coze_claw/file/agent_upload",$b=6e4;async function th(t,e={}){let i=`${Rr(Dr(e.handshakeBase))}${Kb}`,o=e.timeoutMs??$b,c=await jb.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...In(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),o);eh.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),_=m.headers.get("x-tt-logid")??"";if(!m.ok){let v=await m.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${_}: ${v.slice(0,200)}`)}let S=await m.json();if(S.code!==void 0&&S.code!==0)throw new T("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${_}`);let y=S.data?.file?.file_url;if(!y)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${_}: ${JSON.stringify(S).slice(0,200)}`);return eh.info("file upload ok",{uri:y,logid:_}),{uri:y}}catch(m){throw m instanceof T?m:m.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Wb(t.path)}`):new T("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(x)}}Ve();ne();import{extname as Vb}from"node:path";var Jb={".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 nh(t){let e=Vb(t).toLowerCase();return Jb[e]??"application/octet-stream"}Be();var ko=H("agent-send"),rh=50*1024*1024;function oh(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 ah(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&&(ko.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(m=>setTimeout(m,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function ch(t,e){let{session:r,runtime:i}=oh(e.core,t.agentId,t.sessionId);if(!await si(t.path,r.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await Zb.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>rh)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${rh}`);let c=await nh(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??sh(t.path),u;try{u=await th({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 ko.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:ih(),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 ah(e,r,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),ko.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 dh(t,e){let{session:r,runtime:i}=oh(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??sh(t.path),c={sessionUpdate:"group_file",messageId:ih(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ah(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),ko.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 lh(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}dn();Xt();ne();var zt=H("coze-cli-installer"),uh="@coze/cli@latest",Xb="coze",fh="0.1.8",Yb=5e3,Qb=5e3,eE=9e4,hh=1e4,Ki=null,To=!1;async function md(t,e={}){if(To)return;if(Ki)return Ki;let r=e.exec??Hf;return Ki=(async()=>{try{let i=await tE(Xb,r),o=!1;if(i){let d=await nE(r);if(d===void 0)zt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(lh(d,fh))zt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:fh}),o=!0;else{zt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),To=!0;return}}let c=o?"upgrade-only":"full";zt.info("coze-cli install start",{package:uh,mode:c});try{await r("npm",["i","-g","--prefer-online",uh],{timeout:eE,maxBuffer:10*1024*1024}),zt.info("coze-cli install ok")}catch(d){zt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){To=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:hh}),zt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){zt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:hh}),zt.info("coze auth login ok")}catch(d){zt.warn("coze auth login failed",{err:String(d)});return}To=!0}finally{Ki=null}})(),Ki}async function tE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:Yb});return Oa(i)}catch{return}}async function nE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:Qb});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}un();Be();var rE=10*6e4;function xh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?rE:e}function Co(t){return lr(t??ee().configFile)}function $i(t,e){return ur(e??ee().configFile,t)}import{randomBytes as vE}from"node:crypto";or();Ve();ne();import{createReadStream as iE}from"node:fs";import{mkdir as sE,readFile as oE,realpath as aE,stat as cE,writeFile as dE}from"node:fs/promises";import{basename as lE,dirname as wd,isAbsolute as uE,join as fE,relative as hE,resolve as ph,sep as xE}from"node:path";import{createInterface as pE}from"node:readline";var mh=H("fs-rpc"),Vi=Ze("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function wh(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Vi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Vi} bytes`);let i=await yh(t.path,e);return await sE(wd(i),{recursive:!0}),await dE(i,t.content,"utf8"),mh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function _h(t,e){let r=await yh(t.path,e),i=await cE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Vi&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Vi} bytes`);let c;if(o&&i.size>Vi)c=await gE(r,t.line??1,t.limit);else{let d=await oE(r,"utf8");if(o){let u=d.split(`
108
- `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;c=u.slice(h,x).join(`
109
- `)}else c=d}return mh.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function gE(t,e,r){let i=pE({input:iE(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(`
110
- `)}async function yh(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([gh(ph(e)),gh(ph(t))]),o=hE(r,i);if(mE(o,xE,uE(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function mE(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function gh(t){let e=[],r=t;for(;r!==wd(r);)try{let i=await aE(r);return e.length?fE(i,...e.reverse()):i}catch{e.push(lE(r)),r=wd(r)}return t}ne();var bh=H("prompt-multimodal"),Eh=10*1024*1024,wE=15e3,_E=6;async function vh(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(_E,t.length)},()=>i());return await Promise.all(o),e}function Sh(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||!Ni(e.uri))return t;try{let{buf:r,contentType:i}=await EE(e.uri),o=e.mimeType||bE(i)||"application/octet-stream";return bh.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 bh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function bE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function EE(t){let e=new AbortController,r=setTimeout(()=>e.abort(),wE);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>Eh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Eh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}fn();Ve();ne();var K=H("core"),SE=3e4,IE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,AE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",kE="\u5BA1\u6279\u5DF2\u8D85\u65F6",TE=3e4,Ro=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Nr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=xh(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),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}),Wi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){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(kn(o,{code:X.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:X.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: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 T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(wo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&IE.test(i)?this.currentCozeEnv=i:i&&K.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):K.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Lr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Lr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Lr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):K.warn("drop unknown notification",{method:e.method})}catch(o){K.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(kn(r,Hi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new 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,m=uo(r._meta);return K.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,h,c,AE,x,m)}}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=CE();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)?Ff(i._meta):void 0;if(u!==void 0&&!Ft(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${ud(e.framework)}`);let h=await this.ensureRuntime(e,d);if(u!==void 0&&h.permissionMode===void 0&&(h.permissionMode=u,await this.persistSessionMapping(e)),h.replySeq=0,await this.ensureDownstream(e,d,h),!h.downstream||!h.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&h.permissionMode!==void 0&&h.permissionMode!==u){let S=h.permissionMode;h.permissionMode=u,await this.persistSessionMapping(e);try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(y){throw h.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),y}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(h.acpSessionId,x):e.activeTriggers.delete(h.acpSessionId);let m=uo(i._meta);if(m?e.activeGroupIds.set(h.acpSessionId,m):e.activeGroupIds.delete(h.acpSessionId),m&&h.cozeGroupId!==m&&(h.cozeGroupId=m,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Sh(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let _=await vh(c.prompt);try{let S=await h.downstream.sessionPrompt({...c,sessionId:h.acpSessionId,prompt:_});return h.lastActiveAt=Date.now(),S}catch(S){if(S instanceof T&&S.code==="AGENT_APPROVAL_TIMEOUT"){let y=h.pendingPermission;y&&(y.downstream.respondAgentRequest(y.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(y.upstreamId),h.pendingPermission=void 0);let v=h.acpSessionId,I=v?e.activeTriggers.get(v):void 0,A=v?e.activeGroupIds.get(v):void 0;return K.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,h,d,kE,I,A)}throw S}finally{if(e.activeTriggers.delete(h.acpSessionId),e.activeGroupIds.delete(h.acpSessionId),h.pendingPermission=void 0,h.reloadAfterTurn){h.reloadAfterTurn=!1;let S=h.downstream;S&&(h.downstream=void 0,K.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:h.acpSessionId}),S.stop("reload-after-turn").catch(y=>K.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(y)})))}else h.downstream?.isAlive()&&this.armIdleTimer(e,d,h)}}case"session/cancel":{let d=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=uo(i._meta);if(!d)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Yt(e))throw e.framework==="openclaw"?new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new T("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Ft(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${ud(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let m=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(_){throw x.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),_}else 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){let i=e.sessions.get(r);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Yt(e)&&(c.permissionMode=e.framework==="claude-code"?pd:Q0),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(pt.GEN_MODEL_TOKEN,i,TE);if(!o?.modelToken)throw new T("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return o.modelToken}catch(o){throw o instanceof T&&o.code==="MODEL_TOKEN_GEN_FAILED"?o:new T("MODEL_TOKEN_GEN_FAILED",o instanceof Error?o.message:String(o),{cause:o})}}async ensureDownstream(e,r,i){if(Wi(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{h=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(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 m=await h.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw 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(Wi(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(Or("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(Or("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(PE(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 m=d.currentModeId;Ft(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(_=>K.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(_)}))):typeof m=="string"&&!Ft(e.framework,m)&&K.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:m})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Or("session/update",{...r,sessionId:o,_meta:u})).catch(m=>K.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}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:X.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await wh(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await _h(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,Hi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let m=u?e.activeGroupIds.get(u):void 0;m&&(x.cozeGroupId=m);let _=u?this.reverseSessionId(e,u):void 0,S=_?e.sessions.get(_):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let y={...c,..._?{sessionId:_}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:_}),K.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:_,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(Ui(o,"session/request_permission",y)).catch(v=>{this.pendingUpstream.delete(o),K.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),r.respondAgentRequestError(i.id,{code:X.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(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"&&RE(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 mo(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=SE){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(Ui(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),r.set(i,c)}await oi(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(kn(e,{code:r,message:i,data:{bridgeVersion:Nt}}))}};function CE(){return vE(16).toString("hex")}function RE(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 DE=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."],Ih="Warning: ";function PE(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 o=i.text.startsWith(Ih)?i.text.slice(Ih.length):i.text;return DE.some(c=>o.startsWith(c))}un();ne();Be();import{randomBytes as OE}from"node:crypto";import{createServer as LE}from"node:http";var NE=1e6,Ah=H("ipc"),Do=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??ee()}async start(){this.token=OE(32).toString("hex");let e=LE((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(),Ah.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 ME(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){Ah.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 ME(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>NE)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 nS=jt(Ex(),1),rS=jt(Uo(),1),iS=jt(Gr(),1),sS=jt(Cd(),1),oS=jt(Pd(),1),aS=jt(Fd(),1),Dx=jt(jo(),1),cS=jt(Rx(),1);var Px=Dx.default;Ve();ne();var{FWS:SS}=qx(),Le=H("upstream.frontier"),Wx="application/json",Kx="none",IS=15e3;function AS(t){class e extends Px{constructor(i){super(i,jf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Le.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(kl("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let 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 is=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Le.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Wf,...In(this.opts.ppeOverride)},r=AS(e),i=$f(this.opts.urlOverride),o={url:i,ws:r,fpID:qf,aID:fo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Wx,force:!0},payloadEncoding:{encoding:Kx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new SS(o),d=!1,u=null,h,x,m=new Promise((y,v)=>{h=y,x=v}),_=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?x(y):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Le.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&_();for(let v of this.connectHandlers)Promise.resolve(v({initial:y})).catch(I=>Le.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,Le.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{Le.warn("frontier error",{code:y.code,msg:y.message}),_(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},c.onmessage=y=>this.handleMessage(y),this.fws=c;let S=this.opts.openTimeoutMs??IS;u=setTimeout(()=>{_(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await m}catch(y){try{c.close(1e3,"open failed")}catch(v){Le.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){Le.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Le.warn("frontier send refused: upstream not started",{method:i}),new T("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Le.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState: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;$x(c)||Le.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:Wx,payloadEncoding:Kx})}catch(u){throw Le.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new T("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=r(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let r=e.message?.service;if(r!==33555712){Le.debug("drop non-adapter frontier frame",{service:r});return}let i=CS(e);if(!i){Le.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Le.debug("frame received but no onFrame handler",{size:i.length});return}let 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;$x(c)||Le.info("frontier frame in",{logid:TS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:kS(i)}),Promise.resolve(this.handler(o)).catch(d=>Le.warn("frontier frame handler threw",{err:String(d)}))}};function $x(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Vx=2e3;function kS(t){return t.length<=Vx?t:`${t.slice(0,Vx)}...<truncated, total ${t.length} chars>`}function TS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function CS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}Ve();ne();var Hd=H("skill-publish"),RS="/api/marketplace/product/skill/publish_with_assets",DS=15e4;async function Jx(t,e={}){let i=`${Rr(Dr(e.handshakeBase))}${RS}`,o=e.timeoutMs??DS,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...In(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),o);Hd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),m=x.headers.get("x-tt-logid")??"";if(!x.ok){let y=await x.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${m}: ${y.slice(0,200)}`)}let _=await x.json();if(Hd.info("skill publish response",{logid:m,httpStatus:x.status,code:_.code,msg:_.msg,dataSkillId:_.data?.skill_id??"",dataVersion:_.data?.version??""}),_.code!==void 0&&_.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${_.code} msg=${_.msg??"-"} logid=${m}`);let S={};return _.data?.skill_id!==void 0&&_.data.skill_id!==""&&(S.skillId=String(_.data.skill_id)),_.data?.version&&(S.version=_.data.version),Hd.info("skill publish ok",{logid:m,skillId:S.skillId??"",version:S.version??""}),S}catch(x){throw x instanceof T?x:x.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}ne();var qd=H("upstream.switchable"),Qo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;qd.info("swap upstream",{reason:r});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw qd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>qd.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var jd=H("upstream"),$r=class{handler=null;async start(){jd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){jd.info("NoopUpstream stopped",{reason:e})}async send(e){jd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Ve();ne();un();ne();Be();import{promises as PS}from"node:fs";var Zx=H("pat-token-store");async function ea(t=ee()){try{let r=(await PS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(Zx.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):r}catch(e){let r=e?.code;return r!=="ENOENT"&&Zx.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function ss(t,e=ee()){if(!t)throw new Error("writePatToken: empty patToken");await ln(e.patTokenFile,t,{mode:384})}Be();Be();import{promises as ta}from"node:fs";import{join as OS}from"node:path";function LS(t,e){return`#!/bin/sh
100
+ `}function CE(t){if(t.includes(`
101
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var RE={path:"",version:"cloud-deployed"},$0="openclaw_gateway_unavailable",PE="openclaw_default_agent_missing";function V0(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 DE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},OE=6e4,vo=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??kE,this.createTimeoutMs=e.createTimeoutMs??OE,this.detectorFactory=e.detectorFactory??(()=>new Vn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new bo({command:r})),this.openclawConfigDir=e.openclawConfigDir??K0(IE(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{ue.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=K0(e,".env");if(await SE(r).then(c=>c.isFile()).catch(()=>!1)){ue.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=TE({...process.env,...od(this.paths.agentEnvFile)});await cn(r,o,{mode:384}),ue.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ue.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await Re(e.agentId,this.paths).catch(()=>null),o=oo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")ue.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>ue.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")ue.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>ue.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){ue.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await Re(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Ue(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ue.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await Re(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Ue(T,this.paths))}return ue.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework])throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Ze(e.agentId,this.paths),f=o?"cloud":"local",x=e.framework==="openclaw"&&f==="local",g;x&&!r?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let m=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??m??u.workspace,y=new AbortController,b=setTimeout(()=>y.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&ud(e.framework)&&await cr(e.framework,y.signal);let T=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await ld(u.root,{recursive:!0}),await ld(S,{recursive:!0}),await ld(u.logs,{recursive:!0}),T(),x||await ur(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Oa(S,"cloud"):await Oa(S,"local",fd)),T();let D=i,E=$f({model:e.model??D?.model}),R=Lf(e._meta)??D?.accountId,O=e.patToken??D?.patToken,F=f==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new yo({agentId:e.agentId,framework:e.framework,workspace:S,model:E.model??Lt,deployType:f,...R?{accountId:R}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",D?.sessions){let J=f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,oe]of Object.entries(D.sessions)){let ae={acpSessionId:oe.acpSessionId,modelToken:oe.modelToken,tokenGeneratedAt:oe.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};J?oe.permissionMode===void 0?(ae.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",ue.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:ae.permissionMode})):Mt(e.framework,oe.permissionMode)?ae.permissionMode=oe.permissionMode:ue.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&ue.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:f}),oe.cozeGroupId&&(ae.cozeGroupId=oe.cozeGroupId),I.sessions.set(X,ae)}let re=Object.keys(D.sessions).length;re>0&&ue.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(I),A=!0;let B={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:E.model};f==="cloud"&&(B.deployType="cloud"),R&&(B.accountId=R),O&&(B.patToken=O),F&&(B.modelInfo=F),D?.skills&&(B.skills=D.skills),D?.agentName&&(B.agentName=D.agentName),D?.description&&(B.description=D.description),B.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Ot,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):ue.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let Z=e.initialSkills??[];if(Z.length>0){let J=[...B.skills??[]],re=new Map(J.map((ae,P)=>[ae.skillId,P])),X=await Promise.allSettled(Z.map(ae=>fo({agentId:e.agentId,workspace:S,framework:e.framework,skill:ae}))),oe=0;for(let[ae,P]of X.entries()){let q=Z[ae];q&&(P.status==="fulfilled"?(ho(J,re,P.value),oe++):ue.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:q.skillId,skillName:q.skillName,err:String(P.reason)}))}oe>0&&(B.skills=J,ue.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:Z.length}))}return await Ue(B,this.paths),ue.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(T){throw ue.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await vE(u.root,{recursive:!0,force:!0}).catch(D=>ue.warn("rm agent dir failed (ignored)",{err:String(D)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(b)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&ud(e.framework))u=RE;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);ud(e.framework)&&!hs(e.framework)&&(ue.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await cr(e.framework));let f=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:f,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else{let g=e.sessions.get(i),m=Zt(e)?g?.permissionMode??J0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,this.buildBinShimPathEnv(),m)}try{return await x.start(),await x.initialize(DE),x}catch(g){let m=x instanceof Nt?x.getStderrTail():[];throw m.length>0&&ue.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof k?g.code:"unknown",recentStderr:m}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,g)}}async resolveSpawnFailure(e,r,i){if(e.framework==="openclaw"&&e.deployType==="local"&&r)try{let o=await this.detectorFactory().probeOpenclawGateway(r);if(!o.reachable)return new k("AGENT_ENV_NOT_READY",V0(o),{cause:{reason:$0}})}catch(o){ue.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};ue.warn("openclaw default agent stale or missing, attempting lazy re-detect");let r=await this.detectorFactory().detect("openclaw");if(r?.defaultAgent?.id&&r.defaultAgent.workspace)return ue.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:PE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new k("AGENT_ENV_NOT_READY",V0(r),{cause:{reason:$0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,f=dd(o);if(r.deployType==="local"){let m=await this.ensureOpenclawDefaultAgent();return new Br({command:u,cwd:m.workspace,agentId:m.id,sessionName:f})}let x=await W0(),g;if(i?.modelToken){let m=$c(o),S=Vc(i),y=`${m}/${S}`;if(!this.ensuredProviders.has(y)){let b=this.getOpenclawConfig(),I=await b.getAllowlistModelsForProvider(m),A=Qf(i,c,d,I);A&&(await b.ensureProvider(m,A),await b.addModelToAllowlist(y),this.ensuredProviders.add(y))}g=y}return new Br({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:f,...x?{gatewayToken:x}:{},...g?{slashModelOnStart:g}:{}})}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=$c(c),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(x){f=!1,ue.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){f=!1,ue.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as th}from"node:crypto";import{promises as UE}from"node:fs";import{basename as nh}from"node:path";$e();ne();import{promises as LE}from"node:fs";import{basename as NE}from"node:path";var Y0=W("file-upload"),ME="/api/coze_claw/file/agent_upload",BE=6e4;async function X0(t,e={}){let i=`${Cr(Rr(e.handshakeBase))}${ME}`,o=e.timeoutMs??BE,c=await LE.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",...Sn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);Y0.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:f.signal}),m=g.headers.get("x-tt-logid")??"";if(!g.ok){let b=await g.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${m}: ${b.slice(0,200)}`)}let S=await g.json();if(S.code!==void 0&&S.code!==0)throw new k("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${m}`);let y=S.data?.file?.file_url;if(!y)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${m}: ${JSON.stringify(S).slice(0,200)}`);return Y0.info("file upload ok",{uri:y,logid:m}),{uri:y}}catch(g){throw g instanceof k?g:g.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${NE(t.path)}`):new k("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}$e();ne();import{extname as FE}from"node:path";var zE={".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 Q0(t){let e=FE(t).toLowerCase();return zE[e]??"application/octet-stream"}Me();var So=W("agent-send"),eh=50*1024*1024;function rh(t,e,r){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new k("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function ih(t,e,r,i,o,c){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(x){u=x,f<2&&(So.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(g=>setTimeout(g,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function sh(t,e){let{session:r,runtime:i}=rh(e.core,t.agentId,t.sessionId);if(!await ri(t.path,r.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await UE.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>eh)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${eh}`);let c=await Q0(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??nh(t.path),u;try{u=await X0({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 So.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:th(),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 ih(e,r,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),So.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 oh(t,e){let{session:r,runtime:i}=rh(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??nh(t.path),c={sessionUpdate:"group_file",messageId:th(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ih(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),So.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 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}an();Jt();ne();var Bt=W("coze-cli-installer"),ch="@coze/cli@latest",qE="coze",dh="0.1.8",GE=5e3,HE=5e3,jE=9e4,lh=1e4,Hi=null,Io=!1;async function xd(t,e={}){if(Io)return;if(Hi)return Hi;let r=e.exec??zf;return Hi=(async()=>{try{let i=await WE(qE,r),o=!1;if(i){let d=await KE(r);if(d===void 0)Bt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(ah(d,dh))Bt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:dh}),o=!0;else{Bt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Io=!0;return}}let c=o?"upgrade-only":"full";Bt.info("coze-cli install start",{package:ch,mode:c});try{await r("npm",["i","-g","--prefer-online",ch],{timeout:jE,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){Io=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:lh}),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:lh}),Bt.info("coze auth login ok")}catch(d){Bt.warn("coze auth login failed",{err:String(d)});return}Io=!0}finally{Hi=null}})(),Hi}async function WE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:GE});return Pa(i)}catch{return}}async function KE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:HE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}dn();Me();var $E=10*6e4;function uh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?$E:e}function Ao(t){return dr(t??ee().configFile)}function ji(t,e){return lr(e??ee().configFile,t)}import{randomBytes as hb}from"node:crypto";sr();$e();ne();import{createReadStream as VE}from"node:fs";import{mkdir as JE,readFile as ZE,realpath as YE,stat as XE,writeFile as QE}from"node:fs/promises";import{basename as eb,dirname as pd,isAbsolute as tb,join as nb,relative as rb,resolve as fh,sep as ib}from"node:path";import{createInterface as sb}from"node:readline";var xh=W("fs-rpc"),Wi=Je("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function ph(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Wi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Wi} bytes`);let i=await mh(t.path,e);return await JE(pd(i),{recursive:!0}),await QE(i,t.content,"utf8"),xh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function gh(t,e){let r=await mh(t.path,e),i=await XE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Wi&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Wi} bytes`);let c;if(o&&i.size>Wi)c=await ob(r,t.line??1,t.limit);else{let d=await ZE(r,"utf8");if(o){let u=d.split(`
102
+ `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;c=u.slice(f,x).join(`
103
+ `)}else c=d}return xh.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function ob(t,e,r){let i=sb({input:VE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let f of i)if(u>=o&&u<c&&d.push(f),u++,u>=c)break}finally{i.close()}return d.join(`
104
+ `)}async function mh(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([hh(fh(e)),hh(fh(t))]),o=rb(r,i);if(ab(o,ib,tb(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function ab(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function hh(t){let e=[],r=t;for(;r!==pd(r);)try{let i=await YE(r);return e.length?nb(i,...e.reverse()):i}catch{e.push(eb(r)),r=pd(r)}return t}ne();var wh=W("prompt-multimodal"),_h=10*1024*1024,cb=15e3,db=6;async function yh(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 lb(d))}}let o=Array.from({length:Math.min(db,t.length)},()=>i());return await Promise.all(o),e}function Eh(t){return t.some(e=>e.type==="image")}async function lb(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Di(e.uri))return t;try{let{buf:r,contentType:i}=await fb(e.uri),o=e.mimeType||ub(i)||"application/octet-stream";return wh.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 wh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function ub(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function fb(t){let e=new AbortController,r=setTimeout(()=>e.abort(),cb);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>_h)throw new Error(`image too large: ${o.byteLength} bytes (max ${_h})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}ln();$e();ne();var V=W("core"),xb=3e4,pb=/^(boe|ppe)_[A-Za-z0-9_-]+$/,gb="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",mb="\u5BA1\u6279\u5DF2\u8D85\u65F6",wb=3e4,ko=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Lr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=uh(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),V.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){V.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),V.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){V.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)&&V.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)=>{V.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),Gi(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){V.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(An(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(d=>V.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)){V.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 k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(po(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&&pb.test(i)?this.currentCozeEnv=i:i&&V.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):V.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Or(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Or(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Or(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):V.warn("drop unknown notification",{method:e.method})}catch(o){V.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(An(r,zi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let f=o.sessions.get(c);if(f?.pendingPermission){let x=r._meta?.cozeTriggerMsgId,g=ao(r._meta);return V.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,gb,x,g)}}let d=Date.now(),u=!1;try{let f=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,f}finally{V.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}=Mf(i);switch(r){case"session/new":{let c=_b();return V.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return V.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=Zt(e)?Nf(i._meta):void 0;if(u!==void 0&&!Mt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${cd(e.framework)}`);let f=await this.ensureRuntime(e,d);if(u!==void 0&&f.permissionMode===void 0&&(f.permissionMode=u,await this.persistSessionMapping(e)),f.replySeq=0,await this.ensureDownstream(e,d,f),!f.downstream||!f.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&f.permissionMode!==void 0&&f.permissionMode!==u){let S=f.permissionMode;f.permissionMode=u,await this.persistSessionMapping(e);try{await f.downstream.setSessionMode({sessionId:f.acpSessionId,modeId:u})}catch(y){throw f.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),y}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(f.acpSessionId,x):e.activeTriggers.delete(f.acpSessionId);let g=ao(i._meta);if(g?e.activeGroupIds.set(f.acpSessionId,g):e.activeGroupIds.delete(f.acpSessionId),g&&f.cozeGroupId!==g&&(f.cozeGroupId=g,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Eh(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let m=await yh(c.prompt);try{let S=await f.downstream.sessionPrompt({...c,sessionId:f.acpSessionId,prompt:m});return f.lastActiveAt=Date.now(),S}catch(S){if(S instanceof k&&S.code==="AGENT_APPROVAL_TIMEOUT"){let y=f.pendingPermission;y&&(y.downstream.respondAgentRequest(y.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(y.upstreamId),f.pendingPermission=void 0);let b=f.acpSessionId,I=b?e.activeTriggers.get(b):void 0,A=b?e.activeGroupIds.get(b):void 0;return V.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,f,d,mb,I,A)}throw S}finally{if(e.activeTriggers.delete(f.acpSessionId),e.activeGroupIds.delete(f.acpSessionId),f.pendingPermission=void 0,f.reloadAfterTurn){f.reloadAfterTurn=!1;let S=f.downstream;S&&(f.downstream=void 0,V.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:f.acpSessionId}),S.stop("reload-after-turn").catch(y=>V.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(y)})))}else f.downstream?.isAlive()&&this.armIdleTimer(e,d,f)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let f=e.getSessionQueue(d);f.size>0&&(V.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=ao(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Zt(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(!Mt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${cd(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 g=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(m){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),m}else V.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return V.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};V.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of o){let u=d.runtime.downstream,f=d.runtime.acpSessionId;u?.isAlive()&&f&&c.push({downstream:u,acpSessionId:f,oldMode:d.oldMode,runtime:d.runtime})}for(let d of c)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let f of o)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r){let i=e.sessions.get(r);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Zt(e)&&(c.permissionMode=e.framework==="claude-code"?fd:Z0),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(ht.GEN_MODEL_TOKEN,i,wb);if(!o?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return o.modelToken}catch(o){throw o instanceof k&&o.code==="MODEL_TOKEN_GEN_FAILED"?o:new k("MODEL_TOKEN_GEN_FAILED",o instanceof Error?o.message:String(o),{cause:o})}}async ensureDownstream(e,r,i){if(Gi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let f;try{f=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(V.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),V.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){V.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let g=await f.sessionNew({cwd:e.workspace});i.acpSessionId=g.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw V.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),Zt(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){V.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(Gi(i),this.isRuntimeBusy(e,i)){V.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)){V.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}V.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=>V.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(Dr("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(Dr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>V.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){V.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){V.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(bb(r)){V.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"&&Zt(e)){let g=d.currentModeId;Mt(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(m=>V.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(m)}))):typeof g=="string"&&!Mt(e.framework,g)&&V.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:g})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Dr("session/update",{...r,sessionId:o,_meta:u})).catch(g=>V.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}V.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 ph(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await gh(c,o);r.respondAgentRequest(i.id,d)}}catch(o){V.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,zi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let g=u?e.activeGroupIds.get(u):void 0;g&&(x.cozeGroupId=g);let m=u?this.reverseSessionId(e,u):void 0,S=m?e.sessions.get(m):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let y={...c,...m?{sessionId:m}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:m}),V.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:m,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(b=>({optionId:b.optionId,kind:b.kind,name:b.name}))}),this.upstream.send(Bi(o,"session/request_permission",y)).catch(b=>{this.pendingUpstream.delete(o),V.error("forward permission request failed",{agentId:e.agentId,err:String(b)}),r.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(b)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(V.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"&&yb(e.result,o),V.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 xo(e.error)):i.value.resolve(e.result);return}V.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 V.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:d,key:c}}}sendRequest(e,r,i=xb){let o=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(Bi(o,e,r)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(f)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Zt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await ii(e.agentId,r,this.paths)}catch(r){V.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(An(e,{code:r,message:i,data:{bridgeVersion:Ot}}))}};function _b(){return hb(16).toString("hex")}function yb(t,e){if(!t||typeof t!="object"){V.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){V.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"){V.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")&&V.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var Eb=["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."],bh="Warning: ";function bb(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 o=i.text.startsWith(bh)?i.text.slice(bh.length):i.text;return Eb.some(c=>o.startsWith(c))}dn();ne();Me();import{randomBytes as vb}from"node:crypto";import{createServer as Sb}from"node:http";var Ib=1e6,vh=W("ipc"),To=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??ee()}async start(){this.token=vb(32).toString("hex");let e=Sb((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(),vh.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,i)=>{e.close(o=>o?i(o):r())}),this.server=null)}async persistAuthFiles(){await cn(this.paths.portFile,String(this.port)),await cn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Ki(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Ki(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await Ab(e)}catch(u){Ki(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Ki(r,200,u??{ok:!0})}catch(u){vh.error("IPC handler failed",{key:o,err:String(u)}),Ki(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Ki(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function Ab(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>Ib)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 $v=Gt(_x(),1),Vv=Gt(Bo(),1),Jv=Gt(Ur(),1),Zv=Gt(Ad(),1),Yv=Gt(Cd(),1),Xv=Gt(Nd(),1),Tx=Gt(qo(),1),Qv=Gt(kx(),1);var Cx=Tx.default;$e();ne();var{FWS:p1}=Ux(),Oe=W("upstream.frontier"),Gx="application/json",Hx="none",g1=15e3;function m1(t){class e extends Cx{constructor(i){super(i,qf,{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(Il("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let d=Buffer.from(c.slice(0,128)).toString("hex");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 ts=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Oe.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Gf,...Sn(this.opts.ppeOverride)},r=m1(e),i=jf(this.opts.urlOverride),o={url:i,ws:r,fpID:Uf,aID:co,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Gx,force:!0},payloadEncoding:{encoding:Hx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new p1(o),d=!1,u=null,f,x,g=new Promise((y,b)=>{f=y,x=b}),m=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?x(y):f())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Oe.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&m();for(let b of this.connectHandlers)Promise.resolve(b({initial:y})).catch(I=>Oe.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,Oe.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{Oe.warn("frontier error",{code:y.code,msg:y.message}),m(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},c.onmessage=y=>this.handleMessage(y),this.fws=c;let S=this.opts.openTimeoutMs??g1;u=setTimeout(()=>{m(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await g}catch(y){try{c.close(1e3,"open failed")}catch(b){Oe.warn("fws close during start failure threw (ignored)",{err:String(b)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){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 k("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 k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;jx(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:Gx,payloadEncoding:Hx})}catch(u){throw Oe.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=r(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let r=e.message?.service;if(r!==33555712){Oe.debug("drop non-adapter frontier frame",{service:r});return}let i=y1(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;jx(c)||Oe.info("frontier frame in",{logid:_1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:w1(i)}),Promise.resolve(this.handler(o)).catch(d=>Oe.warn("frontier frame handler threw",{err:String(d)}))}};function jx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Wx=2e3;function w1(t){return t.length<=Wx?t:`${t.slice(0,Wx)}...<truncated, total ${t.length} chars>`}function _1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function y1(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}}$e();ne();var zd=W("skill-publish"),E1="/api/marketplace/product/skill/publish_with_assets",b1=15e4;async function Kx(t,e={}){let i=`${Cr(Rr(e.handshakeBase))}${E1}`,o=e.timeoutMs??b1,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",...Sn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);zd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let y=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${y.slice(0,200)}`)}let m=await x.json();if(zd.info("skill publish response",{logid:g,httpStatus:x.status,code:m.code,msg:m.msg,dataSkillId:m.data?.skill_id??"",dataVersion:m.data?.version??""}),m.code!==void 0&&m.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${m.code} msg=${m.msg??"-"} logid=${g}`);let S={};return m.data?.skill_id!==void 0&&m.data.skill_id!==""&&(S.skillId=String(m.data.skill_id)),m.data?.version&&(S.version=m.data.version),zd.info("skill publish ok",{logid:g,skillId:S.skillId??"",version:S.version??""}),S}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(f)}}ne();var Ud=W("upstream.switchable"),Zo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Ud.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 Ud.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Ud.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 qd=W("upstream"),Kr=class{handler=null;async start(){qd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){qd.info("NoopUpstream stopped",{reason:e})}async send(e){qd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};$e();ne();dn();ne();Me();import{promises as v1}from"node:fs";var $x=W("pat-token-store");async function Yo(t=ee()){try{let r=(await v1.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?($x.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"&&$x.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function ns(t,e=ee()){if(!t)throw new Error("writePatToken: empty patToken");await cn(e.patTokenFile,t,{mode:384})}Me();Me();import{promises as Xo}from"node:fs";import{join as S1}from"node:path";function I1(t,e){return`#!/bin/sh
111
105
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
112
- `}function NS(t,e){return`@echo off\r
106
+ `}function A1(t,e){return`@echo off\r
113
107
  "${e}" "${t}" %*\r
114
- `}async function Xx(t,e=ee()){let r=e.binDir;await ta.mkdir(r,{recursive:!0});let i=OS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?NS(t,o):LS(t,o);return await ta.readFile(i,"utf8").catch(()=>null)===c||(await ta.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ta.chmod(i,493)),r}ne();Be();import{execSync as Yx}from"node:child_process";import{readFileSync as Qx,unlinkSync as MS}from"node:fs";import{mkdir as BS,open as FS,readFile as ep,unlink as Wd,writeFile as zS}from"node:fs/promises";import{dirname as US}from"node:path";var GS=H("single-instance"),HS=t=>new Promise(e=>setTimeout(e,t)),na=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??ee().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>qi(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&GS.warn("removing stale pid file",{stalePid:i}),await zS(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 ep(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Wd(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 ep(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 BS(US(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await FS(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 HS(this.claimLockIntervalMs);continue}await Wd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Wd(r).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${r} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let r=Qx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Mr)||r.includes("lib/index.js"))}catch{}try{let r=Yx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Mr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Yx(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let o=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return o.includes("node")||o.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Qx(this.pidFile,"utf8").trim()===String(this.selfPid)&&MS(this.pidFile)}catch{}})}};ra();ne();var tr=H("daemon.upstream-watchdog"),ZS=12e4,XS=9e5,YS=3e4;function $d(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ia=class{constructor(e){this.opts=e;this.softMs=e.softMs??$d("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",ZS),this.hardMs=e.hardMs??$d("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",XS),this.intervalMs=e.intervalMs??$d("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",YS),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?.(),tr.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&&tr.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&&tr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,tr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){tr.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,tr.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>tr.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 rp(){let t=ee();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Il({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:D=>Xe(D,t).logs,listAgentIds:()=>ms(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
108
+ `}async function Vx(t,e=ee()){let r=e.binDir;await Xo.mkdir(r,{recursive:!0});let i=S1(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?A1(t,o):I1(t,o);return await Xo.readFile(i,"utf8").catch(()=>null)===c||(await Xo.writeFile(i,c,"utf8"),process.platform!=="win32"&&await Xo.chmod(i,493)),r}ne();Me();import{execSync as Jx}from"node:child_process";import{readFileSync as Zx,unlinkSync as k1}from"node:fs";import{mkdir as T1,open as C1,readFile as Yx,unlink as Gd,writeFile as R1}from"node:fs/promises";import{dirname as P1}from"node:path";var D1=W("single-instance"),O1=t=>new Promise(e=>setTimeout(e,t)),Qo=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??ee().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Ui(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&D1.warn("removing stale pid file",{stalePid:i}),await R1(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 Yx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Gd(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 Yx(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 T1(P1(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await C1(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 O1(this.claimLockIntervalMs);continue}await Gd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Gd(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=Zx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Nr)||r.includes("lib/index.js"))}catch{}try{let r=Jx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Nr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Jx(`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{Zx(this.pidFile,"utf8").trim()===String(this.selfPid)&&k1(this.pidFile)}catch{}})}};ea();ne();var er=W("daemon.upstream-watchdog"),q1=12e4,G1=9e5,H1=3e4;function jd(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ta=class{constructor(e){this.opts=e;this.softMs=e.softMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",q1),this.hardMs=e.hardMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",G1),this.intervalMs=e.intervalMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",H1),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?.(),er.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&&er.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&&er.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,er.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){er.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,er.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>er.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 K=W("daemon");async function ep(){let t=ee();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){vl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Ze(P,t).logs,listAgentIds:()=>xs(t)});try{let{writeFileSync:P}=await import("node:fs");P(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
115
109
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
116
110
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
117
- `)}catch{}}let e=new na({processTitle:Mr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Co(),o=i??{};xs({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let c=new Qo(new $r),d=null,u=new Ro({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(D,U,W,te)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(D,U,W,te)}}),h=new Ao({paths:t,config:o,registry:u});d=h;let x,m,_=null,S={},y,v=null,I=null,A=null,C=new Tn;function P(D,U){return C.enqueue(()=>R(D,U))}function b(){I||(I=new ia({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:D=>{if(process.env[os]==="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 W=D,te=W?.privatecode;if(!te)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let nt=Bi(W.env),pe=W.handshake_url,ge=W.frontier_url,kt=np(W.env,pe,ge);if(A=W,!U?.force&&x===te&&m===kt){let ye=await QS(t);return u.agents.size===0&&ye?(q.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),oa(t,h).catch(Re=>q.warn("connect-noop auto-revive error (ignored)",{err:String(Re)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let wt=!!x&&x!==te,sn=m!==void 0&&m!==kt,qt=wt||sn,on=await Wc({privatecode:te,...pe?{endpoint:pe}:{},ppeOverride:nt});if(qt){q.warn("connect config switched, resetting agents",{pcChanged:wt,envChanged:sn,previousPc:x?sa(x):"",nextPc:sa(te)});for(let ye of[...u.agents.values()])await ye.dispose("connect config switch").catch(()=>{}),u.agents.delete(ye.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 $r,"connect switch").catch(()=>{})}_=on.deviceId,xs({deviceId:_,pid:process.pid}),md({patToken:te,env:W.env}).catch(ye=>q.warn("coze-cli setup error (ignored)",{err:String(ye)}));let Yr=new is({handshake:on,privatecode:te,...ge?{urlOverride:ge}:{},ppeOverride:nt,getPatTokenForAgent:ye=>u.agents.get(ye)?.patToken});return await c.swap(Yr,"connect"),x=te,m=kt,S=nt,y=pe,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),q.info("mock scenario set",{scenario:W.mock_scenario})),v||(v=new zi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>N.retryPending().catch(ye=>q.warn("detailSync.retryPending failed (ignored)",{err:String(ye)})),onAuthFailures:J})),v.start(),b(),qt&&oa(t,h).catch(ye=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(ye)})),ss(te,t).catch(ye=>q.warn("writePatToken after /connect failed (ignored)",{err:String(ye)})),q.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async D=>h.createAgent(D.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},M=new xo({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 Jx({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:y,ppeOverride:S})},disposeAndMarkDisconnected:async(D,U)=>{let W=u.agents.get(D);if(W){await h.cleanupOpenclawSessionProviders(W).catch(nt=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:D,err:String(nt)}));let te=!0;try{await W.dispose(`disconnect: ${U}`)}catch(nt){te=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:D,err:String(nt)}),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=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:D,err:String(te)})),await W.dispose(`delete: ${U}`).catch(te=>q.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=>M.listSkills(D.params)),u.registerExtension("_agent/addSkills",D=>M.addSkills(D.params)),u.registerExtension("_agent/removeSkills",D=>M.removeSkills(D.params)),u.registerExtension("_agent/publishSkill",D=>M.publishSkill(D.params)),u.registerExtension("_agent/getFileTree",D=>M.getFileTree(D.params)),u.registerExtension("_agent/getFileContent",D=>M.getFileContent(D.params)),u.registerExtension("_agent/update",D=>M.updateAgent(D.params)),u.registerExtension("_agent/disconnect",D=>M.disconnectAgent(D.params)),u.registerExtension("_agent/switchModel",D=>M.switchModel(D.params)),u.registerExtension("_agent/reset",D=>M.resetAgent(D.params)),u.registerExtension("_agent/repair",D=>M.repairAgent(D.params)),u.registerExtension("_agent/delete",D=>M.deleteAgent(D.params)),u.registerExtension("_agent/upgrade",D=>M.upgradeBridge(D.params));let N=new ys({paths:t,handlers:M,agentManager:h,sendDetail:D=>u.sendRequest("_agent/detail",D)});O.ref=N;let J=async D=>{await Promise.allSettled(D.map(async U=>{try{await M.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(W){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(W)})}}))};c.onConnect(({initial:D})=>{q.info("frontier upstream connected, triggering detail sync",{initial:D}),N.syncAll(D?"initial-connect":"reconnect").catch(U=>q.warn("detail sync top-level error (ignored)",{err:String(U)}))});let V=new Do({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[os]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:_??"",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 nt=Bi(U.env),pe=U.handshake_url,ge=U.frontier_url,kt=np(U.env,pe,ge),wt=!!x&&x!==W,sn=m!==void 0&&m!==kt,qt=wt||sn,on=await Wc({privatecode:W,...pe?{endpoint:pe}:{},ppeOverride:nt});if(qt){q.warn("pair config switched, resetting agents",{pcChanged:wt,envChanged:sn,previousPc:x?sa(x):"",nextPc:sa(W),previousEnvKey:m??"",nextEnvKey:kt});for(let Re of[...u.agents.values()])await Re.dispose("pair config switch").catch(()=>{}),u.agents.delete(Re.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 $r,"pair switch").catch(()=>{})}_=on.deviceId,xs({deviceId:_,pid:process.pid}),md({patToken:W,env:U.env}).catch(Re=>q.warn("coze-cli setup error (ignored)",{err:String(Re)}));let Yr=new is({handshake:on,privatecode:W,...ge?{urlOverride:ge}:{},ppeOverride:nt,getPatTokenForAgent:Re=>u.agents.get(Re)?.patToken});await c.swap(Yr,"pair");try{let Re=new Jn;o.frameworksCache=await Re.detectAll(),await $i(o),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Re){q.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Re)})}let ye=Object.keys(o.frameworksCache??{});try{let Re=await u.sendRequest("_agent/pair",{pairCode:te,patToken:W,frameworks:ye,_meta:{cozeDeviceId:_}});q.info("_agent/pair ok",{pairResult:Re}),x=W,m=kt,S=nt,y=pe,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),q.info("mock scenario set",{scenario:U.mock_scenario})),ss(W,t).catch(Me=>q.warn("writePatToken after /pair failed (ignored)",{err:String(Me)})),v||(v=new zi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>N.retryPending().catch(Me=>q.warn("detailSync.retryPending failed (ignored)",{err:String(Me)})),onAuthFailures:J})),v.start(),b(),qt&&oa(t,h).catch(Me=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(Me)}));let nr;return U.agent_id&&(nr=await t1(U.agent_id,t,h,Me=>u.sendRequest("_agent/detail",Me),W).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",...nr?{agent:nr}:{}}}catch(Re){return q.error("_agent/pair failed",{err:String(Re)}),{ok:!1,note:`pair failed: ${String(Re)}`}}}},{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?dh:ch)(W,{core:u,patToken:x,handshakeBase:y,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 q.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:Y}=await V.start();try{await Xx(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(),n1({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new Jn().detectAll(),await $i(o),o.frameworksCache)}).catch(D=>q.warn("startup warmup error (ignored)",{err:String(D)})),Nl().then(async()=>{let{probeAcpVersion:D}=await Promise.resolve().then(()=>(dn(),Ol));for(let U of["claude-code","codex"]){let W=await D(U);W&&q.info("acp wrapper version",{framework:U,version:W})}}).catch(D=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(D)}));let se=null,ae={port:re,token:Y,core:u,ipc:V,shutdown(D){return se||(q.info("daemon shutdown",{reason:D}),se=(async()=>{v?.stop(),I?.stop(),await u.stop(D),await V.stop(),await e.release()})(),se)}};for(let D of["SIGTERM","SIGINT"])process.on(D,()=>{ae.shutdown(D).then(()=>process.exit(0))});return process.on("exit",()=>C0()),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}
118
- `)}catch{}process.exit(1)}),q.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),i1({cliSpawned:process.env[os]==="1",readPatToken:()=>ea(t),connect:P}).catch(D=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(D)})),ae}async function QS(t){return ms(t).length>0}function sa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function np(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function e1(t,e){let r=ms(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(fn(),_s));for(let c of r){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 t1(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(fn(),_s)),d=await c(t,e);if(d){if(d.deletedAt)throw new T("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let m=ip(d),_={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...m?{_meta:m}:{}};return await r.createAgent(_),{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 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 n1(t){let e=t.logger??q;try{let r=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(r??{})})}catch(r){e.warn("framework detection failed (using cached)",{err:String(r)})}await e1(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await oa(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await r1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function oa(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(()=>(fn(),_s));q.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){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){q.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){q.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{q.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=ip(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){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.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 r1(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 g0(o,t)).status==="refreshed"&&(i+=1)}catch(c){q.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&q.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function i1(t){let e=t.logger??q;if(t.cliSpawned)return"skipped-cli";let r=await t.readPatToken();return r?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:r}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function ip(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ra();Be();import{readFile as sp}from"node:fs/promises";var rn=class{paths;constructor(e){this.paths=e??ee()}async probe(e=1e3){let r=await aa(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:o1(i)}}}async request(e){let r=await aa(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:s1(h)}}finally{clearTimeout(d)}}};async function aa(t){try{let[e,r]=await Promise.all([sp(t.portFile,"utf8"),sp(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 s1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function o1(t){return t instanceof Error?t.message:String(t)}Xt();ne();or();import{spawn as a1}from"node:child_process";import{userInfo as ap}from"node:os";var Vd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",c1=new Set(["bash","zsh","sh","dash","ksh"]),op=Ze("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),d1=2e3;function l1(t,e=Vd){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let d of o.split(`
119
- `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function u1(){let t=(process.env.SHELL??"").trim()||(ap().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return c1.has(e)?t:null}function f1(t){return new Promise(e=>{let r=`printf '%s' '${Vd}'; env; printf '%s' '${Vd}'`,i;try{i=a1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??ap().homedir}})}catch{e(null);return}let o="",c=!1,d=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{c||(c=!0,clearTimeout(h),clearTimeout(x),e(m))};i.stdout?.on("data",m=>{o+=m.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let h=setTimeout(()=>d("SIGTERM"),op),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},op+d1)})}async function Jd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=u1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??f1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=l1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Be();function Dn(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}}dn();import{chmod as h1,copyFile as cp,mkdir as lp,readFile as cs,rename as dp,rm as Yd,stat as up,writeFile as x1}from"node:fs/promises";import{homedir as kP}from"node:os";import{dirname as p1,join as Ne,resolve as Qd,sep as as}from"node:path";import{fileURLToPath as g1}from"node:url";Xt();ne();Be();function Vr(t,e,r,i){it(t.bridgeLogsDir,e,"dist-install",r,i)}function fp(){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 m1(){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 w1(t){let e=g1(t),r=p1(e),i=`${as}src${as}`;if(r.includes(i)||r.endsWith(`${as}src${as}cli`))return null;let o=Qd(r,"index.js"),c=Qd(r,"..","package.json");return{dist:o,pkgJson:c}}async function el(t={}){let e=t.paths??ee(),r=w1(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,d;try{let v=JSON.parse(await cs(o,"utf8"));c=v.version??"unknown",d=v.dependencies??{}}catch(v){throw Vr(e,"error","cannot read source package.json",{err:String(v)}),new Error(`cannot read source package.json: ${String(v)}`,{cause:v})}let u=ps.map(v=>({name:v,spec:d[v]??"latest"})),h=u.map(({name:v,spec:I})=>`${v}@${I}`),x=await Co(e.configFile)??{},m=x.libVersion,_=await cs(e.libEntry).then(()=>!0).catch(()=>!1),S=m===c,y=await hp(e,u);if(S&&_&&y)return{kind:"already-current",libVersion:c};if(!S||!_){await lp(e.libDir,{recursive:!0}),await cp(i,e.libEntry),await cp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=Qd(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
120
- `;await cs(v,"utf8").catch(()=>null)!==I&&await x1(v,I)}return y||(t.installWrappers?await t.installWrappers(e,h):await b1(e,h,u)),x.libVersion=c,await $i(x,e.configFile),Vr(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),S&&_?{kind:"already-current",libVersion:c}:m?{kind:"version-changed",fromVersion:m,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function hp(t,e){for(let r of e){let i=Ne(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await cs(i,"utf8"))}catch(d){return Vr(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 Vr(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!_1(c,r.spec))return Vr(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await xp(Ne(t.libDir,"node_modules"))}function _1(t,e){let r=Zd(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=Zd(i.slice(1));if(!c)return!0;if(Xd(r,c)<0)return!1;let d=y1(c);return Xd(r,d)<0}let o=Zd(i);return o?Xd(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 Zd(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Xd(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 b1(t,e,r){await S1(t.installLock,async()=>{if(await hp(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${as}.staging-${process.pid}-${i}`,c=Ne(o,"node_modules"),d=Ne(t.libDir,"node_modules");try{await lp(o,{recursive:!0}),await E1(e,o),await v1(c);let u=`${d}.trash-${i}`;await dp(d,u).catch(()=>{}),await dp(c,d),await Yd(u,{recursive:!0,force:!0}).catch(()=>{}),Vr(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await Yd(o,{recursive:!0,force:!0}).catch(()=>{})}})}function E1(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=ot("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 v1(t){for(let e of ps){let r=Ne(t,...e.split("/")),i=JSON.parse(await cs(Ne(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=Ne(t,".bin",o),d=await up(c);process.platform!=="win32"&&!(d.mode&73)&&await h1(c,d.mode|73).catch(()=>{})}if(!await xp(t)){let e=fp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function xp(t){let e=fp(),r=m1();if(!e||!r)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,r)];return(await Promise.all(c.map(u=>up(u).then(h=>h.isFile()).catch(()=>!1)))).every(Boolean)}async function S1(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 Yd(t,{force:!0}).catch(()=>{})}}Ca();ne();Be();import{closeSync as gp,fstatSync as mp,openSync as wp,readFileSync as I1,readSync as A1,readdirSync as k1,statSync as T1}from"node:fs";import{join as ca}from"node:path";var C1=new Set(["debug","info","warn","error"]);function _p(t){let e=t,r=Dn(e,"--agent-id");e=r.rest;let i=Dn(e,"--date");e=i.rest;let o=Dn(e,"-n","--lines");e=o.rest;let c=Dn(e,"--level");e=c.rest;let d=Dn(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&&C1.has(c.value)?c.value:void 0,m={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(m.agentId=r.value),i.value&&(m.date=i.value),x&&(m.level=x),d.value&&(m.grep=d.value),m}function R1(t,e){return t.agentId?ca(Xe(t.agentId,e).logs,ar("agent",t.date)):ca(e.bridgeLogsDir,ar("bridge",t.date))}function D1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function P1(t,e){let r;try{r=k1(t)}catch{return[]}let i=[];for(let o of r){let c=Ta(o,e);if(!c)continue;let d=0;try{d=T1(ca(t,o)).size}catch{}i.push({file:ca(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function yp(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let r;try{r=JSON.parse(t).level}catch{return!0}if(typeof r=="string"&&!Tl(r,e.level))return!1}return!0}var pp={debug:"90",info:"36",warn:"33",error:"31"},O1=new Set(["ts","level","module","msg"]);function L1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function bp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=L1(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&pp[o]&&(c=`\x1B[${pp[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])=>!O1.has(x)).map(([x,m])=>` ${x}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${d} ${u}${h}`}function N1(t,e,r){let c=I1(t,"utf8").split(`
121
- `).filter(d=>d.length>0).filter(d=>yp(d,{level:e.level,grep:e.grep}));for(let d of D1(c,e.lines))process.stdout.write(`${bp(d,{raw:e.raw,color:r})}
122
- `)}async function Ep(t,e){let r=e.paths??ee(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Xe(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=P1(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
123
- `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
124
- `);return 0}let o=t.date??On(new Date),c=R1({agentId:t.agentId,date:o},r);try{N1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
111
+ `)}catch{}}let e=new Qo({processTitle:Nr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Ao(),o=i??{};us({pid:process.pid}),K.info(i?"loaded bridge config":"initialized bridge config");let c=new Zo(new Kr),d=null,u=new ko({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,q,$,te)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,q,$,te)}}),f=new vo({paths:t,config:o,registry:u});d=f;let x,g,m=null,S={},y,b=null,I=null,A=null,T=new kn;function D(P,q){return T.enqueue(()=>R(P,q))}function E(){I||(I=new ta({isConnected:()=>c.isConnected()&&!(b?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:P=>{if(process.env[rs]==="1"){K.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}K.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),I.start()}async function R(P,q){let $=P,te=$?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let et=Li($.env),me=$.handshake_url,we=$.frontier_url,At=Qx($.env,me,we);if(A=$,!q?.force&&x===te&&g===At){let Ee=await j1(t);return u.agents.size===0&&Ee?(K.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ra(t,f).catch(Te=>K.warn("connect-noop auto-revive error (ignored)",{err:String(Te)}))):K.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let gt=!!x&&x!==te,nn=g!==void 0&&g!==At,qt=gt||nn,rn=await Gc({privatecode:te,...me?{endpoint:me}:{},ppeOverride:et});if(qt){K.warn("connect config switched, resetting agents",{pcChanged:gt,envChanged:nn,previousPc:x?na(x):"",nextPc:na(te)});for(let Ee of[...u.agents.values()])await Ee.dispose("connect config switch").catch(()=>{}),u.agents.delete(Ee.agentId);u.disconnectedAgents.size>0&&(K.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"connect switch").catch(()=>{})}m=rn.deviceId,us({deviceId:m,pid:process.pid}),xd({patToken:te,env:$.env}).catch(Ee=>K.warn("coze-cli setup error (ignored)",{err:String(Ee)}));let Yr=new ts({handshake:rn,privatecode:te,...we?{urlOverride:we}:{},ppeOverride:et,getPatTokenForAgent:Ee=>u.agents.get(Ee)?.patToken});return await c.swap(Yr,"connect"),x=te,g=At,S=et,y=me,$.mock_scenario!==void 0&&(u.setMockScenario($.mock_scenario),K.info("mock scenario set",{scenario:$.mock_scenario})),b||(b=new Mi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>B.retryPending().catch(Ee=>K.warn("detailSync.retryPending failed (ignored)",{err:String(Ee)})),onAuthFailures:Z})),b.start(),E(),qt&&ra(t,f).catch(Ee=>K.warn("post-connect-switch auto-revive error (ignored)",{err:String(Ee)})),ns(te,t).catch(Ee=>K.warn("writePatToken after /connect failed (ignored)",{err:String(Ee)})),K.info("/connect: WS established",{deviceId:m}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>f.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},F=new uo({agents:u.agents,publishSkillToMarketplace:async P=>{let q=u.agents.get(P.agentId)?.patToken??x;if(!q)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Kx({patToken:q,zip:P.zip,...P.skillId?{skillId:P.skillId}:{},skillName:P.skillName,...P.description?{description:P.description}:{},agentId:P.agentId,...P.accountId?{accountId:P.accountId}:{}},{handshakeBase:y,ppeOverride:S})},disposeAndMarkDisconnected:async(P,q)=>{let $=u.agents.get(P);if($){await f.cleanupOpenclawSessionProviders($).catch(et=>K.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(et)}));let te=!0;try{await $.dispose(`disconnect: ${q}`)}catch(et){te=!1,K.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(et)}),$.status="error"}te&&($.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,q)=>{let $=u.agents.get(P);$&&(await f.cleanupOpenclawSessionProviders($).catch(te=>K.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(te)})),await $.dispose(`delete: ${q}`).catch(te=>K.warn("dispose during delete failed (ignored)",{agentId:P,err:String(te)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(P)},cleanupOpenclawProviders:async(P,q)=>{await f.cleanupOpenclawSessionProviders(P,q)},openclawRepair:async(P,q)=>{await f.openclawRepair(P,q)},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>F.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>F.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>F.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>F.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>F.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>F.getFileContent(P.params)),u.registerExtension("_agent/update",P=>F.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>F.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>F.switchModel(P.params)),u.registerExtension("_agent/reset",P=>F.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>F.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>F.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>F.upgradeBridge(P.params));let B=new ms({paths:t,handlers:F,agentManager:f,sendDetail:P=>u.sendRequest("_agent/detail",P)});O.ref=B;let Z=async P=>{await Promise.allSettled(P.map(async q=>{try{await F.disconnectAgent({agentId:q.agentId,reason:`auth_failure: code=${q.code} ${q.message}`}),K.info("agent disconnected due to auth failure from heartbeat response",{agentId:q.agentId,code:q.code,message:q.message})}catch($){K.warn("disconnect during authFailure handling failed (ignored)",{agentId:q.agentId,err:String($)})}}))};c.onConnect(({initial:P})=>{K.info("frontier upstream connected, triggering detail sync",{initial:P}),B.syncAll(P?"initial-connect":"reconnect").catch(q=>K.warn("detail sync top-level error (ignored)",{err:String(q)}))});let J=new To({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let P=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[rs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:m??"",frameworksCache:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let q=P,$=q?.privatecode,te=q?.pairing_code;if(!$||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let et=Li(q.env),me=q.handshake_url,we=q.frontier_url,At=Qx(q.env,me,we),gt=!!x&&x!==$,nn=g!==void 0&&g!==At,qt=gt||nn,rn=await Gc({privatecode:$,...me?{endpoint:me}:{},ppeOverride:et});if(qt){K.warn("pair config switched, resetting agents",{pcChanged:gt,envChanged:nn,previousPc:x?na(x):"",nextPc:na($),previousEnvKey:g??"",nextEnvKey:At});for(let Te of[...u.agents.values()])await Te.dispose("pair config switch").catch(()=>{}),u.agents.delete(Te.agentId);u.disconnectedAgents.size>0&&(K.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"pair switch").catch(()=>{})}m=rn.deviceId,us({deviceId:m,pid:process.pid}),xd({patToken:$,env:q.env}).catch(Te=>K.warn("coze-cli setup error (ignored)",{err:String(Te)}));let Yr=new ts({handshake:rn,privatecode:$,...we?{urlOverride:we}:{},ppeOverride:et,getPatTokenForAgent:Te=>u.agents.get(Te)?.patToken});await c.swap(Yr,"pair");try{let Te=new Vn;o.frameworksCache=await Te.detectAll(),await ji(o),K.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Te){K.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Te)})}let Ee=Object.keys(o.frameworksCache??{});try{let Te=await u.sendRequest("_agent/pair",{pairCode:te,patToken:$,frameworks:Ee,_meta:{cozeDeviceId:m}});K.info("_agent/pair ok",{pairResult:Te}),x=$,g=At,S=et,y=me,q.mock_scenario!==void 0&&(u.setMockScenario(q.mock_scenario),K.info("mock scenario set",{scenario:q.mock_scenario})),ns($,t).catch(Ne=>K.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),b||(b=new Mi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>B.retryPending().catch(Ne=>K.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:Z})),b.start(),E(),qt&&ra(t,f).catch(Ne=>K.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let tr;return q.agent_id&&(tr=await K1(q.agent_id,t,f,Ne=>u.sendRequest("_agent/detail",Ne),$).catch(Ne=>(K.error("--agent-id ensureAgent failed",{agentId:q.agent_id,err:String(Ne)}),{ok:!1,agentId:q.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...tr?{agent:tr}:{}}}catch(Te){return K.error("_agent/pair failed",{err:String(Te)}),{ok:!1,note:`pair failed: ${String(Te)}`}}}},{method:"POST",path:"/connect",handler:P=>D(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let q=P;return{ok:!0,result:await f.createAgent(q)}}},{method:"POST",path:"/agent/send",handler:async P=>{let q=P;if(!q?.agentId||!q?.sessionId||!q?.kind||!q?.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 $=q;return await($.groupFile?oh:sh)($,{core:u,patToken:x,handshakeBase:y,ppeOverride:S})}catch($){if($ instanceof k)return{ok:!1,code:$.code,message:$.message};throw $}}},{method:"POST",path:"/reload",handler:async P=>{let q=P?.agent_id,$=await u.reloadAgents(q);return K.info("IPC /reload: recycled agent subprocesses",{agentId:q??"(all)",recycled:$}),{ok:!0,recycled:$}}},{method:"POST",path:"/shutdown",handler:async()=>(K.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:X}=await J.start();try{await Vx(t.libEntry,t)}catch(P){K.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),$1({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new Vn().detectAll(),await ji(o),o.frameworksCache)}).catch(P=>K.warn("startup warmup error (ignored)",{err:String(P)})),Ol().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(an(),Pl));for(let q of["claude-code","codex"]){let $=await P(q);$&&K.info("acp wrapper version",{framework:q,version:$})}}).catch(P=>K.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let oe=null,ae={port:re,token:X,core:u,ipc:J,shutdown(P){return oe||(K.info("daemon shutdown",{reason:P}),oe=(async()=>{b?.stop(),I?.stop(),await u.stop(P),await J.stop(),await e.release()})(),oe)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{ae.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>k0()),process.on("unhandledRejection",P=>{K.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{K.error("uncaughtException (will exit, supervisor will restart)",{message:P.message,stack:P.stack,name:P.name});try{process.stderr.write(`FATAL uncaughtException: ${P.stack??P.message}
112
+ `)}catch{}process.exit(1)}),K.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),J1({cliSpawned:process.env[rs]==="1",readPatToken:()=>Yo(t),connect:D}).catch(P=>K.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),ae}async function j1(t){return xs(t).length>0}function na(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Qx(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function W1(t,e){let r=xs(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(ln(),gs));for(let c of r){await o(c,t).catch(d=>K.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),K.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),K.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){K.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function K1(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(ln(),gs)),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`);K.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let g=tp(d),m={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(m),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}K.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(f);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function $1(t){let e=t.logger??K;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 W1(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await ra(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await V1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function ra(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(()=>(ln(),gs));K.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){K.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){K.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){K.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{K.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=tp(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){K.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),d+=1}}return K.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function V1(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 x0(o,t)).status==="refreshed"&&(i+=1)}catch(c){K.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&K.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function J1(t){let e=t.logger??K;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 tp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ea();Me();import{readFile as np}from"node:fs/promises";var tn=class{paths;constructor(e){this.paths=e??ee()}async probe(e=1e3){let r=await ia(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:Y1(i)}}}async request(e){let r=await ia(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let i=r.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,d=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),f=await u.text();return{status:u.status,body:Z1(f)}}finally{clearTimeout(d)}}};async function ia(t){try{let[e,r]=await Promise.all([np(t.portFile,"utf8"),np(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 Z1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Y1(t){return t instanceof Error?t.message:String(t)}Jt();ne();sr();import{spawn as X1}from"node:child_process";import{userInfo as ip}from"node:os";var Wd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",Q1=new Set(["bash","zsh","sh","dash","ksh"]),rp=Je("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),eS=2e3;function tS(t,e=Wd){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let d of o.split(`
113
+ `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function nS(){let t=(process.env.SHELL??"").trim()||(ip().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return Q1.has(e)?t:null}function rS(t){return new Promise(e=>{let r=`printf '%s' '${Wd}'; env; printf '%s' '${Wd}'`,i;try{i=X1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??ip().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(f),clearTimeout(x),e(g))};i.stdout?.on("data",g=>{o+=g.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>d("SIGTERM"),rp),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},rp+eS)})}async function Kd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=nS();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??rS)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=tS(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Me();function Rn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],d=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||r.push(c)}return{value:i,rest:r}}an();import{chmod as iS,copyFile as sp,mkdir as ap,readFile as ss,rename as op,rm as Jd,stat as cp,writeFile as sS}from"node:fs/promises";import{homedir as xD}from"node:os";import{dirname as oS,join as Le,resolve as Zd,sep as is}from"node:path";import{fileURLToPath as aS}from"node:url";Jt();ne();Me();function $r(t,e,r,i){rt(t.bridgeLogsDir,e,"dist-install",r,i)}function dp(){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 cS(){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 dS(t){let e=aS(t),r=oS(e),i=`${is}src${is}`;if(r.includes(i)||r.endsWith(`${is}src${is}cli`))return null;let o=Zd(r,"index.js"),c=Zd(r,"..","package.json");return{dist:o,pkgJson:c}}async function Yd(t={}){let e=t.paths??ee(),r=dS(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 b=JSON.parse(await ss(o,"utf8"));c=b.version??"unknown",d=b.dependencies??{}}catch(b){throw $r(e,"error","cannot read source package.json",{err:String(b)}),new Error(`cannot read source package.json: ${String(b)}`,{cause:b})}let u=fs.map(b=>({name:b,spec:d[b]??"latest"})),f=u.map(({name:b,spec:I})=>`${b}@${I}`),x=await Ao(e.configFile)??{},g=x.libVersion,m=await ss(e.libEntry).then(()=>!0).catch(()=>!1),S=g===c,y=await lp(e,u);if(S&&m&&y)return{kind:"already-current",libVersion:c};if(!S||!m){await ap(e.libDir,{recursive:!0}),await sp(i,e.libEntry),await sp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let b=Zd(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
114
+ `;await ss(b,"utf8").catch(()=>null)!==I&&await sS(b,I)}return y||(t.installWrappers?await t.installWrappers(e,f):await fS(e,f,u)),x.libVersion=c,await ji(x,e.configFile),$r(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:c}),S&&m?{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 lp(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 ss(i,"utf8"))}catch(d){return $r(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 $r(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!lS(c,r.spec))return $r(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await up(Le(t.libDir,"node_modules"))}function lS(t,e){let r=$d(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=$d(i.slice(1));if(!c)return!0;if(Vd(r,c)<0)return!1;let d=uS(c);return Vd(r,d)<0}let o=$d(i);return o?Vd(r,o)===0:!0}function uS(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function $d(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Vd(t,e){for(let r=0;r<3;r++){let i=(t[r]??0)-(e[r]??0);if(i!==0)return i}return 0}async function fS(t,e,r){await pS(t.installLock,async()=>{if(await lp(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${is}.staging-${process.pid}-${i}`,c=Le(o,"node_modules"),d=Le(t.libDir,"node_modules");try{await ap(o,{recursive:!0}),await hS(e,o),await xS(c);let u=`${d}.trash-${i}`;await op(d,u).catch(()=>{}),await op(c,d),await Jd(u,{recursive:!0,force:!0}).catch(()=>{}),$r(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await Jd(o,{recursive:!0,force:!0}).catch(()=>{})}})}function hS(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=st("npm",r,{stdio:["ignore","pipe","pipe"]}),d="";c.stderr?.on("data",f=>{d.length<8192&&(d+=f.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",f=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(f)}`))}),c.once("close",f=>{clearTimeout(u),f===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${d.trim().slice(0,2e3)}`))})})}async function xS(t){for(let e of fs){let r=Le(t,...e.split("/")),i=JSON.parse(await ss(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 cp(c);process.platform!=="win32"&&!(d.mode&73)&&await iS(c,d.mode|73).catch(()=>{})}if(!await up(t)){let e=dp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function up(t){let e=dp(),r=cS();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=>cp(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function pS(t,e){let{open:r}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await r(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await Jd(t,{force:!0}).catch(()=>{})}}ka();ne();Me();import{closeSync as hp,fstatSync as xp,openSync as pp,readFileSync as gS,readSync as mS,readdirSync as wS,statSync as _S}from"node:fs";import{join as sa}from"node:path";var yS=new Set(["debug","info","warn","error"]);function gp(t){let e=t,r=Rn(e,"--agent-id");e=r.rest;let i=Rn(e,"--date");e=i.rest;let o=Rn(e,"-n","--lines");e=o.rest;let c=Rn(e,"--level");e=c.rest;let d=Rn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,x=c.value&&yS.has(c.value)?c.value:void 0,g={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(g.agentId=r.value),i.value&&(g.date=i.value),x&&(g.level=x),d.value&&(g.grep=d.value),g}function ES(t,e){return t.agentId?sa(Ze(t.agentId,e).logs,or("agent",t.date)):sa(e.bridgeLogsDir,or("bridge",t.date))}function bS(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function vS(t,e){let r;try{r=wS(t)}catch{return[]}let i=[];for(let o of r){let c=Aa(o,e);if(!c)continue;let d=0;try{d=_S(sa(t,o)).size}catch{}i.push({file:sa(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function mp(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"&&!Al(r,e.level))return!1}return!0}var fp={debug:"90",info:"36",warn:"33",error:"31"},SS=new Set(["ts","level","module","msg"]);function IS(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function wp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=IS(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&fp[o]&&(c=`\x1B[${fp[o]}m${c}\x1B[0m`);let d=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",f=Object.entries(r).filter(([x])=>!SS.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${d} ${u}${f}`}function AS(t,e,r){let c=gS(t,"utf8").split(`
115
+ `).filter(d=>d.length>0).filter(d=>mp(d,{level:e.level,grep:e.grep}));for(let d of bS(c,e.lines))process.stdout.write(`${wp(d,{raw:e.raw,color:r})}
116
+ `)}async function _p(t,e){let r=e.paths??ee(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Ze(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=vS(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
117
+ `),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
118
+ `);return 0}let o=t.date??Dn(new Date),c=ES({agentId:t.agentId,date:o},r);try{AS(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
125
119
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
126
120
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
127
- `),1}return t.follow&&await F1(c,t,i),0}var M1=500;function B1(t){try{let e=wp(t,"r");try{return mp(e).size}finally{gp(e)}}catch{return 0}}async function F1(t,e,r){let i=B1(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let h=wp(t,"r");try{let x=mp(h).size;if(x>i){let m=Buffer.allocUnsafe(x-i),_=A1(h,m,0,m.length,i);u=m.subarray(0,_).toString("utf8"),i+=_}}finally{gp(h)}}catch{}if(u){let h=(o+u).split(`
128
- `);o=h.pop()??"";for(let x of h)x.length>0&&yp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${bp(x,{raw:e.raw,color:r})}
129
- `)}await new Promise(h=>setTimeout(h,M1))}}finally{process.off("SIGINT",d)}}import{basename as z1,resolve as U1}from"node:path";Be();var G1=9e4,H1={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 q1(t){return H1[t]??1}async function vp(t,e={}){let r=e.paths??ee();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
121
+ `),1}return t.follow&&await CS(c,t,i),0}var kS=500;function TS(t){try{let e=pp(t,"r");try{return xp(e).size}finally{hp(e)}}catch{return 0}}async function CS(t,e,r){let i=TS(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let f=pp(t,"r");try{let x=xp(f).size;if(x>i){let g=Buffer.allocUnsafe(x-i),m=mS(f,g,0,g.length,i);u=g.subarray(0,m).toString("utf8"),i+=m}}finally{hp(f)}}catch{}if(u){let f=(o+u).split(`
122
+ `);o=f.pop()??"";for(let x of f)x.length>0&&mp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${wp(x,{raw:e.raw,color:r})}
123
+ `)}await new Promise(f=>setTimeout(f,kS))}}finally{process.off("SIGINT",d)}}import{basename as RS,resolve as PS}from"node:path";Me();var DS=9e4,OS={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 LS(t){return OS[t]??1}async function yp(t,e={}){let r=e.paths??ee();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
130
124
  `),4;if(t.groupFile&&!t.mimeType)return process.stderr.write(`Error: --group-file requires --mime <mimeType> (e.g. application/pdf, image/png). No local file is read in group-file mode, mime cannot be auto-detected.
131
- `),3;let i=await aa(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.
132
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:U1(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 j1(i,"/agent/send",o,G1)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
125
+ `),3;let i=await ia(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
126
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:PS(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 NS(i,"/agent/send",o,DS)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
133
127
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
134
- `),q1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
135
- `);else{let d=t.name??z1(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})
136
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${W1(c.bytes)})
137
- `)}return 0}async function j1(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 W1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Op=H("cli");function $e(t,e){let{value:r,rest:i}=Dn(t,e);return{value:r,rest:i}}function xa(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
138
- `)}function pI(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 gI(e.slice(1));if(e[0]==="log")return{mode:"log",..._p(e.slice(1))};if(e[0]==="connect")return mI(e.slice(1));if(e.includes("--status"))return xa("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return xa("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return xa("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return xa("--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}=$e(r,"--pat-token");r=o;let{value:c,rest:d}=$e(r,"--pair-code");r=d;let{value:u,rest:h}=$e(r,"--env");r=h;let{value:x,rest:m}=$e(r,"--handshake-url");r=m;let{value:_,rest:S}=$e(r,"--frontier-url");r=S;let{value:y,rest:v}=$e(r,"--mock-scenario");r=v;let{value:I}=$e(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let C={mode:"pair",privatecode:i,pairingCode:c};return u&&(C.env=u),x&&(C.handshakeUrl=x),_&&(C.frontierUrl=_),y&&(C.mockScenario=y),I&&(C.agentId=I),A&&(C.skipRebuildEnv=!0),C}function gI(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}=$e(i,"--caption");i=c;let{value:d,rest:u}=$e(i,"--name");i=u;let{value:h,rest:x}=$e(i,"--agent-id");i=x;let{value:m,rest:_}=$e(i,"--session-id");i=_;let{value:S,rest:y}=$e(i,"--mime");i=y;let v=i.includes("--group-file");i=i.filter(C=>C!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return o&&(A.caption=o),d&&(A.name=d),h&&(A.agentId=h),m&&(A.sessionId=m),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function mI(t){let e=t,{value:r,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:h,rest:x}=$e(e,"--frontier-url");e=x;let{value:m,rest:_}=$e(e,"--mock-scenario");e=_;let S=e.includes("--skip-rebuild-env"),y={mode:"connect"};return r&&(y.privatecode=r),o&&(y.env=o),d&&(y.handshakeUrl=d),h&&(y.frontierUrl=h),m&&(y.mockScenario=m),S&&(y.skipRebuildEnv=!0),y}var wI=`
128
+ `),LS(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
129
+ `);else{let d=t.name??RS(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
130
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${MS(c.bytes)})
131
+ `)}return 0}async function NS(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await d.text(),f=u?JSON.parse(u):null;return f&&typeof f=="object"&&"ok"in f?f:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function MS(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Rp=W("cli");function Ke(t,e){let{value:r,rest:i}=Rn(t,e);return{value:r,rest:i}}function ua(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
132
+ `)}function o2(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:D}=Ke(e.slice(1),"--agent-id");return D?{mode:"reload",agentId:D}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return a2(e.slice(1));if(e[0]==="log")return{mode:"log",...gp(e.slice(1))};if(e[0]==="connect")return c2(e.slice(1));if(e.includes("--status"))return ua("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ua("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ua("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ua("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:o}=Ke(r,"--pat-token");r=o;let{value:c,rest:d}=Ke(r,"--pair-code");r=d;let{value:u,rest:f}=Ke(r,"--env");r=f;let{value:x,rest:g}=Ke(r,"--handshake-url");r=g;let{value:m,rest:S}=Ke(r,"--frontier-url");r=S;let{value:y,rest:b}=Ke(r,"--mock-scenario");r=b;let{value:I}=Ke(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:c};return u&&(T.env=u),x&&(T.handshakeUrl=x),m&&(T.frontierUrl=m),y&&(T.mockScenario=y),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function a2(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=Ke(i,"--caption");i=c;let{value:d,rest:u}=Ke(i,"--name");i=u;let{value:f,rest:x}=Ke(i,"--agent-id");i=x;let{value:g,rest:m}=Ke(i,"--session-id");i=m;let{value:S,rest:y}=Ke(i,"--mime");i=y;let b=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return o&&(A.caption=o),d&&(A.name=d),f&&(A.agentId=f),g&&(A.sessionId=g),b&&(A.groupFile=!0),S&&(A.mimeType=S),A}function c2(t){let e=t,{value:r,rest:i}=Ke(e,"--pat-token");e=i;let{value:o,rest:c}=Ke(e,"--env");e=c;let{value:d,rest:u}=Ke(e,"--handshake-url");e=u;let{value:f,rest:x}=Ke(e,"--frontier-url");e=x;let{value:g,rest:m}=Ke(e,"--mock-scenario");e=m;let S=e.includes("--skip-rebuild-env"),y={mode:"connect"};return r&&(y.privatecode=r),o&&(y.env=o),d&&(y.handshakeUrl=d),f&&(y.frontierUrl=f),g&&(y.mockScenario=g),S&&(y.skipRebuildEnv=!0),y}var d2=`
139
133
  coze-bridge - local bridge daemon for cloud Agent Service
140
134
 
141
135
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -216,57 +210,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
216
210
 
217
211
  Internal:
218
212
  <node> <entry> --daemon daemon mode (OS supervisor only)
219
- `.trimStart();async function Lp(t=process.argv,e={}){let r=pI(t);switch(r.mode){case"help":return process.stdout.write(wI),0;case"version":return process.stdout.write(`${Nt}
220
- `),0;case"daemon":{try{await rp()}catch(i){return Op.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return _I(e);case"stop":return Mp(e);case"reload":return EI(r.agentId,e);case"log":return Ep(r,e);case"update":return yI(e);case"purge":return SI(e);case"service-install":return II(e);case"service-uninstall":return AI(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),kI(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),TI(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return vp({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 Np(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 _I(t){let e=t.paths??ee(),r=new rn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
221
- `),1;if(i.kind==="stale")return await Np(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
213
+ `.trimStart();async function Pp(t=process.argv,e={}){let r=o2(t);switch(r.mode){case"help":return process.stdout.write(d2),0;case"version":return process.stdout.write(`${Ot}
214
+ `),0;case"daemon":{try{await ep()}catch(i){return Rp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return l2(e);case"stop":return Op(e);case"reload":return h2(r.agentId,e);case"log":return _p(r,e);case"update":return u2(e);case"purge":return p2(e);case"service-install":return g2(e);case"service-uninstall":return m2(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),w2(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),_2(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return yp({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 Dp(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 l2(t){let e=t.paths??ee(),r=new tn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
215
+ `),1;if(i.kind==="stale")return await Dp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
222
216
  `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
223
217
  ${JSON.stringify(o.body,null,2)}
224
- `),0}async function Mp(t){let e=t.paths??ee(),r=new rn(e),i=t.daemonSweep??(async()=>{let h=R0();return await D0(h),h}),o=async()=>{t.skipProcessKill||await i(e)},c=await ls(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
218
+ `),0}async function Op(t){let e=t.paths??ee(),r=new tn(e),i=t.daemonSweep??(async()=>{let f=T0();return await C0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await as(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
225
219
  `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
226
220
  `:`coze-bridge: not running
227
- `),0;if(u.kind==="stale")return await Np(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
221
+ `),0;if(u.kind==="stale")return await Dp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
228
222
  `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
229
- `),0}catch(h){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
230
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
231
- `),1)}}async function yI(t){return await Mp(t),(t.spawnNpx??bI)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function bI(t){return new Promise(e=>{let r=ot("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)}
232
- `),e(1)})})}async function EI(t,e){let r=new rn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
223
+ `),0}catch(f){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
224
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
225
+ `),1)}}async function u2(t){return await Op(t),(t.spawnNpx??f2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function f2(t){return new Promise(e=>{let r=st("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
226
+ `),e(1)})})}async function h2(t,e){let r=new tn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
233
227
  `),1;try{let o=await r.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let c=o.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
234
228
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
235
229
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
236
230
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
237
- `),1}}async function ls(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Rp(),Cp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Bp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??CI,c=t.paths??ee();if(r.kind==="connected"){if(!vI(r.body))return r;it(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=>it(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await Pp(c.pidFile,o)}let d=t.spawnDaemon??tp,u=await ls(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await Dp(e,i,o);if(h.kind==="connected")return h;it(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){it(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}it(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 Pp(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)}
231
+ `),1}}async function as(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(()=>(kp(),Ap)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Lp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??y2,c=t.paths??ee();if(r.kind==="connected"){if(!x2(r.body))return r;rt(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(f=>rt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await Cp(c.pidFile,o)}let d=t.spawnDaemon??Xx,u=await as(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await Tp(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 Cp(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)}
238
232
  `));return process.stdout.write(`coze-bridge: starting daemon...
239
- `),await d({paths:t.paths}),Dp(e,i,o)}function vI(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 SI(t){let e=new rn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
233
+ `),await d({paths:t.paths}),Tp(e,i,o)}function x2(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 p2(t){let e=new tn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
240
234
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
241
- `)}await new Promise(d=>setTimeout(d,500))}let i=await ls(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
235
+ `)}await new Promise(d=>setTimeout(d,500))}let i=await as(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
242
236
  `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
243
237
  `)}let o=t.paths??ee(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
244
238
  `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
245
239
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
246
- `),0}async function II(t){let e=await ls(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
240
+ `),0}async function g2(t){let e=await as(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
247
241
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
248
242
  `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
249
- `),1}}async function AI(t){let e=await ls(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
243
+ `),1}}async function m2(t){let e=await as(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
250
244
  `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
251
- `),1}}async function Fp(t,e,r){if(e)return it(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(it(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(it(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
252
- `),it(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function kI(t,e,r,i={},o,c){let d=new rn(r.paths),u=r.paths??ee(),h=await Fp(u,c,r.reconstructEnv??Jd);if(await cd(u,h).catch(_=>it(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(_)})),!r.skipDistInstall){let _=await el({paths:r.paths});_.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${_.fromVersion} \u2192 ${_.toVersion}
253
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):_.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${_.libVersion}
254
- `)}let x=await Bp(r,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
255
- `),1;let m={privatecode:t,pairing_code:e};i.env&&(m.env=i.env),i.handshakeUrl&&(m.handshake_url=i.handshakeUrl),i.frontierUrl&&(m.frontier_url=i.frontierUrl),i.mockScenario&&(m.mock_scenario=i.mockScenario),o&&(m.agent_id=o);try{let _=await d.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(_.status===200&&_.body?.ok){let S=_.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
245
+ `),1}}async function Np(t,e,r){if(e)return rt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();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)
246
+ `),rt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function w2(t,e,r,i={},o,c){let d=new tn(r.paths),u=r.paths??ee(),f=await Np(u,c,r.reconstructEnv??Kd);if(await sd(u,f).catch(m=>rt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!r.skipDistInstall){let m=await Yd({paths:r.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
247
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
248
+ `)}let x=await Lp(r,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
249
+ `),1;let g={privatecode:t,pairing_code:e};i.env&&(g.env=i.env),i.handshakeUrl&&(g.handshake_url=i.handshakeUrl),i.frontierUrl&&(g.frontier_url=i.frontierUrl),i.mockScenario&&(g.mock_scenario=i.mockScenario),o&&(g.agent_id=o);try{let m=await d.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(m.status===200&&m.body?.ok){let S=m.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
256
250
  `),1):(process.stdout.write(`\u5DF2\u914D\u5BF9\u8FDE\u63A5\u5B8C\u6210\uFF0C\u8BF7\u8FD4\u56DE\u5230 coze \u5E73\u53F0\u4E0A\u70B9\u51FB "\u6211\u5DF2\u6267\u884C"
257
- `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(_.body)}
258
- `),1}catch(_){return process.stderr.write(`coze-bridge: pair failed: ${String(_)}
259
- `),1}}async function TI(t,e,r={},i){let o=e.paths??ee(),c=t??await ea(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 Fp(o,i,e.reconstructEnv??Jd);if(await cd(o,u).catch(m=>it(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await el({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
260
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
261
- `)}let h=await Bp(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
262
- `),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 m=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
263
- `),t!==void 0&&await ss(c,o).catch(_=>Op.warn("writePatToken after connect failed (ignored)",{err:String(_)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
264
- `),1)}catch(m){return process.stderr.write(`coze-bridge: connect failed: ${String(m)}
265
- `),1}}async function Dp(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 Pp(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||!qi(u))return;await e(i)}}function CI(t){return new Promise(e=>setTimeout(e,t))}ne();function RI(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 zp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=RI(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
251
+ `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(m.body)}
252
+ `),1}catch(m){return process.stderr.write(`coze-bridge: pair failed: ${String(m)}
253
+ `),1}}async function _2(t,e,r={},i){let o=e.paths??ee(),c=t??await Yo(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 tn(e.paths),u=await Np(o,i,e.reconstructEnv??Kd);if(await sd(o,u).catch(g=>rt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await Yd({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
254
+ `),(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}
255
+ `)}let f=await Lp(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
256
+ `),1;let x={privatecode:c};r.env&&(x.env=r.env),r.handshakeUrl&&(x.handshake_url=r.handshakeUrl),r.frontierUrl&&(x.frontier_url=r.frontierUrl),r.mockScenario&&(x.mock_scenario=r.mockScenario);try{let 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"})
257
+ `),t!==void 0&&await ns(c,o).catch(m=>Rp.warn("writePatToken after connect failed (ignored)",{err:String(m)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
258
+ `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
259
+ `),1}}async function Tp(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 Cp(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Ui(u))return;await e(i)}}function y2(t){return new Promise(e=>setTimeout(e,t))}ne();function E2(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 Mp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=E2(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
266
260
  `),r(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${o},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
267
261
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
268
262
  npx -y coze-bridge@latest stop
269
263
  npx -y coze-bridge@latest connect
270
264
 
271
- `)}zp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Al("warn");Lp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
265
+ `)}Mp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Sl("warn");Pp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
272
266
  `),process.exit(1)});