coze-bridge 0.2.7-beta.1 → 0.2.7-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +99 -99
  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 Wg=Object.create;var Da=Object.defineProperty;var Kg=Object.getOwnPropertyDescriptor;var $g=Object.getOwnPropertyNames;var Vg=Object.getPrototypeOf,Yg=Object.prototype.hasOwnProperty;var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var et=(t,e)=>()=>(t&&(e=t(t=0)),e);var de=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Oa=(t,e)=>{for(var r in e)Da(t,r,{get:e[r],enumerable:!0})},Jg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $g(e))!Yg.call(t,o)&&o!==r&&Da(t,o,{get:()=>e[o],enumerable:!(i=Kg(e,o))||i.enumerable});return t};var Ht=(t,e,r)=>(r=t!=null?Wg(Vg(t)):{},Jg(e||!t||!t.__esModule?Da(r,"default",{value:t,enumerable:!0}):r,t));function Ye(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ar=et(()=>{"use strict"});import{createWriteStream as Xg,mkdirSync as Zg,readdirSync as Qg,unlinkSync as em}from"node:fs";import{join as Cl}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 cr(t,e){return`${t}-${e}.log`}function La(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function tm(t,e,r){let i=c=>{let[d,u,x]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,x??1)};return Math.floor((i(e)-i(t))/864e5)>r}function hs(t,e,r,i){let o;try{o=Qg(t)}catch{return}for(let c of o){let d=La(c,e);if(d&&tm(d,r,i))try{em(Cl(t,c))}catch{}}}var ri,Na=et(()=>{"use strict";ri=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{Zg(this.dir,{recursive:!0});let r=Xg(Cl(this.dir,cr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
- `)),this.stream=r}catch(r){process.stderr.write(`[log-sink] rotate failed: ${String(r)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&hs(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 nm,mkdirSync as rm}from"node:fs";import{join as im}from"node:path";function Rl(t){let e=t.retentionDays??am,r=t.clock??(()=>Dn(new Date));gs={bridgeSink:new ri(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ri(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();hs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])hs(t.agentLogsDir(o),"agent",i,e)}function cm(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Dl(t){Ma=t}function Ol(t){return dr[Ma]<=dr[t]}function Ll(t,e){let r=dr[t];return r===void 0?!0:r>=dr[e]}function ms(t){Pl={...t}}function Nl(t){let e=(u,x=2)=>String(u).padStart(x,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),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 nt(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Nl(new Date),level:e,module:r,msg:i,...o})}
11
- `;rm(t,{recursive:!0}),nm(im(t,cr("bridge",Dn(new Date))),c)}catch{}}function dm(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function ps(t,e,r,i,o){if(dr[t]<dr[Ma])return;let c=`${JSON.stringify({ts:Nl(new Date),level:t,module:e,msg:r,...Pl,...i})}
12
- `;if(gs){let d=dm(o,i),u=d?cm(gs,d):gs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?om.write(c):sm.write(c)}function j(t,e){return{debug:(r,i)=>ps("debug",t,r,i,e),info:(r,i)=>ps("info",t,r,i,e),warn:(r,i)=>ps("warn",t,r,i,e),error:(r,i)=>ps("error",t,r,i,e),child:r=>j(`${t}.${r}`,e),forAgent:r=>j(t,r)}}var dr,Ma,sm,om,Pl,am,gs,te=et(()=>{"use strict";ar();Na();dr={debug:10,info:20,warn:30,error:40},Ma=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),sm=process.stdout,om=process.stderr,Pl={},am=Ye("COZE_BRIDGE_LOG_RETENTION_DAYS",30),gs=null});var T,Ke=et(()=>{"use strict";T=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var zl={};Oa(zl,{ACP_WRAPPER_NPM_PACKAGES:()=>ws,_resetAcpInstallerForTests:()=>pm,_setBinaryPathCacheForTests:()=>gm,buildAcpSpawn:()=>si,ensureAcpInstalled:()=>lr,getAcpBinaryPath:()=>_s,pickWhichLine:()=>za,probeAcpVersion:()=>hm,resolveAcpCommand:()=>Fl});import{readFileSync as Ml}from"node:fs";import{createRequire as lm}from"node:module";import{dirname as um,resolve as fm}from"node:path";function za(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 xm(t){let e=Bl.resolve(`${t.npmPackage}/package.json`),r=um(e),i=JSON.parse(Ml(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 fm(r,o)}async function lr(t,e){let r=Fa[t];if(!r)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ii.get(t);if(i)return i;try{let o=xm(r);return ii.set(t,o),Ba.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Ba.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 hm(t){let e=Fa[t];if(e)try{let r=Bl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Ml(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Ba.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function _s(t){return ii.get(t)}function Fl(t,e){if(e)return e;let r=_s(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 si(t,e,r){if(e)return{command:e,args:[...r]};let i=Fl(t);return{command:process.execPath,args:[i,...r]}}function pm(){ii.clear()}function gm(t,e){ii.set(t,e)}var Ba,Fa,ws,Bl,ii,ln=et(()=>{"use strict";Ke();te();Ba=j("agents.acp-installer"),Fa={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ws=Object.values(Fa).filter(t=>t!==void 0).map(t=>t.npmPackage),Bl=lm(import.meta.url),ii=new Map});import{chmod as wm,mkdir as _m,readFile as ym,rename as bm,rm as Em,writeFile as vm}from"node:fs/promises";import{dirname as Sm}from"node:path";async function ur(t){try{let e=await ym(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ut(t,e,r){await _m(Sm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await vm(i,e,{encoding:"utf8",mode:r?.mode}),await bm(i,t),r?.mode!==void 0&&await wm(t,r.mode)}catch(o){throw await Em(i,{force:!0}).catch(()=>{}),o}}async function fr(t,e,r){await ut(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var Gt=et(()=>{"use strict"});import{promises as Gl,readdirSync as Im}from"node:fs";import{homedir as Am}from"node:os";import{sep as km,join as Te,resolve as ql}from"node:path";function J(t){let e=t??Am(),r=Te(e,".coze"),i=Te(r,"bridge"),o=Te(i,"lib"),c=Te(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Te(o,"index.js"),binDir:Te(i,"bin"),pidFile:Te(i,"bridge.pid"),portFile:Te(i,"bridge.port"),tokenFile:Te(i,"bridge.token"),patTokenFile:Te(i,"pat-token"),agentEnvFile:Te(i,"agent-env.json"),logFile:Te(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Te(c,"daemon-stdio.log"),installLock:Te(i,"install.lock"),configFile:Te(i,"config.json"),agentsRoot:Te(r,"agents")}}function Fe(t,e=J()){let r=Te(e.agentsRoot,t);return{root:r,config:Te(r,"config.json"),workspace:Te(r,"workspace"),logs:Te(r,"logs")}}function ys(t=J()){try{return Im(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function oi(t,e){let r=await Gl.realpath(ql(t)).catch(()=>null);if(!r)return!1;let i=await Gl.realpath(ql(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+km)}var Ce=et(()=>{"use strict"});var Es={};Oa(Es,{AGENT_CONFIG_FILE_MODE:()=>bs,enforceAgentConfigMode:()=>Pm,loadAgentConfig:()=>ve,persistAgentSessions:()=>ai,persistAgentSkills:()=>ci,saveAgentConfig:()=>ze});import{chmod as Tm,stat as Cm}from"node:fs/promises";function ve(t,e){return ur(Fe(t,e).config)}function ze(t,e){return fr(Fe(t.agentId,e).config,t,{mode:bs})}async function Pm(t,e){if(process.platform==="win32")return;let r=Fe(t,e).config;try{let i=await Cm(r);if(!i.isFile())return;let o=i.mode&511;o!==bs&&(await Tm(r,bs),jl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;jl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ai(t,e,r){let i=await ve(t,r);i&&(i.sessions=Object.fromEntries(e),await ze(i,r))}async function ci(t,e,r){let i=await ve(t,r);i&&(i.skills=e,await ze(i,r))}var jl,bs,qt=et(()=>{"use strict";Gt();te();Ce();jl=j("agent-config"),bs=384});var Ga=de((NI,$l)=>{$l.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 Ss=de(Yl=>{var Vl={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 Mm(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(Vl))Yl[t]=Mm(Vl[t])});var eu=de((BI,Ql)=>{var Bm=xe("fs"),Ne=xe("path"),Jl=Ga(),Fm=Ss(),zm=typeof process=="object"&&process.platform==="win32",Xl=t=>typeof t=="object"&&t!==null,Zl=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Se(t){this.sep=Ne.sep,this.fs=Bm,Xl(t)&&Xl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Ql.exports=Se;Se.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw Fm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Se.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var d=Ne.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Se.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!r)return o(!1);c.fs.stat(t,function(u,x){if(d&&x.isDirectory())return o(!1);var h=Ne.dirname(t);c.fs.exists(h,function(m){m||c.makeDir(h),c.fs.open(t,"w",438,function(w,I){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(b,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)})})})})}):I?c.fs.write(I,e,0,e.length,0,function(){c.fs.close(I,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Se.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let x=Ne.join(i,u),h=e.fs.statSync(x);(!o||o.test(x))&&d.push(Ne.normalize(x)+(h.isDirectory()?e.sep:"")),h.isDirectory()&&c&&(d=d.concat(r(x,o,c)))}),d}return r(t,void 0,!0)};Se.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Ne.join(t,u),r.fs.stat(u,function(x,h){if(x)return e(x);h&&(i.push(Ne.normalize(u)+(h.isDirectory()?r.sep:"")),h.isDirectory()?r.findFilesAsync(u,function(m,w){if(m)return e(m);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};Se.prototype.getAttributes=function(){};Se.prototype.setAttributes=function(){};Se.crc32update=function(t,e){return Zl[(t^e)&255]^t>>>8};Se.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Se.crc32update(r,t[i++]);return~r>>>0};Se.methodToString=function(t){switch(t){case Jl.STORED:return"STORED ("+t+")";case Jl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Se.canonical=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.join(".",e)};Se.zipnamefix=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.posix.join(".",e)};Se.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Se.sanitize=function(t,e){t=Ne.resolve(Ne.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Ne.normalize(Ne.join(t,r.slice(i,o).join(Ne.sep)));if(c.indexOf(t)===0)return c}return Ne.normalize(Ne.join(t,Ne.basename(e)))};Se.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Se.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Se.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Se.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};Se.isWin=zm;Se.crcTable=Zl});var nu=de((FI,tu)=>{var Um=xe("path");tu.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=Um.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 iu=de((zI,ru)=>{ru.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=de((UI,hr)=>{hr.exports=eu();hr.exports.Constants=Ga();hr.exports.Errors=Ss();hr.exports.FileAttr=nu();hr.exports.decoder=iu()});var ou=de((HI,su)=>{var un=pr(),q=un.Constants;su.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,x=0,h=0,m=0,w=0,I=0,b=0,S=0;t|=un.isWin?2560:768,r|=q.FLG_EFS;let A={extraLen:0},k=E=>Math.max(0,E)>>>0,P=E=>Math.max(0,E)&65535,L=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&q.FLG_EFS)>0},set flags_efs(E){E?r|=q.FLG_EFS:r&=~q.FLG_EFS},get flags_desc(){return(r&q.FLG_DESC)>0},set flags_desc(E){E?r|=q.FLG_DESC:r&=~q.FLG_DESC},get method(){return i},set method(E){switch(E){case q.STORED:this.version=10;case q.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=k(E)},get timeHighByte(){return L(o>>>8)},get crc(){return c},set crc(E){c=k(E)},get compressedSize(){return d},set compressedSize(E){d=k(E)},get size(){return u},set size(E){u=k(E)},get fileNameLength(){return x},set fileNameLength(E){x=E},get extraLength(){return h},set extraLength(E){h=E},get extraLocalLength(){return A.extraLen},set extraLocalLength(E){A.extraLen=E},get commentLength(){return m},set commentLength(E){m=E},get diskNumStart(){return w},set diskNumStart(E){w=k(E)},get inAttr(){return I},set inAttr(E){I=k(E)},get attr(){return b},set attr(E){b=k(E)},get fileAttr(){return(b||0)>>16&4095},get offset(){return S},set offset(E){S=k(E)},get encrypted(){return(r&q.FLG_ENC)===q.FLG_ENC},get centralHeaderSize(){return q.CENHDR+x+h+m},get realDataOffset(){return S+q.LOCHDR+A.fnameLen+A.extraLen},get localHeader(){return A},loadLocalHeaderFromBinary:function(E){var D=E.slice(S,S+q.LOCHDR);if(D.readUInt32LE(0)!==q.LOCSIG)throw un.Errors.INVALID_LOC();A.version=D.readUInt16LE(q.LOCVER),A.flags=D.readUInt16LE(q.LOCFLG),A.flags_desc=(A.flags&q.FLG_DESC)>0,A.method=D.readUInt16LE(q.LOCHOW),A.time=D.readUInt32LE(q.LOCTIM),A.crc=D.readUInt32LE(q.LOCCRC),A.compressedSize=D.readUInt32LE(q.LOCSIZ),A.size=D.readUInt32LE(q.LOCLEN),A.fnameLen=D.readUInt16LE(q.LOCNAM),A.extraLen=D.readUInt16LE(q.LOCEXT);let N=S+q.LOCHDR+A.fnameLen,z=N+A.extraLen;return E.slice(N,z)},loadFromBinary:function(E){if(E.length!==q.CENHDR||E.readUInt32LE(0)!==q.CENSIG)throw un.Errors.INVALID_CEN();t=E.readUInt16LE(q.CENVEM),e=E.readUInt16LE(q.CENVER),r=E.readUInt16LE(q.CENFLG),i=E.readUInt16LE(q.CENHOW),o=E.readUInt32LE(q.CENTIM),c=E.readUInt32LE(q.CENCRC),d=E.readUInt32LE(q.CENSIZ),u=E.readUInt32LE(q.CENLEN),x=E.readUInt16LE(q.CENNAM),h=E.readUInt16LE(q.CENEXT),m=E.readUInt16LE(q.CENCOM),w=E.readUInt16LE(q.CENDSK),I=E.readUInt16LE(q.CENATT),b=E.readUInt32LE(q.CENATX),S=E.readUInt32LE(q.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(q.LOCHDR);return E.writeUInt32LE(q.LOCSIG,0),E.writeUInt16LE(e,q.LOCVER),E.writeUInt16LE(r,q.LOCFLG),E.writeUInt16LE(i,q.LOCHOW),E.writeUInt32LE(o,q.LOCTIM),E.writeUInt32LE(c,q.LOCCRC),E.writeUInt32LE(d,q.LOCSIZ),E.writeUInt32LE(u,q.LOCLEN),E.writeUInt16LE(x,q.LOCNAM),E.writeUInt16LE(A.extraLen,q.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(q.CENHDR+x+h+m);return E.writeUInt32LE(q.CENSIG,0),E.writeUInt16LE(t,q.CENVEM),E.writeUInt16LE(e,q.CENVER),E.writeUInt16LE(r,q.CENFLG),E.writeUInt16LE(i,q.CENHOW),E.writeUInt32LE(o,q.CENTIM),E.writeUInt32LE(c,q.CENCRC),E.writeUInt32LE(d,q.CENSIZ),E.writeUInt32LE(u,q.CENLEN),E.writeUInt16LE(x,q.CENNAM),E.writeUInt16LE(h,q.CENEXT),E.writeUInt16LE(m,q.CENCOM),E.writeUInt16LE(w,q.CENDSK),E.writeUInt16LE(I,q.CENATT),E.writeUInt32LE(b,q.CENATX),E.writeUInt32LE(S,q.CENOFF),E},toJSON:function(){let E=function(D){return D+" 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(x),extraLength:E(h),commentLength:E(m),diskNumStart:w,inAttr:I,attr:b,offset:S,centralHeaderSize:E(q.CENHDR+x+h+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var cu=de((GI,au)=>{var gr=pr(),ye=gr.Constants;au.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 ye.ENDHDR+o},loadFromBinary:function(c){if((c.length!==ye.ENDHDR||c.readUInt32LE(0)!==ye.ENDSIG)&&(c.length<ye.ZIP64HDR||c.readUInt32LE(0)!==ye.ZIP64SIG))throw gr.Errors.INVALID_END();c.readUInt32LE(0)===ye.ENDSIG?(t=c.readUInt16LE(ye.ENDSUB),e=c.readUInt16LE(ye.ENDTOT),r=c.readUInt32LE(ye.ENDSIZ),i=c.readUInt32LE(ye.ENDOFF),o=c.readUInt16LE(ye.ENDCOM)):(t=gr.readBigUInt64LE(c,ye.ZIP64SUB),e=gr.readBigUInt64LE(c,ye.ZIP64TOT),r=gr.readBigUInt64LE(c,ye.ZIP64SIZE),i=gr.readBigUInt64LE(c,ye.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(ye.ENDHDR+o);return c.writeUInt32LE(ye.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,ye.ENDSUB),c.writeUInt16LE(e,ye.ENDTOT),c.writeUInt32LE(r,ye.ENDSIZ),c.writeUInt32LE(i,ye.ENDOFF),c.writeUInt16LE(o,ye.ENDCOM),c.fill(" ",ye.ENDHDR),c},toJSON:function(){let c=function(d,u){let x=d.toString(16).toUpperCase();for(;x.length<u;)x="0"+x;return"0x"+x};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ja=de(qa=>{qa.EntryHeader=ou();qa.MainHeader=cu()});var lu=de((jI,du)=>{du.exports=function(t){var e=xe("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],d=0;o.on("data",function(u){c.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),x=0;u.fill(0);for(var h=0;h<c.length;h++){var m=c[h];m.copy(u,x),x+=m.length}i&&i(u)}),o.end(t)}}}});var fu=de((WI,uu)=>{var Hm=+(process.versions?process.versions.node:"").split(".")[0]||0;uu.exports=function(t,e){var r=xe("zlib");let i=Hm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),d=[],u=0;c.on("data",function(x){d.push(x),u+=x.length}),c.on("end",function(){var x=Buffer.alloc(u),h=0;x.fill(0);for(var m=0;m<d.length;m++){var w=d[m];w.copy(x,h),h+=w.length}o&&o(x)}),c.end(t)}}}});var mu=de((KI,gu)=>{"use strict";var{randomFillSync:xu}=xe("crypto"),Gm=Ss(),qm=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),pu=(t,e)=>Math.imul(t,e)>>>0,hu=(t,e)=>qm[(t^e)&255]^t>>>8,di=()=>typeof xu=="function"?xu(Buffer.alloc(12)):di.node();di.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var Is={genSalt:di};function As(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])}As.prototype.updateKeys=function(t){let e=this.keys;return e[0]=hu(e[0],t),e[1]+=e[0]&255,e[1]=pu(e[1],134775813)+1,e[2]=hu(e[2],e[1]>>>24),t};As.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return pu(t,t^1)>>8&255};function jm(t){let e=new As(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 Wm(t){let e=new As(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 Km(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=jm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Gm.WRONG_PASSWORD();return i(t.slice(12))}function $m(t){Buffer.isBuffer(t)&&t.length>=12?Is.genSalt=function(){return t.slice(0,12)}:t==="node"?Is.genSalt=di.node:Is.genSalt=di}function Vm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Wm(r),c=Is.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)}gu.exports={decrypt:Km,encrypt:Vm,_salter:$m}});var wu=de(ks=>{ks.Deflater=lu();ks.Inflater=fu();ks.ZipCrypto=mu()});var Ka=de((VI,_u)=>{var le=pr(),Ym=ja(),Ie=le.Constants,Wa=wu();_u.exports=function(t,e){var r=new Ym.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),x=Buffer.alloc(0),h=!0;let m=t,w=typeof m.decoder=="object"?m.decoder:le.decoder;h=w.hasOwnProperty("efs")?w.efs:!1;function I(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(x=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function b(E){if(!r.flags_desc&&!r.localHeader.flags_desc){if(le.crc32(E)!==r.localHeader.crc)return!1}else{let D={},N=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(N)==Ie.LOCSIG||e.readUInt32LE(N)==Ie.CENSIG)throw le.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(N)==Ie.EXTSIG)D.crc=e.readUInt32LE(N+Ie.EXTCRC),D.compressedSize=e.readUInt32LE(N+Ie.EXTSIZ),D.size=e.readUInt32LE(N+Ie.EXTLEN);else if(e.readUInt16LE(N+12)===19280)D.crc=e.readUInt32LE(N+Ie.EXTCRC-4),D.compressedSize=e.readUInt32LE(N+Ie.EXTSIZ-4),D.size=e.readUInt32LE(N+Ie.EXTLEN-4);else throw le.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==r.compressedSize||D.size!==r.size||D.crc!==r.crc)throw le.Errors.DESCRIPTOR_FAULTY();if(le.crc32(E)!==D.crc)return!1}return!0}function S(E,D,N){if(typeof D>"u"&&typeof E=="string"&&(N=E,E=void 0),c)return E&&D&&D(Buffer.alloc(0),le.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var z=I();if(z.length===0)return E&&D&&D(z),z;if(r.encrypted){if(typeof N!="string"&&!Buffer.isBuffer(N))throw le.Errors.INVALID_PASS_PARAM();z=Wa.ZipCrypto.decrypt(z,r,N)}var B=Buffer.alloc(r.size);switch(r.method){case le.Constants.STORED:if(z.copy(B),b(B))return E&&D&&D(B),B;throw E&&D&&D(B,le.Errors.BAD_CRC()),le.Errors.BAD_CRC();case le.Constants.DEFLATED:var Y=new Wa.Inflater(z,r.size);if(E)Y.inflateAsync(function(V){V.copy(V,0),D&&(b(V)?D(V):D(V,le.Errors.BAD_CRC()))});else{if(Y.inflate(B).copy(B,0),!b(B))throw le.Errors.BAD_CRC(`"${w.decode(i)}"`);return B}break;default:throw E&&D&&D(Buffer.alloc(0),le.Errors.UNKNOWN_METHOD()),le.Errors.UNKNOWN_METHOD()}}function A(E,D){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&D&&D(I()),I();if(d.length&&!c){var N;switch(r.method){case le.Constants.STORED:return r.compressedSize=r.size,N=Buffer.alloc(d.length),d.copy(N),E&&D&&D(N),N;default:case le.Constants.DEFLATED:var z=new Wa.Deflater(d);if(E)z.deflateAsync(function(Y){N=Buffer.alloc(Y.length),r.compressedSize=Y.length,Y.copy(N),D&&D(N)});else{var B=z.deflate();return r.compressedSize=B.length,B}z=null;break}}else if(E&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function k(E,D){return le.readBigUInt64LE(E,D)}function P(E){try{for(var D=0,N,z,B;D+4<E.length;)N=E.readUInt16LE(D),D+=2,z=E.readUInt16LE(D),D+=2,B=E.slice(D,D+z),D+=z,Ie.ID_ZIP64===N&&L(B)}catch{throw le.Errors.EXTRA_FIELD_PARSE_ERROR()}}function L(E){var D,N,z,B;E.length>=Ie.EF_ZIP64_SCOMP&&(D=k(E,Ie.EF_ZIP64_SUNCOMP),r.size===Ie.EF_ZIP64_OR_32&&(r.size=D)),E.length>=Ie.EF_ZIP64_RHO&&(N=k(E,Ie.EF_ZIP64_SCOMP),r.compressedSize===Ie.EF_ZIP64_OR_32&&(r.compressedSize=N)),E.length>=Ie.EF_ZIP64_DSN&&(z=k(E,Ie.EF_ZIP64_RHO),r.offset===Ie.EF_ZIP64_OR_32&&(r.offset=z)),E.length>=Ie.EF_ZIP64_DSN+4&&(B=E.readUInt32LE(Ie.EF_ZIP64_DSN),r.diskNumStart===Ie.EF_ZIP64_OR_16&&(r.diskNumStart=B))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(E){i=le.toBuffer(E,w.encode);var D=i[i.length-1];c=D===47||D===92,r.fileNameLength=i.length},get efs(){return typeof h=="function"?h(this.entryName):h},get extra(){return u},set extra(E){u=E,r.extraLength=E.length,P(E)},get comment(){return w.decode(o)},set comment(E){if(o=le.toBuffer(E,w.encode),r.commentLength=o.length,o.length>65535)throw le.Errors.COMMENT_TOO_LONG()},get name(){var E=w.decode(i);return c?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return A(!1,null)},getCompressedDataAsync:function(E){A(!0,E)},setData:function(E){d=le.toBuffer(E,le.decoder.encode),!c&&d.length?(r.size=d.length,r.method=le.Constants.DEFLATED,r.crc=le.crc32(E),r.changed=!0):r.method=le.Constants.STORED},getData:function(E){return r.changed?d:S(!1,null,E)},getDataAsync:function(E,D){r.changed?E(d):S(!0,E,D)},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(),D=le.Constants.CENHDR;return i.copy(E,D),D+=i.length,u.copy(E,D),D+=r.extraLength,o.copy(E,D),E},packLocalHeader:function(){let E=0;r.flags_efs=this.efs,r.extraLocalLength=x.length;let D=r.localHeaderToBinary(),N=Buffer.alloc(D.length+i.length+r.extraLocalLength);return D.copy(N,E),E+=D.length,i.copy(N,E),E+=i.length,x.copy(N,E),E+=x.length,N},toJSON:function(){let E=function(D){return"<"+(D&&D.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 Eu=de((YI,bu)=>{var yu=Ka(),Jm=ja(),$e=pr();bu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Jm.MainHeader,d=!1,u=null;let x=new Set,h=e,{noSort:m,decoder:w}=h;t?S(h.readEntries):d=!0;function I(){let k=new Set;for(let P of Object.keys(i)){let L=P.split("/");if(L.pop(),!!L.length)for(let E=0;E<L.length;E++){let D=L.slice(0,E+1).join("/")+"/";k.add(D)}}for(let P of k)if(!(P in i)){let L=new yu(h);L.entryName=P,L.attr=16,L.temporary=!0,r.push(L),i[L.entryName]=L,x.add(L)}}function b(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/$e.Constants.CENHDR)throw $e.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var k=c.offset,P=0;P<r.length;P++){var L=k,E=new yu(h,t);E.header=t.slice(L,L+=$e.Constants.CENHDR),E.entryName=t.slice(L,L+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(L,L+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(L,L+E.header.commentLength)),k+=E.header.centralHeaderSize,r[P]=E,i[E.entryName]=E}x.clear(),I()}function S(k){var P=t.length-$e.Constants.ENDHDR,L=Math.max(0,P-65535),E=L,D=t.length,N=-1,z=0;for(typeof h.trailingSpace=="boolean"&&h.trailingSpace&&(L=0),P;P>=E;P--)if(t[P]===80){if(t.readUInt32LE(P)===$e.Constants.ENDSIG){N=P,z=P,D=P+$e.Constants.ENDHDR,E=P-$e.Constants.END64HDR;continue}if(t.readUInt32LE(P)===$e.Constants.END64SIG){E=L;continue}if(t.readUInt32LE(P)===$e.Constants.ZIP64SIG){N=P,D=P+$e.readBigUInt64LE(t,P+$e.Constants.ZIP64SIZE)+$e.Constants.ZIP64LEAD;break}}if(N==-1)throw $e.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(N,D)),c.commentLength&&(o=t.slice(z+$e.Constants.ENDHDR)),k&&b()}function A(){r.length>1&&!m&&r.sort((k,P)=>k.entryName.toLowerCase().localeCompare(P.entryName.toLowerCase()))}return{get entries(){return d||b(),r.filter(k=>!x.has(k))},get comment(){return w.decode(o)},set comment(k){o=$e.toBuffer(k,w.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(k){this.entries.forEach(k)},getEntry:function(k){return d||b(),i[k]||null},setEntry:function(k){d||b(),r.push(k),i[k.entryName]=k,c.totalEntries=r.length},deleteFile:function(k,P=!0){d||b();let L=i[k];this.getEntryChildren(L,P).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(k){d||b();let P=i[k],L=r.indexOf(P);L>=0&&(r.splice(L,1),delete i[k],c.totalEntries=r.length)},getEntryChildren:function(k,P=!0){if(d||b(),typeof k=="object")if(k.isDirectory&&P){let L=[],E=k.entryName;for(let D of r)D.entryName.startsWith(E)&&L.push(D);return L}else return[k];return[]},getChildCount:function(k){if(k&&k.isDirectory){let P=this.getEntryChildren(k);return P.includes(k)?P.length-1:P.length}return 0},compressToBuffer:function(){d||b(),A();let k=[],P=[],L=0,E=0;c.size=0,c.offset=0;let D=0;for(let B of this.entries){let Y=B.getCompressedData();B.header.offset=E;let V=B.packLocalHeader(),re=V.length+Y.length;E+=re,k.push(V),k.push(Y);let Z=B.packCentralHeader();P.push(Z),c.size+=Z.length,L+=re+Z.length,D++}L+=c.mainHeaderSize,c.offset=E,c.totalEntries=D,E=0;let N=Buffer.alloc(L);for(let B of k)B.copy(N,E),E+=B.length;for(let B of P)B.copy(N,E),E+=B.length;let z=c.toBinary();return o&&o.copy(z,$e.Constants.ENDHDR),z.copy(N,E),t=N,d=!1,N},toAsyncBuffer:function(k,P,L,E){try{d||b(),A();let D=[],N=[],z=0,B=0,Y=0;c.size=0,c.offset=0;let V=function(re){if(re.length>0){let Z=re.shift(),oe=Z.entryName+Z.extra.toString();L&&L(oe),Z.getCompressedDataAsync(function(ce){E&&E(oe),Z.header.offset=B;let R=Z.packLocalHeader(),G=R.length+ce.length;B+=G,D.push(R),D.push(ce);let W=Z.packCentralHeader();N.push(W),c.size+=W.length,z+=G+W.length,Y++,V(re)})}else{z+=c.mainHeaderSize,c.offset=B,c.totalEntries=Y,B=0;let Z=Buffer.alloc(z);D.forEach(function(ce){ce.copy(Z,B),B+=ce.length}),N.forEach(function(ce){ce.copy(Z,B),B+=ce.length});let oe=c.toBinary();o&&o.copy(oe,$e.Constants.ENDHDR),oe.copy(Z,B),t=Z,d=!1,k(Z)}};V(Array.from(this.entries))}catch(D){P(D)}}}}});var Iu=de((JI,Su)=>{var Ee=pr(),be=xe("path"),Xm=Ka(),Zm=Eu(),On=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),vu=(...t)=>Ee.findLast(t,e=>typeof e=="string"),Qm=(...t)=>Ee.findLast(t,e=>typeof e=="function"),ew={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};Su.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),ew);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=Ee.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Ee(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ee.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Ee.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw Ee.Errors.INVALID_FILENAME();let c=new Zm(r,i),{canonical:d,sanitize:u,zipnamefix:x}=Ee;function h(b){if(b&&c){var S;if(typeof b=="string"&&(S=c.getEntry(be.posix.normalize(b))),typeof b=="object"&&typeof b.entryName<"u"&&typeof b.header<"u"&&(S=c.getEntry(b.entryName)),S)return S}return null}function m(b){let{join:S,normalize:A,sep:k}=be.posix;return S(be.isAbsolute(b)?"/":".",A(k+b.split("\\").join(k)+k))}function w(b){return b instanceof RegExp?(function(S){return function(A){return S.test(A)}})(b):typeof b!="function"?()=>!0:b}let I=(b,S)=>{let A=S.slice(-1);return A=A===o.sep?o.sep:"",be.relative(b,S)+A};return{readFile:function(b,S){var A=h(b);return A&&A.getData(S)||null},childCount:function(b){let S=h(b);if(S)return c.getChildCount(S)},readFileAsync:function(b,S){var A=h(b);A?A.getDataAsync(S):S(null,"getEntry failed for:"+b)},readAsText:function(b,S){var A=h(b);if(A){var k=A.getData();if(k&&k.length)return k.toString(S||"utf8")}return""},readAsTextAsync:function(b,S,A){var k=h(b);k?k.getDataAsync(function(P,L){if(L){S(P,L);return}P&&P.length?S(P.toString(A||"utf8")):S("")}):S("")},deleteFile:function(b,S=!0){var A=h(b);A&&c.deleteFile(A.entryName,S)},deleteEntry:function(b){var S=h(b);S&&c.deleteEntry(S.entryName)},addZipComment:function(b){c.comment=b},getZipComment:function(){return c.comment||""},addZipEntryComment:function(b,S){var A=h(b);A&&(A.comment=S)},getZipEntryComment:function(b){var S=h(b);return S&&S.comment||""},updateFile:function(b,S){var A=h(b);A&&A.setData(S)},addLocalFile:function(b,S,A,k){if(o.fs.existsSync(b)){S=S?m(S):"";let P=be.win32.basename(be.win32.normalize(b));S+=A||P;let L=o.fs.statSync(b),E=L.isFile()?o.fs.readFileSync(b):Buffer.alloc(0);L.isDirectory()&&(S+=o.sep),this.addFile(S,E,k,L)}else throw Ee.Errors.FILE_NOT_FOUND(b)},addLocalFileAsync:function(b,S){b=typeof b=="object"?b:{localPath:b};let A=be.resolve(b.localPath),{comment:k}=b,{zipPath:P,zipName:L}=b,E=this;o.fs.stat(A,function(D,N){if(D)return S(D,!1);P=P?m(P):"";let z=be.win32.basename(be.win32.normalize(A));if(P+=L||z,N.isFile())o.fs.readFile(A,function(B,Y){return B?S(B,!1):(E.addFile(P,Y,k,N),setImmediate(S,void 0,!0))});else if(N.isDirectory())return P+=o.sep,E.addFile(P,Buffer.alloc(0),k,N),setImmediate(S,void 0,!0)})},addLocalFolder:function(b,S,A){if(A=w(A),S=S?m(S):"",b=be.normalize(b),o.fs.existsSync(b)){let k=o.findFiles(b),P=this;if(k.length)for(let L of k){let E=be.join(S,I(b,L));A(E)&&P.addLocalFile(L,be.dirname(E))}}else throw Ee.Errors.FILE_NOT_FOUND(b)},addLocalFolderAsync:function(b,S,A,k){k=w(k),A=A?m(A):"",b=be.normalize(b);var P=this;o.fs.open(b,"r",function(L){if(L&&L.code==="ENOENT")S(void 0,Ee.Errors.FILE_NOT_FOUND(b));else if(L)S(void 0,L);else{var E=o.findFiles(b),D=-1,N=function(){if(D+=1,D<E.length){var z=E[D],B=I(b,z).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),k(B)?o.fs.stat(z,function(Y,V){Y&&S(void 0,Y),V.isFile()?o.fs.readFile(z,function(re,Z){re?S(void 0,re):(P.addFile(A+B,Z,"",V),N())}):(P.addFile(A+B+"/",Buffer.alloc(0),"",V),N())}):process.nextTick(()=>{N()})}else S(!0,void 0)};N()}})},addLocalFolderAsync2:function(b,S){let A=this;b=typeof b=="object"?b:{localPath:b},localPath=be.resolve(m(b.localPath));let{zipPath:k,filter:P,namefix:L}=b;P instanceof RegExp?P=(function(N){return function(z){return N.test(z)}})(P):typeof P!="function"&&(P=function(){return!0}),k=k?m(k):"",L=="latin1"&&(L=N=>N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof L!="function"&&(L=N=>N);let E=N=>be.join(k,L(I(localPath,N))),D=N=>be.win32.basename(be.win32.normalize(L(N)));o.fs.open(localPath,"r",function(N){N&&N.code==="ENOENT"?S(void 0,Ee.Errors.FILE_NOT_FOUND(localPath)):N?S(void 0,N):o.findFilesAsync(localPath,function(z,B){if(z)return S(z);B=B.filter(Y=>P(E(Y))),B.length||S(void 0,!1),setImmediate(B.reverse().reduce(function(Y,V){return function(re,Z){if(re||Z===!1)return setImmediate(Y,re,!1);A.addLocalFileAsync({localPath:V,zipPath:be.dirname(E(V)),zipName:D(V)},Y)}},S))})})},addLocalFolderPromise:function(b,S){return new Promise((A,k)=>{this.addLocalFolderAsync2(Object.assign({localPath:b},S),(P,L)=>{P&&k(P),L&&A(this)})})},addFile:function(b,S,A,k){b=x(b);let P=h(b),L=P!=null;L||(P=new Xm(i),P.entryName=b),P.comment=A||"";let E=typeof k=="object"&&k instanceof o.fs.Stats;E&&(P.header.time=k.mtime);var D=P.isDirectory?16:0;let N=P.isDirectory?16384:32768;return E?N|=4095&k.mode:typeof k=="number"?N|=4095&k:N|=P.isDirectory?493:420,D=(D|N<<16)>>>0,P.attr=D,P.setData(S),L||c.setEntry(P),P},getEntries:function(b){return c.password=b,c?c.entries:[]},getEntry:function(b){return h(b)},getEntryCount:function(){return c.getEntryCount()},forEach:function(b){return c.forEach(b)},extractEntryTo:function(b,S,A,k,P,L){k=On(!1,k),P=On(!1,P),A=On(!0,A),L=vu(P,L);var E=h(b);if(!E)throw Ee.Errors.NO_ENTRY();var D=d(E.entryName),N=u(S,L&&!E.isDirectory?L:A?D:be.basename(D));if(E.isDirectory){var z=c.getEntryChildren(E);return z.forEach(function(V){if(V.isDirectory)return;var re=V.getData();if(!re)throw Ee.Errors.CANT_EXTRACT_FILE();var Z=d(V.entryName),oe=u(S,A?Z:be.basename(Z));let ce=P?V.header.fileAttr:void 0;o.writeFileTo(oe,re,k,ce)}),!0}var B=E.getData(c.password);if(!B)throw Ee.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(N)&&!k)throw Ee.Errors.CANT_OVERRIDE();let Y=P?b.header.fileAttr:void 0;return o.writeFileTo(N,B,k,Y),!0},test:function(b){if(!c)return!1;for(var S in c.entries)try{if(S.isDirectory)continue;var A=c.entries[S].getData(b);if(!A)return!1}catch{return!1}return!0},extractAllTo:function(b,S,A,k){if(A=On(!1,A),k=vu(A,k),S=On(!1,S),!c)throw Ee.Errors.NO_ZIP();c.entries.forEach(function(P){var L=u(b,d(P.entryName));if(P.isDirectory){o.makeDir(L);return}var E=P.getData(k);if(!E)throw Ee.Errors.CANT_EXTRACT_FILE();let D=A?P.header.fileAttr:void 0;o.writeFileTo(L,E,S,D);try{o.fs.utimesSync(L,P.header.time,P.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(b,S,A,k){if(k=Qm(S,A,k),A=On(!1,A),S=On(!1,S),!k)return new Promise((N,z)=>{this.extractAllToAsync(b,S,A,function(B){B?z(B):N(this)})});if(!c){k(Ee.Errors.NO_ZIP());return}b=be.resolve(b);let P=N=>u(b,be.normalize(d(N.entryName))),L=(N,z)=>new Error(N+': "'+z+'"'),E=[],D=[];c.entries.forEach(N=>{N.isDirectory?E.push(N):D.push(N)});for(let N of E){let z=P(N),B=A?N.header.fileAttr:void 0;try{o.makeDir(z),B&&o.fs.chmodSync(z,B),o.fs.utimesSync(z,N.header.time,N.header.time)}catch{k(L("Unable to create folder",z))}}D.reverse().reduce(function(N,z){return function(B){if(B)N(B);else{let Y=be.normalize(d(z.entryName)),V=u(b,Y);z.getDataAsync(function(re,Z){if(Z)N(Z);else if(!re)N(Ee.Errors.CANT_EXTRACT_FILE());else{let oe=A?z.header.fileAttr:void 0;o.writeFileToAsync(V,re,S,oe,function(ce){ce||N(L("Unable to write file",V)),o.fs.utimes(V,z.header.time,z.header.time,function(R){R?N(L("Unable to set times",V)):N()})})}})}}},k)()},writeZip:function(b,S){if(arguments.length===1&&typeof b=="function"&&(S=b,b=""),!b&&i.filename&&(b=i.filename),!!b){var A=c.compressToBuffer();if(A){var k=o.writeFileTo(b,A,!0);typeof S=="function"&&S(k?null:new Error("failed"),"")}}},writeZipPromise:function(b,S){let{overwrite:A,perm:k}=Object.assign({overwrite:!0},S);return new Promise((P,L)=>{!b&&i.filename&&(b=i.filename),b||L("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let D=N=>N?P(N):L("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(b,E,A,k,D)},L)})},toBufferPromise:function(){return new Promise((b,S)=>{c.toAsyncBuffer(b,S)})},toBuffer:function(b,S,A,k){return typeof b=="function"?(c.toAsyncBuffer(b,S,A,k),null):c.compressToBuffer()}}}});import{execFile as oy,spawn as ay,spawnSync as hk}from"node:child_process";import{promisify as cy}from"node:util";function ly(t){if(process.platform!=="win32")return!1;if(Wf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Wf,"").toLowerCase();return dy.has(r)}function Kf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return ly(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function it(t,e=[],r={}){return ay(t,e,Kf(t,r))}function $f(t,e=[],r={}){return uy(t,e,Kf(t,r))}var dy,Wf,uy,Jt=et(()=>{"use strict";dy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Wf=/\.(cmd|bat|ps1)$/i;uy=cy(oy)});var Zt=de((ER,qx)=>{"use strict";var Hx=["nodebuffer","arraybuffer","fragments"],Gx=typeof Blob<"u";Gx&&Hx.push("blob");qx.exports={BINARY_TYPES:Hx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Gx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Qi=de((vR,Fo)=>{"use strict";var{EMPTY_BUFFER:nv}=Zt(),vd=Buffer[Symbol.species];function rv(t,e){if(t.length===0)return nv;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 vd(r.buffer,r.byteOffset,i):r}function jx(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Wx(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function iv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Sd(t){if(Sd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new vd(t):ArrayBuffer.isView(t)?e=new vd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Sd.readOnly=!1),e}Fo.exports={concat:rv,mask:jx,toArrayBuffer:iv,toBuffer:Sd,unmask:Wx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");Fo.exports.mask=function(e,r,i,o,c){c<48?jx(e,r,i,o,c):t.mask(e,r,i,o,c)},Fo.exports.unmask=function(e,r){e.length<32?Wx(e,r):t.unmask(e,r)}}catch{}});var Vx=de((SR,$x)=>{"use strict";var Kx=Symbol("kDone"),Id=Symbol("kRun"),Ad=class{constructor(e){this[Kx]=()=>{this.pending--,this[Id]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Id]()}[Id](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Kx])}}};$x.exports=Ad});var qr=de((IR,Zx)=>{"use strict";var es=xe("zlib"),Yx=Qi(),sv=Vx(),{kStatusCode:Jx}=Zt(),ov=Buffer[Symbol.species],av=Buffer.from([0,0,255,255]),Uo=Symbol("permessage-deflate"),Qt=Symbol("total-length"),Hr=Symbol("callback"),Tn=Symbol("buffers"),Gr=Symbol("error"),zo,kd=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,!zo){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zo=new sv(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Hr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let o=r[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){zo.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){zo.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"?es.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=es.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Uo]=this,this._inflate[Qt]=0,this._inflate[Tn]=[],this._inflate.on("error",dv),this._inflate.on("data",Xx)}this._inflate[Hr]=i,this._inflate.write(e),r&&this._inflate.write(av),this._inflate.flush(()=>{let c=this._inflate[Gr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Yx.concat(this._inflate[Tn],this._inflate[Qt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Qt]=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"?es.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=es.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Qt]=0,this._deflate[Tn]=[],this._deflate.on("data",cv)}this._deflate[Hr]=i,this._deflate.write(e),this._deflate.flush(es.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Yx.concat(this._deflate[Tn],this._deflate[Qt]);r&&(c=new ov(c.buffer,c.byteOffset,c.length-4)),this._deflate[Hr]=null,this._deflate[Qt]=0,this._deflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Zx.exports=kd;function cv(t){this[Tn].push(t),this[Qt]+=t.length}function Xx(t){if(this[Qt]+=t.length,this[Uo]._maxPayload<1||this[Qt]<=this[Uo]._maxPayload){this[Tn].push(t);return}this[Gr]=new RangeError("Max payload size exceeded"),this[Gr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Gr][Jx]=1009,this.removeListener("data",Xx),this.reset()}function dv(t){if(this[Uo]._inflate=null,this[Gr]){this[Hr](this[Gr]);return}t[Jx]=1007,this[Hr](t)}});var jr=de((AR,Ho)=>{"use strict";var{isUtf8:Qx}=xe("buffer"),{hasBlob:lv}=Zt(),uv=[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 fv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Td(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 xv(t){return lv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ho.exports={isBlob:xv,isValidStatusCode:fv,isValidUTF8:Td,tokenChars:uv};if(Qx)Ho.exports.isValidUTF8=function(t){return t.length<24?Td(t):Qx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");Ho.exports.isValidUTF8=function(e){return e.length<32?Td(e):t(e)}}catch{}});var Od=de((kR,oh)=>{"use strict";var{Writable:hv}=xe("stream"),eh=qr(),{BINARY_TYPES:pv,EMPTY_BUFFER:th,kStatusCode:gv,kWebSocket:mv}=Zt(),{concat:Cd,toArrayBuffer:wv,unmask:_v}=Qi(),{isValidStatusCode:yv,isValidUTF8:nh}=jr(),Go=Buffer[Symbol.species],gt=0,rh=1,ih=2,sh=3,Pd=4,Rd=5,qo=6,Dd=class extends hv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pv[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[mv]=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();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 Go(i.buffer,i.byteOffset+e,i.length-e),new Go(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 Go(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 rh:this.getPayloadLength16(e);break;case ih:this.getPayloadLength64(e);break;case sh:this.getMask();break;case Pd:this.getData(e);break;case Rd:case qo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(r[0]&64)===64;if(i&&!this._extensions[eh.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=rh:this._payloadLength===127?this._state=ih: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=sh:this._state=Pd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Pd}getData(e){let r=th;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&&_v(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Rd,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[eh.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===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=Cd(i,r):this._binaryType==="arraybuffer"?o=wv(Cd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=gt):(this._state=qo,setImmediate(()=>{this.emit("message",o,!0),this._state=gt,this.startLoop(e)}))}else{let o=Cd(i,r);if(!this._skipUTF8Validation&&!nh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Rd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=gt):(this._state=qo,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,th),this.end();else{let i=e.readUInt16BE(0);if(!yv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Go(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!nh(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=qo,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[gv]=o,d}};oh.exports=Dd});var Md=de((CR,dh)=>{"use strict";var{Duplex:TR}=xe("stream"),{randomFillSync:bv}=xe("crypto"),{types:{isUint8Array:Ev}}=xe("util"),ah=qr(),{EMPTY_BUFFER:vv,kWebSocket:Sv,NOOP:Iv}=Zt(),{isBlob:Wr,isValidStatusCode:Av}=jr(),{mask:ch,toBuffer:Xn}=Qi(),mt=Symbol("kByteLength"),kv=Buffer.alloc(4),jo=8*1024,Zn,Kr=jo,At=0,Tv=1,Cv=2,Ld=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=Iv,this[Sv]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||kv,r.generateMask?r.generateMask(i):(Kr===jo&&(Zn===void 0&&(Zn=Buffer.alloc(jo)),bv(Zn,0,jo),Kr=0),i[0]=Zn[Kr++],i[1]=Zn[Kr++],i[2]=Zn[Kr++],i[3]=Zn[Kr++]),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 x=u;u>=65536?(c+=8,x=127):u>125&&(c+=2,x=126);let h=Buffer.allocUnsafe(o?u+c:c);return h[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(h[0]|=64),h[1]=x,x===126?h.writeUInt16BE(u,2):x===127&&(h[2]=h[3]=0,h.writeUIntBE(u,4,6)),r.mask?(h[1]|=128,h[c-4]=i[0],h[c-3]=i[1],h[c-2]=i[2],h[c-1]=i[3],d?[h,e]:o?(ch(e,i,h,c,u),[h]):(ch(e,i,e,0,u),[h,e])):[h,e]}close(e,r,i,o){let c;if(e===void 0)c=vv;else{if(typeof e!="number"||!Av(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(Ev(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}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):Wr(e)?(o=e.size,c=!1):(e=Xn(e),o=e.length,c=Xn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[mt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Wr(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):Wr(e)?(o=e.size,c=!1):(e=Xn(e),o=e.length,c=Xn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[mt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Wr(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[ah.extensionName],c=r.binary?2:1,d=r.compress,u,x;typeof e=="string"?(u=Buffer.byteLength(e),x=!1):Wr(e)?(u=e.size,x=!1):(e=Xn(e),u=e.length,x=Xn.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,c=0),r.fin&&(this._firstFragment=!0);let h={[mt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:x,rsv1:d};Wr(e)?this._state!==At?this.enqueue([this.getBlobData,e,this._compress,h,i]):this.getBlobData(e,this._compress,h,i):this._state!==At?this.enqueue([this.dispatch,e,this._compress,h,i]):this.dispatch(e,this._compress,h,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[mt],this._state=Cv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Nd,this,u,o);return}this._bufferedBytes-=i[mt];let d=Xn(c);r?this.dispatch(d,r,i,o):(this._state=At,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(Pv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[ah.extensionName];this._bufferedBytes+=i[mt],this._state=Tv,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let x=new Error("The socket was closed while data was being compressed");Nd(this,x,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)}};dh.exports=Ld;function Nd(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 Pv(t,e,r){Nd(t,e,r),t.onerror(e)}});var wh=de((PR,mh)=>{"use strict";var{kForOnEventAttribute:ts,kListener:Bd}=Zt(),lh=Symbol("kCode"),uh=Symbol("kData"),fh=Symbol("kError"),xh=Symbol("kMessage"),hh=Symbol("kReason"),$r=Symbol("kTarget"),ph=Symbol("kType"),gh=Symbol("kWasClean"),en=class{constructor(e){this[$r]=null,this[ph]=e}get target(){return this[$r]}get type(){return this[ph]}};Object.defineProperty(en.prototype,"target",{enumerable:!0});Object.defineProperty(en.prototype,"type",{enumerable:!0});var Qn=class extends en{constructor(e,r={}){super(e),this[lh]=r.code===void 0?0:r.code,this[hh]=r.reason===void 0?"":r.reason,this[gh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[lh]}get reason(){return this[hh]}get wasClean(){return this[gh]}};Object.defineProperty(Qn.prototype,"code",{enumerable:!0});Object.defineProperty(Qn.prototype,"reason",{enumerable:!0});Object.defineProperty(Qn.prototype,"wasClean",{enumerable:!0});var Vr=class extends en{constructor(e,r={}){super(e),this[fh]=r.error===void 0?null:r.error,this[xh]=r.message===void 0?"":r.message}get error(){return this[fh]}get message(){return this[xh]}};Object.defineProperty(Vr.prototype,"error",{enumerable:!0});Object.defineProperty(Vr.prototype,"message",{enumerable:!0});var ns=class extends en{constructor(e,r={}){super(e),this[uh]=r.data===void 0?null:r.data}get data(){return this[uh]}};Object.defineProperty(ns.prototype,"data",{enumerable:!0});var Rv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[ts]&&o[Bd]===e&&!o[ts])return;let i;if(t==="message")i=function(c,d){let u=new ns("message",{data:d?c:c.toString()});u[$r]=this,Wo(e,this,u)};else if(t==="close")i=function(c,d){let u=new Qn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[$r]=this,Wo(e,this,u)};else if(t==="error")i=function(c){let d=new Vr("error",{error:c,message:c.message});d[$r]=this,Wo(e,this,d)};else if(t==="open")i=function(){let c=new en("open");c[$r]=this,Wo(e,this,c)};else return;i[ts]=!!r[ts],i[Bd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Bd]===e&&!r[ts]){this.removeListener(t,r);break}}};mh.exports={CloseEvent:Qn,ErrorEvent:Vr,Event:en,EventTarget:Rv,MessageEvent:ns};function Wo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Ko=de((RR,_h)=>{"use strict";var{tokenChars:rs}=jr();function Bt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Dv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,x=-1,h=-1,m=-1,w=0;for(;w<t.length;w++)if(h=t.charCodeAt(w),d===void 0)if(m===-1&&rs[h]===1)x===-1&&(x=w);else if(w!==0&&(h===32||h===9))m===-1&&x!==-1&&(m=w);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let b=t.slice(x,m);h===44?(Bt(e,b,r),r=Object.create(null)):d=b,x=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(m===-1&&rs[h]===1)x===-1&&(x=w);else if(h===32||h===9)m===-1&&x!==-1&&(m=w);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w),Bt(r,t.slice(x,m),!0),h===44&&(Bt(e,d,r),r=Object.create(null),d=void 0),x=m=-1}else if(h===61&&x!==-1&&m===-1)u=t.slice(x,w),x=m=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(rs[h]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);x===-1?x=w:i||(i=!0),o=!1}else if(c)if(rs[h]===1)x===-1&&(x=w);else if(h===34&&x!==-1)c=!1,m=w;else if(h===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(h===34&&t.charCodeAt(w-1)===61)c=!0;else if(m===-1&&rs[h]===1)x===-1&&(x=w);else if(x!==-1&&(h===32||h===9))m===-1&&(m=w);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let b=t.slice(x,m);i&&(b=b.replace(/\\/g,""),i=!1),Bt(r,u,b),h===44&&(Bt(e,d,r),r=Object.create(null),d=void 0),u=void 0,x=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(x===-1||c||h===32||h===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=w);let I=t.slice(x,m);return d===void 0?Bt(e,I,r):(u===void 0?Bt(r,I,!0):i?Bt(r,u,I.replace(/\\/g,"")):Bt(r,u,I),Bt(e,d,r)),e}function Ov(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(", ")}_h.exports={format:Ov,parse:Dv}});var Jo=de((LR,Rh)=>{"use strict";var Lv=xe("events"),Nv=xe("https"),Mv=xe("http"),Eh=xe("net"),Bv=xe("tls"),{randomBytes:Fv,createHash:zv}=xe("crypto"),{Duplex:DR,Readable:OR}=xe("stream"),{URL:Fd}=xe("url"),Cn=qr(),Uv=Od(),Hv=Md(),{isBlob:Gv}=jr(),{BINARY_TYPES:yh,CLOSE_TIMEOUT:qv,EMPTY_BUFFER:$o,GUID:jv,kForOnEventAttribute:zd,kListener:Wv,kStatusCode:Kv,kWebSocket:je,NOOP:vh}=Zt(),{EventTarget:{addEventListener:$v,removeEventListener:Vv}}=wh(),{format:Yv,parse:Jv}=Ko(),{toBuffer:Xv}=Qi(),Sh=Symbol("kAborted"),Ud=[8,13],tn=["CONNECTING","OPEN","CLOSING","CLOSED"],Zv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends Lv{constructor(e,r,i){super(),this._binaryType=yh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=$o,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]),Ih(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){yh.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,i){let o=new 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 Hv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[je]=this,c[je]=this,e[je]=this,o.on("conclude",t1),o.on("drain",n1),o.on("error",r1),o.on("message",i1),o.on("ping",s1),o.on("pong",o1),c.onerror=a1,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Th),e.on("data",Yo),e.on("end",Ch),e.on("error",Ph),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())}),kh(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){Hd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||$o,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){Hd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||$o,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){Hd(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||$o,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(we,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(we.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(we.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[zd])return e[Wv];return null},set(e){for(let r of this.listeners(t))if(r[zd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[zd]:!0})}})});we.prototype.addEventListener=$v;we.prototype.removeEventListener=Vv;Rh.exports=we;function Ih(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qv,protocolVersion:Ud[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,!Ud.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ud.join(", ")})`);let c;if(e instanceof Fd)c=e;else try{c=new Fd(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:",x;if(c.protocol!=="ws:"&&!d&&!u?x=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?x="The URL's pathname is empty":c.hash&&(x="The URL contains a fragment identifier"),x){let A=new SyntaxError(x);if(t._redirects===0)throw A;Vo(t,A);return}let h=d?443:80,m=Fv(16).toString("base64"),w=d?Nv.request:Mv.request,I=new Set,b;if(o.createConnection=o.createConnection||(d?e1:Qv),o.defaultPort=o.defaultPort||h,o.port=c.port||h,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new Cn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Yv({[Cn.extensionName]:b.offer()})),r.length){for(let A of r){if(typeof A!="string"||!Zv.test(A)||I.has(A))throw new SyntaxError("An invalid or duplicated subprotocol was specified");I.add(A)}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 A=o.path.split(":");o.socketPath=A[0],o.path=A[1]}let S;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let A=i&&i.headers;if(i={...i,headers:{}},A)for(let[k,P]of Object.entries(A))i.headers[k.toLowerCase()]=P}else if(t.listenerCount("redirect")===0){let A=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!A||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,A||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),S=t._req=w(o),t._redirects&&t.emit("redirect",t.url,S)}else S=t._req=w(o);o.timeout&&S.on("timeout",()=>{dt(t,S,"Opening handshake has timed out")}),S.on("error",A=>{S===null||S[Sh]||(S=t._req=null,Vo(t,A))}),S.on("response",A=>{let k=A.headers.location,P=A.statusCode;if(k&&o.followRedirects&&P>=300&&P<400){if(++t._redirects>o.maxRedirects){dt(t,S,"Maximum redirects exceeded");return}S.abort();let L;try{L=new Fd(k,e)}catch{let D=new SyntaxError(`Invalid URL: ${k}`);Vo(t,D);return}Ih(t,L,r,i)}else t.emit("unexpected-response",S,A)||dt(t,S,`Unexpected server response: ${A.statusCode}`)}),S.on("upgrade",(A,k,P)=>{if(t.emit("upgrade",A),t.readyState!==we.CONNECTING)return;S=t._req=null;let L=A.headers.upgrade;if(L===void 0||L.toLowerCase()!=="websocket"){dt(t,k,"Invalid Upgrade header");return}let E=zv("sha1").update(m+jv).digest("base64");if(A.headers["sec-websocket-accept"]!==E){dt(t,k,"Invalid Sec-WebSocket-Accept header");return}let D=A.headers["sec-websocket-protocol"],N;if(D!==void 0?I.size?I.has(D)||(N="Server sent an invalid subprotocol"):N="Server sent a subprotocol but none was requested":I.size&&(N="Server sent no subprotocol"),N){dt(t,k,N);return}D&&(t._protocol=D);let z=A.headers["sec-websocket-extensions"];if(z!==void 0){if(!b){dt(t,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=Jv(z)}catch{dt(t,k,"Invalid Sec-WebSocket-Extensions header");return}let Y=Object.keys(B);if(Y.length!==1||Y[0]!==Cn.extensionName){dt(t,k,"Server indicated an extension that was not requested");return}try{b.accept(B[Cn.extensionName])}catch{dt(t,k,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Cn.extensionName]=b}t.setSocket(k,P,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,t):S.end()}function Vo(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Qv(t){return t.path=t.socketPath,Eh.connect(t)}function e1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Eh.isIP(t.host)?"":t.host),Bv.connect(t)}function dt(t,e,r){t._readyState=we.CLOSING;let i=new Error(r);Error.captureStackTrace(i,dt),e.setHeader?(e[Sh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Vo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Hd(t,e,r){if(e){let i=Gv(e)?e.size:Xv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${tn[t.readyState]})`);process.nextTick(r,i)}}function t1(t,e){let r=this[je];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[je]!==void 0&&(r._socket.removeListener("data",Yo),process.nextTick(Ah,r._socket),t===1005?r.close():r.close(t,e))}function n1(){let t=this[je];t.isPaused||t._socket.resume()}function r1(t){let e=this[je];e._socket[je]!==void 0&&(e._socket.removeListener("data",Yo),process.nextTick(Ah,e._socket),e.close(t[Kv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function bh(){this[je].emitClose()}function i1(t,e){this[je].emit("message",t,e)}function s1(t){let e=this[je];e._autoPong&&e.pong(t,!this._isServer,vh),e.emit("ping",t)}function o1(t){this[je].emit("pong",t)}function Ah(t){t.resume()}function a1(t){let e=this[je];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,kh(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function kh(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Th(){let t=this[je];if(this.removeListener("close",Th),this.removeListener("data",Yo),this.removeListener("end",Ch),t._readyState=we.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",bh),t._receiver.on("finish",bh))}function Yo(t){this[je]._receiver.write(t)||this.pause()}function Ch(){let t=this[je];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function Ph(){let t=this[je];this.removeListener("error",Ph),this.on("error",vh),t&&(t._readyState=we.CLOSING,this.destroy())}});var Nh=de((MR,Lh)=>{"use strict";var NR=Jo(),{Duplex:c1}=xe("stream");function Dh(t){t.emit("close")}function d1(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Oh(t){this.removeListener("error",Oh),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function l1(t,e){let r=!0,i=new c1({...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(Dh,i);return}let d=!1;t.once("error",function(x){d=!0,c(x)}),t.once("close",function(){d||c(o),process.nextTick(Dh,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",d1),i.on("error",Oh),i}Lh.exports=l1});var Gd=de((BR,Mh)=>{"use strict";var{tokenChars:u1}=jr();function f1(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&&u1[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}Mh.exports={parse:f1}});var qh=de((zR,Gh)=>{"use strict";var x1=xe("events"),Xo=xe("http"),{Duplex:FR}=xe("stream"),{createHash:h1}=xe("crypto"),Bh=Ko(),er=qr(),p1=Gd(),g1=Jo(),{CLOSE_TIMEOUT:m1,GUID:w1,kWebSocket:_1}=Zt(),y1=/^[+/0-9A-Za-z]{22}==$/,Fh=0,zh=1,Hh=2,qd=class extends x1{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:m1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:g1,...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=Xo.createServer((i,o)=>{let c=Xo.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=b1(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=Fh}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===Hh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(is,this);return}if(e&&this.once("close",e),this._state!==zh)if(this._state=zh,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(is,this):process.nextTick(is,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{is(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",Uh);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){tr(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!y1.test(c)){tr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){tr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ss(r,400);return}let x=e.headers["sec-websocket-protocol"],h=new Set;if(x!==void 0)try{h=p1.parse(x)}catch{tr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&m!==void 0){let I=new er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let b=Bh.parse(m);b[er.extensionName]&&(I.accept(b[er.extensionName]),w[er.extensionName]=I)}catch{tr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let I={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(I,(b,S,A,k)=>{if(!b)return ss(r,S||401,A,k);this.completeUpgrade(w,c,h,e,r,i,o)});return}if(!this.options.verifyClient(I))return ss(r,401)}this.completeUpgrade(w,c,h,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[_1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Fh)return ss(c,503);let h=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${h1("sha1").update(r+w1).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(h.push(`Sec-WebSocket-Protocol: ${w}`),m._protocol=w)}if(e[er.extensionName]){let w=e[er.extensionName].params,I=Bh.format({[er.extensionName]:[w]});h.push(`Sec-WebSocket-Extensions: ${I}`),m._extensions=e}this.emit("headers",h,o),c.write(h.concat(`\r
8
+ var jm=Object.create;var Ma=Object.defineProperty;var Km=Object.getOwnPropertyDescriptor;var Wm=Object.getOwnPropertyNames;var $m=Object.getPrototypeOf,Vm=Object.prototype.hasOwnProperty;var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var it=(t,e)=>()=>(t&&(e=t(t=0)),e);var le=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ba=(t,e)=>{for(var n in e)Ma(t,n,{get:e[n],enumerable:!0})},Jm=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wm(e))!Vm.call(t,o)&&o!==n&&Ma(t,o,{get:()=>e[o],enumerable:!(i=Km(e,o))||i.enumerable});return t};var qt=(t,e,n)=>(n=t!=null?jm($m(t)):{},Jm(e||!t||!t.__esModule?Ma(n,"default",{value:t,enumerable:!0}):n,t));function Xe(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ar=it(()=>{"use strict"});import{createWriteStream as Zm,mkdirSync as Ym,readdirSync as Xm,unlinkSync as Qm}from"node:fs";import{join as Cl}from"node:path";function Dn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function cr(t,e){return`${t}-${e}.log`}function Fa(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function eg(t,e,n){let i=c=>{let[l,u,h]=c.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>n}function ws(t,e,n,i){let o;try{o=Xm(t)}catch{return}for(let c of o){let l=Fa(c,e);if(l&&eg(l,n,i))try{Qm(Cl(t,c))}catch{}}}var si,za=it(()=>{"use strict";si=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Dn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let n=this.clock();n!==this.currentDate&&this.rotate(n),this.stream?.write(e)}rotate(e){this.stream?.end();try{Ym(this.dir,{recursive:!0});let n=Zm(Cl(this.dir,cr(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
+ `)),this.stream=n}catch(n){process.stderr.write(`[log-sink] rotate failed: ${String(n)}
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&ws(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as tg,mkdirSync as ng}from"node:fs";import{join as rg}from"node:path";function Ol(t){let e=t.retentionDays??og,n=t.clock??(()=>Dn(new Date));ys={bridgeSink:new si(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new si(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();ws(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])ws(t.agentLogsDir(o),"agent",i,e)}function ag(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Ll(t){Ua=t}function Nl(t){return dr[Ua]<=dr[t]}function Ml(t,e){let n=dr[t];return n===void 0?!0:n>=dr[e]}function bs(t){Dl={...t}}function Bl(t){let e=(u,h=2)=>String(u).padStart(h,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",o=Math.abs(n),c=e(Math.floor(o/60)),l=e(o%60);return`${Dn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${l}`}function st(t,e,n,i,o){try{let c=`${JSON.stringify({ts:Bl(new Date),level:e,module:n,msg:i,...o})}
11
+ `;ng(t,{recursive:!0}),tg(rg(t,cr("bridge",Dn(new Date))),c)}catch{}}function cg(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function _s(t,e,n,i,o){if(dr[t]<dr[Ua])return;let c=`${JSON.stringify({ts:Bl(new Date),level:t,module:e,msg:n,...Dl,...i})}
12
+ `;if(ys){let l=cg(o,i),u=l?ag(ys,l):ys.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?sg.write(c):ig.write(c)}function K(t,e){return{debug:(n,i)=>_s("debug",t,n,i,e),info:(n,i)=>_s("info",t,n,i,e),warn:(n,i)=>_s("warn",t,n,i,e),error:(n,i)=>_s("error",t,n,i,e),child:n=>K(`${t}.${n}`,e),forAgent:n=>K(t,n)}}var dr,Ua,ig,sg,Dl,og,ys,ne=it(()=>{"use strict";ar();za();dr={debug:10,info:20,warn:30,error:40},Ua=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),ig=process.stdout,sg=process.stderr,Dl={},og=Xe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ys=null});var k,Ve=it(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,n,i){super(n),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Gl={};Ba(Gl,{ACP_WRAPPER_NPM_PACKAGES:()=>Es,_resetAcpInstallerForTests:()=>xg,_setBinaryPathCacheForTests:()=>pg,buildAcpSpawn:()=>ai,ensureAcpInstalled:()=>lr,getAcpBinaryPath:()=>vs,pickWhichLine:()=>qa,probeAcpVersion:()=>hg,resolveAcpCommand:()=>Ul});import{readFileSync as Fl}from"node:fs";import{createRequire as dg}from"node:module";import{dirname as lg,resolve as ug}from"node:path";function qa(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=i=>e.find(o=>o.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function fg(t){let e=zl.resolve(`${t.npmPackage}/package.json`),n=lg(e),i=JSON.parse(Fl(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 ug(n,o)}async function lr(t,e){let n=Ha[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=oi.get(t);if(i)return i;try{let o=fg(n);return oi.set(t,o),Ga.info("acp wrapper resolved",{framework:t,binary:n.binary,path:o}),o}catch(o){throw Ga.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(o)}),new k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${n.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
+ `),{cause:o})}}async function hg(t){let e=Ha[t];if(e)try{let n=zl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Fl(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Ga.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function vs(t){return oi.get(t)}function Ul(t,e){if(e)return e;let n=vs(t);if(!n)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return n}function ai(t,e,n){if(e)return{command:e,args:[...n]};let i=Ul(t);return{command:process.execPath,args:[i,...n]}}function xg(){oi.clear()}function pg(t,e){oi.set(t,e)}var Ga,Ha,Es,zl,oi,ln=it(()=>{"use strict";Ve();ne();Ga=K("agents.acp-installer"),Ha={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Es=Object.values(Ha).filter(t=>t!==void 0).map(t=>t.npmPackage),zl=dg(import.meta.url),oi=new Map});import{chmod as gg,mkdir as wg,readFile as _g,rename as yg,rm as bg,writeFile as Eg}from"node:fs/promises";import{dirname as vg}from"node:path";async function ur(t){try{let e=await _g(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ht(t,e,n){await wg(vg(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Eg(i,e,{encoding:"utf8",mode:n?.mode}),await yg(i,t),n?.mode!==void 0&&await gg(t,n.mode)}catch(o){throw await bg(i,{force:!0}).catch(()=>{}),o}}async function fr(t,e,n){await ht(t,`${JSON.stringify(e,null,2)}
14
+ `,n)}var jt=it(()=>{"use strict"});import{promises as jl,readdirSync as Sg}from"node:fs";import{homedir as Ig}from"node:os";import{sep as Ag,join as Re,resolve as Kl}from"node:path";function Y(t){let e=t??Ig(),n=Re(e,".coze"),i=Re(n,"bridge"),o=Re(i,"lib"),c=Re(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:Re(o,"index.js"),binDir:Re(i,"bin"),pidFile:Re(i,"bridge.pid"),portFile:Re(i,"bridge.port"),tokenFile:Re(i,"bridge.token"),patTokenFile:Re(i,"pat-token"),agentEnvFile:Re(i,"agent-env.json"),logFile:Re(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Re(c,"daemon-stdio.log"),installLock:Re(i,"install.lock"),configFile:Re(i,"config.json"),agentsRoot:Re(n,"agents")}}function Ue(t,e=Y()){let n=Re(e.agentsRoot,t);return{root:n,config:Re(n,"config.json"),workspace:Re(n,"workspace"),logs:Re(n,"logs")}}function Ss(t=Y()){try{return Sg(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ci(t,e){let n=await jl.realpath(Kl(t)).catch(()=>null);if(!n)return!1;let i=await jl.realpath(Kl(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?n.toLowerCase():n,c=process.platform==="win32"?i.toLowerCase():i;return o===c||o.startsWith(c+Ag)}var Pe=it(()=>{"use strict"});var As={};Ba(As,{AGENT_CONFIG_FILE_MODE:()=>Is,enforceAgentConfigMode:()=>Rg,loadAgentConfig:()=>Se,persistAgentSessions:()=>di,persistAgentSkills:()=>li,saveAgentConfig:()=>Ge});import{chmod as kg,stat as Tg}from"node:fs/promises";function Se(t,e){return ur(Ue(t,e).config)}function Ge(t,e){return fr(Ue(t.agentId,e).config,t,{mode:Is})}async function Rg(t,e){if(process.platform==="win32")return;let n=Ue(t,e).config;try{let i=await Tg(n);if(!i.isFile())return;let o=i.mode&511;o!==Is&&(await kg(n,Is),Wl.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Wl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function di(t,e,n){let i=await Se(t,n);i&&(i.sessions=Object.fromEntries(e),await Ge(i,n))}async function li(t,e,n){let i=await Se(t,n);i&&(i.skills=e,await Ge(i,n))}var Wl,Is,Kt=it(()=>{"use strict";jt();ne();Pe();Wl=K("agent-config"),Is=384});var Wa=le((L2,Jl)=>{Jl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Ts=le(Yl=>{var Zl={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 Ng(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(n,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Zl))Yl[t]=Ng(Zl[t])});var nu=le((M2,tu)=>{var Mg=xe("fs"),Me=xe("path"),Xl=Wa(),Bg=Ts(),Fg=typeof process=="object"&&process.platform==="win32",Ql=t=>typeof t=="object"&&t!==null,eu=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Ie(t){this.sep=Me.sep,this.fs=Mg,Ql(t)&&Ql(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}tu.exports=Ie;Ie.prototype.makeDir=function(t){let e=this;function n(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var l;try{l=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(l&&l.isFile())throw Bg.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};Ie.prototype.writeFileTo=function(t,e,n,i){let o=this;if(o.fs.existsSync(t)){if(!n)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var l=Me.dirname(t);o.fs.existsSync(l)||o.makeDir(l);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ie.prototype.writeFileToAsync=function(t,e,n,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(l){if(l&&!n)return o(!1);c.fs.stat(t,function(u,h){if(l&&h.isDirectory())return o(!1);var x=Me.dirname(t);c.fs.exists(x,function(m){m||c.makeDir(x),c.fs.open(t,"w",438,function(w,v){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):v?c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ie.prototype.findFiles=function(t){let e=this;function n(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let l=[];return e.fs.readdirSync(i).forEach(function(u){let h=Me.join(i,u),x=e.fs.statSync(h);(!o||o.test(h))&&l.push(Me.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(l=l.concat(n(h,o,c)))}),l}return n(t,void 0,!0)};Ie.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(o,c){if(o)return e(o);let l=c.length;if(!l)return e(null,i);c.forEach(function(u){u=Me.join(t,u),n.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Me.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(m,w){if(m)return e(m);i=i.concat(w),--l||e(null,i)}):--l||e(null,i))})})})};Ie.prototype.getAttributes=function(){};Ie.prototype.setAttributes=function(){};Ie.crc32update=function(t,e){return eu[(t^e)&255]^t>>>8};Ie.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Ie.crc32update(n,t[i++]);return~n>>>0};Ie.methodToString=function(t){switch(t){case Xl.STORED:return"STORED ("+t+")";case Xl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ie.canonical=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.join(".",e)};Ie.zipnamefix=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.posix.join(".",e)};Ie.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let i=n-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ie.sanitize=function(t,e){t=Me.resolve(Me.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var c=Me.normalize(Me.join(t,n.slice(i,o).join(Me.sep)));if(c.indexOf(t)===0)return c}return Me.normalize(Me.join(t,Me.basename(e)))};Ie.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Ie.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Ie.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ie.fromDate2DOS=function(t){let e=0,n=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),n=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|n};Ie.isWin=Fg;Ie.crcTable=eu});var iu=le((B2,ru)=>{var zg=xe("path");ru.exports=function(t,{fs:e}){var n=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(o=e.statSync(n),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=zg.basename(n)[0]==="."):console.warn("Invalid path: "+n),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:n,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ou=le((F2,su)=>{su.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=le((z2,xr)=>{xr.exports=nu();xr.exports.Constants=Wa();xr.exports.Errors=Ts();xr.exports.FileAttr=iu();xr.exports.decoder=ou()});var cu=le((U2,au)=>{var un=pr(),j=un.Constants;au.exports=function(){var t=20,e=10,n=0,i=0,o=0,c=0,l=0,u=0,h=0,x=0,m=0,w=0,v=0,_=0,E=0;t|=un.isWin?2560:768,n|=j.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,T=b=>Math.max(0,b)&65535,O=b=>Math.max(0,b)&255;return o=un.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return n},set flags(b){n=b},get flags_efs(){return(n&j.FLG_EFS)>0},set flags_efs(b){b?n|=j.FLG_EFS:n&=~j.FLG_EFS},get flags_desc(){return(n&j.FLG_DESC)>0},set flags_desc(b){b?n|=j.FLG_DESC:n&=~j.FLG_DESC},get method(){return i},set method(b){switch(b){case j.STORED:this.version=10;case j.DEFLATED:default:this.version=20}i=b},get time(){return un.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=un.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=A(b)},get timeHighByte(){return O(o>>>8)},get crc(){return c},set crc(b){c=A(b)},get compressedSize(){return l},set compressedSize(b){l=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return 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 w},set diskNumStart(b){w=A(b)},get inAttr(){return v},set inAttr(b){v=A(b)},get attr(){return _},set attr(b){_=A(b)},get fileAttr(){return(_||0)>>16&4095},get offset(){return E},set offset(b){E=A(b)},get encrypted(){return(n&j.FLG_ENC)===j.FLG_ENC},get centralHeaderSize(){return j.CENHDR+h+x+m},get realDataOffset(){return E+j.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var D=b.slice(E,E+j.LOCHDR);if(D.readUInt32LE(0)!==j.LOCSIG)throw un.Errors.INVALID_LOC();I.version=D.readUInt16LE(j.LOCVER),I.flags=D.readUInt16LE(j.LOCFLG),I.flags_desc=(I.flags&j.FLG_DESC)>0,I.method=D.readUInt16LE(j.LOCHOW),I.time=D.readUInt32LE(j.LOCTIM),I.crc=D.readUInt32LE(j.LOCCRC),I.compressedSize=D.readUInt32LE(j.LOCSIZ),I.size=D.readUInt32LE(j.LOCLEN),I.fnameLen=D.readUInt16LE(j.LOCNAM),I.extraLen=D.readUInt16LE(j.LOCEXT);let L=E+j.LOCHDR+I.fnameLen,G=L+I.extraLen;return b.slice(L,G)},loadFromBinary:function(b){if(b.length!==j.CENHDR||b.readUInt32LE(0)!==j.CENSIG)throw un.Errors.INVALID_CEN();t=b.readUInt16LE(j.CENVEM),e=b.readUInt16LE(j.CENVER),n=b.readUInt16LE(j.CENFLG),i=b.readUInt16LE(j.CENHOW),o=b.readUInt32LE(j.CENTIM),c=b.readUInt32LE(j.CENCRC),l=b.readUInt32LE(j.CENSIZ),u=b.readUInt32LE(j.CENLEN),h=b.readUInt16LE(j.CENNAM),x=b.readUInt16LE(j.CENEXT),m=b.readUInt16LE(j.CENCOM),w=b.readUInt16LE(j.CENDSK),v=b.readUInt16LE(j.CENATT),_=b.readUInt32LE(j.CENATX),E=b.readUInt32LE(j.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(j.LOCHDR);return b.writeUInt32LE(j.LOCSIG,0),b.writeUInt16LE(e,j.LOCVER),b.writeUInt16LE(n,j.LOCFLG),b.writeUInt16LE(i,j.LOCHOW),b.writeUInt32LE(o,j.LOCTIM),b.writeUInt32LE(c,j.LOCCRC),b.writeUInt32LE(l,j.LOCSIZ),b.writeUInt32LE(u,j.LOCLEN),b.writeUInt16LE(h,j.LOCNAM),b.writeUInt16LE(I.extraLen,j.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(j.CENHDR+h+x+m);return b.writeUInt32LE(j.CENSIG,0),b.writeUInt16LE(t,j.CENVEM),b.writeUInt16LE(e,j.CENVER),b.writeUInt16LE(n,j.CENFLG),b.writeUInt16LE(i,j.CENHOW),b.writeUInt32LE(o,j.CENTIM),b.writeUInt32LE(c,j.CENCRC),b.writeUInt32LE(l,j.CENSIZ),b.writeUInt32LE(u,j.CENLEN),b.writeUInt16LE(h,j.CENNAM),b.writeUInt16LE(x,j.CENEXT),b.writeUInt16LE(m,j.CENCOM),b.writeUInt16LE(w,j.CENDSK),b.writeUInt16LE(v,j.CENATT),b.writeUInt32LE(_,j.CENATX),b.writeUInt32LE(E,j.CENOFF),b},toJSON:function(){let b=function(D){return D+" bytes"};return{made:t,version:e,flags:n,method:un.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(l),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(m),diskNumStart:w,inAttr:v,attr:_,offset:E,centralHeaderSize:b(j.CENHDR+h+x+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var lu=le((G2,du)=>{var mr=pr(),be=mr.Constants;du.exports=function(){var t=0,e=0,n=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return n},set size(c){n=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return 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 mr.Errors.INVALID_END();c.readUInt32LE(0)===be.ENDSIG?(t=c.readUInt16LE(be.ENDSUB),e=c.readUInt16LE(be.ENDTOT),n=c.readUInt32LE(be.ENDSIZ),i=c.readUInt32LE(be.ENDOFF),o=c.readUInt16LE(be.ENDCOM)):(t=mr.readBigUInt64LE(c,be.ZIP64SUB),e=mr.readBigUInt64LE(c,be.ZIP64TOT),n=mr.readBigUInt64LE(c,be.ZIP64SIZE),i=mr.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(n,be.ENDSIZ),c.writeUInt32LE(i,be.ENDOFF),c.writeUInt16LE(o,be.ENDCOM),c.fill(" ",be.ENDHDR),c},toJSON:function(){let c=function(l,u){let h=l.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Va=le($a=>{$a.EntryHeader=cu();$a.MainHeader=lu()});var fu=le((q2,uu)=>{uu.exports=function(t){var e=xe("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var o=e.createDeflateRaw(n),c=[],l=0;o.on("data",function(u){c.push(u),l+=u.length}),o.on("end",function(){var u=Buffer.alloc(l),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 xu=le((j2,hu)=>{var Ug=+(process.versions?process.versions.node:"").split(".")[0]||0;hu.exports=function(t,e){var n=xe("zlib");let i=Ug>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var c=n.createInflateRaw(i),l=[],u=0;c.on("data",function(h){l.push(h),u+=h.length}),c.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var m=0;m<l.length;m++){var w=l[m];w.copy(h,x),x+=w.length}o&&o(h)}),c.end(t)}}}});var _u=le((K2,wu)=>{"use strict";var{randomFillSync:pu}=xe("crypto"),Gg=Ts(),Hg=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),gu=(t,e)=>Math.imul(t,e)>>>0,mu=(t,e)=>Hg[(t^e)&255]^t>>>8,ui=()=>typeof pu=="function"?pu(Buffer.alloc(12)):ui.node();ui.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let n=0;n<e;n++)t[n]=Math.random()*256&255;return t};var Rs={genSalt:ui};function Ps(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let n=0;n<e.length;n++)this.updateKeys(e[n])}Ps.prototype.updateKeys=function(t){let e=this.keys;return e[0]=mu(e[0],t),e[1]+=e[0]&255,e[1]=gu(e[1],134775813)+1,e[2]=mu(e[2],e[1]>>>24),t};Ps.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return gu(t,t^1)>>8&255};function qg(t){let e=new Ps(t);return function(n){let i=Buffer.alloc(n.length),o=0;for(let c of n)i[o++]=e.updateKeys(c^e.next());return i}}function jg(t){let e=new Ps(t);return function(n,i,o=0){i||(i=Buffer.alloc(n.length));for(let c of n){let l=e.next();i[o++]=c^l,e.updateKeys(c)}return i}}function Kg(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=qg(n),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Gg.WRONG_PASSWORD();return i(t.slice(12))}function Wg(t){Buffer.isBuffer(t)&&t.length>=12?Rs.genSalt=function(){return t.slice(0,12)}:t==="node"?Rs.genSalt=ui.node:Rs.genSalt=ui}function $g(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=jg(n),c=Rs.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let l=Buffer.alloc(t.length+12);return o(c,l),o(t,l,12)}wu.exports={decrypt:Kg,encrypt:$g,_salter:Wg}});var yu=le(Cs=>{Cs.Deflater=fu();Cs.Inflater=xu();Cs.ZipCrypto=_u()});var Za=le(($2,bu)=>{var ue=pr(),Vg=Va(),Ae=ue.Constants,Ja=yu();bu.exports=function(t,e){var n=new Vg.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,l=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let m=t,w=typeof m.decoder=="object"?m.decoder:ue.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(b){if(!n.flags_desc&&!n.localHeader.flags_desc){if(ue.crc32(b)!==n.localHeader.crc)return!1}else{let D={},L=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(L)==Ae.LOCSIG||e.readUInt32LE(L)==Ae.CENSIG)throw ue.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(L)==Ae.EXTSIG)D.crc=e.readUInt32LE(L+Ae.EXTCRC),D.compressedSize=e.readUInt32LE(L+Ae.EXTSIZ),D.size=e.readUInt32LE(L+Ae.EXTLEN);else if(e.readUInt16LE(L+12)===19280)D.crc=e.readUInt32LE(L+Ae.EXTCRC-4),D.compressedSize=e.readUInt32LE(L+Ae.EXTSIZ-4),D.size=e.readUInt32LE(L+Ae.EXTLEN-4);else throw ue.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==n.compressedSize||D.size!==n.size||D.crc!==n.crc)throw ue.Errors.DESCRIPTOR_FAULTY();if(ue.crc32(b)!==D.crc)return!1}return!0}function E(b,D,L){if(typeof D>"u"&&typeof b=="string"&&(L=b,b=void 0),c)return b&&D&&D(Buffer.alloc(0),ue.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var G=v();if(G.length===0)return b&&D&&D(G),G;if(n.encrypted){if(typeof L!="string"&&!Buffer.isBuffer(L))throw ue.Errors.INVALID_PASS_PARAM();G=Ja.ZipCrypto.decrypt(G,n,L)}var U=Buffer.alloc(n.size);switch(n.method){case ue.Constants.STORED:if(G.copy(U),_(U))return b&&D&&D(U),U;throw b&&D&&D(U,ue.Errors.BAD_CRC()),ue.Errors.BAD_CRC();case ue.Constants.DEFLATED:var Z=new Ja.Inflater(G,n.size);if(b)Z.inflateAsync(function(J){J.copy(J,0),D&&(_(J)?D(J):D(J,ue.Errors.BAD_CRC()))});else{if(Z.inflate(U).copy(U,0),!_(U))throw ue.Errors.BAD_CRC(`"${w.decode(i)}"`);return U}break;default:throw b&&D&&D(Buffer.alloc(0),ue.Errors.UNKNOWN_METHOD()),ue.Errors.UNKNOWN_METHOD()}}function I(b,D){if((!l||!l.length)&&Buffer.isBuffer(e))return b&&D&&D(v()),v();if(l.length&&!c){var L;switch(n.method){case ue.Constants.STORED:return n.compressedSize=n.size,L=Buffer.alloc(l.length),l.copy(L),b&&D&&D(L),L;default:case ue.Constants.DEFLATED:var G=new Ja.Deflater(l);if(b)G.deflateAsync(function(Z){L=Buffer.alloc(Z.length),n.compressedSize=Z.length,Z.copy(L),D&&D(L)});else{var U=G.deflate();return n.compressedSize=U.length,U}G=null;break}}else if(b&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,D){return ue.readBigUInt64LE(b,D)}function T(b){try{for(var D=0,L,G,U;D+4<b.length;)L=b.readUInt16LE(D),D+=2,G=b.readUInt16LE(D),D+=2,U=b.slice(D,D+G),D+=G,Ae.ID_ZIP64===L&&O(U)}catch{throw ue.Errors.EXTRA_FIELD_PARSE_ERROR()}}function O(b){var D,L,G,U;b.length>=Ae.EF_ZIP64_SCOMP&&(D=A(b,Ae.EF_ZIP64_SUNCOMP),n.size===Ae.EF_ZIP64_OR_32&&(n.size=D)),b.length>=Ae.EF_ZIP64_RHO&&(L=A(b,Ae.EF_ZIP64_SCOMP),n.compressedSize===Ae.EF_ZIP64_OR_32&&(n.compressedSize=L)),b.length>=Ae.EF_ZIP64_DSN&&(G=A(b,Ae.EF_ZIP64_RHO),n.offset===Ae.EF_ZIP64_OR_32&&(n.offset=G)),b.length>=Ae.EF_ZIP64_DSN+4&&(U=b.readUInt32LE(Ae.EF_ZIP64_DSN),n.diskNumStart===Ae.EF_ZIP64_OR_16&&(n.diskNumStart=U))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=ue.toBuffer(b,w.encode);var D=i[i.length-1];c=D===47||D===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,n.extraLength=b.length,T(b)},get comment(){return w.decode(o)},set comment(b){if(o=ue.toBuffer(b,w.encode),n.commentLength=o.length,o.length>65535)throw ue.Errors.COMMENT_TOO_LONG()},get name(){var b=w.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){l=ue.toBuffer(b,ue.decoder.encode),!c&&l.length?(n.size=l.length,n.method=ue.Constants.DEFLATED,n.crc=ue.crc32(b),n.changed=!0):n.method=ue.Constants.STORED},getData:function(b){return n.changed?l:E(!1,null,b)},getDataAsync:function(b,D){n.changed?b(l):E(!0,b,D)},set attr(b){n.attr=b},get attr(){return n.attr},set header(b){n.loadFromBinary(b)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var b=n.centralHeaderToBinary(),D=ue.Constants.CENHDR;return i.copy(b,D),D+=i.length,u.copy(b,D),D+=n.extraLength,o.copy(b,D),b},packLocalHeader:function(){let b=0;n.flags_efs=this.efs,n.extraLocalLength=h.length;let D=n.localHeaderToBinary(),L=Buffer.alloc(D.length+i.length+n.extraLocalLength);return D.copy(L,b),b+=D.length,i.copy(L,b),b+=i.length,h.copy(L,b),b+=h.length,L},toJSON:function(){let b=function(D){return"<"+(D&&D.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:b(e),data:b(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Su=le((V2,vu)=>{var Eu=Za(),Jg=Va(),Je=pr();vu.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),c=new Jg.MainHeader,l=!1,u=null;let h=new Set,x=e,{noSort:m,decoder:w}=x;t?E(x.readEntries):l=!0;function v(){let A=new Set;for(let T of Object.keys(i)){let O=T.split("/");if(O.pop(),!!O.length)for(let b=0;b<O.length;b++){let D=O.slice(0,b+1).join("/")+"/";A.add(D)}}for(let T of A)if(!(T in i)){let O=new Eu(x);O.entryName=T,O.attr=16,O.temporary=!0,n.push(O),i[O.entryName]=O,h.add(O)}}function _(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/Je.Constants.CENHDR)throw Je.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(c.diskEntries);for(var A=c.offset,T=0;T<n.length;T++){var O=A,b=new Eu(x,t);b.header=t.slice(O,O+=Je.Constants.CENHDR),b.entryName=t.slice(O,O+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(O,O+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(O,O+b.header.commentLength)),A+=b.header.centralHeaderSize,n[T]=b,i[b.entryName]=b}h.clear(),v()}function E(A){var T=t.length-Je.Constants.ENDHDR,O=Math.max(0,T-65535),b=O,D=t.length,L=-1,G=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(O=0),T;T>=b;T--)if(t[T]===80){if(t.readUInt32LE(T)===Je.Constants.ENDSIG){L=T,G=T,D=T+Je.Constants.ENDHDR,b=T-Je.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Je.Constants.END64SIG){b=O;continue}if(t.readUInt32LE(T)===Je.Constants.ZIP64SIG){L=T,D=T+Je.readBigUInt64LE(t,T+Je.Constants.ZIP64SIZE)+Je.Constants.ZIP64LEAD;break}}if(L==-1)throw Je.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(L,D)),c.commentLength&&(o=t.slice(G+Je.Constants.ENDHDR)),A&&_()}function I(){n.length>1&&!m&&n.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return l||_(),n.filter(A=>!h.has(A))},get comment(){return w.decode(o)},set comment(A){o=Je.toBuffer(A,w.encode),c.commentLength=o.length},getEntryCount:function(){return l?n.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return l||_(),i[A]||null},setEntry:function(A){l||_(),n.push(A),i[A.entryName]=A,c.totalEntries=n.length},deleteFile:function(A,T=!0){l||_();let O=i[A];this.getEntryChildren(O,T).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||_();let T=i[A],O=n.indexOf(T);O>=0&&(n.splice(O,1),delete i[A],c.totalEntries=n.length)},getEntryChildren:function(A,T=!0){if(l||_(),typeof A=="object")if(A.isDirectory&&T){let O=[],b=A.entryName;for(let D of n)D.entryName.startsWith(b)&&O.push(D);return O}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){l||_(),I();let A=[],T=[],O=0,b=0;c.size=0,c.offset=0;let D=0;for(let U of this.entries){let Z=U.getCompressedData();U.header.offset=b;let J=U.packLocalHeader(),ie=J.length+Z.length;b+=ie,A.push(J),A.push(Z);let Q=U.packCentralHeader();T.push(Q),c.size+=Q.length,O+=ie+Q.length,D++}O+=c.mainHeaderSize,c.offset=b,c.totalEntries=D,b=0;let L=Buffer.alloc(O);for(let U of A)U.copy(L,b),b+=U.length;for(let U of T)U.copy(L,b),b+=U.length;let G=c.toBinary();return o&&o.copy(G,Je.Constants.ENDHDR),G.copy(L,b),t=L,l=!1,L},toAsyncBuffer:function(A,T,O,b){try{l||_(),I();let D=[],L=[],G=0,U=0,Z=0;c.size=0,c.offset=0;let J=function(ie){if(ie.length>0){let Q=ie.shift(),ce=Q.entryName+Q.extra.toString();O&&O(ce),Q.getCompressedDataAsync(function(de){b&&b(ce),Q.header.offset=U;let P=Q.packLocalHeader(),H=P.length+de.length;U+=H,D.push(P),D.push(de);let W=Q.packCentralHeader();L.push(W),c.size+=W.length,G+=H+W.length,Z++,J(ie)})}else{G+=c.mainHeaderSize,c.offset=U,c.totalEntries=Z,U=0;let Q=Buffer.alloc(G);D.forEach(function(de){de.copy(Q,U),U+=de.length}),L.forEach(function(de){de.copy(Q,U),U+=de.length});let ce=c.toBinary();o&&o.copy(ce,Je.Constants.ENDHDR),ce.copy(Q,U),t=Q,l=!1,A(Q)}};J(Array.from(this.entries))}catch(D){T(D)}}}}});var ku=le((J2,Au)=>{var ve=pr(),Ee=xe("path"),Zg=Za(),Yg=Su(),On=(...t)=>ve.findLast(t,e=>typeof e=="boolean"),Iu=(...t)=>ve.findLast(t,e=>typeof e=="string"),Xg=(...t)=>ve.findLast(t,e=>typeof e=="function"),Qg={noSort:!1,readEntries:!1,method:ve.Constants.NONE,fs:null};Au.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),Qg);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=ve.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new ve(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=ve.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=ve.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw ve.Errors.INVALID_FILENAME();let c=new Yg(n,i),{canonical:l,sanitize:u,zipnamefix:h}=ve;function x(_){if(_&&c){var E;if(typeof _=="string"&&(E=c.getEntry(Ee.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(E=c.getEntry(_.entryName)),E)return E}return null}function m(_){let{join:E,normalize:I,sep:A}=Ee.posix;return E(Ee.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function w(_){return _ instanceof RegExp?(function(E){return function(I){return E.test(I)}})(_):typeof _!="function"?()=>!0:_}let v=(_,E)=>{let I=E.slice(-1);return I=I===o.sep?o.sep:"",Ee.relative(_,E)+I};return{readFile:function(_,E){var I=x(_);return I&&I.getData(E)||null},childCount:function(_){let E=x(_);if(E)return c.getChildCount(E)},readFileAsync:function(_,E){var I=x(_);I?I.getDataAsync(E):E(null,"getEntry failed for:"+_)},readAsText:function(_,E){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(E||"utf8")}return""},readAsTextAsync:function(_,E,I){var A=x(_);A?A.getDataAsync(function(T,O){if(O){E(T,O);return}T&&T.length?E(T.toString(I||"utf8")):E("")}):E("")},deleteFile:function(_,E=!0){var I=x(_);I&&c.deleteFile(I.entryName,E)},deleteEntry:function(_){var E=x(_);E&&c.deleteEntry(E.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,E){var I=x(_);I&&(I.comment=E)},getZipEntryComment:function(_){var E=x(_);return E&&E.comment||""},updateFile:function(_,E){var I=x(_);I&&I.setData(E)},addLocalFile:function(_,E,I,A){if(o.fs.existsSync(_)){E=E?m(E):"";let T=Ee.win32.basename(Ee.win32.normalize(_));E+=I||T;let O=o.fs.statSync(_),b=O.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);O.isDirectory()&&(E+=o.sep),this.addFile(E,b,A,O)}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,E){_=typeof _=="object"?_:{localPath:_};let I=Ee.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:O}=_,b=this;o.fs.stat(I,function(D,L){if(D)return E(D,!1);T=T?m(T):"";let G=Ee.win32.basename(Ee.win32.normalize(I));if(T+=O||G,L.isFile())o.fs.readFile(I,function(U,Z){return U?E(U,!1):(b.addFile(T,Z,A,L),setImmediate(E,void 0,!0))});else if(L.isDirectory())return T+=o.sep,b.addFile(T,Buffer.alloc(0),A,L),setImmediate(E,void 0,!0)})},addLocalFolder:function(_,E,I){if(I=w(I),E=E?m(E):"",_=Ee.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),T=this;if(A.length)for(let O of A){let b=Ee.join(E,v(_,O));I(b)&&T.addLocalFile(O,Ee.dirname(b))}}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,E,I,A){A=w(A),I=I?m(I):"",_=Ee.normalize(_);var T=this;o.fs.open(_,"r",function(O){if(O&&O.code==="ENOENT")E(void 0,ve.Errors.FILE_NOT_FOUND(_));else if(O)E(void 0,O);else{var b=o.findFiles(_),D=-1,L=function(){if(D+=1,D<b.length){var G=b[D],U=v(_,G).split("\\").join("/");U=U.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(U)?o.fs.stat(G,function(Z,J){Z&&E(void 0,Z),J.isFile()?o.fs.readFile(G,function(ie,Q){ie?E(void 0,ie):(T.addFile(I+U,Q,"",J),L())}):(T.addFile(I+U+"/",Buffer.alloc(0),"",J),L())}):process.nextTick(()=>{L()})}else E(!0,void 0)};L()}})},addLocalFolderAsync2:function(_,E){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=Ee.resolve(m(_.localPath));let{zipPath:A,filter:T,namefix:O}=_;T instanceof RegExp?T=(function(L){return function(G){return L.test(G)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?m(A):"",O=="latin1"&&(O=L=>L.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof O!="function"&&(O=L=>L);let b=L=>Ee.join(A,O(v(localPath,L))),D=L=>Ee.win32.basename(Ee.win32.normalize(O(L)));o.fs.open(localPath,"r",function(L){L&&L.code==="ENOENT"?E(void 0,ve.Errors.FILE_NOT_FOUND(localPath)):L?E(void 0,L):o.findFilesAsync(localPath,function(G,U){if(G)return E(G);U=U.filter(Z=>T(b(Z))),U.length||E(void 0,!1),setImmediate(U.reverse().reduce(function(Z,J){return function(ie,Q){if(ie||Q===!1)return setImmediate(Z,ie,!1);I.addLocalFileAsync({localPath:J,zipPath:Ee.dirname(b(J)),zipName:D(J)},Z)}},E))})})},addLocalFolderPromise:function(_,E){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},E),(T,O)=>{T&&A(T),O&&I(this)})})},addFile:function(_,E,I,A){_=h(_);let T=x(_),O=T!=null;O||(T=new Zg(i),T.entryName=_),T.comment=I||"";let b=typeof A=="object"&&A instanceof o.fs.Stats;b&&(T.header.time=A.mtime);var D=T.isDirectory?16:0;let L=T.isDirectory?16384:32768;return b?L|=4095&A.mode:typeof A=="number"?L|=4095&A:L|=T.isDirectory?493:420,D=(D|L<<16)>>>0,T.attr=D,T.setData(E),O||c.setEntry(T),T},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,E,I,A,T,O){A=On(!1,A),T=On(!1,T),I=On(!0,I),O=Iu(T,O);var b=x(_);if(!b)throw ve.Errors.NO_ENTRY();var D=l(b.entryName),L=u(E,O&&!b.isDirectory?O:I?D:Ee.basename(D));if(b.isDirectory){var G=c.getEntryChildren(b);return G.forEach(function(J){if(J.isDirectory)return;var ie=J.getData();if(!ie)throw ve.Errors.CANT_EXTRACT_FILE();var Q=l(J.entryName),ce=u(E,I?Q:Ee.basename(Q));let de=T?J.header.fileAttr:void 0;o.writeFileTo(ce,ie,A,de)}),!0}var U=b.getData(c.password);if(!U)throw ve.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(L)&&!A)throw ve.Errors.CANT_OVERRIDE();let Z=T?_.header.fileAttr:void 0;return o.writeFileTo(L,U,A,Z),!0},test:function(_){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var I=c.entries[E].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,E,I,A){if(I=On(!1,I),A=Iu(I,A),E=On(!1,E),!c)throw ve.Errors.NO_ZIP();c.entries.forEach(function(T){var O=u(_,l(T.entryName));if(T.isDirectory){o.makeDir(O);return}var b=T.getData(A);if(!b)throw ve.Errors.CANT_EXTRACT_FILE();let D=I?T.header.fileAttr:void 0;o.writeFileTo(O,b,E,D);try{o.fs.utimesSync(O,T.header.time,T.header.time)}catch{throw ve.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,E,I,A){if(A=Xg(E,I,A),I=On(!1,I),E=On(!1,E),!A)return new Promise((L,G)=>{this.extractAllToAsync(_,E,I,function(U){U?G(U):L(this)})});if(!c){A(ve.Errors.NO_ZIP());return}_=Ee.resolve(_);let T=L=>u(_,Ee.normalize(l(L.entryName))),O=(L,G)=>new Error(L+': "'+G+'"'),b=[],D=[];c.entries.forEach(L=>{L.isDirectory?b.push(L):D.push(L)});for(let L of b){let G=T(L),U=I?L.header.fileAttr:void 0;try{o.makeDir(G),U&&o.fs.chmodSync(G,U),o.fs.utimesSync(G,L.header.time,L.header.time)}catch{A(O("Unable to create folder",G))}}D.reverse().reduce(function(L,G){return function(U){if(U)L(U);else{let Z=Ee.normalize(l(G.entryName)),J=u(_,Z);G.getDataAsync(function(ie,Q){if(Q)L(Q);else if(!ie)L(ve.Errors.CANT_EXTRACT_FILE());else{let ce=I?G.header.fileAttr:void 0;o.writeFileToAsync(J,ie,E,ce,function(de){de||L(O("Unable to write file",J)),o.fs.utimes(J,G.header.time,G.header.time,function(P){P?L(O("Unable to set times",J)):L()})})}})}}},A)()},writeZip:function(_,E){if(arguments.length===1&&typeof _=="function"&&(E=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof E=="function"&&E(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,E){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},E);return new Promise((T,O)=>{!_&&i.filename&&(_=i.filename),_||O("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let D=L=>L?T(L):O("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,b,I,A,D)},O)})},toBufferPromise:function(){return new Promise((_,E)=>{c.toAsyncBuffer(_,E)})},toBuffer:function(_,E,I,A){return typeof _=="function"?(c.toAsyncBuffer(_,E,I,A),null):c.compressToBuffer()}}}});import{execFile as sy,spawn as oy,spawnSync as hk}from"node:child_process";import{promisify as ay}from"node:util";function dy(t){if(process.platform!=="win32")return!1;if($f.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace($f,"").toLowerCase();return cy.has(n)}function Vf(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return dy(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function at(t,e=[],n={}){return oy(t,e,Vf(t,n))}function Jf(t,e=[],n={}){return ly(t,e,Vf(t,n))}var cy,$f,ly,Xt=it(()=>{"use strict";cy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),$f=/\.(cmd|bat|ps1)$/i;ly=ay(sy)});var en=le((bC,jh)=>{"use strict";var Hh=["nodebuffer","arraybuffer","fragments"],qh=typeof Blob<"u";qh&&Hh.push("blob");jh.exports={BINARY_TYPES:Hh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:qh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ts=le((EC,Ho)=>{"use strict";var{EMPTY_BUFFER:tv}=en(),kd=Buffer[Symbol.species];function nv(t,e){if(t.length===0)return tv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let c=t[o];n.set(c,i),i+=c.length}return i<e?new kd(n.buffer,n.byteOffset,i):n}function Kh(t,e,n,i,o){for(let c=0;c<o;c++)n[i+c]=t[c]^e[c&3]}function Wh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function rv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Td(t){if(Td.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new kd(t):ArrayBuffer.isView(t)?e=new kd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Td.readOnly=!1),e}Ho.exports={concat:nv,mask:Kh,toArrayBuffer:rv,toBuffer:Td,unmask:Wh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");Ho.exports.mask=function(e,n,i,o,c){c<48?Kh(e,n,i,o,c):t.mask(e,n,i,o,c)},Ho.exports.unmask=function(e,n){e.length<32?Wh(e,n):t.unmask(e,n)}}catch{}});var Jh=le((vC,Vh)=>{"use strict";var $h=Symbol("kDone"),Rd=Symbol("kRun"),Pd=class{constructor(e){this[$h]=()=>{this.pending--,this[Rd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Rd]()}[Rd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$h])}}};Vh.exports=Pd});var qr=le((SC,Qh)=>{"use strict";var ns=xe("zlib"),Zh=ts(),iv=Jh(),{kStatusCode:Yh}=en(),sv=Buffer[Symbol.species],ov=Buffer.from([0,0,255,255]),jo=Symbol("permessage-deflate"),tn=Symbol("total-length"),Gr=Symbol("callback"),Tn=Symbol("buffers"),Hr=Symbol("error"),qo,Cd=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,!qo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;qo=new iv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Gr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let o=n[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=o})}),e}decompress(e,n,i){qo.add(o=>{this._decompress(e,n,(c,l)=>{o(),i(c,l)})})}compress(e,n,i){qo.add(o=>{this._compress(e,n,(c,l)=>{o(),i(c,l)})})}_decompress(e,n,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?ns.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=ns.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[jo]=this,this._inflate[tn]=0,this._inflate[Tn]=[],this._inflate.on("error",cv),this._inflate.on("data",Xh)}this._inflate[Gr]=i,this._inflate.write(e),n&&this._inflate.write(ov),this._inflate.flush(()=>{let c=this._inflate[Hr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=Zh.concat(this._inflate[Tn],this._inflate[tn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[tn]=0,this._inflate[Tn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,l)})}_compress(e,n,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?ns.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=ns.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[tn]=0,this._deflate[Tn]=[],this._deflate.on("data",av)}this._deflate[Gr]=i,this._deflate.write(e),this._deflate.flush(ns.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Zh.concat(this._deflate[Tn],this._deflate[tn]);n&&(c=new sv(c.buffer,c.byteOffset,c.length-4)),this._deflate[Gr]=null,this._deflate[tn]=0,this._deflate[Tn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Qh.exports=Cd;function av(t){this[Tn].push(t),this[tn]+=t.length}function Xh(t){if(this[tn]+=t.length,this[jo]._maxPayload<1||this[tn]<=this[jo]._maxPayload){this[Tn].push(t);return}this[Hr]=new RangeError("Max payload size exceeded"),this[Hr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Hr][Yh]=1009,this.removeListener("data",Xh),this.reset()}function cv(t){if(this[jo]._inflate=null,this[Hr]){this[Gr](this[Hr]);return}t[Yh]=1007,this[Gr](t)}});var jr=le((IC,Ko)=>{"use strict";var{isUtf8:ex}=xe("buffer"),{hasBlob:dv}=en(),lv=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function uv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Dd(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function fv(t){return dv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ko.exports={isBlob:fv,isValidStatusCode:uv,isValidUTF8:Dd,tokenChars:lv};if(ex)Ko.exports.isValidUTF8=function(t){return t.length<24?Dd(t):ex(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");Ko.exports.isValidUTF8=function(e){return e.length<32?Dd(e):t(e)}}catch{}});var Bd=le((AC,ax)=>{"use strict";var{Writable:hv}=xe("stream"),tx=qr(),{BINARY_TYPES:xv,EMPTY_BUFFER:nx,kStatusCode:pv,kWebSocket:mv}=en(),{concat:Od,toArrayBuffer:gv,unmask:wv}=ts(),{isValidStatusCode:_v,isValidUTF8:rx}=jr(),Wo=Buffer[Symbol.species],wt=0,ix=1,sx=2,ox=3,Ld=4,Nd=5,$o=6,Md=class extends hv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||xv[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[mv]=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=wt}_write(e,n,i){if(this._opcode===8&&this._state==wt)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 Wo(i.buffer,i.byteOffset+e,i.length-e),new Wo(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=n.length-e;e>=i.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new Wo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case wt:this.getInfo(e);break;case ix:this.getPayloadLength16(e);break;case sx:this.getPayloadLength64(e);break;case ox:this.getMask();break;case Ld:this.getData(e);break;case Nd:case $o:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(n[0]&64)===64;if(i&&!this._extensions[tx.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=ix:this._payloadLength===127?this._state=sx:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=ox:this._state=Ld}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ld}getData(e){let n=nx;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&wv(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Nd,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[tx.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return n(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(l);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let l=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(l);return}this._fragments.push(c)}this.dataMessage(n),this._state===wt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=wt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Od(i,n):this._binaryType==="arraybuffer"?o=gv(Od(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=wt):(this._state=$o,setImmediate(()=>{this.emit("message",o,!0),this._state=wt,this.startLoop(e)}))}else{let o=Od(i,n);if(!this._skipUTF8Validation&&!rx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Nd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=wt):(this._state=$o,setImmediate(()=>{this.emit("message",o,!1),this._state=wt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,nx),this.end();else{let i=e.readUInt16BE(0);if(!_v(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(c);return}let o=new Wo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!rx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=wt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=wt):(this._state=$o,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=wt,this.startLoop(n)}))}createError(e,n,i,o,c){this._loop=!1,this._errored=!0;let l=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(l,this.createError),l.code=c,l[pv]=o,l}};ax.exports=Md});var Ud=le((TC,lx)=>{"use strict";var{Duplex:kC}=xe("stream"),{randomFillSync:yv}=xe("crypto"),{types:{isUint8Array:bv}}=xe("util"),cx=qr(),{EMPTY_BUFFER:Ev,kWebSocket:vv,NOOP:Sv}=en(),{isBlob:Kr,isValidStatusCode:Iv}=jr(),{mask:dx,toBuffer:Yn}=ts(),_t=Symbol("kByteLength"),Av=Buffer.alloc(4),Vo=8*1024,Xn,Wr=Vo,Tt=0,kv=1,Tv=2,Fd=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Tt,this.onerror=Sv,this[vv]=void 0}static frame(e,n){let i,o=!1,c=2,l=!1;n.mask&&(i=n.maskBuffer||Av,n.generateMask?n.generateMask(i):(Wr===Vo&&(Xn===void 0&&(Xn=Buffer.alloc(Vo)),yv(Xn,0,Vo),Wr=0),i[0]=Xn[Wr++],i[1]=Xn[Wr++],i[2]=Xn[Wr++],i[3]=Xn[Wr++]),l=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!n.mask||l)&&n[_t]!==void 0?u=n[_t]:(e=Buffer.from(e),u=e.length):(u=e.length,o=n.mask&&n.readOnly&&!l);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]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],l?[x,e]:o?(dx(e,i,x,c,u),[x]):(dx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,o){let c;if(e===void 0)c=Ev;else{if(typeof e!="number"||!Iv(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");if(c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof n=="string")c.write(n,2);else if(bv(n))c.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let l={[_t]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Tt?this.enqueue([this.dispatch,c,!1,l,o]):this.sendFrame(t.frame(c,l),o)}ping(e,n,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Kr(e)?(o=e.size,c=!1):(e=Yn(e),o=e.length,c=Yn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[_t]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Kr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==Tt?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}pong(e,n,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Kr(e)?(o=e.size,c=!1):(e=Yn(e),o=e.length,c=Yn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[_t]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Kr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==Tt?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,n,i){let o=this._extensions[cx.extensionName],c=n.binary?2:1,l=n.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):Kr(e)?(u=e.size,h=!1):(e=Yn(e),u=e.length,h=Yn.readOnly),this._firstFragment?(this._firstFragment=!1,l&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=u>=o._threshold),this._compress=l):(l=!1,c=0),n.fin&&(this._firstFragment=!0);let x={[_t]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:l};Kr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Tt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[_t],this._state=Tv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(zd,this,u,o);return}this._bufferedBytes-=i[_t];let l=Yn(c);n?this.dispatch(l,n,i,o):(this._state=Tt,this.sendFrame(t.frame(l,i),o),this.dequeue())}).catch(c=>{process.nextTick(Rv,this,c,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[cx.extensionName];this._bufferedBytes+=i[_t],this._state=kv,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");zd(this,h,o);return}this._bufferedBytes-=i[_t],this._state=Tt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===Tt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][_t],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][_t],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};lx.exports=Fd;function zd(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],c=o[o.length-1];typeof c=="function"&&c(e)}}function Rv(t,e,n){zd(t,e,n),t.onerror(e)}});var yx=le((RC,_x)=>{"use strict";var{kForOnEventAttribute:rs,kListener:Gd}=en(),ux=Symbol("kCode"),fx=Symbol("kData"),hx=Symbol("kError"),xx=Symbol("kMessage"),px=Symbol("kReason"),$r=Symbol("kTarget"),mx=Symbol("kType"),gx=Symbol("kWasClean"),nn=class{constructor(e){this[$r]=null,this[mx]=e}get target(){return this[$r]}get type(){return this[mx]}};Object.defineProperty(nn.prototype,"target",{enumerable:!0});Object.defineProperty(nn.prototype,"type",{enumerable:!0});var Qn=class extends nn{constructor(e,n={}){super(e),this[ux]=n.code===void 0?0:n.code,this[px]=n.reason===void 0?"":n.reason,this[gx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[ux]}get reason(){return this[px]}get wasClean(){return this[gx]}};Object.defineProperty(Qn.prototype,"code",{enumerable:!0});Object.defineProperty(Qn.prototype,"reason",{enumerable:!0});Object.defineProperty(Qn.prototype,"wasClean",{enumerable:!0});var Vr=class extends nn{constructor(e,n={}){super(e),this[hx]=n.error===void 0?null:n.error,this[xx]=n.message===void 0?"":n.message}get error(){return this[hx]}get message(){return this[xx]}};Object.defineProperty(Vr.prototype,"error",{enumerable:!0});Object.defineProperty(Vr.prototype,"message",{enumerable:!0});var is=class extends nn{constructor(e,n={}){super(e),this[fx]=n.data===void 0?null:n.data}get data(){return this[fx]}};Object.defineProperty(is.prototype,"data",{enumerable:!0});var Pv={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[rs]&&o[Gd]===e&&!o[rs])return;let i;if(t==="message")i=function(c,l){let u=new is("message",{data:l?c:c.toString()});u[$r]=this,Jo(e,this,u)};else if(t==="close")i=function(c,l){let u=new Qn("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[$r]=this,Jo(e,this,u)};else if(t==="error")i=function(c){let l=new Vr("error",{error:c,message:c.message});l[$r]=this,Jo(e,this,l)};else if(t==="open")i=function(){let c=new nn("open");c[$r]=this,Jo(e,this,c)};else return;i[rs]=!!n[rs],i[Gd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Gd]===e&&!n[rs]){this.removeListener(t,n);break}}};_x.exports={CloseEvent:Qn,ErrorEvent:Vr,Event:nn,EventTarget:Pv,MessageEvent:is};function Jo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Zo=le((PC,bx)=>{"use strict";var{tokenChars:ss}=jr();function zt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Cv(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,c=!1,l,u,h=-1,x=-1,m=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),l===void 0)if(m===-1&&ss[x]===1)h===-1&&(h=w);else if(w!==0&&(x===32||x===9))m===-1&&h!==-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let _=t.slice(h,m);x===44?(zt(e,_,n),n=Object.create(null)):l=_,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(m===-1&&ss[x]===1)h===-1&&(h=w);else if(x===32||x===9)m===-1&&h!==-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w),zt(n,t.slice(h,m),!0),x===44&&(zt(e,l,n),n=Object.create(null),l=void 0),h=m=-1}else if(x===61&&h!==-1&&m===-1)u=t.slice(h,w),h=m=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(ss[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);h===-1?h=w:i||(i=!0),o=!1}else if(c)if(ss[x]===1)h===-1&&(h=w);else if(x===34&&h!==-1)c=!1,m=w;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)c=!0;else if(m===-1&&ss[x]===1)h===-1&&(h=w);else if(h!==-1&&(x===32||x===9))m===-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let _=t.slice(h,m);i&&(_=_.replace(/\\/g,""),i=!1),zt(n,u,_),x===44&&(zt(e,l,n),n=Object.create(null),l=void 0),u=void 0,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=w);let v=t.slice(h,m);return l===void 0?zt(e,v,n):(u===void 0?zt(n,v,!0):i?zt(n,u,v.replace(/\\/g,"")):zt(n,u,v),zt(e,l,n)),e}function Dv(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(l=>l===!0?o:`${o}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bx.exports={format:Dv,parse:Cv}});var ea=le((OC,Ox)=>{"use strict";var Ov=xe("events"),Lv=xe("https"),Nv=xe("http"),Sx=xe("net"),Mv=xe("tls"),{randomBytes:Bv,createHash:Fv}=xe("crypto"),{Duplex:CC,Readable:DC}=xe("stream"),{URL:Hd}=xe("url"),Rn=qr(),zv=Bd(),Uv=Ud(),{isBlob:Gv}=jr(),{BINARY_TYPES:Ex,CLOSE_TIMEOUT:Hv,EMPTY_BUFFER:Yo,GUID:qv,kForOnEventAttribute:qd,kListener:jv,kStatusCode:Kv,kWebSocket:We,NOOP:Ix}=en(),{EventTarget:{addEventListener:Wv,removeEventListener:$v}}=yx(),{format:Vv,parse:Jv}=Zo(),{toBuffer:Zv}=ts(),Ax=Symbol("kAborted"),jd=[8,13],rn=["CONNECTING","OPEN","CLOSING","CLOSED"],Yv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_e=class t extends Ov{constructor(e,n,i){super(),this._binaryType=Ex[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Yo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),kx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ex.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let o=new zv({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 Uv(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",eS),o.on("drain",tS),o.on("error",nS),o.on("message",rS),o.on("ping",iS),o.on("pong",sS),c.onerror=oS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Px),e.on("data",Qo),e.on("end",Cx),e.on("error",Dx),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Rn.extensionName]&&this._extensions[Rn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ut(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Rx(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Kd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Yo,n,i)}pong(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Kd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Yo,n,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Kd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Rn.extensionName]||(o.compress=!1),this._sender.send(e||Yo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ut(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:rn.indexOf("CONNECTING")});Object.defineProperty(_e.prototype,"CONNECTING",{enumerable:!0,value:rn.indexOf("CONNECTING")});Object.defineProperty(_e,"OPEN",{enumerable:!0,value:rn.indexOf("OPEN")});Object.defineProperty(_e.prototype,"OPEN",{enumerable:!0,value:rn.indexOf("OPEN")});Object.defineProperty(_e,"CLOSING",{enumerable:!0,value:rn.indexOf("CLOSING")});Object.defineProperty(_e.prototype,"CLOSING",{enumerable:!0,value:rn.indexOf("CLOSING")});Object.defineProperty(_e,"CLOSED",{enumerable:!0,value:rn.indexOf("CLOSED")});Object.defineProperty(_e.prototype,"CLOSED",{enumerable:!0,value:rn.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[qd])return e[jv];return null},set(e){for(let n of this.listeners(t))if(n[qd]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[qd]:!0})}})});_e.prototype.addEventListener=Wv;_e.prototype.removeEventListener=$v;Ox.exports=_e;function kx(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Hv,protocolVersion:jd[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,!jd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${jd.join(", ")})`);let c;if(e instanceof Hd)c=e;else try{c=new Hd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let l=c.protocol==="wss:",u=c.protocol==="ws+unix:",h;if(c.protocol!=="ws:"&&!l&&!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;Xo(t,I);return}let x=l?443:80,m=Bv(16).toString("base64"),w=l?Lv.request:Nv.request,v=new Set,_;if(o.createConnection=o.createConnection||(l?Qv:Xv),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&&(_=new Rn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Vv({[Rn.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!Yv.test(I)||v.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(I)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=l,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,T]of Object.entries(I))i.headers[A.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!l)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=w(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=w(o);o.timeout&&E.on("timeout",()=>{ut(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[Ax]||(E=t._req=null,Xo(t,I))}),E.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){ut(t,E,"Maximum redirects exceeded");return}E.abort();let O;try{O=new Hd(A,e)}catch{let D=new SyntaxError(`Invalid URL: ${A}`);Xo(t,D);return}kx(t,O,n,i)}else t.emit("unexpected-response",E,I)||ut(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==_e.CONNECTING)return;E=t._req=null;let O=I.headers.upgrade;if(O===void 0||O.toLowerCase()!=="websocket"){ut(t,A,"Invalid Upgrade header");return}let b=Fv("sha1").update(m+qv).digest("base64");if(I.headers["sec-websocket-accept"]!==b){ut(t,A,"Invalid Sec-WebSocket-Accept header");return}let D=I.headers["sec-websocket-protocol"],L;if(D!==void 0?v.size?v.has(D)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":v.size&&(L="Server sent no subprotocol"),L){ut(t,A,L);return}D&&(t._protocol=D);let G=I.headers["sec-websocket-extensions"];if(G!==void 0){if(!_){ut(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Jv(G)}catch{ut(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Z=Object.keys(U);if(Z.length!==1||Z[0]!==Rn.extensionName){ut(t,A,"Server indicated an extension that was not requested");return}try{_.accept(U[Rn.extensionName])}catch{ut(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Rn.extensionName]=_}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,t):E.end()}function Xo(t,e){t._readyState=_e.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Xv(t){return t.path=t.socketPath,Sx.connect(t)}function Qv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Sx.isIP(t.host)?"":t.host),Mv.connect(t)}function ut(t,e,n){t._readyState=_e.CLOSING;let i=new Error(n);Error.captureStackTrace(i,ut),e.setHeader?(e[Ax]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Kd(t,e,n){if(e){let i=Gv(e)?e.size:Zv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${rn[t.readyState]})`);process.nextTick(n,i)}}function eS(t,e){let n=this[We];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[We]!==void 0&&(n._socket.removeListener("data",Qo),process.nextTick(Tx,n._socket),t===1005?n.close():n.close(t,e))}function tS(){let t=this[We];t.isPaused||t._socket.resume()}function nS(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",Qo),process.nextTick(Tx,e._socket),e.close(t[Kv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function vx(){this[We].emitClose()}function rS(t,e){this[We].emit("message",t,e)}function iS(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,Ix),e.emit("ping",t)}function sS(t){this[We].emit("pong",t)}function Tx(t){t.resume()}function oS(t){let e=this[We];e.readyState!==_e.CLOSED&&(e.readyState===_e.OPEN&&(e._readyState=_e.CLOSING,Rx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Rx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Px(){let t=this[We];if(this.removeListener("close",Px),this.removeListener("data",Qo),this.removeListener("end",Cx),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[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",vx),t._receiver.on("finish",vx))}function Qo(t){this[We]._receiver.write(t)||this.pause()}function Cx(){let t=this[We];t._readyState=_e.CLOSING,t._receiver.end(),this.end()}function Dx(){let t=this[We];this.removeListener("error",Dx),this.on("error",Ix),t&&(t._readyState=_e.CLOSING,this.destroy())}});var Bx=le((NC,Mx)=>{"use strict";var LC=ea(),{Duplex:aS}=xe("stream");function Lx(t){t.emit("close")}function cS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Nx(t){this.removeListener("error",Nx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function dS(t,e){let n=!0,i=new aS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,l){let u=!l&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(n=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(Lx,i);return}let l=!1;t.once("error",function(h){l=!0,c(h)}),t.once("close",function(){l||c(o),process.nextTick(Lx,i)}),n&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,l){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,l)});return}t.send(o,l)},i.on("end",cS),i.on("error",Nx),i}Mx.exports=dS});var Wd=le((MC,Fx)=>{"use strict";var{tokenChars:lS}=jr();function uS(t){let e=new Set,n=-1,i=-1,o=0;for(o;o<t.length;o++){let l=t.charCodeAt(o);if(i===-1&&lS[l]===1)n===-1&&(n=o);else if(o!==0&&(l===32||l===9))i===-1&&n!==-1&&(i=o);else if(l===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(n,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}Fx.exports={parse:uS}});var Kx=le((FC,jx)=>{"use strict";var fS=xe("events"),ta=xe("http"),{Duplex:BC}=xe("stream"),{createHash:hS}=xe("crypto"),zx=Zo(),er=qr(),xS=Wd(),pS=ea(),{CLOSE_TIMEOUT:mS,GUID:gS,kWebSocket:wS}=en(),_S=/^[+/0-9A-Za-z]{22}==$/,Ux=0,Gx=1,qx=2,$d=class extends fS{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:mS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:pS,...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=ta.createServer((i,o)=>{let c=ta.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=yS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,l)=>{this.handleUpgrade(o,c,l,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ux}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===qx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(os,this);return}if(e&&this.once("close",e),this._state!==Gx)if(this._state=Gx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(os,this):process.nextTick(os,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{os(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,o){n.on("error",Hx);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,n,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){tr(this,e,n,400,"Invalid Upgrade header");return}if(c===void 0||!_S.test(c)){tr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){tr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){as(n,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=xS.parse(h)}catch{tr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&m!==void 0){let v=new er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=zx.parse(m);_[er.extensionName]&&(v.accept(_[er.extensionName]),w[er.extensionName]=v)}catch{tr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(_,E,I,A)=>{if(!_)return as(n,E||401,I,A);this.completeUpgrade(w,c,x,e,n,i,o)});return}if(!this.options.verifyClient(v))return as(n,401)}this.completeUpgrade(w,c,x,e,n,i,o)}completeUpgrade(e,n,i,o,c,l,u){if(!c.readable||!c.writable)return c.destroy();if(c[wS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ux)return as(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hS("sha1").update(n+gS).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),m._protocol=w)}if(e[er.extensionName]){let w=e[er.extensionName].params,v=zx.format({[er.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${v}`),m._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",Uh),m.setSocket(c,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(is,this)})),u(m,o)}};Gh.exports=qd;function b1(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 is(t){t._state=Hh,t.emit("close")}function Uh(){this.destroy()}function ss(t,e,r,i){r=r||Xo.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} ${Xo.STATUS_CODES[e]}\r
16
+ `)),c.removeListener("error",Hx),m.setSocket(c,l,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(os,this)})),u(m,o)}};jx.exports=$d;function yS(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function os(t){t._state=qx,t.emit("close")}function Hx(){this.destroy()}function as(t,e,n,i){n=n||ta.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${ta.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 tr(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,tr),t.emit("wsClientError",d,r,e)}else ss(r,i,o,c)}});var np=de(Be=>{"use strict";var M=F;function ta(){let t=["BxnN","Dg9mB3DLCKm","txHRy2e","u3DnCLy","DKLluKS","C3vqyui","ExnLAem","EfvHtwK","zxjYtM8","C3bZteO","y3jLyxrLtwu","D24GCMvHC28","tK9lq0m","ChjVDg90Exa","zxmGCMvHy2G","BNrLCG","vw5PBxbSzw0","zgvMAw5Luhi","rgjzsum","AMTJDKC","x2nSzwfYvgK","ChbL","Bgj5Eue","DxrMofDYAxq","rNjyEfe","DMfSDwu","wxPIEM8","Afz5CuK","EufQvw4","C2vetNq","z0TLzM0","Ahnyu0S","sgP1u2q","x3DHAxq","zw13yKi","Cg9PBNrbBMq","x21PBMLoyxy","tvrWy2i","C2v0zgi","ENv5EKi","vK9xrwC","u3fmy1y","AefJA01LC3m","BeHdALG","rwHmDM8","qw1VDw50","BhrPCgXLihq","sM1YtKy","zNrTA3G","EfvZzuvUDG","rKjXwvq","zxj2AwnL","uNjHD20","DxH4s3K","AKf1Awq","yw9rtu8","tNncALK","DMvYC2LVBMm","BMnKD3i","wu5Zz0O","ywnOzwq","Dxfku1e","AxnbCNjHEq","uLjLvxC","ig1LC3nHz2u","DhjPzxmGCMu","AxnszwfKEq","ExP3C2q","zvvYBa","x2LZsw5PDa","q1P6Eva","q0vAz3y","uMzgtwu","EvngwvK","BxzXzfK","Bw9iyKy","C0jf","B2fJzKe","rKDUyMm","y29Uy2f0","BLfiuvK","DMXOCwq","B3jpBMXPBMu","Dg9cExrLC0i","qwj2tum","rNvQu1a","zeH6AeC","uhnfz1q","r2jjCwm","uxDbq1O","BvLqtKW","BfLZruy","sM9QAfC","uML6v1O","DLf0zM8","B25ozxr3B3i","tLfYuha","x2LZqNjVD3m","qKHLseq","yLf3wwq","Cg9PBNrdB24","whLtDvy","ufr1wwG","t2PrtMu","x2jPBMfYEvq","EwfvrwO","Bg9Nsurhzw4","DgHLBG","vg55D3G","CYbHBhjLywq","DfzhELO","x2LZtwLUAvC","Dw50","A0rnEwG","AvfStvi","Cgf5Bg9Hza","zgjUENK","se9LqMK","EwXRsxa","y29UBMvJDfm","B2zMBgLUzq","qNvYEfm","Eunsy3e","Cgf5Bg9Hzfq","yuLYBhy","DgHHBIbSB2m","BNruCMLLC0m","x2LZv29YA2u","z2vjBMzVu3K","BMv4DcGPigm","Cfr3qxm","x3DZ","rLHZvve","C3zzrg0","CgPyAgK","uu93EhK","r1jjwe8","EMrpAw8","DK5TrxC","C2vYDMLJzs0","ywXSB2nvBNm","Ahv3u0O","BM9Uzv9UB24","y3nTB2i","tMfTzq","BML0AwfSAxO","u2nrtK8","zM9YrwfJAa","wNPHsvy","CIb0DhDjra","v0H2BwG","AeLyt2i","C2rcDhm","sNbKDu8","zvD0AwG","z2zgsfO","BLHUtuq","vMLvy0m","s2vLu0O","DKzgrg0","r1DNq3m","CxPOswu","v01otKq","AvbwsuW","ww1WELq","zcbLCNjVCI4","qNjPzgDL","CgLUz09Uy2u","CfDyswS","zgjjsNG","A3DvDhq","tMjHAuy","r0n0tvG","q3vZDg9Trxi","CK1MugS","Bg9N","r2r4DxG","quXfs1C","zgvIDwC","u3PWCwm","AgLNAa","zeLgywG","rg9XueK","u2vYDMLJzvC","n3W0Fdb8nG","AevYCM9Yrxy","qMnOreK","C2v0y3vYC28","yw5kwu4","t2zxBhq","DvLrq3C","vu5cr1u","EuXIAgK","AxmGDw5Kzwy","vejNs2K","vNrcru8","yNbeu0W","B3jRig9MzMW","uKnfC3e","DMPosgi","tKjMrfO","DMLduhi","C0LouxC","yMLUyxj5vhK","q09oveLovuu","Ce5IAha","EKjgyNe","x3bYzwzPEa","zfbVrxi","ze5VzhO","s0XhC0m","CMvHzfvjBNq","EwvrExq","B25dBg9Zzq","q1bdvKK","zxf1ywXZ","EgXvyMS","tef5sgS","y2XVC2uSihC","EMDrC20","x3bHDgHlzxK","DMvYC2LVBG","yLzmzvC","r0HlwgS","zxjHDg9Y","CLreyxm","BwvKAwf0zwW","zw96uw8","CeD3zLG","Axnby2TdBgu","AvnMs0W","yw5kEei","y2zvzMe","CNnVCL9Uyw0","x2rLyNvN","Cw1gBNa","BfLvv2G","Dgz5ALO","t1bjyxq","q1Dut3y","uNnAsvC","r0jHs2i","DLnArK8","zgvJB2rLzey","vvfZyM4","DNzQwhy","B3P3uu8","ChjVy2vZCW","EMnzvgW","CgLUz1rPBwu","t2XOsNC","sKnlC1i","x2rItMfTzq","ruf0EKC","AM9PBG","sNfWzeu","x2HHBMrSzu8","wNL6u2S","AwX2B0q","yw1LoIa","yxnZAwDU","C1nzCuS","we1IBgq","t3bLBKv2zw4","uvrKzeG","nxWWFdn8mxW","ywjVCNq","whvIthC","y2HLy2Tszwe","tgr5rui","ywzL","y2rqB2m","Ew5JswO","CM92AwrLihy","DhPXuNO","AgvHzgvYCW","tgzKrvi","yMfvzKW","DcbVzIbYyw4","q0jgtwm","ALnYvKC","t0z2vvm","y29Kzq","BgLTAxq","y1fXzxO","x2n1CNnVCK0","tMj3zvq","BMv3vMvYC2K","Dxrjza","rK9yuKq","CMvQzwn0","tgX0CfK","C2DPza","EvjLy29UBMu","Aw1LCYbPBIa","teDIug8","ywDLu2HVDW","v2PbwLK","CNzJqLy","t2nlDeS","u0fRBxC","DhjQrMu","EfDVEe4","zLLpzwO","DLL4u0K","nhWXFdn8mNW","D2vI","sfzLrxG","yxGGCMv0CMK","x2LUAxrhBg8","x25HDMLNyxq","CNLrqMO","refNrwu","B2LUDfjLywm","y2HnyxHdB3u","weH4wfy","q29Kzq","zwnVBM5Ly3q","EwTPs3C","BfrUueO","zg5hzKS","m3WWFdf8nxW","rMfACMW","oda0mdqXDvj1u2Hw","ihzHBgLKihm","AwXLtMfTzq","AwX5B0y","AwDHDg9Yt24","CK5UreC","CMvZB2X2zq","CMvWBgfJzq","y2XVC2u","qvv5Eha","uejhBwK","u3rTtxm","C2v0","y3zsANm","y0H4Cvu","z0rtugm","BNv0tfK","r29hzxi","CgLKEMu","yufWz0y","wK9kreK","x2LZtwLUAvq","BwvZC2fNztO","zMXAD3m","C3rYAw5N","CMvZzxrfBMq","AM5qEgm","zMLArK0","x29UugfNzu4","x2DLDeLUDgu","BeXrDMu","EhrMAKK","EvPxwe8","x29UtwvZC2e","DxbKyxrLq3u","ugnzC0W","EM9Ls28","DhjrDgC","B25szwnLAxy","D0HLBwS","q0Xpu0ve","vNzKDeO","vu9uBee","vvDjq0q","wMHmAwi","nhWXFdv8mNW","AeHQr0e","DgrkChC","BLLWC1q","B3bLBIa","BNPvDMK","vKTQBhC","tLj3Dg4","r01KELe","B25Uzwn0Aw4","EeXzt1m","zgnQwNq","yMLUyxj5","BwvZC2fNzv8","icSG","BMvY","uu1Sugq","v3vjuwS","A2v0ignVBNm","x2nYzwf0zvm","Aw47y2HHCNm","sMj5txm","uLbmD0q","C2v0q3vYC28","ufvZv1C","zNjVBuHHC2G","y21KzvO","A1HTEvK","ihrVihjLDhi","zMLUza","zw5HyMXLvhi","tfbov0y","EuzsuK8","ChvZAa","wMjksgy","zhfnv24","B25JBg9Zzq","BMrWB2LUDfq","zKT2Aue","rK1Wq0m","x3jLywr5q2W","qLv6ELe","CgLUz0XVC3m","CLDrCve","CvfHBxu","AMnvtva","u3n2sxu","Bvzbvuy","C1rUzvy","r3vxBwm","qNvWvhe","s2DfBvO","Cu1lA3e","wejMsfy","yMLUza","ywX3yxLZ","B3beq0S","rKXRBKW","AvjQuLu","A1bMvhC","uuvkCNq","DgLLCKPtt04","teT3ue8","s010sMe","y3jLyxrLt3a","x2LUAxq","igzPzwXKoIa","qNfYAue","qwvSzNm","B0rUzMS","r2XgA2S","B0rzBeG","rNfmEwq","s2jezg4","AvrIALO","BxnNsuq","uMvJB25Uzwm","CgzMEuS","D0rgv2C","qvvXyKm","y2vZC0HHBMq","zw50","B2veuKi","yMfJA3vWigu","Fdz8m3WXmxW","wNjtA2K","A3PhCha","CMvWBgfJzui","x2LUAxrqCM8","y29UBMvJDeu","CLzHBhvLCW","B1DTy0u","AxnmB25N","u1zcz0G","DgLTzw91DcW","r0fpD0u","Ec1TC2CTy3u","Dg9VigXHCMC","C3vIyxjYyxK","ywnRpwzYB24","zKPxBKm","DePXDuK","C3vIC3rYAw4","BMnVzgLUzW","DMvUDa","C0XPC3rLBMu","v2vIu29JA2u","u0Lxzxi","u3Dttwu","uMLZB0u","yM9L","Auz3Ehi","vfveywS","t1bftG","DhnwENy","uMnLEMi","zunqteG","s1DKsui","yw94rhm","ihbYB3rVy28","ENfwA3O","DxLIDNO","ww1Kuwy","vgvrDxa","zu11CMq","AK9Nu0i","yw5ZzM9YBvq","A2v5","veLID0u","qvjKsue","B25pCgvU","y29TCgXLDgu","BwfW","qLbmwg8","vhjHz3m","Aw9Ul2PZB24","BKHUvfO","zNjVBuj5Dgu","zcWGDw5RBM8","DfLjtMq","vg1hy2O","vu9Tt2W","q1fOAKu","zw5NDgG","x3fVC0rc","BNrbBMrvCgq","CNnVCKzPBgu","AxnAzxjV","CeHlsgK","zKPVDKu","uLryt2W","BLbZvwy","z2jVuMu","CMvUDevUzha","mxWWFdr8m3W","CfbTr3y","z3LYEwW","ywr4Cgm","v3bVBhC","v0HcBg8","CuDkB1u","r25WvfG","DeLK","vu5eA1O","sNnJs2u","rMLADxq","ruTtrgu","CMvZDwX0","rxjYB3jdB2q","z2v0sxrLBq","AevbweO","BKfLufu","v2zOueu","zxjYtxnN","Bhr4Cvq","ywnRx2nVzgu","AfL0Avi","zxjFBxnNAwq","DeHRCuu","s3Lmzvu","wKDwC2m","y09NuKu","x3vYBa","BMrLEa","C2nYAxb0","vLDTC2O","BMnLq2XVC2u","vfnRzfm","Dw5RBM93BIa","x3nLCuLK","zwn0","z2DzCNG","EKHvEMy","CgLUz0LUDgu","vMPRANy","qKTeAKe","zuXQwhi","Dg9tDhjPBMC","sxrMA1a","wxnYrfy","DNDSCuS","z3rjueO","q1bnvMG","A0DvAMK","yw5Nzq","B2nMDKG","t0vLDNK","vgvmyKC","CeHcq28","y29UDgLUDwu","AgfZ","Bfz2DLq","DwPPD1i","DgfYz2v0","t1Hmv1u","CMvHC29U","yMfSrxzLBNq","vgfN","t0r4v20","r25lBgi","Aw50zwDLCIa","B25VCgvU","rxP3sgC","yw1L","A1PMv2m","A2LxvfG","CMvKDwnL","B3v0sLO","vxbKyxrLq28","AwrI","t3zIsgS","v2H1CKe","AgvKtwf4uMu","DhbizwfKzxi","z01cvNa","DMfqEvi","ExbL","vgfTuvG","u2TLzKW","yxrLq291BNq","x2HHBMrSzvi","x3bPBMDqB24","ALrKtw8","sNzzr0i","B3jLtMfTzxm","CKXrC0i","r0XLDvG","tuvtu0fhrv8","C2vYDMLJzq","z0TUEw8","tM9Zs0O","D0HbEe8","y2uGBM90igK","AM9nvue","AxnrB1nnzxm","DxjS","Chfozgu","B0nzAxK","y2j0quS","AKP2BwS","vhHgzeq","zgH4quK","Eg5QsK8","C2XPy2u","CffJExe","r0ryzee","BuTAELi","CxDKBfK","BMrWB2LUDca","ywXPzcb1CMW","DLnfreS","vgLTzw91Da","BMfTzq","y3vYC29Yx2y","zxH0zw5ZAw8","vMLnzwm","ANzoD0G","q2vRrNu","wgP5DMu","EhbyExy","tLvrsMC","CM51q3u","BfbrBxK","CK9is0G","yMfSu2nVCgu","B3Pzy2e","CNnVCL92ywW","y2Xdwhe","r1fZBKe","yxKSig5LDhC","vg5gzuS","EuTvquW","CMvTB3zLrxy","CgfNzwHPzgu","A3Pgs2y","B3nLrxzLBNq","BvPst0W","C2HPzNq","C0XJzuC","CMfTugfYyw0","A2nusLK","CuXRsuu","wfn0vM0","vLvXzKK","ywrK","B3PUzKG","thvzuKy","ywXty29Wzq","vwfYsxa","BwnmtNG","B2nRzxrgywK","zufJAW","v0P4AMK","zxHWB3j0CW","FdD8m3WX","tMvKs0G","zw50zwqGDhK","uLzQDva","zMLSzw5HBwu","u2TPCcbWyxm","C3fqse8","EfnvC3C","B0XKyuq","u2z2Bw8","y29UBMvJDa","B0zLzvy","vKDstee","B2vuCee","x2nSzwfYugK","yNLL","B3zbDhK","t0viuLy","surNtge","uMvHzcbWyxm","z3vvwM8","mJmYwK5rEe53","CK1Qswi","z2v0s2v5","B2XKvMvYC2K","EuvuuwO","zxrxB3jRq2G","Dw15v0C","Cg5ss0O","ruf1rNG","shbkENO","CNfNvKS","C3vJy2vZCW","EM1Sr1a","y3r4","z2v0u3rVCMe","Bwu6ia","DefJrKW","BM93","ywWGy3vYC28","qKnduvy","re1Ps0O","z2LPDgi","r21cs3m","v0L1AwO","EK9Jq0i","B25fCNjVCG","uxvLDwu","l3DZl3yY","rw1js1G","BMvLzf9Hy2S","ELPqvMu","ntyZmM5ntLrPta","BfLpDuK","B25TzxnZywC","x29Ut3bLBG","zNjVBNrPzxi","uKXMu1a","zhv1zhq","qKHJyNq","tNrjC0y","y2Ldy28","tgn2CKy","v3LKreG","Dg9hzw5LCMe","u3vPueS","zMLQrve","C3rHCNq","vLb4weu","ANbbB08","Bg9IywXty28","y2f0y2G","q0XfCxG","v0fowgu","zNzmweW","tu5Nt08","y3jLyxrLq2W","nhWWFdf8mNW","q2rNyu8","vwLJveO","A0TqA2i","EhHfDvq","AxnFywnR","A25Uz0u","Bw5eDuC","yxnL","tg9NsurozxC","Aw5KzxHpzG","ihrYEsbYzwm","wLzZwLu","ntKYzxfHCM9q","ANHvt1y","nZmZndyXD2Dttw1b","BNrfBMrWB2K","vMv2Aeu","EwTLtgO","B3bLCNr5tMe","zxjev2W","BfrPBwvVDxq","BgLZDgvUtMu","ihjLy29UBMu","ELz0Eue","B0nHCeq","y29UBMvJDca","aaaaaaaaaaa","AwjYvhy","C2fNzq","DhvOt3q","Cu93Dee","zLfKDg8","BwfUDwfSihi","vLrdrK0","yNHVrfm","s3nrzvC","vgzfEMi","tNnXEeu","zgjhqve","x19LC01Vzhu","wLHmCwW","D0Dlzfi","zw5fDMvUDa","q1rJvu8","yw5Hz2vY","zhzyuhe","wgXfvKy","qMDVwgi","DxDeyMq","yu9kAgy","twvZC2fNzuu","ChDcC2m","v05WzLK","wwTove0","qxLgue0","CMvJB25Uzwm","tg9Nsuq","y3vYDMfSDwu","BM5Ly3q","C0Xf","Ag1psxK","sLjVvLi","qM13BwG","CMv0CNLdB3u","Ef9MCM9UDgK","DMfuDLy","AxHVvMu","u0DAr0S","AwXK","rNjVBNrPzxi","refRDwe","De9jvwq","x2XPC3rLBMu","DMfS","Devms04","uNH2zhy","D3r3wfK","AgfUz2u","wMLAq3q","yMrFzgLK","qNvrq3m","t3LHwfq","AhLgCui","BgvY","Dev2zw50","rxLrCMW","q0jgzfa","C1H3wu0","CKHUsuu","C3bSAxq","tK5tzvy","ufv1tvO","EM1jDKS","q3vWELm","vgfNvwq","yvnXvKG","qNzRCKm","r2rdy24","Ae9Wzw5fDMu","ihn1y2nLC3m","BwLUAvbYB2C","B3bLCNr5","qujSDvK","z2vY","zMLSDgvY","B25nzxnZywC","v0Pfywi","tgLwq0u","Cgu6ia","y3ruAw1LB3u","v1LRvhi","CuLNwLy","sMHrC0e","BNvTyMvY","Dgv4Dc9Qyxy","sM9LBxe","A3HWA24","tg9KzwO","Auv4rwG","EhP3ExG","u053A0q","CM92AwrLigi","yLDJr2m","vgTZEMG","BwD3B1y","qw9wCw4","y3vYC29Yx24","Bwf4tg9ZC0m","v2LUzg93","CwXSDM8","nhWXFdL8nxW","y2HHCKnVzgu","sfjsCvy","x2DLBMvYyxq","sfnxrgK","yMf0A08","yMH1v08","DxPdEMq","ALrsA1e","Cg9W","DLPwqvy","yKPWAgS","AhHutgm","y3jLyxrLrwW","zMX1C2HfEha","DxLWBxK","EgfOBLy","rgL2C08","uLjpuG","vwHTuK0","x0rctMfTzq","D3jPDgu","z2Ppwuq","Fdj8nxW4Fda","y2HLy2TdDxi","Aw5KzxG","A1n0yxr1C0m","zMXQrg4","zvDhCK0","sNDYreG","y3vYCMvUDeu","zMroDem","ywDLsgLKzq","r3jxu2e","ywrKrxzLBNq","DhjHBNnHy3q","Bun6wfO","zv9ZDwnJzxm","q1PgtNq","x2n1CNnVCKy","t2jjzgK","q3vZDg9Tq2W","ChfisxC","qw1KCxi","zMXVB3i","zNjVBunOyxi","x3jLy29UBMu","y3vYCMvUDeK","BgnwsuO","twLZC2LUzYa","AMXNB0m","uuPhD1C","x29Uq2XVC2u","DfHPufe","AMTyDgi","ywDL","zNjHBwvuExa","EKfdsNC","tu9qt2e","yNn2u08","ywXSzwqGBxu","D01Yyu8","yKzSEfi","s0fNyvu","zenJue4","B1zXBeu","qxDSv2i","zKPtruO","DMLVANa","wvb2yxq","BMXKC3O","x29UrxjYB3i","B25LCNjVCG","qwrIzNq","B3vUDa","rwPpshm","BMzequm","uLfsAuO","uxPXuvC","rLjptLrjrvi","rLDt","A3fcCg8","EKrgBge","CM9YrxzLBNq","CYbWyxjHBxm","Dw5ZAwDUzwq","DKDouNy","D0LTAgy","D2fZq2XLyw4","ihrPBwvVDxq","DgvZDa","zKriD1m","CMfUzg9T","wxjMuxa","veHcsfO","zgv2AwnLx2K","nhWWFdn8mxW","CMvHzhLtDge","sfnwuM8","DMfSDwvZ","t2vfthG","zgnHy1K","AKfhAgm","yw1Lu3bHy2u","id4G","yxrHlcbKyxq","DMDQqvC","CgfNzxnOB3C","B3jgr0i","yNL0zu9MzNm","BvbZtK0","u0Hvrwq","y1Ljvfu","y291BNq","DhjPzxm","AMTtruW","zKz2z3e","z01ZENm","yxv0B21HDgK","zMHArey","wur3t08","C2zpsNC","CNrot1y","C3rLBMvYCW","sfnStu0","yMziqLi","B21jA0O","nxWX","Dgv4Dc9WBge","qNburMm","yxnJCMLWDa","BKTzDuK","zKXyEfG","vLPhBNK","zwDoD0O","tLroEg0","whzzsgC","z0r6rvm","BMCGzMfPBgu","EuDqugu","qvHbsvm","BwLZzq","veLjAem","ELjirKy","DgfIyxnL","wwjeuKO","DhL5A3u","sgfWBwq","r2feEgm","D2jfvM4","B2nRzxq","s01SwK4","zNDZxZeUmc4","t2zhvM4","x2vUzhbVAw4","t1bftL9fuLi","DNv0DuW","q09otKvdveK","Bg9cqxK","vfDHt0O","sxvnELy","qun4ugK","CgLUz19VBMm","DgTwzKi","BwLUzW","tgLZDgvUzxi","t0fwAhO","C3v6Chm","AwDHBuu","mNW0Fdn8mhW","rKjYzvy","sMHVqw8","EKHhyxC","CgfYC2u","zhz3vwW","ign1CNnVCIa","vhDzqxK","A1n0ugW","u0LrsfC","Dhntq04","y2XVC2veqG","zfDVCMTLCKC","r1j4wg0","EKDTAg8","ELjozve","BuzHveK","DeDsCgi","ndeWngTmr2HdEq","t2rnzMq","DwzQqwu","D3HeDxC","D0rHt3a","v1PJsxy","yxv0BW","ugDIz0q","zgf0yq","D0zUuhu","uMvzrxK","CM92AwrLihC","vxf4uLe","CMvHzhDYAxq","zMLN","AwHzqNq","zeXRuNO","BNvpuNm","tM5MtNu","qvDRtxK","C0nVDw50zxi","C2vUDa","BMDLza","Bwv0Ag9K","C1D0q2K","tLHhywy","vwXPthO","wKPoBwe","CMfTzq","BwvZ","tg9JAW","BMvJDa","DhLWzq","r1fSyLK","DvHesK0","B25tDgfYDfi","zw1LBNq","B2zM","C2vUzf9Hy2S","DK9IC1m","Au55z1y","ufLwChq","vw1LsLq","zNvUy3rPB24","DMrHAxK","DMTZsge","wMLKD0S","y3H5sNG","ugXdyK0","De5pv3O","ALDbufy","CgLHANu","rwvYywi","CMvXDwLYzwq","BKfoyuq","tfDmsem","x3bYB3rVy28","ywr2yw5Jzq","Bfzbz3y","tvPWzNO","zNjVBujPDhm","C2nrzva","AxvNv3m","mNW0","otu0nJuYt0T3A2Tf","z1rPBwvVDxq","BgLUzw5V","C3rVCMu","wNfiree","z2v0q3vYCMu","vgjXyK8","tLrUtwm","v1ffDva","zvHitMu","Ae1LC3nHz2u","zMfPuMq","tKfAy24","t1rxwNG","AKnOv0e","sxfWAvq","zxjFywnRx20","wxL3DK8","Aw9MEg0","BwvZC2fNzq","DMfbDKm","reT5z2O","AhDXyw8","uLnyEMm","wNPewKW","C3rVCcbPBw0","zw5JB2rLrNi","AuTizvG","sMPqEw0","wenmEMC","swrduu4","ALLqBwe","x2nVBM5Ly3q","sgjYALC","BefYtvO","AhL4Auq","D2LSBfjLy28","yvfiseK","Bw5lzNa","De1HBMfNzxi","oduYwxDvzuP4","DMLJzuLeig8","rxzLBNq","vwjtu3a","AwP5vK0","qMTWrMC","DLrlEwi","zgvS","zM9Yy2u","qMXNv2S","rxz2reW","q2zltg4","qvnAreu","z2vtEw5J","uLLqAvK","AuX6DfC","rKLmrv9ot1q","zwHKr0G","zu1rAuu","Bw16vKC","Cg93","q29UzMLN","v1Hpq3u","Dg9Y","t1nerNC","sLbNyvq","vePRvxK","zxf6ENu","Aw9UvgLTzw8","vgHgDxe","AwfTC3u","zM1VwMe","B2fK","x2zVCM1HDeu","BxvNs2W","v0ntt2G","BhLkCLe","BLHIrwK","B2fgBgC","ExfLvLy","yuXZD0y","vLzTEMC","x2fKzfDZtgK","zw5KCg9PBNq","tw9KDwXL","thn5Axm","DgLUzYbZzxi","Aw5JBhvKzxm","C3nHz2vfDMu","yNL0zxm","Dg9oDw1Izxi","sKfosMO","uhvYC08","x3jLBw92zvC","CgjICdi","zxjYB3i","A0XTEKW","y3vYC29YlNm","yxbWBhK","twP0uM0","ELb4shi","re1Ku0e","DMDkBKy","wKnhzeK","v1Djrgi","z1rwDwq","y3vYC29Y","r05vy3O","zwDXzgy","EeDwt0K","C29YDa","C0Pcz24","u0nQD20","r0rxuei","y0HvAgK","whLlsuC","sgz3rg8","s2PsCuG","Dg9cExrLC0W","y3jLyxrLuMu","x2rYB3bhBg8","oda4DMrHELjq","uwLwu3K","ywrKq291BNq","wfnLAui","uvPyAgO","wevlqxy","q2DYugC","C1jltLa","ufn4q0K","zNn3uLq","zxjFDhrS","z2v0qwXSs2u","CMnTBKm","CMXhzhm","vgTut2W","BgvUz3rO","x3nLBMrby2S","r29OCeO","CMvZzxrdB3u","CMvJzxzPzwq","y3nTv0K","q0Xpu0LorW","ugLTt0W","yKj2DNu","t0rNtKe","BeHHBMrSzxi","wNP1sve","Bhm6ia","D3blzgu","rvP3r1y","Ahr0Chm6","DcbSAw1PDa","vhvuqKe","AeLmteq","BMDuAw1LCG","zMzmAw5L","AxLSzLq","CMLLC0nVDw4","rK15EKe","ywnRtxnNswq","x2n1CNnVCK4","rvDpu2q","CMXouNq","yKnfA3a","CM92AwrLige","A1vHv2S","EMXzAgq","uK1Awey","A2v5CW","wKnvwgO","rxL3vfq","AuXJwfm","zxH0ugf5Bg8","AwPbBM4","Cgf5Bg9Hzeu","DufwBMq","AuDHy3C","B1nnDwi","ChrVCG","C2fyAeu","sMPrC0m","nhWY","BujoyKq","zw1PDa","zcWG","vNPhyxy","yw10A0y","t3ziBNO","A1jXzxO","DxbNCMfKzw4","zw5JB2rPBMC","AfjAs1u","AgnKy1m","EevbrNe","uw5AA1O","nxWWFdf8m3W","u1jyCLe","x2LUDgvYDMe","CNfuD0e","y2XLyxi","Awfhu2W","vgXprue","ndmZmffKuevbza","DxbkDKW","BNbmruq","s3j3zhi","x3bPBMDmB3m","AM5rBLO","vxzQsKC","AunWwwO","yKLHrKW","CKzND0W","t0fkD3u","AeTNDwq","ExbTDNa","r01IuKi","yLfnCvm","tKrvz0i","C2v0sxrLBq","yNvMuuS","igzHAwWSig0","x2HHBMrSzva","Cw1xzwS","svPwvKG","tfbSzhG","yMXVy2TLza","C3HPwge","tM1LDhG","q0Xbtfi","su5tvefova","BuvtDei","BvnUsfC","sg9MEhC","EuT4r3m","y2vuBKi","EuvMDMq","yxKSihrYEsa","zw5HyMXLuw8","yuLQv0K","zu1qAKm","BLzeANu","rKHTzhK","zwvKzwq","mdaWmdaWmda","qLDmBLm","vfPwvxi","u2XNwg8","lcbxzwjtB2m","t29drfy","B3jRzxjhBg8","v3rUug8","tKfusvzfx0u","zwfitvy","sLnptLa","mhWZ","y3jLyxrLrxi","vKLSsMK","y29SBM8","B3bLBG","DhjPBq","CxLtCKS","tvnUvvK","BLv6wfi","CeDXAva","tuLpEe8","wffvBMu","C2v0u3rVCMe","yxDUqvC","BgXhsgO","AenKEM8","Eg5hDfm","zwrPyxrLBhK","Dg9iyxnO","C2vYDMvYvgK","DeLUDgvYy2u","B2zMC2v0","Dhj1y3rVCIa","x2rLC3rYB3K","x29UvgLTzw8","EuXLz24","Aw5KzxGGB3u","CLfpCuW","y2fSBa","BwvY","BhjUvuC","ywjcyLq","wuXsq0S","zffxtgm","ywnRDxbfBMq","yM1NuvK","q291BNq","reiGzMfPBgu","mxWYFdv8m3W","zLHkA2K","C25nC2m","x2rPC2nVBM4","B3bLBKrc","AxjLza","zv90Aw1LB3u","qxz2wMS","DvvXwhu","Dg9cExrLCW","uxDvD3a","nhW2Fdi","x21LC3nHz2u","rvjst1i","Ae1uq1a","wuHysuW","yNvMzMvYzwq","uffts08","Cfvjue8","vg1ls3O","y29UC3rYDwm","x29WDgLVBNm","B2DTEfm","C3rYAw5NAwy","zgLZCgf0y2G","ELLwtKK","CKrYww4","qvDQChC","yM9KEq","uNjAzM8","uujOqLa","Aw5PDcbrB1m","DxnLCKLW","ANr1u3O","CMvTB3zLq2G","rezTB2m","z2v0","DM5Az1i","tgTLqKW","Bfbcz2e","uLDetg4","suvtx0vsuK8","CMTjDva","B3nLza","zsbHihn0CMK","ChjVDg9JB2W","AwXSihvZzsa","quXm","s2LKB0u","BIWGAg9ZDg4","sLnLuu0","uwTvr2e","Bvz0vxO","B2XcBKS","y09Wzw4","t0zXD2G","DMvY","B2nRzxrtDwm","tMPirvG","seDPqxK","tKnMv2q","AenSB3nLrxy","AunhA3u","z2v0qwXS","yNrAu2W","qwPrAeG","uMDcDNe","mdaWma","s2vzEwW","Bg93","Aw5L","tK92tvy","uKzQvxK","x3DZsw5ZDge","C29Tzq","z1z5se0","CgXLyxnLiha","Dgv4DfbHEwW","Au9nEhq","CKrey1e","yNL0zuXLBMC","mxW0Fdb8mNW","CMDsA2u","B25SAw5L","tufyx1jfvfi","rvHyEKS","Bwf4uMv0CMK","zgrjrcWGzgu","t1zxuu4","B2jQzwn0u3q","BKrtChi","v3rNyKu","Aw9U","u21jC3a","Efrurw52","q3zdDwy","zw50tgLZDgu","AxrNDvG","AxnrB1nby2S","B25tDg9Wsw0","y2HnyxHuCMK","zgjIBKK","CNzHBfzHBhu","vLrUsKS","x3bPBMC","qu9jBgS","sMnxyuy","m3W1","zNrOA00","ugHoyMq","vvDVBM8","wgXlzhy","rgrduwu","z29PBMCGyxC","q0PYEhO","t2PgvM8","Cw9Zx18","rwH4sNi","Ee1uCwG","zgXLuMu","y29UBMvJDgK","EKrutLa","sNbgEgC","vufKyu4","pxv0zI04","qLLeCwW","A1POBge","zxLRru4","y3vZDg9Tshq","BK5Mvwq","sKjnwvG","rxDUwxm","rhPvswi","AwXLx25HBwu","u2T1y3O","BgLUzq","vw5Oyw5KBgu","quHowM4","yxbWBgLJyxq","C0rpsuK","uejIthi","CKTTwgq","qLn3De8","ENjjveK","DgLTzw91Da","yNvMzMvY","BwvRqNK","B1jOwge","x2rPC3bHDgm","BwP5t28","uMDxr1O","s093Dhy","CfLdB28","CMvZzxruCMK","uKDJtgC","EKnlELG","ywDLrxzLBNq","AMvJDfn0B3i","z0jYEuO","zg9Uzq","u1LrBNm","x3nVy2TLDa","zLnJzwy","D3jPDgvvAw4","CerpyKu","nJuWnxDeCxbdva","vwDRCgK","thzIC1m","v2vPEgLUsLm","rvPQvu8","ELvKBui","C2vUza","t2jQzwn0","Dhr3Awq","tLHJswq","svPZtLK","zNjVBu51Bwi","DhDVCMTdAge","sLPTwvi","z2v0q3vYC28","EKHqu3C","venUAgW","ysbTDxn0igi","wg5MAMq","qNLywKy","CKvdEvm","s2rxA0i","CKvnrem","AvnRCfG","zxq9DxrMltG","DxrVuMvJB24","txPKwfi","BKXPBMu","x2TLEvbHDgG","B25mAw5L","lcbTyxGGCMu","CNjVCK1LC3m","B2DtDui","C3jJ","CMvHzg9UBhK","BhHpAuu","C09qwNy","qMf5AKO","tfLltxu","B0vjruu","Aw5Lza","zNvYs20","yM9KEK0","CMfNzvn5BMm","CKvpCu0","Dw5KzwzPBMu","rxvXzvu","z3bVy2u","B1vdEui","ufjrDgu","CezMAKG","z0jyDxi","Chv0","rfDIq3u","ywXSq3vYC28","AePYzfq","yMPtB3C","x1fVu01HBMe","q0H2Bvi"];return ta=function(){return t},ta()}(function(t,e){let r=F,i=t();for(;;)try{if(parseInt(r(1255))/1*(parseInt(r(765))/2)+parseInt(r(767))/3+-parseInt(r(1134))/4+-parseInt(r(1592))/5*(parseInt(r(1174))/6)+-parseInt(r(316))/7+-parseInt(r(696))/8*(-parseInt(r(1070))/9)+parseInt(r(1337))/10*(parseInt(r(727))/11)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ta,180307);var C1=Object[M(1668)+M(854)],P1=Object["getOwnPr"+M(771)+M(1099)],Xh=(t,e)=>function(){return t&&(e=(0,t[P1(t)[0]])(t=0)),e},R1=(t,e)=>{let r=M,i={hwqao:function(c,d,u,x){return c(d,u,x)}};for(var o in e)i[r(1156)](C1,t,o,{get:e[o],enumerable:!0})};function D1(){return Kh||(Kh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function O1(){let t=M;return $h||($h=[IDBCursor[t(1664)+"e"][t(1127)],IDBCursor[t(1664)+"e"][t(570)],IDBCursor[t(1664)+"e"][t(570)+"PrimaryKey"]])}function L1(t){let e=M,r={iylfT:e(707),KbDdn:e(1229),YbDRJ:function(o,c){return o!==c},LltpY:"LkSak",BlNyd:"Lzcgl",trQtg:function(o,c){return o(c)},JhKPu:function(o,c){return o===c},vaPyR:e(364)},i=new Promise((o,c)=>{let d=e,u={WZcIv:function(x,h){return r[F(1028)](x,h)},bJphk:r[d(284)],jJvmk:r.BlNyd,tdJpw:function(x,h){return r[d(353)](x,h)},iGacw:function(x,h){return x(h)}};if(r.JhKPu(d(1699),r[d(596)]))this.on(_0x573076,_0x493746);else{let x=()=>{let w=d;t[w(653)+w(1523)+w(376)](r[w(1291)],h),t[w(653)+w(1523)+w(376)](r[w(434)],m)},h=()=>{let w=d;if(u[w(1075)](u[w(894)],u[w(620)]))o(u[w(363)](zt,t.result)),x();else return _0x4b19e7?.[w(390)](I=>I[w(488)]===_0x541597)?.[w(1676)]},m=()=>{let w=d;u[w(1311)](c,t[w(1229)]),x()};t[d(917)+d(1048)](r.iylfT,h),t["addEvent"+d(1048)](d(1229),m)}});return i[e(1758)](o=>{let c=e;o instanceof IDBCursor&&Wd[c(328)](o,t)})[e(746)](()=>{}),ra[e(328)](i,t),i}function F(t,e){t=t-207;let r=ta(),i=r[t];if(F.sIiVUS===void 0){var o=function(x){let h="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",w="";for(let I=0,b,S,A=0;S=x.charAt(A++);~S&&(b=I%4?b*64+S:S,I++%4)?m+=String.fromCharCode(255&b>>(-2*I&6)):0)S=h.indexOf(S);for(let I=0,b=m.length;I<b;I++)w+="%"+("00"+m.charCodeAt(I).toString(16)).slice(-2);return decodeURIComponent(w)};F.ePcqBW=o,F.nGhNCL={},F.sIiVUS=!0}let c=r[0],d=t+c,u=F.nGhNCL[d];return u?i=u:(i=F.ePcqBW(i),F.nGhNCL[d]=i),i}function N1(t){let e=M,r={dbnzy:function(o){return o()},jChWA:e(1444),UNDkZ:"AbortError",HobBL:function(o,c){return o===c},pGqiP:"mtkuX",PxtuM:e(492),OFvUS:e(1229)};if(na[e(571)](t))return;let i=new Promise((o,c)=>{let d=e,u={fAXrI:d(1229),FMpCC:"abort",jlgoC:function(x,h){return x!==h},UmeJT:r[d(1148)],yKUAL:d(1569),DxZhA:function(x,h){return x(h)},adxpc:r[d(524)],itguX:function(x){return x()}};if(r.HobBL(d(1205),r[d(1398)]))return!0;{let x=()=>{let w=d;t[w(653)+"entListe"+w(376)]("complete",h),t[w(653)+w(1523)+w(376)](u.fAXrI,m),t[w(653)+w(1523)+"ner"](u[w(400)],m)},h=()=>{r[d(1767)](o),r.dbnzy(x)},m=()=>{let w=d;u[w(933)](u[w(1112)],u[w(652)])?(u.DxZhA(c,t[w(1229)]||new DOMException(u.adxpc,u[w(518)])),u[w(1524)](x)):_0x4e585b.exports=_0x41581e[w(322)]()[w(1758)](()=>(_0x4f8e04(),_0x4560c7))[w(1758)](function(I){return I})};t[d(917)+d(1048)](r.PxtuM,h),t["addEvent"+d(1048)](r[d(274)],m),t[d(917)+"Listener"](d(259),m)}});na[e(328)](t,i)}function M1(t){ia={RWDLn:function(i,o){return i(o)}}[M(1467)](t,ia)}function B1(t){let e=M,r={OEHRV:function(i,o){return i(o)},QnyPS:function(i,o){return i===o},flZws:e(1516)+"oreNames",WMNND:function(i){return i()}};return r.QnyPS(t,IDBDatabase[e(1664)+"e"][e(918)+e(1519)])&&!(r[e(339)]in IDBTransaction[e(1664)+"e"])?function(i,...o){let c=e,d=t[c(1417)](r[c(692)](os,this),i,...o);return jd.set(d,i[c(1244)]?i.sort():[i]),r[c(692)](zt,d)}:r[e(1813)](O1)[e(1221)](t)?function(...i){let o=e;return t.apply(os(this),i),r[o(692)](zt,Wd.get(this))}:function(...i){let o=e;return zt(t.apply(r[o(692)](os,this),i))}}function F1(t){let e=M,r={qIgZV:function(i,o){return i(o)},VVmzg:function(i){return i()}};return typeof t===e(1113)?B1(t):(t instanceof IDBTransaction&&r[e(864)](N1,t),Zh(t,r[e(1215)](D1))?new Proxy(t,ia):t)}function zt(t){let e=M,r={uUkid:function(o,c){return o instanceof c},zUdmB:function(o,c){return o(c)},WJxji:function(o,c){return o(c)},bBvvu:function(o,c){return o!==c}};if(r.uUkid(t,IDBRequest))return r[e(1597)](L1,t);if(Qo[e(571)](t))return Qo[e(1463)](t);let i=r[e(673)](F1,t);return r[e(1278)](i,t)&&(Qo[e(328)](t,i),ra[e(328)](i,t)),i}var Zh,Kh,$h,Wd,na,jd,Qo,ra,ia,os,Vh=Xh({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={CHvmR:function(r,i){return r&i},yLegn:function(r,i){return r>>>i},xahnV:function(r,i){return r&i},SCpZu:function(r,i){return r>>>i},uXDJM:function(r,i){return r&i},ViMec:function(r,i){return r>>>i},OywOT:function(r,i){return r>>>i},zHGaw:function(r,i){return r(i)},Wpolw:function(r,i){return r===i},oMkfN:"xGHfy",eaHMV:function(r,i){return r instanceof i},DMiKJ:t(1e3),wHAxO:t(500),YmpzT:function(r,i){return r===i},AXAIS:t(1586),lPQmy:function(r,i){return r===i},sINQw:t(1137),hCdzo:function(r,i){return r(i)},ZzaIV:function(r,i){return r<i},gfFHZ:function(r,i){return r<<i},kkMDd:function(r,i){return r instanceof i},TkTOl:function(r,i){return r!==i},mnDuG:t(1850),BUzzQ:function(r,i){return r in i}};Zh=(r,i)=>i[t(1501)](o=>r instanceof o),Wd=new WeakMap,na=new WeakMap,jd=new WeakMap,Qo=new WeakMap,ra=new WeakMap,ia={get(r,i,o){let c=t,d={uZMRq:function(u,x){return e[F(1055)](u,x)}};if(e[c(519)](e.oMkfN,e.oMkfN)){if(e[c(1387)](r,IDBTransaction)){if(e[c(519)](e[c(716)],e[c(612)]))return d.uZMRq(_0x5c284d,_0x589689);if(e[c(1815)](i,e.AXAIS))return na.get(r);if(e[c(1815)](i,c(1516)+c(605)))return r[c(1516)+"oreNames"]||jd[c(1463)](r);if(e[c(643)](i,e[c(1853)]))return o[c(1516)+"oreNames"][1]?void 0:o.objectStore(o[c(1516)+c(605)][0])}return e[c(1404)](zt,r[i])}else{let u=this[c(1831)],x=this[c(1496)];return[255&x,e[c(1650)](e[c(1414)](x,8),255),e[c(899)](e.SCpZu(x,16),255),e.yLegn(x,24),e[c(1104)](255,u),e[c(899)](e[c(636)](u,8),255),e[c(899)](u>>>16,255),e.OywOT(u,24)]}},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;if(e.kkMDd(r,IDBTransaction)&&(i===e[o(1023)]||i===o(1137)))if(e[o(1269)](e[o(759)],e[o(759)]))_0x13086b=_0x480f5d(_0x5e4f25),e[o(1799)](_0x282dac,32)&&(_0x9b1a47|=e[o(1806)](e[o(899)](127,_0x499283),_0x4c1be2)),_0x41b953+=7;else return!0;return e[o(402)](i,r)}},os=r=>ra[t(1463)](r)}}),Qh={};R1(Qh,{deleteDB:()=>U1,openDB:()=>z1,unwrap:()=>os,wrap:()=>zt});function z1(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=M,u={Rxvdv:function(m,w,I,b,S){return m(w,I,b,S)},sdBts:function(m,w){return m(w)},IAeWI:"close",GLeuX:d(1708)+"hange",FMyzA:function(m,w){return m(w)},hYtiR:function(m,w){return m===w},wHemk:d(1324)+"eeded",gBryJ:d(1360)},x=indexedDB[d(1393)](t,e),h=u[d(1293)](zt,x);return i&&(u[d(537)]("iaGSl",d(1335))?x["addEvent"+d(1048)](u[d(355)],m=>{let w=d;u.Rxvdv(i,u[w(1803)](zt,x.result),m[w(699)+"on"],m[w(280)+"on"],zt(x[w(918)+w(1519)]))}):u[d(828)](_0x4dfe68,u[d(1803)](_0x3aed1a,_0x18c410[d(528)]),_0x1f0bea[d(699)+"on"],_0x78e07a[d(280)+"on"],u[d(1803)](_0x31614d,_0x4c353b[d(918)+d(1519)]))),r&&x[d(917)+d(1048)](u[d(1585)],()=>r()),h[d(1758)](m=>{let w=d;c&&m["addEvent"+w(1048)](u.IAeWI,()=>c()),o&&m[w(917)+w(1048)](u[w(607)],()=>o())})[d(746)](()=>{}),h}function U1(t,{blocked:e}={}){let r=M,i={zayZN:r(1360),IZsNY:function(c,d){return c(d)}},o=indexedDB["deleteDa"+r(1027)](t);return e&&o[r(917)+r(1048)](i.zayZN,()=>e()),i[r(1602)](zt,o).then(()=>{})}function Yh(t,e){let r=M,i={TfEzb:function(x,h){return x===h},zPxHr:function(x,h){return x===h},zHUzf:function(x,h){return x+h},hXpXN:r(1083)+"e",hVqAE:function(x,h){return x instanceof h},BHcbt:r(340),llGHj:function(x,h){return x!==h},EvvDL:function(x,h){return x in h},ZCUXj:function(x,h){return x!==h},vwlqK:r(250)};if(!(i.hVqAE(t,IDBDatabase)&&!(e in t)&&typeof e===i[r(734)]))return;if(ea[r(1463)](e))return ea[r(1463)](e);let o=e[r(323)](/FromIndex$/,""),c=i[r(1403)](e,o),d=tp[r(1221)](o);if(!i[r(1184)](o,(c?IDBIndex:IDBObjectStore)[r(1664)+"e"])||!(d||ep.includes(o)))return i[r(1304)](i[r(561)],i[r(561)])?i[r(789)](-1,this[r(1496)])&&i[r(1234)](-1,this[r(1831)])?_0x124c12[r(1130)](0,0,this[r(968)]):i.zPxHr(-1,this[r(1496)])?_0x533346[r(1130)](0,i[r(553)](this[r(1831)],1),this[r(968)]):_0x2dbf30[r(1130)](this[r(1496)]+1,this.high,this[r(968)]):void 0;let u=async function(x,...h){let m=r,w=this[m(918)+"ion"](x,d?i.hXpXN:m(1626)),I=w.store;return c&&(I=I[m(908)](h[m(658)]())),(await Promise.all([I[o](...h),d&&w[m(1586)]]))[0]};return ea[r(328)](e,u),u}var ep,tp,ea,H1=Xh({"node_modules/idb/build/index.js"(){let t=M,e={ylkIp:t(1644),buWIR:"delete",CBFMc:t(1334),bxoDS:function(o,c){return o(c)},bWcGc:function(o){return o()},Vjkjv:t(1463),OjFVo:t(698),qyttd:t(1490),yZWXO:t(1266)+"ys",fKviA:t(996)},r=(t(361)+t(1389))[t(842)]("|"),i=0;for(;;){switch(r[i++]){case"0":ea=new Map;continue;case"1":Vh();continue;case"2":tp=[e[t(1769)],t(665),e.buWIR,e[t(272)]];continue;case"3":e[t(787)](M1,o=>({...o,get:(c,d,u)=>Yh(c,d)||o[t(1463)](c,d,u),has:(c,d)=>!!Yh(c,d)||o[t(571)](c,d)}));continue;case"4":e[t(875)](Vh);continue;case"5":ep=[e[t(555)],e[t(1542)],e.qyttd,e[t(348)],e[t(399)]];continue}break}}}),G1={idb:function(t){let e=M;t[e(674)]=Promise[e(322)]().then(()=>(H1(),Qh))[e(1758)](function(r){return r})}},Jh={};function Ft(t){let e=M,r={rECyS:"2|0|3|1|4",nutLY:function(u,x){return u!==x}},i=r[e(1612)].split("|"),o=0;for(;;){switch(i[o++]){case"0":if(r[e(332)](void 0,c))return c.exports;continue;case"1":G1[t](d,d.exports,Ft);continue;case"2":var c=Jh[t];continue;case"3":var d=Jh[t]={exports:{}};continue;case"4":return d.exports}break}}Ft.d=(t,e)=>{let r=F;for(var i in e)Ft.o(e,i)&&!Ft.o(t,i)&&Object[r(1668)+r(854)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Ft.o=(e,r)=>Object[t(1664)+"e"].hasOwnProperty[t(1417)](e,r)})(),(()=>{let t=M,e={vWUbw:function(r,i){return r!=i},WuIQk:t(1637)+"d",gboRe:t(1218),iQlMR:t(792)+"le"};Ft.r=r=>{let i=t;e.vWUbw(e[i(378)],typeof Symbol)&&Symbol[i(558)+i(578)]&&Object[i(1668)+i(854)](r,Symbol.toStringTag,{value:e[i(513)]}),Object[i(1668)+i(854)](r,e[i(1765)],{value:!0})}})();var Re={};(()=>{let t=M,e={OXLWU:function(a,n){return a(n)},qySrK:function(a,n){return a+n},ZzDZL:function(a,n){return a+n},ZidwK:function(a,n){return a+n},sDOII:function(a,n){return a*n},GaDxc:function(a,n){return a+n},yGPPe:function(a,n){return a(n)},mekBy:function(a,n,s){return a(n,s)},nQHQY:function(a,n){return a===n},CuTaE:"aBoKb",KunFh:t(410),OVWQN:function(a,n){return a+n},FROXY:function(a,n){return a(n)},rTDas:function(a,n){return a+n},kGUji:function(a,n){return a(n)},MNgOO:t(1494),cfUfa:"ffff",trjFe:function(a,n){return a(n)},CPCVI:"0000000000000000"+t(1378)+t(1378),dCcPN:function(a,n){return a!==n},vaAvC:t(567),amtkF:function(a,n){return a>n},XStVm:function(a,n){return a<n},uwDbd:function(a,n){return a<n},ViUcC:function(a,n){return a-n},DWbCu:function(a,n){return a-n},KMIFM:function(a,n){return a<n},IdCQN:function(a,n){return a<n},OdMfd:"ruGJw",jnQnZ:t(1379),NQrPp:function(a,n){return a!==n},EuqeU:function(a,n,s){return a(n,s)},bsvSO:function(a,n,s){return a(n,s)},WNpfY:function(a,n){return a(n)},OSDFw:function(a,n){return a>>>n},FawFp:function(a,n,s){return a(n,s)},UbSSp:function(a,n){return a(n)},qMKkq:function(a,n){return a(n)},nzUvi:function(a,n,s){return a(n,s)},pqNde:function(a,n){return a&n},aApgF:t(932)+t(1123)+t(427)+t(1676),zACJw:function(a){return a()},suPaB:function(a,n,s){return a(n,s)},zCKzX:function(a,n){return a>n},GohpJ:t(680)+t(1286),TagUd:t(556),NBfDZ:function(a,n){return a!==n},wtwXY:function(a,n,s){return a(n,s)},JhoAo:function(a,n,s){return a(n,s)},CtIsf:function(a,n,s){return a(n,s)},pTwAs:function(a,n){return a!==n},EWOSd:function(a,n){return a(n)},ujiwR:function(a,n,s){return a(n,s)},zYVNI:function(a,n,s){return a(n,s)},VPxXE:function(a,n,s){return a(n,s)},nKYuI:function(a,n,s){return a(n,s)},furKm:function(a,n){return a!==n},Sbokt:function(a,n,s){return a(n,s)},OyaXT:function(a,n,s){return a(n,s)},TuTBA:function(a,n){return a!==n},LGbPo:function(a,n,s){return a(n,s)},GHKXk:function(a,n,s){return a(n,s)},ilvoD:function(a,n){return a===n},ryQBj:function(a,n){return a(n)},dbGAQ:function(a,n){return a(n)},nNfUd:function(a,n){return a>>>n},kzGpp:function(a,n,s){return a(n,s)},PqWkM:function(a,n,s){return a(n,s)},opDCK:function(a,n){return a(n)},GrWSa:function(a,n,s){return a(n,s)},OKHva:t(932)+t(1123)+t(427)+t(809),FLknL:function(a,n){return a===n},ogSuB:t(932)+t(1123)+t(427)+t(1093),gpoce:function(a,n){return a(n)},rtNOV:function(a,n){return a+n},NnfNu:function(a,n){return a&n},mgwoV:function(a,n){return a(n)},ACxPi:function(a,n,s){return a(n,s)},stDln:t(1667)+t(677)+t(861),vYxSI:function(a,n){return a>>n},FrXxQ:"close",hIXOb:function(a,n){return a+n},rMfPk:function(a,n){return a>n},ncdwr:t(1510),RLfSP:t(1771),Xnfjd:"pagehide",VWmsj:t(990),AyFPM:t(777),QwUwp:function(a,n){return a+n},BGFIl:t(694)+t(1286),dvwUl:function(a,n){return a>=n},wFnPu:function(a,n){return a+n},zmlGP:function(a,n){return a-n},nAePU:function(a,n){return a<<n},qzhIe:function(a,n){return a<n},bjSow:function(a,n){return a<n},QpFKf:function(a,n,s){return a(n,s)},ibrTv:function(a,n){return a<n},xMTqh:function(a,n){return a===n},TCnhl:function(a,n){return a&n},GCtMX:function(a,n){return a(n)},PBbLr:function(a,n){return a+n},ogmxS:function(a,n){return a+n},ABluY:function(a,n){return a<<n},KyLeU:function(a,n){return a&n},zHPSw:function(a,n){return a==n},LkeBL:function(a,n){return a+n},rDJEd:function(a,n){return a+n},FOXRD:function(a,n){return a!==n},jYPma:function(a,n){return a&n},WtgbE:function(a,n){return a|n},vSZFO:function(a,n){return a===n},kRqez:t(585),mvqdY:t(1326),VUqfI:function(a,n){return a|n},kKPkb:function(a,n){return a&n},iamsu:function(a,n){return a&n},lbyyA:function(a,n){return a&n},oacfA:function(a,n){return a+n},LpvtK:function(a,n){return a+n},zuyzB:function(a,n){return a+n},mZROL:function(a,n){return a!==n},oeTpA:function(a,n){return a&n},RReUw:function(a,n){return a|n},NOKCC:function(a,n){return a<<n},oUCyB:function(a,n){return a|n},ZVsZU:function(a,n){return a&n},MOPOa:function(a,n){return a<<n},SmIsp:function(a,n){return a&n},TlOEA:function(a,n){return a<<n},EhLvo:function(a,n){return a<n},SIWer:function(a,n){return a>n},bfHBR:function(a,n,s){return a(n,s)},mCzXZ:function(a,n){return a>>n},gDSPc:function(a,n){return a+n},JANJj:function(a,n){return a>>>n},pPmGv:function(a,n){return a*n},LKwPO:function(a,n,s){return a(n,s)},UhmRM:"lMYey",Lodej:function(a,n){return a<n},rvcBV:function(a,n){return a>=n},SwMrV:function(a,n){return a-n},RQRiJ:function(a,n){return a+n},BkpFg:function(a,n){return a<<n},StmMs:function(a,n){return a<n},MIOxO:function(a,n){return a<=n},vGNRv:function(a,n){return a<<n},XubLw:function(a,n){return a!==n},WANXe:t(248),spsLJ:"irYAa",fJWnC:function(a,n){return a|n},FujSP:function(a,n){return a&n},QJGwW:function(a,n){return a<n},abBbT:function(a,n){return a&n},bodzM:function(a,n){return a|n},iCpYj:function(a,n){return a&n},vgjAW:function(a,n){return a>>n},PsEgT:function(a,n){return a<n},sqPHO:function(a,n,s){return a(n,s)},PcYsL:function(a,n){return a(n)},dqMWn:function(a,n){return a&n},orFGB:t(1857),VvdtJ:function(a,n){return a(n)},NUQJg:function(a,n){return a(n)},nDSpr:function(a,n){return a(n)},ySFYY:function(a,n){return a(n)},JpduO:function(a,n){return a===n},ozwQO:t(814),dHzhG:function(a,n){return a(n)},pQsuK:function(a,n){return a&n},tAcFL:function(a,n){return a&n},TTGeC:function(a,n){return a&n},kZhla:function(a,n){return a!==n},bVLeW:"ZWDbY",CupzS:function(a,n){return a&n},RMZXF:function(a,n){return a&n},GoGer:function(a,n){return a&n},CnJQN:function(a,n){return a<<n},VevhE:function(a,n){return a&n},lHCjX:function(a,n){return a!==n},NNSeV:t(1380),TIbwE:function(a,n){return a(n)},NosKJ:function(a,n){return a<<n},hGQNI:function(a,n){return a&n},yCRcq:function(a,n){return a|n},OjQNe:function(a,n){return a>>>n},vUCCH:function(a,n){return a>>>n},EzwHg:function(a,n){return a===n},FHmdy:function(a,n){return a<n},sSYqK:function(a,n){return a<n},Szpqc:function(a,n){return a<n},pFfjH:function(a,n){return a|n},fJSEJ:function(a,n){return a+n},kxpkn:function(a,n){return a!==n},WYkTr:function(a,n){return a|n},SkefL:function(a,n){return a>>>n},BHeHD:function(a,n){return a>>>n},QzqQW:function(a,n){return a&n},XlEVF:function(a,n){return a>>>n},BgoXb:function(a,n){return a&n},dNodz:function(a,n){return a+n},OAVhz:function(a,n){return a+n},EXXzK:function(a,n){return a>>>n},zDTNP:function(a,n){return a>>>n},nfDAC:function(a,n){return a|n},mjyOo:function(a,n){return a>>>n},ZqXuI:function(a,n){return a&n},mKZzR:function(a,n){return a(n)},GnpTX:function(a,n){return a|n},YPvat:function(a,n){return a===n},RPLwD:function(a,n){return a===n},ocfvH:"jIFtE",iExEh:t(435),oSMub:function(a,n){return a<<n},GQlbY:function(a,n){return a|n},batkO:function(a,n){return a|n},yKxGs:function(a,n){return a<<n},GBaKb:t(1849),CEZgv:function(a,n){return a|n},Trags:function(a,n){return a|n},fQdto:function(a,n){return a<<n},ykeLj:function(a,n){return a<<n},LPNWF:function(a,n){return a|n},YrhAW:function(a,n){return a|n},iKHeX:function(a,n){return a<<n},KOwtv:function(a,n){return a|n},oEIEE:function(a,n){return a>>>n},uYQCw:function(a,n){return a>>>n},tOIUd:function(a,n){return a>>>n},zZPVe:function(a,n){return a>>>n},CQhjE:function(a,n){return a|n},ItfkP:function(a,n){return a/n},oPwuA:function(a,n){return a!==n},ggYrx:t(1856),jvNwH:t(1564),sRKNP:function(a,n){return a+n},UarIp:function(a,n){return a*n},ijAnn:function(a,n){return a>>>n},iDXVN:function(a,n){return a>>>n},PUuMZ:function(a,n){return a===n},HOeBi:function(a,n){return a&n},bCEkp:function(a,n){return a>>>n},oFeeV:function(a,n){return a&n},aQHHI:function(a,n){return a>>>n},EmIKX:function(a,n){return a>>>n},dVfxC:function(a,n){return a+n},eWtih:function(a,n){return a<<n},mYPNL:function(a,n){return a>>>n},oLdaD:function(a,n){return a===n},LvbsS:function(a,n){return a===n},tkVfB:function(a,n,s,l){return a(n,s,l)},HfwDo:t(431),omIkJ:function(a,n){return a+n},sWtCi:function(a,n){return a+n},nVDju:function(a,n){return a===n},yzwsd:t(736),AOIlk:t(752)+t(1534),EKSDe:"CONNECTING_ERROR",yEfvd:t(1511)+t(1468)+"R",Aelfs:t(608)+t(1440),anJYN:t(1038)+"OR",eCPLH:"NATIVE_E"+t(901),xGVOI:function(a,n){return a!==n},KgEww:"oGder",cHUhi:function(a,n){return a&n},DMdSA:function(a,n){return a>>>n},dwYRd:function(a,n){return a>>>n},zqVkz:function(a,n){return a&n},oDnfk:function(a,n){return a>>>n},bFlxR:function(a,n){return a>>>n},AbvMC:t(649),wGKdR:function(a,n){return a>>>n},aSqVH:function(a,n){return a>>>n},EyQrl:function(a,n){return a&n},Rrawm:function(a,n){return a>>>n},hsXSK:function(a,n){return a&n},PAsne:function(a,n){return a>>>n},PTuYh:function(a,n){return a+n},XOwsn:function(a,n){return a*n},NXGaf:t(687),ODxWm:t(314)+t(1438),wldEb:t(298)+"0",zVtyA:function(a,n){return a!==n},OoGJH:t(1820),GWgCs:t(923),WWIDb:function(a,n){return a===n},xWoxN:function(a,n){return a>n},iofxm:t(416),eykEN:t(1076),BchDI:function(a,n){return a===n},oVqlE:t(315),Krwdr:t(319),rlNRt:t(1229),HSWDi:function(a,n){return a instanceof n},XBfHV:function(a,n){return a+n},VZGny:t(1563)+t(1816),FBqYT:function(a,n){return a+n},awnAW:function(a,n){return a!==n},YGesZ:function(a,n){return a>>>n},dcjZt:function(a,n){return a===n},KeeSJ:t(1489),sJBgn:t(1454),BurxS:t(1393),WQEuP:function(a,n,s){return a(n,s)},dleRe:function(a,n){return a instanceof n},eWGrM:function(a,n){return a||n},WXOCu:function(a,n){return a||n},NsBjY:function(a,n){return a!=n},NtmLC:"1|3|0|4|2",viCPr:"undefined",KGYhy:function(a,n){return a!==n},FXsUQ:"Qkksn",RFjUy:function(a,n){return a<n},XHxXV:function(a,n){return a!==n},tDDQb:t(1363),HSlMM:"ofOKN",xEAFq:function(a,n){return a===n},dQWLc:function(a,n){return a&n},CvCuf:function(a,n){return a===n},fFvgq:t(1003),OPIat:function(a,n){return a<n},XSeiB:function(a,n,s){return a(n,s)},QEJrt:function(a,n){return a!==n},hyFqB:t(956),EAuFx:function(a,n){return a>=n},oeDRB:function(a,n){return a<n},Nmetx:function(a,n){return a<<n},HkJSx:function(a,n){return a&n},opTfO:function(a,n){return a>=n},xbSEA:function(a,n){return a<n},gjNAb:function(a,n){return a&n},iLztW:function(a,n){return a&n},uARTM:function(a,n){return a-n},sTneV:function(a,n){return a|n},xnjJO:function(a,n){return a|n},dhxAI:function(a,n){return a&n},SVBgH:function(a,n){return a<<n},NXcId:function(a,n){return a&n},EwnYs:function(a,n,s,l,f){return a(n,s,l,f)},UWICD:"upgraden"+t(1377),zRHFF:function(a,n){return a<n},rKmXd:function(a,n){return a|n},knngE:function(a,n){return a&n},iLcXS:function(a,n){return a===n},uxxKy:"OtwzV",fJovE:t(921),SJKuD:t(1330)+t(1316),KMlZN:function(a,n){return a&n},BuQCs:function(a,n){return a+n},kXmyY:function(a,n){return a+n},AUqbC:function(a,n){return a<<n},WHvmh:function(a,n){return a|n},MQNzI:function(a,n){return a&n},kPfTw:function(a,n){return a>>n},QiVSy:function(a,n){return a|n},vZVAV:function(a,n){return a&n},WHBlo:t(340),FBreV:t(1121),lVAgv:t(1565)+t(496),KidoE:function(a,n){return a(n)},JwrDH:t(471),zdOio:function(a,n,s){return a(n,s)},VTnJK:function(a,n,s,l){return a(n,s,l)},PUsWW:function(a,n){return a+n},rlGds:t(1163),IDgLa:function(a,n){return a>=n},loBAy:t(549)+t(576),QTddH:function(a,n){return a<<n},eBxXC:function(a,n){return a&n},NjHEX:function(a,n){return a===n},WydDH:t(1424),sxiXa:t(867)+t(1013),UvjJG:"http",PlCbM:"&jscallb"+t(460)+t(422)+"P",XyKIG:t(1859),YrfQp:function(a,n){return a!==n},ehdGH:t(1482),NedKH:t(590),pGwfX:function(a,n){return a!==n},QGZtS:"Adfgh",BPLXo:function(a,n){return a===n},XKcFx:t(798),eMPjC:function(a,n){return a!==n},kStPl:function(a,n){return a|n},KsQeW:function(a,n,s){return a(n,s)},SwSMe:function(a,n){return a!==n},UliLz:t(563),anJxB:t(873),uAVnd:function(a,n){return a===n},hJrdT:function(a,n){return a(n)},GDXdA:function(a,n){return a+n},gtpnl:function(a,n){return a+n},TJkUy:t(937),OvbHk:t(890),NsqxE:function(a,n){return a||n},lyJrQ:t(953),AWkMy:function(a,n){return a||n},GAOwE:"tLvmQ",xzwyx:function(a,n){return a||n},iNygV:function(a,n){return a<=n},ZrSki:function(a,n){return a>=n},AOdiR:function(a,n){return a===n},oDYlH:t(512),cbtAK:function(a,n){return a||n},lcVIJ:function(a,n){return a===n},pUIPO:"LnyJC",hEAXJ:function(a,n){return a(n)},KAgaU:function(a,n){return a(n)},yLbhi:t(1233),NtIsF:function(a,n){return a||n},uUqXu:function(a,n){return a||n},PgbgD:function(a,n){return a!=n},CZzyP:t(1458)+t(1426)+"d",zJLuq:"qos",csmWI:t(374)+"id",jLbUW:function(a,n){return a!==n},uypmy:t(1193),rWQqQ:function(a,n,s){return a(n,s)},KLGsC:function(a,n){return a(n)},EywTT:t(1111),oWmcE:function(a,n){return a+n},TUDak:t(1832),qOwtA:t(1132),rFgwL:function(a,n,s){return a(n,s)},vTFnY:function(a,n){return a!==n},nUzXR:t(951),lVvvT:t(1004),AMWBy:t(817)+"er_qos",LPldx:function(a,n,s,l){return a(n,s,l)},RizWZ:t(817)+"er_qos_ack",pWXIk:function(a,n,s,l){return a(n,s,l)},aOJhf:t(817)+t(1150)+t(285),OcKtK:function(a,n){return a!==n},SCjwm:t(490),pVaGF:t(1833),eeJJI:t(725),bIaFL:t(757),Tkszh:function(a,n){return a&&n},rkIuP:"ack_id",pQcyq:function(a,n){return a||n},suzps:t(536),yncIj:"received",EAtzG:function(a,n,s){return a(n,s)},mVtUz:function(a,n){return a|n},LdyEB:function(a,n){return a|n},CTcUO:function(a,n){return a<<n},kwUtt:function(a,n){return a&n},ceTnB:function(a,n){return a<<n},nANaD:t(1678),GRIXO:function(a,n){return a(n)},zgQsm:t(994),cxyJx:t(1011)+t(381)+"et=utf-8",WPGYM:t(1565)+t(496)+";charset"+t(1551),ZzuIQ:t(373),ixoVe:function(a){return a()},bFnXc:function(a,n){return a<n},SGZGK:function(a,n){return a+n},NvubG:function(a,n){return a&n},QOXNY:function(a,n){return a||n},hyxiD:function(a,n){return a+n},DAkua:function(a,n){return a|n},nnHSB:function(a,n){return a<<n},kzFKf:function(a,n){return a+n},vFFDm:function(a,n){return a+n},gtIPJ:function(a,n){return a+n},pHKHi:function(a,n){return a(n)},BayjJ:function(a,n){return a+n},lYsEF:t(375),ThFuq:t(987),QnZkZ:t(1068),jOtbp:t(581)+t(458)+"e",XEKAv:function(a,n){return a>=n},zcYTl:function(a,n){return a&n},KWdIB:function(a,n){return a+n},NAZcn:function(a,n){return a+n},vlhqd:function(a,n){return a-n},LcvrF:function(a,n){return a<n},xakps:function(a,n){return a&n},sOPZv:function(a,n){return a&n},cHxqU:function(a,n){return a|n},WjAZY:function(a,n){return a&n},tsVzv:function(a,n){return a|n},ZCGdI:function(a,n){return a!==n},uqJSQ:t(368),BqriA:function(a,n){return a+n},bQMqS:function(a,n){return a<n},ScQNO:function(a,n){return a<<n},ePtLU:function(a,n){return a===n},guUZo:"MgFnj",WCSOh:t(1508)+"3",ZNiFD:function(a,n){return a+n},TgqEJ:function(a,n){return a+n},KvWSg:function(a,n){return a|n},PimOL:function(a,n){return a|n},yZzFy:function(a,n){return a|n},rNnDG:function(a,n){return a<<n},RSXzc:function(a,n){return a|n},pIfjz:function(a,n){return a|n},scQeP:function(a,n){return a+n},jkcvG:function(a,n){return a+n},HRRqV:t(369),zOcCB:function(a,n){return a>>>n},egNwJ:function(a,n){return a+n},MzdXR:function(a,n){return a&n},ZbJHf:function(a,n){return a+n},Cygkv:function(a,n){return a&n},RYPiY:function(a,n){return a>>>n},qmWek:function(a,n){return a+n},uHlLi:function(a,n){return a>>>n},rQOqL:function(a,n){return a<n},qwdlY:function(a,n){return a>>>n},xxEuT:function(a,n){return a&n},BUHQS:function(a,n){return a>>>n},UAdaN:function(a,n){return a<<n},KeYyl:function(a,n){return a<n},WFCoH:function(a,n){return a(n)},Pshzm:function(a,n,s,l){return a(n,s,l)},cYITU:t(810),zRNeQ:t(609),SRIxF:function(a,n,s,l){return a(n,s,l)},tfyjZ:t(1790)+t(633),vutuL:"header",tsSCN:t(634)+t(1560),npLED:function(a,n,s){return a(n,s)},OAJwu:function(a,n,s){return a(n,s)},kCWHB:function(a,n,s){return a(n,s)},qmFnp:t(1646)+t(451),ReYEy:t(1474),jkSEL:t(1364),vIKRK:t(1855),jAGhc:function(a){return a()},WWTNZ:t(1838)+"r",HGiAy:t(511),tVGzZ:function(a,n){return a!==n},JfQyc:function(a,n){return a||n},iFwxr:function(a,n){return a(n)},pYCoo:function(a,n){return a(n)},YmdQf:"code",baUfL:function(a,n,s){return a(n,s)},EhxJr:"x_fronti"+t(538),pjXhi:function(a,n){return a(n)},zlYhd:function(a,n,s){return a(n,s)},QRXnO:t(817)+t(1265),tyyku:function(a,n,s,l){return a(n,s,l)},lxOiE:"x-msg-qos",IACoX:function(a,n,s){return a(n,s)},zoWbb:function(a,n){return a(n)},aIrlv:function(a){return a()},niNnJ:function(a,n){return a===n},gVyHM:function(a,n){return a+n},TamQX:function(a){return a()},VzGav:function(a,n){return a>>>n},YsrDV:function(a,n){return a<<n},rOHKH:function(a,n){return a<n},YHXIL:function(a,n){return a<n},OvHnz:function(a,n){return a!==n},sdXTv:function(a,n){return a|n},rLcuH:function(a,n){return a+n},yFRRO:function(a,n){return a&n},umyWG:function(a,n){return a>>>n},lNfyP:function(a,n){return a>>>n},zbUfG:function(a,n){return a>>>n},emwbB:function(a,n){return a>>>n},Mxkca:function(a,n){return a&n},DdCQe:function(a,n){return a&n},RgWGZ:function(a,n){return a>>>n},CaXGx:function(a,n){return a!==n},fXJki:function(a){return a()},Eerab:function(a,n){return a|n},SlgXo:function(a,n){return a&n},bhuWO:function(a,n,s){return a(n,s)},Rcezb:function(a,n){return a(n)},gFQqp:t(1072),kDMyh:function(a,n){return a!==n},pidze:function(a){return a()},DDJZQ:function(a,n){return a===n},mSnHW:function(a,n,s){return a(n,s)},sXwYM:function(a,n){return a===n},tNOWz:function(a,n,s,l){return a(n,s,l)},vObsS:"ping_onc"+t(920)+"s",hHjGA:t(707),Skucz:function(a,n){return a!==n},AjQhH:function(a,n,s){return a(n,s)},HSVRo:t(690),MVcQG:function(a,n){return a!==n},Sfvmo:function(a,n){return a(n)},UWsuV:"TRjlP",SqLcV:function(a,n){return a instanceof n},dBLlb:function(a,n){return a instanceof n},rqTwA:t(1793)+"e",OoCDV:"arraybuffer",ZGVsc:function(a,n){return a(n)},UOTlA:t(1503)+t(1081)+t(967)+t(1382)+t(379)+t(1411)+t(1844)+t(1632),qLkIE:t(682),xtfjI:function(a,n,s){return a(n,s)},FGnbc:t(1159)+t(1406)+t(775)+"ct",WJEab:function(a,n){return a>>>n},mcLNx:function(a,n){return a&n},PSxCI:function(a,n){return a&n},qoLxE:function(a,n){return a>>>n},saXhE:function(a,n){return a+n},RgBvq:function(a,n){return a>>>n},FiZut:t(1069),THBHZ:"function",LfdER:function(a,n){return a(n)},aLswF:function(a,n){return a instanceof n},oRhXa:function(a){return a()},ciprZ:t(485),BCCQV:t(326),HbrjW:t(1540)+t(1371)+t(808)+t(1220)+t(1483),yENlR:t(1261),IqpiT:t(639),TNfXv:function(a,n){return a!==n},wMraO:function(a,n){return a!==n},ltxqT:t(1043),mnKfp:t(1285),GmBKs:"wss://",vQtfo:"ws://",TmKKz:"vMStC",yAjUn:t(832),bQwYd:t(978)+"d",JvYGB:function(a,n){return a||n},gDzES:t(1503)+t(874)+t(1514)+t(1175)+t(1800),YywvO:function(a,n){return a==n},ASZDE:function(a,n,s){return a(n,s)},GNUcz:t(742),RrZfo:function(a,n,s){return a(n,s)},rHnIE:function(a,n,s){return a(n,s)},TBgKi:"0|3|1|4|2",OlhJw:function(a,n){return a+n},iSfKL:function(a,n){return a<n},iPVIL:t(300),npmFC:t(1141),ihYBt:function(a,n){return a(n)},DVPzl:function(a,n){return a-n},kUaWk:function(a,n){return a!==n},yqeVV:t(1045)+t(1433)+"t",MSnUY:t(1571),kzMJv:function(a,n,s){return a(n,s)},LAyHk:"iyePq",kqBpo:"nyOKe",FqLyd:t(455)+t(763)+t(370)+"g",lPBga:function(a,n){return a(n)},NbweT:function(a,n){return a===n},RVjuP:t(1108),gyryl:"ack",kcTJY:function(a,n){return a===n},YLRCK:"VrXlM",GbIqc:t(515)+"2",SIQHW:t(1153),pcLoI:"0|3|2|4|1",ODgNA:function(a,n){return a!==n},oCYiy:t(741),aIjWI:function(a,n,s){return a(n,s)},jWAPV:t(1540)+t(650)+t(1848)+t(1497),gBXur:function(a,n){return a===n},RsZIW:t(470),uzjbU:function(a,n){return a!==n},DzUIb:t(1354),CPupp:function(a,n){return a&n},hCvod:function(a,n){return a|n},QMlPd:function(a,n){return a&n},BCquO:function(a,n){return a|n},EjOHs:function(a,n){return a&n},ykiKw:function(a,n){return a&n},vaTvV:function(a,n){return a>>n},yXDkE:function(a,n){return a|n},LWLHC:function(a,n){return a&n},gKefm:t(408),hxTLc:t(1427)+t(1835),bpDSL:function(a,n){return a===n},dLkRz:"close, ws instan"+t(613)+t(1796)+"ed",mBNbD:function(a,n){return a||n},vdaiy:function(a,n){return a===n},tDMHM:function(a,n){return a==n},LYKMu:function(a,n){return a instanceof n},VsNbb:function(a,n){return a(n)},kiWTX:function(a,n){return a(n)},uzFkW:function(a,n){return a||n},VffVW:t(1503)+t(1299)+t(317)+t(1702),QkUGa:function(a,n){return a instanceof n},Ugkpi:t(1015),hzhaz:t(1091),gMBVp:"enqueue",XvYHg:t(1143),lrnUG:function(a,n){return a==n},Bcrbk:t(785)+t(310)+"ing",zrITI:function(a,n){return a!==n},MZpfz:t(367),NCfWd:t(979)+"2",rEOqM:function(a,n){return a(n)},fvLXL:t(1012),olBnK:function(a,n){return a!=n},dYmNr:"Window",TeQup:function(a,n){return a!=n},rgRke:t(1599),rcmnC:function(a,n){return a===n},IZVVH:"Dedicate"+t(1064)+t(745)+"pe",JCKsR:function(a,n){return a!=n},wpKde:function(a,n){return a===n},ZiZCt:function(a,n){return a==n},kExrs:function(a,n){return a!=n},Amdqr:function(a,n){return a!=n},CLMGL:"SharedWorkerGlob"+t(668),wDFWg:function(a,n){return a===n},DbYIC:t(1834)+t(1384)+t(645),Eljau:function(a,n){return a!=n},SsvIu:function(a,n){return a!=n},JSeQM:function(a,n){return a!=n},TUXDV:"__x_msg_"+t(1543)};Ft.r(Re),Ft.d(Re,{FWS:()=>Hg,CustomErrorEvent:()=>ul,createCloseEvent:()=>_t,ReconnectEvent:()=>ll,createErrorEvent:()=>lt,decodedFrame:()=>rn,createOpenEvent:()=>ml,CustomCloseEvent:()=>fl,createReconnectEvent:()=>ba,FrontierMessageEvent:()=>hl,encodeFrame:()=>Ut,createMessageEvent:()=>gl,OpenEvent:()=>pl,ErrorCode:()=>on,Event:()=>ir,MessageEvent:()=>xl});let r="";function i(a=""){let n=t,s="02",l=""+Date[n(713)](),f=r||(r=e[n(575)](x,a)),g=Math[n(975)]().toString(16)[n(624)](-6);return e[n(1395)](e[n(1158)](e[n(1116)](s,l),f),g)}function o(){let a=t;return e.ZzDZL(e.sDOII(1e4,Date[a(713)]()),Math[a(927)](e[a(1566)](1e4,Math[a(975)]())))}function c(a){let n=t;return e[n(1031)](e.yGPPe(Array,8)[n(247)]("0"),e[n(1573)](parseInt,a,10)[n(558)](2))[n(624)](-8)}function d(a){let n=t;return e[n(1731)](e.CuTaE,e.KunFh)?this._socket[n(635)+"ns"]:e[n(1515)](e.FROXY(Array,4).join("0"),e[n(1573)](parseInt,a,2)[n(558)](16))[n(624)](-4)}function u(a){let n=t,s=a.split(/\./)[n(493)](g=>c(g)),l=[];return l[0]=d(e[n(218)](s[0],s[1])),l[1]=e[n(564)](d,s[2]+s[3]),[e[n(750)],"0000",e[n(750)],e[n(750)],e.MNgOO,e[n(225)],l[0],l[1]][n(247)]("")}function x(a){let n=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(a),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[n(973)](a);return s?u(a):l?e.trjFe(h,a):e[n(207)]}function h(a){let n=t;if(e.dCcPN(n(1759),e[n(1154)])){let s="",l=[],f=0,g=0,v=!0,_=e[n(750)];if(e[n(1321)](a[n(762)]("::"),-1)){let p=a.split("::");for(let C=0;e[n(663)](C,p[n(1270)]);C++){let O=p[C];if(e[n(1321)](O[n(762)](":"),0)){let U=O[n(842)](":");v&&(f=U[n(1270)]),g+=U.length;for(let H=0;e.uwDbd(H,U[n(1270)]);H++)if(e[n(947)](4,U[H][n(1270)])){let ae=_[n(463)+"g"](0,e[n(1808)](4,U[H][n(1270)])),st=ae[n(1730)](U[H]);l[n(394)](st)}else l[n(394)](U[H]);v=!1}else{if(O[n(1270)]!==4){let U=_[n(463)+"g"](0,e[n(1645)](4,O[n(1270)])),H=U[n(1730)](O);l.push(H)}else l.push(O);v&&(f+=1),g+=1,v=!1}}let y="";for(let C=0;e.XStVm(C,8-g);C++)y=y[n(1730)](_);for(let C=0;e.KMIFM(C,l[n(1270)]);C++)e[n(1731)](C,f)?(s=s[n(1730)](y),s=s.concat(l[C])):s=s[n(1730)](l[C]);return s}{let p=a[n(842)](":");for(let y=0;e[n(1164)](y,p[n(1270)]);y++){let C=p[y];if(e.dCcPN(4,p[y][n(1270)]))if(e[n(947)](e[n(1071)],e[n(1342)])){let O=_[n(463)+"g"](0,e[n(1808)](4,p[y][n(1270)])),U=O[n(1730)](C);s=s[n(1730)](U)}else this[n(1782)]&&this[n(1782)][n(1598)](_0x5b431b),this[n(1439)+n(722)][_0xa07f00]=null;else s=s[n(1730)](C)}return s}}else return new _0x442577(_0x10c9d9,{code:_0x3067ee,reason:_0x24e8e3,wasClean:_0x55f20c,willReconnect:_0x1f6831})}function m(a,n){let s=t,l=a[s(488)];e[s(1747)](void 0,l)&&(e.EuqeU(ge,n,10),e[s(942)](G,n,l));let f=a[s(1676)];e[s(947)](void 0,f)&&(e[s(1638)](ge,n,18),e[s(1638)](G,n,f))}function w(a){let n=t,s={};e:for(;!e[n(1022)](V,a);){let l=e[n(805)](pe,a);switch(e[n(1198)](l,3)){case 0:break e;case 1:s[n(488)]=e.FawFp(R,a,e[n(1177)](pe,a));break;case 2:s[n(1676)]=R(a,e[n(413)](pe,a));break;default:e[n(366)](P,a,e.pqNde(7,l))}}if(e[n(1731)](void 0,s[n(488)]))throw new Error("Missing "+n(1123)+n(427)+"key");if(e[n(1731)](void 0,s[n(1676)]))throw new Error(e[n(335)]);return s}function I(a){let n=t,s=e.zACJw(D);return e[n(1656)](b,a,s),e[n(294)](B,s)}function b(a,n){let s=t,l={ozYca:function(f,g){return e[F(1582)](f,g)},snMsc:function(f,g){return f+g},JjQsC:e[s(1272)]};if(e[s(1731)](s(1145),e[s(847)])){if(l[s(646)](l[s(1429)](_0x1ef624[s(1410)],_0x54862f),_0x4b7db2.limit))throw new _0x1d7075(l[s(1315)]);_0x10e951[s(1410)]+=_0x1a68af}else{let f=a.SeqID;e[s(1851)](void 0,f)&&(e[s(829)](ge,n,8),e[s(1054)](wt,n,f));let g=a[s(809)];e[s(947)](void 0,g)&&(e.wtwXY(ge,n,16),e.CtIsf(wt,n,g));let v=a[s(609)];e[s(1781)](void 0,v)&&(e[s(1573)](ge,n,24),wt(n,e.EWOSd(L,v)));let _=a[s(1093)];e.pTwAs(void 0,_)&&(e[s(573)](ge,n,32),e[s(1638)](wt,n,L(_)));let p=a[s(268)];if(e[s(1851)](void 0,p))for(let cn of p){ge(n,42);let dn=e[s(940)](D);m(cn,dn),e[s(1452)](ge,n,dn[s(276)]),e[s(743)](W,n,dn),e[s(1296)](N,dn)}let y=a[s(1309)+"ncoding"];y!==void 0&&(e.FawFp(ge,n,50),e[s(1638)](G,n,y));let C=a["payloadT"+s(597)];e.NBfDZ(void 0,C)&&(ge(n,58),e[s(366)](G,n,C));let O=a[s(1766)];O!==void 0&&(e[s(1638)](ge,n,66),e.nKYuI(ge,n,O[s(1270)]),e[s(1054)](ce,n,O));let U=a[s(761)];e[s(1633)](void 0,U)&&(e[s(1638)](ge,n,74),e.Sbokt(G,n,U));let H=a[s(1408)+s(1047)];e.NBfDZ(void 0,H)&&(e[s(834)](ge,n,82),G(n,H));let ae=a[s(436)];e.TuTBA(void 0,ae)&&(e[s(288)](ge,n,90),e[s(216)](G,n,ae));let st=a[s(939)+"e"];if(st!==void 0)if(e[s(251)](s(606),s(606)))e.bsvSO(ge,n,96),wt(n,e[s(805)](L,st));else return 0}}function S(a){return e.ryQBj(A,z(a))}function A(a){let n=t,s={};e:for(;!e.yGPPe(V,a);){let l=e[n(791)](pe,a);switch(e[n(1556)](l,3)){case 0:break e;case 1:s.SeqID=e[n(447)](kt,a,!0);break;case 2:s[n(809)]=e.mekBy(kt,a,!0);break;case 3:s.service=pe(a);break;case 4:s.method=pe(a);break;case 5:{let f=e[n(575)](k,a);(s[n(268)]||(s[n(268)]=[]))[n(394)](e.yGPPe(w,a)),a[n(276)]=f;break}case 6:s[n(1309)+n(464)]=R(a,pe(a));break;case 7:s["payloadT"+n(597)]=R(a,pe(a));break;case 8:s[n(1766)]=e.PqWkM(oe,a,pe(a));break;case 9:s[n(761)]=e.kzGpp(R,a,e[n(417)](pe,a));break;case 10:s[n(1408)+n(1047)]=e.PqWkM(R,a,e[n(805)](pe,a));break;case 11:s.msgID=e[n(916)](R,a,pe(a));break;case 12:s.frameType=pe(a);break;default:P(a,e[n(617)](7,l))}}if(s.SeqID===void 0)throw new Error("Missing required field: SeqID");if(s[n(809)]===void 0)throw new Error(e.OKHva);if(e[n(251)](void 0,s[n(609)]))throw new Error("Missing required field: service");if(e[n(418)](void 0,s[n(1093)]))throw new Error(e[n(1624)]);return s}function k(a){let n=t,s=e[n(1639)](pe,a),l=a.limit;return a.limit=e[n(1005)](a[n(1410)],s),l}function P(a,n){let s=t;switch(n){case 0:for(;e.NnfNu(128,e.trjFe(ee,a)););break;case 2:e[s(1452)](Y,a,e[s(877)](pe,a));break;case 5:e[s(942)](Y,a,4);break;case 1:e[s(1044)](Y,a,8);break;default:throw new Error(e.stDln+n)}}function L(a){return a|=0,{low:a,high:e.vYxSI(a,31),unsigned:a>=0}}let E=[];function D(){let a=t,n={yhEVo:function(s,l,f){return e[F(829)](s,l,f)},sviLW:e[a(1675)]};if(a(717)!=="giitb"){let s=this[a(1448)][a(808)+a(1409)+a(1313)](_0x5b7d88,_0x24c410);this[a(1575)+a(1488)+a(442)](n.yhEVo(_0x1d4bfc,n.sviLW,{code:_0x2d4546,reason:_0x48d70a,wasClean:!0,willReconnect:s})),s&&this[a(1166)]()}else{let s=E[a(892)]();return s?(s[a(1410)]=s[a(276)]=0,s):{bytes:new Uint8Array(64),offset:0,limit:0}}}function N(a){E.push(a)}function z(a){return{bytes:a,offset:0,limit:a.length}}function B(a){let n=t,s=a[n(1223)],l=a.limit;return e[n(1731)](s[n(1270)],l)?s:s[n(459)](0,l)}function Y(a,n){let s=t;if(e[s(1802)](a.offset,n)>a[s(276)])throw new Error(e.GohpJ);a[s(1410)]+=n}function V(a){let n=t;return a[n(1410)]>=a[n(276)]}function re(a,n){let s=t,l=a[s(1223)],f=a[s(1410)],g=a[s(276)],v=e.GaDxc(f,n);if(v>l[s(1270)]){let _=new Uint8Array(e[s(1566)](2,v));_[s(328)](l),a[s(1223)]=_}return a.offset=v,e[s(1825)](v,g)&&(a.limit=v),f}function Z(a,n){let s=t;if(e[s(807)]===s(777)){let l=a[s(1410)];if(e[s(1321)](e[s(1437)](l,n),a[s(276)]))throw new Error(e.BGFIl);return a[s(1410)]+=n,l}else this[s(1748)+"er"]&&_0x3634af[s(917)+s(1048)](e[s(1709)],this["_handleO"+s(1619)]),this._isBrowser&&_0x11ec52[s(917)+s(1048)](e.RLfSP,this._handleOffLine),this._isBrowser&&_0x571dea["addEvent"+s(1048)](e[s(1610)],this[s(1356)+"ageHide"]),this._isBrowser&&_0x530916[s(917)+s(1048)](e[s(546)],this[s(1356)+s(289)])}function oe(a,n){let s=t,l=e[s(1044)](Z,a,n);return a[s(1223)].subarray(l,e.OVWQN(l,n))}function ce(a,n){let s=t,l=e.GHKXk(re,a,n[s(1270)]);a[s(1223)][s(328)](n,l)}function R(a,n){let s=t,l=e.QpFKf(Z,a,n),f=String[s(928)+s(309)],g=a.bytes,v="\uFFFD",_="";for(let p=0;e[s(780)](p,n);p++){let y=g[e.rTDas(p,l)],C,O,U,H;if(e.xMTqh(e[s(1608)](128,y),0))_+=e[s(1823)](f,y);else if(e[s(1545)](224&y,192))e[s(1057)](e[s(1567)](p,1),n)?_+=v:(C=g[e[s(1449)](e.PBbLr(p,l),1)],e[s(947)](192&C,128)?_+=v:(H=e[s(855)](e[s(540)](31,y),6)|e[s(617)](63,C),H<128?_+=v:(_+=f(H),p++)));else if(e.zHPSw(e.TCnhl(240,y),224))if(p+2>=n)_+=v;else if(C=g[e[s(1465)](e.rDJEd(p,l),1)],O=g[p+l+2],e.FOXRD(e.jYPma(e[s(1518)](C,e[s(532)](O,8)),49344),32896))_+=v;else if(e[s(235)](e[s(1323)],e[s(1725)])){let ae=_0xd961e.charCodeAt(_0x5168b5);e[s(1057)](ae,55296)&&ae<=56319&&e[s(663)](e[s(1079)](_0x23db12,1),_0x46c9a5)&&(ae=e.zmlGP(e[s(532)](ae,10)+_0x4a9e4f[s(884)+"At"](++_0x1e1ea6),56613888)),_0x30b0f4+=e.IdCQN(ae,128)?1:e[s(1812)](ae,2048)?2:e.bjSow(ae,65536)?3:4}else H=e[s(664)](e.VUqfI(e.kKPkb(15,y)<<12,e[s(532)](e.iamsu(63,C),6)),63&O),H<2048||e[s(1057)](H,55296)&&H<=57343?_+=v:(_+=e.qMKkq(f,H),p+=2);else e[s(1673)](248,y)==240?e[s(1057)](p+3,n)?_+=v:(C=g[e.oacfA(e.LpvtK(p,l),1)],O=g[e[s(1690)](e[s(1437)](p,l),2)],U=g[e[s(1449)](p+l,3)],e[s(657)](e[s(688)](e[s(1714)](C,e.nAePU(O,8))|e.NOKCC(U,16),12632256),8421504)?_+=v:(H=e[s(664)](e[s(1714)](e[s(1640)](e[s(764)](7,y)<<18,e[s(941)](e[s(1520)](63,C),12)),e.TlOEA(e[s(764)](63,O),6)),63&U),e[s(1695)](H,65536)||e[s(468)](H,1114111)?_+=v:s(1536)!=="PhNbd"?(this[s(1439)+s(722)][s(658)](),this[s(1439)+"Queue"][s(394)](_0x346371)):(H-=65536,_+=e[s(1008)](f,e[s(1728)](e[s(919)](H,10),55296),e[s(331)](e[s(764)](1023,H),56320)),p+=3))):_+=v}return _}function G(a,n){let s=t,l={cQqez:function(f,g,v){return e[F(423)](f,g,v)},wImhf:e[s(1675)],CLEqx:function(f,g,v){return f(g,v)}};if(s(648)===e[s(902)])return this[s(968)]?e[s(1437)](e.sDOII(this[s(1831)]>>>0,_0x17d182),e.JANJj(this.low,0)):e[s(1437)](e[s(516)](this[s(1831)],_0x172a42),this[s(1496)]>>>0);{let f=n.length,g=0;for(let p=0;e[s(870)](p,f);p++){let y=n[s(884)+"At"](p);e[s(291)](y,55296)&&y<=56319&&e[s(1812)](p+1,f)&&(y=e[s(1654)](e.RQRiJ(e[s(1179)](y,10),n[s(884)+"At"](++p)),56613888)),g+=e[s(663)](y,128)?1:e[s(801)](y,2048)?2:y<65536?3:4}ge(a,g);let v=re(a,g),_=a[s(1223)];for(let p=0;e[s(327)](p,f);p++){let y=n.charCodeAt(p);if(y>=55296&&e[s(1399)](y,56319)&&e[s(1648)](e[s(1079)](p,1),f)&&(y=e.ViUcC(e[s(960)](e[s(969)](y,10),n[s(884)+"At"](++p)),56613888)),y<128)_[v++]=y;else if(e[s(260)](e[s(748)],e[s(1660)]))e[s(870)](y,2048)?_[v++]=e[s(461)](e[s(1736)](e[s(297)](y,6),31),192):(e[s(934)](y,65536)?_[v++]=e[s(1640)](e[s(1608)](e[s(297)](y,12),15),224):(_[v++]=e[s(461)](e[s(1420)](y>>18,7),240),_[v++]=e.bodzM(y>>12&63,128)),_[v++]=e[s(1640)](e[s(1344)](e[s(989)](y,6),63),128)),_[v++]=e.VUqfI(63&y,128);else{if(this["_endpoin"+s(1173)]?.["checkRea"+s(1527)+"es"]()){let O=this[s(1037)+s(1173)]?.[s(1139)+s(768)+"nt"]();this[s(1575)+"hCloseEv"+s(442)](l[s(277)](_0x58b7f9,l[s(970)],{code:1006,reason:"connect "+O+(" timeout"+s(1622)+"tries re"+s(1711)),wasClean:!0}))}else{let O=this[s(1448)][s(808)+s(1409)+s(1313)](_0x39cc89,_0x187364);this[s(1575)+s(1488)+"ent"](l[s(747)](_0x179550,l.wImhf,{code:_0x58c9fc,reason:_0x45f7d6,wasClean:!0,willReconnect:O})),O&&this._connect()}return}}}}function W(a,n){let s=t,l=re(a,n.limit),f=a[s(1223)],g=n[s(1223)];for(let v=0,_=n.limit;e[s(1738)](v,_);v++)f[e.wFnPu(v,l)]=g[v]}function ee(a){let n=t;return a[n(1223)][e[n(681)](Z,a,1)]}function Ve(a,n){let s=t,l=re(a,1);a[s(1223)][l]=n}function pe(a){let n=t,s=0,l=0,f;do f=e[n(351)](ee,a),s<32&&(l|=e[n(1663)](e[n(396)](127,f),s)),s+=7;while(128&f);return l}function ge(a,n){let s=t;for(n>>>=0;e.dvwUl(n,128);)e[s(991)]!==s(1857)?(this[s(1782)]&&this[s(1782)].send(_0x1b01c3),this._debug(s(1091),_0x145a93)):(Ve(a,127&n|128),n>>>=7);e[s(1008)](Ve,a,n)}function kt(a,n){let s=t,l={gKnyo:function(p,y){return e[F(641)](p,y)}},f=0,g=0,v=0,_;if(_=e[s(1517)](ee,a),f=e[s(617)](127,_),128&_&&(_=e.mgwoV(ee,a),f|=e.MOPOa(127&_,7),128&_&&(_=e[s(1724)](ee,a),f|=e[s(941)](e[s(396)](127,_),14),e[s(1088)](128,_))))if(e[s(1804)](e.ozwQO,e[s(239)])){if(_=e[s(1737)](ee,a),f|=e[s(941)](e.pQsuK(127,_),21),128&_&&(_=e[s(791)](ee,a),g=e[s(712)](127,_),e.TTGeC(128,_))){if(e.kZhla(e[s(215)],e[s(215)]))eFeJkP[s(610)](_0x59b80e,_0x5e5624[s(1229)]),_0x1969e1();else if(_=e.WNpfY(ee,a),g|=e[s(1336)](e[s(846)](127,_),7),e[s(1302)](128,_)&&(_=e.kGUji(ee,a),g|=e[s(941)](e.GoGer(127,_),14),128&_&&(_=e.VvdtJ(ee,a),g|=e.CnJQN(e[s(769)](127,_),21),e[s(764)](128,_))))if(e[s(1694)](e[s(843)],e[s(843)])){let p={JBMYX:s(1229),upJvL:function(y,C,O){return y(C,O)},XySuV:s(324)};_0xecb416[s(322)]()[s(1758)](()=>{let y=s,C=_0x2ceaaa(p.JBMYX,{message:this[y(1207)+y(1623)+y(938)](_0x3bfa88)});this.emit(p[y(1557)],C);let O=p[y(1338)](_0x4ff029,p.XySuV,{reason:this[y(1207)+y(1623)+"age"](_0x154f98)});this[y(1318)](p[y(1752)],O)})}else _=e.TIbwE(ee,a),v=e[s(1736)](127,_),128&_&&(_=e[s(575)](ee,a),v|=e[s(611)](e.hGQNI(127,_),7))}}else _0x160921+=e[s(357)](_0x5a1e56,_0x207b6d),_0x1c5caf++;return{low:f|g<<28,high:e[s(1773)](e.OjQNe(g,4),v<<24),unsigned:n}}function wt(a,n){let s=t,l=e[s(1556)](n[s(1496)],0),f=e.nNfUd(e[s(1714)](e[s(1198)](n.low,28),e[s(1663)](n[s(1831)],4)),0),g=e.vUCCH(n[s(1831)],24),v=e[s(583)](0,g)?e[s(1731)](0,f)?e[s(1738)](l,16384)?l<128?1:2:l<2097152?3:4:e[s(663)](f,16384)?e[s(1376)](f,128)?5:6:e[s(254)](f,2097152)?7:8:e.Szpqc(g,128)?9:10,_=e.CtIsf(re,a,v),p=a.bytes;switch(v){case 10:p[_+9]=e[s(688)](g>>>7,1);case 9:p[_+8]=e[s(1694)](9,v)?e.pFfjH(128,g):127&g;case 8:p[e[s(950)](_,7)]=e[s(869)](8,v)?e.WYkTr(e[s(599)](f,21),128):e[s(1556)](f,21)&127;case 7:p[_+6]=e[s(1633)](7,v)?e[s(863)](e[s(1749)](f,14),128):e[s(961)](f>>>14,127);case 6:p[e[s(218)](_,5)]=e[s(260)](6,v)?e[s(799)](f,7)|128:e[s(800)](f>>>7,127);case 5:p[e[s(1802)](_,4)]=e[s(282)](5,v)?128|f:e.pqNde(127,f);case 4:p[e[s(1860)](_,3)]=v!==4?l>>>21|128:e[s(1556)](l,21)&127;case 3:p[e[s(1049)](_,2)]=e[s(657)](3,v)?e.yCRcq(e[s(1512)](l,14),128):e.VevhE(e[s(1548)](l,14),127);case 2:p[e.qySrK(_,1)]=e[s(1781)](2,v)?e[s(959)](e[s(1576)](l,7),128):e.ZqXuI(l>>>7,127);case 1:p[_]=e[s(947)](1,v)?e[s(1642)](128,l):127&l}}function rn(a){return e[t(627)](S,a)}function Ut(a){return e[t(1737)](I,a)}let sn=65536,ei=t(779),_e=sn*sn,ke=_e*_e,rr=ke/2,Le=String.prototype[t(884)+"At"];class he{constructor(n,s,l){let f=t;this[f(453)]=!0,this.low=e[f(522)](0,n),this[f(1831)]=e[f(1773)](0,s),this[f(968)]=!!l}static isLong(n){let s=t;return n&&e.YPvat(!0,n[s(453)])}static[t(1130)](n,s,l){let f=t;return e[f(383)](e[f(566)],e[f(871)])?{bytes:_0x14d193,offset:0,limit:_0x20ba5a[f(1270)]}:new he(n,s,l)}static[t(498)+"s"](n,s,l){let f=t;return l?he[f(498)+f(812)](n,s):he[f(498)+f(1727)](n,s)}static[t(498)+t(812)](n,s){let l=t;return new he(e[l(1714)](n[0]|e[l(1312)](n[1],8),e[l(1663)](n[2],16))|n[3]<<24,e[l(1714)](e[l(1103)](e[l(888)](n[4],e[l(855)](n[5],8)),e[l(1368)](n[6],16)),n[7]<<24),s)}static[t(498)+t(1727)](n,s){let l=t;if(e.YPvat(e[l(234)],l(642)))_0x41debd(this,_0x391953,[_0x1529be,_0x163959,_0x3a0fdc,_0x545bb7,_0x3dc621,_0xbaec28]);else return new he(e.fJWnC(e.CEZgv(e[l(1640)](n[4]<<24,e[l(855)](n[5],16)),n[6]<<8),n[7]),e[l(522)](e[l(495)](e.batkO(e[l(784)](n[0],24),e[l(770)](n[1],16)),e.MOPOa(n[2],8)),n[3]),s)}static[t(386)](n){let s=t;return e[s(1731)](n,ei)?dl:new he(e.BHeHD(e[s(461)](e[s(392)](e.YrhAW(Le[s(1417)](n,0),e[s(1161)](Le[s(1417)](n,1),8)),e[s(532)](Le[s(1417)](n,2),16)),Le[s(1417)](n,3)<<24),0),e.WYkTr(e[s(1578)](e.oUCyB(Le[s(1417)](n,4),Le.call(n,5)<<8),Le.call(n,6)<<16),Le[s(1417)](n,7)<<24)>>>0,!0)}[t(1407)](){let n=t;return String[n(928)+n(309)](255&this.low,e[n(1420)](this.low>>>8,255),e[n(1631)](this.low,16)&255,e.mjyOo(this[n(1496)],24),255&this.high,e[n(1088)](e[n(1841)](this[n(1831)],8),255),e[n(1204)](e[n(824)](this[n(1831)],16),255),e.zZPVe(this.high,24))}static[t(1603)+"er"](n,s=!0){let l=t;if(isNaN(n))return s?Qp:dl;if(s){if(e.rvcBV(n,ke))return tg}else{if(e[l(1399)](n,-rr))return ng;if(n+1>=rr)return eg}return he.fromBits(e[l(503)](n%_e,0),e.ItfkP(n,_e)|0,s)}[t(1224)](){let n=t;return e.oPwuA(e[n(552)],e[n(637)])?this.unsigned?e[n(1262)](e[n(669)](e[n(824)](this.high,0),_e),e[n(1308)](this.low,0)):e[n(1437)](e[n(669)](this[n(1831)],_e),e.iDXVN(this[n(1496)],0)):_0xb21fab["objectSt"+n(605)]||_0x186590[n(1463)](_0x20e5a1)}[t(508)](){let n=t;return e[n(1731)](0,this[n(1831)])&&e[n(844)](0,this[n(1496)])}[t(665)](n){let s=t;he[s(453)](n)||(n=he[s(1603)+"er"](n));let l=e[s(1198)](this[s(1831)],16),f=e[s(1344)](65535,this[s(1831)]),g=this.low>>>16,v=e[s(1768)](65535,this.low),_=e[s(599)](n.high,16),p=e[s(333)](65535,n.high),y=e[s(1298)](n[s(1496)],16),C=e[s(686)](65535,n[s(1496)]),O=0,U=0,H=0,ae=0;return ae+=v+C,H+=e.aQHHI(ae,16),ae&=65535,H+=g+y,U+=e[s(724)](H,16),H&=65535,U+=e.dVfxC(f,p),O+=e[s(1548)](U,16),U&=65535,O+=l+_,O&=65535,he[s(1130)](H<<16|ae,e[s(461)](e[s(1805)](O,16),U),this[s(968)])}[t(208)](n){let s=t;return he.isLong(n)||(n=he.fromNumber(n)),e[s(1553)](this[s(968)],n[s(968)])&&e[s(235)](e[s(1741)](this[s(1831)],31),1)&&e[s(683)](e[s(1298)](n[s(1831)],31),1)?!1:e.LvbsS(this.high,n[s(1831)])&&this[s(1496)]===n[s(1496)]}addOne(){let n=t;if(e[n(383)](e.HfwDo,e[n(1250)]))return e[n(844)](-1,this.low)&&e[n(844)](-1,this.high)?he[n(1130)](0,0,this[n(968)]):e[n(952)](-1,this[n(1496)])?he[n(1130)](0,e[n(1009)](this[n(1831)],1),this[n(968)]):he[n(1130)](e[n(1094)](this[n(1496)],1),this[n(1831)],this[n(968)]);{let s=new _0x4eec46(e[n(1737)](_0x43110e,_0x53d57d));return e.tkVfB(_0x3d663b,_0x5ec717,s,0),s}}[t(1436)](n){let s=t;return e.nVDju(e[s(1718)],e.yzwsd)?n?this[s(1252)+"E"]():this[s(1734)+"E"]():"frontier_"+this._DBName}[t(1252)+"E"](){let n=t;if(e[n(1243)](e.KgEww,"UhoXn")){let s=this[n(1831)],l=this[n(1496)];return[e[n(1204)](255,l),e.cHUhi(e[n(1235)](l,8),255),e.dwYRd(l,16)&255,e[n(1171)](l,24),e[n(481)](255,s),e[n(617)](e[n(430)](s,8),255),e[n(945)](s,16)&255,s>>>24]}else{let s=e[n(1532)][n(842)]("|"),l=0;for(;;){switch(s[l++]){case"0":_0x2fd2d3[_0x23c5d1[e[n(527)]]=5002]=n(1040)+"NG_ERROR";continue;case"1":_0x467d7a[_0x2c8533[e[n(1370)]]=5003]=e[n(1370)];continue;case"2":_0x4c90eb[_0xa8fdbf[e.Aelfs]=5004]=n(608)+n(1440);continue;case"3":_0x37af90[_0x83fe06.OPEN_ERROR=5005]=e[n(1839)];continue;case"4":_0x57534f[_0x5e104b[n(1386)+n(901)]=5001]=e.eCPLH;continue;case"5":return _0x2f2b88}break}}}[t(1734)+"E"](){let n=t,s={ezdba:function(l,f,g){return e[F(288)](l,f,g)}};if(e[n(1735)]!==n(882)){let l=this[n(1831)],f=this[n(1496)];return[e[n(794)](l,24),e[n(1576)](l,16)&255,e[n(848)](l,8)&255,e[n(838)](255,l),e[n(1703)](f,24),e[n(1682)](e.PAsne(f,16),255),f>>>8&255,e.jYPma(255,f)]}else _0xc5cbae(_0x1397f6,82),HWoOMj.ezdba(_0x2dcdc4,_0x3238b1,_0x1575b4)}}let dl=new he(0,0,!1),Qp=new he(0,0,!0),eg=he[t(1130)](-1,2147483647,!1),tg=he[t(1130)](-1,-1,!0),ng=he[t(1130)](0,-2147483648,!1);var on=(function(a){let n=t,s=(n(1052)+n(1010))[n(842)]("|"),l=0;for(;;){switch(s[l++]){case"0":a[a[n(608)+"ERROR"]=5004]=e[n(429)];continue;case"1":return a;case"2":a[a["NATIVE_E"+n(901)]=5001]=e[n(477)];continue;case"3":a[a[e[n(1370)]]=5003]=e.yEfvd;continue;case"4":a[a[e[n(527)]]=5002]=e[n(527)];continue;case"5":a[a[n(1038)+"OR"]=5005]=e[n(1839)];continue}break}})({});class ir{constructor(n){let s=t,l={bHvxJ:function(f,g){return e[F(1753)](f,g)},NrJaY:function(f,g){return e.XOwsn(f,g)}};if(e[s(282)](e[s(1095)],e.NXGaf))return VzjxkV.bHvxJ(VzjxkV.NrJaY(1e4,_0x2aaea4[s(713)]()),_0x216350[s(927)](1e4*_0x2357eb[s(975)]()));this[s(1102)]=n,this[s(574)]=null}}class ll extends ir{constructor(n,s){let l=t;super(n),this[l(1153)]=s&&s[l(1153)]||null}}class ul extends ir{constructor(n,s){let l=t,f=e[l(579)][l(842)]("|"),g=0;for(;;){switch(f[g++]){case"0":this.error=s&&s.error||null;continue;case"1":this[l(1392)]=s&&s[l(1392)]||0;continue;case"2":this[l(275)]=s&&s[l(275)]||5001;continue;case"3":super(n);continue;case"4":this[l(1136)]=s&&s[l(1136)]||0;continue;case"5":this[l(679)]=s&&s[l(679)]||"";continue;case"6":this.message=s&&s[l(1153)]||"";continue}break}}}class fl extends ir{constructor(n,s){let l=t,f=e.wldEb.split("|"),g=0;for(;;){switch(f[g++]){case"0":this[l(1170)+"nnect"]=s&&s[l(1170)+l(811)]||!1;continue;case"1":this[l(275)]=s&&s.code||0;continue;case"2":this[l(971)]=s&&s.wasClean||!1;continue;case"3":this[l(576)]=s&&s[l(576)]||"";continue;case"4":super(n);continue}break}}}class xl extends ir{constructor(n,s){let l=t;super(n),this[l(1078)]=s&&s.data||null}}class hl extends xl{constructor(n,s){let l=t;super(n),this[l(1078)]=s&&s[l(1078)]||null,this[l(1153)]=s&&s[l(1153)]||null}}class pl extends ir{constructor(n,s){let l=t;super(n),this[l(1078)]=s&&s.data||null}}function lt(a,{message:n,code:s,error:l}){return new ul(a,{message:n,code:s,error:l})}function _t(a,{code:n,reason:s,wasClean:l,willReconnect:f}){return new fl(a,{code:n,reason:s,wasClean:l,willReconnect:f})}function gl(a,{data:n,message:s}){return new hl(a,{data:n,message:s})}function ml(a,{data:n}){return new pl(a,{data:n})}function ba(a,{message:n}){return new ll(a,{message:n})}class wl{constructor(n,s){let l=t;this[l(1217)+"s"]=n,this[l(1513)+"es"]=s,this["currentI"+l(544)]=0,this[l(913)+l(398)+"riesCount"]=0}["resetEndpointCon"+t(1084)](){let n=t;if(e[n(776)](e.OoGJH,e[n(1811)]))this[n(930)+"ndex"]=0,this[n(913)+"ndpointTriesCount"]=0;else return!!this[n(505)]}[t(1580)+"es"](){let n=t;this[n(913)+n(398)+n(1292)+"t"]=0}[t(1139)+"ntEndpoint"](){let n=t;return this[n(1217)+"s"][this[n(930)+"ndex"]]}["getCurrentEndpoi"+t(1777)+"ount"](){let n=t;return this[n(913)+"ndpointT"+n(1292)+"t"]}[t(261)+t(1527)+"es"](){let n=t;return!!(this[n(930)+n(544)]>=this[n(1217)+"s"][n(1270)]||e[n(1238)](this[n(930)+"ndex"],e[n(708)](this[n(1217)+"s"].length,1))&&e[n(1545)](this[n(913)+n(398)+n(1292)+"t"],this[n(1513)+"es"]))}["checkCur"+t(514)+t(306)+t(593)+t(997)](){let n=t;return e[n(1607)](this[n(930)+n(544)],this.endpoints[n(1270)])?!0:e[n(295)](this[n(913)+"ndpointTriesCount"],this[n(1513)+"es"])}[t(448)+t(1423)+t(1686)+t(589)+"unt"](){let n=t;return this[n(913)+n(398)+n(1292)+"t"]=1,this[n(930)+n(544)]++,this[n(1217)+"s"][this[n(930)+n(544)]]}[t(1139)+t(768)+t(506)+t(600)](){let n=t;return this[n(913)+n(398)+n(1292)+"t"]++,this[n(1139)+n(768)+"nt"]()}}let sr=(e.olBnK(e.viCPr,typeof globalThis)&&t(881)===globalThis["construc"+t(1197)][t(633)]||e.NsBjY(t(1637)+"d",typeof window)&&e.dYmNr===window[t(1447)+t(1197)][t(633)])&&e[t(1077)](e[t(1852)],typeof document),Rn=e.TeQup(e.viCPr,typeof globalThis)&&(e[t(1375)](e.rgRke,globalThis[t(1447)+t(1197)][t(633)])||e[t(1267)](e[t(1358)],globalThis[t(1447)+"tor"][t(633)]))&&e[t(244)](e[t(1852)],typeof tt),ti=(e[t(1480)](t(1637)+"d",typeof globalThis)&&e[t(1283)](e[t(1509)],globalThis[t(1447)+"tor"][t(633)])||e[t(831)](e[t(1852)],typeof globalThis)||e[t(484)](e[t(1852)],typeof globalThis)&&!!globalThis[t(1595)+t(1817)])&&e.kExrs(t(1637)+"d",typeof wx),ni=e[t(926)](t(1637)+"d",typeof globalThis)&&(e[t(1238)](e[t(1358)],globalThis["construc"+t(1197)].name)||e.CLMGL===globalThis[t(1447)+t(1197)][t(633)]||e[t(439)](e[t(1669)],globalThis[t(1447)+t(1197)][t(633)]))&&e.Eljau(e[t(1852)],typeof self),rg=e.Amdqr(e[t(1852)],typeof globalThis)&&e[t(1267)](t(1599),globalThis[t(1447)+t(1197)][t(633)])&&e[t(407)](e.viCPr,typeof global)&&e.rgRke===global[t(1447)+"tor"].name&&e[t(1477)](e.viCPr,typeof process)&&!!process[t(214)];class Ea{constructor(){let n=t,s={cOgRE:function(l,f){return e.LvbsS(l,f)},eMQiE:e[n(1152)],mugKl:e[n(1554)],GnKlb:function(l,f,g){return e[n(743)](l,f,g)},AGoHQ:function(l,f){return l===f},TmGcj:function(l,f,g,v){return e[n(1046)](l,f,g,v)}};if(e[n(1837)](e[n(948)],n(1596))){let{pingInterval:l,pingFrequency:f}=this[n(1448)];if((_0xe0276d.data==="hi"&&s[n(542)](s[n(1192)],f)||s[n(1208)]===f)&&(this[n(689)+n(1289)](),this.emit(n(1045)+n(920)+"s",n(707)),this[n(602)+n(1135)+"Id"]=s.GnKlb(_0x7e2897,this[n(1531)][n(415)](this),l)),s.AGoHQ("hi",_0x2f3446[n(1078)]))return;try{s[n(501)](_0x3785a9,this,_0x4d1861,[_0x14e45c,_0x10c779,_0x17b070,_0x5c39b3,_0x2eca91,_0x2fe06c])}catch(g){let v=s[n(580)](_0x4e17f7,"error",{message:g[n(1153)],code:_0x2900a4[n(608)+n(1440)],error:g});this["_dispatc"+n(1836)+n(442)](v)}}else this[n(825)+"rs"]={}}[t(1318)](n,...s){let l=t;if(e[l(1340)]==="ilyoF"){let f=this[l(825)+"rs"][n];if(f)f.slice().forEach(g=>g.fn.apply(g[l(709)],s));else if(e[l(583)](e[l(1297)],n)&&!this[l(955)]){let g=s[l(1270)]&&s[0];if(e.HSWDi(g,Error))throw g;let v=new Error(e[l(414)](e[l(1016)],g?e[l(1860)](e[l(1701)](" (",g[l(1153)]),")"):""));throw v.context=g,g}return this}else return this[l(1782)]?this[l(1782)].url:this[l(543)]}[t(1107)](n,s){let l=t,f={rEMDC:function(g,v){return e[F(1402)](g,v)},BYDql:function(g,v){return e.YGesZ(g,v)},CWTOv:function(g,v){return g===v}};if(e[l(372)](e[l(1809)],e[l(1809)])){if(n===void 0)this[l(825)+"rs"]={};else if(e[l(251)](void 0,s))this._listeners[n]=null;else{let g=this[l(825)+"rs"][n];if(g)for(let v=0;v<g[l(1270)];)g[v].fn===s?g.splice(v,1):++v}return this}else return _0x3b53bc.isLong(_0x2c8ce)||(_0x1cedd5=_0x1e127f.fromNumber(_0x4a1241)),cyijWT[l(1614)](this[l(968)],_0x4b78b6[l(968)])&&cyijWT[l(1552)](this[l(1831)],31)===1&&cyijWT.CWTOv(cyijWT[l(1552)](_0x1007cb[l(1831)],31),1)?!1:cyijWT[l(232)](this[l(1831)],_0x3559ea[l(1831)])&&cyijWT[l(232)](this[l(1496)],_0x4b4492[l(1496)])}on(n,s,l){let f=t;return(this._listeners[n]||(this._listeners[n]=[]))[f(394)]({fn:s,ctx:l||this}),this}}class ig extends Ea{[t(1207)+t(1623)+t(938)](n){let s=t;return n[s(534)]||n[s(1659)]?(s(338)+" "+(n[s(534)]||"")+" code: "+(n[s(1659)]||""))[s(1394)]():JSON[s(1450)+"y"](n)}constructor(n,s,l){let f=t;super(),this[f(1588)]=null,ti&&wx[f(1770)+f(1033)]&&(this[f(1588)]=wx[f(1770)+"ocket"]({url:n,protocols:s,header:l,fail:this["_createS"+f(671)+f(1280)][f(415)](this),success:this[f(380)+f(1484)+f(441)+f(836)][f(415)](this)})),Rn&&tt[f(1770)+f(1033)]&&(this[f(1588)]=tt[f(1770)+f(1033)]({url:n,protocols:s,header:l,fail:this["_createS"+f(671)+f(1280)].bind(this),success:this["_createS"+f(1484)+"cessHand"+f(836)][f(415)](this)}))}[t(380)+t(1484)+"cessHand"+t(836)](){let n=t;Promise[n(322)]()[n(1758)](()=>{let s=n;this[s(1216)+s(1006)]()})}["_createS"+t(671)+t(1280)](n){let s=t,l={mPsNM:function(f,g,v){return e.OyaXT(f,g,v)},CfKLn:e.rlNRt,xLYOS:e[s(1675)]};Promise[s(322)]()[s(1758)](()=>{let f=s,g=l[f(993)](lt,l[f(1185)],{message:this[f(1207)+f(1623)+"age"](n)});this[f(1318)](l[f(1185)],g);let v=l[f(993)](_t,l[f(371)],{reason:this["_formatE"+f(1623)+f(938)](n)});this[f(1318)](l[f(371)],v)})}["_addWsLi"+t(1006)](){let n=t,s={XQUne:n(1153),RfFMe:function(l,f,g){return l(f,g)},oznfH:function(l,f,g){return e[n(1638)](l,f,g)}};this._socket[n(491)](l=>{let f=n;if(e[f(1402)](e[f(1245)],e[f(1245)]))return this._qosDB?.[f(1463)](_0x47aab9);this[f(1318)](e[f(1772)],ml(e[f(1772)],{...l,data:l.errMsg||""}))}),this[n(1588)][n(1864)](l=>{let f=n;this[f(1318)](e[f(1675)],e[f(1014)](_t,e.FrXxQ,{...l}))}),this[n(1588)][n(858)+"e"](l=>{let f=n;this[f(1318)](s[f(1400)],s[f(1723)](gl,s.XQUne,{...l}))}),this[n(1588)][n(721)](l=>{let f=n;this[f(1318)](f(1229),s[f(666)](lt,f(1229),{...l,message:l[f(534)]||""}))})}[t(1598)](n){let s=t,l={DFmoc:e[s(1297)],lYUWh:function(f,g,v){return e[s(1142)](f,g,v)},oqmSD:function(f,g,v){return e[s(942)](f,g,v)}};if(e.dleRe(n,Uint8Array)){let f=n.buffer[s(624)](n.byteOffset,e[s(960)](n[s(1507)+"th"],n[s(992)+"et"]));this[s(1588)]&&this[s(1588)][s(1598)]({data:f,fail:g=>{let v=s;this[v(1318)](l[v(1462)],l[v(229)](lt,v(1229),{message:this[v(1207)+"rrorMess"+v(938)](g)}))}})}else this[s(1588)]&&this[s(1588)][s(1598)]({data:n,fail:f=>{let g=s;this.emit(g(1229),l.oqmSD(lt,l[g(1462)],{message:this._formatErrorMessage(f)}))}})}[t(324)](n,s){let l=t;this[l(1588)]&&this[l(1588)][l(324)]({code:n,reason:s})}[t(917)+t(1048)](n,s){this.on(n,s)}["removeEventListe"+t(376)](n,s){this[t(1107)](n,s)}get[t(980)+"te"](){let n=t;return this._socket[n(980)+"te"]}get[t(1854)+"pe"](){let n=t;return this._socket[n(1854)+"pe"]}set[t(1854)+"pe"](n){}get[t(616)](){let n=t;return this[n(1588)][n(616)]}get[t(1472)](){let n=t;return this[n(1588)][n(1472)]}get[t(635)+"ns"](){let n=t;return this[n(1588)][n(635)+"ns"]}get[t(1443)+t(1696)](){return 0}}function sg(a,n){let s=t;if(n)return new n(a.url,a[s(1472)]);if(e.eWGrM(ti,Rn))return new ig(a.url,a[s(1472)],a[s(268)]);if(e[s(1196)](sr,ni)&&e[s(1707)](s(1637)+"d",typeof WebSocket)&&WebSocket)return new WebSocket(a.url,a[s(1472)+"s"])}function og(a){let n=t,s=e.NtmLC.split("|"),l=0;for(;;){switch(s[l++]){case"0":if(Rn&&tt[n(1770)+"ocket"])return!0;continue;case"1":if(a)return!0;continue;case"2":return!1;case"3":if(ti&&wx[n(1770)+n(1033)])return!0;continue;case"4":if(e[n(911)](sr,ni)&&e[n(1707)](e[n(1852)],typeof WebSocket)&&WebSocket)return!0;continue}break}}function _l(a,n,s){let l=t,f={FkRMZ:l(1780)+l(943)+l(1697)+l(287)+l(240),nHnTZ:function(g,v){return g===v},pvrjn:function(g,v){return g+v}};if(e.KGYhy(e[l(1783)],e[l(1783)]))return this[l(505)][l(1717)];{let g=-1;async function v(_){let p=l;return _<=g?Promise[p(283)](new Error(f.FkRMZ)):(g=_,f[p(497)](_,s[p(1270)])?Promise[p(322)]():s[_].bind(a)(n,v[p(415)](null,f.pvrjn(_,1))))}v(0)}}function yl(a){let n=t,s={SYQns:e[n(1675)]},l=0,f=0;for(let g=0;e[n(1499)](g,a.length);++g)e[n(308)](e.tDDQb,e[n(1007)])?(f=a.charCodeAt(g),e[n(254)](f,128)?l+=1:e[n(1648)](f,2048)?l+=2:e.xEAFq(e[n(1422)](64512,f),55296)&&e.CvCuf(e.iCpYj(64512,a[n(884)+"At"](e[n(1515)](g,1))),56320)?e.XubLw(e[n(999)],n(766))?(++g,l+=4):(this[n(453)]=!0,this[n(1496)]=0|_0xfb0959,this[n(1831)]=0|_0xef6a74,this[n(968)]=!!_0x29279a):l+=3):(_0x4e95ec&&_0x3e2f20[n(917)+"Listener"](RlCvfU[n(1587)],()=>_0x460fcc()),_0x416b24&&_0x1f4fee[n(917)+n(1048)](n(1708)+n(830),()=>_0x56dfa1()));return l}function bl(a,n,s){let l=t,f={QZXhj:function(v,_){return e[F(1158)](v,_)},gTVud:function(v,_){return e[F(231)](v,_)},svYDm:function(v,_,p){return e[F(1258)](v,_,p)},KjRqH:function(v,_){return e[F(1225)](v,_)},yeQyt:function(v,_){return e[F(611)](v,_)}};if(e.ViUcC(s,n)<1)return"";let g="";for(let v=n;e[l(1830)](v,s);)if(e[l(421)](e[l(835)],"YHnIR")){let _=a[v++];if(e[l(1399)](_,127))g+=String[l(928)+l(309)](_);else if(e[l(704)](_,192)&&e[l(443)](_,224))g+=String["fromChar"+l(309)](e[l(1773)](e[l(1362)](e.HkJSx(31,_),6),e[l(1248)](63,a[v++])));else if(e.opTfO(_,224)&&e.xbSEA(_,240))g+=String["fromChar"+l(309)](e[l(1518)](e[l(1103)](e[l(770)](15&_,12),e[l(1362)](e.gjNAb(63,a[v++]),6)),e.iLztW(63,a[v++])));else if(_>=240){let p=e.uARTM(e[l(1634)](e[l(409)](e[l(623)](e[l(1312)](7&_,18),e[l(1368)](e[l(622)](63,a[v++]),12)),e[l(454)](e[l(1520)](63,a[v++]),6)),e[l(688)](63,a[v++])),65536);g+=String[l(928)+l(309)](55296+e[l(297)](p,10)),g+=String[l(928)+l(309)](e.sWtCi(56320,e[l(1601)](1023,p)))}}else{let _=0,p=_0x184e02,y=f[l(1259)](_0x3f8fcd,4);for(;f[l(1239)](p,y);){let{value:C,offset:O}=f[l(1784)](_0x59b31c,_0x210f24,p);p=O,_=f[l(1251)](f[l(1863)](_,8),0),_+=C}return{value:_,offset:y}}return g}function va(a,n,s){let l=t,f={gzOVn:function(p,y,C,O,U){return e[F(1558)](p,y,C,O,U)},jTdMo:function(p,y){return e.mKZzR(p,y)},OfWlt:function(p,y){return e[F(1823)](p,y)},QOwxy:e[l(359)]},g=s,v,_;for(let p=0;e[l(801)](p,a[l(1270)]);++p)if(v=a[l(884)+"At"](p),v<128)n[s++]=v;else if(e[l(1026)](v,2048))n[s++]=e[l(919)](v,6)|192,n[s++]=e[l(1568)](e[l(758)](63,v),128);else if(e.iLcXS(e.hsXSK(64512,v),55296)&&e[l(1306)](e[l(333)](64512,_=a.charCodeAt(p+1)),56320))if(e.LvbsS(e[l(1704)],e[l(510)]))_0x4de9bc[l(917)+l(1048)](uGmNmF[l(1786)],y=>{let C=l;uGmNmF.gzOVn(_0x19517e,uGmNmF[C(603)](_0x50b186,_0x44ed0c[C(528)]),y.oldVersion,y[C(280)+"on"],uGmNmF[C(1840)](_0x3da8e6,_0x389592[C(918)+C(1519)]))});else{let y=e.SJKuD[l(842)]("|"),C=0;for(;;){switch(y[C++]){case"0":++p;continue;case"1":n[s++]=v>>18|240;continue;case"2":n[s++]=e[l(522)](e[l(755)](63,v),128);continue;case"3":n[s++]=e[l(1642)](e[l(1034)](v>>12,63),128);continue;case"4":n[s++]=e[l(919)](v,6)&63|128;continue;case"5":v=e[l(833)](e[l(388)](65536,e[l(440)](1023&v,10)),e.KMlZN(1023,_));continue}break}}else n[s++]=e[l(522)](v>>12,224),n[s++]=e[l(1801)](e.MQNzI(e[l(420)](v,6),63),128),n[s++]=e[l(1256)](e[l(893)](63,v),128);return e[l(1654)](s,g)}async function El(a){let n=t,s={PRQte:function(l,f){return e[F(708)](l,f)}};if(e.WHBlo==typeof a)if(e.XubLw(e[n(1053)],n(1121))){let l=_0xf412c[n(463)+"g"](0,fyUBai[n(1641)](4,_0x19debb[_0x239230][n(1270)])),f=l.concat(_0x2a080b);_0x3d9df2=_0x40a5e4[n(1730)](f)}else{let l=new Uint8Array(e.mKZzR(yl,a));return va(a,l,0),l}return e[n(887)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[n(1572)],a[n(992)+"et"],a.byteLength)}function ag(a){let n=t;try{return e.NsBjY(e[n(520)],typeof a)&&(a instanceof ArrayBuffer||a[n(1572)]&&e[n(1546)](a[n(1572)],ArrayBuffer))||e.NsBjY(e[n(520)],typeof a)?"":(JSON[n(1056)](a),e[n(1128)])}catch{return e.WHBlo==typeof a?n(1011)+n(381)+n(1616):""}}let cg=(a,n)=>{let s=t,l={tXiPQ:function(f,g){return e[F(1475)](f,g)},XqXGP:function(f,g,v){return e.zYVNI(f,g,v)}};switch(a){case e[s(912)]:case s(1672):return{["x-use-"+a]:1,"x-tt-env":n};default:return{}}};class dg{constructor(n){let s=t;this[s(880)+"ount"]=n,this.count=0}addCount(){let n=t;if(e[n(583)](e[n(1268)],e[n(1268)]))this.count++;else{let s=0,l=[];for(;e[n(1164)](s,_0x211fdb.byteLength);){let{offset:f}=e[n(1008)](_0x8a717a,_0x18d70f,s);s=f;let g={cursor_name:"",cursor:0,service:0},{value:v,offset:_}=_0x350687(_0x5b57a1,s);g[n(609)]=v,s=_;let{value:p,offset:y}=e.zdOio(_0x56e80c,_0x480e98,s);s=y,g[n(879)+"ame"]=e[n(1530)](_0x4d3935,_0x42d0e4,s,e[n(385)](s,p)),s+=p;let{value:C,offset:O}=_0x1811e0(_0xcdc765,s);g.cursor=C[n(1224)](),s=O,l[n(394)](g)}return l}}[t(261)+"chMaxCount"](){let n=t;return e[n(693)](this[n(996)],this[n(880)+n(957)])}[t(1273)+"nter"](n=0){let s=t;this[s(880)+s(957)]=n,this[s(996)]=0}}async function lg(a){let n=t,s={LuYRF:function(l,f){return e.mgwoV(l,f)},igamE:e[n(1041)],AUyxp:function(l,f,g,v){return e[n(1046)](l,f,g,v)},Hofxw:function(l,f){return e[n(257)](l,f)},huwSJ:function(l,f){return e.eBxXC(l,f)},btZSl:function(l,f){return e[n(1520)](l,f)},Yihsr:function(l,f){return e[n(1485)](l,f)},CBFdP:e[n(738)],UQsbn:e[n(1361)],PursO:e[n(1343)],pwBsc:e[n(1118)],DAgEe:function(l,f){return e[n(1545)](l,f)},wbEVn:e[n(1249)],NTNxm:function(l,f){return l(f)}};return new Promise(l=>{let f=n,g={rqgVK:function(_,p){return s[F(1367)](_,p)},SAkmw:function(_,p){return s[F(1792)](_,p)},fhZDF:function(_,p){return s[F(1491)](_,p)},zoeKo:function(_,p){return s.LuYRF(_,p)},fiZFM:function(_,p){return _<<p}};if(s.Yihsr(s[f(839)],s.CBFdP)){if(!sr)return s[f(667)](l,s[f(1051)]);try{let _=document[f(896)+f(1106)](f(545));window.frontierJSONP=p=>{let y=f;document[y(1455)][y(1461)+"ild"](_),window[y(731)+y(1388)]=void 0,s[y(667)](l,p&&p[y(1651)]||s[y(1051)])},_.type=s[f(237)],_[f(1625)]=a.replace(/^ws/,s[f(1226)])+s[f(804)];try{s[f(305)](s[f(1032)],s[f(1032)])?document[f(1455)]["appendCh"+f(821)](_):(_0x3ef61a=_0x338d45(_0x30a5ee),_0x38d801|=xmcoTK[f(706)](127&_0x263e62,21),xmcoTK[f(293)](128,_0x5484a4)&&(_0x47d14c=_0x455bf6(_0x51226f),_0x11a397=xmcoTK[f(1002)](127,_0x428546),128&_0x1139c4&&(_0x2e93f9=xmcoTK[f(352)](_0x566484,_0xf59a85),_0x335be5|=xmcoTK[f(343)](xmcoTK[f(293)](127,_0x370294),7))))}catch{document[f(1455)][f(1461)+"ild"](_)}}catch{window["frontier"+f(1388)]=void 0,s[f(1018)](l,f(549)+f(576))}}else for(var v in _0xe459c0)SaPLxt[f(325)](_0x391791,_0x7bbd4d,v,{get:_0x19d6cb[v],enumerable:!0})})}function an(a,n,s){return!!a?.[t(390)](f=>f.key===n&&f.value===s)}function or(a,n){let s=t;if(e[s(976)](e.ehdGH,e[s(1191)])){let l=this[s(1037)+s(1173)]?.["getCurre"+s(768)+"nt"](),f=this[s(1448)]["reconnec"+s(1409)+s(1313)](_0x5c9eca[s(275)],_0x4f411c[s(576)]);this[s(1575)+"hCloseEv"+s(442)](e[s(1638)](_0xa1d0cf,s(324),{code:1006,reason:_0x320d12.reason||s(1547)+s(1021)+"d, unkno"+s(1662)+s(1476)+"ame: "+l,willReconnect:f})),f&&this[s(1166)]();return}else return a?.[s(390)](l=>l[s(488)]===n)?.[s(1676)]}let Sa=null;async function ug(){let a=t;return Sa||(Sa=Promise[a(322)]().then(Ft[a(415)](Ft,e[a(676)]))),Sa}class fg extends Ea{constructor(n,s){let l=t;e[l(221)](e.QGZtS,l(1036))?(super(),this[l(245)]=n,this._keyPath=s,this[l(505)]=void 0,this[l(449)+l(1024)]=null):_0x13d955.set(_0x59aca1,_0x4a3f25)}async[t(1431)](){let n=t;if(e.BPLXo(n(1030),e.XKcFx)){let{type:s}=_0x22277c;this[n(1318)](s,_0x551720)}else await this[n(426)]()}async _init(){let n=t,s={MTpcb:function(l,f){return e[F(1374)](l,f)},kLmzL:n(220),EZwGV:function(l,f){return e[n(919)](l,f)},OTWZx:function(l,f){return l&f},DKygj:function(l,f){return e[n(683)](l,f)},Gdxux:function(l,f){return e[n(1801)](l,f)},fswRT:function(l,f){return l|f},VtBEO:function(l,f){return l+f},qXFOY:function(l,f){return e.AUqbC(l,f)},NFCZK:function(l,f){return l|f},JjPym:function(l,f){return e[n(1060)](l,f)},JbyMs:function(l,f,g){return e[n(788)](l,f,g)},TxFdD:e[n(1297)],HpJzz:"eqzzu",uybvz:function(l){return e[n(940)](l)}};if(e.SwSMe(e[n(1096)],e[n(224)])){if(this[n(505)])return;if(this[n(449)+n(1024)])return this[n(449)+n(1024)];try{let l=this[n(245)],f=this[n(1620)];this[n(449)+"mise"]=(async()=>{let g=n,v={ZhLib:function(_,p){return _<p},jAuid:function(_,p){return s[F(1284)](_,p)},hmOIy:function(_,p){return s[F(1147)](_,p)},JscKe:function(_,p){return s[F(1155)](_,p)},zmIvK:g(258)+g(1133),Joemq:function(_,p){return s[g(1827)](_,p)},pHBCo:function(_,p){return s[g(1264)](_,p)},rMjIb:function(_,p){return s[g(1846)](_,p)},fYOej:function(_,p){return s.qXFOY(_,p)},dbbnI:function(_,p){return s.OTWZx(_,p)},GdCcn:function(_,p){return s.NFCZK(_,p)},ovAty:function(_,p){return s[g(1162)](_,p)},gjOYD:function(_,p,y){return s[g(382)](_,p,y)},Yzbzo:s[g(621)]};if(s[g(1155)](s[g(705)],g(1201))){let{openDB:_}=await s[g(482)](ug);this[g(505)]=await _(g(731)+"_"+l,1,{upgrade(p){let y=g;if(s[y(1688)](s[y(1230)],y(220)))if(_0x407715=_0x14bdff[y(884)+"At"](_0x45d856),tbIuMP[y(360)](_0x250a9f,128))_0x8355b1[_0x5a1bba++]=_0x29ec62;else if(tbIuMP[y(360)](_0x56844f,2048))_0x501dc4[_0x48d7a9++]=tbIuMP.jAuid(_0x45fae9,6)|192,_0x3bee91[_0x2db730++]=tbIuMP[y(813)](63,_0x12bfc3)|128;else if((64512&_0x286540)===55296&&tbIuMP[y(525)](64512&(_0x2f4b14=_0x46470a[y(884)+"At"](_0x5f2440+1)),56320)){let C=tbIuMP[y(845)][y(842)]("|"),O=0;for(;;){switch(C[O++]){case"0":++_0x1b1d05;continue;case"1":_0x5f08a5[_0x3e3570++]=tbIuMP[y(868)](tbIuMP[y(813)](tbIuMP[y(1705)](_0x38f8f3,12),63),128);continue;case"2":_0x5d81c0[_0x551c95++]=tbIuMP[y(813)](tbIuMP[y(1705)](_0x415f40,6),63)|128;continue;case"3":_0x26feb6[_0x2e2578++]=tbIuMP[y(868)](tbIuMP[y(1705)](_0x55c3bb,18),240);continue;case"4":_0x17d525[_0x517bde++]=tbIuMP[y(569)](63&_0x1c0d21,128);continue;case"5":_0x383297=tbIuMP[y(697)](65536,tbIuMP[y(296)](1023&_0x50d28d,10))+tbIuMP[y(1528)](1023,_0x214e26);continue}break}}else _0x34fc0a[_0x20522c++]=tbIuMP[y(850)](tbIuMP.jAuid(_0x2bc807,12),224),_0x257776[_0x570a1e++]=tbIuMP[y(569)](tbIuMP[y(1705)](_0x235792,6)&63,128),_0xe3ecaa[_0x459799++]=tbIuMP[y(691)](63&_0x37cf7d,128);else p["createOb"+y(1584)+"e"](l,{keyPath:f})}})}else{let _="connect "+_0x30d07b+(g(1355)+g(301)+g(1665)+"ed");this[g(1575)+g(1836)+g(442)](v[g(905)](_0x53c158,v[g(1677)],{message:_,code:_0x33b494[g(1511)+g(1468)+"R"],error:_0x1d4f9f}));return}})(),await this[n(449)+n(1024)]}catch(l){console[n(1826)](l)}finally{this["_initPro"+n(1024)]=null}}else _0x3ea9d3.body["appendCh"+n(821)](_0x51b320)}async[t(1463)](n){let s=t;try{return await this[s(426)](),this[s(505)]?.[s(1463)](this._dbName,n)}catch(l){console.log(l)}}async set(n,s){let l=t;return await this._init(),this[l(505)]?.[l(1644)](this[l(245)],n)}async del(n){let s=t,l={YkNTM:function(f,g){return f+g}};if(e[s(1310)](s(631),"HUexd")){let f=this[s(1439)+s(722)][s(587)]((g,v)=>(g+=v&&v[s(1507)+"th"]||0,g),0);return l[s(806)](f,this[s(1782)]?this[s(1782)][s(1443)+s(1696)]:0)}else try{return await this[s(426)](),this._qosDB?.delete(this[s(245)],n)}catch(f){console.log(f)}}async[t(1334)](){let n=t;try{return await this[n(426)](),this[n(505)]?.clear(this[n(245)])}catch(s){console.log(s)}}async keys(){let n=t;return await this[n(426)](),this._qosDB?.[n(1266)+"ys"](this[n(245)])}async[t(1490)](){let n=t;return await this._init(),this[n(505)]?.[n(1490)](this[n(245)])}async[t(1063)](){let n=t;try{this._qosDB?.[n(324)](),this[n(505)]=void 0}catch(s){console[n(1826)](s)}}get[t(1717)](){let n=t;try{return!!this[n(505)]}catch(s){return console[n(1826)](s),!1}}}class xg{constructor(n,s){let l=t;this[l(903)]=n,this._pathKey=s,this[l(505)]=localStorage}async[t(1431)](){}get _prefix(){let n=t;if(e[n(1200)]===e[n(591)]){let l=""+_0x50fa3e.now(),f=_0xf3f7e||(_0x9d6ad3=e[n(1647)](_0x2af195,_0x5aa98f)),g=_0x227644[n(975)]()[n(558)](16).slice(-6);return e[n(626)](e.gtpnl("02"+l,f),g)}else return n(731)+"_"+this[n(903)]}async[t(1463)](n){let s=t,l=this[s(505)].getItem(this[s(1858)]);return JSON[s(1056)](e.WXOCu(l,"{}"))[n]}async set(n,s){let l=t,f=this[l(505)][l(530)](this[l(1858)]),g=JSON[l(1056)](e.NsqxE(f,"{}"));return g[s||n[this[l(213)]]]=n,this[l(505)][l(1353)](this[l(1858)],JSON[l(1450)+"y"](g)),s||n[this[l(213)]]}async del(n){let s=t,l=this[s(505)].getItem(this[s(1858)]),f=JSON[s(1056)](e[s(1196)](l,"{}"));return f[n]=void 0,this[s(505)].setItem(this[s(1858)],JSON[s(1450)+"y"](f))}async[t(1334)](){return this._qosDB.clear()}async[t(1303)](){let n=t,s={TIIhC:function(l,f){return e[F(1724)](l,f)}};if(e.xEAFq("nldsz",e[n(1210)])){let l=this._qosDB.getItem(this._prefix),f=JSON[n(1056)](l||"{}");return Object[n(1303)](f)}else return function(l,...f){let g=n,v=_0xbd2ccf[g(1417)](_0x10dc0e(this),l,...f);return _0x54c545[g(328)](v,l.sort?l[g(1244)]():[l]),gEkwyH[g(1025)](_0x48539c,v)}}async getAll(){let n=t,s=this[n(505)].getItem(this[n(1858)]),l=JSON[n(1056)](e[n(1089)](s,"{}"));return Object[n(982)](l)}[t(1063)](){return Promise[t(322)]()}get isReady(){return!!this[t(505)]}}class hg{constructor(n,s){let l=t;this[l(903)]=n,this[l(213)]=s,this._qosDB=Rn?tt:ti?wx:null}async[t(1431)](){}get _prefix(){return t(731)+"_"+this._DBName}async get(n){let s=t,l={vnZgR:function(f,g){return e.EAuFx(f,g)}};if(e[s(1781)](s(1242),e[s(456)])){let f=this._qosDB[s(710)+"geSync"](this._prefix);return JSON[s(1056)](e[s(872)](f,"{}"))[n]}else if(FJKKBX[s(1464)](_0x3c2a7a,_0x155c8c))return _0x5c32e8}async[t(328)](n,s){let l=t,f=this._qosDB["getStora"+l(1187)](this[l(1858)]),g=JSON[l(1056)](e[l(790)](f,"{}"));return g[s||n[this._pathKey]]=n,this[l(505)][l(1401)+l(1187)](this[l(1858)],JSON[l(1450)+"y"](g)),s||n[this[l(213)]]}async[t(1181)](n){let s=t,l=this._qosDB[s(710)+s(1187)](this[s(1858)]),f=JSON.parse(e[s(790)](l,"{}"));return f[n]=void 0,this[s(505)][s(1401)+s(1187)](this[s(1858)],JSON[s(1450)+"y"](f))}async[t(1334)](){let n=t;return this[n(505)]["clearSto"+n(1635)]()}async[t(1303)](){let n=t,s={qQamu:function(l,f){return e[F(1110)](l,f)},jpAoO:function(l,f){return e[F(446)](l,f)}};if(e.AOdiR(e[n(432)],e[n(432)])){let l=this[n(505)]["getStora"+n(1779)+"nc"](this[n(1858)]),f=JSON[n(1056)](e[n(790)](l,"{}"));return Object.keys(f)}else{if(xsMtSE[n(405)](_0x1f5c82,-_0x26fb14))return _0xf8bab9;if(xsMtSE[n(744)](_0xc73cbf+1,_0x167428))return _0x537c03}}async[t(1490)](){let n=t,s=this[n(505)][n(710)+n(1779)+"nc"](this._prefix),l=JSON[n(1056)](e[n(619)](s,"{}"));return Object[n(982)](l)}[t(1063)](){let n=t,s={pqHIw:function(l,f){return e[F(1639)](l,f)}};if(e[n(931)](e[n(1445)],e.pUIPO))return Promise.resolve();s[n(925)](_0x5ab672,this._pingPongTimeoutId),s[n(925)](_0x48f101,this[n(929)+n(862)+n(523)]),this[n(602)+n(1135)+"Id"]=null,this[n(929)+n(862)+n(523)]=null}get isReady(){return!!this[t(505)]}}function vl(a,n){let s=t;if(e[s(1843)]===e[s(1843)]){if(e[s(735)](Rn,Rn))return new hg(a,n);if(e[s(1435)](sr,ni)&&e[s(1707)](e.viCPr,typeof indexedDB))return new fg(a,n);if((sr||ni)&&e[s(1077)](e[s(1852)],typeof localStorage))return new xg(a,n);throw new Error(e[s(1721)])}else return _0x39af29.apply(ylhYic[s(531)](_0x2da1f6,this),_0x5a76ca),ylhYic[s(946)](_0x40241f,_0x41f71d[s(1463)](this))}class pg{constructor(){let n=t;this["_interva"+n(773)+"Id"]=null,this[n(1332)+"l"]=36e5,this[n(505)]=e[n(1258)](vl,e.zJLuq,e[n(1275)])}async[t(1332)+"lFlush"](){let n=t;e.TIbwE(clearInterval,this[n(1332)+"lTimeoutId"]),this[n(1332)+n(773)+"Id"]=e[n(404)](setInterval,()=>{let s=n;e.jLbUW(e[s(898)],e[s(898)])?_0x5211ec[s(322)]().then(()=>{let l=s;this[l(1216)+l(1006)]()}):this[s(897)+"ired"]()},this[n(1332)+"l"])}async openDB(){let n=t;await this[n(505)][n(1431)]().then(()=>{this._intervalFlush()})}async[t(897)+t(1432)](){let n=t;(await this[n(505)]?.[n(1490)]()||[]).filter(({timestamp:f})=>f<Date.now())[n(1798)](f=>{let g=n;this._qosDB?.[g(1181)](f[g(374)+"id"])})}async del(n){let s=t;return this[s(505)]?.[s(1181)](n)}async set(n,s){let l=t;return this[l(505)]?.[l(328)]({message_id:n,timestamp:s})}async get(n){return this[t(505)]?.get(n)}async[t(1063)](){let n=t,s={lArMZ:function(l,f){return e[F(1861)](l,f)}};if(e[n(469)](e.EywTT,e[n(1305)])){let l=_0x4ccf5d[n(1417)](avLdrO[n(1168)](_0x1b581e,this),_0x42832a,..._0x4a470b);return _0x4dff3c.set(l,_0x462515[n(1244)]?_0x48cc61[n(1244)]():[_0x575309]),avLdrO[n(1168)](_0x57463c,l)}else e[n(489)](clearInterval,this["_interva"+n(773)+"Id"]),await this[n(505)]?.[n(1063)]()}get isReady(){let n=t;return e[n(251)](e[n(473)],e[n(783)])?(_0x4f761d[n(1590)+"t8"]?_0x421bf7[n(1590)+"t8"](_0x1a5b23,_0x4cc61b):_0x5e44b4[_0x2343c9]=e[n(1189)](255,_0x2e1263),e[n(452)](_0x536f47,1)):this[n(505)]?.[n(1717)]}}function Ia(a){let n=t;if(e.vTFnY(e[n(1397)],e[n(572)])){let s=!!this[n(1448)][n(1372)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=an(a[n(1153)][n(268)],e.AMWBy,"2"),f=l&&e[n(1359)](an,a[n(1153)][n(268)],e[n(1744)],"1"),g=l&&e[n(1819)](an,a[n(1153)][n(268)],n(817)+"er_is_ack","1"),v=g?e[n(1788)](or,a[n(1153)].headers,e[n(802)])?.[n(842)](",").filter(Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:g,ackMsgIds:v}}else{let s={QBhBP:function(l,f,g){return e[n(1346)](l,f,g)}};return new _0xbaa79e(l=>{let f=n;s[f(1457)](_0xe8115d,l,this[f(345)+"rvalValue"](_0x359820))})}}async function Sl(){let a=t,n={yETQj:function(s,l,f,g){return e[F(1046)](s,l,f,g)},zDFla:function(s,l,f){return s(l,f)},wxDuw:e[a(1297)]};if(e[a(292)](e[a(1246)],e.pVaGF))return this[a(1649)+a(856)]||(this[a(1649)+a(856)]=new pg),this[a(1649)+a(856)].isReady||await this["_QoSMana"+a(856)][a(1431)](),this._QoSManager;try{n[a(700)](_0x5bf63d,this,_0x20a73e,[_0x470ade,_0x24222c,_0x4e8d55])}catch(s){let l=n[a(965)](_0x52ec3c,n[a(1073)],{message:s[a(1153)],code:_0x542389.OPEN_ERROR,error:s});this[a(1575)+a(1836)+a(442)](l)}}async function gg(a,n){let s=t,{enableAutoAck:l}=this._options,f=e[s(1359)](an,a[s(1153)][s(268)],e.eeJJI,"1"),g=e[s(1359)](an,a[s(1153)][s(268)],e[s(1345)],"1"),v=Ia.call(this,a);if(e[s(876)](l,f)){let{SeqID:_,LogID:p,service:y,LogIDNew:C,method:O}=a[s(1153)];this[s(1271)]({SeqID:_,LogID:p,LogIDNew:C,service:y,method:O,headers:[{key:e.bIaFL,value:"1"},{key:e[s(1469)],value:e[s(625)](C,"")},{key:e[s(1050)],value:"0"}]})}g&&!v.isQoSAck&&this[s(1575)+s(1693)+s(1583)](a),n()}async function mg(a,n){let s=t;this[s(227)](e[s(265)],a[s(1153)]),e[s(940)](n)}async function wg(a,n){let s=t,l={pnRKJ:function(f,g,v){return e[F(246)](f,g,v)},rDDcQ:function(f,g){return e[F(1479)](f,g)},myDtf:function(f,g){return e[F(262)](f,g)},CekFu:function(f,g){return e.CTcUO(f,g)},iQHWE:function(f,g){return e[F(1821)](f,g)},RGcLg:function(f,g){return e[F(1369)](f,g)},hKgud:function(f,g){return f&g},JcWaF:function(f,g){return e[F(626)](f,g)},DgzsO:function(f,g){return f>>g}};if(e[s(418)](s(1678),e[s(1124)])){let f=e[s(1647)](rn,await e[s(1787)](El,a.data));try{if(e[s(683)](e[s(212)],e[s(212)]))if(f[s(1766)]instanceof Uint8Array){let g=e[s(1546)](this._options[s(1309)+s(464)],Object)?{force:!!this[s(1448)][s(1309)+s(464)][s(1182)],encoding:this._options[s(1309)+"ncoding"][s(1325)]?this._options[s(1309)+"ncoding"][s(1325)].replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this[s(1448)][s(1309)+s(464)]?this[s(1448)][s(1309)+s(464)][s(323)](/\s/g,"").toLowerCase():""},v=f["payloadE"+s(464)]?f[s(1309)+s(464)].replace(/\s/g,"")[s(1652)+"ase"]():"",_=e[s(1546)](this[s(1448)][s(1774)+s(597)],Object)?{force:!!this[s(1448)][s(1774)+"ype"].force,type:this._options[s(1774)+s(597)][s(1102)]?this[s(1448)][s(1774)+"ype"][s(1102)][s(323)](/\s/g,"")[s(1652)+s(760)]():""}:{force:!1,type:this[s(1448)]["payloadT"+s(597)]?this[s(1448)][s(1774)+s(597)].replace(/\s/g,"")[s(1652)+"ase"]():""},p=f[s(1774)+s(597)]?f[s(1774)+s(597)][s(323)](/\s/g,"")[s(1652)+s(760)]():"",y=_[s(1182)]?_[s(1102)]:p||_[s(1102)],C=g[s(1182)]?g.encoding:v||g[s(1325)],O=[e[s(1117)],e[s(1128)],e.WPGYM,s(340)],U=[s(1793)+"e",e[s(1281)]];this[s(1448)][s(391)+s(487)+"extPayload"]&&O[s(1221)](y)&&(!C||U[s(1221)](C))?f[s(1504)+s(1206)]=e.VTnJK(bl,f[s(1766)],0,f[s(1766)][s(1507)+"th"]):f[s(1504)+"oad"]=""}else f[s(1504)+s(1206)]="";else jdXpyZ[s(703)](_0x45f316,_0x1bde6c,50),jdXpyZ.pnRKJ(_0x995e0e,_0x301338,_0x4b46ef)}catch(g){f["textPayl"+s(1206)]="",console[s(1826)](g)}a.message=f,e[s(819)](n)}else{let f=jdXpyZ[s(1506)](jdXpyZ.myDtf(jdXpyZ[s(638)](jdXpyZ.iQHWE(7,_0x3964f3),18)|jdXpyZ[s(1581)](63&_0x425e21[_0x3e3c2b++],12),jdXpyZ.CekFu(jdXpyZ[s(1348)](63,_0x255cd6[_0x151590++]),6)),63&_0x2135d3[_0x38533f++])-65536;_0x1b70b3+=_0x50f959[s(928)+s(309)](jdXpyZ[s(1533)](55296,jdXpyZ.DgzsO(f,10))),_0x359af6+=_0x40d8eb["fromChar"+s(309)](jdXpyZ.JcWaF(56320,1023&f))}}function _g(a,n,s){let l={TWaOJ:function(p,y){return e.bFnXc(p,y)},Lsyis:function(p,y){return e[F(357)](p,y)},hMTCP:function(p,y){return e[F(820)](p,y)},hYkob:function(p,y){return p(y)},HjuSd:function(p,y){return e.NvubG(p,y)},tuhOt:function(p,y){return e.oacfA(p,y)},QwACZ:function(p,y){return e[F(461)](p,y)}},f=e.QOXNY(s,8192),g=f>>>1,v=null,_=f;return function(p){let y=F;if(l[y(1042)](p,1)||p>g)return l[y(1219)](a,p);l[y(1441)](_,p)>f&&(v=l.hYkob(a,f),_=0);let C=n[y(1417)](v,_,_+=p);return l[y(1683)](7,_)&&(_=l[y(782)](l[y(1740)](7,_),1)),C}}let yg=4294967295;function bg(a,n,s){let l=t;if(e[l(1594)](l(329),l(753))){let f=new _0x2a4063(e.QiVSy(e[l(784)](_0x3231c3[e[l(1169)](_0x17590a,4)],24)|_0x1d6682[_0x412d89+5]<<16|_0x128e03[_0x5d1b40+6]<<8,_0xb4e7ce[_0x650922+7]),e[l(461)](e[l(823)](e[l(1642)](e.nnHSB(_0x304141[e[l(1437)](_0x362fec,0)],24),_0x36db43[e[l(655)](_0x491754,1)]<<16),_0x15d02a[e[l(1009)](_0x3c27ad,2)]<<8),_0x1a5ef5[e[l(1810)](_0x51217c,3)]),!0);return _0x32870d+=8,{value:f,offset:e[l(562)](_0x109822,8)}}else return e[l(509)](RangeError,e[l(1116)](e[l(1629)](l(1415)+l(271)+"ge: "+a+e[l(1742)],e.eWGrM(n,1)),e[l(1203)])+s)}function Eg(a,n,s){let l=t;if(e[l(1328)](e[l(1329)],e[l(1329)])){if(s>yg)throw new Error(e.jOtbp);let f=3;for(;e[l(1260)](f,0);){let g=e[l(241)](255,s);ka(g,a,e[l(478)](n,f)),s>>>=8,f--}return e[l(478)](n,4)}else return this._socket.binaryType}function vg(a,n){let s=t;if(e[s(1237)](s(1691),e[s(1712)])){let l=0,f=n,g=e[s(428)](n,4);for(;e[s(1351)](f,g);){let{value:v,offset:_}=Aa(a,f);f=_,l=e[s(1741)](e[s(1797)](l,8),0),l+=v}return{value:l,offset:g}}else{let l=_0x47ce0e[s(884)+"At"](_0x5493e5);e[s(693)](l,55296)&&l<=56319&&e.FHmdy(e.NAZcn(_0xccc08b,1),_0x26e8df)&&(l=e[s(1732)](e.PBbLr(l<<10,_0xd09583[s(884)+"At"](++_0x5263a3)),56613888)),e[s(737)](l,128)?_0x4f24a4[_0x36c650++]=l:(e[s(327)](l,2048)?_0xd39cae[_0x1fe67c++]=e.xakps(l>>6,31)|192:(e[s(663)](l,65536)?_0x57bacf[_0x4c519c++]=e[s(1628)](e[s(420)](l,12),15)|224:(_0x2c4187[_0x357a3a++]=l>>18&7|240,_0x631a26[_0x18864b++]=e[s(919)](l,12)&63|128),_0x4057ae[_0x75783f++]=e[s(330)](e[s(290)](l>>6,63),128)),_0x3624eb[_0x439928++]=e[s(475)](e[s(1248)](63,l),128))}}function Sg(a,n,s){let l=t;if(e.ePtLU("PYsvG",e[l(695)]))this[l(337)+"T"]||this[l(1762)+"X"]?this[l(344)+l(701)+l(565)]():this[l(1748)+"er"]&&this[l(302)+l(577)+"Listener"]();else{let f=e[l(1209)][l(842)]("|"),g=0;for(;;){switch(f[g++]){case"0":if(n[l(1674)+"e"])return e.ZNiFD(n[l(1674)+"e"](a,s),s);continue;case"1":if(!a)return s;continue;case"2":if(n.write)return e[l(1395)](n[l(904)](a,s),s);continue;case"3":return e.TgqEJ(e[l(1530)](va,a,n,s),s);case"4":if(e[l(801)](a[l(1270)],40))return e[l(1046)](va,a,n,s)+s;continue}break}}}function Ig(a,n){let s=t,l=new he(e.KvWSg(e[s(1277)](e.yZzFy(e.QTddH(a[e.oWmcE(n,4)],24),e.Nmetx(a[e.ZidwK(n,5)],16)),e[s(321)](a[e[s(960)](n,6)],8)),a[e[s(1146)](n,7)]),e[s(1157)](e.KOwtv(e.pIfjz(e[s(454)](a[e[s(1131)](n,0)],24),a[e[s(626)](n,1)]<<16),a[n+2]<<8),a[e[s(1670)](n,3)]),!0);return n+=8,{value:l,offset:n+8}}function Ag(a,n,s){let l=t;if(e[l(1522)](l(1066),e[l(885)]))this[l(880)+l(957)]=_0x47167c,this[l(996)]=0;else{let f=a.low,g=a[l(1831)];return n[s]=e.DMdSA(g,24),n[s+1]=e.sOPZv(e[l(720)](g,16),255),n[e[l(1017)](s,2)]=e[l(1618)](e.zZPVe(g,8),255),n[e[l(1116)](s,3)]=e.abBbT(255,g),n[e[l(395)](s,4)]=f>>>24,n[s+5]=e.Cygkv(e[l(1188)](f,16),255),n[e[l(388)](s,6)]=e.iLztW(e[l(1308)](f,8),255),n[s+7]=255&f,s+=8,s}}function Aa(a,n){let s=t;return a[s(1862)+"8"]?{value:a[s(1862)+"8"](n),offset:n+1}:{value:e.WjAZY(255,a[n]),offset:e[s(1357)](n,1)}}function ka(a,n,s){let l=t;return n[l(1590)+"t8"]?n[l(1590)+"t8"](a,s):n[s]=e[l(1165)](255,a),s+1}let kg=function(a){return new Uint8Array(a)},Tg=e[t(407)](e.viCPr,typeof Buffer)?Buffer[t(1791)+t(263)]:_g(kg,Uint8Array.prototype[t(459)]),Cg=16,Ta=32;function Pg(a){let n=t,s=0,l={};for(let f=0;e[n(1495)](f,a[n(1270)]);f++)l[a[f][n(879)+"ame"]]=e.WFCoH(yl,a[f][n(879)+n(584)]),s+=14+l[a[f][n(879)+"ame"]];return[s,l]}function Il(a,n,s){let l=t,[f,g]=e[l(1475)](Pg,a),v=e[l(1737)](Tg,f),_=0;return a.forEach(p=>{let y=l,C=("9|4|10|6"+y(906)+y(675)).split("|"),O=0;for(;;){switch(C[O++]){case"0":_=e.Pshzm(Sg,p[y(879)+y(584)],v,_);continue;case"1":console[y(1826)](e[y(995)],_);continue;case"2":console[y(1826)](e[y(1067)],_);continue;case"3":_=e[y(1530)](Ag,he[y(1603)+"er"](p[y(1240)]||n),v,_);continue;case"4":_=e.SRIxF(ka,0,v,_);continue;case"5":_=e[y(1530)](ka,g[p["cursor_n"+y(584)]],v,_);continue;case"6":_=e.LPldx(Eg,v,_,p[y(609)]||0);continue;case"7":console[y(1826)](y(633),_);continue;case"8":console[y(1826)](e[y(230)],_);continue;case"9":console.log(y(1231)+y(1702),p,p[y(609)]);continue;case"10":console[y(1826)](e[y(1039)],_);continue}break}}),{frameType:Ta,headers:[{key:e[l(1062)],value:s}],payload:v}}function Rg(a){let n=t,s=0,l=[];for(;e[n(254)](s,a[n(1507)+"th"]);){let{offset:f}=e[n(1339)](Aa,a,s);s=f;let g={cursor_name:"",cursor:0,service:0},{value:v,offset:_}=e[n(1347)](vg,a,s);g[n(609)]=v,s=_;let{value:p,offset:y}=e.kCWHB(Aa,a,s);s=y,g[n(879)+"ame"]=e.pWXIk(bl,a,s,e[n(1262)](s,p)),s+=p;let{value:C,offset:O}=e[n(788)](Ig,a,s);g.cursor=C[n(1224)](),s=O,l[n(394)](g)}return l}function Dg(){let a=t;return{frameType:Ta,headers:[{key:"cursor_f"+a(1560),value:a(1190)+"_EXIST"}],payload:void 0}}class Og{constructor(n,s,l){let f=t;this[f(1295)+f(986)]=n,this[f(922)+f(318)]=s,this[f(1439)+"Strategy"]=l,this[f(505)]=e[f(788)](vl,this[f(1295)+f(986)],f(879)+f(584))}async[t(1431)](){await this._qosDB.openDB()}async[t(1606)+"rs"](){let n=t;if(!this[n(505)][n(1717)])return;let s=this[n(1439)+"Strategy"],l=await this[n(505)].getAll();switch(console.log(e[n(228)],l),s){case e[n(1080)]:return l&&l[n(1270)]?Il(l,0,this[n(922)+n(318)]):void 0;case e[n(998)]:return;case e[n(1655)]:return l&&l.length?Il(l,0,this["_cursorF"+n(318)]):e[n(985)](Dg)}}async[t(328)](n,s,l){let f=t;return console[f(1826)](f(1689),n,s,l),this[f(505)][f(328)]({cursor_name:n,cursor:s,service:l})}async[t(384)+"rs"](n){let s=t,l=e[s(877)](Rg,n);for(let f of l)console[s(1826)](e.WWTNZ,l),await this[s(505)][s(328)](f)}async[t(1463)](n){let s=t;return e[s(221)](e[s(1486)],s(424))?(await this[s(505)][s(1463)](n))?.[s(1240)]:this[s(337)+"T"]||this._isMiniWX?this[s(1687)+s(320)+s(1562)]:(this[s(1748)+"er"]||this._isWorker)&&this._options[s(774)+s(1604)+s(1092)]?_0x2dca8c[s(1621)]:!0}async[t(1063)](){let n=t;if(e[n(1761)](n(1178),n(1178)))return _0x4853aa[n(322)]();await this._qosDB[n(1063)]()}[t(350)+t(507)+t(1795)](n){let s=t;this[s(922)+s(318)]=n}get[t(1717)](){let n=t;return this[n(505)][n(1717)]}}let Lg=e.TUXDV;async function Al(a){let n=t;if(!this[n(1448)].enableQoS)return null;let{aID:s,fpID:l,messageStrategy:f}=this[n(1448)],g=e.JfQyc(a,Lg);try{return this["_cursorM"+n(797)]?a&&this[n(278)+"anager"][n(350)+n(507)+n(1795)](a):this[n(278)+n(797)]=new Og(l+"_"+s+"_"+g,g,f),this[n(278)+n(797)].isReady||await this[n(278)+"anager"][n(1431)](),this["_cursorM"+n(797)]}catch{return null}}async function Ng(a,n){let s=t,l=an(a[s(1153)][s(268)],e[s(483)],"-1"),f=e[s(1046)](an,a[s(1153)].headers,s(757),"1"),g=e[s(270)](or,a[s(1153)].headers,e[s(1544)]),v=e[s(1785)](Number,e[s(1301)](or,a[s(1153)].headers,e.QRXnO))||0,_=Ia[s(1417)](this,a),p=e[s(1029)](an,a[s(1153)][s(268)],e[s(1627)],"2"),y=e.IACoX(or,a[s(1153)][s(268)],s(457)+s(226)+"e"),C=e.zoWbb(Number,e.sqPHO(or,a[s(1153)][s(268)],"x-msg-cu"+s(647)+"ue"));if(_[s(1525)])return e[s(1775)](n);let O=_[s(615)+s(781)]?await Sl[s(1417)](this):null;if(e[s(468)](a.message[s(609)],0)&&f&&!l||a.message.service>0)if(e.niNnJ(s(1453),s(1453))){if(g&&_[s(615)+"sage"]&&O)return!!!await O[s(1463)](g)&&(this[s(1575)+s(1144)+s(1176)](a),await O[s(328)](g,e[s(1502)](Date[s(713)](),v))),e.jAGhc(n);if(p){let U=await Al[s(1417)](this);if(!U){if(e[s(1485)](s(865),s(865)))return this[s(1575)+s(1144)+s(1176)](a),e.zACJw(n);{let ae=/(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(_0x4f5bbe),st=/(([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]))/[s(973)](_0x514d54);return ae?e.iFwxr(_0x119315,_0x6a0e09):st?e[s(1579)](_0x47bc17,_0x563053):e.CPCVI}}let H=await U[s(1463)](y)??-1;if(e.xbSEA(H,C))this[s(1575)+s(1144)+s(1176)](a),U[s(328)](y,C,a[s(1153)][s(609)]);else throw new Error(s(1274)+s(1715)+s(1058)+C+(" larger "+s(1776)+s(714)+"r ")+H);return e[s(598)](n)}return this[s(1575)+s(1144)+s(1176)](a),e[s(940)](n)}else return this[s(1588)][s(616)]}async function Mg(a,n){let s=t,l={fljDn:function(f,g){return e[F(1320)](f,g)},fthkM:function(f,g){return f|g},PHhkz:function(f,g){return e[F(560)](f,g)},PBKIw:function(f,g){return f===g},OKsua:function(f,g){return e[F(844)](f,g)},OeELx:function(f,g){return e[F(644)](f,g)},lTnPJ:function(f,g){return e[F(1442)](f,g)},OqyHu:function(f,g){return e[F(801)](f,g)},hILLD:function(f,g,v){return f(g,v)},tHkqE:function(f,g){return f+g},cmdeZ:function(f,g){return f&g},NOvMV:function(f,g){return e[F(1322)](f,g)},ByXZF:function(f,g){return e.sdXTv(f,g)},cdPoc:function(f,g){return f&g},BlgWk:function(f,g){return e.rLcuH(f,g)},UicTJ:function(f,g){return e.DMdSA(f,g)},jTRkQ:function(f,g){return e[F(393)](f,g)},zcIsi:function(f,g){return e[F(702)](f,g)},ZqHDA:function(f,g){return f!==g},JpFxg:function(f,g){return e[F(461)](f,g)},xUaMi:function(f,g){return e.lNfyP(f,g)},TbqbO:function(f,g){return e.zbUfG(f,g)},vNmEw:function(f,g){return e[F(1685)](f,g)},UOmOl:function(f,g){return f+g},GEygs:function(f,g){return f|g},LSHft:function(f,g){return e[F(1653)](f,g)},WIuij:function(f,g){return e.OvHnz(f,g)},zgoaG:function(f,g){return f!==g},tJquI:function(f,g){return e.nNfUd(f,g)},Bmwmh:function(f,g){return e[F(1768)](f,g)},vgJnF:function(f,g){return e.DMdSA(f,g)},VTCFM:function(f,g){return f>>>g},BvkrC:function(f,g){return e[F(1539)](f,g)},VIlJi:function(f,g){return e[F(1577)](f,g)},XMbld:function(f,g){return e.CaXGx(f,g)}};if(s(1505)===s(479)){let f=YhTktM[s(910)](_0x5f0bcd[s(1496)],0),g=YhTktM.fljDn(YhTktM[s(1535)](_0x196c90[s(1496)]>>>28,YhTktM.PHhkz(_0x39540f[s(1831)],4)),0),v=YhTktM[s(910)](_0x510222.high,24),_=YhTktM.PBKIw(0,v)?YhTktM.OKsua(0,g)?YhTktM[s(983)](f,16384)?YhTktM.lTnPJ(f,128)?1:2:YhTktM[s(983)](f,2097152)?3:4:YhTktM[s(312)](g,16384)?YhTktM.OeELx(g,128)?5:6:YhTktM[s(312)](g,2097152)?7:8:YhTktM.OqyHu(v,128)?9:10,p=YhTktM[s(1288)](_0x497f75,_0x2eaf7b,_),y=_0x1818af[s(1223)];switch(_){case 10:y[YhTktM[s(539)](p,9)]=YhTktM[s(387)](YhTktM.fljDn(v,7),1);case 9:y[p+8]=YhTktM.NOvMV(9,_)?YhTktM[s(1611)](128,v):YhTktM[s(264)](127,v);case 8:y[YhTktM[s(1183)](p,7)]=_!==8?YhTktM[s(754)](g,21)|128:YhTktM[s(891)](YhTktM.zcIsi(g,21),127);case 7:y[YhTktM[s(1183)](p,6)]=YhTktM[s(1138)](7,_)?YhTktM[s(1549)](YhTktM[s(1658)](g,14),128):YhTktM[s(1140)](g,14)&127;case 6:y[p+5]=_!==6?YhTktM[s(1535)](YhTktM.UicTJ(g,7),128):YhTktM.cmdeZ(YhTktM.vNmEw(g,7),127);case 5:y[YhTktM[s(502)](p,4)]=YhTktM[s(1498)](5,_)?YhTktM.GEygs(128,g):YhTktM.LSHft(127,g);case 4:y[p+3]=YhTktM[s(719)](4,_)?f>>>21|128:YhTktM[s(1789)](f,21)&127;case 3:y[YhTktM[s(1183)](p,2)]=YhTktM.zgoaG(3,_)?YhTktM[s(462)](f,14)|128:YhTktM[s(815)](YhTktM[s(1236)](f,14),127);case 2:y[YhTktM[s(539)](p,1)]=_!==2?YhTktM[s(1535)](YhTktM[s(786)](f,7),128):YhTktM[s(849)](YhTktM[s(1391)](f,7),127);case 1:y[p]=YhTktM[s(255)](1,_)?YhTktM[s(1611)](128,f):YhTktM.BvkrC(127,f)}}else{let f=Ia[s(1417)](this,a);if(!f["isQoSMes"+s(781)])return e[s(1428)](n);let g=await Sl[s(1417)](this);if(f[s(222)+"anupMess"+s(938)]&&f[s(1294)+"s"][s(1270)])for(let v of f[s(1294)+"s"])await g[s(1181)](v);e[s(940)](n)}}async function Bg(a,n){let s=t,l={jSrVG:function(p,y){return e[F(1578)](p,y)},moHbF:function(p,y){return p>>>y},AvvZk:function(p,y){return p<y},zbonS:function(p,y,C,O){return p(y,C,O)},UNBGU:function(p,y){return e[F(1122)](p,y)},NbaiF:function(p,y){return e[F(1381)](p,y)},YNsgJ:function(p,y){return p&y},WtnPo:function(p,y){return p>>>y}},f=a.message[s(939)+"e"]===Cg,g=e[s(931)](a[s(1153)][s(939)+"e"],Ta);if(!f&&!g)return n();let v=e[s(889)](or,a[s(1153)].headers,"cursor_f"+s(1560));if(!v)return n();let _=await Al[s(1417)](this,v);if(!_)return e[s(819)](n);if(f){let p=await _.getCursors(),y={frameType:p?.[s(939)+"e"],SeqID:he[s(1603)+"er"](this[s(550)]++),LogID:he[s(1603)+"er"](this._options[s(1757)+s(217)]()),service:9e3,method:5,headers:p?.[s(268)],payload:p?.payload},C=e[s(476)](I,y);this[s(1782)]&&this._ws[s(980)+"te"]&&this[s(1782)][s(1598)](C)}if(g)if(e.gFQqp===s(1072)){let p=a[s(1153)][s(1766)];p&&_[s(384)+"rs"](p)}else{let p={LiVCE:function(C,O){let U=s;return LRHdeL[U(273)](C,O)},JPgaT:function(C,O){let U=s;return LRHdeL[U(1726)](C,O)},vvjXv:function(C,O){return C<<O},jOgSB:function(C,O){return C&O},vksHa:function(C,O){return C>>>O},nXnMD:function(C,O){let U=s;return LRHdeL[U(1434)](C,O)},iRjRU:function(C,O){return C>O},AoVqn:function(C,O,U,H){return LRHdeL.zbonS(C,O,U,H)},WfhPE:function(C,O){let U=s;return LRHdeL[U(1842)](C,O)},UqxRQ:function(C,O){let U=s;return LRHdeL[U(1822)](C,O)},aoQMO:function(C,O){let U=s;return LRHdeL[U(1434)](C,O)},erDWl:function(C,O){return C|O},NDUgB:function(C,O){let U=s;return LRHdeL[U(1710)](C,O)},jtuSz:function(C,O){let U=s;return LRHdeL[U(273)](C,O)},JkSUG:function(C,O){let U=s;return LRHdeL[U(1385)](C,O)},joMUA:function(C,O){let U=s;return LRHdeL[U(273)](C,O)}},y=4294967295;return function(C,O,U=!0){let H=s,ae=("2|7|8|10"+H(445)+H(883)+"0")[H(842)]("|"),st=0;for(;;){switch(ae[st++]){case"0":return{value:U?y:p[H(860)](0,y),offset:O};case"1":y=p[H(1199)](y|p[H(238)](p[H(486)](15,C[O]),28),0);continue;case"2":y=p[H(1115)](p[H(486)](127,C[O]),0);continue;case"3":if(p[H(1807)](C[O++],128))return{value:U?y:0|y,offset:O};continue;case"4":if(p[H(1807)](C[O++],128))return{value:U?y:p[H(860)](0,y),offset:O};continue;case"5":if(p[H(419)](O+=5,C.length))throw O=C.length,p[H(878)](_0x2b5dff,O,10,C.length);continue;case"6":y=p[H(533)](y,p.vvjXv(p[H(1082)](127,C[O]),14))>>>0;continue;case"7":if(p[H(1706)](C[O++],128))return{value:U?y:p[H(772)](0,y),offset:O};continue;case"8":y=p.WfhPE(y,p[H(238)](p[H(1352)](127,C[O]),7))>>>0;continue;case"9":if(p[H(1706)](C[O++],128))return{value:U?y:p[H(860)](0,y),offset:O};continue;case"10":if(C[O++]<128)return{value:U?y:p[H(1460)](0,y),offset:O};continue;case"11":y=p.JkSUG(p[H(614)](y,(127&C[O])<<21),0);continue}break}}}}let Fg=async function(a,n){let s=t;this[s(1720)]=!1,e[s(413)](clearTimeout,this["_connect"+s(1202)+s(281)]),e[s(819)](n)},zg=async function(a,n){let s=t;if(!this._ws||e[s(1764)](this._ws[s(980)+"te"],this.OPEN))return e[s(334)](n);let{pingInterval:l}=this[s(1448)];this[s(1037)+s(1173)]?.[s(341)+s(1751)+"fig"]();for(let g=0;e[s(1738)](g,this["_message"+s(722)].length);g++){let v=this[s(1439)+s(722)][g];if(e.DDJZQ(this[s(1782)].readyState,this.OPEN)&&e[s(1374)](null,v))this[s(1782)]&&this[s(1782)][s(1598)](v),this["_message"+s(722)][g]=null;else break}this[s(1439)+s(722)]=this["_message"+s(722)][s(857)](g=>!!g),this[s(602)+s(1135)+"Id"]=e[s(1366)](setTimeout,()=>this[s(1531)](),l),this[s(1575)+"hOpenEvent"](a),this._isBrowser&&this[s(1782)]&&(this[s(1782)][s(1854)+"pe"]=this["_binaryT"+s(597)]);let f=this[s(1037)+s(1173)]?.[s(1139)+"ntEndpoint"]();this[s(227)](s(365)+f+s(852)),e[s(1775)](n)},Ug=async function(a,n){let s=t,l=this[s(1037)+s(1173)]?.getCurrentEndpoint();this[s(227)](s(365)+l),e.TamQX(n)};class Hg extends Ea{constructor(n){let s=t,l={sLceG:function(_,p,y,C){return e.tNOWz(_,p,y,C)},rrUPW:function(_,p,y){return e.kCWHB(_,p,y)},dnGfK:function(_,p){return _===p},csmob:s(416),xpXyv:e[s(1109)],TeLbG:e[s(362)],qNWvk:function(_,p,y,C){return _(p,y,C)},JZmYR:function(_,p){return e[s(1561)](_,p)},GMbRB:function(_,p,y){return e[s(1492)](_,p,y)},WhurA:e[s(1675)],xlUbk:e[s(981)],NQTZw:function(_,p){return e.MVcQG(_,p)},XlKdv:function(_,p){return e[s(684)](_,p)},seDNt:function(_,p){return e[s(869)](_,p)},jnPxc:e.UWsuV,pDObE:function(_,p){return e[s(1692)](_,p)},yaUEj:function(_,p){return e.dBLlb(_,p)},wDaOp:e[s(1128)],XxofP:"applicat"+s(496)+";charset"+s(1551),UWono:e[s(1333)]};super(),this[s(1687)+s(320)+"line"]=!0,this[s(1748)+"er"]=sr,this._isNode=rg,this[s(337)+"T"]=Rn,this[s(1762)+"X"]=ti,this._isWorker=ni,this["_message"+s(722)]=[],this[s(1037)+"tManager"]=null,this[s(401)+s(1470)]=!1,this[s(1755)+"ype"]=e[s(1383)],this[s(1166)+s(1100)]=!1,this[s(1166)+s(1202)+s(281)]=null,this[s(929)+s(862)+s(523)]=null,this[s(602)+s(1135)+"Id"]=null,this[s(550)]=0,this[s(1720)]=!1,this._url="",this[s(1649)+s(856)]=null,this[s(278)+s(797)]=null,this[s(1341)+s(1090)]=null,this[s(1126)+"ls"]=s(1228),this[s(356)]=3,this.CONNECTING=0,this.OPEN=1,this[s(1276)]=2,this._onOpen=_=>{let p=s;try{l[p(659)](_l,this,_,[Fg,zg,Ug])}catch(y){let C=l.rrUPW(lt,p(1229),{message:y[p(1153)],code:on[p(1038)+"OR"],error:y});this[p(1575)+"hErrorEv"+p(442)](C)}},this[s(349)+"ge"]=async _=>{let p=s,{pingInterval:y,pingFrequency:C}=this[p(1448)];if((_[p(1078)]==="hi"&&l[p(313)](l[p(1794)],C)||l[p(313)](p(1076),C))&&(this[p(689)+p(1289)](),this[p(1318)](l[p(640)],l[p(568)]),this[p(602)+p(1135)+"Id"]=setTimeout(this[p(1531)][p(415)](this),y)),!l.dnGfK("hi",_.data))try{l.qNWvk(_l,this,_,[wg,gg,Mg,Bg,Ng,mg])}catch(O){let U=l.rrUPW(lt,p(1229),{message:O[p(1153)],code:on[p(608)+p(1440)],error:O});this[p(1575)+p(1836)+p(442)](U)}},this[s(954)]=_=>{let p=s,y=this[p(1037)+p(1173)]?.[p(261)+p(1527)+"es"](),C=this[p(1037)+p(1173)]?.[p(1139)+p(768)+"nt"]();if(y&&!_[p(1153)]){let O=p(778)+C+(" fail, m"+p(301)+p(1665)+"ed");this["_dispatc"+p(1836)+p(442)](lt(p(1229),{message:O,code:on[p(1511)+"IES_ERROR"],error:_}));return}this[p(1782)]&&e[p(840)](this[p(1782)][p(980)+"te"],this[p(474)])&&this["_disconn"+p(551)](),this[p(1575)+"hErrorEvent"](e[p(1142)](lt,e[p(1297)],{message:_[p(1153)],code:on[p(1386)+p(901)],error:_}))},this._onClose=async _=>{let p=s;this[p(1671)+p(1418)](),this[p(689)+"ngTimer"](),this[p(1227)+p(466)+"rs"](),this[p(1782)]=null,this[p(1166)+p(1100)]=!1;let y=this[p(1037)+p(1173)]?.[p(261)+"chMaxTries"]();if(!y&&this[p(303)+p(1733)]()&&!this[p(401)+"osed"]){let C=this["_endpoin"+p(1173)]?.[p(1139)+p(768)+"nt"](),O=this[p(1448)]["reconnec"+p(1409)+p(1313)](_[p(275)],_[p(576)]);this[p(1575)+p(1488)+p(442)](_t(p(324),{code:1006,reason:_[p(576)]||p(1547)+"ng failed, unkno"+p(1662)+"n, hostn"+p(252)+C,willReconnect:O})),O&&this[p(1166)]();return}if(l[p(1605)](1e3,_[p(275)])&&this["_readyCl"+p(1470)]){this[p(1575)+p(1488)+p(442)](l[p(1350)](_t,l[p(592)],{code:1e3,reason:l[p(209)]})),this[p(1037)+p(1173)]?.["resetEnd"+p(1751)+p(1084)](),this["_pingLos"+p(1090)]?.[p(1273)+p(1666)]();return}if(l.NQTZw(1e3,_[p(275)])&&y){let C=this[p(1037)+"tManager"]?.[p(1139)+p(768)+"nt"](),O=_[p(576)];O||(O=await l[p(1538)](lg,this[p(543)])),O="connecti"+p(1021)+p(1319)+O+(", hostna"+p(711))+C+(p(1622)+p(1716)+"ached"),this[p(1575)+"hCloseEv"+p(442)](_t(p(324),{code:_.code,reason:O}));let U=p(778)+C+(p(1355)+p(301)+p(1665)+"ed");this[p(1575)+p(1836)+p(442)](l.GMbRB(lt,"error",{message:U,code:on[p(1511)+p(1468)+"R"]})),this[p(1037)+p(1173)]?.[p(341)+p(1751)+p(1084)](),this[p(1341)+p(1090)]?.[p(1273)+p(1666)]();return}if(l[p(1680)](1e3,_[p(275)])&&!_.reason)if(l[p(313)]("TRjlP",l[p(342)])){let C=this[p(1037)+p(1173)]?.[p(1139)+p(768)+"nt"]();this[p(1575)+"hCloseEv"+p(442)](l[p(1350)](_t,p(324),{code:_[p(275)],reason:p(1547)+"ng faile"+p(499)+p(1662)+p(1476)+"ame: "+C})),this["_endpoin"+p(1173)]?.[p(341)+p(1751)+p(1084)](),this["_pingLos"+p(1090)]?.[p(1273)+"nter"]();return}else this.endpoints=_0x57b29a,this[p(1513)+"es"]=_0x24a412,this[p(930)+p(544)]=0,this.currentEndpointTriesCount=0;this[p(1575)+"hCloseEv"+p(442)](_),this[p(1037)+p(1173)]?.[p(341)+p(1751)+p(1084)](),this[p(1341)+"sCounter"]?.["resetCou"+p(1666)]()},this[s(397)]=null,this.onerror=null,this[s(729)+"e"]=null,this[s(582)]=null,this[s(1105)+"econnect"]=null,this[s(354)+s(672)]=null,this[s(1526)+s(219)+s(286)+"ct"]=null,this["_handleO"+s(1619)]=this[s(249)+"nLine"][s(415)](this),this[s(249)+s(1290)]=this._handleOffLine[s(415)](this),this["_handleP"+s(915)]=this["_handleP"+s(915)][s(415)](this),this[s(1356)+s(289)]=this[s(1356)+"ageShow"][s(415)](this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(559)](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(1554)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e.vIKRK,env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:g}=n,v=Array.isArray(f)?f:e.zHPSw(e.WHBlo,typeof f)?[f]:[];if(!v||v[s(1270)]===0)throw new Error(s(1503)+s(266)+s(630));if(!e[s(541)](og,g))throw new Error(e[s(358)]);if(Object.assign(this[s(1448)],n),this["_endpoin"+s(1173)]=new wl(v,this._options.maxRetries),this[s(1341)+"sCounter"]=new dg(this[s(1448)][s(403)+s(1425)]),this[s(1448)][s(1001)+s(1481)])if(e[s(418)](e[s(662)],e[s(662)]))this[s(1720)]=!0,this[s(1166)]();else if(MysuFu[s(1591)](_0x1907cd.payload,_0x6f7b59)){let _=this[s(1448)][s(1309)+s(464)]instanceof _0x1df69e?{force:!!this[s(1448)][s(1309)+"ncoding"][s(1182)],encoding:this._options[s(1309)+s(464)].encoding?this[s(1448)][s(1309)+"ncoding"][s(1325)][s(323)](/\s/g,"")[s(1652)+"ase"]():""}:{force:!1,encoding:this[s(1448)]["payloadE"+s(464)]?this[s(1448)]["payloadE"+s(464)][s(323)](/\s/g,"")[s(1652)+s(760)]():""},p=_0x295a49[s(1309)+"ncoding"]?_0xfa9521[s(1309)+s(464)].replace(/\s/g,"")[s(1652)+s(760)]():"",y=MysuFu[s(1756)](this[s(1448)].payloadType,_0x21dd86)?{force:!!this[s(1448)][s(1774)+"ype"][s(1182)],type:this[s(1448)][s(1774)+s(597)][s(1102)]?this[s(1448)][s(1774)+s(597)][s(1102)][s(323)](/\s/g,"")["toLowerC"+s(760)]():""}:{force:!1,type:this[s(1448)][s(1774)+s(597)]?this[s(1448)][s(1774)+"ype"][s(323)](/\s/g,"")[s(1652)+s(760)]():""},C=_0x1d2205[s(1774)+s(597)]?_0x52cba9[s(1774)+s(597)][s(323)](/\s/g,"")[s(1652)+"ase"]():"",O=y[s(1182)]?y[s(1102)]:C||y[s(1102)],U=_[s(1182)]?_[s(1325)]:p||_[s(1325)],H=["text/pla"+s(381)+s(1616),MysuFu[s(1074)],MysuFu.XxofP,s(340)],ae=[MysuFu[s(1537)],s(373)];this[s(1448)][s(391)+s(487)+s(1307)+"ad"]&&H[s(1221)](O)&&(!U||ae[s(1221)](U))?_0x179386[s(1504)+s(1206)]=MysuFu[s(659)](_0x4b2649,_0x37e563.payload,0,_0x2999df[s(1766)][s(1507)+"th"]):_0x443b14[s(1504)+s(1206)]=""}else _0xc8d1d2[s(1504)+s(1206)]="";this[s(1448)]["listenNe"+s(1604)+s(1092)]&&(this[s(337)+"T"]||this[s(1762)+"X"]?this[s(344)+s(701)+"ange"]():this[s(1748)+"er"]&&this[s(302)+"balEvent"+s(1048)]())}[t(249)+t(1619)](){let n=t;this[n(1448)]["disableA"+n(1617)+n(1101)]||this[n(401)+"osed"]||this[n(601)+n(310)]()}[t(249)+t(1290)](){let n=t;this._destroyWebSocket();let s=e[n(347)](ba,"reconnect",{message:e[n(1729)]});this[n(1526)+n(219)+"yReconnect"]&&this[n(1526)+"mediatel"+n(286)+"ct"](s)}["_initGlobalEvent"+t(1048)](){let n=t;this[n(1748)+"er"]&&window[n(917)+n(1048)](e[n(1709)],this[n(249)+n(1619)]),this._isBrowser&&window[n(917)+n(1048)](e[n(732)],this[n(249)+n(1290)]),this._isBrowser&&window[n(917)+n(1048)](e.Xnfjd,this[n(1356)+n(915)]),this[n(1748)+"er"]&&window[n(917)+n(1048)](e[n(546)],this["_handleP"+n(289)])}[t(1254)+t(577)+t(1048)](){let n=t;if(e[n(526)]===e[n(526)])this[n(1748)+"er"]&&window[n(653)+n(1523)+n(376)](e[n(1709)],this[n(249)+n(1619)]),this[n(1748)+"er"]&&window[n(653)+n(1523)+n(376)](n(1771),this[n(249)+n(1290)]),this[n(1748)+"er"]&&window[n(653)+n(1523)+n(376)](n(654),this[n(1356)+n(915)]),this[n(1748)+"er"]&&window[n(653)+n(1523)+"ner"](e.VWmsj,this["_handleP"+n(289)]);else{_0x3ac07f[n(453)](_0x4145a7)||(_0x31e90b=_0x1fcd15[n(1603)+"er"](_0x25ac2e));let s=e[n(859)](this.high,16),l=e[n(670)](65535,this[n(1831)]),f=this[n(1496)]>>>16,g=e[n(756)](65535,this.low),v=e[n(1754)](_0x317896.high,16),_=e[n(1263)](65535,_0x35bc6a.high),p=e[n(1512)](_0x2aceb4[n(1496)],16),y=e[n(1302)](65535,_0x1cb749.low),C=0,O=0,U=0,H=0;return H+=e[n(1009)](g,y),U+=e.qoLxE(H,16),H&=65535,U+=e[n(1314)](f,p),O+=e[n(726)](U,16),U&=65535,O+=l+_,C+=e[n(1493)](O,16),O&=65535,C+=e[n(1701)](s,v),C&=65535,_0xb1fa01[n(1130)](e[n(1369)](U,16)|H,e[n(1722)](C<<16,O),this[n(968)])}}[t(1356)+t(915)](n){let s=t,l={JmrNF:function(f,g){return e[F(494)](f,g)},BupTq:e.THBHZ,wGtXk:function(f,g){return e[F(269)](f,g)},CJrxz:function(f,g){return e[F(1214)](f,g)},ZOJDI:function(f,g,v){return f(g,v)},ysehC:function(f){return e[F(1574)](f)}};if(!n.persisted)if(e[s(282)](e.ciprZ,e[s(715)]))this[s(1748)+"er"]&&window[s(653)+"entListe"+s(376)](e[s(1610)],this["_handleP"+s(915)]),this[s(1748)+"er"]&&window[s(653)+s(1523)+"ner"](e[s(546)],this["_handleP"+s(289)]),this.close();else return FktREh[s(1698)](typeof _0x439cf9,FktREh[s(411)])?FktREh.wGtXk(_0x24d0ca,_0x1574d4):(FktREh[s(1541)](_0x5e5faf,_0x46136d)&&_0x1cf367(_0x54c8c6),FktREh[s(336)](_0x27a581,_0x283ae1,FktREh[s(1657)](_0x4ed18e))?new _0x5eac9b(_0x27ca6d,_0x2ab670):_0x1f2f79);this._isBrowser&&window[s(653)+"entListe"+s(376)](s(1510),this[s(249)+s(1619)]),this._isBrowser&&window[s(653)+s(1523)+s(376)](e[s(732)],this[s(249)+s(1290)])}["_handleP"+t(289)](n){let s=t;if(e.yENlR!==e[s(1149)])n.persisted&&(this[s(303)+s(1733)]()&&(!this[s(1782)]||e.TNfXv(this[s(1782)][s(980)+"te"],this[s(474)])||e[s(944)](this[s(1782)].readyState,this[s(1040)+"NG"]))&&this[s(249)+"nLine"](),this[s(1748)+"er"]&&window[s(917)+s(1048)](e[s(1709)],this._handleOnLine),this[s(1748)+"er"]&&window[s(917)+s(1048)](s(1771),this[s(249)+s(1290)]));else{if(!this._navigatorOnline()||this[s(401)+"osed"])return;this[s(1037)+"tManager"]?.[s(341)+s(1751)+"fig"](),this[s(1341)+"sCounter"]?.[s(1273)+s(1666)](),this._ws?this[s(1430)+"ect"](1001,e[s(1167)],!0):this._connect()}}async[t(886)+"eUrl"](n){let s=t,l={TwYAy:"success",TSkdS:s(1045)+"e_success",AwlWb:"ping_onc"+s(1433)+"t"};if(e[s(235)](e[s(535)],s(1065)))_0x2ef30b(l[s(1059)]),this.off(l[s(548)],_0x1de966),this[s(1107)](l[s(949)],_0x2f8754);else{let{fpID:f,deviceID:g,bddID:v,ttwID:_,accessKey:p,aID:y,customParams:C={},enableAutoAck:O,enableQoS:U,QoSLevel:H,env:ae}=this[s(1448)],st,cn,dn;this[s(1748)+"er"]||this[s(1762)+"X"]||this._isMiniTT?(st=location&&e[s(1172)]==location[s(1472)]?e[s(718)]:e[s(1745)],cn=n[s(323)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),dn=/^wss(.*:\/\/)/[s(973)](n)?n:""+st+cn):e[s(1287)](s(1365),e[s(1446)])?(st=e[s(718)],cn=n[s(323)](/(^http)((?:[s]*:\/\/))/,""),dn=/(^ws)((?:[s]*:\/\/))/.test(cn)?cn:""+st+cn):(this[s(1318)](e[s(1675)],_0x19e07c),this[s(397)]&&this[s(397)](_0x1ae0d8));let kl=v?e[s(1679)]:_?s(1600):e[s(1750)],Tl=v||_||g;if(e[s(604)](!Tl,!kl))throw new Error(e[s(1020)]);let Gg=e[s(1151)](e[s(977)],typeof C)?await e.zACJw(C):C,qg=ae?e[s(1186)](cg,ae[s(1700)],ae[s(1521)]):{},Ca=Object[s(253)]({device_platform:s(299),version_code:s(1035)+"0",access_key:p,fpid:f,aid:y,[kl]:Tl,xsack:O?1:0,xaack:O?1:0,xsqos:U?1:0,qos_level:U?H:void 0,qos_sdk_version:2,...qg},Gg),jg=Object[s(1303)](Ca).reduce((Pa,Ra)=>Ca[Ra]!==void 0?""+Pa+(Pa?"&":"?")+Ra+"="+Ca[Ra]:Pa,"");return dn+s(723)+jg}}async _connect(){let n=t;if(!(this[n(1166)+n(1100)]||this["_readyCl"+n(1470)])){this[n(1166)+n(1100)]=!0;try{let s=this._endpointManager?.[n(907)+"rentEndp"+n(306)+n(593)+n(997)](),{timeoutInterval:l}=this[n(1448)];if(s){let g=this[n(1037)+n(1173)]?.["getCurre"+n(768)+"nt"](),v=this[n(1037)+n(1173)]?.[n(448)+"ackupEnd"+n(1686)+"UpdateCo"+n(1763)](),_=this["_endpoin"+n(1173)]?.[n(1139)+n(768)+n(1777)+n(957)]();if(v){let p=n(778)+g+(n(972)+", max re"+n(1716)+"ached, w"+n(1473)+n(444)+n(629))+v+(n(389)+"y"),y=e.mekBy(lt,e[n(1297)],{message:p,code:on[n(1511)+n(1468)+"R"]});this[n(227)](p),this[n(1575)+n(1836)+n(442)](y),this._url=await this[n(886)+n(1719)](v),this[n(227)]("connect "+v+" "+_+" times"),this["_removeW"+n(466)+"rs"]()}else{let p="connect "+g+(n(972)+n(1622)+n(1716)+n(1711));this[n(227)](p),this["_dispatc"+n(1836)+"ent"](e[n(1788)](lt,n(1229),{message:p,code:on[n(1511)+n(1468)+"R"]}));return}}else{let g=this[n(1037)+n(1173)]?.[n(1139)+n(768)+n(506)+n(600)](),v=this[n(1037)+"tManager"]?.["getCurre"+n(768)+"ntTriesC"+n(957)]();this[n(543)]=await this[n(886)+"eUrl"](e[n(911)](g,"")),this._debug(n(778)+g+" "+v+" times"),this["_removeW"+n(466)+"rs"]()}if(this[n(1720)])this[n(1720)]=!1;else{let g=e[n(1142)](ba,n(808)+"t",{message:e[n(1241)]});this[n(1105)+n(310)]&&this["onStartR"+n(310)](g)}let f=this[n(1037)+n(1173)]?.["getCurre"+n(768)+n(1777)+n(957)]()||0;e[n(468)](f,1)&&await this[n(1684)](e[n(708)](f,1)),this[n(227)]("connecting url: "+this[n(543)]+(n(480)+n(1282))+this[n(1126)+"ls"]),this[n(1782)]=e[n(1456)](sg,{url:this[n(543)],protocols:[this[n(1126)+"ls"]],headers:this[n(1448)][n(853)+n(660)+"s"][n(1555)+n(594)]},this._options.ws),(this[n(1748)+"er"]||this._isWorker)&&this[n(1782)]&&(this[n(1782)][n(1854)+"pe"]=this["_binaryT"+n(597)]),this[n(1216)+"steners"](),this[n(1166)+"ionTimeo"+n(281)]=e[n(841)](setTimeout,this[n(1413)+"ut"][n(415)](this),l)}catch(s){throw this[n(1166)+n(1100)]=!1,s}}}[t(1671)+"mer"](){let n=t;clearTimeout(this[n(1166)+n(1202)+n(281)]),this[n(1166)+n(1202)+n(281)]=null}[t(689)+t(1289)](){let n=t;if(e[n(976)](e[n(1814)],e.npmFC))e[n(1085)](clearTimeout,this[n(602)+"gTimeoutId"]),e[n(472)](clearTimeout,this[n(929)+n(862)+"tId"]),this["_pingPon"+n(1135)+"Id"]=null,this[n(929)+n(862)+n(523)]=null;else{let s=e[n(1845)][n(842)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(!_0x1676de)return _0x3df685;continue;case"1":if(_0x50696b.utf8Write)return e[n(243)](_0x60842c[n(1674)+"e"](_0xedda31,_0xd057ea),_0x529d36);continue;case"2":return e[n(1728)](e[n(1119)](_0x2d88d5,_0x3aedf1,_0x2b501e,_0xcb4ff2),_0x22776d);case"3":if(e[n(223)](_0x4b8405[n(1270)],40))return _0x1f1fca(_0x1bced2,_0x3b5972,_0x226a00)+_0x3d312e;continue;case"4":if(_0x374569[n(904)])return _0x439989[n(904)](_0x3f0c39,_0x1cfd12)+_0x283093;continue}break}}}[t(227)](...n){let s=t;this[s(1448)][s(1829)]&&console.log[s(1232)](console,[s(962)+">",...n])}[t(345)+t(1529)+"e"](n){let s=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:g}=this[s(1448)],v=l*Math[s(1194)](g,e.DVPzl(n,1));return v>f?f:v}[t(1531)](){let n=t;if(this[n(1782)]&&e[n(1804)](this[n(1782)].readyState,this[n(1040)+"NG"])){this[n(689)+n(1289)](),this[n(602)+n(1135)+"Id"]=e[n(423)](setTimeout,this[n(1531)][n(415)](this),this[n(1448)][n(554)+"rval"]);return}if(!this[n(1782)]||e[n(1300)](this[n(1782)].readyState,this[n(474)]))return void this[n(601)+n(310)]();this._ws&&this[n(1782)].send("hi"),this["_reconne"+n(862)+n(523)]=setTimeout(this["_handleR"+n(310)+n(632)][n(415)](this),this[n(1448)][n(242)+"outInter"+n(826)])}["_handleR"+t(310)+"Timeout"](){let n=t;this[n(1341)+n(1090)]?.[n(1257)](),this.emit(e.yqeVV,e[n(1396)]),this[n(1341)+n(1090)]?.checkReachMaxCount()?this[n(601)+n(310)]():this._ping()}[t(303)+t(1733)](){let n=t;return this._isMiniTT||this[n(1762)+"X"]?this[n(1687)+n(320)+n(1562)]:(this._isBrowser||this[n(1778)+"r"])&&this[n(1448)]["listenNe"+n(1604)+n(1092)]?navigator[n(1621)]:!0}[t(601)+t(310)](){let n=t;!this[n(303)+"orOnline"]()||this[n(401)+n(1470)]||(this[n(1037)+n(1173)]?.["resetEnd"+n(1751)+n(1084)](),this[n(1341)+"sCounter"]?.[n(1273)+n(1666)](),this[n(1782)]?this[n(1430)+n(551)](1001,n(1540)+n(1371)+n(808)+n(1220)+n(1483),!0):this[n(1166)]())}["_onPageNetWorkCh"+t(565)](){let n=t,s={outJZ:function(l,f){return l===f}};this[n(337)+"T"]?tt[n(1746)+"kStatusC"+n(830)](({isConnected:l})=>{let f=n;this[f(1687)+f(320)+f(1562)]=l,l?this[f(249)+f(1619)]():this[f(249)+f(1290)]()}):this._isMiniWX&&wx["onNetwor"+n(909)+n(830)](({isConnected:l})=>{let f=n;if(s[f(588)](f(900),f(1828))){let g=_0x209954[f(1153)][f(1766)];g&&_0x3e1af8[f(384)+"rs"](g)}else this["_miniNav"+f(320)+"line"]=l,l?this[f(249)+f(1619)]():this[f(249)+f(1290)]()})}[t(1684)](n){return new Promise(s=>{let l=F;e.kzMJv(setTimeout,s,this[l(345)+l(1529)+"e"](n))})}[t(1430)+t(551)](n=1e3,s="",l=!1){let f=t;if(e[f(210)]===e[f(964)])this["currentE"+f(398)+f(1292)+"t"]=0;else{if(!this._ws)return;this[f(1412)+f(467)+"t"](n,s,l)}}[t(1413)+"ut"](){let n=t,s=this[n(1037)+n(1173)]?.[n(1139)+n(768)+"nt"]();this[n(227)](n(778)+s+n(972)),this[n(1430)+n(551)](1001,e[n(433)],!0)}[t(1271)](n){let s=t,l=e[s(1466)](Ut,n);this[s(1782)]&&e[s(279)](this[s(1782)][s(980)+"te"],this[s(474)])&&(this[s(1782)]&&this[s(1782)][s(1598)](l),this._debug(e[s(678)],n))}[t(1227)+t(466)+"rs"](){let n=t,s={dcacY:e[n(517)]};if(e[n(661)](e.YLRCK,e[n(1421)])){let l=e[n(1739)][n(842)]("|"),f=0;for(;;){switch(l[f++]){case"0":this[n(1782)][n(653)+n(1523)+n(376)](e[n(1772)],this[n(730)]);continue;case"1":if(!this[n(1782)])return;continue;case"2":this._ws["removeEv"+n(1523)+n(376)](e[n(1297)],this[n(954)]);continue;case"3":this[n(1782)][n(653)+"entListe"+n(376)](e[n(1061)],this[n(349)+"ge"]);continue;case"4":this._ws["removeEv"+n(1523)+n(376)](e.FrXxQ,this._onClose);continue}break}}else this[n(1318)](s[n(984)],_0x438ae4),this[n(354)+"eAck"]&&this[n(354)+n(672)](_0x44430b)}[t(1216)+t(1006)](){let n=t,s=e.pcLoI[n(842)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[n(1782)])return;continue;case"1":this[n(1782)][n(917)+n(1048)]("error",this[n(954)]);continue;case"2":this[n(1782)][n(917)+n(1048)](e[n(1675)],this[n(935)]);continue;case"3":this[n(1782)][n(917)+n(1048)]("open",this._onOpen);continue;case"4":this[n(1782)]["addEvent"+n(1048)](e.SIQHW,this[n(349)+"ge"]);continue}break}}[t(1500)+"nceClose"](n=1e3,s=""){let l=t;try{this._ws&&this[l(1782)].close(n,s)}catch{}}[t(1412)+t(467)+"t"](n=1e3,s="",l=!1){let f=t;if(this[f(689)+f(1289)](),this[f(1671)+f(1418)](),this[f(1227)+"sListeners"](),this["_wsInsta"+f(547)](1e3,s),this[f(1166)+f(1100)]=!1,l&&this[f(303)+f(1733)]()&&!this[f(401)+"osed"]){if(this[f(1037)+"tManager"]?.[f(261)+f(1527)+"es"]()){let v=this[f(1037)+f(1173)]?.[f(1139)+"ntEndpoint"]();this[f(1575)+f(1488)+f(442)](e[f(1456)](_t,f(324),{code:1006,reason:f(778)+v+(f(972)+f(1622)+"tries reached"),wasClean:!0}))}else if(e[f(1279)](e[f(618)],e.oCYiy)){let v=_0x341875[f(463)+"g"](0,e.vlhqd(4,_0x118422.length)),_=v[f(1730)](_0x475460);_0x59bb3c.push(_)}else{let v=this._options[f(808)+f(1409)+f(1313)](n,s);this[f(1575)+f(1488)+"ent"](_t(e.FrXxQ,{code:n,reason:s,wasClean:!0,willReconnect:v})),v&&this._connect()}return}this._navigatorOnline()||this["_readyCl"+f(1470)]?this[f(1575)+f(1488)+"ent"](e.kCWHB(_t,e[f(1675)],{code:n,reason:e[f(981)]})):this["_dispatc"+f(1488)+f(442)](e[f(1373)](_t,e[f(1675)],{code:1006,reason:e[f(1120)]})),this._ws=null,this[f(1037)+f(1173)]?.["resetEnd"+f(1751)+f(1084)](),this[f(1341)+f(1090)]?.[f(1273)+f(1666)]()}["_dispatc"+t(851)+"nt"](n){let s=t,l={ZJNma:e[s(1213)]};e[s(1643)](e[s(233)],s(974))?(this["_pingLos"+s(1090)]?.[s(1257)](),this[s(1318)](JpuwWE[s(1097)],s(1571)),this[s(1341)+"sCounter"]?.[s(261)+s(307)+"nt"]()?this["_handleR"+s(310)]():this[s(1531)]()):(this[s(1318)](e[s(1772)],n),this[s(582)]&&this.onopen(n))}[t(1575)+t(1144)+t(1176)](n){let s=t;if(e.uzjbU(e[s(1559)],s(438)))this[s(1318)](e[s(1061)],n),this[s(729)+"e"]&&this[s(729)+"e"](n);else return(this[s(825)+"rs"][_0x668acd]||(this[s(825)+"rs"][_0x26a7b5]=[]))[s(394)]({fn:_0x4a4fc8,ctx:_0x3d6a25||this}),this}[t(1575)+t(1693)+t(1583)](n){let s=t;e[s(657)](s(1613),e[s(1681)])?(this[s(1318)](e[s(517)],n),this[s(354)+s(672)]&&this["onReceiv"+s(672)](n)):(e[s(934)](_0x5985ca,2048)?_0x39be4c[_0x976471++]=e.CPupp(e[s(919)](_0x4c63fc,6),31)|192:(e[s(1830)](_0x3283fd,65536)?_0x2dd4ff[_0xc613b0++]=_0x248750>>12&15|224:(_0x485a08[_0x274ca7++]=e.hCvod(e[s(377)](e[s(919)](_0x32deb5,18),7),240),_0x1a46fc[_0xe7b171++]=e.BCquO(e[s(958)](e[s(919)](_0x40adb1,12),63),128)),_0x48f6fc[_0x1d3a74++]=e[s(311)](e[s(818)](_0xe942f2,6),63)|128),_0x4ba554[_0x53ae52++]=e.yXDkE(e[s(1125)](63,_0x13c5d5),128))}[t(1575)+t(1836)+t(442)](n){let s=t;this[s(1318)](e[s(1297)],n),this.onerror&&this[s(955)](n)}[t(1575)+"hCloseEvent"](n){let s=t;this[s(1318)](e[s(1675)],n),this[s(397)]&&this[s(397)](n)}get[t(1854)+"pe"](){let n=t;return this[n(1782)]?this[n(1782)][n(1854)+"pe"]:this[n(1755)+n(597)]}set[t(1854)+"pe"](n){let s=t;this["_binaryT"+s(597)]=n,this._ws&&(this[s(1782)].binaryType=n)}get[t(816)+"nt"](){let n=t;return this[n(1037)+n(1173)]?.[n(1139)+n(768)+n(1777)+n(957)]()||0}get bufferedAmount(){let n=t,s=this["_message"+n(722)][n(587)]((l,f)=>(l+=f&&f[n(1507)+"th"]||0,l),0);return e[n(1860)](s,this[n(1782)]?this[n(1782)][n(1443)+"Amount"]:0)}get extensions(){let n=t;return this[n(1782)]?this[n(1782)][n(635)+"ns"]:""}get protocol(){let n=t;return this[n(1782)]?this[n(1782)][n(1472)]:""}get readyState(){let n=t;return this._ws?this._ws[n(980)+"te"]:this[n(1448)][n(1001)+n(1481)]?this[n(1040)+"NG"]:this[n(356)]}get[t(616)](){let n=t;return this[n(1782)]?this._ws[n(616)]:this[n(543)]}[t(324)](n=1e3,s){let l=t,f=e[l(895)][l(842)]("|"),g=0;for(;;){switch(f[g++]){case"0":if(this[l(1782)][l(980)+"te"]===this[l(356)]||e[l(1847)](this._ws[l(980)+"te"],this[l(1276)]))return void this[l(227)](l(211)+l(1760)+"y closed");continue;case"1":this[l(401)+l(1470)]=!0;continue;case"2":this[l(1671)+"mer"]();continue;case"3":this[l(1254)+l(577)+l(1048)]();continue;case"4":if(!this._ws)return void this[l(227)](e[l(1086)]);continue;case"5":this[l(689)+"ngTimer"]();continue;case"6":this[l(1412)+l(467)+"t"](n,s);continue;case"7":this[l(1649)+l(856)]?.closeDB();continue}break}}async[t(1598)](n,s){let l=t;if(e.tDMHM(null,n))throw new Error(l(1503)+l(1299)+" valid d"+l(988)+l(1609)+l(1471)+"ng or an arraybuffer");l(866)==typeof n&&(n=JSON[l(1450)+"y"](n)),e[l(1707)](e[l(520)],typeof n)&&!e[l(887)](n,ArrayBuffer)&&!(n[l(1572)]&&e[l(1630)](n[l(1572)],ArrayBuffer))&&(n=JSON[l(1450)+"y"](n));let f=await e.VsNbb(El,n),g=e[l(586)](ag,n),{method:v=0,service:_=this[l(1448)][l(609)],logID:p=this[l(1448)][l(1757)+l(217)](),headers:y=this[l(1448)].headers,payloadEncoding:C=this[l(1448)][l(1309)+l(464)],payloadType:O=this[l(1448)][l(1774)+l(597)],logIDNew:U=this[l(1448)]["logIDNew"+l(1195)]["enableAu"+l(739)+"teLogIDNew"]?i(this[l(1448)]["logIDNew"+l(1195)][l(1459)]):""}=e.uzFkW(s,{});if(!_)throw new Error(e.VffVW);let H={SeqID:he.fromNumber(this[l(550)]++),LogID:he[l(1603)+"er"](p),service:_,method:v,headers:y,payloadEncoding:e[l(1546)](C,Object)?C[l(1325)]?C[l(1325)]:"":C,payloadType:e[l(1478)](O,Object)?O[l(1102)]?O.type:g:O||g,payload:f,LogIDNew:U},ae=e[l(304)](Ut,H);if(this[l(1782)]&&e.vSZFO(this[l(1782)][l(980)+"te"],this[l(474)]))if(e[l(1593)]!==e.Ugkpi){if(_0x511bbb)return new _0x118bef(_0x10790a[l(616)],_0x28acbe.protocol);if(e[l(1317)](_0x28b00b,_0x29b99d))return new _0x20f1ee(_0x33323b[l(616)],_0x558efa.protocol,_0x345c88[l(268)]);if(e.JfQyc(_0x4c65df,_0x142120)&&e[l(1077)](e[l(1852)],typeof _0x576371)&&_0x12f644)return new _0x26c5c7(_0xf71303[l(616)],_0x20ffc2.protocols)}else this[l(1782)]&&this[l(1782)][l(1598)](ae),this[l(227)](e.hzhaz,H);else if(this[l(1439)+"Queue"][l(1270)]<this._options["maxMessageQueueL"+l(504)])if(e[l(1310)](l(1331),"SRXrQ"))this[l(1439)+l(722)][l(394)](ae),this[l(227)](e[l(595)],H);else return _0x18e0a5&&e[l(1114)](!0,_0x1c4eae.isLong);else this._messageQueue[l(658)](),this[l(1439)+l(722)][l(394)](ae);return{seqID:this[l(550)],logID:p,logIDNew:U}}async[t(808)+"t"](n){let s=t;if(e[s(844)]("CsbkO",e[s(1019)]))throw this[s(1166)+"Lock"]=!1,_0x176838;{let{url:l}=e.AWkMy(n,{}),f=Array[s(1713)](l)?l:e[s(1419)](e[s(520)],typeof l)?[l]:[];n&&Object[s(253)](this[s(1448)],n),f&&f[s(1270)]?this[s(1037)+s(1173)]=new wl(f,this[s(1448)][s(1513)+"es"]):this[s(1037)+s(1173)]?.[s(341)+s(1751)+s(1084)](),this[s(1341)+"sCounter"]?.[s(1273)+s(1666)](this[s(1448)][s(403)+s(1425)]),this[s(401)+"osed"]=!1,this[s(1782)]&&e[s(292)](this[s(1782)][s(980)+"te"],this[s(356)])?this[s(1430)+s(551)](1e3,e.Bcrbk,!0):(this[s(1720)]=!0,this._connect())}}async[t(685)](){let n=t,s={oaFlg:function(l,f){return e[F(1317)](l,f)}};if(e[n(1570)](e[n(1129)],e[n(1129)])){let l=this._qosDB[n(710)+n(1187)](this[n(1858)]),f=_0x2975f0[n(1056)](XoiiLQ[n(1212)](l,"{}"));return f[_0x310e24||_0x1f3ef7[this._pathKey]]=_0x547e21,this[n(505)][n(1401)+n(1187)](this._prefix,_0x499e2f[n(1450)+"y"](f)),_0x52a319||_0x473f1d[this[n(213)]]}else if(!this[n(1166)+n(1100)]){let l=e[n(1487)].split("|"),f=0;for(;;){switch(l[f++]){case"0":this[n(1341)+n(1090)]?.[n(1273)+n(1666)]();continue;case"1":this[n(1720)]=!0;continue;case"2":this._connect();continue;case"3":this[n(401)+"osed"]=!1;continue;case"4":this["_endpoin"+n(1173)]?.[n(341)+n(1751)+"fig"]();continue}break}}}[t(917)+t(1048)](n,s){this.on(n,s)}[t(1451)+t(1176)](n){let s=t,{type:l}=n;this[s(1318)](l,n)}[t(653)+t(1523)+t(376)](n,s){this[t(1107)](n,s)}[t(1818)](){let n=t,s={iIWru:function(l,f){return e[F(1636)](l,f)},TnFeK:e[n(1109)],iSkpX:n(1045)+"e_timeout",tzqRz:function(l,f,g){return e[n(1142)](l,f,g)},SuiPK:function(l,f){return e[n(1647)](l,f)},tIznB:e[n(749)],pGZih:e[n(362)],hcdcS:function(l,f,g){return e[n(1186)](l,f,g)}};return new Promise((l,f)=>{let g=n,v={nXbEi:function(y,C,O){return s[F(267)](y,C,O)},eLjXr:function(y,C){return s[F(740)](y,C)},nuORs:function(y,C){return y===C},KgEmZ:s.tIznB,qGJoU:s.pGZih};this[g(689)+g(1289)](),this[g(602)+g(1135)+"Id"]=s[g(1327)](setTimeout,this[g(1531)][g(415)](this),this._options.pingInterval);let _=()=>{let y=g;if(v[y(1087)]("FoCxD",v[y(412)])){let C=_0x269241();return vGrUTi[y(1211)](_0x82433b,_0x1fedc7,C),vGrUTi[y(557)](_0x97f5ea,C)}else l(v[y(521)]),this[y(1107)](y(1045)+y(920)+"s",_),this[y(1107)]("ping_onc"+y(1433)+"t",p)},p=()=>{let y=g;s.iIWru(f,y(1571)),this[y(1107)](s.TnFeK,_),this[y(1107)](s[y(1615)],p)};this.on(s[g(651)],_),this.on(s[g(1615)],p),this[g(1531)]()})}}})(),Be["CustomCl"+M(656)]=Re[M(924)+"oseEvent"],Be[M(1824)+M(966)]=Re[M(1824)+M(966)],Be[M(529)+"e"]=Re[M(529)+"e"],Be.Event=Re[M(1176)],Be[M(963)]=Re[M(963)],Be[M(822)+"MessageE"+M(465)]=Re[M(822)+M(803)+M(465)],Be[M(803)+M(465)]=Re[M(803)+M(465)],Be.OpenEvent=Re[M(256)+"t"],Be[M(437)+M(837)]=Re[M(437)+"tEvent"],Be[M(751)+"oseEvent"]=Re[M(751)+"oseEvent"],Be[M(1390)+M(966)]=Re.createErrorEvent,Be[M(1661)+M(1222)+"nt"]=Re["createMe"+M(1222)+"nt"],Be["createOp"+M(795)]=Re.createOpenEvent,Be[M(1253)+"connectEvent"]=Re[M(1253)+M(450)+M(465)],Be[M(236)+M(1098)]=Re[M(236)+"rame"],Be[M(1160)+M(584)]=Re["encodeFr"+M(584)];for(Zo in Re)[M(924)+M(656),"CustomEr"+M(966),M(529)+"e",M(1176),M(963),M(822)+M(803)+M(465),M(803)+"vent",M(256)+"t",M(437)+"tEvent",M(751)+M(656),M(1390)+M(966),M(1661)+"ssageEvent",M(425)+"enEvent",M(1253)+M(450)+M(465),M(236)+M(1098),M(1160)+M(584)][M(762)](Zo)===-1&&(Be[Zo]=Re[Zo]);var Zo;Object[M(1668)+M(854)](Be,M(792)+"le",{value:!0})});import{existsSync as dS,openSync as lS}from"node:fs";import{mkdir as uS}from"node:fs/promises";import{dirname as fS}from"node:path";import{fileURLToPath as xS}from"node:url";function pS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Jd(t=J()){return dS(t.libEntry)?t.libEntry:xS(new URL("../index.ts",import.meta.url))}async function hp(t={}){let e=t.paths??J(),r=t.entryOverride??Jd(e),i=pS(e,process.env.COZE_BRIDGE_LOG_MODE);await uS(fS(i),{recursive:!0});let o=lS(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=it(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[ds]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return hS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var hS,ds,da=et(()=>{"use strict";Jt();te();Ce();hS=j("spawn-daemon"),ds="COZE_BRIDGE_DAEMON"});import{spawn as f2}from"node:child_process";import{mkdir as x2,unlink as h2,writeFile as p2}from"node:fs/promises";import{dirname as g2,join as m2}from"node:path";function Zr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function w2(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Zr(r)}</key>
21
- <string>${Zr(i)}</string>`).join(`
20
+ `+n)}function tr(t,e,n,i,o,c){if(t.listenerCount("wsClientError")){let l=new Error(o);Error.captureStackTrace(l,tr),t.emit("wsClientError",l,n,e)}else as(n,i,o,c)}});var ip=le(Fe=>{"use strict";var F=z;(function(t,e){let n=z,i=t();for(;;)try{if(parseInt(n(684))/1*(parseInt(n(201))/2)+parseInt(n(283))/3+-parseInt(n(1099))/4*(-parseInt(n(1476))/5)+-parseInt(n(783))/6+-parseInt(n(1050))/7*(-parseInt(n(1629))/8)+-parseInt(n(451))/9*(parseInt(n(1511))/10)+-parseInt(n(805))/11*(-parseInt(n(664))/12)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(sa,780984);var TS=Object[F(1137)+F(790)],RS=Object[F(1521)+"opertyNames"],Qx=(t,e)=>function(){return t&&(e=(0,t[{mBfBu:function(c,l){return c(l)}}[F(711)](RS,t)[0]])(t=0)),e},PS=(t,e)=>{let n=F,i={JgbgQ:function(c,l,u,h){return c(l,u,h)}};for(var o in e)i[n(1483)](TS,t,o,{get:e[o],enumerable:!0})};function CS(){return Vx||(Vx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function sa(){let t=["q29UzMLN","zwLZwwm","o2nOyxjZzxq","uhzrrhy","rwTTAwm","uKTuv3i","Aw5N","u3LNr3O","tfPqCeu","DhfnvLa","AwDHDg9Yt24","ywnRDxbfBMq","AwfnzMW","CNzHBa","CM92AwrLige","yKTmvKm","mhWY","A25Zq2m","zxq9DxrMltG","EwTLz3m","D250qMe","EwfcDKC","D0j6A3q","ExHiChi","su5QAgu","t3DLvLq","q25nswe","rvHzsNC","AKnkveO","Dg9cExrLC0i","BwnkChq","twjnELq","y2HnyxHdB3u","s0zJwvm","y2HHCKnVzgu","yMfSrxzLBNq","whD0BxC","rxjYB3jdB2q","uxvsBwO","B1vKuLG","DxrVuMvJB24","Bw5yBw0","Dg9mB3DLCKm","ug5wt3e","CLzHBhvLCW","CMvHC29U","r1vZBxm","A0HTzhO","zg9Uzq","CMvJB25Uzwm","D1rmBxu","EKDyCKG","B2nRzxrtDwm","thzmvNi","B3jLtMfTzxm","tMjus0u","x3jLBw92zvC","CKTqs0K","y3r4","BNrfBMrWB2K","A0Liv0C","DfrIwvu","C2vQzw0","yNLL","wKreD1C","zgLZCgf0y2G","B0Lksu8","BLD2zKK","r1jAALu","u2TPCcbWyxm","sevxuxe","q21lAhe","zxmGCMvHy2G","uM52seG","x3fVC0rc","r0nowwG","wMPyBLC","rNjVBNrPzxi","ruv4r1a","CKjwqLm","ohW2Fdn8n3W","CxrUtfi","C2v0y3vYC28","igXHCMDLCIa","tufyx1jfvfi","yNvMzMvY","Ahr0Ca","DvvYtuu","AKv0vhC","uLvTDeq","shPzyui","rhHmqLC","seXtrwq","x2n1CNnVCK4","r3vpBKm","x3nLCuLK","yM9KEq","t0LHtuC","CMDKzvq","sLn6z0W","B25mAw5L","ruTeD1y","yNzQqLm","yNL0zu9MzNm","BMnLq2XVC2u","x3bYzwzPEa","rKjjy3K","AwDWqu0","y0jfwfi","u0PoDMu","C0Xf","uMvHzcbWyxm","ywnOzwq","yxbWBhK","vhf0s0y","vunhzM4","CNnVCKzPBgu","CxjYDM8","zKvzvvi","zKffvem","rgrOvge","BhzrvLq","yMLUyxj5vhK","zK5XD2K","AxjLza","DMzHt1e","CMvXDwLYzwq","swD0s0W","x2HHBMrSzvi","yxrHlcbKyxq","tKrRv1C","EwLbrw0","qK1JwKq","zMzmAw5L","s0nWBeK","s1PcseK","mhW1Fdf8mNW","BhzIqwG","twLZC2LUzYa","aaaaaaaaaaa","x3DHAxq","qNzjuLe","yKfKBg4","zgDzuMu","Aw9Ul2PZB24","uvjVzxi","Ae1ruNu","BxHuy2G","q3vZDg9Tq2W","zhLOAgu","B1nNueG","B1bAAMS","B2ncCLm","CLvnENO","C3nHz2vfDMu","vMj4CwC","z3rPvuO","AgvHzgvYCW","x3bPBMC","BNrLCG","ze1qv24","zMz6tK8","uuTIv2i","Ce91EgW","rfnoD2K","wenQuwO","yK1TEM0","AhnqAMm","AM9cwK8","CgLUz0LUDgu","y3jLyxrLt3a","AxnAzxjV","rLjptLrjrvi","A2v5","zMLxuxq","C2HktvO","x2rYB3bhBg8","BwXrBfq","tMfTz3q","rg1RrKK","Be5IDw4","mNWW","BLzHr2C","BxHwBKW","quPyv3y","t3LrC1G","ENbprg4","zwXZAK0","yxKSihrYEsa","y29UBMvJDeu","DgzRy0i","yKPnB0m","C29Tzq","zMLN","Ag1Kq2C","AM9oBhO","wKHWCKq","DLPNvuq","AuLTz2q","quLQyMK","BwLZzq","rwLusMu","tuXvENe","CNnVCL9Uyw0","vwznz2S","Evvvy0G","y2f0y2G","u3zjAvG","ndC4mdu1wLDXuuvj","y3jLyxrLrwW","Dwn6uhK","CMvZzxrfBMq","x2n1CNnVCKy","EfvZzuvUDG","AM1ktKW","sMDIz1e","qw14uvq","s1rMwfG","x2LZsw5PDa","AuPQAfK","x2zVCM1HDeu","u2vYDMLJzvC","CMvWBgfJzq","y3vYC29Y","A3nKB1y","x2DLDeLUDgu","zxjHDg9Y","BKndy2G","s0DUrKK","zhf6BLu","y3vYCMvUDeK","Aw9U","q0vLsfC","AunPEwO","t1fTBLm","vvfNv3G","qwT3s1K","yNvMzMvYzwq","sg5WwxC","B25SAw5L","Dendt2e","DxrMofDYAxq","rKLkA2u","mtbIrhrkueK","ruPoEMS","B25JBg9Zzq","y3ruAw1LB3u","CeXZzNO","uLrtCLy","tMzLAey","wM9HAKC","CwjqA2m","BMnpwvK","z2v0t3DUuhi","ChnLDNm","vvP1Ag8","weX4vw0","qu5Jv2K","Aw5KzxG","vvrRzgW","t1bftG","z1Lbteq","sMvcq1i","vwTxBMy","veDVsMW","m3WXFdv8nhW","ufvhuvK","Bg9NsurozxC","B1fXAgC","u3rYyxrLz3K","zv90Aw1LB3u","C3rYAw5N","DhbizwfKzxi","q3jlBwS","BM9Uzv9UB24","EKfTBKm","ANLKqMq","tg9Nsuq","y3bOs2y","ihrYEsbYzwm","wLbcswq","zxrxB3jRq2G","u2f2s3e","x2jPBMfYEvq","u0P3wg4","EwTIs2W","ugXozxa","tLfdBeC","Bg1Ls24","AenSB3nLrxy","qMr5Bxy","AK5PwLG","sMjfyxa","tKDFrvjst1i","q3vZDg9Trxi","yu9yCue","DeLUDgvYy2u","seX6BhO","B1DbwhO","ExHPAw0","z0T1tgS","vw5Oyw5KBgu","C2vUzf9Hy2S","AgfZt3DUuhi","ihrPBwvZ","t2LLBw0","uNzvDeS","BK1irwW","tvr1EKW","twver1u","BfrPBwvVDxq","C0nVDw50zxi","tfnJC0G","zw5fDMvUDa","z2v6uuC","sMDPBuy","BLrKBu4","ywXS","ufjjEeK","DvzPvee","qLDVz1i","y0zLwKG","u0D5AMO","Avn3sMC","r25XC3O","twTgv0W","Aw5KzxGGB3u","rvj1DMC","uxPWy1y","rKDivMe","rNPsAu8","whL5Dem","EM1bCMC","y2XVC2u","mxWZFdr8mNW","DgfYz2v0","whHyEuS","ChjVy2vZCW","uLjpuG","sfbWr3m","Aw5PDcbrB1m","rLrlteS","uMXxyNa","rKzbAvK","D0HqsLK","CMvZB2X2zq","x2rLC3rYB3K","sMTSBgK","D3nZoI8V","mhW0Fdn8mxW","rLjQC0m","Aw1LCYbPBIa","C0XPC3rLBMu","mxWWFdj8nhW","Aw5KzxHpzG","EfjRy1u","wMn1Ahe","x2XPC3rLBMu","yxGGCMv0CMK","yNPqDvy","ig1LC3nHz2u","odHuzxvyyuC","vLDeBxG","sM95re0","CwLHB08","tK1iyNm","wLjJvfq","rhjJB2e","vfbNywS","s292tgu","AMHsChy","yuTiD2y","DcbSAw1PDa","DxDVCvO","AM9PBG","svHsthm","yxPlyxy","DhjPBq","EMzNqM4","ChrVCG","DgjnBK4","vMzqteq","v2vIu29JA2u","DhDPyva","quTiEKy","BwvZC2fNztO","x3jLy29UBMu","zNvUy3rPB24","CYbPBNn0yw4","z0Xeq2K","x2rLyNvN","Ce1vyvG","rxbLBw4","vLvbq1O","B3vUDa","B2rbvLe","u2fIr20","ufDhveS","zv9ZDwnJzxm","x3bPBMDqB24","BMrWB2LUDca","yxbvtM0","vvLIu0u","tKfusvzfx0u","weHHwMW","zNzcDvG","u2f5DNa","AxzVChm","rfHJy1i","sKHbqNu","y29UBMvJDa","BhrPCgXLihq","C2fNzq","yxv0BW","D2HYuLC","EsbJBg9Zzwq","x29Ut3bLBG","D3jPDgu","r0fly1G","wvvly1e","Bxztz0K","A0LxuKK","BhfJzM8","Dg9cExrLC0W","zwPrCuq","Bg96AfO","BK11BMe","zgTMEK0","AM14Agi","vxPiqvm","s1vJAhK","yK5XwMW","q1PoBwq","BKLtq24","A0fxzKy","sKX2tMK","q1byuMm","zMX1C2HfEha","C2v0","vMPtBg4","tgffALy","ihrVihjLDhi","Bhm6ia","t2jQzwn0","rvLWwhG","ywDLu2HVDW","C1jTsuO","wK1VDLu","y2Psu2u","wNjIr28","DMfS","EeXRu1q","rNDqBfK","ruXTCvK","s3LduLO","teLeqxG","CNvkC3K","vg11Euq","Dg9tDhjPBMC","yMvrteS","t1HUu08","D3LzDKC","ChvZAa","yufVwNq","uefRCMq","C3vIC3rYAw4","uMvJB25Uzwm","ywXSq3vYC28","Eg1bwNG","yxjYyxLIDwy","AxfvCvG","zxbKDhi","B3nLza","y0ffB24","u1zfDgW","ufDdsu4","t3jPDMm","BKzHvfq","CKfkreC","BMv4DcGPigm","AxnmB25N","B2XKvMvYC2K","EeTfrwS","yMXVy2TLza","uNfhuwG","s2zUExe","zufJAW","qKDXDuK","zNjpvLi","Bgzcs2O","yuvzvxm","CNjVCK1LC3m","runVrwC","CgXLyxnLiha","B1v0se0","r0jcuvG","teriBMi","ywnOzwqSihC","BwfUDwfSihi","rLDt","B2nRzxq","BMvY","DgvmB2Djre4","BNnMv1y","v0rUvKu","mM9ZrePuyq","ysbTDxn0igi","ywnR","tuLyDu4","zNjVBuHHC2G","BK90Bxm","zw5NDgG","mNWWFdr8m3W","CM9ArLi","zw50","rKzfD0S","Bfjbqwm","DeTVBMG","B2zMBgLUzq","B3HYDK8","BMfTzq","DMjSEuS","zgvSzxrLrge","uwHpCLe","AwrI","CMvZzxrdB3u","zNjVBNrPzxi","ueDVCui","Du9dyLi","ywrK","zM1TseK","x2LUAxrqCM8","EKfmz20","Axrqwhy","z2u6ia","DgHHBIbSB2m","rgH6AM4","B25fCNjVCG","C3rLBMvYCW","seviuvm","x2rItMfTzq","CMvTB3zLq2G","CLfpDfG","B25LCNjVCG","CgfYC2u","ELzoBue","mtb8nhW5","DKTPsvm","Ef9MCM9UDgK","B2LUDfjLywm","CMHQsKO","vxPwvfe","q2zPqvi","De1HBMfNzxi","x2nSzwfYvgK","Cw9Zx18","ww15yMG","x29UrxjYB3i","zcbLCNjVCI4","wxrwvvK","t0fwD0O","DeLK","AwXK","zgvS","zw5JB2rPBMC","t3bLBKv2zw4","vgPAq1q","ruDsvwK","vMPtB2y","uNPbtM4","t1Lor1u","rKLmrv9ot1q","x25HDMLNyxq","y29TCgXLDgu","ywDLrxzLBNq","t2f3veu","D3bjv2C","DMfSDwu","z2v0","AxrxuLq","yw1LoIa","zxH0zw5ZAw8","Bwv0Ag9K","BgvUz3rO","Dw1qu1C","uuPQrKS","A2ftqu4","mJCZnJuYnwLhAgTdAG","sLDsDMu","AxnrB1nby2S","BwLUzW","B2nRzxrgywK","u1z4qLi","q3nfBNG","CNDlsw4","q2zAA04","zw5JB2rLrNi","yuPctg4","sxLdDwe","y0TSuxy","s2PuAxu","AwXSihvZzsa","D3jPDgvvAw4","yLbzyM4","B1nWAKe","zwX1weq","CMLLC0nVDw4","y3zhD2u","B2L3A3e","mdaWmdaWmda","AxnrB1nnzxm","y3vZDg9Tshq","wg1jtMK","C2DPza","sxL4CMq","zgvIDwC","rNLlC00","rgfpt3a","wMr5AgO","D2fZq2XLyw4","C29YDa","svvmvuC","wNr5Duq","DNjhrva","rMvpwxi","rhjny1u","yxv0B21HDgK","C2vYDMvYvgK","zNjVBu51Bwi","ChHgDgC","yxrdv2C","Dwzts1m","Dw50","yxnL","tKngDhy","CMvUDevUzha","lcbTyxGGCMu","AKD5zeW","q0fZww8","vvzADxe","rejrB00","tMfTzq","Aer2wui","r3zTDMC","yKTsA2S","x3nLBMrby2S","Dgfcz1K","x29UugfNzu4","l3DZl3yY","BNrbBMrvCgq","AefJA01LC3m","CKzsBvi","BvPWq08","DMfSDwvZ","vgvXAMK","q2TIzw4","rwHlvNu","EgvssLC","Dvvtu3i","AeDAy0W","twHUq1a","Aw9nALO","C2XPy2u","y29Uy2f0","t3DMtMK","yur2Be0","ywzOA08","Aw50zwDLCIa","D2vQtuC","Ae9Wzw5fDMu","BeHABhG","B0j2Cwy","wLjABM0","tLLmA0u","BMCGzMfPBgu","sML4ruW","B2XVtK0","EvLmrM0","C29Myum","yw1Lu3bHy2u","EwPctfe","zvjLD24","Dgr0C2i","y3vYC29Yx24","nhWXFdj8mhW","vKPwAg0","BMj3B2q","EvbJDwy","uwfWs1i","qxvbwgK","zhPxqvC","tK9ms1y","CMTnCKq","x3DZsw5ZDge","DMTmAfi","yw1L","x2LZtwLUAvC","ywr2yw5Jzq","AKfbtxe","svPtsgy","s0LYEfC","s0Pbwhq","q2H1zLa","DhjPzxm","rvjst1i","C2vUza","wuDVtKq","zxjYB3i","tgTOvMu","zNjVBuj5Dgu","ywnRtxnNswq","shnjsMy","y3jLyxrLrxi","ihrPBwvVDxq","B3jRig9MzMW","CMrewge","CLrrEM8","zw1PDa","whbduxG","EgPMA3G","zuvJD1a","q2Lws1G","Dhj1y3rVCIa","CMvQzwn0","tendwuy","DgntCgK","CNPzBhu","x29UvgLTzw8","AxnszwfKEq","reDjs28","CMTLCKDSB2i","rKnUsei","Cu91DwC","DMvYC2LVBG","z2v0qwXSs2u","Aw9UvgLTzw8","CezNu2e","C3vJy2vZCW","rK9hteq","q0Xpu0ve","DgLTzw91Da","thLkCwS","BgLZDgvUtMu","Ae1pB1K","y2XVC2uSihC","vwvcqvC","DhjHBNnHy3q","Dev2zw50","z09ZEvG","CMvTB3zLrxy","tMrAEKW","ANb5u3K","D3HqsNe","zxjFCw9Zx2e","DMfUCLy","mtiZnZe1mtDxBLLpt2G","zw50tgLZDgu","wfjdBKS","v0H0qvm","v0LADu8","DgLUzYbZzxi","vwLrthy","t1LVsMe","EMzrqKy","qwf2sfe","q0Xpu0LorW","DKLHwK4","svzOrgu","zgvSzxrL","ywrKrxzLBNq","wNPRuMG","txfvzM4","CgvYC2LZDgu","x21LC3nHz2u","qMnrAMy","r3HRswq","BwfW","rxHLz3O","Dgv4DfbHEwW","BvfYvvK","BNruCMLLC0m","DxfWEhu","BvbutMC","r1Huswi","CePMCKS","ELz2rw0","rK9tvNi","uxDkDwG","BIWGAg9ZDg4","y3vYDMfSDwu","DNbIBfC","CKvJwhO","wwHMwMW","Bg9Nwe4","BKXPBMu","vw5ODLu","qvrTD1K","CMvHzhLtDge","veLyq3i","BfbnAva","BM5HAMO","sunxz2G","Dw5KzwzPBMu","twvyCKG","tNr2seG","wxHiy2q","wNjID00","Chv0","ugvbBNy","BMDLza","rhzbCey","C3PvBxm","Aw5L","y3jLyxrLtwu","DMjxEfq","q1DHAuS","t2zYwu0","yKzLC0O","uxHYq2C","tgvZs3i","zMXVB3i","B2jQzwn0u3q","r1jcv3C","Dgv4Dc9WBge","CMv0CNLdB3u","CxzrB28","rg1Lq1a","x2LZv29YA2u","CM9YrxzLBNq","y29SBM8","x0vysvnu","z2v0q3vYCMu","BgvY","z2vAu1a","y01fywy","vvrhqwe","igzHAwWSig0","wu9Iywq","CYbHBhjLywq","AwfmELK","zNjHBwvuExa","DhnjA2i","zMjKtey","Cgfguu0","shvjv1q","y0PrwK0","B0rezhm","s2f4z1m","vwzhsvq","yLbeqve","C2v0q3vYC28","D2LSBfjLy28","BezUAvu","u0vKtu8","x2TLEvbHDgG","x2LUAxq","tujftuC","wM9gEw8","rg9Zs1e","BwvZC2fNzq","yw5Hz2vY","vvnpANa","D2vI","B2XhuMm","AvbSEwK","CKH1Bha","vhHAB2G","AevYCM9Yrxy","q3PTqui","BgP4zxi","CxPhEvq","EwDny2m","D0TxzeO","Bg93","uxjXCK8","zxj2AwnL","Dg9iyxnO","z3PRyMm","C2vYDMLJzq","yKTYEvm","D2XNthC","zM9YrwfJAa","Bwf4twvZC2e","BMCGB3iGyw4","y29Kzq","Aw47y2HHCNm","q3zit2G","yNL0zxm","tg9NsurozxC","ENrvtwK","Eu93wvm","C2Djs1m","CMTHA2m","zw1LBNq","BxnN","AKTqCMu","AxnbCNjHEq","q2HAz2y","BezSDxnO","v01lBeK","DhLgzLq","tLDVD1O","yxnJCMLWDa","zgrjrcWGzgu","uKflvw4","tgL0uhC","CMfTzq","BgHfDMS","u013sxa","zgLZywjSzue","x2LZqNjVD3m","wurYsuG","wMPhzfi","tMTjte8","B25ozxr3B3i","B0v6Awu","sNfQB0u","mNW0Fdb8mxW","C2v0sxrLBq","q29Kzq","tKX5sgG","AwXLtMfTzq","CgLUz0XVC3m","zMLUza","B2DjEwG","zuLAD20","tgfZz2q","yMfKCum","twvZC2fNzuu","DKzts3e","y09Wzw4","su9Tu3m","qMztuve","CMvKDwnL","y0fKBwe","zxDuEg4","Ewzzy2e","twv3uuC","qNDoAMK","yNffDNa","r1rtCKq","CMvZDwX0","sLLRzwC","tw9KDwXL","ugP2wM8","z2vtEw5J","r1f5rNe","A0TbwLq","EwrmAe0","DujbBgi","senMuwy","DxPVv3O","uerJtK4","zwn0","ChjVDg90Exa","tMvovvi","vKzYu2e","rufksgy","z2vjBMzVu3K","ignVzgu6ia","CgLUz1rPBwu","tKj3rhC","AxnFywnR","sujPDgK","Bg9IywXty28","yND5thy","B2zMC2v0","CMfTugfYyw0","nZmYu0zbthLV","zMLSzw5HBwu","CNzHBfzHBhu","BfDsD2O","B05sDKm","suXHrwW","vgvXrwy","BMDuAw1LCG","A2HfEgW","x2LUAxrhBg8","tu1Uuwy","uvncy1i","Duztuwy","vg1xB00","CgjICdi","tfb4uNq","x2rPC2nVBM4","C0jRz2K","B2fK","DhDVCMTdAge","ote5mdC5vhzxqwHw","qLvkrgu","suzsExe","yxbWzw5Kq2G","rw1qzwC","ELj5BvC","qw5KvLO","ALfkCwy","BgLUzq","EhDPz0W","id4G","A2H0uLG","y1Hwz3y","x2vUzhbVAw4","DevcrgW","svvxC3i","Cg9PBNrdB24","BLjgyMC","txHts2C","ign1CNnVCIa","ruTrBLu","CgfNzxnOB3C","vgfN","AgLNAa","B3bLBKrc","AuvhC1O","u0rswwC","BujMqNu","BxLKC2e","BfrXqNG","A1n0yxr1C0m","y29UC3rYDwm","CIb0DhDjra","rxzLBNq","ihn1y2nLC3m","AeTUrNu","Dw1Au0K","ywnRx2LK","ywnRpwzYB24","AKPptu8","z0vwz3e","AMjPrMK","sxPLz2u","zMvY","tg9JAW","AwPSDhu","B3bLBIa","z3betK8","vw5PBxbSzw0","r29ODKG","q291BNq","x2nVBM5Ly3q","B25TzxnZywC","DMLjr28","BfjQsMe","BMvJDa","rxDOwgm","x3vYBa","rgvJwwO","DMvYC2LVBMm","y29UBMvJDgK","Cgf5Bg9Hzfq","uMfutwe","reLqzgW","C0rzvMW","B0njrfK","vKLbC3e","sLnptLa","rNHfuLG","y29UBMvJDca","Egrsvg8","qNn3ug4","wMTrq2G","qwjVCNrfCNi","D0LhANO","Bg9N","t2P5AxG","svzsD1O","C3vIyxjYyxK","uffHqLi","y1Hut3e","uw5UuNi","pxv0zI04","zhb0BhK","yxrLq291BNq","uejQEKy","sgnUAw0","BvDOrxq","zKvArLi","Cfjwzxa","CMvHzfvjBNq","A1nZweO","zM9Yy2u","zKn5EM0","DhLWzq","x3nVy2TLDa","x3bHDgHlzxK","sNLmrKy","Dg9Y","nJqYndK1mfnKu3bHuG","x3bYB3rVy28","Dhrdz3C","BM93","D0TOqxO","EvjLy29UBMu","B25VCgvU","B3bLCNr5","yM5XBfu","BgjRCvq","DMXIB2e","wgX0uMe","zxjFDhrS","tKHVEgm","B3jRzxjhBg8","qLz0B0W","zNjVBujPDhm","suvtx0vsuK8","swjPA1i","uMD1zeq","zw5KCg9PBNq","zwrPyxrLBhK","mtKYmdGYrwv1wKPm","BMr2uwC","vMnxCxi","CMvJzxzPzwq","x2LZtwLUAvq","t0riBeG","DwjkyxK","x2HHBMrSzu8","C3bSAxq","t2TZwwq","AwXLx25HBwu","vgLTzw91Da","ihjLy29UBMu","C090thi","se13Aeq","vw1oELG","z2D5y3O","zM5sA1O","DerlAMG","rKrTAu8","uMXAwgC","shn4Bgu","v1PcDfi","EuvwvKO","yLrwrvi","y29UBMvJDfm","zxjYtM8","y2HnyxHuCMK","t1nPDvu","z2vY","twP3u2e","x2n1CNnVCK0","zxHWB3j0CW","C2Dmy0W","qur3ugm","DurvDvq","DhnpChK","yMLUza","yuXVAwe","ve5VtKW","x2LUDgvYDMe","yw5Nzq","z3vssxq","D2vxr2e","DgLgAue","wMD5q1m","C2vYDMLJzs0","DxfuB1y","wuTvzhK","y21tCfq","x19LC01Vzhu","uuPZDKK","x0rctMfTzq","mxWZFdv8nhW","BgLTAxq","ExDctLu","D24GCMvHC28","vhDVDxi","z2fwyMq","svjcCe8","x29WDgLVBNm","ExvHDNu","t2fyA2q","yMzQrvu","r2rKDg0","yLnAqLy","vg1Xque","AgfUz2u","CM92AwrLihC","CMr4BeC","r2LsALe","qNHAqvi","Bwf4uMv0CMK","rLPRrxy","BMrLEa","qMvsze0","CMfNzvn5BMm","wef2tvq","zeDPru0","t1jmrNe","C2v0u3rVCMe","y3vYC29Yx2y","EfLLrgO","BNrkvfG","yuHIvxO","ywrKt25L","D1zLDeC","x21PBMLoyxy","CMfUzg9T","ChjVDg9JB2W","q09otKvdveK","svPqyK0","B3bLBG","u0PIte0","y2XtBM0","uMD3rNy","sg5zzKK","y3jLyxrLq2W","CxrkAuu","AgTTtgK","qNDcswK","yxbWBgLJyxq","rgvKAwnHDgu","twf0q1y","B25Uzwn0Aw4","DwnRz20","y3LAqwy","u1jbuKW","ENHjwuS","z0v1zxm","B25nzxnZywC","Cg9PBNrbBMq","ywvSzum","B3jpBMXPBMu","x2rPC3bHDgm","z1rPBwvVDxq","BMv3vMvYC2K","vMX5rfm","thvMD04","Dw5ZAwDUzwq","DuDhDvO","reiGzMfPBgu","uNbfq0m","zNHcvKO","DevtD1O","y3vYCMvUDeu","DhjPzxmGCMu","sNbHwfC","icSG","AMHZCfG","Evviwva","AuLvsve","BgPcC2W","mxWW","yxPHAu8","zxjFCw9Z","DhL1t2K","DhHXv2q","u1nAwKm","wMfNEeu","DxbNCMfKzw4","yvbRqxm","zNDxr3y","y2HLy2Tszwe","y3jLyxrLuMu","m3WYFdb8mxW","y29UDgLUDwu","uwTku20","CMvJzwL2zwq","yw51Ce1LC3m","ywDLsgLKzq","ywrtu1G","DgHLBG","ruvPtgK","qw5eAMu","zw5HyMXLuw8","B2zM","wevHqwm","vNfnrvC","x2nSzwfYugK","C3rYAw5NAwy","z252qwG","lcbOB3n0BMe","ChbL","DePPzee","z2v0q3vYC28","uMncCNq","u2fVvvO","zw5HyMXLvhi","ruDrq1a","zM13wei","y2fSBa","y2HLy2TdDxi","EwvIqwm","z0vSCwG","z2Dpv04","yw5ZzM9YBvq","A29wtLO","C3rHCNq","x29Uq2XVC2u","D21RueW","ExbL","vLDPEM0","DxjS","z2DoqLm","DKjVvuG","BwvKAwf0zwW","Dxrjza","ywXPzcb1CMW","s0jZvwS","CMvWBgfJzui","EuTRsgW","EhzgEuO","CwrnAfO","x3jLywr5q2W","rMfyu0S","x2fKzfDZtgK","AxLdCuq","sK95tuq","vwPIsxK","EMP6zMC","zxf1ywXZ","D2LYAu8","surmDeq","uhb6CKW","CLL4rgO","AvbTA2O","zgvJB2rLzey","tvPVEhG","rhbfA2W","DeHxvhC","z05Ryvm","rhvQEKi","AgvHzgvY","Eu1MEKS","mdaWma","BMTdrfe","Eg11ruu","qwLOBgy","zvvYBa","wLrRvfi","vLbjELq","Ce52DKq","ywXSB2nvBNm","B25tDgfYDfi","t1bftL9fuLi","vuH0vuq","qNDkzfu","Aw5Lza","q05UqLi","rNnsAgy","zKrbBeW","DxnLCKLW","DMTrCMi","Cgu6ia","y291BNq","tgLZDgvUzxi","zun3qxu","r3rnCfu","AgfZ","zff1A3G","sxvAuhu","ihzHBgLKihm","ugXKr1m","uhzYwfC","mJC0nJfzEhfyEKu","v2ryy1O","B25pCgvU","Ec1TC2CTy3u","A2v5CW","uwDmChC","uxvLDwu","vfDMEu0","BgLfuuy","wunAveK","EhD4C0G","quTsz08","igzPzwXKoIa","zMLSDgvY","DvbZwfi","EfnTuM0","z2vLC2q","B25szwnLAxy","CNnVCL92ywW","yNP4rgq","yKjTswS","BKDOwuK","zxjFAxnFywm","BKHwA1a","wMPyv0G","te9QBwK","twrIquu","C0PHsMG","Dg9oDw1Izxi","su5tvefova","sw9Wu2W","s3jgzKq","ALnAr0S","vwfVEK0","lcbxzwjtB2m","Awrvrhy","ihzHBgLKigq","vgvqDMi","BMnVzgLUzW","CNnKA1y","AhzzBNe","y2XVC2veqG","Egr4rfe","Dg9cExrLCW","wMf1z1m","uhvNyw8","B3jL","z2v0u3rVCMe","DKDYCu4","mtjszNfTA3m","EMz1zei","C3rVCcbPBw0","DMLJzuLeig8","zgf0yq","BwvZC2fNzv8","C2HPzNq","D2fnCvy","ywDL","y0z3tKq","ihbYB3rVy28","tLLMq2m","BMCGDxjSoIa","wxv6BMK","BxnuBe0","CgHLzvy","Aunks1i","ugz6wu0","BeHHBMrSzxi","zxLHD2W","ALHsueG","tuvtu0fhrv8","D3m6lY8","DgLLCKPtt04","B25tDg9Wsw0","vLLLr1m","Cw9lvhu","z2vrDwv1zuW","z2v0qwXS","Aw5JBhvKzxm","DcbVzIbYyw4","y1n2y2u","B3nLrxzLBNq","u1jws00","q2TKqwi","qLLHsha","DMrxyMm","x29UtwvZC2e","zgvMAw5Luhi","uLfWuK4","ywzL","vwvOugy","qKr4Bhm","EwfYAfG","B3LIBfy","C0Trs24","Bg9Nsurhzw4","u2vXsuq","y29UDgv4Da","ywnRx2nVzgu","DgvZDa","tK1Mz1u","t2rvAfO","rvb1Cey","BgDnqKC","CgLUz19VBMm","twjryvq","DMvUDa","ufniBKG","uLPPEwm","wfL6zwW","BgLUzw5V","Ae5MrKW","D0XKBMq","DuvLuu4","qLjYA2y","ufzRy1O","EwHtzwK","C1nAweS","wxvhuhK","sMvNCeC","uhrkAK0","zKjkrNq","Cgf5Bg9Hzeu","rKjbtMm","thHfD0G","BuP4y2K","v0rxEfq","y2XLyxi","x3bPBMDmB3m","rNrOwMu","CgfNzwHPzgu","vwLyAxO","y1zQEvm","zNjVBunOyxi","A0XdAfK","zMTOu04","vwfLq2O","rvvksLq","q3jnwNi","txz3z1a","CxvnzKm","suD3zfO","Ehf6swy","Eufcywi","C2nYAxb0","yNL0zuXLBMC","CM93thC","C3bSAwnL","x2DLBMvYyxq","wLzvA00","Bu1rDhC","x2nYzwf0zvm","Bwf4tg9ZC0m","AhnTwwy","qNjPzgDL","zxjYtxnN","Ae1LC3nHz2u","ywrKq291BNq","quDive8","D3Lwtum","y05krxm","ELvlwMy","CejNAgO","Cgf5Bg9Hza","A2jpAey","vfjtvM8","D2rUrK4","twPXqKi","zwnVBM5Ly3q","AMjKwLG","B3v0sw50zxi","ExPkqLO","uvHlzvm","zLPSC0u","Cg1oyMi","EMLKuhG","BMrWB2LUDfq","x2HHBMrSzva","ywWGy3vYC28","BwLUAvbYB2C","BxnNsuq","suzVtNu","yMzvENC","zxjFBxnNAwq","t0rTtgW","sK54C00","BML0AwfSAxO","yvDwDhi","BwzNy1i","A3zbwgG","s0nctLC","x1fVu01HBMe","z29PBMCGyxC","DxbKyxrLq3u","y2vZC0HHBMq","yMLUyxj5","BMflyNC","x3DZ","wMDHufa","DgfIyxnL","y3vYC29YlNm","v0TxsKu","Efrurw52","z2v0sxrLBq","BM5Ly3q","BwvY","vMfhr2y","tw5mEMO","CLvlAwK","BNvTyMvY","CvPLyui","DfvQA0m","A3zYAvO","CMnYzuO","ueXrB1q","sLHVD3a","rNPSz3u","rhvdwfK"];return sa=function(){return t},sa()}function DS(){let t=F;return Jx||(Jx=[IDBCursor.prototype[t(393)],IDBCursor[t(650)+"e"].continue,IDBCursor[t(650)+"e"][t(951)+"PrimaryKey"]])}function OS(t){let e=F,n={tdtsb:e(433),EmPeg:e(403),KAGHf:function(o,c){return o(c)},YDrIH:function(o){return o()},qZeaB:function(o,c){return o(c)},txqWd:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let l=e,u={MeXrH:function(w,v){return n[z(1260)](w,v)},tyFfT:function(w){return w()}},h=()=>{let w=z;t["removeEv"+w(452)+"ner"](n[w(378)],x),t["removeEventListe"+w(197)](n[w(688)],m)},x=()=>{let w=z;u[w(499)](o,u[w(499)](Gt,t[w(637)])),u[w(596)](h)},m=()=>{let w=z;n.KAGHf(c,t.error),n[w(607)](h)};t[l(465)+l(1041)](n[l(378)],x),t[l(465)+l(1041)](n.EmPeg,m)});return i[e(957)](o=>{let c=e;n[c(942)](o,IDBCursor)&&Jd[c(1706)](o,t)})[e(1474)](()=>{}),aa[e(1706)](i,t),i}function LS(t){let e=F,n={hsmYf:function(o){return o()},MIXuN:function(o,c){return o(c)},rAJDG:e(757)+"or",bMmzm:e(403),roZFR:"abort",eRewn:e(269)};if(oa[e(1044)](t))return;let i=new Promise((o,c)=>{let l=e,u={CZNmd:l(269),nbwod:n.bMmzm,XThSr:n.roZFR},h=()=>{let w=l;t[w(445)+w(452)+w(197)](u[w(1700)],x),t[w(445)+w(452)+w(197)](u[w(382)],m),t[w(445)+w(452)+w(197)](u.XThSr,m)},x=()=>{let w=l;o(),n[w(1203)](h)},m=()=>{let w=l;n[w(204)](c,t[w(403)]||new DOMException(n.rAJDG,n[w(1746)])),n[w(1203)](h)};t[l(465)+l(1041)](n[l(377)],x),t[l(465)+l(1041)](n[l(1434)],m),t["addEvent"+l(1041)](n[l(209)],m)});oa.set(t,i)}function NS(t){ca={FgYgr:function(n,i){return n(i)}}.FgYgr(t,ca)}function MS(t){let e=F,n={zxIYK:function(i,o){return i>o},lfBKj:e(363)+"too large",MvwgP:function(i,o){return i&o},fBJFt:function(i,o){return i+o},OksYd:e(1092),fEZFR:function(i,o){return i(o)},nMHEl:function(i,o){return i(o)},vblyK:function(i,o){return i(o)},FaXSK:function(i,o){return i===o},DujzB:function(i,o){return i in o},KyCRZ:e(517)+e(1322)};return n[e(1e3)](t,IDBDatabase.prototype[e(442)+"ion"])&&!n[e(1017)](n[e(1722)],IDBTransaction[e(650)+"e"])?function(i,...o){let c=e,l={VIAsq:function(u,h){return n[z(913)](u,h)},qUBVF:n[c(1757)],IZSHf:function(u,h){return n[c(1189)](u,h)},eisYc:function(u,h,x,m){return u(h,x,m)},kvAXh:function(u,h){return n[c(1171)](u,h)}};if(n[c(814)]==="oMfxm"){if(l[c(750)](_0x4e137b,_0xbf2f00))throw new _0x4382bb(l.qUBVF);let u=3;for(;u>=0;){let h=l[c(395)](255,_0x4b3476);l[c(1269)](_0x1a85bf,h,_0x3eda55,_0x26d3ee+u),_0x4d66f7>>>=8,u--}return l[c(1239)](_0xbcfaae,4)}else{let u=t.call(n[c(772)](cs,this),i,...o);return Vd[c(1706)](u,i[c(316)]?i[c(316)]():[i]),n.fEZFR(Gt,u)}}:DS()[e(1128)](t)?function(...i){let o=e;return t.apply(cs(this),i),n[o(772)](Gt,Jd[o(274)](this))}:function(...i){let o=e;return n[o(1575)](Gt,t[o(1381)](n[o(217)](cs,this),i))}}function BS(t){let e=F,n={DZSXO:function(i,o){return i===o},CiVKX:function(i,o){return i(o)},PjvZo:function(i,o,c){return i(o,c)},lmeKn:function(i){return i()}};return n.DZSXO(typeof t,e(1655))?MS(t):(t instanceof IDBTransaction&&n[e(417)](LS,t),n[e(640)](ep,t,n[e(1556)](CS))?new Proxy(t,ca):t)}function Gt(t){let e=F,n={LScsH:function(o,c){return o(c)},cVjyS:function(o,c){return o(c)}};if(t instanceof IDBRequest)return n[e(1580)](OS,t);if(ra[e(1044)](t))return ra.get(t);let i=n[e(1182)](BS,t);return i!==t&&(ra[e(1706)](t,i),aa[e(1706)](i,t)),i}var ep,Vx,Jx,Jd,oa,Vd,ra,aa,ca,cs,Zx=Qx({"node_modules/idb/build/wrap-idb-value.js"(){let t=F,e={tzZrr:function(n,i){return n instanceof i},XqCNx:function(n,i){return n===i},zfQBF:"done",iEGsZ:function(n,i){return n===i},PldGS:t(517)+t(1322),oiwkq:function(n,i){return n!==i},ZDDwW:"ILaEl",EYqbD:"store",BYDtw:function(n,i){return n(i)},KjTiu:t(1592),GBBQX:function(n,i){return n instanceof i},itPXv:function(n,i){return n===i},sBkgi:function(n,i){return n===i}};ep=(n,i)=>i[t(1460)](o=>n instanceof o),Jd=new WeakMap,oa=new WeakMap,Vd=new WeakMap,ra=new WeakMap,aa=new WeakMap,ca={get(n,i,o){let c=t;if(e.tzZrr(n,IDBTransaction)){if(e.XqCNx(i,e[c(459)]))return oa[c(274)](n);if(e[c(709)](i,e[c(1048)]))if(e[c(304)](e[c(1332)],c(669)))_0x1a5373&&this[c(836)+c(556)][c(1243)+"rsorFile"+c(337)](_0x553fdc);else return n[c(517)+c(1322)]||Vd[c(274)](n);if(i===e.EYqbD)return o[c(517)+c(1322)][1]?void 0:o[c(517)+c(1096)](o[c(517)+"oreNames"][0])}return e.BYDtw(Gt,n[i])},set(n,i,o){let c=t;if(c(1465)===e[c(296)])this._ws&&this[c(1247)].send(_0x5b1e40),this[c(1658)]("send_ack",_0x32c750);else return n[i]=o,!0},has(n,i){let o=t;return e[o(191)](n,IDBTransaction)&&(e[o(229)](i,o(1316))||e[o(681)](i,"store"))?!0:i in n}},cs=n=>aa.get(n)}}),tp={};PS(tp,{deleteDB:()=>zS,openDB:()=>FS,unwrap:()=>cs,wrap:()=>Gt});function FS(t,e,{blocked:n,upgrade:i,blocking:o,terminated:c}={}){let l=F,u={RLaUS:function(w,v,_,E,I){return w(v,_,E,I)},nsfWV:function(w,v){return w(v)},imnLx:l(1601),wdnFN:l(743)+l(872),ZMovU:function(w,v){return w(v)},pJfrK:function(w,v){return w!==v},ZagxE:l(1453),aKHwf:l(1398),YCZTI:l(945)+"eeded",ssRwW:"blocked"},h=indexedDB[l(897)](t,e),x=u[l(1715)](Gt,h);if(i)if(u[l(480)](u[l(944)],u[l(1639)]))h["addEvent"+l(1041)](u[l(1059)],w=>{let v=l;u.RLaUS(i,u[v(199)](Gt,h[v(637)]),w[v(1749)+"on"],w.newVersion,u[v(199)](Gt,h["transact"+v(1499)]))});else for(var m in _0x459126)_0x23877f.o(_0xab088f,m)&&!_0x53942e.o(_0x5d9ac3,m)&&_0xba7027[l(1137)+"operty"](_0x3bd98d,m,{enumerable:!0,get:_0x353bac[m]});return n&&h["addEvent"+l(1041)](u.ssRwW,()=>n()),x.then(w=>{let v=l;c&&w[v(465)+v(1041)](u.imnLx,()=>c()),o&&w["addEvent"+v(1041)](u[v(1216)],()=>o())})[l(1474)](()=>{}),x}function z(t,e){t=t-191;let n=sa(),i=n[t];if(z.TsQErA===void 0){var o=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",w="";for(let v=0,_,E,I=0;E=h.charAt(I++);~E&&(_=v%4?_*64+E:E,v++%4)?m+=String.fromCharCode(255&_>>(-2*v&6)):0)E=x.indexOf(E);for(let v=0,_=m.length;v<_;v++)w+="%"+("00"+m.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(w)};z.vnbXWp=o,z.KHLLPc={},z.TsQErA=!0}let c=n[0],l=t+c,u=z.KHLLPc[l];return u?i=u:(i=z.vnbXWp(i),z.KHLLPc[l]=i),i}function zS(t,{blocked:e}={}){let n=F,i=indexedDB[n(218)+n(1249)](t);return e&&i["addEvent"+n(1041)](n(1751),()=>e()),Gt(i)[n(957)](()=>{})}function Yx(t,e){let n=F,i={IXRLs:"readonly",Ymybh:function(h,x){return h in x},tKonh:function(h,x){return h===x},hMOoY:n(1539),umZSI:function(h,x){return h!==x}};if(!(t instanceof IDBDatabase&&!i[n(252)](e,t)&&i[n(213)](typeof e,i[n(439)])))return;if(ia[n(274)](e))return ia.get(e);let o=e.replace(/FromIndex$/,""),c=i[n(720)](e,o),l=rp[n(1128)](o);if(!i[n(252)](o,(c?IDBIndex:IDBObjectStore)[n(650)+"e"])||!(l||np[n(1128)](o)))return;let u=async function(h,...x){let m=n,w=this[m(442)+m(1499)](h,l?"readwrite":i[m(1643)]),v=w.store;return c&&(v=v[m(1526)](x[m(1105)]())),(await Promise[m(1585)]([v[o](...x),l&&w.done]))[0]};return ia[n(1706)](e,u),u}var np,rp,ia,US=Qx({"node_modules/idb/build/index.js"(){let t=F,e={NYfCc:t(858)+t(1449),RneyO:function(o,c){return o(c)},beQLK:function(o){return o()},FzRiO:t(503),UCHlz:t(1177),paFQM:t(1040)},n=e[t(1110)][t(813)]("|"),i=0;for(;;){switch(n[i++]){case"0":e.RneyO(NS,o=>({...o,get:(c,l,u)=>Yx(c,l)||o.get(c,l,u),has:(c,l)=>!!Yx(c,l)||o.has(c,l)}));continue;case"1":Zx();continue;case"2":ia=new Map;continue;case"3":e[t(1727)](Zx);continue;case"4":rp=[e[t(1598)],t(225),t(464),e.UCHlz];continue;case"5":np=[t(274),"getKey",t(1127),t(430)+"ys",e[t(539)]];continue}break}}}),GS={idb:function(t){let e=F;t[e(837)]=Promise[e(1613)]().then(()=>(US(),tp)).then(function(n){return n})}},Xx={};function Ut(t){let e=F,n={LxEwH:function(u,h){return u!==h}},i=(e(208)+"1").split("|"),o=0;for(;;){switch(i[o++]){case"0":if(n[e(1174)](void 0,c))return c[e(837)];continue;case"1":return l[e(837)];case"2":var c=Xx[t];continue;case"3":GS[t](l,l[e(837)],Ut);continue;case"4":var l=Xx[t]={exports:{}};continue}break}}Ut.d=(t,e)=>{let n=z;for(var i in e)Ut.o(e,i)&&!Ut.o(t,i)&&Object[n(1137)+n(790)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=F;Ut.o=(e,n)=>Object[t(650)+"e"][t(1571)+"operty"][t(976)](e,n)})(),(()=>{let t=F,e={qtJiE:t(498)+"d",Jklli:t(639),lgMBG:t(855)+"le"};Ut.r=n=>{let i=t;e[i(903)]!=typeof Symbol&&Symbol["toString"+i(706)]&&Object[i(1137)+i(790)](n,Symbol[i(1726)+i(706)],{value:e[i(1615)]}),Object["definePr"+i(790)](n,e[i(1153)],{value:!0})}})();var De={};(()=>{let t=F,e={NYLkE:function(a,r){return a===r},XHaZl:"OfGFK",sgIKS:function(a,r){return a(r)},vanrV:function(a,r){return a+r},DxLBW:function(a,r){return a+r},kvriZ:function(a,r){return a*r},EXYJw:function(a,r){return a(r)},OaXkd:function(a,r,s){return a(r,s)},yarhX:function(a,r){return a+r},aPkAs:function(a,r,s){return a(r,s)},mMQtw:function(a,r){return a(r)},uUrME:function(a,r){return a+r},gzkbc:function(a,r){return a(r)},Ekmic:t(1020),UkWnf:"ffff",UfMgk:function(a,r){return a<r},bzxDd:function(a,r){return a<<r},qoKTu:function(a,r){return a===r},hvYnq:t(434),JeBCR:function(a,r){return a(r)},BDxls:"00000000"+t(305)+t(305)+t(305),wKWdJ:function(a,r){return a&r},OweVT:function(a,r){return a>>>r},DIPdl:function(a,r){return a&r},NeNUR:function(a,r){return a>>>r},waNDr:function(a,r){return a>>>r},rzYlu:function(a,r){return a===r},OYoJa:function(a,r){return a<r},wyYvG:function(a,r,s){return a(r,s)},GAKcX:function(a,r){return a<<r},FBANc:function(a,r){return a>r},yMfzK:function(a,r){return a<r},oSgPH:function(a,r){return a===r},lRAAc:t(1644),ivops:function(a,r){return a!==r},VYeGS:function(a,r){return a-r},Namgt:function(a,r){return a-r},ssPNP:function(a,r){return a<r},ZTkTR:function(a,r){return a<r},fAETC:function(a,r){return a<r},WDnVE:function(a,r){return a!==r},iqUqX:t(631),ZRcTT:t(1130),BvIRQ:t(1497),WrNnN:function(a,r,s){return a(r,s)},BGquI:function(a,r){return a!==r},iPlyi:function(a,r,s){return a(r,s)},DSNwi:function(a,r){return a(r)},aOXqA:function(a,r){return a>>>r},jAAMq:function(a,r){return a&r},XTCYP:"Missing "+t(1394)+" field: "+t(273),fkhSN:function(a){return a()},HPpGs:function(a,r,s){return a(r,s)},SavKq:t(403),RlWbp:function(a,r,s){return a(r,s)},FeOYr:function(a,r,s){return a(r,s)},lFniU:function(a,r){return a!==r},BswPn:function(a,r){return a(r)},FdaFb:t(1022),rdDXa:t(1466),BcQjf:function(a,r,s){return a(r,s)},nWvfI:function(a,r,s){return a(r,s)},EUJJT:function(a,r){return a!==r},TeqEf:"Ebikw",uOCbR:function(a,r,s){return a(r,s)},jhspX:function(a,r){return a!==r},IZPbM:function(a,r,s){return a(r,s)},aEYUs:function(a,r,s){return a(r,s)},AIjbi:function(a,r){return a!==r},TPgak:function(a,r,s){return a(r,s)},ZPBId:function(a,r,s){return a(r,s)},hkmLi:function(a,r,s){return a(r,s)},mZpCO:function(a,r,s){return a(r,s)},iSwJg:function(a,r){return a(r)},GiRjQ:function(a,r){return a(r)},lqcfo:function(a,r){return a>>>r},ATmwY:function(a,r,s){return a(r,s)},GuOnC:function(a,r,s){return a(r,s)},SVEtl:function(a,r){return a(r)},OwfNi:function(a,r,s){return a(r,s)},zUKZf:function(a,r){return a(r)},IyCua:function(a,r){return a(r)},wntBa:function(a,r,s){return a(r,s)},gOsyX:function(a,r){return a(r)},iCiyj:function(a,r){return a(r)},yxHpr:function(a,r){return a&r},kHmdz:t(1406)+"required"+t(1062)+t(1146),uBAlb:t(1406)+t(1394)+t(1062)+t(1545),Drcoa:function(a,r){return a===r},CzmAB:t(1406)+t(1394)+" field: "+t(574),gKuLk:t(1406)+t(1394)+t(1062)+t(278),xeRJW:function(a,r){return a(r)},FDmiO:function(a,r,s){return a(r,s)},geZSP:function(a,r){return a>=r},QhOrQ:function(a,r){return a!==r},hSZUL:t(543),Gdkkn:"zCNix",pFgSa:t(1692),yEVVJ:function(a,r){return a+r},SJNve:t(1337)+t(1640),vFSKq:function(a,r){return a===r},hMQRu:t(1002),PpzrL:function(a,r){return a*r},LkhVe:function(a,r){return a>r},IOmSs:t(1379)+"t limit",Gddtm:function(a,r,s){return a(r,s)},ODmLl:function(a,r,s){return a(r,s)},jmJNL:function(a,r){return a instanceof r},Hsxle:function(a,r){return a|r},yYLFm:function(a,r){return a<r},vGrqN:function(a,r){return a+r},pLsfz:function(a,r){return a&r},eluXD:function(a,r){return a&r},frOVR:function(a,r){return a>=r},BMcZD:function(a,r){return a+r},xvFyJ:function(a,r){return a+r},bFesJ:t(628),OSiuU:t(674),ZtyuD:function(a,r){return a|r},lbkqT:function(a,r){return a<<r},rsdkV:function(a,r){return a==r},cyZAf:function(a,r){return a+r},KTfXX:function(a,r){return a!==r},yxiim:t(487),JegpG:function(a,r){return a+r},ViQov:function(a,r){return a+r},tiFiA:function(a,r){return a|r},FOSVr:function(a,r){return a|r},RgwFv:function(a,r){return a<<r},atCWg:function(a,r){return a<=r},HxGtE:t(838),PvrXW:t(262),afhkO:function(a,r){return a+r},Lasgd:function(a,r){return a+r},Yuzni:function(a,r){return a+r},CpISS:function(a,r){return a+r},hDvYB:function(a,r){return a|r},aAoZt:function(a,r){return a<<r},SJwXn:function(a,r){return a|r},LitPw:function(a,r){return a<<r},ERuvg:function(a,r){return a<r},eEcwP:function(a,r){return a>r},iIUIQ:function(a,r){return a+r},SaoUZ:t(1404)+t(1348)+t(242),yABab:t(1018),OIaMG:function(a,r,s,d){return a(r,s,d)},elsjM:t(851)+t(216),VjSof:t(574),XAvMT:"curvalue",yOwYS:t(216),RvUtK:function(a,r){return a(r)},aWVtr:function(a,r){return a|r},jhRpv:function(a,r){return a<<r},hNfFL:function(a,r){return a<r},MnLzj:t(1192),YUKcQ:function(a,r){return a-r},bAdln:function(a,r){return a<r},CWaiK:function(a,r){return a<r},rhjJJ:function(a,r,s){return a(r,s)},vfaOQ:function(a,r){return a+r},ZyeiJ:function(a,r){return a<r},wVetG:function(a,r){return a!==r},kAWfF:t(454),PWCIN:function(a,r){return a<r},oIJIO:function(a,r){return a&r},ELmqY:function(a,r){return a===r},qWTlV:t(860),adSSX:function(a,r){return a>>r},pxFtg:function(a,r){return a|r},tqMVP:function(a,r){return a&r},LesKr:t(206),TIXCr:function(a,r,s){return a(r,s)},yPcuf:function(a,r){return a<r},RlZXg:function(a,r){return a&r},tEBDl:function(a,r){return a>=r},UQgWx:function(a,r,s){return a(r,s)},tfkcB:function(a,r){return a(r)},GQyFq:function(a,r){return a!==r},zRymW:t(1388),EiTJe:t(290),cKlQv:function(a,r){return a(r)},NMHbs:function(a,r){return a(r)},gLDCi:function(a,r){return a&r},xwigL:function(a,r){return a(r)},RkDRo:function(a,r){return a<<r},zALgm:function(a,r){return a&r},CAsYo:function(a,r){return a&r},UiXiz:function(a,r){return a<<r},bTVER:function(a,r){return a|r},ntJTX:function(a,r){return a>>>r},xLkST:function(a,r){return a<<r},JyLFF:function(a,r){return a>>>r},oUdRX:function(a,r){return a<r},nMuna:function(a,r){return a+r},yUHYP:function(a,r){return a&r},iPmkj:function(a,r){return a>>>r},VjSln:function(a,r){return a+r},fNqwi:function(a,r){return a!==r},SDRYg:function(a,r){return a&r},PtJjM:function(a,r){return a+r},FFEwK:function(a,r){return a|r},zidPx:function(a,r){return a+r},jCJTJ:function(a,r){return a!==r},xmAZx:function(a,r){return a|r},OYNGU:function(a,r){return a&r},OawTE:function(a,r){return a>>>r},GRBWw:function(a,r){return a+r},OVrBo:function(a,r){return a|r},NfehF:function(a,r){return a&r},EhKVu:function(a,r){return a!==r},QrqrO:function(a,r){return a&r},iKTnK:function(a,r){return a|r},bKLVC:function(a,r){return a+r},EYpXx:function(a,r){return a>>>r},CCxQW:function(a,r){return a|r},sIaPM:function(a,r){return a&r},zjzfg:t(886)+t(815),cXVgv:t(1631),gJsGS:function(a,r){return a|r},gEVgq:function(a,r){return a|r},Mujgi:"3|2|1|4|0",bPYbn:function(a,r){return a<r},rdxlG:function(a,r){return a+r},bwyLv:function(a,r,s,d){return a(r,s,d)},oUtHM:function(a,r){return a===r},NHoxc:t(376),CsEnx:function(a,r){return a===r},BUJDe:t(603),jQJqf:t(415),fEYUR:function(a,r){return a|r},RZiyc:function(a,r){return a<<r},lRjJa:function(a,r){return a<<r},cvGwe:function(a,r){return a|r},oWAXz:function(a,r){return a<<r},aHbUz:function(a,r){return a<<r},DuCXY:function(a,r){return a|r},wTLmu:function(a,r){return a|r},ogIyh:function(a,r){return a<<r},PWGTK:function(a,r){return a>>>r},Orivc:function(a,r){return a|r},Fzlgu:function(a,r){return a<<r},AJqjZ:function(a,r){return a<<r},VPIzT:function(a,r){return a!==r},nCCch:"nkJyp",SoZAf:function(a,r){return a&r},sofaC:function(a,r){return a&r},HMwhD:function(a,r){return a>=r},UTkdl:function(a,r){return a+r},gtiUJ:function(a,r){return a%r},RKTWr:function(a,r){return a/r},PSHnH:t(1317)+"t",KovLe:t(1101)+t(804)+t(817)+"ct",gaVbd:function(a,r){return a!==r},vdWbc:t(1760),vFQCh:"eoFIb",qnzEp:function(a,r){return a>>>r},tUjkC:function(a,r){return a+r},SgYeM:function(a,r){return a*r},OJFXf:function(a,r){return a>>>r},RaTMa:function(a,r){return a>>>r},sKQKn:function(a,r){return a>>>r},LyJqk:function(a,r){return a&r},RqGQh:function(a,r){return a>>>r},oNRvC:function(a,r){return a&r},IVhDe:"KXloI",LvLVr:function(a,r){return a&r},bKRkk:function(a,r){return a&r},PLQoT:function(a,r){return a>>>r},wmkPL:function(a,r){return a<<r},BwBIi:function(a,r){return a|r},RQpRN:"zfdWc",ljxer:function(a,r){return a!==r},ydoIG:function(a,r){return a>>>r},sDYVl:function(a,r){return a===r},ncOYY:function(a,r){return a===r},knsCc:function(a,r){return a+r},Zcuhq:function(a,r){return a===r},TxZoh:t(652),kSsXJ:t(1604),wyVMC:function(a,r){return a>>>r},wpIWg:function(a,r){return a&r},HMIFh:function(a,r){return a&r},apUNm:function(a,r){return a&r},DpEkl:function(a,r){return a>>>r},zVvEm:function(a,r){return a>>>r},Exegz:function(a,r){return a>>>r},ndvQg:function(a,r){return a&r},WDWxT:function(a,r){return a&r},mfgcR:t(1533)+t(1284),NBwDw:t(1030)+"OR",KDudE:t(895)+t(1561),PUGQY:t(1671)+t(1606),rkakc:t(1120)+t(400),fCyzm:t(1352)+t(800)+"R",pTgDl:function(a,r,s){return a(r,s)},SLttv:function(a,r){return a!==r},fwWGv:function(a,r){return a(r)},liEQF:"QgLpw",QuRmj:"Module",xRkcU:t(855)+"le",CNnBR:t(192),UZuho:"LdKdC",EGRUi:t(630),vIaZN:t(731),joNlz:function(a,r){return a===r},tDKjh:function(a,r){return a>r},cFeZH:function(a,r){return a+r},bJMoC:function(a,r){return a===r},WWYEH:function(a,r){return a===r},IgtKL:t(1543),WdXcZ:function(a,r){return a===r},uPsXR:t(1443),nkCDQ:t(752),UHtUD:function(a,r,s){return a(r,s)},ukrUw:function(a,r,s){return a(r,s)},JqjoE:t(1601),VLTom:function(a,r){return a+r},nnhCR:function(a,r){return a-r},VWDmx:function(a,r){return a+r},cXTOq:t(925),SxocV:"Urcew",zGXrH:function(a,r,s){return a(r,s)},OfrYM:function(a,r){return a&r},ZRZnm:function(a,r){return a>>r},IFoNu:function(a,r){return a&r},ZjXWH:t(1716),PBjzF:t(897),SvIiX:t(555),rowLw:function(a,r){return a instanceof r},DecYj:t(676),JbEap:t(1454),jydBd:function(a,r){return a+r},LOjmi:"pISiF",CnMIa:t(901),KJAXt:function(a,r){return a===r},BeRdM:t(958),JLvNi:t(1704),MbMzT:t(471),MkFWL:function(a,r,s){return a(r,s)},rwXWM:"vpQxZ",BwNji:function(a,r){return a||r},ZjXnW:function(a,r){return a!=r},UehPf:t(498)+"d",Xwtmw:function(a,r){return a||r},FGHVa:t(613)+"3",uViTA:"aLTbC",HCfQf:t(975),joBZO:t(1747)+"alled mu"+t(1679)+t(1619)+t(1605),YuRMg:function(a,r){return a(r)},UmNzX:function(a,r){return a<r},mvSgI:function(a,r){return a-r},ggycz:function(a,r){return a<r},nnajj:function(a,r){return a&r},UCGfn:function(a,r){return a|r},AVwAt:function(a,r){return a<<r},weWGa:function(a,r){return a&r},eyawl:function(a,r){return a<<r},DwaAL:function(a,r){return a&r},sRmIJ:function(a,r){return a|r},MjqBB:function(a,r){return a<<r},NMfgU:function(a,r){return a&r},twiaP:function(a,r){return a&r},ZrbGo:function(a,r){return a+r},CrMZr:function(a,r){return a&r},VWizm:function(a,r){return a<r},HnpYw:function(a,r){return a!==r},XMrhC:"PIUuQ",MchJz:function(a,r){return a|r},aLoia:function(a,r){return a>>r},IuZPu:function(a,r){return a===r},XRCnK:function(a,r){return a&r},bSZBV:function(a,r){return a===r},AKRgO:function(a,r){return a&r},idUDv:"5|4|3|2|"+t(938),lozhZ:function(a,r){return a|r},IRBpO:function(a,r){return a&r},UfGIT:function(a,r){return a&r},FIJke:function(a,r){return a|r},WMKlI:function(a,r){return a>>r},naKbw:function(a,r){return a+r},GoDXN:function(a,r){return a&r},zXSvX:function(a,r){return a&r},gnvAh:function(a,r){return a>>r},BFVPG:function(a,r){return a>>r},TmqAA:"string",rKPKI:function(a,r){return a<<r},JpaXW:function(a,r){return a(r)},WPVXR:function(a,r){return a&r},KTKta:function(a,r){return a!==r},FCnHB:t(1027),gElqh:t(906)+"ion/json",NGoUL:t(519)+t(581)+t(1286),bPDAQ:"boe",KhyYZ:t(968),EfiXo:function(a,r){return a!==r},AndVZ:t(1411),uwoqZ:t(1071),mcJpt:function(a,r){return a>=r},vpblW:"unknown "+t(1313),ttCgw:t(1194),kKAZT:"text/jav"+t(598),DaOOp:t(1354),pOuxl:function(a,r,s,d){return a(r,s,d)},xdRTo:function(a,r){return a+r},mtiJS:function(a,r){return a+r},yiAEm:function(a,r){return a<<r},EWjbd:function(a,r){return a&r},UfLhC:function(a,r){return a&r},FZkEv:function(a,r){return a===r},OXnSO:t(1701),bvjBS:t(436),RUmtD:function(a,r){return a!==r},VaGGf:"maOWv",uqpxu:t(672),kwuqn:t(756),dGiEM:t(953),xBztZ:t(327),XEaAc:t(1133),YuGPy:"FeoXV",taBgY:t(387),Ckben:function(a,r){return a||r},geesd:function(a,r){return a||r},Izege:function(a,r){return a||r},OdkIF:function(a,r){return a||r},mlOpx:function(a,r){return a||r},SJbLM:function(a,r){return a!=r},EKDwV:function(a,r,s){return a(r,s)},cMEaf:"qos",ZjGdR:t(1104)+"id",DmkFI:function(a,r,s){return a(r,s)},XLxUm:"Sayvp",MdbAE:function(a,r){return a>>r},psevs:function(a,r){return a===r},yhSei:t(241),sskRX:function(a,r){return a!==r},nTdmN:t(1739),uDUuT:function(a,r,s){return a(r,s)},kvbos:t(943),XltRa:t(1462),uUSSr:function(a,r){return a(r)},JHABu:function(a,r,s,d){return a(r,s,d)},EJNzk:t(244)+t(449)+"ck",bqEvp:"x_fronti"+t(1072)+"k",UzHAS:function(a,r,s){return a(r,s)},vIhCq:t(244)+"er_ack_m"+t(309),tsOpy:"need_ack",Ojyix:function(a,r,s,d){return a(r,s,d)},FthZe:t(658),WZBtR:function(a,r){return a&&r},Pugao:function(a,r){return a||r},HEHQS:t(1148),VfPLD:function(a){return a()},MatCV:function(a,r){return a(r)},bzPuV:function(a,r){return a instanceof r},PDcNN:"applicat"+t(1412)+t(1270)+t(766),kIzoP:t(1542)+"e",UaozM:t(1245),iJjhY:function(a,r,s,d){return a(r,s,d)},PRIxI:function(a){return a()},RzANn:function(a,r){return a>r},JCQOF:function(a,r){return a+r},UiQLv:function(a,r){return a(r)},ZiWGg:function(a,r){return a&r},wKhAz:function(a,r){return a+r},ANcWi:function(a,r){return a(r)},UYbSE:function(a,r){return a+r},zfgBn:t(933),tHWTw:t(694),PGoqB:function(a,r,s,d){return a(r,s,d)},azaiO:t(549),PfzYM:"integer too large",KrFfD:function(a,r){return a+r},vkLhR:function(a,r){return a>>>r},WKWJE:function(a,r){return a<<r},jHSfF:t(1621)+"3",wPFPR:function(a,r){return a<r},sJaJh:function(a,r){return a+r},vbWxT:function(a,r){return a+r},faNlR:function(a,r){return a+r},ODHlH:function(a,r){return a<<r},bDHNs:function(a,r){return a+r},rcreJ:function(a,r){return a<<r},OplzG:function(a,r){return a&r},tBDlS:function(a,r){return a>>>r},cphKf:function(a,r){return a+r},vlboa:function(a,r){return a>>>r},Bdymv:function(a,r){return a>>>r},lvQVT:function(a,r){return a&r},HLzlz:function(a,r){return a+r},NkILO:function(a,r){return a>>>r},rBVBS:function(a,r){return a<r},AnxKp:function(a,r){return a&r},dQukx:function(a,r){return a===r},tJidA:t(1532),GRZjU:function(a,r){return a(r)},kIHWG:function(a,r){return a||r},FRjsC:t(1366),DTEZK:t(1250)+t(571),ZoajG:function(a,r,s){return a(r,s)},qdMhZ:function(a,r){return a===r},WLRkS:t(604),aeleC:t(267)+"_EXIST",hsPjc:t(379)+t(391),RnvHH:t(1735)+t(1312),JgimF:function(a,r,s,d){return a(r,s,d)},oDDds:"CONTINUE",qvQoo:function(a){return a()},NCFtv:"setdb",MqUfn:function(a,r){return a===r},Zdyhj:t(1208),ZgaPP:t(1350)+"r",jKPre:t(1423),ubJay:function(a,r){return a>>>r},shoGQ:function(a,r){return a+r},hiqRD:function(a,r){return a&r},EPupF:function(a,r){return a+r},TQvnf:function(a,r){return a&r},JXowp:function(a,r){return a+r},bfjEU:function(a,r){return a>>>r},KCplI:function(a,r,s,d){return a(r,s,d)},XYzpz:t(580),jUwpC:function(a,r,s,d){return a(r,s,d)},kLChY:t(244)+t(1233),Omlwc:function(a,r,s){return a(r,s)},SRVKM:t(244)+t(795),badqC:"x-msg-qos",gYALD:t(1053)+t(1471)+"e",inOWu:function(a,r){return a(r)},zfudB:"x-msg-cu"+t(1068)+"ue",qtnLR:function(a){return a()},tyuOi:function(a,r){return a!==r},Gvmvg:t(576),IGwdZ:function(a,r){return a+r},PAkrd:function(a){return a()},NbTKE:t(910),yfYca:function(a){return a()},NQClG:function(a){return a()},zmArg:"wTpHI",NtvHH:function(a,r,s){return a(r,s)},fnRkZ:function(a){return a()},jXRPH:function(a,r){return a(r)},QnnRr:"XQFWY",QxrCg:t(1698),pRVep:function(a,r){return a<r},GohvH:function(a,r){return a===r},YsQTD:"WXYvA",jdJqF:function(a,r){return a===r},OdUhZ:function(a,r){return a===r},JSzgL:"ping_once_success",mQrUY:function(a,r){return a===r},HbaAr:function(a,r){return a!==r},CEeHW:t(1507),ZgyCS:t(214),whrRW:function(a,r,s){return a(r,s)},AavHQ:function(a,r,s){return a(r,s)},AVDro:"hMFkI",uqToV:function(a,r){return a!==r},TmWoM:t(478),wEroU:function(a,r,s){return a(r,s)},XYzel:function(a,r){return a(r)},oyblV:function(a,r){return a===r},YGoND:t(1382),Kfnyq:t(1737)+t(727),AnDje:t(678),fDAlL:function(a,r){return a/r},viIGo:t(1681),ORLFq:function(a,r){return a==r},TddeF:t(1761)+"rovide v"+t(993),olGRc:function(a,r){return a!==r},rwuue:t(255),GXTIb:t(280),HsIJf:function(a,r,s){return a(r,s)},QJjFK:function(a,r){return a||r},hKnFu:t(1190),VlyDS:t(1180),XpCQx:t(705),rUMzz:function(a,r){return a===r},ffzNO:"function",EdWky:function(a,r){return a(r)},ydLhM:t(770),FBewE:function(a,r){return a!==r},Twour:t(1725),UjbIy:"nlPBK",TePvb:function(a,r){return a!==r},LKxHO:t(1616),qHszA:t(1121),JCsdp:"bd_did",PlNep:"device_id",PVkcZ:function(a,r){return a||r},yebAc:function(a,r,s){return a(r,s)},wejMG:"fws_1.0.0",MewQG:function(a,r){return a>=r},TWfyM:function(a,r,s){return a(r,s)},pBghj:function(a,r){return a&r},vxMKj:function(a,r,s){return a(r,s)},rFRmR:t(1164),MOsmX:t(1661),ioMjZ:function(a,r,s){return a(r,s)},UnhvU:t(983),TRSVo:t(945)+"eeded",qzGyT:function(a,r){return a===r},dyhhe:t(372),hYTNb:function(a,r){return a(r)},XmINi:t(1440)+">",tcSpi:t(1154)+t(1538)+"t",VqMEW:t(248),rHulp:function(a,r){return a-r},USOjp:function(a,r){return a===r},fvBuX:function(a,r){return a!==r},mnXmm:t(501),cAEon:"LeHsM",mxTch:function(a,r,s){return a(r,s)},KFcYS:t(1242)+t(1456)+t(1317)+t(456)+"ver",tjRvT:function(a,r,s){return a(r,s)},qiaoO:t(1038),MAHEV:t(380)+"3",QJsvI:t(1617)+"2",ChZgf:function(a,r){return a!==r},dgdCu:t(616),uczPy:t(1516),bfUzw:t(1242)+"ay, netw"+t(410)+t(508),MhnCP:function(a,r){return a!==r},EGQCP:"XzbDr",oiOkx:t(203),IbikR:"EVNmR",JYkeg:function(a,r){return a===r},dptly:"close, w"+t(534)+t(1683),khtRX:function(a){return a()},uzoWz:function(a,r){return a==r},ykegs:t(1761)+"rovide a"+t(1086)+t(1397)+t(202)+"e a stri"+t(579)+" arraybuffer",IULUG:function(a,r){return a==r},ChufP:t(1259),eIZwm:function(a,r){return a!=r},rUKii:function(a,r){return a(r)},UCNGG:function(a,r){return a(r)},SGyjj:t(1761)+t(1282)+t(1047)+"ervice",bBmIk:function(a,r){return a instanceof r},UVZuq:function(a,r){return a===r},rQOtX:"sent",cmSpT:t(1664),QmgmE:function(a,r){return a||r},zsXjc:t(194)+t(1218)+t(1274),oBvqf:t(215),sejem:t(1502),hwOgx:function(a,r){return a(r)},KIrxW:function(a,r){return a&r},GUsms:function(a,r){return a&r},VJVhm:"jffcz",QKbWb:t(1199),EAJHf:t(506),QSBcR:t(502),QapKR:t(723),LPxRt:function(a,r){return a(r)},YJDEZ:"success",CrKmk:function(a,r,s){return a(r,s)},oQqhg:t(412),FFAiY:t(1407),cBEXR:"Window",aJBLn:function(a,r){return a!=r},ZoFyo:function(a,r){return a===r},LyvJu:function(a,r){return a!=r},rkMrD:function(a,r){return a!=r},KBsUk:t(1711),iaLzY:function(a,r){return a!=r},ukdGS:function(a,r){return a!=r},DrMcU:function(a,r){return a===r},dkfzM:t(907)+"dWorkerG"+t(660)+"pe",qbPkc:"SharedWo"+t(426)+"alScope",NWowZ:t(1489)+t(797)+"balScope",Teqji:function(a,r){return a!=r},ksdoV:function(a,r){return a===r},MBEMG:function(a,r){return a!=r},BwJdU:function(a,r,s){return a(r,s)},NdZzL:"__x_msg_"+t(251)};Ut.r(De),Ut.d(De,{FWS:()=>qm,CustomErrorEvent:()=>pl,createCloseEvent:()=>bt,ReconnectEvent:()=>xl,createErrorEvent:()=>ft,decodedFrame:()=>on,createOpenEvent:()=>bl,CustomCloseEvent:()=>ml,createReconnectEvent:()=>Ia,FrontierMessageEvent:()=>wl,encodeFrame:()=>Ht,createMessageEvent:()=>yl,OpenEvent:()=>_l,ErrorCode:()=>cn,Event:()=>ir,MessageEvent:()=>gl});let n="";function i(a=""){let r=t;if(e[r(369)](e[r(1672)],e[r(1672)])){let d=""+Date[r(786)](),f=n||(n=e.sgIKS(h,a)),p=Math.random()[r(1726)](16)[r(358)](-6);return e[r(450)](e.DxLBW("02"+d,f),p)}else return new _0x1d68b2(_0x122d56)}function o(){let a=t;return e[a(1359)](e[a(1262)](1e4,Date.now()),Math[a(516)](1e4*Math[a(893)]()))}function c(a){let r=t;return(e[r(1295)](Array,8)[r(1642)]("0")+e[r(867)](parseInt,a,10)[r(1726)](2)).slice(-8)}function l(a){let r=t;return e[r(1142)](e.EXYJw(Array,4).join("0"),e[r(946)](parseInt,a,2)[r(1726)](16))[r(358)](-4)}function u(a){let r=t,s=a.split(/\./)[r(472)](p=>c(p)),d=[];return d[0]=e.mMQtw(l,e[r(1355)](s[0],s[1])),d[1]=e.gzkbc(l,s[2]+s[3]),[e.Ekmic,r(1020),e[r(1272)],e.Ekmic,r(1020),e[r(1531)],d[0],d[1]][r(1642)]("")}function h(a){let r=t;if(e[r(1125)](e[r(1090)],r(434))){let s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(1149)](a),d=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(a);return s?e.JeBCR(u,a):d?e.EXYJw(x,a):e[r(1141)]}else _0x2beda8=_0x2c88ea(_0x30ecb5),e[r(1472)](_0x33b32f,32)&&(_0x5e0ca7|=e[r(1069)](127&_0x23ec5c,_0xf598b)),_0x24da06+=7}function x(a){let r=t,s={EwhXc:function(R,C){return e[z(422)](R,C)},BWogR:function(R,C){return e.DxLBW(R,C)},jpySy:function(R,C){return e[z(458)](R,C)},cJQZM:function(R,C,N){return e.wyYvG(R,C,N)},WIZuO:function(R,C){return e[z(1686)](R,C)}},d="",f=[],p=0,y=0,S=!0,g=e[r(1272)];if(e[r(1173)](a[r(1622)]("::"),-1)){let R=a.split("::");for(let N=0;e[r(1019)](N,R[r(279)]);N++)if(r(1271)==="dArfR")this["_cursorF"+r(617)]=_0x5394db;else{let q=R[N];if(e.FBANc(q[r(1622)](":"),0))if(e[r(1418)]("dlDLl",e[r(212)])){let B=_0x36f4ca(_0x4e7a77);this[r(1247)]&&s[r(740)](this[r(1247)][r(493)+"te"],this[r(1528)])&&(this[r(1247)]&&this[r(1247)][r(401)](B),this[r(1658)](r(1570),_0x452dc9))}else{let B=q.split(":");S&&(p=B[r(279)]),y+=B.length;for(let M=0;M<B[r(279)];M++)if(e[r(1675)](4,B[M][r(279)])){let oe=g.substring(0,e[r(1124)](4,B[M][r(279)])),ze=oe.concat(B[M]);f.push(ze)}else f[r(1730)](B[M]);S=!1}else{if(q[r(279)]!==4){let B=g[r(1733)+"g"](0,e[r(1446)](4,q[r(279)])),M=B[r(359)](q);f.push(M)}else f[r(1730)](q);S&&(p+=1),y+=1,S=!1}}let C="";for(let N=0;e.ssPNP(N,e[r(1446)](8,y));N++)C=C[r(359)](g);for(let N=0;e[r(1025)](N,f[r(279)]);N++)e[r(1418)](N,p)&&(d=d.concat(C)),d=d[r(359)](f[N]);return d}{let R=a[r(813)](":");for(let C=0;e[r(1387)](C,R[r(279)]);C++)if(e.WDnVE(e[r(1738)],e[r(1634)])){let N=R[C];if(e.WDnVE(4,R[C].length))if(e[r(1409)]===r(428)){let q=0,B=_0x3c1f0a,M=s[r(1588)](_0x2bc102,4);for(;s[r(447)](B,M);){let{value:oe,offset:ze}=s[r(541)](_0x553203,_0x435240,B);B=ze,q=s[r(455)](q,8)>>>0,q+=oe}return{value:q,offset:M}}else{let q=g[r(1733)+"g"](0,4-R[C][r(279)]),B=q.concat(N);d=d[r(359)](B)}else d=d[r(359)](N)}else return _0x2bcda9[r(1183)+"Code"](e[r(568)](255,this[r(569)]),e.OweVT(this[r(569)],8)&255,e[r(568)](e[r(1293)](this[r(569)],16),255),this.low>>>24,255&this[r(707)],e[r(747)](this[r(707)]>>>8,255),e[r(747)](e.NeNUR(this.high,16),255),e.waNDr(this.high,24));return d}}function m(a,r){let s=t,d=a[s(1441)];e.WDnVE(void 0,d)&&(ge(r,10),e.WrNnN(H,r,d));let f=a[s(273)];e[s(1755)](void 0,f)&&(e[s(560)](ge,r,18),e[s(867)](H,r,f))}function w(a){let r=t,s={};e:for(;!e[r(1432)](J,a);){let d=e[r(573)](me,a);switch(e[r(1563)](d,3)){case 0:break e;case 1:s.key=P(a,e[r(1530)](me,a));break;case 2:s.value=e[r(867)](P,a,e[r(1200)](me,a));break;default:e[r(867)](T,a,e[r(394)](7,d))}}if(e[r(369)](void 0,s.key))throw new Error(r(1406)+r(1394)+" field: "+r(1441));if(e.oSgPH(void 0,s[r(273)]))throw new Error(e.XTCYP);return s}function v(a){let r=t,s=e[r(1185)](D);return e[r(1607)](_,a,s),e[r(1200)](U,s)}function _(a,r){let s=t,d={RcBrt:e[s(1550)]},f=a[s(1146)];e[s(1675)](void 0,f)&&(e[s(1610)](ge,r,8),e.FeOYr(yt,r,f));let p=a.LogID;e.BGquI(void 0,p)&&(e[s(946)](ge,r,16),yt(r,p));let y=a[s(574)];e[s(548)](void 0,y)&&(e[s(946)](ge,r,24),e[s(867)](yt,r,e.BswPn(O,y)));let S=a[s(278)];S!==void 0&&(ge(r,32),e[s(320)](yt,r,e.EXYJw(O,S)));let g=a[s(1425)];if(e[s(200)](void 0,g))for(let ze of g)if(e.FdaFb!==e[s(411)]){e[s(1607)](ge,r,42);let Ye=e[s(1185)](D);e[s(867)](m,ze,Ye),ge(r,Ye[s(859)]),e[s(470)](W,r,Ye),L(Ye)}else{let Ye=_0x5d1e4a(d[s(971)],{message:_0x2e4c77[s(555)],code:_0x295402[s(1120)+s(400)],error:_0x464f5d});this[s(919)+s(563)+s(210)](Ye)}let R=a[s(1172)+s(1088)];R!==void 0&&(e[s(1335)](ge,r,50),e[s(560)](H,r,R));let C=a[s(745)+s(986)];e[s(1187)](void 0,C)&&(e[s(369)](e[s(670)],e[s(670)])?(e.FeOYr(ge,r,58),e[s(1607)](H,r,C)):(_0x48ea9c[s(474)+s(682)]="",_0x191d46[s(759)](_0x324b84)));let N=a[s(1213)];e[s(1187)](void 0,N)&&(e[s(224)](ge,r,66),ge(r,N[s(279)]),e[s(470)](de,r,N));let q=a[s(584)];e.jhspX(void 0,q)&&(e[s(896)](ge,r,74),e[s(1758)](H,r,q));let B=a[s(323)+s(286)];e[s(1467)](void 0,B)&&(e[s(1636)](ge,r,82),H(r,B));let M=a[s(1230)];e[s(934)](void 0,M)&&(e[s(1548)](ge,r,90),e[s(904)](H,r,M));let oe=a[s(536)+"e"];e.WDnVE(void 0,oe)&&(ge(r,96),e[s(348)](yt,r,e[s(1591)](O,oe)))}function E(a){let r=t;return e[r(755)](I,e[r(875)](G,a))}function I(a){let r=t,s={};e:for(;!e[r(1200)](J,a);){let d=me(a);switch(e[r(1690)](d,3)){case 0:break e;case 1:s.SeqID=e[r(492)](Rt,a,!0);break;case 2:s.LogID=e[r(1362)](Rt,a,!0);break;case 3:s.service=me(a);break;case 4:s.method=me(a);break;case 5:{let f=e[r(1742)](A,a);(s.headers||(s[r(1425)]=[]))[r(1730)](e.sgIKS(w,a)),a.limit=f;break}case 6:s[r(1172)+r(1088)]=P(a,e[r(1295)](me,a));break;case 7:s["payloadT"+r(986)]=e[r(360)](P,a,e[r(1211)](me,a));break;case 8:s[r(1213)]=e.OaXkd(ce,a,e[r(294)](me,a));break;case 9:s.LogIDNew=e[r(1288)](P,a,e[r(444)](me,a));break;case 10:s[r(323)+"ming"]=e[r(904)](P,a,e[r(1501)](me,a));break;case 11:s[r(1230)]=P(a,me(a));break;case 12:s[r(536)+"e"]=e.IyCua(me,a);break;default:e[r(1758)](T,a,e[r(1291)](7,d))}}if(e[r(422)](void 0,s[r(1146)]))throw new Error(e[r(1315)]);if(e[r(369)](void 0,s[r(1545)]))throw new Error(e[r(645)]);if(e[r(1635)](void 0,s[r(574)]))throw new Error(e[r(564)]);if(e[r(369)](void 0,s[r(278)]))throw new Error(e[r(1568)]);return s}function A(a){let r=t,s=e.BswPn(me,a),d=a.limit;return a[r(859)]=e[r(450)](a[r(662)],s),d}function T(a,r){let s=t;switch(r){case 0:for(;e[s(568)](128,e[s(353)](te,a)););break;case 2:e[s(824)](Z,a,e[s(353)](me,a));break;case 5:e[s(1636)](Z,a,4);break;case 1:e[s(360)](Z,a,8);break;default:throw new Error(s(732)+"ented ty"+s(1039)+r)}}function O(a){return a|=0,{low:a,high:a>>31,unsigned:e.geZSP(a,0)}}let b=[];function D(){let a=t;if(e[a(219)](a(659),e.hSZUL)){let r=b.pop();return r?(r.offset=r.limit=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}else return!!this[a(1342)]}function L(a){let r=t;if(e.Gdkkn===e[r(432)])return null;b[r(1730)](a)}function G(a){return{bytes:a,offset:0,limit:a[t(279)]}}function U(a){let r=t,s=a[r(583)],d=a.limit;return e[r(369)](s[r(279)],d)?s:s[r(762)](0,d)}function Z(a,r){let s=t;if(e[s(1173)](e[s(828)](a.offset,r),a.limit))throw new Error(e[s(1377)]);a[s(662)]+=r}function J(a){let r=t;return e.geZSP(a[r(662)],a[r(859)])}function ie(a,r){let s=t;if(e[s(1187)](s(1445),"mlQlT"))return this[s(1247)]?this._ws[s(493)+"te"]:this._options["automati"+s(626)]?this.CONNECTING:this[s(435)];{let d=a[s(583)],f=a[s(662)],p=a[s(859)],y=f+r;if(e[s(1173)](y,d[s(279)]))if(e.vFSKq(e[s(1414)],e.hMQRu)){let S=new Uint8Array(e[s(1009)](2,y));S.set(d),a.bytes=S}else return s(222)+"_"+this[s(857)];return a[s(662)]=y,e[s(404)](y,p)&&(a[s(859)]=y),f}}function Q(a,r){let s=t,d=a[s(662)];if(e[s(404)](d+r,a[s(859)]))throw new Error(e[s(627)]);return a[s(662)]+=r,d}function ce(a,r){let s=t,d=e[s(869)](Q,a,r);return a[s(583)][s(762)](d,e[s(1359)](d,r))}function de(a,r){let s=t,d=e[s(1234)](ie,a,r[s(279)]);a[s(583)][s(1706)](r,d)}function P(a,r){let s=t,d=Q(a,r),f=String.fromCharCode,p=a[s(583)],y="\uFFFD",S="";for(let g=0;e[s(373)](g,r);g++){let R=p[e.vGrqN(g,d)],C,N,q,B;if(e[s(1515)](128,R)===0)S+=f(R);else if(e[s(301)](224,R)===192)e[s(1756)](e.BMcZD(g,1),r)?S+=y:(C=p[e[s(997)](g+d,1)],e[s(394)](192,C)!==128?S+=y:e[s(1125)](e[s(513)],e[s(833)])?mYkanF[s(1482)](_0x3f0ac9,_0x4a5f00)&&_0x485a45[s(1706)](_0x9666c6,_0x528c93):(B=e[s(318)](e[s(792)](e[s(747)](31,R),6),63&C),e[s(1019)](B,128)?S+=y:(S+=e[s(587)](f,B),g++)));else if(e[s(1089)](e[s(301)](240,R),224))if(e[s(529)](e[s(911)](g,2),r))S+=y;else if(e.KTfXX(e.yxiim,e[s(1567)]))try{return!!this[s(1342)]}catch(M){return _0x312192[s(759)](M),!1}else C=p[e[s(1355)](g+d,1)],N=p[e[s(1169)](e.ViQov(g,d),2)],e[s(394)](e[s(849)](C,N<<8),49344)!==32896?S+=y:(B=e.FOSVr(e.RgwFv(e[s(394)](15,R),12)|e[s(792)](63&C,6),63&N),B<2048||B>=55296&&e[s(326)](B,57343)?S+=y:(S+=f(B),g+=2));else e[s(1089)](248&R,240)?e.vGrqN(g,3)>=r?S+=y:e[s(200)](e.HxGtE,e[s(1049)])?(C=p[e[s(1355)](e[s(362)](g,d),1)],N=p[e[s(622)](e[s(1112)](g,d),2)],q=p[e[s(1112)](e.CpISS(g,d),3)],(e[s(338)](e[s(826)](C,e[s(1731)](N,8)),e[s(1069)](q,16))&12632256)!==8421504?S+=y:(B=e.SJwXn(e[s(1552)](e[s(601)](7&R,18),e[s(568)](63,C)<<12),e[s(1069)](e[s(301)](63,N),6))|63&q,e[s(1595)](B,65536)||e[s(416)](B,1114111)?S+=y:(B-=65536,S+=e.OaXkd(f,e[s(622)](B>>10,55296),e[s(936)](1023&B,56320)),g+=3))):(e[s(867)](_0x3c4dac,_0x259d4b,e[s(826)](e.jAAMq(127,_0x4b397a),128)),_0x2e96f9>>>=7):S+=y}return S}function H(a,r){let s=t,d={ygMcc:e[s(972)],AmxQT:s(1250)+"ervice",JWRve:e[s(1193)],GlrBI:function(g,R,C,N){return e[s(1365)](g,R,C,N)},CmKhq:e[s(1455)],tTbYU:function(g,R,C,N){return e[s(1365)](g,R,C,N)},AJXWv:e[s(264)],tbMnN:e[s(882)],xKEEk:e[s(586)],KGnFI:function(g,R){return e[s(1574)](g,R)},AuAXi:function(g,R){return e[s(1237)](g,R)},LdjQd:function(g,R){return g<<R},Iyxrd:function(g,R){return g<<R},RgudD:function(g,R){return e[s(1638)](g,R)},itWRT:function(g,R){return g<<R}},f=r[s(279)],p=0;for(let g=0;e[s(1161)](g,f);g++)if(e[s(1257)]!=="LnpDf"){let R=r.charCodeAt(g);e[s(1756)](R,55296)&&e[s(326)](R,56319)&&e[s(1161)](e[s(450)](g,1),f)&&(R=e[s(1687)](e[s(900)](R,10)+r.charCodeAt(++g),56613888)),p+=e[s(1410)](R,128)?1:e.CWaiK(R,2048)?2:R<65536?3:4}else{let[R,C]=_0x13ee01(_0x331dfc),N=d[s(1496)](_0x48290f,R),q=0;return _0x3f0f7e[s(577)](B=>{let M=s,oe=d[M(567)].split("|"),ze=0;for(;;){switch(oe[ze++]){case"0":_0x1c8cd3.log(d[M(1484)],B,B[M(574)]);continue;case"1":_0x5734ee[M(759)](d[M(284)],q);continue;case"2":q=d.GlrBI(_0x31b035,N,q,B[M(574)]||0);continue;case"3":_0x47708a[M(759)](d[M(1339)],q);continue;case"4":q=_0x2b3a49(_0x1adf3a[M(324)+"er"](B[M(1491)]||_0xdf27fd),N,q);continue;case"5":q=d[M(1329)](_0x1266e9,0,N,q);continue;case"6":q=d.GlrBI(_0x4c27ef,C[B[M(379)+M(391)]],N,q);continue;case"7":q=_0x5aa3df(B[M(379)+M(391)],N,q);continue;case"8":_0x39f671[M(759)](d[M(1452)],q);continue;case"9":_0x4badf3[M(759)](d[M(1648)],q);continue;case"10":_0x314dda.log(d[M(1750)],q);continue}break}}),{frameType:_0x587203,headers:[{key:s(886)+s(815),value:_0x43088f}],payload:N}}e[s(320)](ge,a,p);let y=e[s(246)](ie,a,p),S=a[s(583)];for(let g=0;e[s(511)](g,f);g++){let R=r[s(1302)+"At"](g);if(e[s(529)](R,55296)&&e[s(326)](R,56319)&&e.UfMgk(e[s(1393)](g,1),f)&&(R=e[s(1687)](e[s(997)](e.RgwFv(R,10),r[s(1302)+"At"](++g)),56613888)),e.ZyeiJ(R,128))S[y++]=R;else if(e[s(891)](e.kAWfF,e[s(1702)])){if(_0x316a78<=-_0x5e94f9)return _0x227f6f;if(e[s(1756)](_0x4fc419+1,_0x144083))return _0x3992fc}else{if(e[s(1472)](R,2048))S[y++]=e.SJwXn(R>>6&31,192);else{if(e[s(1743)](R,65536))S[y++]=e[s(318)](e.oIJIO(R>>12,15),224);else if(e[s(1721)](e.qWTlV,e.qWTlV))S[y++]=e[s(394)](e.adSSX(R,18),7)|240,S[y++]=e[s(956)](R,12)&63|128;else return new _0x5b333f(d[s(385)](d[s(385)](d.LdjQd(_0x1dd0fe[4],24)|d[s(310)](_0x1a1399[5],16),d[s(802)](_0x43f2e8[6],8)),_0x307e32[7]),d[s(385)](_0x1a8edc[0]<<24|d[s(275)](_0x42787b[1],16)|_0x22dff4[2]<<8,_0x1bb17b[3]),_0x578b06);S[y++]=R>>6&63|128}S[y++]=e.pxFtg(e.tqMVP(63,R),128)}}}function W(a,r){let s=t,d={FTKLK:function(f,p,y){return e[z(1758)](f,p,y)},AKHzF:function(f,p){return f(p)}};if(e[s(515)]==="USxdU"){_0x2ed173(_0x281d95,42);let f=_0x2921ad();wKXQkc[s(1609)](_0x483ac2,_0xf629f0,f),wKXQkc[s(1609)](_0x3a5085,_0x348060,f[s(859)]),_0x3124a2(_0x1a3378,f),wKXQkc[s(1652)](_0x53eefe,f)}else{let f=e[s(494)](ie,a,r[s(859)]),p=a[s(583)],y=r[s(583)];for(let S=0,g=r[s(859)];e[s(1387)](S,g);S++)p[e[s(1098)](S,f)]=y[S]}}function te(a){let r=t;return a[r(583)][e[r(224)](Q,a,1)]}function Ze(a,r){let s=t,d=ie(a,1);a[s(583)][d]=r}function me(a){let r=t,s=0,d=0,f;do f=e[r(1574)](te,a),e[r(383)](s,32)&&(d|=e[r(825)](127,f)<<s),s+=7;while(e[r(301)](128,f));return d}function ge(a,r){let s=t;for(r>>>=0;e[s(698)](r,128);)e[s(1503)](Ze,a,e[s(1552)](e[s(1515)](127,r),128)),r>>>=7;e.IZPbM(Ze,a,r)}function Rt(a,r){let s=t,d={ZHprD:function(g,R){return e[z(294)](g,R)},yzJBZ:function(g,R){return e.xeRJW(g,R)}},f=0,p=0,y=0,S;if(S=e[s(1458)](te,a),f=e.eluXD(127,S),e[s(301)](128,S)&&(S=e[s(1742)](te,a),f|=e.wKWdJ(127,S)<<7,128&S))if(e[s(642)](e[s(689)],e[s(1469)]))S=e[s(295)](te,a),f|=e[s(1069)](e[s(1334)](127,S),14),128&S&&(S=te(a),f|=e[s(825)](127,S)<<21,e[s(1334)](128,S)&&(S=e[s(1633)](te,a),p=127&S,e[s(1657)](128,S)&&(S=e[s(1530)](te,a),p|=e[s(1334)](127,S)<<7,e[s(747)](128,S)&&(S=e[s(693)](te,a),p|=e[s(1686)](127&S,14),128&S&&(S=e[s(1295)](te,a),p|=e.RkDRo(e[s(1515)](127,S),21),e[s(228)](128,S)&&(S=e.mMQtw(te,a),y=e[s(334)](127,S),128&S&&(S=e[s(1633)](te,a),y|=e[s(792)](127&S,7))))))));else{let g=_0x4e5f43.call(gfNytZ[s(1464)](_0xaf9a12,this),_0x1e0eca,..._0x5ba046);return _0x494681[s(1706)](g,_0x1cb02c[s(316)]?_0x36ee19[s(316)]():[_0x379967]),gfNytZ[s(1221)](_0x2e712b,g)}return{low:f|e[s(1181)](p,28),high:e[s(829)](e.ntJTX(p,4),e.xLkST(y,24)),unsigned:r}}function yt(a,r){let s=t,d=e[s(781)](r[s(569)],0),f=(r.low>>>28|e[s(1181)](r[s(707)],4))>>>0,p=r[s(707)]>>>24,y=e[s(422)](0,p)?f===0?d<16384?e[s(1595)](d,128)?1:2:e[s(1307)](d,2097152)?3:4:e.yPcuf(f,16384)?f<128?5:6:f<2097152?7:8:e[s(373)](p,128)?9:10,S=ie(a,y),g=a[s(583)];switch(y){case 10:g[e[s(1694)](S,9)]=e[s(935)](e.iPmkj(p,7),1);case 9:g[e[s(1707)](S,8)]=e.fNqwi(9,y)?e[s(1237)](128,p):e[s(710)](127,p);case 8:g[e[s(1170)](S,7)]=e.WDnVE(8,y)?e[s(211)](e[s(651)](f,21),128):e[s(1011)](f,21)&127;case 7:g[e[s(1225)](S,6)]=e[s(1296)](7,y)?e[s(1736)](f>>>14,128):e[s(394)](e.OweVT(f,14),127);case 6:g[e[s(1170)](S,5)]=e[s(934)](6,y)?f>>>7|128:e[s(266)](e[s(271)](f,7),127);case 5:g[e[s(518)](S,4)]=e[s(1391)](5,y)?e.OVrBo(128,f):e[s(1517)](127,f);case 4:g[S+3]=e.EhKVu(4,y)?e[s(211)](d>>>21,128):e[s(570)](e.waNDr(d,21),127);case 3:g[S+2]=e[s(352)](3,y)?e.iKTnK(e[s(781)](d,14),128):e[s(1277)](d>>>14,127);case 2:g[e[s(1283)](S,1)]=y!==2?e.hDvYB(e[s(1293)](d,7),128):e[s(1712)](d,7)&127;case 1:g[S]=e[s(219)](1,y)?e.CCxQW(128,d):e.sIaPM(127,d)}}function on(a){let r=t,s={fiWQt:e[r(1005)],ocBrS:r(267)+r(526)};return e[r(891)](e[r(696)],e[r(696)])?{frameType:_0x2b9b7f,headers:[{key:s[r(1442)],value:s[r(1420)]}],payload:void 0}:E(a)}function Ht(a){return v(a)}let an=65536,ei=e[t(1611)],ye=e.PpzrL(an,an),Te=ye*ye,rr=e[t(1036)](Te,2),Ne=String[t(650)+"e"][t(1302)+"At"];class pe{constructor(r,s,d){let f=t;this[f(1748)]=!0,this[f(569)]=e.gJsGS(0,r),this.high=e[f(724)](0,s),this[f(924)]=!!d}static[t(1748)](r){let s=t;if(e[s(1762)](e.NHoxc,e[s(796)]))return r&&e[s(289)](!0,r[s(1748)]);{let d=e.Mujgi[s(813)]("|"),f=0;for(;;){switch(d[f++]){case"0":return _0xc666ef(_0x1b9c37,_0x70aaaf,_0x1ed7a8)+_0x25f4ca;case"1":if(_0x24148e.utf8Write)return _0x2766fd.utf8Write(_0x2f6478,_0x441375)+_0x4eae03;continue;case"2":if(e.bPYbn(_0x40a0de.length,40))return e[s(874)](e[s(661)](_0x298356,_0x5b485d,_0x17de9f,_0x4df27d),_0x2a4d32);continue;case"3":if(!_0x429bd9)return _0xb4d570;continue;case"4":if(_0x4dc77b[s(1685)])return e.yarhX(_0x4da821[s(1685)](_0x233e26,_0x222997),_0x43ed99);continue}break}}}static fromBits(r,s,d){let f=t,p={SRARL:function(y,S,g){return y(S,g)},PnVOq:e.SavKq};if(f(489)!==e[f(685)])return new pe(r,s,d);{let y=_0x1f9903[f(1353)][f(358)](_0x146a52[f(1371)+"et"],e[f(1393)](_0x81ecbe[f(1195)+"th"],_0x1faefc[f(1371)+"et"]));this[f(779)]&&this[f(779)].send({data:y,fail:S=>{let g=f;this[g(413)](g(403),p[g(912)](_0x2ac083,p[g(1311)],{message:this[g(1488)+"rrorMess"+g(1107)](S)}))}})}}static[t(405)+"s"](r,s,d){let f=t;return d?pe["fromByte"+f(1378)](r,s):pe[f(405)+"sBE"](r,s)}static[t(405)+"sLE"](r,s){let d=t;return e[d(691)]===e[d(691)]?new pe(e.fEYUR(e[d(1736)](r[0]|e[d(1719)](r[1],8),e[d(1638)](r[2],16)),e[d(1158)](r[3],24)),r[4]|e.RkDRo(r[5],8)|e.aAoZt(r[6],16)|e[d(738)](r[7],24),s):this._qosDB?.[d(1706)]({message_id:_0x499733,timestamp:_0x2c9f72})}static[t(405)+"sBE"](r,s){let d=t;return new pe(e.cvGwe(e[d(1552)](e.xLkST(r[4],24),r[5]<<16)|e[d(1566)](r[6],8),r[7]),e[d(211)](e[d(1686)](r[0],24)|e[d(889)](r[1],16)|r[2]<<8,r[3]),s)}static[t(205)](r){let s=t;return e.Drcoa(r,ei)?hl:new pe(e.lqcfo(e.gJsGS(e[s(1267)](e[s(1318)](Ne.call(r,0),e[s(792)](Ne[s(976)](r,1),8)),e[s(620)](Ne[s(976)](r,2),16)),e[s(900)](Ne.call(r,3),24)),0),e[s(1665)](e[s(1744)](e[s(1552)](Ne.call(r,4),Ne[s(976)](r,5)<<8),e[s(1266)](Ne[s(976)](r,6),16))|e.AJqjZ(Ne[s(976)](r,7),24),0),!0)}[t(572)](){let r=t;if(e[r(1026)](e[r(1495)],e[r(1495)]))e[r(492)](_0x3ca07a,_0x34142a,96),_0x64be5c(_0x2f8c8e,_0xb03f2(_0x468b09));else return String[r(1183)+r(615)](e.SoZAf(255,this.low),e[r(374)](this.low>>>8,255),e[r(228)](this[r(569)]>>>16,255),this.low>>>24,e[r(228)](255,this[r(707)]),this[r(707)]>>>8&255,e.yUHYP(this[r(707)]>>>16,255),this[r(707)]>>>24)}static fromNumber(r,s=!0){let d=t;if(isNaN(r))return s?tm:hl;if(s){if(r>=Te)return rm}else{if(e[d(326)](r,-rr))return im;if(e[d(819)](e[d(1527)](r,1),rr))return nm}return pe[d(799)](e[d(1424)](r,ye)|0,e[d(318)](e[d(1273)](r,ye),0),s)}[t(1078)](){let r=t,s={eCwAu:function(d,f,p){return d(f,p)},GTSrD:e[r(1157)],fZlsE:e[r(1637)]};if(e[r(863)](e[r(1135)],e.vFQCh))return this[r(924)]?e[r(1169)](e.qnzEp(this[r(707)],0)*ye,this[r(569)]>>>0):e[r(1261)](e.SgYeM(this.high,ye),e.lqcfo(this.low,0));{this[r(1614)+r(1650)+"t"]();let d=s[r(1042)](_0x4c8ad3,s[r(636)],{message:s[r(1223)]});this[r(1123)+r(991)+"yReconnect"]&&this["onStopIm"+r(991)+"yReconnect"](d)}}[t(1439)](){let r=t;return e[r(1762)](0,this[r(707)])&&this[r(569)]===0}[t(225)](r){let s=t;if(e[s(463)]===e[s(463)]){pe[s(1748)](r)||(r=pe[s(324)+"er"](r));let d=e[s(1144)](this[s(707)],16),f=e.LvLVr(65535,this[s(707)]),p=e[s(1712)](this.low,16),y=65535&this[s(569)],S=r.high>>>16,g=e[s(374)](65535,r[s(707)]),R=e[s(746)](r[s(569)],16),C=e.bKRkk(65535,r[s(569)]),N=0,q=0,B=0,M=0;return M+=e[s(1261)](y,C),B+=M>>>16,M&=65535,B+=p+R,q+=e[s(651)](B,16),B&=65535,q+=f+g,N+=e[s(1264)](q,16),q&=65535,N+=d+S,N&=65535,pe[s(799)](e[s(985)](B,16)|M,e[s(905)](e[s(1719)](N,16),q),this[s(924)])}else{let d=this[s(707)],f=this[s(569)];return[e.OJFXf(d,24),e[s(935)](e.RaTMa(d,16),255),e.qnzEp(d,8)&255,255&d,e[s(1144)](f,24),e[s(437)](e[s(1752)](f,16),255),e[s(668)](f>>>8,255),e[s(334)](255,f)]}}[t(1006)](r){let s=t;if(e[s(352)](e[s(1138)],e[s(1138)]))_0x3e6c5d.log(_0x211df3);else return pe[s(1748)](r)||(r=pe[s(324)+"er"](r)),e[s(565)](this.unsigned,r[s(924)])&&e.oUtHM(e.ydoIG(this[s(707)],31),1)&&r[s(707)]>>>31===1?!1:e[s(748)](this.high,r[s(707)])&&e.qoKTu(this[s(569)],r[s(569)])}[t(890)](){let r=t;return e[r(1520)](-1,this[r(569)])&&this[r(707)]===-1?pe[r(799)](0,0,this[r(924)]):e.ncOYY(-1,this[r(569)])?pe[r(799)](0,e[r(1169)](this[r(707)],1),this[r(924)]):pe[r(799)](e[r(1285)](this[r(569)],1),this[r(707)],this[r(924)])}[t(1093)](r){let s=t;if(e[s(562)]!==e[s(775)])return r?this[s(1691)+"E"]():this[s(1297)+"E"]();{let d=this._listeners[_0x5349a2];if(d)for(let f=0;e[s(458)](f,d[s(279)]);)e[s(1624)](d[f].fn,_0x3991c5)?d[s(1197)](f,1):++f}}[t(1691)+"E"](){let r=t,s=this.high,d=this[r(569)];return[e[r(437)](255,d),e[r(888)](d,8)&255,e[r(935)](e[r(1209)](d,16),255),e.NeNUR(d,24),e[r(272)](255,s),e.HMIFh(e.PWGTK(s,8),255),e.apUNm(s>>>16,255),s>>>24]}toBytesBE(){let r=t,s=this[r(707)],d=this[r(569)];return[e[r(271)](s,24),e[r(781)](s,16)&255,e[r(1014)](s,8)&255,255&s,e[r(481)](d,24),e[r(668)](e[r(473)](d,16),255),e[r(806)](d>>>8,255),e[r(1176)](255,d)]}}let hl=new pe(0,0,!1),tm=new pe(0,0,!0),nm=pe[t(799)](-1,2147483647,!1),rm=pe[t(799)](-1,-1,!0),im=pe[t(799)](0,-2147483648,!1);var cn=(function(a){let r=t,s=e[r(1238)].split("|"),d=0;for(;;){switch(s[d++]){case"0":a[a[e[r(657)]]=5005]=r(1030)+"OR";continue;case"1":a[a[e.KDudE]=5002]=r(895)+r(1561);continue;case"2":return a;case"3":a[a[e[r(1534)]]=5001]="NATIVE_E"+r(1606);continue;case"4":a[a[e[r(588)]]=5004]=e[r(588)];continue;case"5":a[a[e[r(777)]]=5003]=r(1352)+"IES_ERROR";continue}break}})({});class ir{constructor(r){let s=t;if(e.SLttv(s(1470),"MLUzq")){let d=this[s(697)+s(249)]?.[s(948)+s(832)+"es"](),f=this[s(697)+s(249)]?.[s(527)+s(1327)+"nt"]();if(d&&!_0xa14177[s(555)]){let p="connect "+f+(s(532)+s(1626)+s(1340)+"ed");this["_dispatchErrorEv"+s(210)](e.pTgDl(_0x30d12a,e.SavKq,{message:p,code:_0x503f57[s(1352)+s(800)+"R"],error:_0xfa4987}));return}this._ws&&this[s(1247)][s(493)+"te"]===this[s(1528)]&&this[s(680)+"ect"](),this[s(919)+s(563)+s(210)](e.ZPBId(_0xd28ac,e.SavKq,{message:_0x49f6d3[s(555)],code:_0x1e96b9["NATIVE_E"+s(1606)],error:_0x20ab97}))}else this[s(778)]=r,this[s(1603)]=null}}class xl extends ir{constructor(r,s){let d=t;super(r),this[d(555)]=s&&s[d(555)]||null}}class pl extends ir{constructor(r,s){let d=t,f={HLSEd:function(p,y){return e[z(947)](p,y)}};if(d(1055)!==e[d(1058)])return function(p,...y){let S=d,g=_0x45fd04[S(976)](cJAbZG.HLSEd(_0x39089d,this),p,...y);return _0x253021[S(1706)](g,p[S(316)]?p[S(316)]():[p]),cJAbZG[S(1360)](_0x82463a,g)};{let p=(d(1602)+"6|0|5")[d(813)]("|"),y=0;for(;;){switch(p[y++]){case"0":this[d(555)]=s&&s[d(555)]||"";continue;case"1":super(r);continue;case"2":this[d(665)]=s&&s[d(665)]||"";continue;case"3":this.error=s&&s[d(403)]||null;continue;case"4":this[d(525)]=s&&s[d(525)]||0;continue;case"5":this.code=s&&s[d(580)]||5001;continue;case"6":this[d(1160)]=s&&s[d(1160)]||0;continue}break}}}}class ml extends ir{constructor(r,s){let d=t;super(r),this[d(580)]=s&&s.code||0,this.reason=s&&s[d(1313)]||"",this[d(315)]=s&&s[d(315)]||!1,this[d(547)+d(1254)]=s&&s[d(547)+"nnect"]||!1}}class gl extends ir{constructor(r,s){let d=t;super(r),this[d(1103)]=s&&s[d(1103)]||null}}class wl extends gl{constructor(r,s){let d=t;super(r),this.data=s&&s.data||null,this[d(555)]=s&&s[d(555)]||null}}class _l extends ir{constructor(r,s){let d=t,f={HzYaB:function(p,y){return p!=y},DnYfu:d(498)+"d",LaEjV:e[d(1306)],Aihlf:e[d(1623)]};e.wVetG(e[d(1034)],e[d(1523)])?(super(r),this[d(1103)]=s&&s[d(1103)]||null):_0x240f80.r=p=>{let y=d;gdvoVX[y(1358)](gdvoVX.DnYfu,typeof _0x230881)&&_0x55411e["toString"+y(706)]&&_0x1b3248[y(1137)+"operty"](p,_0xf96897[y(1726)+y(706)],{value:gdvoVX[y(1708)]}),_0x5abf7d[y(1137)+y(790)](p,gdvoVX[y(1023)],{value:!0})}}}function ft(a,{message:r,code:s,error:d}){return new pl(a,{message:r,code:s,error:d})}function bt(a,{code:r,reason:s,wasClean:d,willReconnect:f}){return new ml(a,{code:r,reason:s,wasClean:d,willReconnect:f})}function yl(a,{data:r,message:s}){let d=t;if(e[d(263)]!==e[d(462)])return new wl(a,{data:r,message:s});this._socket&&this[d(779)][d(1601)]({code:_0x375d46,reason:_0x494496})}function bl(a,{data:r}){return new _l(a,{data:r})}function Ia(a,{message:r}){return new xl(a,{message:r})}class El{constructor(r,s){let d=t;this.endpoints=r,this.maxRetries=s,this[d(1498)+d(879)]=0,this["currentE"+d(1226)+d(302)+"t"]=0}[t(1479)+t(700)+t(1461)](){let r=t;this[r(1498)+"ndex"]=0,this[r(930)+r(1226)+r(302)+"t"]=0}resetTries(){let r=t;this[r(930)+r(1226)+"riesCount"]=0}["getCurre"+t(1327)+"nt"](){let r=t;return this[r(803)+"s"][this[r(1498)+"ndex"]]}["getCurre"+t(1327)+t(476)+t(1662)](){let r=t;return this[r(930)+r(1226)+r(302)+"t"]}[t(948)+t(832)+"es"](){let r=t;return!!(this.currentIndex>=this[r(803)+"s"][r(279)]||this[r(1498)+r(879)]===e[r(1687)](this.endpoints.length,1)&&e[r(1463)](this[r(930)+r(1226)+r(302)+"t"],this[r(877)+"es"]))}[t(977)+t(331)+t(245)+"hedMaxRe"+t(399)](){let r=t;return this[r(1498)+r(879)]==this[r(803)+"s"][r(279)]?!0:e[r(823)](this[r(930)+r(1226)+r(302)+"t"],this[r(877)+"es"])}[t(995)+t(1279)+t(916)+"UpdateCo"+t(328)](){let r=t;return this[r(930)+r(1226)+"riesCount"]=1,this[r(1498)+r(879)]++,this[r(803)+"s"][this[r(1498)+r(879)]]}["getCurrentEndpointAndUpd"+t(768)](){let r=t;return this[r(930)+r(1226)+r(302)+"t"]++,this[r(527)+r(1327)+"nt"]()}}let sr=(e[t(1344)](e[t(1140)],typeof globalThis)&&e[t(1376)]===globalThis[t(715)+t(782)][t(216)]||e[t(293)](e[t(1140)],typeof window)&&e[t(553)](e.cBEXR,window[t(715)+"tor"][t(216)]))&&e.LyvJu(t(498)+"d",typeof document),Cn=e[t(388)](e[t(1140)],typeof globalThis)&&(e[t(994)]===globalThis["construc"+t(782)].name||"DedicatedWorkerG"+t(660)+"pe"===globalThis["construc"+t(782)].name)&&e[t(388)](e[t(1140)],typeof tt),ti=(e[t(535)](e[t(1140)],typeof globalThis)&&e[t(1520)](t(1711),globalThis[t(715)+t(782)].name)||e[t(317)](e[t(1140)],typeof globalThis)||e.LyvJu(e[t(1140)],typeof globalThis)&&!!globalThis["WeixinJS"+t(1204)])&&e[t(1140)]!=typeof wx,ni=e.ukdGS(e.UehPf,typeof globalThis)&&(e[t(321)](e[t(1695)],globalThis[t(715)+t(782)].name)||e[t(1519)]===globalThis[t(715)+t(782)][t(216)]||e.GohvH(e[t(597)],globalThis[t(715)+t(782)][t(216)]))&&e[t(350)](e[t(1140)],typeof self),sm=e[t(1140)]!=typeof globalThis&&t(1711)===globalThis["construc"+t(782)][t(216)]&&e[t(388)](t(498)+"d",typeof global)&&e[t(1492)](e[t(994)],global[t(715)+t(782)][t(216)])&&e[t(552)](e[t(1140)],typeof process)&&!!process[t(429)];class Aa{constructor(){this._listeners={}}[t(413)](r,...s){let d=t,f=this[d(1625)+"rs"][r];if(f)f.slice()[d(577)](p=>p.fn[d(1381)](p[d(1326)],s));else if(e.SavKq===r&&!this[d(239)]){let p=s.length&&s[0];if(p instanceof Error)throw p;let y=new Error(e[d(1170)](d(1569)+d(254),p?e[d(1589)](e[d(1400)](" (",p[d(555)]),")"):""));throw y[d(1147)]=p,p}return this}[t(961)](r,s){let d=t;if(r===void 0)this._listeners={};else if(e[d(625)](void 0,s))this._listeners[r]=null;else{let f=this._listeners[r];if(f)for(let p=0;p<f[d(279)];)e[d(1459)](f[p].fn,s)?f[d(1197)](p,1):++p}return this}on(r,s,d){let f=t,p={HEWQq:"close"};if(e.WWYEH(f(847),e[f(1395)]))this[f(413)](p[f(1338)],_0x4e35f5),this.onclose&&this[f(1513)](_0x7a3b04);else return(this[f(1625)+"rs"][r]||(this._listeners[r]=[]))[f(1730)]({fn:s,ctx:d||this}),this}}class om extends Aa{[t(1488)+"rrorMess"+t(1107)](r){let s=t;return r[s(1205)]||r[s(831)]?(s(1653)+" "+(r.errMsg||"")+s(655)+(r.errNo||""))[s(1645)]():JSON[s(965)+"y"](r)}constructor(r,s,d){let f=t;super(),this[f(779)]=null,ti&&wx[f(830)+f(196)]&&(this._socket=wx[f(830)+f(196)]({url:r,protocols:s,header:d,fail:this[f(1201)+f(287)+f(1117)][f(842)](this),success:this[f(1201)+f(1320)+f(1244)+"ler"][f(842)](this)})),Cn&&tt[f(830)+f(196)]&&(this[f(779)]=tt.connectSocket({url:r,protocols:s,header:d,fail:this[f(1201)+f(287)+"lHandler"][f(842)](this),success:this[f(1201)+f(1320)+f(1244)+f(528)][f(842)](this)}))}[t(1201)+t(1320)+t(1244)+"ler"](){let r=t;e[r(1051)](e[r(1064)],e[r(1021)])?this[r(930)+r(1226)+r(302)+"t"]=0:Promise[r(1613)]().then(()=>{let s=r;this[s(1001)+s(234)]()})}[t(1201)+t(287)+t(1117)](r){let s=t;Promise[s(1613)]().then(()=>{let d=s,f=e[d(1031)](ft,e[d(1550)],{message:this[d(1488)+d(1759)+d(1107)](r)});this[d(413)](e[d(1550)],f);let p=e.ukrUw(bt,e.JqjoE,{reason:this[d(1488)+d(1759)+d(1107)](r)});this[d(413)](e.JqjoE,p)})}[t(1001)+t(234)](){let r=t,s={cNJEs:function(d,f){return e[z(338)](d,f)},rYxDj:function(d,f){return e[z(956)](d,f)},lvbAh:function(d,f){return e[z(458)](d,f)},RpECC:function(d,f){return e[z(826)](d,f)},bKryS:function(d,f){return e[z(512)](d,f)},oPZjk:function(d,f){return e[z(368)](d,f)},uEeQN:function(d,f){return d&f},IUWsr:function(d,f){return e[z(1231)](d,f)},bbIbx:function(d,f){return e[z(482)](d,f)},xYeDj:function(d,f){return e[z(565)](d,f)},KbRWr:e[r(1074)],UeBAW:function(d,f,p){return e[r(867)](d,f,p)},nVaGg:e[r(769)],tCCOa:e.SvIiX,ykbKl:e[r(1550)]};this[r(779)][r(1052)](d=>{let f=r;s[f(887)]("cjRSe",s.KbRWr)?(_0x221ca6<2048?_0xf24a5d[_0x2f945a++]=gImMyT[f(1210)](gImMyT[f(1010)](_0x24de63,6)&31,192):(gImMyT[f(1405)](_0x46e6d6,65536)?_0x444cdb[_0x91cb9c++]=gImMyT.RpECC(gImMyT[f(575)](gImMyT[f(1419)](_0x89f77b,12),15),224):(_0x55fac3[_0x3782b5++]=gImMyT[f(927)](gImMyT[f(1163)](gImMyT.oPZjk(_0x56e9d9,18),7),240),_0x4ba228[_0xdf2e3f++]=gImMyT[f(927)](gImMyT.IUWsr(gImMyT[f(1010)](_0x52ac57,12),63),128)),_0x4edb97[_0x3f7a52++]=gImMyT.bbIbx(gImMyT[f(699)](gImMyT.rYxDj(_0xd1f383,6),63),128)),_0x257e5f[_0x37879a++]=gImMyT.uEeQN(63,_0x2192a5)|128):this[f(413)]("open",s[f(441)](bl,s[f(1450)],{...d,data:d[f(1205)]||""}))}),this[r(779)].onClose(d=>{let f=r,p={CvHOh:function(y,S){return e.atCWg(y,S)},nHVkP:function(y,S){return e.bAdln(y,S)},BYaHp:function(y,S){return e.VLTom(y,S)},MeDGU:function(y,S){return e.nnhCR(y,S)},nRFbg:function(y,S){return e[z(1630)](y,S)},igpAM:function(y,S){return e.LitPw(y,S)},DSaMi:function(y,S){return y<S}};if(e.oSgPH(e[f(764)],e.SxocV)){let y=_0x2c91d2[f(1302)+"At"](_0x4d6a7e);y>=55296&&xnEmbd[f(582)](y,56319)&&xnEmbd[f(1073)](xnEmbd[f(1134)](_0x43c438,1),_0x6cc49e)&&(y=xnEmbd[f(1577)](xnEmbd[f(701)](xnEmbd[f(1375)](y,10),_0x348aad[f(1302)+"At"](++_0x59f28b)),56613888)),_0x3e33f2+=xnEmbd[f(1073)](y,128)?1:xnEmbd[f(1073)](y,2048)?2:xnEmbd.DSaMi(y,65536)?3:4}else this[f(413)](f(1601),e[f(1319)](bt,e[f(612)],{...d}))}),this[r(779)][r(915)+"e"](d=>{let f=r;this[f(413)](f(555),yl(s[f(1508)],{...d}))}),this[r(779)][r(233)](d=>{let f=r;this[f(413)](s[f(1553)],s[f(441)](ft,s[f(1553)],{...d,message:d[f(1205)]||""}))})}send(r){let s=t,d={UzVTQ:s(403),pmNbb:function(f,p,y){return e.TIXCr(f,p,y)},fmmHI:e.JqjoE};if(e[s(1196)](r,Uint8Array))if(e.QhOrQ(e[s(742)],e[s(1560)])){let f=r.buffer[s(358)](r[s(1371)+"et"],e[s(1544)](r.byteLength,r.byteOffset));this[s(779)]&&this[s(779)][s(401)]({data:f,fail:p=>{let y=s;this[y(413)](d[y(247)],d[y(1224)](ft,d[y(247)],{message:this[y(1488)+y(1759)+y(1107)](p)}))}})}else _0x585857&&_0x4dbd2e[s(465)+"Listener"](QWlVhg[s(226)],()=>_0x53d942()),_0x31052b&&_0xc54b36[s(465)+"Listener"](s(743)+s(872),()=>_0x246113());else this._socket&&this[s(779)][s(401)]({data:r,fail:f=>{let p=s;this[p(413)](e[p(1550)],e[p(320)](ft,e[p(1550)],{message:this["_formatE"+p(1759)+p(1107)](f)}))}})}close(r,s){let d=t;e[d(1075)]!==e[d(1294)]?this[d(779)]&&this[d(779)][d(1601)]({code:r,reason:s}):(_0x52939f.set(_0x4d54b0,_0x316423),_0x48abdf[d(1706)](_0x2d3b3c,_0x280168))}["addEvent"+t(1041)](r,s){this.on(r,s)}[t(445)+t(452)+t(197)](r,s){let d=t,f={szFvT:function(p,y,S){return e[z(1610)](p,y,S)},oSpjA:e.JqjoE};if(e[d(397)](d(958),e[d(880)]))this.off(r,s);else{let p=this["_endpoin"+d(249)]?.["getCurre"+d(1327)+"nt"](),y=this[d(865)]["reconnec"+d(1564)+d(1647)](_0x1a1302[d(580)],_0x29303d[d(1313)]);this[d(919)+d(1557)+d(210)](f.szFvT(_0x14532e,f[d(300)],{code:1006,reason:_0x8cf20e.reason||d(744)+d(370)+"d, unkno"+d(861)+d(484)+d(276)+p,willReconnect:y})),y&&this[d(735)]();return}}get[t(493)+"te"](){let r=t;return this._socket[r(493)+"te"]}get[t(1390)+"pe"](){let r=t;if(e[r(1703)]===e[r(1299)])this[r(961)](_0x8dfe44,_0x53dca4);else return this._socket[r(1390)+"pe"]}set[t(1390)+"pe"](r){}get[t(988)](){let r=t;return this[r(779)][r(988)]}get[t(894)](){let r=t;return this[r(779)][r(894)]}get[t(277)+"ns"](){let r=t;return this[r(779)][r(277)+"ns"]}get[t(1505)+"Amount"](){return 0}}function am(a,r){let s=t,d={JixEL:function(f,p,y){return e[z(1593)](f,p,y)}};if(e[s(625)]("vpQxZ",e.rwXWM)){if(r)return new r(a[s(988)],a[s(894)]);if(ti||Cn)return new om(a[s(988)],a[s(894)],a.headers);if(e[s(634)](sr,ni)&&e[s(1344)](e[s(1140)],typeof WebSocket)&&WebSocket)return new WebSocket(a[s(988)],a.protocols)}else _0x5e0647(_0x3fac84,18),XUzqQP[s(371)](_0x68cf2f,_0x1fa993,_0x2a6c0c)}function cm(a){let r=t;return!!(a||ti&&wx[r(830)+"ocket"]||Cn&&tt[r(830)+"ocket"]||e[r(1304)](sr,ni)&&e.ZjXnW(r(498)+"d",typeof WebSocket)&&WebSocket)}function vl(a,r,s){let d=-1;async function f(p){let y=z,S={INjhe:e[y(1597)]};if(e[y(1296)](e[y(1587)],e[y(646)]))return e[y(326)](p,d)?Promise[y(419)](new Error(e[y(1436)])):(d=p,e.KJAXt(p,s.length)?Promise[y(1613)]():s[p][y(842)](a)(r,f[y(842)](null,e[y(874)](p,1))));{let g=S[y(1292)][y(813)]("|"),R=0;for(;;){switch(g[R++]){case"0":this[y(999)+"osed"]=!1;continue;case"1":this[y(1486)]=!0;continue;case"2":this[y(697)+"tManager"]?.["resetEnd"+y(700)+y(1461)]();continue;case"3":this._connect();continue;case"4":this["_pingLos"+y(1579)]?.[y(221)+"nter"]();continue}break}}}e.YuRMg(f,0)}function Sl(a){let r=t,s=0,d=0;for(let f=0;e.ZyeiJ(f,a[r(279)]);++f)d=a[r(1302)+"At"](f),e[r(820)](d,128)?s+=1:e[r(1019)](d,2048)?s+=2:e[r(935)](64512,d)===55296&&e.vFSKq(e[r(340)](64512,a.charCodeAt(e[r(1112)](f,1))),56320)?(++f,s+=4):s+=3;return s}function Il(a,r,s){let d=t;if(e[d(511)](e[d(1688)](s,r),1))return"";let f="";for(let p=r;p<s;){let y=a[p++];if(e.atCWg(y,127))f+=String[d(1183)+d(615)](y);else if(e.geZSP(y,192)&&e.ggycz(y,224))f+=String[d(1183)+d(615)](e[d(1267)](e[d(496)](31,y)<<6,e[d(437)](63,a[p++])));else if(e[d(698)](y,224)&&y<240)f+=String[d(1183)+"Code"](e[d(1383)](e[d(1267)](e.AVwAt(e[d(848)](15,y),12),e[d(1118)](e.DwaAL(63,a[p++]),6)),e.pLsfz(63,a[p++])));else if(e[d(819)](y,240)){let S=e[d(1446)](e[d(1736)](e[d(1714)](e[d(829)](e[d(1217)](e[d(1150)](7,y),18),e[d(1651)](63,a[p++])<<12),e[d(1657)](63,a[p++])<<6),63&a[p++]),65536);f+=String[d(1183)+d(615)](e.ZrbGo(55296,S>>10)),f+=String[d(1183)+d(615)](56320+e[d(1188)](1023,S))}}return f}function ka(a,r,s){let d=t,f=s,p,y;for(let S=0;e[d(987)](S,a[d(279)]);++S)if(e[d(1506)](e.XMrhC,d(1082)))if(p=a[d(1302)+"At"](S),p<128)r[s++]=p;else if(p<2048)r[s++]=e.MchJz(e.aLoia(p,6),192),r[s++]=e[d(338)](e[d(1651)](63,p),128);else if(e[d(1046)](e.XRCnK(64512,p),55296)&&e[d(870)](e[d(1061)](64512,y=a[d(1302)+"At"](e[d(518)](S,1))),56320)){let g=e[d(1085)].split("|"),R=0;for(;;){switch(g[R++]){case"0":r[s++]=e[d(1693)](e[d(864)](63,p),128);continue;case"1":r[s++]=e[d(849)](e.ZRZnm(p,6)&63,128);continue;case"2":r[s++]=e[d(1267)](e[d(544)](e[d(368)](p,12),63),128);continue;case"3":r[s++]=e[d(1510)](e[d(595)](p,18),240);continue;case"4":++S;continue;case"5":p=e[d(1169)](e[d(1246)](65536,e.GoDXN(1023,p)<<10),e.zXSvX(1023,y));continue}break}}else r[s++]=e[d(1386)](e[d(966)](p,12),224),r[s++]=e[d(1237)](e.BFVPG(p,6)&63,128),r[s++]=e[d(1176)](63,p)|128;else this[d(809)+"T"]||this[d(392)+"X"]?this[d(343)+d(1549)+"ange"]():this[d(606)+"er"]&&this._initGlobalEventListener();return e[d(1687)](s,f)}async function Al(a){let r=t;if(e[r(871)]==typeof a){let s=new Uint8Array(e[r(1501)](Sl,a));return e.OIaMG(ka,a,s,0),s}return e[r(1482)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[r(1353)],a[r(1371)+"et"],a.byteLength)}function dm(a){let r=t,s={ggOWN:function(d,f){return e[z(755)](d,f)},LZPpE:function(d,f){return e[z(1325)](d,f)},jmxhb:function(d,f){return e[z(806)](d,f)},kIWRI:function(d,f){return e[z(587)](d,f)},sSZXK:function(d,f){return e[z(453)](d,f)},BVtoL:function(d,f){return e[z(932)](d,f)},CfZkN:function(d,f){return e.WPVXR(d,f)}};try{if(e.KTKta(e.FCnHB,e[r(427)]))_0x47dda0=AqBvuG[r(980)](_0x44be4d,_0x34f63b),_0x59fee7|=AqBvuG[r(1276)](AqBvuG[r(1696)](127,_0x285021),21),AqBvuG[r(1696)](128,_0x11b024)&&(_0x509aaa=AqBvuG[r(1689)](_0x54bc1a,_0x40842f),_0x3982fa=AqBvuG[r(1167)](127,_0x34a6d6),AqBvuG.jmxhb(128,_0x51cf06)&&(_0x3cf957=AqBvuG[r(798)](_0x5bb803,_0x58f3ff),_0x511447|=AqBvuG.LZPpE(AqBvuG[r(291)](127,_0x3af920),7)));else return e[r(1344)](r(1539),typeof a)&&(e[r(1196)](a,ArrayBuffer)||a.buffer&&e[r(1196)](a[r(1353)],ArrayBuffer))||r(1539)!=typeof a?"":(JSON[r(240)](a),e.gElqh)}catch{return e[r(1089)](r(1539),typeof a)?e.NGoUL:""}}let lm=(a,r)=>{let s=t;switch(a){case e[s(545)]:case e.KhyYZ:return{["x-use-"+a]:1,"x-tt-env":r};default:return{}}};class um{constructor(r){let s=t,d={GCNYh:function(f,p){return e.BwNji(f,p)}};if(e.EfiXo(e[s(690)],e[s(1641)]))this[s(1202)+s(1662)]=r,this[s(1040)]=0;else{let f=this[s(1342)][s(1097)+s(641)](this[s(1373)]),p=_0x535efb.parse(d[s(1343)](f,"{}"));return p[_0xc17875]=void 0,this._qosDB[s(885)+s(641)](this[s(1373)],_0x169bff[s(965)+"y"](p))}}[t(1207)](){let r=t;this[r(1040)]++}[t(948)+t(1300)+"nt"](){let r=t;return e[r(1298)](this[r(1040)],this[r(1202)+r(1662)])}[t(221)+t(1427)](r=0){let s=t;this[s(1202)+s(1662)]=r,this[s(1040)]=0}}async function fm(a){let r=t,s={UaeCj:e[r(486)],CFieF:function(d,f){return e[r(1295)](d,f)},mydsa:e[r(785)],nFaTT:e[r(643)],DmeCP:e[r(313)],yKkHl:"&jscallb"+r(722)+r(1122)+"P"};return new Promise(d=>{let f=r;if(!sr)return s.CFieF(d,s[f(1186)]);try{let p=document[f(1477)+f(589)](s[f(712)]);window["frontier"+f(751)]=y=>{let S=f;document[S(1364)][S(237)+S(258)](p),window[S(222)+S(751)]=void 0,d(y&&y[S(590)]||s[S(1186)])},p[f(778)]=s[f(1745)],p.src=a[f(1490)](/^ws/,s[f(522)])+s[f(996)];try{document[f(1364)][f(687)+f(258)](p)}catch{document.body[f(237)+"ild"](p)}}catch{window[f(222)+f(751)]=void 0,d(s[f(1186)])}})}function dn(a,r,s){let d=t;return!!a?.[d(619)](f=>f[d(1441)]===r&&f.value===s)}function or(a,r){let s=t;return a?.[s(619)](d=>d[s(1441)]===r)?.[s(273)]}let Ta=null;async function hm(){let a=t;return Ta||(Ta=Promise.resolve()[a(957)](Ut[a(842)](Ut,a(220)))),Ta}class xm extends Aa{constructor(r,s){let d=t;super(),this._dbName=r,this[d(550)]=s,this[d(1342)]=void 0,this["_initPro"+d(1468)]=null}async[t(708)](){await this[t(551)]()}async _init(){let r=t,s={IDLtD:function(d){return e.fkhSN(d)},bNqZl:function(d,f,p,y){return e[z(1431)](d,f,p,y)},FyKsM:function(d,f){return d+f},IopSl:function(d,f){return e[z(754)](d,f)},SqcrF:function(d,f){return e[z(1717)](d,f)},QzpcV:function(d,f){return e[z(1283)](d,f)},QRycJ:function(d,f){return e.mtiJS(d,f)},pheeV:function(d,f){return d!==f},cLAYa:function(d,f){return d&f},Dhzjn:function(d,f){return e[z(1383)](d,f)},szUms:function(d,f){return e[z(1399)](d,f)},ztUMi:function(d,f){return d|f},aDvlM:function(d,f){return e.EWjbd(d,f)},TNoNL:function(d,f){return d<<f},dzWAW:function(d,f){return e.UfLhC(d,f)},RAKUn:function(d,f){return d>f},xSmRm:function(d,f,p){return e[z(320)](d,f,p)},ggNBS:function(d,f){return e[z(843)](d,f)},vrGEP:function(d,f){return e[z(1170)](d,f)}};if(e[r(878)](e[r(1728)],e[r(1728)])){if(this[r(1342)])return;if(this[r(227)+r(1468)])return this[r(227)+r(1468)];try{let d=this[r(236)],f=this[r(550)];this[r(227)+r(1468)]=(async()=>{let p=r,{openDB:y}=await s[p(1008)](hm);this[p(1342)]=await s[p(1699)](y,p(222)+"_"+d,1,{upgrade(S){S.createObjectStore(d,{keyPath:f})}})})(),await this[r(227)+"mise"]}catch(d){console[r(759)](d)}finally{this[r(227)+r(1468)]=null}}else _0x2cd6b3=_0x12d932[cEFjPK[r(312)](cEFjPK[r(1080)](_0x3cfb5d,_0x50602e),1)],_0x2f8fd0=_0x303b3e[cEFjPK.SqcrF(_0x163566+_0x22c2a8,2)],_0x3d44a9=_0x58c68c[cEFjPK[r(1596)](cEFjPK.QRycJ(_0x3f15f3,_0xefa433),3)],cEFjPK[r(1114)](cEFjPK.cLAYa(cEFjPK.Dhzjn(_0x47fa15|cEFjPK[r(507)](_0x4ca757,8),_0x4450ca<<16),12632256),8421504)?_0x523dbd+=_0x2375cf:(_0xf3d443=cEFjPK[r(232)](cEFjPK[r(585)](cEFjPK[r(507)](cEFjPK.aDvlM(7,_0x1c507e),18),cEFjPK[r(844)](cEFjPK.cLAYa(63,_0x31c1b2),12)),cEFjPK.cLAYa(63,_0x1838cc)<<6)|cEFjPK[r(386)](63,_0x8a48c5),_0x41b860<65536||cEFjPK[r(600)](_0x1ac55f,1114111)?_0x1cfdc4+=_0x24b400:(_0x5cbfa5-=65536,_0x509c74+=cEFjPK[r(1065)](_0x56a9a3,cEFjPK[r(989)](_0x143db5,10)+55296,cEFjPK[r(319)](cEFjPK[r(361)](1023,_0x5948ad),56320)),_0x55d34a+=3))}async get(r){let s=t;if(e[s(1391)](e[s(1256)],e[s(1256)]))this[s(1178)+s(1579)]?.addCount(),this[s(413)](s(1154)+"e_timeout",e[s(1370)]),this[s(1178)+s(1579)]?.[s(948)+s(1300)+"nt"]()?this[s(1396)+s(1218)]():this[s(1426)]();else try{if(e[s(1391)](e[s(477)],e.kwuqn))return await this[s(551)](),this[s(1342)]?.[s(274)](this[s(236)],r);{let p=(s(950)+"4").split("|"),y=0;for(;;){switch(p[y++]){case"0":var d=_0x4d59ea[_0x39c8a4]={exports:{}};continue;case"1":_0x1ff6dc[_0x530d80](d,d[s(837)],_0x5aebb8);continue;case"2":if(mYkanF[s(1357)](void 0,f))return f[s(837)];continue;case"3":var f=_0x46cbed[_0x349a04];continue;case"4":return d[s(837)]}break}}}catch(p){console[s(759)](p)}}async set(r,s){let d=t;return await this[d(551)](),this[d(1342)]?.[d(503)](this._dbName,r)}async[t(259)](r){let s=t;try{return await this._init(),this[s(1342)]?.delete(this[s(236)],r)}catch(d){console.log(d)}}async clear(){let r=t,s={dMPWn:e[r(883)],ijltu:function(d){return e.fkhSN(d)}};try{return await this[r(551)](),this[r(1342)]?.[r(1177)](this[r(236)])}catch(d){e.xBztZ===e[r(962)]?(this[r(1658)](s[r(1428)],_0x170d00[r(555)]),s[r(729)](_0x354745)):console[r(759)](d)}}async[t(1054)](){let r=t;return await this[r(551)](),this[r(1342)]?.[r(430)+"ys"](this[r(236)])}async[t(1127)](){let r=t,s={PeAnv:function(d,f){return e[z(622)](d,f)},EExGP:r(1020),KZBHI:e.UkWnf};if(e[r(1168)]===e[r(342)]){let d=_0x36461b[r(813)](/\./)[r(472)](y=>_0x53ddcd(y)),f=[];return f[0]=_0x254d30(d[0]+d[1]),f[1]=_0x23605f(sXJZeU[r(504)](d[2],d[3])),[sXJZeU[r(1346)],sXJZeU[r(1346)],r(1020),sXJZeU[r(1346)],sXJZeU.EExGP,sXJZeU[r(1403)],f[0],f[1]][r(1642)]("")}else return await this[r(551)](),this[r(1342)]?.getAll(this[r(236)])}async[t(1091)](){let r=t;try{this[r(1342)]?.[r(1601)](),this._qosDB=void 0}catch(s){console[r(759)](s)}}get[t(424)](){let r=t;try{return!!this._qosDB}catch(s){return console[r(759)](s),!1}}}class pm{constructor(r,s){let d=t;this._DBName=r,this[d(780)]=s,this[d(1342)]=localStorage}async[t(708)](){}get[t(1373)](){let r=t;return r(222)+"_"+this[r(857)]}async get(r){let s=t,d=this._qosDB.getItem(this[s(1373)]);return JSON.parse(e[s(634)](d,"{}"))[r]}async[t(1706)](r,s){let d=t,f=this._qosDB[d(1253)](this[d(1373)]),p=JSON[d(240)](f||"{}");return p[s||r[this._pathKey]]=r,this[d(1342)][d(614)](this[d(1373)],JSON[d(965)+"y"](p)),s||r[this[d(780)]]}async[t(259)](r){let s=t,d=this[s(1342)][s(1253)](this[s(1373)]),f=JSON[s(240)](e[s(351)](d,"{}"));return f[r]=void 0,this[s(1342)][s(614)](this[s(1373)],JSON[s(965)+"y"](f))}async[t(1177)](){let r=t;return this._qosDB[r(1177)]()}async[t(1054)](){let r=t,s=this[r(1342)][r(1253)](this[r(1373)]),d=JSON.parse(s||"{}");return Object[r(1054)](d)}async[t(1127)](){let r=t,s=this[r(1342)][r(1253)](this._prefix),d=JSON.parse(e[r(1066)](s,"{}"));return Object.values(d)}closeDB(){return Promise[t(1613)]()}get[t(424)](){return!!this[t(1342)]}}class mm{constructor(r,s){let d=t;this[d(857)]=r,this._pathKey=s,this[d(1342)]=Cn?tt:ti?wx:null}async[t(708)](){}get _prefix(){return t(222)+"_"+this._DBName}async[t(274)](r){let s=t,d=this[s(1342)][s(1097)+s(641)](this[s(1373)]);return JSON[s(240)](e[s(351)](d,"{}"))[r]}async[t(1706)](r,s){let d=t,f=this[d(1342)]["getStora"+d(641)](this[d(1373)]),p=JSON[d(240)](e[d(726)](f,"{}"));return p[s||r[this[d(780)]]]=r,this[d(1342)][d(885)+d(641)](this[d(1373)],JSON[d(965)+"y"](p)),s||r[this._pathKey]}async[t(259)](r){let s=t,d=this._qosDB[s(1097)+s(641)](this[s(1373)]),f=JSON[s(240)](e[s(1066)](d,"{}"));return f[r]=void 0,this[s(1342)][s(885)+"geSync"](this[s(1373)],JSON[s(965)+"y"](f))}async clear(){let r=t;return this[r(1342)]["clearSto"+r(881)]()}async[t(1054)](){let r=t,s=this[r(1342)][r(1097)+r(654)+"nc"](this._prefix),d=JSON.parse(s||"{}");return Object.keys(d)}async[t(1127)](){let r=t,s=this[r(1342)][r(1097)+r(654)+"nc"](this._prefix),d=JSON[r(240)](e.OdkIF(s,"{}"));return Object[r(349)](d)}closeDB(){return Promise[t(1613)]()}get[t(424)](){return!!this[t(1342)]}}function kl(a,r){let s=t;if(e.mlOpx(Cn,Cn))return new mm(a,r);if(e[s(1066)](sr,ni)&&e[s(898)](e.UehPf,typeof indexedDB))return new xm(a,r);if(e.Ckben(sr,ni)&&e.UehPf!=typeof localStorage)return new pm(a,r);throw new Error(s(1608)+s(926)+"d")}class gm{constructor(){let r=t;this._intervalTimeoutId=null,this[r(845)+"l"]=36e5,this._qosDB=e[r(1369)](kl,e[r(530)],e[r(608)])}async[t(845)+t(594)](){let r=t,s={ZzkRh:function(d,f){return e.UCGfn(d,f)},ICWgh:function(d,f){return e[z(1566)](d,f)},MxSKg:function(d,f){return e[z(1277)](d,f)},kaSAN:function(d,f){return e.iIUIQ(d,f)},gEues:function(d,f){return e[z(1076)](d,f)},TaBwk:function(d,f){return e[z(1657)](d,f)}};e.psevs(r(1155),e[r(1166)])?(e[r(824)](_0x4376d7,_0x1adbe6,10),e[r(1447)](_0x529f0c,_0x21014a,_0x568839)):(clearInterval(this["_interva"+r(1578)+"Id"]),this["_interva"+r(1578)+"Id"]=setInterval(()=>{let d=r;if(e.KJAXt(d(1674),e[d(1524)]))this[d(1705)+d(1392)]();else{let f=(wILQYl[d(466)](wILQYl[d(466)]((7&_0x1f9433)<<18,wILQYl[d(497)](63&_0x13a9d0[_0x3d23e5++],12)),wILQYl[d(497)](63&_0x186587[_0x36219f++],6))|wILQYl[d(702)](63,_0x5cd303[_0x1c386b++]))-65536;_0x4f8a6f+=_0x2955c7[d(1183)+d(615)](wILQYl[d(282)](55296,wILQYl[d(914)](f,10))),_0x43d1ff+=_0x562f6e[d(1183)+d(615)](wILQYl.kaSAN(56320,wILQYl.TaBwk(1023,f)))}},this[r(845)+"l"]))}async[t(708)](){let r=t;e.sskRX(r(1094),e[r(1584)])?await this[r(1342)][r(708)]().then(()=>{let s=r;this[s(845)+s(594)]()}):(_0x5d6337[_0x290bbc++]=_0x5c0808>>6|192,_0x1dd236[_0x38a893++]=e[r(1267)](63&_0x306de7,128))}async flushExpired(){let r=t;(await this[r(1342)]?.[r(1127)]()||[])[r(1063)](({timestamp:f})=>f<Date[r(786)]())[r(577)](f=>{let p=r;this[p(1342)]?.[p(259)](f.message_id)})}async[t(259)](r){let s=t;return this[s(1342)]?.[s(259)](r)}async[t(1706)](r,s){let d=t,f={xCXjZ:function(p){return e[z(1185)](p)},lPMiP:function(p,y,S){return e[z(840)](p,y,S)},cFwND:function(p,y){return p(y)}};if(e.kvbos!==e[d(794)])return this._qosDB?.[d(1706)]({message_id:r,timestamp:s});{let p=NywdKt.xCXjZ(_0x5ab418);return NywdKt[d(495)](_0x1f15ab,_0x1c1654,p),NywdKt[d(1108)](_0x5282d5,p)}}async get(r){return this[t(1342)]?.get(r)}async[t(1091)](){let r=t;e[r(354)](clearInterval,this["_interva"+r(1578)+"Id"]),await this[r(1342)]?.[r(1091)]()}get[t(424)](){let r=t;return this[r(1342)]?.[r(424)]}}function Ra(a){let r=t,s=!!this._options[r(960)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let d=e[r(661)](dn,a[r(555)][r(1425)],r(244)+r(940),"2"),f=d&&e[r(1677)](dn,a[r(555)][r(1425)],e[r(1512)],"1"),p=d&&e[r(1431)](dn,a.message[r(1425)],e[r(635)],"1"),y=p?e[r(1697)](or,a[r(555)].headers,e.vIhCq)?.[r(813)](",")[r(1063)](Boolean)||[]:[];return{enabled:s,isQoSMessage:d,isQoSAck:f,isAckCleanupMessage:p,ackMsgIds:y}}async function Tl(){let a=t;return this[a(1241)+a(834)]||(this[a(1241)+a(834)]=new gm),this["_QoSMana"+a(834)][a(424)]||await this[a(1241)+a(834)].openDB(),this[a(1241)+a(834)]}async function wm(a,r){let s=t,{enableAutoAck:d}=this._options,f=e[s(661)](dn,a[s(555)][s(1425)],e[s(841)],"1"),p=e[s(760)](dn,a.message[s(1425)],e[s(1179)],"1"),y=Ra[s(976)](this,a);if(e[s(827)](d,f)){let{SeqID:S,LogID:g,service:R,LogIDNew:C,method:N}=a[s(555)];this[s(341)]({SeqID:S,LogID:g,LogIDNew:C,service:R,method:N,headers:[{key:e[s(1179)],value:"1"},{key:s(721),value:e[s(1095)](C,"")},{key:e[s(235)],value:"0"}]})}p&&!y[s(285)]&&this[s(919)+"hAckMess"+s(270)](a),e[s(1649)](r)}async function _m(a,r){let s=t;this[s(1658)](s(953),a.message),r()}async function ym(a,r){let s=t,d=on(await e[s(908)](Al,a.data));try{if(e.bzPuV(d[s(1213)],Uint8Array)){let f=e.rowLw(this[s(865)][s(1172)+s(1088)],Object)?{force:!!this[s(865)][s(1172)+"ncoding"][s(776)],encoding:this[s(865)][s(1172)+"ncoding"][s(260)]?this[s(865)][s(1172)+"ncoding"][s(260)][s(1490)](/\s/g,"")[s(1310)+s(329)]():""}:{force:!1,encoding:this[s(865)][s(1172)+s(1088)]?this[s(865)][s(1172)+s(1088)][s(1490)](/\s/g,"")[s(1310)+s(329)]():""},p=d["payloadE"+s(1088)]?d[s(1172)+s(1088)].replace(/\s/g,"")[s(1310)+"ase"]():"",y=e[s(1482)](this._options["payloadT"+s(986)],Object)?{force:!!this[s(865)][s(745)+"ype"][s(776)],type:this[s(865)][s(745)+s(986)][s(778)]?this[s(865)][s(745)+s(986)].type[s(1490)](/\s/g,"")["toLowerC"+s(329)]():""}:{force:!1,type:this[s(865)][s(745)+s(986)]?this[s(865)][s(745)+s(986)][s(1490)](/\s/g,"")[s(1310)+s(329)]():""},S=d[s(745)+s(986)]?d["payloadT"+s(986)][s(1490)](/\s/g,"")[s(1310)+s(329)]():"",g=y[s(776)]?y.type:S||y.type,R=f.force?f[s(260)]:p||f[s(260)],C=[e.NGoUL,e[s(979)],e[s(648)],e.TmqAA],N=[e.kIzoP,e[s(1083)]];this._options[s(973)+s(981)+"extPayload"]&&C[s(1128)](g)&&(!R||N[s(1128)](R))?d[s(474)+s(682)]=e[s(1487)](Il,d[s(1213)],0,d[s(1213)].byteLength):d[s(474)+"oad"]=""}else d["textPayl"+s(682)]=""}catch(f){d[s(474)+"oad"]="",console.log(f)}a[s(555)]=d,e[s(1586)](r)}function bm(a,r,s){let d=t,f={vBoUH:function(R,C){return e[z(1432)](R,C)},yUUcH:function(R,C){return e[z(265)](R,C)},QRoer:function(R,C){return e.JCQOF(R,C)},XCjQj:function(R,C){return e[z(457)](R,C)},Epemn:function(R,C){return e.ZiWGg(R,C)},HuIWT:function(R,C){return e[z(787)](R,C)}},p=e.Pugao(s,8192),y=e[d(481)](p,1),S=null,g=p;return function(R){let C=d;if(R<1||R>y)return f[C(990)](a,R);f[C(1473)](f[C(1413)](g,R),p)&&(S=f[C(1433)](a,p),g=0);let N=r.call(S,g,g+=R);return f[C(1660)](7,g)&&(g=f[C(540)](7|g,1)),N}}let Em=4294967295;function vm(a,r,s){let d=t;return e[d(1525)](RangeError,e[d(1670)](e[d(874)](e[d(1169)](e[d(1359)](d(1594)+d(1129)+d(230),a),e[d(1646)]),e[d(1095)](r,1))+e[d(1015)],s))}function Sm(a,r,s){let d=t;if(e[d(1418)](e[d(939)],e[d(939)])){if(e.LkhVe(s,Em))throw new Error(e[d(1116)]);let f=3;for(;f>=0;){let p=255&s;e[d(1487)](Ca,p,a,e[d(1081)](r,f)),s>>>=8,f--}return e.vfaOQ(r,4)}else e[d(223)](_0x2f8d03,this,_0x470618,[_0x3e521d,_0x365bc3,_0x399981,_0x1f4a08,_0x1e065e,_0x57081e])}function Im(a,r){let s=t,d=0,f=r,p=e[s(1670)](r,4);for(;e.CWaiK(f,p);){let{value:y,offset:S}=Pa(a,f);f=S,d=e[s(390)](e[s(1251)](d,8),0),d+=y}return{value:d,offset:p}}function Am(a,r,s){let d=t,f=e.jHSfF.split("|"),p=0;for(;;){switch(f[p++]){case"0":if(e.wPFPR(a[d(279)],40))return e[d(1077)](ka(a,r,s),s);continue;case"1":if(!a)return s;continue;case"2":if(r.utf8Write)return e[d(1246)](r[d(1509)+"e"](a,s),s);continue;case"3":return e[d(510)](e.OIaMG(ka,a,r,s),s);case"4":if(r[d(1685)])return e.faNlR(r[d(1685)](a,s),s);continue}break}}function km(a,r){let s=t,d=new pe(e[s(829)](e[s(810)](a[e[s(1169)](r,4)],24)|a[e.bDHNs(r,5)]<<16|e[s(738)](a[r+6],8),a[e[s(1285)](r,7)]),e[s(325)](e[s(303)](e[s(620)](a[r+0],24),e.RgwFv(a[e[s(1527)](r,1)],16)),e[s(1263)](a[r+2],8))|a[e.CpISS(r,3)],!0);return r+=8,{value:d,offset:e[s(1261)](r,8)}}function Tm(a,r,s){let d=t,f=a[d(569)],p=a[d(707)];return r[s]=e[d(1014)](p,24),r[s+1]=e.OplzG(e.tBDlS(p,16),255),r[e[d(1546)](s,2)]=e[d(1669)](e[d(793)](p,8),255),r[e[d(1098)](s,3)]=e[d(1176)](255,p),r[s+4]=e[d(1558)](f,24),r[e[d(1169)](s,5)]=e[d(1321)](e[d(271)](f,16),255),r[e.knsCc(s,6)]=f>>>8&255,r[s+7]=e[d(1291)](255,f),s+=8,s}function Pa(a,r){let s=t;return a.readUInt8?{value:a[s(774)+"8"](r),offset:e[s(754)](r,1)}:{value:e[s(1389)](255,a[r]),offset:e[s(1077)](r,1)}}function Ca(a,r,s){let d=t;return r.writeUint8?r[d(298)+"t8"](a,s):r[s]=e[d(1150)](255,a),e[d(1565)](s,1)}let Rm=function(a){return new Uint8Array(a)},Pm=e.aJBLn(t(498)+"d",typeof Buffer)?Buffer[t(1028)+t(1139)]:e[t(1032)](bm,Rm,Uint8Array[t(650)+"e"].subarray),Cm=16,Da=32;function Dm(a){let r=t;if(e[r(1045)](e[r(969)],e[r(969)])){let s=0,d={};for(let f=0;e[r(987)](f,a[r(279)]);f++)d[a[f][r(379)+r(391)]]=e[r(1336)](Sl,a[f][r(379)+"ame"]),s+=e.KrFfD(14,d[a[f][r(379)+r(391)]]);return[s,d]}else this[r(1498)+"ndex"]=0,this[r(930)+r(1226)+"riesCount"]=0}function Rl(a,r,s){let d=t,f={msTlM:function(R,C){return e[z(1328)](R,C)},fbdLF:function(R,C){return e[z(1045)](R,C)},uEQtU:e[d(1618)],itvUQ:e.DTEZK,waMqV:function(R,C,N,q){return R(C,N,q)},qrrvo:d(1018),VtqFn:e.VjSof,bnqlU:function(R,C,N,q){return e[d(1677)](R,C,N,q)},wBzkt:"service-"+d(216),oEzie:d(216),iCJKR:function(R,C,N,q){return e.bwyLv(R,C,N,q)},YhfZl:d(485)},[p,y]=Dm(a),S=Pm(p),g=0;return a[d(577)](R=>{let C=d,N={XyytC:function(q,B){return f[z(1113)](q,B)}};if(f[C(538)](C(1366),f.uEQtU))console[C(759)](f.itvUQ,R,R[C(574)]),g=f[C(1106)](Ca,0,S,g),console.log(f[C(1385)],g),g=Sm(S,g,R[C(574)]||0),console[C(759)](f.VtqFn,g),g=f[C(791)](Ca,y[R[C(379)+C(391)]],S,g),console[C(759)](f[C(1290)],g),g=f[C(791)](Am,R[C(379)+C(391)],S,g),console[C(759)](f[C(611)],g),g=f[C(1115)](Tm,pe[C(324)+"er"](R[C(1491)]||r),S,g),console[C(759)](f[C(488)],g);else{let q=this._qosDB.getItem(this[C(1373)]),B=_0x51532c[C(240)](fzKBpg[C(1599)](q,"{}"));return B[_0x2058cc||_0x22ca29[this[C(780)]]]=_0x38392d,this[C(1342)][C(614)](this[C(1373)],_0x171b2d.stringify(B)),_0x1c67a7||_0x33aeaa[this._pathKey]}}),{frameType:Da,headers:[{key:d(886)+"ile_name",value:s}],payload:S}}function Om(a){let r=t,s=0,d=[];for(;e[r(821)](s,a[r(1195)+"th"]);){let{offset:f}=Pa(a,s);s=f;let p={cursor_name:"",cursor:0,service:0},{value:y,offset:S}=e.pTgDl(Im,a,s);p.service=y,s=S;let{value:g,offset:R}=Pa(a,s);s=R,p[r(379)+r(391)]=e[r(1677)](Il,a,s,s+g),s+=g;let{value:C,offset:N}=e[r(1518)](km,a,s);p.cursor=C[r(1078)](),s=N,d.push(p)}return d}function Lm(){let a=t;return e[a(998)](e.WLRkS,a(1235))?_0x20e64f||(_0x9a7766=[_0xb85b66.prototype[a(393)],_0x2390a4[a(650)+"e"][a(951)],_0x3a47d7[a(650)+"e"][a(951)+"PrimaryKey"]]):{frameType:Da,headers:[{key:e[a(1005)],value:e[a(917)]}],payload:void 0}}class Nm{constructor(r,s,d){let f=t;this[f(1361)+f(375)]=r,this[f(1480)+"ileName"]=s,this[f(469)+"Strategy"]=d,this[f(1342)]=kl(this[f(1361)+f(375)],e[f(1435)])}async[t(708)](){await this._qosDB.openDB()}async[t(970)+"rs"](){let r=t;if(!this[r(1342)].isReady)return;let s=this[r(469)+r(1537)],d=await this[r(1342)][r(1127)]();switch(console[r(759)](e[r(1341)],d),s){case"ALL":return d&&d[r(279)]?e[r(1583)](Rl,d,0,this[r(1480)+"ileName"]):void 0;case r(1079):return;case e[r(542)]:return d&&d[r(279)]?e.Ojyix(Rl,d,0,this[r(1480)+"ileName"]):e[r(521)](Lm)}}async[t(1706)](r,s,d){let f=t;return console[f(759)](e[f(330)],r,s,d),this[f(1342)][f(1706)]({cursor_name:r,cursor:s,service:d})}async[t(546)+"rs"](r){let s=t;if(e[s(467)]("BFtww",s(1289)))return _0x4d9a2c?.[s(619)](d=>d[s(1441)]===_0x3afe7e)?.value;{let d=e.uUSSr(Om,r);for(let f of d)if(e.joNlz(e[s(314)],"AGHTO"))console[s(759)](e[s(1248)],d),await this[s(1342)][s(1706)](f);else return this[s(1342)]?.[s(274)](_0x36eb02)}}async[t(274)](r){let s=t;return(await this[s(1342)][s(274)](r))?.[s(1491)]}async[t(1091)](){let r=t;await this[r(1342)][r(1091)]()}[t(1243)+t(1384)+t(337)](r){let s=t;this[s(1480)+s(617)]=r}get isReady(){let r=t;return this[r(1342)][r(424)]}}let Mm=e[t(446)];async function Pl(a){let r=t;if(!this._options.enableQoS)return null;let{aID:s,fpID:d,messageStrategy:f}=this._options,p=e[r(726)](a,Mm);try{if(this["_cursorM"+r(556)]){if(r(1423)!==e[r(591)])return this[r(1342)][r(424)];a&&this._cursorManager["updateCu"+r(1384)+r(337)](a)}else this[r(836)+r(556)]=new Nm(d+"_"+s+"_"+p,p,f);return this[r(836)+r(556)][r(424)]||await this[r(836)+r(556)][r(708)](),this[r(836)+"anager"]}catch{return null}}async function Bm(a,r){let s=t,d={tsIkb:function(B,M){return e[z(811)](B,M)},FsRhf:function(B,M){return e.shoGQ(B,M)},jbiFi:function(B,M){return e[z(1291)](B,M)},DosKQ:function(B,M){return e.hiqRD(B,M)},wLdnd:function(B,M){return e[z(1152)](B,M)},UTGAa:function(B,M){return e.knsCc(B,M)},sOtLr:function(B,M){return e.TQvnf(B,M)},QkJSm:function(B,M){return e[z(1265)](B,M)},jNiZX:function(B,M){return e[z(301)](B,M)},lTqBx:function(B,M){return e[z(868)](B,M)},lNbun:function(B,M){return B<M},xwxsH:function(B,M,oe){return e[z(224)](B,M,oe)},wIGjz:function(B,M,oe,ze){return e[z(1402)](B,M,oe,ze)}},f=dn(a[s(555)][s(1425)],e.XYzpz,"-1"),p=e.jUwpC(dn,a.message[s(1425)],e[s(1179)],"1"),y=e.iPlyi(or,a[s(555)][s(1425)],e[s(1184)]),S=e[s(1458)](Number,e.Omlwc(or,a[s(555)].headers,e[s(1132)]))||0,g=Ra[s(976)](this,a),R=dn(a[s(555)].headers,e[s(623)],"2"),C=e.FeOYr(or,a[s(555)].headers,e[s(1529)]),N=e.inOWu(Number,or(a[s(555)][s(1425)],e[s(1100)]));if(g[s(285)])return e[s(1349)](r);let q=g[s(306)+s(1680)]?await Tl[s(976)](this):null;if(e.eEcwP(a[s(555)][s(574)],0)&&p&&!f||e.LkhVe(a[s(555)].service,0)){if(y&&g[s(306)+s(1680)]&&q)if(e[s(941)](e[s(339)],s(576))){let B=_0x1c410f[s(569)],M=_0x2a1c5e.high;return _0x104207[_0x5a707c]=IiLpwI[s(537)](M,24),_0x27eb88[IiLpwI[s(1035)](_0x52b9f4,1)]=IiLpwI[s(725)](IiLpwI.tsIkb(M,16),255),_0x4eceac[_0x216c69+2]=IiLpwI[s(554)](M>>>8,255),_0x3ce6ff[IiLpwI[s(1162)](_0xa2d6ba,3)]=IiLpwI[s(725)](255,M),_0x52306a[IiLpwI[s(531)](_0x2c9113,4)]=IiLpwI[s(537)](B,24),_0x234f64[_0x83c03f+5]=IiLpwI.sOtLr(IiLpwI.tsIkb(B,16),255),_0x5ba099[IiLpwI[s(952)](_0x45db2f,6)]=IiLpwI[s(1559)](IiLpwI[s(713)](B,8),255),_0x743ce3[IiLpwI.QkJSm(_0x3c14b9,7)]=IiLpwI[s(818)](255,B),_0x1e64cf+=8,_0x24b3b5}else{if(!!!await q[s(274)](y))if(e.jhspX(s(1573),s(1573))){let M=0,oe=[];for(;IiLpwI[s(1448)](M,_0x6d7068.byteLength);){let{offset:ze}=_0x2d71b2(_0x454a6f,M);M=ze;let Ye={cursor_name:"",cursor:0,service:0},{value:ms,offset:Oa}=IiLpwI[s(1060)](_0x2356aa,_0x57c2ea,M);Ye[s(574)]=ms,M=Oa;let{value:gs,offset:ri}=IiLpwI[s(1060)](_0x6f7643,_0x1a7631,M);M=ri,Ye[s(379)+s(391)]=IiLpwI[s(758)](_0x5ac5d8,_0x21c03e,M,M+gs),M+=gs;let{value:La,offset:ii}=IiLpwI.xwxsH(_0x290029,_0x2a324c,M);Ye[s(1491)]=La[s(1078)](),M=ii,oe[s(1730)](Ye)}return oe}else this["_dispatc"+s(1206)+s(717)](a),await q[s(1706)](y,e[s(1191)](Date.now(),S));return e[s(1732)](r)}if(R){let B=await Pl[s(976)](this);if(!B)return this["_dispatchMessage"+s(717)](a),e[s(1586)](r);let M=await B.get(C)??-1;if(e[s(299)](M,N))if(e[s(1323)]===e[s(1323)])this[s(919)+s(1206)+s(717)](a),B[s(1706)](C,N,a.message[s(574)]);else return this[s(1342)]?.[s(424)];else throw new Error(s(808)+s(1628)+s(703)+N+(s(1351)+s(231)+s(1228)+"r ")+M);return e.fkhSN(r)}return this[s(919)+s(1206)+"Event"](a),e[s(632)](r)}}async function Fm(a,r){let s=t,d=Ra[s(976)](this,a);if(!d["isQoSMes"+s(1680)])return r();let f=await Tl[s(976)](this);if(d["isAckCle"+s(954)+"age"]&&d[s(406)+"s"][s(279)])for(let p of d.ackMsgIds)await f[s(259)](p);e[s(1555)](r)}async function zm(a,r){let s=t,d={ruJsy:function(f){return e.fkhSN(f)}};if(e[s(565)](e.zmArg,e[s(1600)])){let f=this["_endpoin"+s(249)]?.[s(527)+s(1327)+"nt"]();this[s(1658)](s(730)+f),d[s(1724)](_0x482ec8)}else{let f=a[s(555)].frameType===Cm,p=e[s(1051)](a[s(555)][s(536)+"e"],Da);if(!f&&!p)return e[s(1185)](r);let y=e[s(500)](or,a.message.headers,e[s(1005)]);if(!y)return e[s(822)](r);let S=await Pl.call(this,y);if(!S)return e.fnRkZ(r);if(f){let g=await S[s(970)+"rs"](),R={frameType:g?.[s(536)+"e"],SeqID:pe.fromNumber(this[s(1363)]++),LogID:pe[s(324)+"er"](this[s(865)][s(1145)+s(1494)]()),service:9e3,method:5,headers:g?.[s(1425)],payload:g?.[s(1213)]},C=e[s(1119)](v,R);this[s(1247)]&&this._ws[s(493)+"te"]&&this._ws[s(401)](C)}if(p){let g=a[s(555)][s(1213)];g&&S[s(546)+"rs"](g)}}}let Um=async function(a,r){this._isInit=!1,clearTimeout(this._connectionTimeoutId),r()},Gm=async function(a,r){let s=t,d={HBQfY:s(1601),wiriO:function(f,p,y){return e[s(470)](f,p,y)}};if(e.vFSKq(e[s(765)],e[s(514)]))this._isMiniTT?_0x2832c2[s(610)+s(714)+s(872)](({isConnected:f})=>{let p=s;this[p(892)+p(1278)+p(692)]=f,f?this[p(812)+p(490)]():this[p(812)+p(1401)]()}):this._isMiniWX&&_0x3940df[s(610)+s(714)+"hange"](({isConnected:f})=>{let p=s;this[p(892)+"igatorOn"+p(692)]=f,f?this[p(812)+p(490)]():this["_handleO"+p(1401)]()});else{if(!this[s(1247)]||this._ws.readyState!==this[s(1528)])return e[s(1732)](r);let{pingInterval:f}=this._options;this["_endpoin"+s(249)]?.[s(1479)+"pointCon"+s(1461)]();for(let y=0;e[s(773)](y,this[s(469)+s(1056)][s(279)]);y++){let S=this[s(469)+s(1056)][y];if(e.GohvH(this[s(1247)][s(493)+"te"],this[s(1528)])&&e[s(1485)](null,S))e.YsQTD!=="WXYvA"?this[s(413)](cyVyiF.HBQfY,cyVyiF[s(1007)](_0x2659e4,s(1601),{..._0x2ee7bf})):(this[s(1247)]&&this[s(1247)][s(401)](S),this[s(469)+s(1056)][y]=null);else break}this[s(469)+s(1056)]=this["_message"+s(1056)][s(1063)](y=>!!y),this[s(1667)+s(920)+"Id"]=e[s(492)](setTimeout,()=>this[s(1426)](),f),this[s(919)+s(365)+"nt"](a),this._isBrowser&&this._ws&&(this[s(1247)].binaryType=this[s(1551)+s(986)]);let p=this[s(697)+s(249)]?.["getCurre"+s(1327)+"nt"]();this._debug(s(730)+p+s(718)),r()}},Hm=async function(a,r){let s=t,d=this._endpointManager?.[s(527)+s(1327)+"nt"]();this[s(1658)]("open "+d),e.NQClG(r)};class qm extends Aa{constructor(r){let s=t,d={yuavu:function(f,p,y){return e[z(1682)](f,p,y)},lWRwj:function(f,p,y){return e[z(460)](f,p,y)},kbOhF:function(f,p){return e[z(1522)](f,p)},VcWqr:e.AVDro,fxBVJ:function(f,p){return e[z(852)](f,p)},OAVwJ:e[s(677)],gezQG:function(f,p,y){return e[s(1593)](f,p,y)},YKUdy:e[s(1550)],IVRwZ:function(f,p,y){return e.wEroU(f,p,y)},LIDAx:function(f,p,y){return e[s(896)](f,p,y)},BxZAR:function(f,p,y){return e.WrNnN(f,p,y)},odAVQ:function(f,p,y){return e.MkFWL(f,p,y)},LCCYF:"close",mWhEt:function(f,p){return e[s(1159)](f,p)},SVxBR:function(f,p,y){return e[s(492)](f,p,y)},NpLcS:function(f,p){return e[s(863)](f,p)}};if(e[s(1143)](e.YGoND,e[s(402)])){super(),this[s(892)+s(1278)+s(692)]=!0,this[s(606)+"er"]=sr,this._isNode=sm,this._isMiniTT=Cn,this[s(392)+"X"]=ti,this._isWorker=ni,this["_message"+s(1056)]=[],this[s(697)+s(249)]=null,this[s(999)+"osed"]=!1,this[s(1551)+"ype"]=e[s(1753)],this[s(735)+s(728)]=!1,this[s(735)+"ionTimeoutId"]=null,this["_reconne"+s(1514)+s(257)]=null,this[s(1667)+s(920)+"Id"]=null,this[s(1363)]=0,this._isInit=!1,this[s(741)]="",this[s(1241)+s(834)]=null,this[s(836)+s(556)]=null,this[s(1178)+"sCounter"]=null,this._protocols=e[s(959)],this.CLOSED=3,this[s(895)+"NG"]=0,this[s(1528)]=1,this[s(461)]=2,this[s(1684)]=S=>{let g=s,R={AkwKY:function(C,N,q){return d[z(667)](C,N,q)}};if(d[g(1214)](d[g(807)],d.VcWqr))try{vl(this,S,[Um,Gm,Hm])}catch(C){if(d[g(928)](g(478),d[g(256)]))return _0x17514c.bytes[uaMGeF[g(866)](_0x4e6901,_0xcd4e99,1)];{let N=d[g(1582)](ft,d.YKUdy,{message:C.message,code:cn[g(1030)+"OR"],error:C});this[g(919)+"hErrorEv"+g(210)](N)}}else{let C=xrAbLF[g(1504)](_0x9f452b,_0x189b44,_0x1134f4[g(279)]);_0x38caa7[g(583)][g(1706)](_0x4f63f4,C)}},this[s(1136)+"ge"]=async S=>{let g=s,{pingInterval:R,pingFrequency:C}=this[g(865)];if((e.jdJqF("hi",S[g(1103)])&&e[g(1520)]("always",C)||e[g(1151)]("auto",C))&&(this[g(964)+"ngTimer"](),this[g(413)](e.JSzgL,g(433)),this[g(1667)+"gTimeoutId"]=e.pTgDl(setTimeout,this[g(1426)][g(842)](this),R)),!e[g(475)]("hi",S[g(1103)]))try{vl(this,S,[ym,wm,Fm,zm,Bm,_m])}catch(N){let q=e[g(1729)](ft,e.SavKq,{message:N[g(555)],code:cn[g(1120)+g(400)],error:N});this[g(919)+"hErrorEv"+g(210)](q)}},this._onError=S=>{let g=s,R=this["_endpoin"+g(249)]?.["checkRea"+g(832)+"es"](),C=this["_endpoin"+g(249)]?.[g(527)+g(1327)+"nt"]();if(R&&!S[g(555)]){let N=g(753)+C+(g(532)+g(1626)+g(1340)+"ed");this[g(919)+"hErrorEv"+g(210)](d[g(761)](ft,g(403),{message:N,code:cn[g(1352)+"IES_ERROR"],error:S}));return}this[g(1247)]&&d[g(1214)](this[g(1247)][g(493)+"te"],this[g(1528)])&&this[g(680)+g(649)](),this["_dispatc"+g(563)+"ent"](d[g(1723)](ft,d[g(853)],{message:S.message,code:cn.NATIVE_ERROR,error:S}))},this[s(984)]=async S=>{let g=s;this["_clearTi"+g(1255)](),this[g(964)+g(671)](),this[g(1324)+g(1620)+"rs"](),this[g(1247)]=null,this[g(735)+g(728)]=!1;let R=this["_endpoin"+g(249)]?.[g(948)+g(832)+"es"]();if(!R&&this[g(268)+g(918)]()&&!this[g(999)+g(1740)]){let C=this[g(697)+g(249)]?.["getCurre"+g(1327)+"nt"](),N=this[g(865)]["reconnec"+g(1564)+g(1647)](S[g(580)],S[g(1313)]);this[g(919)+"hCloseEv"+g(210)](d.BxZAR(bt,g(1601),{code:1006,reason:S[g(1313)]||g(744)+g(370)+"d, unkno"+g(861)+g(484)+g(276)+C,willReconnect:N})),N&&this[g(735)]();return}if(d[g(928)](1e3,S.code)&&this["_readyCl"+g(1740)]){this["_dispatc"+g(1557)+g(210)](d[g(1663)](bt,d[g(420)],{code:1e3,reason:g(1331)})),this[g(697)+g(249)]?.[g(1479)+"pointCon"+g(1461)](),this[g(1178)+"sCounter"]?.[g(221)+g(1427)]();return}if(d[g(928)](1e3,S[g(580)])&&R){let C=this[g(697)+g(249)]?.[g(527)+g(1327)+"nt"](),N=S[g(1313)];N||(N=await d[g(771)](fm,this[g(741)])),N=g(744)+"ng failed, "+N+(g(967)+"me: ")+C+(g(332)+g(931)+"ached"),this[g(919)+g(1557)+g(210)](d.odAVQ(bt,d[g(420)],{code:S[g(580)],reason:N}));let q="connect "+C+(g(532)+g(1626)+g(1340)+"ed");this[g(919)+g(563)+g(210)](d[g(288)](ft,d[g(853)],{message:q,code:cn[g(1352)+g(800)+"R"]})),this["_endpoin"+g(249)]?.[g(1479)+"pointCon"+g(1461)](),this[g(1178)+"sCounter"]?.["resetCou"+g(1427)]();return}if(d.NpLcS(1e3,S.code)&&!S[g(1313)]){let C=this[g(697)+g(249)]?.[g(527)+g(1327)+"nt"]();this[g(919)+g(1557)+g(210)](d[g(876)](bt,d[g(420)],{code:S.code,reason:g(744)+"ng failed, unkno"+g(861)+g(484)+g(276)+C})),this[g(697)+g(249)]?.[g(1479)+"pointCon"+g(1461)](),this[g(1178)+g(1579)]?.[g(221)+g(1427)]();return}this["_dispatc"+g(1557)+g(210)](S),this[g(697)+g(249)]?.[g(1479)+g(700)+"fig"](),this[g(1178)+"sCounter"]?.[g(221)+"nter"]()},this[s(1513)]=null,this[s(239)]=null,this[s(736)+"e"]=null,this[s(789)]=null,this[s(1029)+s(1218)]=null,this.onReceiveAck=null,this[s(1123)+s(991)+"yReconnect"]=null,this[s(812)+s(490)]=this[s(812)+s(490)].bind(this),this[s(812)+s(1401)]=this["_handleO"+s(1401)][s(842)](this),this[s(1227)+s(955)]=this[s(1227)+s(955)][s(842)](this),this[s(1227)+s(1713)]=this[s(1227)+"ageShow"][s(842)](this),this[s(865)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1036)](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(737)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e.oDDds,env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:p}=r,y=Array[s(592)](f)?f:e[s(884)](e.TmqAA,typeof f)?[f]:[];if(!y||e[s(733)](0,y[s(279)]))throw new Error(e.TddeF);if(!cm(p))throw new Error("please p"+s(873)+"s params"+s(1084)+"ket cons"+s(418)+"is undef"+s(1033));Object.assign(this[s(865)],r),this[s(697)+s(249)]=new El(y,this[s(865)][s(877)+"es"]),this[s(1178)+"sCounter"]=new um(this[s(865)][s(618)+"Count"]),this[s(865)]["automati"+s(626)]&&(this._isInit=!0,this[s(735)]()),this._options[s(438)+"tworkCha"+s(505)]&&(this._isMiniTT||this[s(392)+"X"]?this["_onPageNetWorkCh"+s(846)]():this[s(606)+"er"]&&this["_initGlo"+s(1303)+"Listener"]())}else _0x321847.persisted&&(this["_navigat"+s(918)]()&&(!this[s(1247)]||e.HbaAr(this[s(1247)][s(493)+"te"],this[s(1528)])||e[s(1391)](this[s(1247)][s(493)+"te"],this[s(895)+"NG"]))&&this[s(812)+s(490)](),this[s(606)+"er"]&&_0xb706e2[s(465)+s(1041)](e[s(1500)],this[s(812)+s(490)]),this[s(606)+"er"]&&_0x27706e[s(465)+s(1041)](e.ZgyCS,this[s(812)+s(1401)]))}[t(812)+t(490)](){let r=t;if(e[r(559)](e.rwuue,e[r(479)])){if(this[r(865)][r(605)+r(1308)+r(739)]||this[r(999)+r(1740)])return;this[r(1396)+"econnect"]()}else _0x11c20f[r(1706)](_0xb5bdb2,_0x4c7148)}[t(812)+t(1401)](){let r=t;this[r(1614)+r(1650)+"t"]();let s=e[r(407)](Ia,e[r(1157)],{message:e.KovLe});this[r(1123)+r(991)+r(788)+"ct"]&&this["onStopImmediatel"+r(788)+"ct"](s)}[t(673)+t(1303)+t(1041)](){let r=t,s={MTuzL:function(d,f){return e[z(281)](d,f)}};if(e.WWYEH(e[r(719)],r(835))){let d=this[r(1342)][r(1097)+r(654)+"nc"](this[r(1373)]),f=_0x50d870.parse(RoKNIA[r(1576)](d,"{}"));return _0x2944a6[r(1054)](f)}else this._isBrowser&&window[r(465)+r(1041)](r(1507),this[r(812)+r(490)]),this[r(606)+"er"]&&window[r(465)+"Listener"](e.ZgyCS,this[r(812)+r(1401)]),this[r(606)+"er"]&&window[r(465)+"Listener"](e[r(922)],this[r(1227)+r(955)]),this[r(606)+"er"]&&window["addEvent"+r(1041)](e[r(414)],this[r(1227)+"ageShow"])}[t(1444)+"balEvent"+t(1041)](){let r=t;this[r(606)+"er"]&&window[r(445)+r(452)+"ner"](e[r(1500)],this[r(812)+r(490)]),this[r(606)+"er"]&&window[r(445)+r(452)+r(197)](e.ZgyCS,this[r(812)+r(1401)]),this._isBrowser&&window[r(445)+r(452)+r(197)](e.VlyDS,this[r(1227)+r(955)]),this._isBrowser&&window["removeEventListe"+r(197)](e[r(414)],this[r(1227)+r(1713)])}["_handleP"+t(955)](r){let s=t,d={EKQnU:function(f,p){return e[z(1421)](f,p)},GtMpU:e.ffzNO,MZoxx:function(f,p){return e.EdWky(f,p)},oCIDY:function(f,p){return e[z(1482)](f,p)},bNVTl:function(f,p){return e.tfkcB(f,p)},SygGz:function(f,p,y){return e[z(869)](f,p,y)}};if(e[s(1506)](e[s(644)],e[s(644)]))return QpiLvV[s(704)](typeof _0x57245f,QpiLvV[s(1043)])?QpiLvV[s(1013)](_0x23559e,_0x131c96):(QpiLvV[s(749)](_0x1cf8fd,_0x5b2048)&&QpiLvV.bNVTl(_0x254bb0,_0x4b178c),QpiLvV[s(1275)](_0x343f89,_0x2cb325,_0x154ef0())?new _0x4f49f2(_0x3aabbd,_0x127102):_0x35a7fe);!r.persisted&&(this[s(606)+"er"]&&window["removeEv"+s(452)+"ner"](e[s(922)],this[s(1227)+s(955)]),this[s(606)+"er"]&&window["removeEv"+s(452)+s(197)](e[s(414)],this._handlePageShow),this[s(1601)]()),this[s(606)+"er"]&&window["removeEv"+s(452)+s(197)](e[s(1500)],this[s(812)+s(490)]),this[s(606)+"er"]&&window[s(445)+"entListe"+s(197)](e[s(850)],this[s(812)+s(1401)])}[t(1227)+t(1713)](r){let s=t;if(e.FBewE(e[s(862)],e[s(1004)]))r[s(468)+"d"]&&(this["_navigat"+s(918)]()&&(!this[s(1247)]||e[s(1087)](this[s(1247)].readyState,this[s(1528)])||e[s(352)](this[s(1247)][s(493)+"te"],this[s(895)+"NG"]))&&this[s(812)+s(490)](),this[s(606)+"er"]&&window[s(465)+s(1041)](e.CEeHW,this[s(812)+s(490)]),this[s(606)+"er"]&&window.addEventListener(e.ZgyCS,this["_handleO"+s(1401)]));else return _0x572645[s(517)+"oreNames"]||_0x4ad1df[s(274)](_0x504a89)}async[t(1198)+t(1024)](r){let s=t,{fpID:d,deviceID:f,bddID:p,ttwID:y,accessKey:S,aID:g,customParams:R={},enableAutoAck:C,enableQoS:N,QoSLevel:q,env:B}=this[s(865)],M,oe,ze;this[s(606)+"er"]||this._isMiniWX||this[s(809)+"T"]?(M=location&&e[s(884)]("https:",location[s(894)])?e.LKxHO:e.qHszA,oe=r[s(1490)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),ze=/^wss(.*:\/\/)/[s(1149)](r)?r:""+M+oe):(M=s(1616),oe=r.replace(/(^http)((?:[s]*:\/\/))/,""),ze=/(^ws)((?:[s]*:\/\/))/[s(1149)](oe)?oe:""+M+oe);let Ye=p?e.JCsdp:y?"ttwid":e[s(1554)],ms=p||y||f;if(e[s(1165)](!ms,!Ye))throw new Error(s(1761)+"rovide b"+s(599)+s(1102)+s(716));let Oa=e.ORLFq(e[s(1429)],typeof R)?await e.PRIxI(R):R,gs=B?e[s(978)](lm,B[s(1481)],B[s(1252)]):{},ri=Object.assign({device_platform:s(558),version_code:e[s(364)],access_key:S,fpid:d,aid:g,[Ye]:ms,xsack:C?1:0,xaack:C?1:0,xsqos:N?1:0,qos_level:N?q:void 0,qos_sdk_version:2,...gs},Oa),La=Object[s(1054)](ri)[s(629)]((ii,Na)=>ri[Na]!==void 0?""+ii+(ii?"&":"?")+Na+"="+ri[Na]:ii,"");return ze+s(344)+La}async _connect(){let r=t;if(e[r(559)](e[r(347)],e.MOsmX)){if(this[r(735)+"Lock"]||this["_readyCl"+r(1740)])return;this[r(735)+r(728)]=!0;try{let s=this[r(697)+"tManager"]?.[r(977)+r(331)+r(245)+"hedMaxRe"+r(399)](),{timeoutInterval:d}=this[r(865)];if(s){let p=this[r(697)+r(249)]?.[r(527)+"ntEndpoint"](),y=this[r(697)+"tManager"]?.[r(995)+r(1279)+"pointAndUpdateCo"+r(328)](),S=this[r(697)+r(249)]?.[r(527)+r(1327)+r(476)+"ount"]();if(y){let g="connect "+p+(r(409)+r(332)+r(931)+r(193)+r(297)+"backup e"+r(1668))+y+(r(1709)+"y"),R=e[r(560)](ft,e[r(1550)],{message:g,code:cn[r(1352)+r(800)+"R"]});this._debug(g),this[r(919)+"hErrorEv"+r(210)](R),this._url=await this[r(1198)+r(1024)](y),this[r(1658)]("connect "+y+" "+S+r(1572)),this[r(1324)+"sListeners"]()}else{let g=r(753)+p+(r(409)+", max re"+r(931)+r(1380));this[r(1658)](g),this[r(919)+r(563)+r(210)](e[r(357)](ft,e[r(1550)],{message:g,code:cn[r(1352)+r(800)+"R"]}));return}}else{let p=this[r(697)+r(249)]?.[r(527)+r(1327)+r(345)+r(768)](),y=this[r(697)+r(249)]?.[r(527)+r(1327)+r(476)+r(1662)]();this[r(741)]=await this[r(1198)+r(1024)](p||""),this[r(1658)](r(753)+p+" "+y+" times"),this[r(1324)+r(1620)+"rs"]()}if(this[r(1486)])this[r(1486)]=!1;else{let p=e.wEroU(Ia,e[r(1157)],{message:e[r(491)]});this[r(1029)+r(1218)]&&this[r(1029)+r(1218)](p)}let f=this["_endpoin"+r(249)]?.[r(527)+r(1327)+"ntTriesC"+r(1662)]()||0;f>1&&await this[r(1408)](f-1),this[r(1658)](r(744)+r(1111)+this[r(741)]+(r(1109)+r(1710))+this[r(784)+"ls"]),this[r(1247)]=am({url:this._url,protocols:[this._protocols],headers:this[r(865)][r(1229)+r(663)+"s"][r(307)+r(1540)]},this[r(865)].ws),(this[r(606)+"er"]||this[r(523)+"r"])&&this[r(1247)]&&(this[r(1247)][r(1390)+"pe"]=this["_binaryT"+r(986)]),this[r(1001)+r(234)](),this["_connect"+r(431)+r(992)]=setTimeout(this[r(423)+"ut"][r(842)](this),d)}catch(s){throw this[r(735)+r(728)]=!1,s}}else{for(_0x3e25b4>>>=0;e[r(633)](_0x9590d2,128);)e[r(1057)](_0x15beb0,_0x515b1a,e[r(1237)](e[r(1212)](127,_0x1122ce),128)),_0x2e2091>>>=7;e.vxMKj(_0x14f8b1,_0xc644c8,_0x32fbbd)}}[t(250)+t(1255)](){let r=t;clearTimeout(this[r(735)+"ionTimeo"+r(992)]),this["_connectionTimeo"+r(992)]=null}[t(964)+t(671)](){let r=t,s={mxVnL:function(d,f,p,y,S){return d(f,p,y,S)},DXccR:function(d,f){return e[z(1525)](d,f)},pMUaX:e[r(1215)]};e[r(566)](e[r(1417)],r(372))?(e[r(1295)](clearTimeout,this["_pingPon"+r(920)+"Id"]),e.hYTNb(clearTimeout,this["_reconne"+r(1514)+r(257)]),this[r(1667)+r(920)+"Id"]=null,this[r(1654)+r(1514)+r(257)]=null):_0xebdc9d[r(465)+r(1041)](UrFeSq[r(1659)],d=>{let f=r;UrFeSq[f(1451)](_0x208e34,_0x18e0d1(_0x2a12b3[f(637)]),d[f(1749)+"on"],d[f(921)+"on"],UrFeSq[f(1676)](_0x2c47d8,_0x476b0c["transact"+f(1499)]))})}[t(1658)](...r){let s=t;this[s(865)][s(311)]&&console[s(759)][s(1381)](console,[e[s(308)],...r])}[t(1493)+t(666)+"e"](r){let s=t,d={FBIcy:function(f,p){return e[z(573)](f,p)},wxPJq:e[s(1367)],LuTIZ:e[s(421)]};if(e.NYLkE(s(982),e[s(963)]))d[s(1374)](_0x1e4854,s(433)),this[s(961)](d[s(448)],_0xe51b00),this[s(961)](d.LuTIZ,_0x2d2182);else{let{initReconnectInterval:f,maxReconnectInterval:p,reconnectIntervalGrowFactor:y}=this[s(865)],S=e.PpzrL(f,Math.pow(y,e[s(561)](r,1)));return S>p?p:S}}_ping(){let r=t;if(this[r(1247)]&&e[r(557)](this._ws[r(493)+"te"],this.CONNECTING))if(e[r(1673)](e[r(1309)],e[r(1741)])){this["_clearPi"+r(671)](),this[r(1667)+r(920)+"Id"]=setTimeout(this[r(1426)][r(842)](this),this._options[r(1437)+r(1281)]);return}else return!!_0x54867f?.[r(619)](s=>s.key===_0x4946d5&&s[r(273)]===_0x3c61c1);if(!this[r(1247)]||e[r(1675)](this[r(1247)][r(493)+"te"],this[r(1528)]))return void this._handleReconnect();this._ws&&this[r(1247)][r(401)]("hi"),this[r(1654)+r(1514)+r(257)]=e[r(1415)](setTimeout,this[r(1396)+"econnect"+r(816)][r(842)](this),this[r(865)][r(656)+r(1220)+r(1718)])}[t(1396)+"econnectTimeout"](){let r=t;this[r(1178)+r(1579)]?.addCount(),this[r(413)](e[r(421)],e[r(1370)]),this[r(1178)+r(1579)]?.[r(948)+r(1300)+"nt"]()?this[r(1396)+r(1218)]():this._ping()}[t(268)+t(918)](){let r=t;return this[r(809)+"T"]||this._isMiniWX?this[r(892)+"igatorOn"+r(692)]:(this[r(606)+"er"]||this[r(523)+"r"])&&this[r(865)][r(438)+r(683)+r(505)]?navigator[r(1368)]:!0}["_handleR"+t(1218)](){let r=t;!this[r(268)+r(918)]()||this[r(999)+r(1740)]||(this[r(697)+r(249)]?.["resetEnd"+r(700)+"fig"](),this[r(1178)+r(1579)]?.[r(221)+"nter"](),this[r(1247)]?this["_disconn"+r(649)](1001,e[r(1301)],!0):this[r(735)]())}[t(343)+t(1549)+"ange"](){let r=t;this[r(809)+"T"]?tt["onNetwor"+r(714)+r(872)](({isConnected:s})=>{let d=r;this[d(892)+d(1278)+d(692)]=s,s?this[d(812)+d(490)]():this[d(812)+d(1401)]()}):this[r(392)+"X"]&&wx["onNetwor"+r(714)+r(872)](({isConnected:s})=>{let d=r;this["_miniNav"+d(1278)+d(692)]=s,s?this["_handleO"+d(490)]():this[d(812)+d(1401)]()})}[t(1408)](r){let s={tESwZ:function(d,f,p){return e.Omlwc(d,f,p)}};return new Promise(d=>{let f=z;s[f(929)](setTimeout,d,this["_getInte"+f(666)+"e"](r))})}[t(680)+t(649)](r=1e3,s="",d=!1){let f=t,p={IFRyq:function(y,S,g){return e.tjRvT(y,S,g)}};if(e[f(565)]("vkQrb",e[f(1632)]))xuXDdK[f(686)](_0x3560f7,_0x1a4e42,16),_0x5be921(_0x23ddf3,_0x37ee43);else{if(!this[f(1247)])return;this["_destroy"+f(1650)+"t"](r,s,d)}}[t(423)+"ut"](){let r=t,s=this._endpointManager?.["getCurre"+r(1327)+"nt"]();this._debug(r(753)+s+r(409)),this["_disconn"+r(649)](1001,"timeout,"+r(1547)+r(909)+"g",!0)}_sendAck(r){let s=t,d=e.sgIKS(Ht,r);this[s(1247)]&&e[s(1635)](this[s(1247)][s(493)+"te"],this[s(1528)])&&(this._ws&&this._ws[s(401)](d),this[s(1658)](s(1570),r))}[t(1324)+t(1620)+"rs"](){let r=t,s=e.MAHEV[r(813)]("|"),d=0;for(;;){switch(s[d++]){case"0":this._ws["removeEventListe"+r(197)](e[r(1475)],this[r(1136)+"ge"]);continue;case"1":this[r(1247)][r(445)+r(452)+r(197)](e[r(769)],this[r(1684)]);continue;case"2":this[r(1247)][r(445)+r(452)+r(197)](e[r(612)],this[r(984)]);continue;case"3":this[r(1247)][r(445)+r(452)+"ner"](e[r(1550)],this[r(253)]);continue;case"4":if(!this[r(1247)])return;continue}break}}[t(1001)+t(234)](){let r=t,s=e[r(856)][r(813)]("|"),d=0;for(;;){switch(s[d++]){case"0":if(!this[r(1247)])return;continue;case"1":this._ws[r(465)+r(1041)](e.SvIiX,this[r(1136)+"ge"]);continue;case"2":this[r(1247)]["addEvent"+r(1041)](e[r(1550)],this[r(253)]);continue;case"3":this[r(1247)].addEventListener(e.JqjoE,this[r(984)]);continue;case"4":this[r(1247)][r(465)+"Listener"](r(897),this[r(1684)]);continue}break}}[t(389)+"nceClose"](r=1e3,s=""){let d=t;try{e[d(593)](e.dgdCu,e[d(1478)])?this[d(1247)]&&this._ws.close(r,s):(_0x4a98b+=_0x27e8af(_0x131db9),_0x4abf64+=2)}catch{}}_destroyWebSocket(r=1e3,s="",d=!1){let f=t;if(this[f(964)+f(671)](),this[f(250)+f(1255)](),this["_removeW"+f(1620)+"rs"](),this[f(389)+f(1372)](1e3,s),this[f(735)+"Lock"]=!1,d&&this[f(268)+"orOnline"]()&&!this[f(999)+"osed"]){if(this["_endpoin"+f(249)]?.[f(948)+f(832)+"es"]()){let y=this["_endpoin"+f(249)]?.[f(527)+"ntEndpoint"]();this[f(919)+f(1557)+f(210)](e[f(1518)](bt,e[f(612)],{code:1006,reason:f(753)+y+(f(409)+", max re"+f(931)+f(1380)),wasClean:!0}))}else{let y=this._options[f(1317)+"tInterce"+f(1647)](r,s);this["_dispatc"+f(1557)+"ent"](bt("close",{code:r,reason:s,wasClean:!0,willReconnect:y})),y&&this._connect()}return}this[f(268)+f(918)]()||this[f(999)+f(1740)]?this[f(919)+"hCloseEv"+f(210)](bt(e[f(612)],{code:r,reason:"bye"})):this["_dispatchCloseEv"+f(210)](bt(e[f(612)],{code:1006,reason:e[f(1232)]})),this[f(1247)]=null,this[f(697)+"tManager"]?.["resetEndpointCon"+f(1461)](),this[f(1178)+f(1579)]?.[f(221)+"nter"]()}[t(919)+t(365)+"nt"](r){let s=t;this.emit(e[s(769)],r),this[s(789)]&&this[s(789)](r)}[t(919)+"hMessage"+t(717)](r){let s=t;this[s(413)](e.SvIiX,r),this[s(736)+"e"]&&this[s(736)+"e"](r)}[t(919)+t(346)+t(270)](r){let s=t;if(e[s(356)](e[s(974)],e.EGQCP))return this[s(930)+s(1226)+s(302)+"t"]=1,this[s(1498)+"ndex"]++,this[s(803)+"s"][this[s(1498)+s(879)]];this[s(413)](e.oiOkx,r),this[s(1067)+s(1754)]&&this[s(1067)+s(1754)](r)}[t(919)+t(563)+t(210)](r){let s=t;this.emit(e.SavKq,r),this[s(239)]&&this[s(239)](r)}["_dispatc"+t(1557)+t(210)](r){let s=t;this.emit(e[s(612)],r),this[s(1513)]&&this[s(1513)](r)}get binaryType(){let r=t;return this[r(1247)]?this[r(1247)][r(1390)+"pe"]:this._binaryType}set binaryType(r){let s=t;this._binaryType=r,this._ws&&(this[s(1247)][s(1390)+"pe"]=r)}get[t(520)+"nt"](){let r=t;return this[r(697)+"tManager"]?.["getCurre"+r(1327)+r(476)+r(1662)]()||0}get bufferedAmount(){let r=t,s={FwPlY:e[r(1550)]};return this[r(469)+r(1056)].reduce((f,p)=>{let y=r;if(e[y(1467)](e[y(801)],"EVNmR"))this[y(413)](xvocGt[y(1720)],_0x17c0fe),this[y(239)]&&this[y(239)](_0x56bdf8);else return f+=p&&p[y(1195)+"th"]||0,f},0)+(this._ws?this[r(1247)].bufferedAmount:0)}get[t(277)+"ns"](){let r=t;return this[r(1247)]?this[r(1247)][r(277)+"ns"]:""}get[t(894)](){let r=t;return this[r(1247)]?this[r(1247)][r(894)]:""}get[t(493)+"te"](){let r=t;return this._ws?this[r(1247)].readyState:this[r(865)][r(322)+r(626)]?this[r(895)+"NG"]:this[r(435)]}get url(){let r=t;return this[r(1247)]?this._ws[r(988)]:this._url}[t(1601)](r=1e3,s){let d=t;if(this[d(999)+d(1740)]=!0,this[d(250)+d(1255)](),this[d(964)+"ngTimer"](),this[d(1444)+d(1303)+d(1041)](),this[d(1241)+d(834)]?.[d(1091)](),!this[d(1247)])return void this[d(1658)](d(440)+d(1656)+"ce not i"+d(1236)+"ed");if(e[d(638)](this[d(1247)][d(493)+"te"],this[d(435)])||this._ws[d(493)+"te"]===this[d(461)])return void this._debug(e[d(767)]);this._destroyWebSocket(r,s)}async[t(401)](r,s){let d=t,f={LufwN:function(ze){return e[z(695)](ze)}};if(e[d(647)](null,r))throw new Error(e[d(1287)]);e[d(317)](e[d(398)],typeof r)&&(r=JSON.stringify(r)),e[d(621)](e[d(871)],typeof r)&&!e[d(1627)](r,ArrayBuffer)&&!(r.buffer&&e[d(1482)](r.buffer,ArrayBuffer))&&(r=JSON[d(965)+"y"](r));let p=await e.xwigL(Al,r),y=e[d(1258)](dm,r),{method:S=0,service:g=this._options.service,logID:R=this[d(865)][d(1145)+"erator"](),headers:C=this[d(865)][d(1425)],payloadEncoding:N=this[d(865)][d(1172)+d(1088)],payloadType:q=this[d(865)][d(745)+d(986)],logIDNew:B=this._options[d(1535)+d(1268)]["enableAutoGenera"+d(198)+"ew"]?e.UCNGG(i,this[d(865)]["logIDNew"+d(1268)][d(1037)]):""}=e[d(726)](s,{});if(!g)throw new Error(e[d(1590)]);let M={SeqID:pe.fromNumber(this[d(1363)]++),LogID:pe[d(324)+"er"](R),service:g,method:S,headers:C,payloadEncoding:e[d(1070)](N,Object)?N[d(260)]?N[d(260)]:"":N,payloadType:e[d(1482)](q,Object)?q.type?q[d(778)]:y:q||y,payload:p,LogIDNew:B},oe=Ht(M);if(this._ws&&e[d(335)](this[d(1247)][d(493)+"te"],this.OPEN)){if(e.ljxer(d(243),"vKiIS"))return!!this[d(1342)];this._ws&&this[d(1247)][d(401)](oe),this[d(1658)](e[d(238)],M)}else e[d(1387)](this[d(469)+d(1056)][d(279)],this[d(865)][d(578)+d(1126)+d(207)])?e.psevs(d(1664),e[d(854)])?(this[d(469)+d(1056)][d(1730)](oe),this[d(1658)]("enqueue",M)):(this[d(1486)]=!1,_0x299c93(this[d(735)+d(431)+d(992)]),TNvPvj[d(923)](_0x13fc47)):(this[d(469)+d(1056)].shift(),this[d(469)+d(1056)].push(oe));return{seqID:this._seqId,logID:R,logIDNew:B}}async[t(1317)+"t"](r){let s=t,{url:d}=e.QmgmE(r,{}),f=Array.isArray(d)?d:e[s(884)](e[s(871)],typeof d)?[d]:[];r&&Object.assign(this._options,r),f&&f[s(279)]?this[s(697)+s(249)]=new El(f,this._options[s(877)+"es"]):this[s(697)+"tManager"]?.["resetEndpointCon"+s(1461)](),this[s(1178)+s(1579)]?.[s(221)+"nter"](this[s(865)][s(618)+s(734)]),this[s(999)+s(1740)]=!1,this._ws&&this._ws[s(493)+"te"]!==this[s(435)]?this[s(680)+s(649)](1e3,e.zsXjc,!0):e[s(422)](e[s(367)],e[s(1330)])?this[s(1342)]?.[s(259)](_0x1886b9[s(1104)+"id"]):(this[s(1486)]=!0,this[s(735)]())}async[t(1678)](){let r=t;if(e[r(381)]===e[r(1430)])_0x1fb773=e.hwOgx(_0x30dc88,_0x52040d),_0x557523=e[r(396)](127,_0x20b29b),128&_0x38b060&&(_0x494f88=e[r(353)](_0xa2988c,_0x238f90),_0x29f9cd|=e[r(1314)](127,_0x33ed35)<<7);else if(!this[r(735)+r(728)])if(e.oyblV(e[r(653)],e[r(653)])){let s="0|2|3|4|1".split("|"),d=0;for(;;){switch(s[d++]){case"0":this[r(697)+r(249)]?.[r(1479)+"pointCon"+r(1461)]();continue;case"1":this[r(735)]();continue;case"2":this[r(1178)+r(1579)]?.resetCounter();continue;case"3":this[r(999)+r(1740)]=!1;continue;case"4":this[r(1486)]=!0;continue}break}}else return _0x4d98da.log(e[r(330)],_0x121d66,_0x40c9dc,_0x3559f7),this[r(1342)][r(1706)]({cursor_name:_0x48e420,cursor:_0x2b5e42,service:_0x4bfc78})}addEventListener(r,s){let d=t;if(e[d(675)]===e[d(384)])return new _0x1c6b38(_0xd34ea5,{message:_0x4de245,code:_0x162531,error:_0x2cdeb7});this.on(r,s)}[t(1333)+t(717)](r){let{type:s}=r;this.emit(s,r)}[t(445)+t(452)+t(197)](r,s){this[t(961)](r,s)}pingOnce(){let r=t,s={jGydL:function(d,f){return e[z(679)](d,f)},JOyMD:e.YJDEZ,jbdZX:e[r(421)],lHZlx:function(d,f,p){return e[r(1541)](d,f,p)}};if(e[r(1391)](e[r(1536)],r(412)))!this[r(735)+"Lock"]&&(this["_endpoin"+r(249)]?.[r(1479)+r(700)+"fig"](),this["_pingLos"+r(1579)]?.[r(221)+r(1427)](),this[r(999)+r(1740)]=!1,this[r(1486)]=!0,this[r(735)]());else return new Promise((d,f)=>{let p=r,y={hGZcL:function(R,C){return s[z(333)](R,C)},YObad:s[p(1003)],clSnm:p(1154)+p(1666)+"s",QwJuh:s[p(1219)],fbzVW:p(436)};this[p(964)+p(671)](),this[p(1667)+p(920)+"Id"]=s[p(366)](setTimeout,this[p(1426)][p(842)](this),this._options.pingInterval);let S=()=>{let R=p;y.hGZcL(d,y[R(533)]),this[R(961)](y[R(899)],S),this[R(961)](y[R(483)],g)},g=()=>{let R=p;y[R(355)](f,y.fbzVW),this[R(961)](y.clSnm,S),this[R(961)](y[R(483)],g)};this.on("ping_onc"+p(1666)+"s",S),this.on(s[p(1219)],g),this[p(1426)]()})}}})(),Fe[F(1416)+F(1131)]=De[F(1416)+F(1131)],Fe[F(1562)+F(524)]=De[F(1562)+"rorEvent"],Fe[F(1305)+"e"]=De.ErrorCode,Fe[F(717)]=De[F(717)],Fe.FWS=De[F(195)],Fe[F(1345)+F(624)+"vent"]=De["Frontier"+F(624)+F(1156)],Fe[F(624)+F(1156)]=De[F(624)+"vent"],Fe[F(261)+"t"]=De[F(261)+"t"],Fe[F(1734)+"tEvent"]=De[F(1734)+F(443)],Fe[F(902)+"oseEvent"]=De[F(902)+F(1131)],Fe["createEr"+F(524)]=De[F(408)+F(524)],Fe[F(509)+F(1422)+"nt"]=De[F(509)+F(1422)+"nt"],Fe[F(1438)+F(1581)]=De[F(1438)+F(1581)],Fe[F(949)+F(1457)+F(1156)]=De[F(949)+F(1457)+"vent"],Fe.decodedFrame=De[F(1012)+F(602)],Fe[F(292)+F(391)]=De[F(292)+F(391)];for(na in De)[F(1416)+F(1131),"CustomEr"+F(524),"ErrorCode",F(717),F(195),F(1345)+F(624)+F(1156),"MessageE"+F(1156),F(261)+"t",F(1734)+F(443),F(902)+F(1131),F(408)+F(524),"createMe"+F(1422)+"nt",F(1438)+F(1581),F(949)+F(1457)+F(1156),"decodedF"+F(602),F(292)+F(391)][F(1622)](na)===-1&&(Fe[na]=De[na]);var na;Object[F(1137)+"operty"](Fe,F(855)+"le",{value:!0})});import{existsSync as c1,openSync as d1}from"node:fs";import{mkdir as l1}from"node:fs/promises";import{dirname as u1}from"node:path";import{fileURLToPath as f1}from"node:url";function x1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function el(t=Y()){return c1(t.libEntry)?t.libEntry:f1(new URL("../index.ts",import.meta.url))}async function mp(t={}){let e=t.paths??Y(),n=t.entryOverride??el(e),i=x1(e,process.env.COZE_BRIDGE_LOG_MODE);await l1(u1(i),{recursive:!0});let o=d1(i,"a"),l=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=at(process.execPath,l,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[us]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return h1.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var h1,us,ha=it(()=>{"use strict";Xt();ne();Pe();h1=K("spawn-daemon"),us="COZE_BRIDGE_DAEMON"});import{spawn as uI}from"node:child_process";import{mkdir as fI,unlink as hI,writeFile as xI}from"node:fs/promises";import{dirname as pI,join as mI}from"node:path";function Xr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function gI(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${Xr(n)}</key>
21
+ <string>${Xr(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function _2(t,e){return new Promise((r,i)=>{let o=f2(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var Xr,fs,pa,sl,Bp=et(()=>{"use strict";te();Xr=j("supervisor.launchd"),fs="ai.coze.bridge",pa=_2,sl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function wI(t,e){return new Promise((n,i)=>{let o=uI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?n():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var Yr,xs,_a,dl,zp=it(()=>{"use strict";ne();Yr=K("supervisor.launchd"),xs="ai.coze.bridge",_a=wI,dl={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>${fs}</string>
31
+ <string>${xs}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Zr(t.nodeBin)}</string>
35
- <string>${Zr(t.entry)}</string>
34
+ <string>${Xr(t.nodeBin)}</string>
35
+ <string>${Xr(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>${Xr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Zr(t.logFile)}</string>${w2(t.env)}
47
+ <string>${Xr(t.logFile)}</string>${gI(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return m2(t.homeDir,"Library","LaunchAgents",`${fs}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await x2(g2(i),{recursive:!0}),await p2(i,this.renderConfig(t),"utf8"),Xr.info("plist written",{plistPath:i,activate:r}),!r)return;await pa("launchctl",["unload","-w",i]).catch(c=>Xr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await pa("launchctl",["load","-w",i]),Xr.info("launchd job loaded",{label:fs});let o=process.getuid?.()??0;await pa("launchctl",["kickstart","-k",`gui/${o}/${fs}`]),Xr.info("launchd job kickstarted",{label:fs,uid:o})},async uninstall(t){let e=this.configPath(t);await pa("launchctl",["unload","-w",e]).catch(r=>Xr.warn("launchctl unload failed (ignored)",{err:String(r)})),await h2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Xr.info("launchd job removed",{plistPath:e})}}});import{spawn as y2}from"node:child_process";import{mkdir as b2,unlink as E2,writeFile as v2}from"node:fs/promises";import{dirname as S2,join as Fp}from"node:path";function ma(t,e){return t.isRoot?e:["--user",...e]}function A2(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function wa(t,e){return new Promise((r,i)=>{let o=y2(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 ga,Qr,I2,ol,zp=et(()=>{"use strict";te();ga=j("supervisor.systemd"),Qr="coze-bridge.service",I2="/etc/systemd/system";ol={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return mI(t.homeDir,"Library","LaunchAgents",`${xs}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await fI(pI(i),{recursive:!0}),await xI(i,this.renderConfig(t),"utf8"),Yr.info("plist written",{plistPath:i,activate:n}),!n)return;await _a("launchctl",["unload","-w",i]).catch(c=>Yr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await _a("launchctl",["load","-w",i]),Yr.info("launchd job loaded",{label:xs});let o=process.getuid?.()??0;await _a("launchctl",["kickstart","-k",`gui/${o}/${xs}`]),Yr.info("launchd job kickstarted",{label:xs,uid:o})},async uninstall(t){let e=this.configPath(t);await _a("launchctl",["unload","-w",e]).catch(n=>Yr.warn("launchctl unload failed (ignored)",{err:String(n)})),await hI(e).catch(n=>{if(n.code!=="ENOENT")throw n}),Yr.info("launchd job removed",{plistPath:e})}}});import{spawn as _I}from"node:child_process";import{mkdir as yI,unlink as bI,writeFile as EI}from"node:fs/promises";import{dirname as vI,join as Up}from"node:path";function ba(t,e){return t.isRoot?e:["--user",...e]}function II(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function Ea(t,e){return new Promise((n,i)=>{let o=_I(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?n():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var ya,Qr,SI,ll,Gp=it(()=>{"use strict";ne();ya=K("supervisor.systemd"),Qr="coze-bridge.service",SI="/etc/systemd/system";ll={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
- ${A2(t.env)}
62
+ ${II(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Fp(I2,Qr):Fp(t.homeDir,".config","systemd","user",Qr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await b2(S2(i),{recursive:!0}),await v2(i,this.renderConfig(t),"utf8"),ga.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await wa("systemctl",ma(t,["daemon-reload"])),await wa("systemctl",ma(t,r?["enable","--now",Qr]:["enable",Qr])),ga.info("systemd unit enabled",{unitName:Qr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await wa("systemctl",ma(t,["disable","--now",Qr])).catch(r=>ga.warn("systemctl disable failed (ignored)",{err:String(r)})),await E2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await wa("systemctl",ma(t,["daemon-reload"])).catch(()=>{}),ga.info("systemd unit removed",{unitPath:e})}}});import{spawn as k2}from"node:child_process";import{join as T2}from"node:path";function Up(t,e){return new Promise((r,i)=>{let o=k2(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 al,_a,cl,Hp=et(()=>{"use strict";te();al=j("supervisor.taskscheduler"),_a="CozeBridge",cl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Up(SI,Qr):Up(t.homeDir,".config","systemd","user",Qr)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await yI(vI(i),{recursive:!0}),await EI(i,this.renderConfig(t),"utf8"),ya.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await Ea("systemctl",ba(t,["daemon-reload"])),await Ea("systemctl",ba(t,n?["enable","--now",Qr]:["enable",Qr])),ya.info("systemd unit enabled",{unitName:Qr,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await Ea("systemctl",ba(t,["disable","--now",Qr])).catch(n=>ya.warn("systemctl disable failed (ignored)",{err:String(n)})),await bI(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Ea("systemctl",ba(t,["daemon-reload"])).catch(()=>{}),ya.info("systemd unit removed",{unitPath:e})}}});import{spawn as AI}from"node:child_process";import{join as kI}from"node:path";function Hp(t,e){return new Promise((n,i)=>{let o=AI(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?n():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var ul,va,fl,qp=it(()=>{"use strict";ne();ul=K("supervisor.taskscheduler"),va="CozeBridge",fl={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,61 +86,61 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return T2(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 Up("schtasks",["/Create","/SC","ONLOGON","/TN",_a,"/TR",r,"/RU",t.userName,"/F"]),al.info("task scheduler entry created",{task:_a,logFile:t.logFile})},async uninstall(t){await Up("schtasks",["/Delete","/TN",_a,"/F"]).catch(e=>al.warn("schtasks /Delete failed (ignored)",{err:String(e)})),al.info("task scheduler entry removed",{task:_a})}}});var Gp={};Oa(Gp,{buildContext:()=>L2,getSupervisor:()=>R2,launchdSupervisor:()=>sl,systemdSupervisor:()=>ol,taskSchedulerSupervisor:()=>cl});import{homedir as C2,userInfo as P2}from"node:os";function R2(t=process.platform){switch(t){case"darwin":return sl;case"linux":return ol;case"win32":return cl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function O2(){let t={};for(let e of D2){let r=process.env[e];r&&(t[e]=r)}return t}function L2(){let t=J();return{nodeBin:process.execPath,entry:Jd(t),logFile:t.logFile,homeDir:C2(),userName:P2().username,isRoot:process.getuid?.()===0,env:O2()}}var D2,qp=et(()=>{"use strict";Ce();da();Bp();zp();Hp();D2=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();ln();var Ul=j("acp-installer-warmup"),mm=["claude-code","codex"];async function Hl(t={}){let e=t.ensure??lr,i=(await Promise.allSettled(mm.map(async o=>{let c=await e(o);Ul.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Ul.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))})}qt();te();import{readdir as Om}from"node:fs/promises";import{mkdir as Wl,readFile as Rm,writeFile as Kl}from"node:fs/promises";import{join as Ua}from"node:path";var Dm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function xr(t,e,r){await Wl(t,{recursive:!0});let i=Dm[e],o=Ua(t,i);return await Kl(o,r??"","utf8"),o}async function Ha(t,e,r){let i=Ua(t,".claude");await Wl(i,{recursive:!0});let o=Ua(i,"settings.local.json"),c={};try{let u=await Rm(o,"utf8"),x=JSON.parse(u);typeof x=="object"&&x!==null&&!Array.isArray(x)&&(c=x)}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 Kl(o,JSON.stringify(c,null,2),"utf8"),o}var Xe=j("agent-detail-sync"),Lm=6e4,Nm=5*6e4,vs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await Om(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 ve(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 ve(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(x){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(x)});let h=this.retryQueue.get(e),m=h?Math.min(h.currentDelay*2,Nm):Lm;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});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 ze(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 xr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var xd=Ht(Iu(),1);import{createHash as vy}from"node:crypto";import{lstat as sd,mkdir as od,readFile as wo,readdir as m0,rm as ad,stat as ud,writeFile as cd}from"node:fs/promises";import{homedir as Sy}from"node:os";import{basename as h0,dirname as Iy,join as fe,normalize as Ay,relative as fd,resolve as dd,sep as w0}from"node:path";import{Readable as _0}from"node:stream";import{pipeline as y0}from"node:stream/promises";import rw from"events";import rt from"fs";import{EventEmitter as Uc}from"node:events";import af from"node:stream";import{StringDecoder as iw}from"node:string_decoder";import lf from"node:path";import Ir from"node:fs";import{dirname as mw,parse as ww}from"path";import{EventEmitter as Aw}from"events";import bc from"assert";import{Buffer as qn}from"buffer";import*as Pu from"zlib";import kw from"zlib";import{posix as wr}from"node:path";import{basename as e_}from"node:path";import to from"fs";import Rt from"fs";import Bu from"path";import{win32 as f_}from"node:path";import ju from"path";import If from"node:fs";import C_ from"node:assert";import{randomBytes as Af}from"node:crypto";import ie from"node:fs";import Me from"node:path";import kf from"fs";import uo from"node:fs";import ki from"node:path";import ct from"node:fs";import M_ from"node:fs/promises";import io from"node:path";import{join as Ff}from"node:path";import at from"node:fs";import Hf from"node:path";var tw=Object.defineProperty,nw=(t,e)=>{for(var r in e)tw(t,r,{get:e[r],enumerable:!0})},Au=typeof process=="object"&&process?process:{stdout:null,stderr:null},sw=t=>!!t&&typeof t=="object"&&(t instanceof Kn||t instanceof af||ow(t)||aw(t)),ow=t=>!!t&&typeof t=="object"&&t instanceof Uc&&typeof t.pipe=="function"&&t.pipe!==af.Writable.prototype.pipe,aw=t=>!!t&&typeof t=="object"&&t instanceof Uc&&typeof t.write=="function"&&typeof t.end=="function",jt=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),fn=Symbol("emittedEnd"),Ts=Symbol("emittingEnd"),li=Symbol("emittedError"),Cs=Symbol("closed"),ku=Symbol("read"),Ps=Symbol("flush"),Tu=Symbol("flushChunk"),yt=Symbol("encoding"),mr=Symbol("decoder"),Ue=Symbol("flowing"),ui=Symbol("paused"),Er=Symbol("resume"),He=Symbol("buffer"),Ze=Symbol("pipes"),Ge=Symbol("bufferLength"),$a=Symbol("bufferPush"),Rs=Symbol("bufferShift"),Je=Symbol("objectMode"),Ae=Symbol("destroyed"),Va=Symbol("error"),Ya=Symbol("emitData"),Cu=Symbol("emitEnd"),Ja=Symbol("emitEnd2"),Tt=Symbol("async"),Xa=Symbol("abort"),Ds=Symbol("aborted"),fi=Symbol("signal"),Ln=Symbol("dataListeners"),ot=Symbol("discarded"),xi=t=>Promise.resolve().then(t),cw=t=>t(),dw=t=>t==="end"||t==="finish"||t==="prefinish",lw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,uw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),cf=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Er](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},fw=class extends cf{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)}},xw=t=>!!t.objectMode,hw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Kn=class extends Uc{[Ue]=!1;[ui]=!1;[Ze]=[];[He]=[];[Je];[yt];[Tt];[mr];[jt]=!1;[fn]=!1;[Ts]=!1;[Cs]=!1;[li]=null;[Ge]=0;[Ae]=!1;[fi];[Ds]=!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");xw(e)?(this[Je]=!0,this[yt]=null):hw(e)?(this[yt]=e.encoding,this[Je]=!1):(this[Je]=!1,this[yt]=null),this[Tt]=!!e.async,this[mr]=this[yt]?new iw(this[yt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ze]});let{signal:r}=e;r&&(this[fi]=r,r.aborted?this[Xa]():r.addEventListener("abort",()=>this[Xa]()))}get bufferLength(){return this[Ge]}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[Je]}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}[Xa](){this[Ds]=!0,this.emit("abort",this[fi]?.reason),this.destroy(this[fi]?.reason)}get aborted(){return this[Ds]}set aborted(t){}write(t,e,r){if(this[Ds])return!1;if(this[jt])throw new Error("write after end");if(this[Ae])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]?xi:cw;if(!this[Je]&&!Buffer.isBuffer(t)){if(uw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(lw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Je]?(this[Ue]&&this[Ge]!==0&&this[Ps](!0),this[Ue]?this.emit("data",t):this[$a](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):t.length?(typeof t=="string"&&!(e===this[yt]&&!this[mr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[yt]&&(t=this[mr].write(t)),this[Ue]&&this[Ge]!==0&&this[Ps](!0),this[Ue]?this.emit("data",t):this[$a](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):(this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue])}read(t){if(this[Ae])return null;if(this[ot]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[Wt](),null;this[Je]&&(t=null),this[He].length>1&&!this[Je]&&(this[He]=[this[yt]?this[He].join(""):Buffer.concat(this[He],this[Ge])]);let e=this[ku](t||null,this[He][0]);return this[Wt](),e}[ku](t,e){if(this[Je])this[Rs]();else{let r=e;t===r.length||t===null?this[Rs]():typeof r=="string"?(this[He][0]=r.slice(t),e=r.slice(0,t),this[Ge]-=t):(this[He][0]=r.subarray(t),e=r.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[He].length&&!this[jt]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[jt]=!0,this.writable=!1,(this[Ue]||!this[ui])&&this[Wt](),this}[Er](){this[Ae]||(!this[Ln]&&!this[Ze].length&&(this[ot]=!0),this[ui]=!1,this[Ue]=!0,this.emit("resume"),this[He].length?this[Ps]():this[jt]?this[Wt]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[Ue]=!1,this[ui]=!0,this[ot]=!1}get destroyed(){return this[Ae]}get flowing(){return this[Ue]}get paused(){return this[ui]}[$a](t){this[Je]?this[Ge]+=1:this[Ge]+=t.length,this[He].push(t)}[Rs](){return this[Je]?this[Ge]-=1:this[Ge]-=this[He][0].length,this[He].shift()}[Ps](t=!1){do;while(this[Tu](this[Rs]())&&this[He].length);!t&&!this[He].length&&!this[jt]&&this.emit("drain")}[Tu](t){return this.emit("data",t),this[Ue]}pipe(t,e){if(this[Ae])return t;this[ot]=!1;let r=this[fn];return e=e||{},t===Au.stdout||t===Au.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Ze].push(e.proxyErrors?new fw(this,t,e):new cf(this,t,e)),this[Tt]?xi(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[Ze].find(r=>r.dest===t);e&&(this[Ze].length===1?(this[Ue]&&this[Ln]===0&&(this[Ue]=!1),this[Ze]=[]):this[Ze].splice(this[Ze].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[Ze].length&&!this[Ue]&&this[Er]();else if(t==="readable"&&this[Ge]!==0)super.emit("readable");else if(dw(t)&&this[fn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[li]){let i=e;this[Tt]?xi(()=>i.call(this,this[li])):i.call(this,this[li])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Ln]=this.listeners("data").length,this[Ln]===0&&!this[ot]&&!this[Ze].length&&(this[Ue]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[ot]&&!this[Ze].length&&(this[Ue]=!1)),e}get emittedEnd(){return this[fn]}[Wt](){!this[Ts]&&!this[fn]&&!this[Ae]&&this[He].length===0&&this[jt]&&(this[Ts]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Cs]&&this.emit("close"),this[Ts]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Ae&&this[Ae])return!1;if(t==="data")return!this[Je]&&!r?!1:this[Tt]?(xi(()=>this[Ya](r)),!0):this[Ya](r);if(t==="end")return this[Cu]();if(t==="close"){if(this[Cs]=!0,!this[fn]&&!this[Ae])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[li]=r,super.emit(Va,r);let o=!this[fi]||this.listeners("error").length?super.emit("error",r):!1;return this[Wt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Wt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[Wt](),i}[Ya](t){for(let r of this[Ze])r.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[Wt](),e}[Cu](){return this[fn]?!1:(this[fn]=!0,this.readable=!1,this[Tt]?(xi(()=>this[Ja]()),!0):this[Ja]())}[Ja](){if(this[mr]){let e=this[mr].end();if(e){for(let r of this[Ze])r.dest.write(e);this[ot]||super.emit("data",e)}}for(let e of this[Ze])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Je]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Je]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Je])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(Ae,()=>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[jt])return e();let i,o,c=h=>{this.off("data",d),this.off("end",u),this.off(Ae,x),e(),o(h)},d=h=>{this.off("error",c),this.off("end",u),this.off(Ae,x),this.pause(),i({value:h,done:!!this[jt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Ae,x),e(),i({done:!0,value:void 0})},x=()=>c(new Error("stream destroyed"));return new Promise((h,m)=>{o=m,i=h,this.once(Ae,x),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(Va,e),this.off(Ae,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(Va,e),this.once(Ae,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Ae])return t?this.emit("error",t):this.emit(Ae),this;this[Ae]=!0,this[ot]=!0,this[He].length=0,this[Ge]=0;let e=this;return typeof e.close=="function"&&!this[Cs]&&e.close(),t?this.emit("error",t):this.emit(Ae),this}static get isStream(){return sw}},pw=rt.writev,En=Symbol("_autoClose"),St=Symbol("_close"),hi=Symbol("_ended"),ue=Symbol("_fd"),Za=Symbol("_finished"),Yt=Symbol("_flags"),Qa=Symbol("_flush"),_c=Symbol("_handleChunk"),yc=Symbol("_makeBuf"),Ii=Symbol("_mode"),Os=Symbol("_needDrain"),kr=Symbol("_onerror"),Tr=Symbol("_onopen"),ec=Symbol("_onread"),vr=Symbol("_onwrite"),vn=Symbol("_open"),vt=Symbol("_path"),mn=Symbol("_pos"),Ct=Symbol("_queue"),Sr=Symbol("_read"),tc=Symbol("_readSize"),Vt=Symbol("_reading"),pi=Symbol("_remain"),nc=Symbol("_size"),qs=Symbol("_write"),Nn=Symbol("_writing"),js=Symbol("_defaultFlag"),Gn=Symbol("_errored"),Hc=class extends Kn{[Gn]=!1;[ue];[vt];[tc];[Vt]=!1;[nc];[pi];[En];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[ue]=typeof e.fd=="number"?e.fd:void 0,this[vt]=t,this[tc]=e.readSize||16*1024*1024,this[Vt]=!1,this[nc]=typeof e.size=="number"?e.size:1/0,this[pi]=this[nc],this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[ue]=="number"?this[Sr]():this[vn]()}get fd(){return this[ue]}get path(){return this[vt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[vn](){rt.open(this[vt],"r",(t,e)=>this[Tr](t,e))}[Tr](t,e){t?this[kr](t):(this[ue]=e,this.emit("open",e),this[Sr]())}[yc](){return Buffer.allocUnsafe(Math.min(this[tc],this[pi]))}[Sr](){if(!this[Vt]){this[Vt]=!0;let t=this[yc]();if(t.length===0)return process.nextTick(()=>this[ec](null,0,t));rt.read(this[ue],t,0,t.length,null,(e,r,i)=>this[ec](e,r,i))}}[ec](t,e,r){this[Vt]=!1,t?this[kr](t):this[_c](e,r)&&this[Sr]()}[St](){if(this[En]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[kr](t){this[Vt]=!0,this[St](),this.emit("error",t)}[_c](t,e){let r=!1;return this[pi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[pi]<=0)&&(r=!1,this[St](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[ue]=="number"&&this[Sr](),!1;case"error":return this[Gn]?!1:(this[Gn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},gw=class extends Hc{[vn](){let t=!0;try{this[Tr](null,rt.openSync(this[vt],"r")),t=!1}finally{t&&this[St]()}}[Sr](){let t=!0;try{if(!this[Vt]){this[Vt]=!0;do{let e=this[yc](),r=e.length===0?0:rt.readSync(this[ue],e,0,e.length,null);if(!this[_c](r,e))break}while(!0);this[Vt]=!1}t=!1}finally{t&&this[St]()}}[St](){if(this[En]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,rt.closeSync(t),this.emit("close")}}},so=class extends rw{readable=!1;writable=!0;[Gn]=!1;[Nn]=!1;[hi]=!1;[Ct]=[];[Os]=!1;[vt];[Ii];[En];[ue];[js];[Yt];[Za]=!1;[mn];constructor(t,e){e=e||{},super(e),this[vt]=t,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[Ii]=e.mode===void 0?438:e.mode,this[mn]=typeof e.start=="number"?e.start:void 0,this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[mn]!==void 0?"r+":"w";this[js]=e.flags===void 0,this[Yt]=e.flags===void 0?r:e.flags,this[ue]===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[ue]}get path(){return this[vt]}[kr](t){this[St](),this[Nn]=!0,this.emit("error",t)}[vn](){rt.open(this[vt],this[Yt],this[Ii],(t,e)=>this[Tr](t,e))}[Tr](t,e){this[js]&&this[Yt]==="r+"&&t&&t.code==="ENOENT"?(this[Yt]="w",this[vn]()):t?this[kr](t):(this[ue]=e,this.emit("open",e),this[Nn]||this[Qa]())}end(t,e){return t&&this.write(t,e),this[hi]=!0,!this[Nn]&&!this[Ct].length&&typeof this[ue]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[hi]?(this.emit("error",new Error("write() after end()")),!1):this[ue]===void 0||this[Nn]||this[Ct].length?(this[Ct].push(t),this[Os]=!0,!1):(this[Nn]=!0,this[qs](t),!0)}[qs](t){rt.write(this[ue],t,0,t.length,this[mn],(e,r)=>this[vr](e,r))}[vr](t,e){t?this[kr](t):(this[mn]!==void 0&&typeof e=="number"&&(this[mn]+=e),this[Ct].length?this[Qa]():(this[Nn]=!1,this[hi]&&!this[Za]?(this[Za]=!0,this[St](),this.emit("finish")):this[Os]&&(this[Os]=!1,this.emit("drain"))))}[Qa](){if(this[Ct].length===0)this[hi]&&this[vr](null,0);else if(this[Ct].length===1)this[qs](this[Ct].pop());else{let t=this[Ct];this[Ct]=[],pw(this[ue],t,this[mn],(e,r)=>this[vr](e,r))}}[St](){if(this[En]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},df=class extends so{[vn](){let t;if(this[js]&&this[Yt]==="r+")try{t=rt.openSync(this[vt],this[Yt],this[Ii])}catch(e){if(e?.code==="ENOENT")return this[Yt]="w",this[vn]();throw e}else t=rt.openSync(this[vt],this[Yt],this[Ii]);this[Tr](null,t)}[St](){if(this[En]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,rt.closeSync(t),this.emit("close")}}[qs](t){let e=!0;try{this[vr](null,rt.writeSync(this[ue],t,0,t.length,this[mn])),e=!1}finally{if(e)try{this[St]()}catch{}}}},_w=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"]]),yw=t=>!!t.sync&&!!t.file,bw=t=>!t.sync&&!!t.file,Ew=t=>!!t.sync&&!t.file,vw=t=>!t.sync&&!t.file,Sw=t=>!!t.file,Iw=t=>_w.get(t)||t,Gc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=Iw(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 x=Gc(c);if(o?.(x,d),yw(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(x,d)}else if(bw(x)){let h=e(x,d);return u?h.then(()=>u(),u):h}else if(Ew(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(x,d)}else if(vw(x)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(x,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),Tw=kw.constants||{ZLIB_VERNUM:4736},Ot=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Tw)),Cw=qn.concat,Ru=Object.getOwnPropertyDescriptor(qn,"concat"),Pw=t=>t,rc=Ru?.writable===!0||Ru?.set!==void 0?t=>{qn.concat=t?Pw:Cw}:t=>{},jn=Symbol("_superWrite"),Ls=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},ic=Symbol("flushFlag"),qc=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 Pu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Pu[e](t)}catch(r){throw new Ls(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 Ls(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return bc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(qn.alloc(0),{[ic]:t})))}end(t,e,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=qn.from(t,e)),this.#e)return;bc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},rc(!0);let d;try{let x=typeof t[ic]=="number"?t[ic]:this.#r;d=this.#t._processChunk(t,x),rc(!1)}catch(x){rc(!1),this.#o(new Ls(x,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",x=>this.#o(new Ls(x,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let x=d[0];u=this[jn](qn.from(x));for(let h=1;h<d.length;h++)u=this[jn](d[h])}else u=this[jn](qn.from(d));return r&&r(),u}},uf=class extends qc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ot.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ot.Z_FINISH,t.fullFlushFlag=Ot.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Ot.Z_SYNC_FLUSH),bc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},Rw=class extends uf{#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)}},Dw=class extends uf{constructor(t){super(t,"Unzip")}},ff=class extends qc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ot.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ot.BROTLI_OPERATION_FLUSH,super(t,e)}},Ow=class extends ff{constructor(t){super(t,"BrotliCompress")}},Lw=class extends ff{constructor(t){super(t,"BrotliDecompress")}},xf=class extends qc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ot.ZSTD_e_end,t.fullFlushFlag=Ot.ZSTD_e_flush,super(t,e)}},Nw=class extends xf{constructor(t){super(t,"ZstdCompress")}},Mw=class extends xf{constructor(t){super(t,"ZstdDecompress")}},Bw=(t,e)=>{if(Number.isSafeInteger(t))t<0?zw(t,e):Fw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Fw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},zw=(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]=hf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=pf(o))}},Uw=t=>{let e=t[0],r=e===128?Gw(t.subarray(1,t.length)):e===255?Hw(t):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},Hw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=hf(c):c===0?d=c:(i=!0,d=pf(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},Gw=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},hf=t=>(255^t)&255,pf=t=>(255^t)+1&255,qw={};nw(qw,{code:()=>jc,isCode:()=>Ws,isName:()=>jw,name:()=>oo,normalFsTypes:()=>gf});var Ws=t=>oo.has(t),jw=t=>jc.has(t),gf=new Set(["0","","1","2","3","4","5","6","7","D"]),oo=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"]]),jc=new Map(Array.from(oo).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=gf.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??sc(t,e+136,12),this.cksum=wn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Ws(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 h=Mn(t,e+345,155);this.path=h+"/"+this.path}else{let h=Mn(t,e+345,130);h&&(this.path=h+"/"+this.path),this.atime=r?.atime??i?.atime??sc(t,e+476,12),this.ctime=r?.ctime??i?.ctime??sc(t,e+488,12)}let x=256;for(let h=e;h<e+148;h++)x+=t[h];for(let h=e+156;h<e+512;h++)x+=t[h];this.cksumValid=x===this.cksum,this.cksum===void 0&&x===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,i=Ww(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=oc(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=oc(t,e+476,12,this.atime)||this.needPax,this.needPax=oc(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:oo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(jc.get(t));if(Ws(e)||e==="Unsupported")this.#e=e;else if(Ws(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Ww=(t,e)=>{let r=t,i="",o,c=wr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=wr.dirname(r),r=wr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?o=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?o=[r.slice(0,99),i,!0]:(r=wr.join(wr.basename(i),r),i=wr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Mn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),sc=(t,e,r)=>Kw(wn(t,e,r)),Kw=t=>t===void 0?void 0:new Date(t*1e3),wn=(t,e,r)=>Number(t[e])&128?Uw(t.subarray(e,e+r)):Vw(t,e,r),$w=t=>isNaN(t)?void 0:t,Vw=(t,e,r)=>$w(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Yw={12:8589934591,8:2097151},_n=(t,e,r,i)=>i===void 0?!1:i>Yw[r]||i<0?(Bw(i,t.subarray(e,e+r)),!0):(Jw(t,e,r,i),!1),Jw=(t,e,r,i)=>t.write(Xw(i,r),e,r,"ascii"),Xw=(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",oc=(t,e,r,i)=>i===void 0?!1:_n(t,e,r,i.getTime()/1e3),Qw=new Array(156).join("\0"),Bn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Qw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),eo=class mf{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/"+e_(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 mf(t_(n_(e),r),i)}},t_=(t,e)=>e?Object.assign({},e,t):t,n_=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(r_,Object.create(null)),r_=(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},i_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=i_!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),s_=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))))}},ao=(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))},o_=1024*1024,Ec=Buffer.from([31,139]),vc=Buffer.from([40,181,47,253]),a_=Math.max(Ec.length,vc.length),ft=Symbol("state"),Fn=Symbol("writeEntry"),Kt=Symbol("readEntry"),ac=Symbol("nextEntry"),Du=Symbol("processEntry"),Pt=Symbol("extendedHeader"),gi=Symbol("globalExtendedHeader"),xn=Symbol("meta"),Ou=Symbol("emitMeta"),me=Symbol("buffer"),$t=Symbol("queue"),hn=Symbol("ended"),cc=Symbol("emittedEnd"),zn=Symbol("emit"),Pe=Symbol("unzip"),Ns=Symbol("consumeChunk"),Ms=Symbol("consumeChunkSub"),dc=Symbol("consumeBody"),Lu=Symbol("consumeMeta"),Nu=Symbol("consumeHeader"),mi=Symbol("consuming"),lc=Symbol("bufferConcat"),Bs=Symbol("maybeEnd"),_r=Symbol("writing"),pn=Symbol("aborted"),Fs=Symbol("onDone"),Un=Symbol("sawValidEntry"),zs=Symbol("sawNullBlock"),Us=Symbol("sawEOF"),Mu=Symbol("closeStream"),c_=()=>!0,Oi=class extends Aw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[$t]=[];[me];[Kt];[Fn];[ft]="begin";[xn]="";[Pt];[gi];[hn]=!1;[Pe];[pn]=!1;[Un];[zs]=!1;[Us]=!1;[_r]=!1;[mi]=!1;[cc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Fs,()=>{(this[ft]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Fs,t.ondone):this.on(Fs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||o_,this.filter=typeof t.filter=="function"?t.filter:c_;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[Mu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){ao(this,t,e,r)}[Nu](t,e){this[Un]===void 0&&(this[Un]=!1);let r;try{r=new Wn(t,e,this[Pt],this[gi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[zs]?(this[Us]=!0,this[ft]==="begin"&&(this[ft]="header"),this[zn]("eof")):(this[zs]=!0,this[zn]("nullBlock"));else if(this[zs]=!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 s_(r,this[Pt],this[gi]);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[ft]="ignore",o.resume()):o.size>0&&(this[xn]="",o.on("data",c=>this[xn]+=c),this[ft]="meta"):(this[Pt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[ft]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ft]="body":(this[ft]="header",o.end()),this[Kt]?this[$t].push(o):(this[$t].push(o),this[ac]())))}}}[Mu](){queueMicrotask(()=>this.emit("close"))}[Du](t){let e=!0;if(!t)this[Kt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Kt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ac]()),e=!1);return e}[ac](){do;while(this[Du](this[$t].shift()));if(this[$t].length===0){let t=this[Kt];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[dc](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[ft]="header",this[Fn]=void 0,r.end()),o.length}[Lu](t,e){let r=this[Fn],i=this[dc](t,e);return!this[Fn]&&r&&this[Ou](r),i}[zn](t,e,r){this[$t].length===0&&!this[Kt]?this.emit(t,e,r):this[$t].push([t,e,r])}[Ou](t){switch(this[zn]("meta",this[xn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Pt]=eo.parse(this[xn],this[Pt],!1);break;case"GlobalExtendedHeader":this[gi]=eo.parse(this[xn],this[gi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Pt]??Object.create(null);this[Pt]=e,e.path=this[xn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Pt]||Object.create(null);this[Pt]=e,e.linkpath=this[xn].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[me]&&(t=Buffer.concat([this[me],t]),this[me]=void 0),t.length<a_)return this[me]=t,r?.(),!0;for(let d=0;this[Pe]===void 0&&d<Ec.length;d++)t[d]!==Ec[d]&&(this[Pe]=!1);let o=!1;if(this[Pe]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<vc.length;d++)if(t[d]!==vc[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Pe]===!1&&c)if(t.length<512)if(this[hn])this.brotli=!0;else return this[me]=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[hn];this[hn]=!1,this[Pe]=this[Pe]===void 0?new Dw({}):o?new Mw({}):new Lw({}),this[Pe].on("data",x=>this[Ns](x)),this[Pe].on("error",x=>this.abort(x)),this[Pe].on("end",()=>{this[hn]=!0,this[Ns]()}),this[_r]=!0;let u=!!this[Pe][d?"end":"write"](t);return this[_r]=!1,r?.(),u}}this[_r]=!0,this[Pe]?this[Pe].write(t):this[Ns](t),this[_r]=!1;let i=this[$t].length>0?!1:this[Kt]?this[Kt].flowing:!0;return!i&&this[$t].length===0&&this[Kt]?.once("drain",()=>this.emit("drain")),r?.(),i}[lc](t){t&&!this[pn]&&(this[me]=this[me]?Buffer.concat([this[me],t]):t)}[Bs](){if(this[hn]&&!this[cc]&&!this[pn]&&!this[mi]){this[cc]=!0;let t=this[Fn];if(t&&t.blockRemain){let e=this[me]?this[me].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[me]&&t.write(this[me]),t.end()}this[zn](Fs)}}[Ns](t){if(this[mi]&&t)this[lc](t);else if(!t&&!this[me])this[Bs]();else if(t){if(this[mi]=!0,this[me]){this[lc](t);let e=this[me];this[me]=void 0,this[Ms](e)}else this[Ms](t);for(;this[me]&&this[me]?.length>=512&&!this[pn]&&!this[Us];){let e=this[me];this[me]=void 0,this[Ms](e)}this[mi]=!1}(!this[me]||this[hn])&&this[Bs]()}[Ms](t){let e=0,r=t.length;for(;e+512<=r&&!this[pn]&&!this[Us];)switch(this[ft]){case"begin":case"header":this[Nu](t,e),e+=512;break;case"ignore":case"body":e+=this[dc](t,e);break;case"meta":e+=this[Lu](t,e);break;default:throw new Error("invalid state: "+this[ft])}e<r&&(this[me]=this[me]?Buffer.concat([t.subarray(e),this[me]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[pn]||(this[Pe]?(t&&this[Pe].write(t),this[Pe].end()):(this[hn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Bs]())),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)},d_=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},wf=(t,e)=>{let r=new Map(e.map(c=>[Ai(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||ww(c).root||".",x;if(c===u)x=!1;else{let h=r.get(c);x=h!==void 0?h:o(mw(c),u)}return r.set(c,x),x};t.filter=i?(c,d)=>i(c,d)&&o(Ai(c)):c=>o(Ai(c))},l_=t=>{let e=new Oi(t),r=t.file,i;try{i=Ir.openSync(r,"r");let o=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Ir.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(c);for(;d<o.size;){let x=Ir.readSync(i,u,0,c,d);if(x===0)break;d+=x,e.write(u.subarray(0,x))}e.end()}}finally{if(typeof i=="number")try{Ir.closeSync(i)}catch{}}},u_=(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),Ir.stat(o,(u,x)=>{if(u)d(u);else{let h=new Hc(o,{readSize:i,size:x.size});h.on("error",d),h.pipe(r)}})})},Cr=Li(l_,u_,t=>new Oi(t),t=>new Oi(t),(t,e)=>{e?.length&&wf(t,e),t.noResume||d_(t)}),_f=(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:x_,parse:Fu}=f_,Wc=t=>{let e="",r=Fu(t);for(;x_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Fu(t)}return[e,t]},co=["|","<",">","?",":"],Kc=co.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),h_=new Map(co.map((t,e)=>[t,Kc[e]])),p_=new Map(Kc.map((t,e)=>[t,co[e]])),zu=t=>co.reduce((e,r)=>e.split(r).join(h_.get(r)),t),g_=t=>Kc.reduce((e,r)=>e.split(r).join(p_.get(r)),t),yf=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Ai(e)+"/"+t):Q(t),m_=16*1024*1024,Uu=Symbol("process"),Hu=Symbol("file"),Gu=Symbol("directory"),Sc=Symbol("symlink"),qu=Symbol("hardlink"),wi=Symbol("header"),Ks=Symbol("read"),Ic=Symbol("lstat"),$s=Symbol("onlstat"),Ac=Symbol("onread"),kc=Symbol("onreadlink"),Tc=Symbol("openfile"),Cc=Symbol("onopenfile"),yn=Symbol("close"),no=Symbol("mode"),Pc=Symbol("awaitDrain"),uc=Symbol("ondrain"),Dt=Symbol("prefix"),bf=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=Gc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||m_,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Q(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Q(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=Wc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=g_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||Bu.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[$s](o):this[Ic]()}warn(t,e,r={}){return ao(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Ic](){Rt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[$s](e)})}[$s](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=y_(t),this.emit("stat",t),this[Uu]()}[Uu](){switch(this.type){case"File":return this[Hu]();case"Directory":return this[Gu]();case"SymbolicLink":return this[Sc]();default:return this.end()}}[no](t){return _f(t,this.type==="Directory",this.portable)}[Dt](t){return yf(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 Wn({path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,mode:this[no](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 eo({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Gu](){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()}[Sc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[kc](e)})}[kc](t){this.linkpath=Q(t),this[wi](),this.end()}[qu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Bu.relative(this.cwd,t)),this.stat.size=0,this[wi](),this.end()}[Hu](){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[qu](e);this.linkCache.set(t,this.absolute)}if(this[wi](),this.stat.size===0)return this.end();this[Tc]()}[Tc](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Cc](e)})}[Cc](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[Ks]()}[Ks](){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[Ac](d)})}[yn](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[Ac](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[uc]():this[Pc](()=>this[uc]())}[Pc](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)}[uc](){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[Ks]()}},w_=class extends bf{sync=!0;[Ic](){this[$s](Rt.lstatSync(this.absolute))}[Sc](){this[kc](Rt.readlinkSync(this.absolute))}[Tc](){this[Cc](Rt.openSync(this.absolute,"r"))}[Ks](){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[Ac](d),t=!1}finally{if(t)try{this[yn](()=>{})}catch{}}}[Pc](t){t()}[yn](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},__=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 ao(this,t,e,r)}constructor(t,e={}){let r=Gc(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[no](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]=Wc(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[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new eo({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Dt](t){return yf(t,this.prefix)}[no](t){return _f(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},y_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",b_=class Ar{tail;head;length=0;static create(e=[]){return new Ar(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)v_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)S_(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new Ar;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new Ar;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Ar;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Ar;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let d=0;o&&d<e;d++)o=o.next;let c=[];for(let d=0;o&&d<r;d++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=E_(this,o,d);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=r,this.tail=e,this}};function E_(t,e,r){let i=e,o=e?e.next:t.head,c=new $c(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function v_(t,e){t.tail=new $c(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function S_(t,e){t.head=new $c(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var $c=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}},Wu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Ku=Buffer.alloc(1024),Vs=Symbol("onStat"),_i=Symbol("ended"),bt=Symbol("queue"),yi=Symbol("pendingLinks"),gn=Symbol("current"),Hn=Symbol("process"),bi=Symbol("processing"),Hs=Symbol("processJob"),Et=Symbol("jobs"),fc=Symbol("jobDone"),Ys=Symbol("addFSEntry"),$u=Symbol("addTarEntry"),Rc=Symbol("stat"),Dc=Symbol("readdir"),Js=Symbol("onreaddir"),Xs=Symbol("pipe"),Vu=Symbol("entry"),xc=Symbol("entryOpt"),Zs=Symbol("writeEntryClass"),Ef=Symbol("write"),hc=Symbol("ondrain"),lo=class extends Kn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Zs];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[Zs]=bf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new Rw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Ow(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Nw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[hc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[hc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[bt]=new b_,this[Et]=0,this.jobs=Number(t.jobs)||4,this[bi]=!1,this[_i]=!1}[Ef](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[Ys](t):this[$u](t),this.flowing}[$u](t){let e=Q(ju.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Wu(t.path,e);r.entry=new __(t,this[xc](r)),r.entry.on("end",()=>this[fc](r)),this[Et]+=1,this[bt].push(r)}this[Hn]()}[Ys](t){let e=Q(ju.resolve(this.cwd,t));this[bt].push(new Wu(t,e)),this[Hn]()}[Rc](t){t.pending=!0,this[Et]+=1;let e=this.follow?"stat":"lstat";to[e](t.absolute,(r,i)=>{t.pending=!1,this[Et]-=1,r?this.emit("error",r):this[Vs](t,i)})}[Vs](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[Hs](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]()}[Dc](t){t.pending=!0,this[Et]+=1,to.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[Hn]()}[Hn](){if(!this[bi]){this[bi]=!0;for(let t=this[bt].head;t&&this[Et]<this.jobs;t=t.next)if(this[Hs](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(Ku):(super.write(Ku),super.end()))}}get[gn](){return this[bt]&&this[bt].head&&this[bt].head.value}[fc](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[Hs](o)}}this[Hn]()}[Hs](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[Xs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Vs](t,e):this[Rc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Js](t,e):this[Dc](t),!t.readdir)return}if(t.entry=this[Vu](t),!t.entry){t.ignore=!0;return}t===this[gn]&&!t.piped&&this[Xs](t)}}}[xc](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}}[Vu](t){this[Et]+=1;try{return new this[Zs](t.path,this[xc](t)).on("end",()=>this[fc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[hc](){this[gn]&&this[gn].entry&&this[gn].entry.resume()}[Xs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ys](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={}){ao(this,t,e,r)}},Vc=class extends lo{sync=!0;constructor(t){super(t),this[Zs]=w_}pause(){}resume(){}[Rc](t){let e=this.follow?"statSync":"lstatSync";this[Vs](t,to[e](t.absolute))}[Dc](t){this[Js](t,to.readdirSync(t.absolute))}[Xs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ys](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[Ef](i)})}},I_=(t,e)=>{let r=new Vc(t),i=new df(t.file,{mode:t.mode||438});r.pipe(i),vf(r,e)},A_=(t,e)=>{let r=new lo(t),i=new so(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 Sf(r,e).catch(c=>r.emit("error",c)),o},vf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:lf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},Sf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:lf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},k_=(t,e)=>{let r=new Vc(t);return vf(r,e),r},T_=(t,e)=>{let r=new lo(t);return Sf(r,e).catch(i=>r.emit("error",i)),r},gA=Li(I_,A_,k_,T_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),P_=process.env.__FAKE_PLATFORM__||process.platform,Tf=P_==="win32",{O_CREAT:Cf,O_NOFOLLOW:Yu,O_TRUNC:Pf,O_WRONLY:Rf}=kf.constants,Df=Number(process.env.__FAKE_FS_O_FILENAME__)||kf.constants.UV_FS_O_FILEMAP||0,R_=Tf&&!!Df,D_=512*1024,O_=Df|Pf|Cf|Rf,Ju=!Tf&&typeof Yu=="number"?Yu|Pf|Cf|Rf:null,Of=Ju!==null?()=>Ju:R_?t=>t<D_?O_:"w":()=>"w",Oc=(t,e,r)=>{try{return uo.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},ro=(t,e,r,i)=>{uo.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},L_=(t,e,r,i,o)=>{if(e.isDirectory())Lf(ki.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=ki.resolve(t,e.name);ro(d,r,i,o)});else{let c=ki.resolve(t,e.name);ro(c,r,i,o)}},Lf=(t,e,r,i)=>{uo.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 ro(t,e,r,i);let d=c.length,u=null,x=h=>{if(!u){if(h)return i(u=h);if(--d===0)return ro(t,e,r,i)}};for(let h of c)L_(t,h,e,r,x)})},N_=(t,e,r,i)=>{e.isDirectory()&&Nf(ki.resolve(t,e.name),r,i),Oc(ki.resolve(t,e.name),r,i)},Nf=(t,e,r)=>{let i;try{i=uo.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Oc(t,e,r);throw c}for(let o of i)N_(t,o,e,r);return Oc(t,e,r)},Mf=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"}},fo=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},B_=(t,e)=>{ct.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Mf(t,r?.code||"ENOTDIR")),e(r)})},F_=(t,e,r)=>{t=Q(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,d=e.uid,u=e.gid,x=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),h=e.preserve,m=e.unlink,w=Q(e.cwd),I=(S,A)=>{S?r(S):A&&x?Lf(A,d,u,k=>I(k)):c?ct.chmod(t,o,r):r()};if(t===w)return B_(t,I);if(h)return M_.mkdir(t,{mode:o,recursive:!0}).then(S=>I(null,S??void 0),I);let b=Q(io.relative(w,t)).split("/");Lc(w,b,o,m,w,void 0,I)},Lc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),x=Q(io.resolve(t+"/"+u));ct.mkdir(x,r,Bf(x,e,r,i,o,c,d))},Bf=(t,e,r,i,o,c,d)=>u=>{u?ct.lstat(t,(x,h)=>{if(x)x.path=x.path&&Q(x.path),d(x);else if(h.isDirectory())Lc(t,e,r,i,o,c,d);else if(i)ct.unlink(t,m=>{if(m)return d(m);ct.mkdir(t,r,Bf(t,e,r,i,o,c,d))});else{if(h.isSymbolicLink())return d(new fo(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Lc(t,e,r,i,o,c,d))},z_=t=>{let e=!1,r;try{e=ct.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Mf(t,r??"ENOTDIR")}},U_=(t,e)=>{t=Q(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,d=e.gid,u=typeof c=="number"&&typeof d=="number"&&(c!==e.processUid||d!==e.processGid),x=e.preserve,h=e.unlink,m=Q(e.cwd),w=S=>{S&&u&&Nf(S,c,d),o&&ct.chmodSync(t,i)};if(t===m)return z_(m),w();if(x)return w(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let I=Q(io.relative(m,t)).split("/"),b;for(let S=I.shift(),A=m;S&&(A+="/"+S);S=I.shift()){A=Q(io.resolve(A));try{ct.mkdirSync(A,i),b=b||A}catch{let k=ct.lstatSync(A);if(k.isDirectory())continue;if(h){ct.unlinkSync(A),ct.mkdirSync(A,i),b=b||A;continue}else if(k.isSymbolicLink())return new fo(A,A+"/"+I.join("/"))}}return w(b)},pc=Object.create(null),Xu=1e4,yr=new Set,H_=t=>{yr.has(t)?yr.delete(t):pc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=pc[t],r=yr.size-Xu;if(r>Xu/10){for(let i of yr)if(yr.delete(i),delete pc[i],--r<=0)break}return e},G_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,q_=G_==="win32",j_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Ff(i,r)),e.push(r||"/"),e},[]),W_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=q_?["win32 parallelization disabled"]:t.map(i=>Ai(Ff(H_(i))));let r=new Set(t.map(i=>j_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let d=this.#e.get(c);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(c);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let x of u)o.add(x)}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 x=d[0];typeof x=="function"&&o.add(x)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},K_=()=>process.umask(),Zu=Symbol("onEntry"),Nc=Symbol("checkFs"),Qu=Symbol("checkFs2"),Mc=Symbol("isReusable"),xt=Symbol("makeFs"),Bc=Symbol("file"),Fc=Symbol("directory"),Qs=Symbol("link"),ef=Symbol("symlink"),tf=Symbol("hardlink"),Si=Symbol("ensureNoSymlink"),nf=Symbol("unsupported"),rf=Symbol("checkPath"),gc=Symbol("stripAbsolutePath"),bn=Symbol("mkdir"),qe=Symbol("onError"),Gs=Symbol("pending"),sf=Symbol("pend"),br=Symbol("unpend"),mc=Symbol("ended"),wc=Symbol("maybeClose"),zc=Symbol("skip"),Ti=Symbol("doChown"),Ci=Symbol("uid"),Pi=Symbol("gid"),Ri=Symbol("checkedCwd"),$_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Di=$_==="win32",V_=1024,Y_=(t,e)=>{if(!Di)return ie.unlink(t,e);let r=t+".DELETE."+Af(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},J_=t=>{if(!Di)return ie.unlinkSync(t);let e=t+".DELETE."+Af(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},of=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Yc=class extends Oi{[mc]=!1;[Ri]=!1;[Gs]=0;reservations=new W_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[mc]=!0,this[wc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:V_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Di,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Me.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:K_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Zu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[wc](){this[mc]&&this[Gs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[gc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Wc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Di&&/^[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=Me.posix.dirname(t.path),x=Me.posix.normalize(Me.posix.join(u,d.join("/")));if(x.startsWith("../")||x==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[rf](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[gc](t,"path")||!this[gc](t,"linkpath"))return!1;if(t.absolute=Me.isAbsolute(t.path)?Q(Me.resolve(t.path)):Q(Me.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}=Me.win32.parse(String(t.absolute));t.absolute=i+zu(String(t.absolute).slice(i.length));let{root:o}=Me.win32.parse(t.path);t.path=o+zu(t.path.slice(o.length))}return!0}[Zu](t){if(!this[rf](t))return t.resume();switch(C_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Nc](t);default:return this[nf](t)}}[qe](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[br](),e.resume())}[bn](t,e,r){F_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[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 of(this.uid,t.uid,this.processUid)}[Pi](t){return of(this.gid,t.gid,this.processGid)}[Bc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new so(String(t.absolute),{flags:Of(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[qe](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[qe](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,x=>{x?this[qe](x,t):this[br](),e()})};i.on("finish",()=>{let u=String(t.absolute),x=i.fd;if(typeof x=="number"&&t.mtime&&!this.noMtime){o++;let h=t.atime||new Date,m=t.mtime;ie.futimes(x,h,m,w=>w?ie.utimes(u,h,m,I=>c(I&&w)):c())}if(typeof x=="number"&&this[Ti](t)){o++;let h=this[Ci](t),m=this[Pi](t);typeof h=="number"&&typeof m=="number"&&ie.fchown(x,h,m,w=>w?ie.chown(u,h,m,I=>c(I&&w)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[qe](u,t),e()}),t.pipe(d)),d.pipe(i)}[Fc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[bn](String(t.absolute),r,i=>{if(i){this[qe](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[br](),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[Pi](t)),c)),c()})}[nf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[ef](t,e){let r=Q(Me.relative(this.cwd,Me.resolve(Me.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Si](t,this.cwd,r,()=>this[Qs](t,String(t.linkpath),"symlink",e),i=>{this[qe](i,t),e()})}[tf](t,e){let r=Q(Me.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Si](t,this.cwd,i,()=>this[Qs](t,r,"link",e),o=>{this[qe](o,t),e()})}[Si](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Me.resolve(e,c);ie.lstat(d,(u,x)=>{if(u)return i();if(x?.isSymbolicLink())return o(new fo(d,Me.resolve(d,r.join("/"))));this[Si](t,d,r,i,o)})}[sf](){this[Gs]++}[br](){this[Gs]--,this[wc]()}[zc](t){this[br](),t.resume()}[Mc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Di}[Nc](t){this[sf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Qu](t,r))}[Qu](t,e){let r=d=>{e(d)},i=()=>{this[bn](this.cwd,this.dmode,d=>{if(d){this[qe](d,t),r();return}this[Ri]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Me.dirname(String(t.absolute)));if(d!==this.cwd)return this[bn](d,this.dmode,u=>{if(u){this[qe](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[zc](t),r();return}if(d||this[Mc](t,u))return this[xt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let x=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,h=m=>this[xt](m??null,t,r);return x?ie.chmod(String(t.absolute),Number(t.mode),h):h()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),x=>this[xt](x??null,t,r))}if(t.absolute===this.cwd)return this[xt](null,t,r);Y_(String(t.absolute),x=>this[xt](x??null,t,r))})};this[Ri]?o():i()}[xt](t,e,r){if(t){this[qe](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Bc](e,r);case"Link":return this[tf](e,r);case"SymbolicLink":return this[ef](e,r);case"Directory":case"GNUDumpDir":return this[Fc](e,r)}}[Qs](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[qe](o,t):(this[br](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},zf=class extends Yc{sync=!0;[xt](t,e){return super[xt](t,e,()=>{})}[Nc](t){if(!this[Ri]){let o=this[bn](this.cwd,this.dmode);if(o)return this[qe](o,t);this[Ri]=!0}if(t.absolute!==this.cwd){let o=Q(Me.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[bn](o,this.dmode);if(c)return this[qe](c,t)}}let[e,r]=Ei(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[zc](t);if(e||this[Mc](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(()=>J_(String(t.absolute)));this[xt](i,t)}[Bc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{ie.closeSync(o)}catch(x){u=x}(d||u)&&this[qe](d||u,t),e()},o;try{o=ie.openSync(String(t.absolute),Of(t.size),r)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[qe](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,x=t.mtime;try{ie.futimesSync(o,u,x)}catch(h){try{ie.utimesSync(String(t.absolute),u,x)}catch{d=h}}}if(this[Ti](t)){let u=this[Ci](t),x=this[Pi](t);try{ie.fchownSync(o,Number(u),Number(x))}catch(h){try{ie.chownSync(String(t.absolute),Number(u),Number(x))}catch{d=d||h}}}i(d)})}[Fc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[bn](String(t.absolute),r);if(i){this[qe](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ti](t))try{ie.chownSync(String(t.absolute),Number(this[Ci](t)),Number(this[Pi](t)))}catch{}e(),t.resume()}[bn](t,e){try{return U_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[Si](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Me.resolve(c,d);let[u,x]=Ei(()=>ie.lstatSync(c));if(u)return i();if(x.isSymbolicLink())return o(new fo(c,Me.resolve(e,r.join("/"))))}i()}[Qs](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[qe](c,t)}}},X_=t=>{let e=new zf(t),r=t.file,i=If.statSync(r),o=t.maxReadSize||16*1024*1024;new gw(r,{readSize:o,size:i.size}).pipe(e)},Z_=(t,e)=>{let r=new Yc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),If.stat(o,(u,x)=>{if(u)d(u);else{let h=new Hc(o,{readSize:i,size:x.size});h.on("error",d),h.pipe(r)}})})},Uf=Li(X_,Z_,t=>new zf(t),t=>new Yc(t),(t,e)=>{e?.length&&wf(t,e)}),Q_=(t,e)=>{let r=new Vc(t),i=!0,o,c;try{try{o=at.openSync(t.file,"r+")}catch(x){if(x?.code==="ENOENT")o=at.openSync(t.file,"w+");else throw x}let d=at.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let m=0,w=0;m<512;m+=w){if(w=at.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(!w)break e}let x=new Wn(u);if(!x.cksumValid)break;let h=512*Math.ceil((x.size||0)/512);if(c+h+512>d.size)break;c+=h,t.mtimeCache&&x.mtime&&t.mtimeCache.set(String(x.path),x.mtime)}i=!1,ey(t,r,c,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},ey=(t,e,r,i,o)=>{let c=new df(t.file,{fd:i,start:r});e.pipe(c),ny(e,o)},ty=(t,e)=>{e=Array.from(e);let r=new lo(t),i=(o,c,d)=>{let u=(I,b)=>{I?at.close(o,S=>d(I)):d(null,b)},x=0;if(c===0)return u(null,0);let h=0,m=Buffer.alloc(512),w=(I,b)=>{if(I||b===void 0)return u(I);if(h+=b,h<512&&b)return at.read(o,m,h,m.length-h,x+h,w);if(x===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(h<512)return u(null,x);let S=new Wn(m);if(!S.cksumValid)return u(null,x);let A=512*Math.ceil((S.size??0)/512);if(x+A+512>c||(x+=A+512,x>=c))return u(null,x);t.mtimeCache&&S.mtime&&t.mtimeCache.set(String(S.path),S.mtime),h=0,at.read(o,m,0,512,x,w)};at.read(o,m,0,512,x,w)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(x,h)=>{if(x&&x.code==="ENOENT"&&d==="r+")return d="w+",at.open(t.file,d,u);if(x||!h)return c(x);at.fstat(h,(m,w)=>{if(m)return at.close(h,()=>c(m));i(h,w.size,(I,b)=>{if(I)return c(I);let S=new so(t.file,{fd:h,start:b});r.pipe(S),S.on("error",c),S.on("close",o),ry(r,e)})})};at.open(t.file,d,u)})},ny=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:Hf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},ry=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:Hf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},vi=Li(Q_,ty,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Sw(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")}),RA=Li(vi.syncFile,vi.asyncFile,vi.syncNoFile,vi.asyncNoFile,(t,e=[])=>{vi.validate?.(t,e),iy(t)}),iy=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,i)=>e(r,i)&&!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0)):(r,i)=>!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0))};qt();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 xo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Gf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ho(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function qf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function jf(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();Ke();te();Ce();Ke();function Pr(t,e){if(xo(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 Ek}from"node:fs";import{dirname as Sk,join as Ik}from"node:path";import{fileURLToPath as kk}from"node:url";var Lt="0.2.7-beta.1";import{mkdir as by,rm as d0}from"node:fs/promises";import{join as Ui}from"node:path";Gt();import{readFileSync as fy}from"node:fs";var xy=384;async function Jc(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await fr(t.agentEnvFile,r,{mode:xy})}function Mi(t){try{let e=JSON.parse(fy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Vf(t,e,r={},i=o=>o){return{...i({...t,...Mi(e)}),...r}}Gt();function Bi(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(hy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return kI(t.homeDir,".coze","bridge","task.xml")},async install(t){let n=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await Hp("schtasks",["/Create","/SC","ONLOGON","/TN",va,"/TR",n,"/RU",t.userName,"/F"]),ul.info("task scheduler entry created",{task:va,logFile:t.logFile})},async uninstall(t){await Hp("schtasks",["/Delete","/TN",va,"/F"]).catch(e=>ul.warn("schtasks /Delete failed (ignored)",{err:String(e)})),ul.info("task scheduler entry removed",{task:va})}}});var jp={};Ba(jp,{buildContext:()=>OI,getSupervisor:()=>PI,launchdSupervisor:()=>dl,systemdSupervisor:()=>ll,taskSchedulerSupervisor:()=>fl});import{homedir as TI,userInfo as RI}from"node:os";function PI(t=process.platform){switch(t){case"darwin":return dl;case"linux":return ll;case"win32":return fl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function DI(){let t={};for(let e of CI){let n=process.env[e];n&&(t[e]=n)}return t}function OI(){let t=Y();return{nodeBin:process.execPath,entry:el(t),logFile:t.logFile,homeDir:TI(),userName:RI().username,isRoot:process.getuid?.()===0,env:DI()}}var CI,Kp=it(()=>{"use strict";Pe();ha();zp();Gp();qp();CI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();ln();var Hl=K("acp-installer-warmup"),mg=["claude-code","codex"];async function ql(t={}){let e=t.ensure??lr,i=(await Promise.allSettled(mg.map(async o=>{let c=await e(o);Hl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Hl.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))})}Kt();ne();import{readdir as Dg}from"node:fs/promises";import{mkdir as $l,readFile as Pg,writeFile as Vl}from"node:fs/promises";import{join as ja}from"node:path";var Cg={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function hr(t,e,n){await $l(t,{recursive:!0});let i=Cg[e],o=ja(t,i);return await Vl(o,n??"","utf8"),o}async function Ka(t,e,n){let i=ja(t,".claude");await $l(i,{recursive:!0});let o=ja(i,"settings.local.json"),c={};try{let u=await Pg(o,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(c=h)}catch{}let l=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")l.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");l.defaultMode===void 0&&(l.defaultMode=n)}return c.permissions=l,await Vl(o,JSON.stringify(c,null,2),"utf8"),o}var et=K("agent-detail-sync"),Og=6e4,Lg=5*6e4,ks=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await Dg(n)}catch(o){et.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}et.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await Se(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){et.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(l){et.warn("detail sync failed for agent, skipping",{agentId:o,err:String(l)})}}})),et.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&n.push(i);if(n.length!==0){et.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){et.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await Se(e,this.opts.paths);if(!i){et.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){et.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,Lg):Og;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(o.agentId&&o.agentId!==e){et.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,l=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,l=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(et.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&et.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){et.debug("detail sync: no diff",{agentId:e});return}await Ge(i,this.opts.paths),et.info("detail sync: config updated",{agentId:e,identityChanged:l,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),et.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await hr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var gd=qt(ku(),1);import{createHash as Ey}from"node:crypto";import{lstat as dd,mkdir as ld,readFile as Eo,readdir as _0,rm as ud,stat as pd,writeFile as fd}from"node:fs/promises";import{homedir as vy}from"node:os";import{basename as m0,dirname as Sy,join as he,normalize as Iy,relative as md,resolve as hd,sep as y0}from"node:path";import{Readable as b0}from"node:stream";import{pipeline as E0}from"node:stream/promises";import nw from"events";import ot from"fs";import{EventEmitter as jc}from"node:events";import df from"node:stream";import{StringDecoder as rw}from"node:string_decoder";import ff from"node:path";import Ir from"node:fs";import{dirname as mw,parse as gw}from"path";import{EventEmitter as Iw}from"events";import Ic from"assert";import{Buffer as qn}from"buffer";import*as Du from"zlib";import Aw from"zlib";import{posix as wr}from"node:path";import{basename as Qw}from"node:path";import so from"fs";import Ot from"fs";import zu from"path";import{win32 as u_}from"node:path";import Wu from"path";import kf from"node:fs";import T_ from"node:assert";import{randomBytes as Tf}from"node:crypto";import se from"node:fs";import Be from"node:path";import Rf from"fs";import po from"node:fs";import Ri from"node:path";import lt from"node:fs";import N_ from"node:fs/promises";import co from"node:path";import{join as Uf}from"node:path";import dt from"node:fs";import qf from"node:path";var ew=Object.defineProperty,tw=(t,e)=>{for(var n in e)ew(t,n,{get:e[n],enumerable:!0})},Tu=typeof process=="object"&&process?process:{stdout:null,stderr:null},iw=t=>!!t&&typeof t=="object"&&(t instanceof Wn||t instanceof df||sw(t)||ow(t)),sw=t=>!!t&&typeof t=="object"&&t instanceof jc&&typeof t.pipe=="function"&&t.pipe!==df.Writable.prototype.pipe,ow=t=>!!t&&typeof t=="object"&&t instanceof jc&&typeof t.write=="function"&&typeof t.end=="function",Wt=Symbol("EOF"),$t=Symbol("maybeEmitEnd"),fn=Symbol("emittedEnd"),Ds=Symbol("emittingEnd"),fi=Symbol("emittedError"),Os=Symbol("closed"),Ru=Symbol("read"),Ls=Symbol("flush"),Pu=Symbol("flushChunk"),Et=Symbol("encoding"),gr=Symbol("decoder"),He=Symbol("flowing"),hi=Symbol("paused"),Er=Symbol("resume"),qe=Symbol("buffer"),nt=Symbol("pipes"),je=Symbol("bufferLength"),Ya=Symbol("bufferPush"),Ns=Symbol("bufferShift"),Qe=Symbol("objectMode"),ke=Symbol("destroyed"),Xa=Symbol("error"),Qa=Symbol("emitData"),Cu=Symbol("emitEnd"),ec=Symbol("emitEnd2"),Pt=Symbol("async"),tc=Symbol("abort"),Ms=Symbol("aborted"),xi=Symbol("signal"),Ln=Symbol("dataListeners"),ct=Symbol("discarded"),pi=t=>Promise.resolve().then(t),aw=t=>t(),cw=t=>t==="end"||t==="finish"||t==="prefinish",dw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,lw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),lf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Er](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},uw=class extends lf{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,n){super(t,e,n),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},fw=t=>!!t.objectMode,hw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Wn=class extends jc{[He]=!1;[hi]=!1;[nt]=[];[qe]=[];[Qe];[Et];[Pt];[gr];[Wt]=!1;[fn]=!1;[Ds]=!1;[Os]=!1;[fi]=null;[je]=0;[ke]=!1;[xi];[Ms]=!1;[Ln]=0;[ct]=!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");fw(e)?(this[Qe]=!0,this[Et]=null):hw(e)?(this[Et]=e.encoding,this[Qe]=!1):(this[Qe]=!1,this[Et]=null),this[Pt]=!!e.async,this[gr]=this[Et]?new rw(this[Et]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[qe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[nt]});let{signal:n}=e;n&&(this[xi]=n,n.aborted?this[tc]():n.addEventListener("abort",()=>this[tc]()))}get bufferLength(){return this[je]}get encoding(){return this[Et]}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[Qe]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Pt]}set async(t){this[Pt]=this[Pt]||!!t}[tc](){this[Ms]=!0,this.emit("abort",this[xi]?.reason),this.destroy(this[xi]?.reason)}get aborted(){return this[Ms]}set aborted(t){}write(t,e,n){if(this[Ms])return!1;if(this[Wt])throw new Error("write after end");if(this[ke])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[Pt]?pi:aw;if(!this[Qe]&&!Buffer.isBuffer(t)){if(lw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(dw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Qe]?(this[He]&&this[je]!==0&&this[Ls](!0),this[He]?this.emit("data",t):this[Ya](t),this[je]!==0&&this.emit("readable"),n&&i(n),this[He]):t.length?(typeof t=="string"&&!(e===this[Et]&&!this[gr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Et]&&(t=this[gr].write(t)),this[He]&&this[je]!==0&&this[Ls](!0),this[He]?this.emit("data",t):this[Ya](t),this[je]!==0&&this.emit("readable"),n&&i(n),this[He]):(this[je]!==0&&this.emit("readable"),n&&i(n),this[He])}read(t){if(this[ke])return null;if(this[ct]=!1,this[je]===0||t===0||t&&t>this[je])return this[$t](),null;this[Qe]&&(t=null),this[qe].length>1&&!this[Qe]&&(this[qe]=[this[Et]?this[qe].join(""):Buffer.concat(this[qe],this[je])]);let e=this[Ru](t||null,this[qe][0]);return this[$t](),e}[Ru](t,e){if(this[Qe])this[Ns]();else{let n=e;t===n.length||t===null?this[Ns]():typeof n=="string"?(this[qe][0]=n.slice(t),e=n.slice(0,t),this[je]-=t):(this[qe][0]=n.subarray(t),e=n.subarray(0,t),this[je]-=t)}return this.emit("data",e),!this[qe].length&&!this[Wt]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[Wt]=!0,this.writable=!1,(this[He]||!this[hi])&&this[$t](),this}[Er](){this[ke]||(!this[Ln]&&!this[nt].length&&(this[ct]=!0),this[hi]=!1,this[He]=!0,this.emit("resume"),this[qe].length?this[Ls]():this[Wt]?this[$t]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[He]=!1,this[hi]=!0,this[ct]=!1}get destroyed(){return this[ke]}get flowing(){return this[He]}get paused(){return this[hi]}[Ya](t){this[Qe]?this[je]+=1:this[je]+=t.length,this[qe].push(t)}[Ns](){return this[Qe]?this[je]-=1:this[je]-=this[qe][0].length,this[qe].shift()}[Ls](t=!1){do;while(this[Pu](this[Ns]())&&this[qe].length);!t&&!this[qe].length&&!this[Wt]&&this.emit("drain")}[Pu](t){return this.emit("data",t),this[He]}pipe(t,e){if(this[ke])return t;this[ct]=!1;let n=this[fn];return e=e||{},t===Tu.stdout||t===Tu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[nt].push(e.proxyErrors?new uw(this,t,e):new lf(this,t,e)),this[Pt]?pi(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[nt].find(n=>n.dest===t);e&&(this[nt].length===1?(this[He]&&this[Ln]===0&&(this[He]=!1),this[nt]=[]):this[nt].splice(this[nt].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[ct]=!1,this[Ln]++,!this[nt].length&&!this[He]&&this[Er]();else if(t==="readable"&&this[je]!==0)super.emit("readable");else if(cw(t)&&this[fn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[fi]){let i=e;this[Pt]?pi(()=>i.call(this,this[fi])):i.call(this,this[fi])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Ln]=this.listeners("data").length,this[Ln]===0&&!this[ct]&&!this[nt].length&&(this[He]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[ct]&&!this[nt].length&&(this[He]=!1)),e}get emittedEnd(){return this[fn]}[$t](){!this[Ds]&&!this[fn]&&!this[ke]&&this[qe].length===0&&this[Wt]&&(this[Ds]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Os]&&this.emit("close"),this[Ds]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==ke&&this[ke])return!1;if(t==="data")return!this[Qe]&&!n?!1:this[Pt]?(pi(()=>this[Qa](n)),!0):this[Qa](n);if(t==="end")return this[Cu]();if(t==="close"){if(this[Os]=!0,!this[fn]&&!this[ke])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[fi]=n,super.emit(Xa,n);let o=!this[xi]||this.listeners("error").length?super.emit("error",n):!1;return this[$t](),o}else if(t==="resume"){let o=super.emit("resume");return this[$t](),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[$t](),i}[Qa](t){for(let n of this[nt])n.dest.write(t)===!1&&this.pause();let e=this[ct]?!1:super.emit("data",t);return this[$t](),e}[Cu](){return this[fn]?!1:(this[fn]=!0,this.readable=!1,this[Pt]?(pi(()=>this[ec]()),!0):this[ec]())}[ec](){if(this[gr]){let e=this[gr].end();if(e){for(let n of this[nt])n.dest.write(e);this[ct]||super.emit("data",e)}}for(let e of this[nt])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Qe]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Qe]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Qe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Et]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ke,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ct]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[Wt])return e();let i,o,c=x=>{this.off("data",l),this.off("end",u),this.off(ke,h),e(),o(x)},l=x=>{this.off("error",c),this.off("end",u),this.off(ke,h),this.pause(),i({value:x,done:!!this[Wt]})},u=()=>{this.off("error",c),this.off("data",l),this.off(ke,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(ke,h),this.once("error",c),this.once("end",u),this.once("data",l)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ct]=!1;let t=!1,e=()=>(this.pause(),this.off(Xa,e),this.off(ke,e),this.off("end",e),t=!0,{done:!0,value:void 0}),n=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Xa,e),this.once(ke,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[ke])return t?this.emit("error",t):this.emit(ke),this;this[ke]=!0,this[ct]=!0,this[qe].length=0,this[je]=0;let e=this;return typeof e.close=="function"&&!this[Os]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return iw}},xw=ot.writev,En=Symbol("_autoClose"),At=Symbol("_close"),mi=Symbol("_ended"),fe=Symbol("_fd"),nc=Symbol("_finished"),Yt=Symbol("_flags"),rc=Symbol("_flush"),vc=Symbol("_handleChunk"),Sc=Symbol("_makeBuf"),ki=Symbol("_mode"),Bs=Symbol("_needDrain"),kr=Symbol("_onerror"),Tr=Symbol("_onopen"),ic=Symbol("_onread"),vr=Symbol("_onwrite"),vn=Symbol("_open"),It=Symbol("_path"),gn=Symbol("_pos"),Ct=Symbol("_queue"),Sr=Symbol("_read"),sc=Symbol("_readSize"),Zt=Symbol("_reading"),gi=Symbol("_remain"),oc=Symbol("_size"),$s=Symbol("_write"),Nn=Symbol("_writing"),Vs=Symbol("_defaultFlag"),Hn=Symbol("_errored"),Kc=class extends Wn{[Hn]=!1;[fe];[It];[sc];[Zt]=!1;[oc];[gi];[En];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[Hn]=!1,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[It]=t,this[sc]=e.readSize||16*1024*1024,this[Zt]=!1,this[oc]=typeof e.size=="number"?e.size:1/0,this[gi]=this[oc],this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[fe]=="number"?this[Sr]():this[vn]()}get fd(){return this[fe]}get path(){return this[It]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[vn](){ot.open(this[It],"r",(t,e)=>this[Tr](t,e))}[Tr](t,e){t?this[kr](t):(this[fe]=e,this.emit("open",e),this[Sr]())}[Sc](){return Buffer.allocUnsafe(Math.min(this[sc],this[gi]))}[Sr](){if(!this[Zt]){this[Zt]=!0;let t=this[Sc]();if(t.length===0)return process.nextTick(()=>this[ic](null,0,t));ot.read(this[fe],t,0,t.length,null,(e,n,i)=>this[ic](e,n,i))}}[ic](t,e,n){this[Zt]=!1,t?this[kr](t):this[vc](e,n)&&this[Sr]()}[At](){if(this[En]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[kr](t){this[Zt]=!0,this[At](),this.emit("error",t)}[vc](t,e){let n=!1;return this[gi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[gi]<=0)&&(n=!1,this[At](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[fe]=="number"&&this[Sr](),!1;case"error":return this[Hn]?!1:(this[Hn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},pw=class extends Kc{[vn](){let t=!0;try{this[Tr](null,ot.openSync(this[It],"r")),t=!1}finally{t&&this[At]()}}[Sr](){let t=!0;try{if(!this[Zt]){this[Zt]=!0;do{let e=this[Sc](),n=e.length===0?0:ot.readSync(this[fe],e,0,e.length,null);if(!this[vc](n,e))break}while(!0);this[Zt]=!1}t=!1}finally{t&&this[At]()}}[At](){if(this[En]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ot.closeSync(t),this.emit("close")}}},lo=class extends nw{readable=!1;writable=!0;[Hn]=!1;[Nn]=!1;[mi]=!1;[Ct]=[];[Bs]=!1;[It];[ki];[En];[fe];[Vs];[Yt];[nc]=!1;[gn];constructor(t,e){e=e||{},super(e),this[It]=t,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[ki]=e.mode===void 0?438:e.mode,this[gn]=typeof e.start=="number"?e.start:void 0,this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[gn]!==void 0?"r+":"w";this[Vs]=e.flags===void 0,this[Yt]=e.flags===void 0?n:e.flags,this[fe]===void 0&&this[vn]()}emit(t,...e){if(t==="error"){if(this[Hn])return!1;this[Hn]=!0}return super.emit(t,...e)}get fd(){return this[fe]}get path(){return this[It]}[kr](t){this[At](),this[Nn]=!0,this.emit("error",t)}[vn](){ot.open(this[It],this[Yt],this[ki],(t,e)=>this[Tr](t,e))}[Tr](t,e){this[Vs]&&this[Yt]==="r+"&&t&&t.code==="ENOENT"?(this[Yt]="w",this[vn]()):t?this[kr](t):(this[fe]=e,this.emit("open",e),this[Nn]||this[rc]())}end(t,e){return t&&this.write(t,e),this[mi]=!0,!this[Nn]&&!this[Ct].length&&typeof this[fe]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[mi]?(this.emit("error",new Error("write() after end()")),!1):this[fe]===void 0||this[Nn]||this[Ct].length?(this[Ct].push(t),this[Bs]=!0,!1):(this[Nn]=!0,this[$s](t),!0)}[$s](t){ot.write(this[fe],t,0,t.length,this[gn],(e,n)=>this[vr](e,n))}[vr](t,e){t?this[kr](t):(this[gn]!==void 0&&typeof e=="number"&&(this[gn]+=e),this[Ct].length?this[rc]():(this[Nn]=!1,this[mi]&&!this[nc]?(this[nc]=!0,this[At](),this.emit("finish")):this[Bs]&&(this[Bs]=!1,this.emit("drain"))))}[rc](){if(this[Ct].length===0)this[mi]&&this[vr](null,0);else if(this[Ct].length===1)this[$s](this[Ct].pop());else{let t=this[Ct];this[Ct]=[],xw(this[fe],t,this[gn],(e,n)=>this[vr](e,n))}}[At](){if(this[En]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},uf=class extends lo{[vn](){let t;if(this[Vs]&&this[Yt]==="r+")try{t=ot.openSync(this[It],this[Yt],this[ki])}catch(e){if(e?.code==="ENOENT")return this[Yt]="w",this[vn]();throw e}else t=ot.openSync(this[It],this[Yt],this[ki]);this[Tr](null,t)}[At](){if(this[En]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ot.closeSync(t),this.emit("close")}}[$s](t){let e=!0;try{this[vr](null,ot.writeSync(this[fe],t,0,t.length,this[gn])),e=!1}finally{if(e)try{this[At]()}catch{}}}},ww=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"]]),_w=t=>!!t.sync&&!!t.file,yw=t=>!t.sync&&!!t.file,bw=t=>!!t.sync&&!t.file,Ew=t=>!t.sync&&!t.file,vw=t=>!!t.file,Sw=t=>ww.get(t)||t,Wc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=Sw(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Mi=(t,e,n,i,o)=>Object.assign((c=[],l,u)=>{Array.isArray(c)&&(l=c,c={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let h=Wc(c);if(o?.(h,l),_w(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,l)}else if(yw(h)){let x=e(h,l);return u?x.then(()=>u(),u):x}else if(bw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(h,l)}else if(Ew(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,l)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:o}),kw=Aw.constants||{ZLIB_VERNUM:4736},Nt=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},kw)),Tw=qn.concat,Ou=Object.getOwnPropertyDescriptor(qn,"concat"),Rw=t=>t,ac=Ou?.writable===!0||Ou?.set!==void 0?t=>{qn.concat=t?Rw:Tw}:t=>{},jn=Symbol("_superWrite"),Fs=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"}},cc=Symbol("flushFlag"),$c=class extends Wn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Du[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Du[e](t)}catch(n){throw new Fs(n,this.constructor)}this.#o=n=>{this.#e||(this.#e=!0,this.close(),this.emit("error",n))},this.#t?.on("error",n=>this.#o(new Fs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Ic(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(qn.alloc(0),{[cc]:t})))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(n)}get ended(){return this.#n}[jn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=qn.from(t,e)),this.#e)return;Ic(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},ac(!0);let l;try{let h=typeof t[cc]=="number"?t[cc]:this.#r;l=this.#t._processChunk(t,h),ac(!1)}catch(h){ac(!1),this.#o(new Fs(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 Fs(h,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let h=l[0];u=this[jn](qn.from(h));for(let x=1;x<l.length;x++)u=this[jn](l[x])}else u=this[jn](qn.from(l));return n&&n(),u}},hf=class extends $c{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Nt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Nt.Z_FINISH,t.fullFlushFlag=Nt.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(Nt.Z_SYNC_FLUSH),Ic(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},Pw=class extends hf{#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)}},Cw=class extends hf{constructor(t){super(t,"Unzip")}},xf=class extends $c{constructor(t,e){t=t||{},t.flush=t.flush||Nt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Nt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Nt.BROTLI_OPERATION_FLUSH,super(t,e)}},Dw=class extends xf{constructor(t){super(t,"BrotliCompress")}},Ow=class extends xf{constructor(t){super(t,"BrotliDecompress")}},pf=class extends $c{constructor(t,e){t=t||{},t.flush=t.flush||Nt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Nt.ZSTD_e_end,t.fullFlushFlag=Nt.ZSTD_e_flush,super(t,e)}},Lw=class extends pf{constructor(t){super(t,"ZstdCompress")}},Nw=class extends pf{constructor(t){super(t,"ZstdDecompress")}},Mw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Fw(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 n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},Fw=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),n?e[i-1]=mf(o):o===0?e[i-1]=0:(n=!0,e[i-1]=gf(o))}},zw=t=>{let e=t[0],n=e===128?Gw(t.subarray(1,t.length)):e===255?Uw(t):null;if(n===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(n))throw Error("parsed number outside of javascript safe integer range");return n},Uw=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),l;i?l=mf(c):c===0?l=c:(i=!0,l=gf(c)),l!==0&&(n-=l*Math.pow(256,e-o-1))}return n},Gw=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(n+=o*Math.pow(256,e-i-1))}return n},mf=t=>(255^t)&255,gf=t=>(255^t)+1&255,Hw={};tw(Hw,{code:()=>Vc,isCode:()=>Js,isName:()=>qw,name:()=>uo,normalFsTypes:()=>wf});var Js=t=>uo.has(t),qw=t=>Vc.has(t),wf=new Set(["0","","1","2","3","4","5","6","7","D"]),uo=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Vc=new Map(Array.from(uo).map(t=>[t[1],t[0]])),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,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=Mn(t,e+156,1),c=wf.has(o),l=c?n:void 0,u=c?i:void 0;if(this.path=l?.path??Mn(t,e,100),this.mode=l?.mode??u?.mode??wn(t,e+100,8),this.uid=l?.uid??u?.uid??wn(t,e+108,8),this.gid=l?.gid??u?.gid??wn(t,e+116,8),this.size=l?.size??u?.size??wn(t,e+124,12),this.mtime=l?.mtime??u?.mtime??dc(t,e+136,12),this.cksum=wn(t,e+148,12),u&&this.#n(u,!0),l&&this.#n(l),Js(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=l?.uname??u?.uname??Mn(t,e+265,32),this.gname=l?.gname??u?.gname??Mn(t,e+297,32),this.devmaj=l?.devmaj??u?.devmaj??wn(t,e+329,8)??0,this.devmin=l?.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=n?.atime??i?.atime??dc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??dc(t,e+488,12)}let h=256;for(let x=e;x<e+148;x++)h+=t[x];for(let x=e+156;x<e+512;x++)h+=t[x];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,i=jw(this.path||"",n),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=lc(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,n,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=lc(t,e+476,12,this.atime)||this.needPax,this.needPax=lc(t,e+488,12,this.ctime)||this.needPax);let l=256;for(let u=e;u<e+148;u++)l+=t[u];for(let u=e+156;u<e+512;u++)l+=t[u];return this.cksum=l,_n(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:uo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Vc.get(t));if(Js(e)||e==="Unsupported")this.#e=e;else if(Js(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},jw=(t,e)=>{let n=t,i="",o,c=wr.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=wr.dirname(n),n=wr.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?o=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?o=[n.slice(0,99),i,!0]:(n=wr.join(wr.basename(i),n),i=wr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Mn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),dc=(t,e,n)=>Kw(wn(t,e,n)),Kw=t=>t===void 0?void 0:new Date(t*1e3),wn=(t,e,n)=>Number(t[e])&128?zw(t.subarray(e,e+n)):$w(t,e,n),Ww=t=>isNaN(t)?void 0:t,$w=(t,e,n)=>Ww(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),Vw={12:8589934591,8:2097151},_n=(t,e,n,i)=>i===void 0?!1:i>Vw[n]||i<0?(Mw(i,t.subarray(e,e+n)),!0):(Jw(t,e,n,i),!1),Jw=(t,e,n,i)=>t.write(Zw(i,n),e,n,"ascii"),Zw=(t,e)=>Yw(Math.floor(t).toString(8),e),Yw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",lc=(t,e,n,i)=>i===void 0?!1:_n(t,e,n,i.getTime()/1e3),Xw=new Array(156).join("\0"),Bn=(t,e,n,i)=>i===void 0?!1:(t.write(i+Xw,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),io=class _f{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[c]=0;new Kn({path:("PaxHeader/"+Qw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,n,"utf8");for(let c=n+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let n=this[e],i=n instanceof Date?n.getTime()/1e3:n,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(o),l=Math.floor(Math.log(c)/Math.log(10))+1;return c+l>=Math.pow(10,l)&&(l+=1),l+c+o}static parse(e,n,i=!1){return new _f(e_(t_(e),n),i)}},e_=(t,e)=>e?Object.assign({},e,t):t,t_=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(n_,Object.create(null)),n_=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),l=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(l)*1e3):/^[0-9]+$/.test(l)?+l:l,t},r_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ee=r_!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),i_=class extends Wn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,n){switch(super({}),this.pause(),this.extended=e,this.globalExtended=n,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=ee(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?ee(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),n&&this.#e(n,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let n=this.remain,i=this.blockRemain;return this.remain=Math.max(0,n-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:n>=e?super.write(t):super.write(t.subarray(0,n))}#e(t,e=!1){t.path&&(t.path=ee(t.path)),t.linkpath&&(t.linkpath=ee(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},fo=(t,e,n,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=n instanceof Error&&n.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(n instanceof Error&&(i=Object.assign(n,i),n=n.message),t.emit("warn",e,n,i)):n instanceof Error?t.emit("error",Object.assign(n,i)):t.emit("error",Object.assign(new Error(`${e}: ${n}`),i))},s_=1024*1024,Ac=Buffer.from([31,139]),kc=Buffer.from([40,181,47,253]),o_=Math.max(Ac.length,kc.length),xt=Symbol("state"),Fn=Symbol("writeEntry"),Vt=Symbol("readEntry"),uc=Symbol("nextEntry"),Lu=Symbol("processEntry"),Dt=Symbol("extendedHeader"),wi=Symbol("globalExtendedHeader"),hn=Symbol("meta"),Nu=Symbol("emitMeta"),we=Symbol("buffer"),Jt=Symbol("queue"),xn=Symbol("ended"),fc=Symbol("emittedEnd"),zn=Symbol("emit"),Ce=Symbol("unzip"),zs=Symbol("consumeChunk"),Us=Symbol("consumeChunkSub"),hc=Symbol("consumeBody"),Mu=Symbol("consumeMeta"),Bu=Symbol("consumeHeader"),_i=Symbol("consuming"),xc=Symbol("bufferConcat"),Gs=Symbol("maybeEnd"),_r=Symbol("writing"),pn=Symbol("aborted"),Hs=Symbol("onDone"),Un=Symbol("sawValidEntry"),qs=Symbol("sawNullBlock"),js=Symbol("sawEOF"),Fu=Symbol("closeStream"),a_=()=>!0,Ni=class extends Iw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Jt]=[];[we];[Vt];[Fn];[xt]="begin";[hn]="";[Dt];[wi];[xn]=!1;[Ce];[pn]=!1;[Un];[qs]=!1;[js]=!1;[_r]=!1;[_i]=!1;[fc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Hs,()=>{(this[xt]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Hs,t.ondone):this.on(Hs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||s_,this.filter=typeof t.filter=="function"?t.filter:a_;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let n=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:n?!0:void 0,this.on("end",()=>this[Fu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){fo(this,t,e,n)}[Bu](t,e){this[Un]===void 0&&(this[Un]=!1);let n;try{n=new Kn(t,e,this[Dt],this[wi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[qs]?(this[js]=!0,this[xt]==="begin"&&(this[xt]="header"),this[zn]("eof")):(this[qs]=!0,this[zn]("nullBlock"));else if(this[qs]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let o=this[Fn]=new i_(n,this[Dt],this[wi]);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[xt]="ignore",o.resume()):o.size>0&&(this[hn]="",o.on("data",c=>this[hn]+=c),this[xt]="meta"):(this[Dt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[xt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[xt]="body":(this[xt]="header",o.end()),this[Vt]?this[Jt].push(o):(this[Jt].push(o),this[uc]())))}}}[Fu](){queueMicrotask(()=>this.emit("close"))}[Lu](t){let e=!0;if(!t)this[Vt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Vt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[uc]()),e=!1);return e}[uc](){do;while(this[Lu](this[Jt].shift()));if(this[Jt].length===0){let t=this[Vt];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[hc](t,e){let n=this[Fn];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(o),n.blockRemain||(this[xt]="header",this[Fn]=void 0,n.end()),o.length}[Mu](t,e){let n=this[Fn],i=this[hc](t,e);return!this[Fn]&&n&&this[Nu](n),i}[zn](t,e,n){this[Jt].length===0&&!this[Vt]?this.emit(t,e,n):this[Jt].push([t,e,n])}[Nu](t){switch(this[zn]("meta",this[hn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Dt]=io.parse(this[hn],this[Dt],!1);break;case"GlobalExtendedHeader":this[wi]=io.parse(this[hn],this[wi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Dt]??Object.create(null);this[Dt]=e,e.path=this[hn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Dt]||Object.create(null);this[Dt]=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,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[pn])return n?.(),!1;if((this[Ce]===void 0||this.brotli===void 0&&this[Ce]===!1)&&t){if(this[we]&&(t=Buffer.concat([this[we],t]),this[we]=void 0),t.length<o_)return this[we]=t,n?.(),!0;for(let l=0;this[Ce]===void 0&&l<Ac.length;l++)t[l]!==Ac[l]&&(this[Ce]=!1);let o=!1;if(this[Ce]===!1&&this.zstd!==!1){o=!0;for(let l=0;l<kc.length;l++)if(t[l]!==kc[l]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Ce]===!1&&c)if(t.length<512)if(this[xn])this.brotli=!0;else return this[we]=t,n?.(),!0;else try{new Kn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ce]===void 0||this[Ce]===!1&&(this.brotli||o)){let l=this[xn];this[xn]=!1,this[Ce]=this[Ce]===void 0?new Cw({}):o?new Nw({}):new Ow({}),this[Ce].on("data",h=>this[zs](h)),this[Ce].on("error",h=>this.abort(h)),this[Ce].on("end",()=>{this[xn]=!0,this[zs]()}),this[_r]=!0;let u=!!this[Ce][l?"end":"write"](t);return this[_r]=!1,n?.(),u}}this[_r]=!0,this[Ce]?this[Ce].write(t):this[zs](t),this[_r]=!1;let i=this[Jt].length>0?!1:this[Vt]?this[Vt].flowing:!0;return!i&&this[Jt].length===0&&this[Vt]?.once("drain",()=>this.emit("drain")),n?.(),i}[xc](t){t&&!this[pn]&&(this[we]=this[we]?Buffer.concat([this[we],t]):t)}[Gs](){if(this[xn]&&!this[fc]&&!this[pn]&&!this[_i]){this[fc]=!0;let t=this[Fn];if(t&&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[zn](Hs)}}[zs](t){if(this[_i]&&t)this[xc](t);else if(!t&&!this[we])this[Gs]();else if(t){if(this[_i]=!0,this[we]){this[xc](t);let e=this[we];this[we]=void 0,this[Us](e)}else this[Us](t);for(;this[we]&&this[we]?.length>=512&&!this[pn]&&!this[js];){let e=this[we];this[we]=void 0,this[Us](e)}this[_i]=!1}(!this[we]||this[xn])&&this[Gs]()}[Us](t){let e=0,n=t.length;for(;e+512<=n&&!this[pn]&&!this[js];)switch(this[xt]){case"begin":case"header":this[Bu](t,e),e+=512;break;case"ignore":case"body":e+=this[hc](t,e);break;case"meta":e+=this[Mu](t,e);break;default:throw new Error("invalid state: "+this[xt])}e<n&&(this[we]=this[we]?Buffer.concat([t.subarray(e),this[we]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[pn]||(this[Ce]?(t&&this[Ce].write(t),this[Ce].end()):(this[xn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Gs]())),this}},Ti=t=>{let e=t.length-1,n=-1;for(;e>-1&&t.charAt(e)==="/";)n=e,e--;return n===-1?t:t.slice(0,n)},c_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},yf=(t,e)=>{let n=new Map(e.map(c=>[Ti(c),!0])),i=t.filter,o=(c,l="")=>{let u=l||gw(c).root||".",h;if(c===u)h=!1;else{let x=n.get(c);h=x!==void 0?x:o(mw(c),u)}return n.set(c,h),h};t.filter=i?(c,l)=>i(c,l)&&o(Ti(c)):c=>o(Ti(c))},d_=t=>{let e=new Ni(t),n=t.file,i;try{i=Ir.openSync(n,"r");let o=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let l=Buffer.allocUnsafe(o.size),u=Ir.readSync(i,l,0,o.size,0);e.end(u===l.byteLength?l:l.subarray(0,u))}else{let l=0,u=Buffer.allocUnsafe(c);for(;l<o.size;){let h=Ir.readSync(i,u,0,c,l);if(h===0)break;l+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Ir.closeSync(i)}catch{}}},l_=(t,e)=>{let n=new Ni(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{n.on("error",l),n.on("end",c),Ir.stat(o,(u,h)=>{if(u)l(u);else{let x=new Kc(o,{readSize:i,size:h.size});x.on("error",l),x.pipe(n)}})})},Rr=Mi(d_,l_,t=>new Ni(t),t=>new Ni(t),(t,e)=>{e?.length&&yf(t,e),t.noResume||c_(t)}),bf=(t,e,n)=>(t&=4095,n&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:f_,parse:Uu}=u_,Jc=t=>{let e="",n=Uu(t);for(;f_(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Uu(t)}return[e,t]},ho=["|","<",">","?",":"],Zc=ho.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),h_=new Map(ho.map((t,e)=>[t,Zc[e]])),x_=new Map(Zc.map((t,e)=>[t,ho[e]])),Gu=t=>ho.reduce((e,n)=>e.split(n).join(h_.get(n)),t),p_=t=>Zc.reduce((e,n)=>e.split(n).join(x_.get(n)),t),Ef=(t,e)=>e?(t=ee(t).replace(/^\.(\/|$)/,""),Ti(e)+"/"+t):ee(t),m_=16*1024*1024,Hu=Symbol("process"),qu=Symbol("file"),ju=Symbol("directory"),Tc=Symbol("symlink"),Ku=Symbol("hardlink"),yi=Symbol("header"),Zs=Symbol("read"),Rc=Symbol("lstat"),Ys=Symbol("onlstat"),Pc=Symbol("onread"),Cc=Symbol("onreadlink"),Dc=Symbol("openfile"),Oc=Symbol("onopenfile"),yn=Symbol("close"),oo=Symbol("mode"),Lc=Symbol("awaitDrain"),pc=Symbol("ondrain"),Lt=Symbol("prefix"),vf=class extends Wn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let n=Wc(e);super(),this.path=ee(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||m_,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=ee(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?ee(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[c,l]=Jc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=p_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ee(n.absolute||zu.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[Ys](o):this[Rc]()}warn(t,e,n={}){return fo(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Rc](){Ot.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Ys](e)})}[Ys](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=__(t),this.emit("stat",t),this[Hu]()}[Hu](){switch(this.type){case"File":return this[qu]();case"Directory":return this[ju]();case"SymbolicLink":return this[Tc]();default:return this.end()}}[oo](t){return bf(t,this.type==="Directory",this.portable)}[Lt](t){return Ef(t,this.prefix)}[yi](){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[Lt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Lt](this.linkpath):this.linkpath,mode:this[oo](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 io({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[Lt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Lt](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)}[ju](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[yi](),this.end()}[Tc](){Ot.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Cc](e)})}[Cc](t){this.linkpath=ee(t),this[yi](),this.end()}[Ku](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ee(zu.relative(this.cwd,t)),this.stat.size=0,this[yi](),this.end()}[qu](){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[Ku](e);this.linkCache.set(t,this.absolute)}if(this[yi](),this.stat.size===0)return this.end();this[Dc]()}[Dc](){Ot.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Oc](e)})}[Oc](t){if(this.fd=t,this.#e)return this[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[Zs]()}[Zs](){let{fd:t,buf:e,offset:n,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Ot.read(t,e,n,i,o,(c,l)=>{if(c)return this[yn](()=>this.emit("error",c));this[Pc](l)})}[yn](t=()=>{}){this.fd!==void 0&&Ot.close(this.fd,t)}[Pc](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[yn](()=>this.emit("error",n))}if(t>this.remain){let n=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[yn](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let n=t;n<this.length&&t<this.blockRemain;n++)this.buf[n+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[pc]():this[Lc](()=>this[pc]())}[Lc](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,n)}[pc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[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[Zs]()}},g_=class extends vf{sync=!0;[Rc](){this[Ys](Ot.lstatSync(this.absolute))}[Tc](){this[Cc](Ot.readlinkSync(this.absolute))}[Dc](){this[Oc](Ot.openSync(this.absolute,"r"))}[Zs](){let t=!0;try{let{fd:e,buf:n,offset:i,length:o,pos:c}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let l=Ot.readSync(e,n,i,o,c);this[Pc](l),t=!1}finally{if(t)try{this[yn](()=>{})}catch{}}}[Lc](t){t()}[yn](t=()=>{}){this.fd!==void 0&&Ot.closeSync(this.fd),t()}},w_=class extends Wn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,n={}){return fo(this,t,e,n)}constructor(t,e={}){let n=Wc(e);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=n.prefix,this.path=ee(t.path),this.mode=t.mode!==void 0?this[oo](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:n.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?ee(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[l,u]=Jc(this.path);l&&typeof u=="string"&&(this.path=u,o=l)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Kn({path:this[Lt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Lt](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 io({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[Lt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Lt](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)}[Lt](t){return Ef(t,this.prefix)}[oo](t){return bf(t,this.type==="Directory",this.portable)}write(t,e,n){typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,n)}end(t,e,n){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),n&&this.once("finish",n),t?super.end(t,n):super.end(n),this}},__=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",y_=class Ar{tail;head;length=0;static create(e=[]){return new Ar(e)}constructor(e=[]){for(let n of e)this.push(n)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let n=e.next,i=e.prev;return n&&(n.prev=i),i&&(i.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,i=e.length;n<i;n++)E_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)v_(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,o=0;i;o++)e.call(n,i.value,o,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(n,i.value,o,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Ar;for(let o=this.head;o;)i.push(e.call(n,o.value,this)),o=o.next;return i}mapReverse(e,n){n=n||this;var i=new Ar;for(let o=this.tail;o;)i.push(e.call(n,o.value,this)),o=o.prev;return i}reduce(e,n){let i,o=this.head;if(arguments.length>1)i=n;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,n){let i,o=this.tail;if(arguments.length>1)i=n;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Ar;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<n;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Ar;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.length,c=this.tail;for(;c&&o>n;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let l=0;o&&l<e;l++)o=o.next;let c=[];for(let l=0;o&&l<n;l++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let l of i)o=b_(this,o,l);return c}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=n,this.tail=e,this}};function b_(t,e,n){let i=e,o=e?e.next:t.head,c=new Yc(n,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function E_(t,e){t.tail=new Yc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function v_(t,e){t.head=new Yc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Yc=class{list;next;prev;value;constructor(t,e,n,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,n?(n.prev=this,this.next=n):this.next=void 0}},$u=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Vu=Buffer.alloc(1024),Xs=Symbol("onStat"),bi=Symbol("ended"),vt=Symbol("queue"),Ei=Symbol("pendingLinks"),mn=Symbol("current"),Gn=Symbol("process"),vi=Symbol("processing"),Ks=Symbol("processJob"),St=Symbol("jobs"),mc=Symbol("jobDone"),Qs=Symbol("addFSEntry"),Ju=Symbol("addTarEntry"),Nc=Symbol("stat"),Mc=Symbol("readdir"),eo=Symbol("onreaddir"),to=Symbol("pipe"),Zu=Symbol("entry"),gc=Symbol("entryOpt"),no=Symbol("writeEntryClass"),Sf=Symbol("write"),wc=Symbol("ondrain"),xo=class extends Wn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[no];onWriteEntry;[vt];[Ei]=new Map;[St]=0;[vi]=!1;[bi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=ee(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[no]=vf,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 Dw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Lw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[wc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[wc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[vt]=new y_,this[St]=0,this.jobs=Number(t.jobs)||4,this[vi]=!1,this[bi]=!1}[Sf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&this.add(t),this[bi]=!0,this[Gn](),n&&n(),this}write(t){if(this[bi])throw new Error("write after end");return typeof t=="string"?this[Qs](t):this[Ju](t),this.flowing}[Ju](t){let e=ee(Wu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new $u(t.path,e);n.entry=new w_(t,this[gc](n)),n.entry.on("end",()=>this[mc](n)),this[St]+=1,this[vt].push(n)}this[Gn]()}[Qs](t){let e=ee(Wu.resolve(this.cwd,t));this[vt].push(new $u(t,e)),this[Gn]()}[Nc](t){t.pending=!0,this[St]+=1;let e=this.follow?"stat":"lstat";so[e](t.absolute,(n,i)=>{t.pending=!1,this[St]-=1,n?this.emit("error",n):this[Xs](t,i)})}[Xs](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[Ks](t);else{let n=`${e.dev}:${e.ino}`,i=this[Ei].get(n);i?i.push(t):this[Ei].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Gn]()}[Mc](t){t.pending=!0,this[St]+=1,so.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[St]-=1,e)return this.emit("error",e);this[eo](t,n)})}[eo](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Gn]()}[Gn](){if(!this[vi]){this[vi]=!0;for(let t=this[vt].head;t&&this[St]<this.jobs;t=t.next)if(this[Ks](t.value),t.value.ignore){let e=t.next;this[vt].removeNode(t),t.next=e}this[vi]=!1,this[bi]&&this[vt].length===0&&this[St]===0&&(this.zip?this.zip.end(Vu):(super.write(Vu),super.end()))}}get[mn](){return this[vt]&&this[vt].head&&this[vt].head.value}[mc](t){this[vt].shift(),this[St]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Ei].get(n);if(i){this[Ei].delete(n);for(let o of i)o.pending=!1,this[Ks](o)}}this[Gn]()}[Ks](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[to](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Xs](t,e):this[Nc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[eo](t,e):this[Mc](t),!t.readdir)return}if(t.entry=this[Zu](t),!t.entry){t.ignore=!0;return}t===this[mn]&&!t.piped&&this[to](t)}}}[gc](t){return{onwarn:(e,n,i)=>this.warn(e,n,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[Zu](t){this[St]+=1;try{return new this[no](t.path,this[gc](t)).on("end",()=>this[mc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[wc](){this[mn]&&this[mn].entry&&this[mn].entry.resume()}[to](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Qs](c+i)});let e=t.entry,n=this.zip;if(!e)throw new Error("cannot pipe without source");n?e.on("data",i=>{n.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,n={}){fo(this,t,e,n)}},Xc=class extends xo{sync=!0;constructor(t){super(t),this[no]=g_}pause(){}resume(){}[Nc](t){let e=this.follow?"statSync":"lstatSync";this[Xs](t,so[e](t.absolute))}[Mc](t){this[eo](t,so.readdirSync(t.absolute))}[to](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Qs](c+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Sf](i)})}},S_=(t,e)=>{let n=new Xc(t),i=new uf(t.file,{mode:t.mode||438});n.pipe(i),If(n,e)},I_=(t,e)=>{let n=new xo(t),i=new lo(t.file,{mode:t.mode||438});n.pipe(i);let o=new Promise((c,l)=>{i.on("error",l),i.on("close",c),n.on("error",l)});return Af(n,e).catch(c=>n.emit("error",c)),o},If=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Rr({file:ff.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Af=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Rr({file:ff.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},A_=(t,e)=>{let n=new Xc(t);return If(n,e),n},k_=(t,e)=>{let n=new xo(t);return Af(n,e).catch(i=>n.emit("error",i)),n},pA=Mi(S_,I_,A_,k_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),R_=process.env.__FAKE_PLATFORM__||process.platform,Pf=R_==="win32",{O_CREAT:Cf,O_NOFOLLOW:Yu,O_TRUNC:Df,O_WRONLY:Of}=Rf.constants,Lf=Number(process.env.__FAKE_FS_O_FILENAME__)||Rf.constants.UV_FS_O_FILEMAP||0,P_=Pf&&!!Lf,C_=512*1024,D_=Lf|Df|Cf|Of,Xu=!Pf&&typeof Yu=="number"?Yu|Df|Cf|Of:null,Nf=Xu!==null?()=>Xu:P_?t=>t<C_?D_:"w":()=>"w",Bc=(t,e,n)=>{try{return po.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},ao=(t,e,n,i)=>{po.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},O_=(t,e,n,i,o)=>{if(e.isDirectory())Mf(Ri.resolve(t,e.name),n,i,c=>{if(c)return o(c);let l=Ri.resolve(t,e.name);ao(l,n,i,o)});else{let c=Ri.resolve(t,e.name);ao(c,n,i,o)}},Mf=(t,e,n,i)=>{po.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 ao(t,e,n,i);let l=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--l===0)return ao(t,e,n,i)}};for(let x of c)O_(t,x,e,n,h)})},L_=(t,e,n,i)=>{e.isDirectory()&&Bf(Ri.resolve(t,e.name),n,i),Bc(Ri.resolve(t,e.name),n,i)},Bf=(t,e,n)=>{let i;try{i=po.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Bc(t,e,n);throw c}for(let o of i)L_(t,o,e,n);return Bc(t,e,n)},Ff=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},mo=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},M_=(t,e)=>{lt.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new Ff(t,n?.code||"ENOTDIR")),e(n)})},B_=(t,e,n)=>{t=ee(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,l=e.uid,u=e.gid,h=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),x=e.preserve,m=e.unlink,w=ee(e.cwd),v=(E,I)=>{E?n(E):I&&h?Mf(I,l,u,A=>v(A)):c?lt.chmod(t,o,n):n()};if(t===w)return M_(t,v);if(x)return N_.mkdir(t,{mode:o,recursive:!0}).then(E=>v(null,E??void 0),v);let _=ee(co.relative(w,t)).split("/");Fc(w,_,o,m,w,void 0,v)},Fc=(t,e,n,i,o,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),h=ee(co.resolve(t+"/"+u));lt.mkdir(h,n,zf(h,e,n,i,o,c,l))},zf=(t,e,n,i,o,c,l)=>u=>{u?lt.lstat(t,(h,x)=>{if(h)h.path=h.path&&ee(h.path),l(h);else if(x.isDirectory())Fc(t,e,n,i,o,c,l);else if(i)lt.unlink(t,m=>{if(m)return l(m);lt.mkdir(t,n,zf(t,e,n,i,o,c,l))});else{if(x.isSymbolicLink())return l(new mo(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,Fc(t,e,n,i,o,c,l))},F_=t=>{let e=!1,n;try{e=lt.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new Ff(t,n??"ENOTDIR")}},z_=(t,e)=>{t=ee(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==0,c=e.uid,l=e.gid,u=typeof c=="number"&&typeof l=="number"&&(c!==e.processUid||l!==e.processGid),h=e.preserve,x=e.unlink,m=ee(e.cwd),w=E=>{E&&u&&Bf(E,c,l),o&&lt.chmodSync(t,i)};if(t===m)return F_(m),w();if(h)return w(lt.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=ee(co.relative(m,t)).split("/"),_;for(let E=v.shift(),I=m;E&&(I+="/"+E);E=v.shift()){I=ee(co.resolve(I));try{lt.mkdirSync(I,i),_=_||I}catch{let A=lt.lstatSync(I);if(A.isDirectory())continue;if(x){lt.unlinkSync(I),lt.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new mo(I,I+"/"+v.join("/"))}}return w(_)},_c=Object.create(null),Qu=1e4,yr=new Set,U_=t=>{yr.has(t)?yr.delete(t):_c[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=_c[t],n=yr.size-Qu;if(n>Qu/10){for(let i of yr)if(yr.delete(i),delete _c[i],--n<=0)break}return e},G_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,H_=G_==="win32",q_=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Uf(i,n)),e.push(n||"/"),e},[]),j_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=H_?["win32 parallelization disabled"]:t.map(i=>Ti(Uf(U_(i))));let n=new Set(t.map(i=>q_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of n){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:i}=e,o=new Set;for(let c of n){let l=this.#e.get(c);if(!l||l?.[0]!==t)continue;let u=l[1];if(!u){this.#e.delete(c);continue}if(l.shift(),typeof u=="function")o.add(u);else for(let h of u)o.add(h)}for(let c of i){let l=this.#e.get(c),u=l?.[0];if(!(!l||!(u instanceof Set)))if(u.size===1&&l.length===1){this.#e.delete(c);continue}else if(u.size===1){l.shift();let h=l[0];typeof h=="function"&&o.add(h)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},K_=()=>process.umask(),ef=Symbol("onEntry"),zc=Symbol("checkFs"),tf=Symbol("checkFs2"),Uc=Symbol("isReusable"),pt=Symbol("makeFs"),Gc=Symbol("file"),Hc=Symbol("directory"),ro=Symbol("link"),nf=Symbol("symlink"),rf=Symbol("hardlink"),Ai=Symbol("ensureNoSymlink"),sf=Symbol("unsupported"),of=Symbol("checkPath"),yc=Symbol("stripAbsolutePath"),bn=Symbol("mkdir"),Ke=Symbol("onError"),Ws=Symbol("pending"),af=Symbol("pend"),br=Symbol("unpend"),bc=Symbol("ended"),Ec=Symbol("maybeClose"),qc=Symbol("skip"),Pi=Symbol("doChown"),Ci=Symbol("uid"),Di=Symbol("gid"),Oi=Symbol("checkedCwd"),W_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Li=W_==="win32",$_=1024,V_=(t,e)=>{if(!Li)return se.unlink(t,e);let n=t+".DELETE."+Tf(16).toString("hex");se.rename(t,n,i=>{if(i)return e(i);se.unlink(n,e)})},J_=t=>{if(!Li)return se.unlinkSync(t);let e=t+".DELETE."+Tf(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},cf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,Qc=class extends Ni{[bc]=!1;[Oi]=!1;[Ws]=0;reservations=new j_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[bc]=!0,this[Ec]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&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:$_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Li,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ee(Be.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:K_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[ef](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Ec](){this[bc]&&this[Ws]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[yc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,c]=Jc(n),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Li&&/^[a-z]:\.\.$/i.test(l[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=Be.posix.dirname(t.path),h=Be.posix.normalize(Be.posix.join(u,l.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:n})),!0}[of](t){let e=ee(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=ee(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}n.splice(0,this.strip),t.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[yc](t,"path")||!this[yc](t,"linkpath"))return!1;if(t.absolute=Be.isAbsolute(t.path)?ee(Be.resolve(t.path)):ee(Be.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:ee(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Be.win32.parse(String(t.absolute));t.absolute=i+Gu(String(t.absolute).slice(i.length));let{root:o}=Be.win32.parse(t.path);t.path=o+Gu(t.path.slice(o.length))}return!0}[ef](t){if(!this[of](t))return t.resume();switch(T_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[zc](t);default:return this[sf](t)}}[Ke](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[br](),e.resume())}[bn](t,e,n){B_(ee(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},n)}[Pi](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 cf(this.uid,t.uid,this.processUid)}[Di](t){return cf(this.gid,t.gid,this.processGid)}[Gc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new lo(String(t.absolute),{flags:Nf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[Ke](u,t),e()});let o=1,c=u=>{if(u){i.fd&&se.close(i.fd,()=>{}),this[Ke](u,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,h=>{h?this[Ke](h,t):this[br](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,m=t.mtime;se.futimes(h,x,m,w=>w?se.utimes(u,x,m,v=>c(v&&w)):c())}if(typeof h=="number"&&this[Pi](t)){o++;let x=this[Ci](t),m=this[Di](t);typeof x=="number"&&typeof m=="number"&&se.fchown(h,x,m,w=>w?se.chown(u,x,m,v=>c(v&&w)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[Ke](u,t),e()}),t.pipe(l)),l.pipe(i)}[Hc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[bn](String(t.absolute),n,i=>{if(i){this[Ke](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[br](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Pi](t)&&(o++,se.chown(String(t.absolute),Number(this[Ci](t)),Number(this[Di](t)),c)),c()})}[sf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[nf](t,e){let n=ee(Be.relative(this.cwd,Be.resolve(Be.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ai](t,this.cwd,n,()=>this[ro](t,String(t.linkpath),"symlink",e),i=>{this[Ke](i,t),e()})}[rf](t,e){let n=ee(Be.resolve(this.cwd,String(t.linkpath))),i=ee(String(t.linkpath)).split("/");this[Ai](t,this.cwd,i,()=>this[ro](t,n,"link",e),o=>{this[Ke](o,t),e()})}[Ai](t,e,n,i,o){let c=n.shift();if(this.preservePaths||c===void 0)return i();let l=Be.resolve(e,c);se.lstat(l,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new mo(l,Be.resolve(l,n.join("/"))));this[Ai](t,l,n,i,o)})}[af](){this[Ws]++}[br](){this[Ws]--,this[Ec]()}[qc](t){this[br](),t.resume()}[Uc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Li}[zc](t){this[af]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[tf](t,n))}[tf](t,e){let n=l=>{e(l)},i=()=>{this[bn](this.cwd,this.dmode,l=>{if(l){this[Ke](l,t),n();return}this[Oi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let l=ee(Be.dirname(String(t.absolute)));if(l!==this.cwd)return this[bn](l,this.dmode,u=>{if(u){this[Ke](u,t),n();return}c()})}c()},c=()=>{se.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[qc](t),n();return}if(l||this[Uc](t,u))return this[pt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=m=>this[pt](m??null,t,n);return h?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),h=>this[pt](h??null,t,n))}if(t.absolute===this.cwd)return this[pt](null,t,n);V_(String(t.absolute),h=>this[pt](h??null,t,n))})};this[Oi]?o():i()}[pt](t,e,n){if(t){this[Ke](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Gc](e,n);case"Link":return this[rf](e,n);case"SymbolicLink":return this[nf](e,n);case"Directory":case"GNUDumpDir":return this[Hc](e,n)}}[ro](t,e,n,i){se[n](e,String(t.absolute),o=>{o?this[Ke](o,t):(this[br](),t.resume()),i()})}},Si=t=>{try{return[null,t()]}catch(e){return[e,null]}},Gf=class extends Qc{sync=!0;[pt](t,e){return super[pt](t,e,()=>{})}[zc](t){if(!this[Oi]){let o=this[bn](this.cwd,this.dmode);if(o)return this[Ke](o,t);this[Oi]=!0}if(t.absolute!==this.cwd){let o=ee(Be.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[bn](o,this.dmode);if(c)return this[Ke](c,t)}}let[e,n]=Si(()=>se.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[qc](t);if(e||this[Uc](t,n))return this[pt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[l]=c?Si(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[pt](l,t)}let[o]=Si(()=>se.rmdirSync(String(t.absolute)));this[pt](o,t)}let[i]=t.absolute===this.cwd?[]:Si(()=>J_(String(t.absolute)));this[pt](i,t)}[Gc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{se.closeSync(o)}catch(h){u=h}(l||u)&&this[Ke](l||u,t),e()},o;try{o=se.openSync(String(t.absolute),Nf(t.size),n)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[Ke](l,t)),t.pipe(c)),c.on("data",l=>{try{se.writeSync(o,l,0,l.length)}catch(u){i(u)}}),c.on("end",()=>{let l=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{se.futimesSync(o,u,h)}catch(x){try{se.utimesSync(String(t.absolute),u,h)}catch{l=x}}}if(this[Pi](t)){let u=this[Ci](t),h=this[Di](t);try{se.fchownSync(o,Number(u),Number(h))}catch(x){try{se.chownSync(String(t.absolute),Number(u),Number(h))}catch{l=l||x}}}i(l)})}[Hc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[bn](String(t.absolute),n);if(i){this[Ke](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Pi](t))try{se.chownSync(String(t.absolute),Number(this[Ci](t)),Number(this[Di](t)))}catch{}e(),t.resume()}[bn](t,e){try{return z_(ee(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(n){return n}}[Ai](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let c=e;for(let l of n){c=Be.resolve(c,l);let[u,h]=Si(()=>se.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return o(new mo(c,Be.resolve(e,n.join("/"))))}i()}[ro](t,e,n,i){let o=`${n}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[Ke](c,t)}}},Z_=t=>{let e=new Gf(t),n=t.file,i=kf.statSync(n),o=t.maxReadSize||16*1024*1024;new pw(n,{readSize:o,size:i.size}).pipe(e)},Y_=(t,e)=>{let n=new Qc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{n.on("error",l),n.on("close",c),kf.stat(o,(u,h)=>{if(u)l(u);else{let x=new Kc(o,{readSize:i,size:h.size});x.on("error",l),x.pipe(n)}})})},Hf=Mi(Z_,Y_,t=>new Gf(t),t=>new Qc(t),(t,e)=>{e?.length&&yf(t,e)}),X_=(t,e)=>{let n=new Xc(t),i=!0,o,c;try{try{o=dt.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=dt.openSync(t.file,"w+");else throw h}let l=dt.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<l.size;c+=512){for(let m=0,w=0;m<512;m+=w){if(w=dt.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(!w)break e}let h=new Kn(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(c+x+512>l.size)break;c+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,Q_(t,n,c,o,e)}finally{if(i)try{dt.closeSync(o)}catch{}}},Q_=(t,e,n,i,o)=>{let c=new uf(t.file,{fd:i,start:n});e.pipe(c),ty(e,o)},ey=(t,e)=>{e=Array.from(e);let n=new xo(t),i=(o,c,l)=>{let u=(v,_)=>{v?dt.close(o,E=>l(v)):l(null,_)},h=0;if(c===0)return u(null,0);let x=0,m=Buffer.alloc(512),w=(v,_)=>{if(v||_===void 0)return u(v);if(x+=_,x<512&&_)return dt.read(o,m,x,m.length-x,h+x,w);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 E=new Kn(m);if(!E.cksumValid)return u(null,h);let I=512*Math.ceil((E.size??0)/512);if(h+I+512>c||(h+=I+512,h>=c))return u(null,h);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),x=0,dt.read(o,m,0,512,h,w)};dt.read(o,m,0,512,h,w)};return new Promise((o,c)=>{n.on("error",c);let l="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&l==="r+")return l="w+",dt.open(t.file,l,u);if(h||!x)return c(h);dt.fstat(x,(m,w)=>{if(m)return dt.close(x,()=>c(m));i(x,w.size,(v,_)=>{if(v)return c(v);let E=new lo(t.file,{fd:x,start:_});n.pipe(E),E.on("error",c),E.on("close",o),ny(n,e)})})};dt.open(t.file,l,u)})},ty=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Rr({file:qf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},ny=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Rr({file:qf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Ii=Mi(X_,ey,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!vw(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")}),PA=Mi(Ii.syncFile,Ii.asyncFile,Ii.syncNoFile,Ii.asyncNoFile,(t,e=[])=>{Ii.validate?.(t,e),ry(t)}),ry=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(n,i)=>e(n,i)&&!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0)):(n,i)=>!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0))};Kt();var mt={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 go(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function jf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function wo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Kf(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function Wf(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function $n(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Xt();Ve();ne();Pe();Ve();function Pr(t,e){if(go(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Bi(t){return t.startsWith("http://")||t.startsWith("https://")}function Cr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as bk}from"node:fs";import{dirname as vk,join as Sk}from"node:path";import{fileURLToPath as Ak}from"node:url";var Mt="0.2.7-beta.2";import{mkdir as yy,rm as u0}from"node:fs/promises";import{join as Hi}from"node:path";jt();import{readFileSync as uy}from"node:fs";var fy=384;async function ed(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await fr(t.agentEnvFile,n,{mode:fy})}function Fi(t){try{let e=JSON.parse(uy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Zf(t,e,n={},i=o=>o){return{...i({...t,...Fi(e)}),...n}}jt();function zi(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(hy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
92
92
  `)}
93
93
  `}function hy(t){if(t.includes(`
94
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}te();Ce();import{homedir as my}from"node:os";import{join as wy}from"node:path";Ke();te();var po="1008033",Yf="1289";var Jf="pbbp2",Xf="https://www.coze.cn",Zf="/api/coze_claw/resource/get_frontier_key",py="https://www.coze.cn",gy="wss://frontier.coze.cn";function Dr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??py}function Qf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??gy}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 zi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Fi=j("handshake");async function Xc(t){let e=Dr(t.endpoint),r=t.timeoutMs??1e4,i=`${Rr(e)}${Zf}?aid=${encodeURIComponent(po)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Sn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Fi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),x=u.headers.get("x-tt-logid")??"",h=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let S=await u.text().catch(()=>"");throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${x}: ${S.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=${x}`);let w=m.data??{},I=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,b=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!I||!b){let S=JSON.stringify(m).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${x}: ${S}`)}return Fi.info("handshake ok",{remoteDeviceId:b,logid:x,traceId:h}),{accessKey:I,deviceId:b}}catch(u){if(u instanceof T)throw Fi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Fi.warn("handshake timeout",{base:e,timeoutMs:r}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let x=u.cause;throw Fi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:x?.code,syscall:x?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var go=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",It="auto",Zc=19e4,e0=8192;function n0(t){return{model:Qc(t.model)??It,...t.modelToken?{modelToken:t.modelToken}:{}}}function r0(t){return!t||t===It}var _y=new Set(["auto","\u81EA\u52A8"]);function Qc(t){let e=t?.trim();if(e)return _y.has(e.toLowerCase())?It:e}function i0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=go,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||It;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 r0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function s0(t,e,r){let i={};if(t.modelToken?i.model=t.model||It:r0(t.model)||(i.model=t.model),t.modelToken){let o={name:"coze",base_url:`${go}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},c=mo(e,r);Object.keys(c).length>0&&(o.http_headers=c),i.model_providers={coze:o},i.model_context_window=t.modelInfo?.contextWindow??Zc}return Object.keys(i).length===0?{}:{CODEX_CONFIG:JSON.stringify(i),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function o0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function mo(t,e){let{ttEnv:r,usePpe:i}=zi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function a0(t,e,r){if(!t.modelToken)return{};let i=mo(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
95
- `)}}function ed(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function td(t){return t.model||It}function t0(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 c0(t,e,r,i){if(!t.modelToken)return null;let o=td(t),c=mo(e,r),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[t0(o,d,t.modelInfo?.contextWindow??Zc,t.modelInfo?.maxOutput??e0)],x=new Set([o]);for(let m of i??[])!m||x.has(m)||(x.add(m),u.push(t0(m,["text"],Zc,e0)));let h={baseUrl:`${go}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(h.headers=c),h}function yy(t){if(t!==void 0)return t?"auto":"text"}function nd(t,e,r){let i=mo(e,r),o=t.model||It,c=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${go}/v1`];if(t.modelInfo?.contextWindow&&c.push(` context_length: ${t.modelInfo.contextWindow}`),t.modelInfo?.maxOutput&&c.push(` max_tokens: ${t.modelInfo.maxOutput}`),t.modelToken&&c.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){c.push(" default_headers:");for(let[u,x]of Object.entries(i))c.push(` ${u}: ${JSON.stringify(x)}`)}c.push("compression:"),c.push(" threshold: 0.8"),c.push("approvals:"),c.push(` mode: ${JSON.stringify("off")}`),c.push(` cron_mode: ${JSON.stringify("approve")}`);let d=yy(t.modelInfo?.capabilities?.image);return d&&(c.push("agent:"),c.push(` image_input_mode: ${JSON.stringify(d)}`)),c.push("skills:"),c.push(" external_dirs:"),c.push(` - ${wy(my(),".hermes","skills")}`),`${c.join(`
94
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}ne();Pe();import{homedir as my}from"node:os";import{join as gy}from"node:path";Ve();ne();var _o="1008033",Yf="1289";var Xf="pbbp2",Qf="https://www.coze.cn",e0="/api/coze_claw/resource/get_frontier_key",xy="https://www.coze.cn",py="wss://frontier.coze.cn";function Dr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??xy}function t0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??py}function Sn(t){let e={},n=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return n&&(e["x-tt-env"]=n),i&&(e["x-use-ppe"]=i),e}function Gi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Ui=K("handshake");async function td(t){let e=Dr(t.endpoint),n=t.timeoutMs??1e4,i=`${Cr(e)}${e0}?aid=${encodeURIComponent(_o)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Sn(t.ppeOverride)},c=new AbortController,l=setTimeout(()=>c.abort(),n);Ui.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),h=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let E=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${E.slice(0,200)}`)}let m=await u.json();if(m.code!==void 0&&m.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${m.code} msg=${m.msg??"-"} logid=${h}`);let w=m.data??{},v=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,_=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!v||!_){let E=JSON.stringify(m).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${E}`)}return Ui.info("handshake ok",{remoteDeviceId:_,logid:h,traceId:x}),{accessKey:v,deviceId:_}}catch(u){if(u instanceof k)throw Ui.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Ui.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let h=u.cause;throw Ui.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 k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}var yo=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",kt="auto",nd=19e4,n0=8192;function i0(t){return{model:rd(t.model)??kt,...t.modelToken?{modelToken:t.modelToken}:{}}}function s0(t){return!t||t===kt}var wy=new Set(["auto","\u81EA\u52A8"]);function rd(t){let e=t?.trim();if(e)return wy.has(e.toLowerCase())?kt:e}function o0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=yo,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||kt;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=n,e.ANTHROPIC_DEFAULT_OPUS_MODEL=n,e.ANTHROPIC_DEFAULT_SONNET_MODEL=n,e.CLAUDE_CODE_SUBAGENT_MODEL=n,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else s0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function a0(t,e,n){let i={};if(t.modelToken?i.model=t.model||kt:s0(t.model)||(i.model=t.model),t.modelToken){let o={name:"coze",base_url:`${yo}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},c=bo(e,n);Object.keys(c).length>0&&(o.http_headers=c),i.model_providers={coze:o},i.model_context_window=t.modelInfo?.contextWindow??nd}return Object.keys(i).length===0?{}:{CODEX_CONFIG:JSON.stringify(i),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function c0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function bo(t,e){let{ttEnv:n,usePpe:i}=Gi(t),o={};return n&&(o["x-tt-env"]=n),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function d0(t,e,n){if(!t.modelToken)return{};let i=bo(e,n);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,l])=>`${c}:${l}`).join(`
95
+ `)}}function id(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function sd(t){return t.model||kt}function r0(t,e,n,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:i,api:"openai-completions"}}function l0(t,e,n,i){if(!t.modelToken)return null;let o=sd(t),c=bo(e,n),l=["text"];t.modelInfo?.capabilities?.image===!0&&l.push("image");let u=[r0(o,l,t.modelInfo?.contextWindow??nd,t.modelInfo?.maxOutput??n0)],h=new Set([o]);for(let m of i??[])!m||h.has(m)||(h.add(m),u.push(r0(m,["text"],nd,n0)));let x={baseUrl:`${yo}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(x.headers=c),x}function _y(t){if(t!==void 0)return t?"auto":"text"}function od(t,e,n){let i=bo(e,n),o=t.model||kt,c=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${yo}/v1`];if(t.modelInfo?.contextWindow&&c.push(` context_length: ${t.modelInfo.contextWindow}`),t.modelInfo?.maxOutput&&c.push(` max_tokens: ${t.modelInfo.maxOutput}`),t.modelToken&&c.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){c.push(" default_headers:");for(let[u,h]of Object.entries(i))c.push(` ${u}: ${JSON.stringify(h)}`)}c.push("compression:"),c.push(" threshold: 0.8"),c.push("approvals:"),c.push(` mode: ${JSON.stringify("off")}`),c.push(` cron_mode: ${JSON.stringify("approve")}`);let l=_y(t.modelInfo?.capabilities?.image);return l&&(c.push("agent:"),c.push(` image_input_mode: ${JSON.stringify(l)}`)),c.push("skills:"),c.push(" external_dirs:"),c.push(` - ${gy(my(),".hermes","skills")}`),`${c.join(`
96
96
  `)}
97
- `}var Vn=j("hermes-config"),l0="dont_ask",u0="default";function Yn(t,e){return Ui(Fe(t,e).root,"hermes-home")}async function Ey(t){let e=Yn(t.agentId,t.paths);await by(e,{recursive:!0,mode:448});let r=Bi({...process.env,...Mi(t.paths.agentEnvFile)});await ut(Ui(e,".env"),r,{mode:384});let i=nd(t.modelConfig,t.cozeEnv,t.mockScenario);await ut(Ui(e,"config.yaml"),i,{mode:384}),Vn.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:r.length,yamlBytes:i.length})}async function f0(t){let e=Yn(t.agentId,t.paths),r=Ui(e,"state.db"),i=Ui(e,"config.yaml");Vn.warn("[AUDIT] ABOUT TO RM hermes state.db (resetHermesHome)",{src:"hermes-config.resetHermesHome",agentId:t.agentId,home:e,stateDb:r,callerStack:new Error("resetHermesHome-caller").stack?.split(`
98
- `).slice(1,6).join(" | ")}),await d0(r,{force:!0}).catch(c=>Vn.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(c)}));let o=nd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await ut(i,o,{mode:384}).catch(c=>Vn.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(c)})),Vn.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function id(t,e){let r=Yn(t,e);Vn.warn("[AUDIT] ABOUT TO RM hermes-home (cleanupHermesHome)",{src:"hermes-config.cleanupHermesHome",agentId:t,home:r,callerStack:new Error("cleanupHermesHome-caller").stack?.split(`
99
- `).slice(1,6).join(" | ")}),await d0(r,{recursive:!0,force:!0}).catch(i=>Vn.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var rd=new Map;function x0(t){let e=rd.get(t.agentId);if(e)return e;let r=Ey(t).finally(()=>rd.delete(t.agentId));return rd.set(t.agentId,r),r}var ne=j("agent-handlers"),p0=5*1024*1024,ky=1,Ty=6,Cy=new Set(["node_modules",".git",".coze","dist","build",".next"]),Py=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ry=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Dy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Oy(t){let e=t?.trim();return e?Dy.test(e)||Ry.test(e)?e:(ne.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Ly(t){return new Promise((e,r)=>{let i=it("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=d=>{o||(o=!0,d?r(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",d=>c(d))})}function Ny(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var _o=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??J()}async listSkills(e){e._meta;let r=$n(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Fe(r,this.paths).workspace,c=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Lr(c,r,o,this.paths),x=[],h=new Set;for(let m of d){let w=fe(u,m.relPath,"SKILL.md");await ud(w).then(b=>b.isFile()).catch(()=>!1)&&(x.push(Uy(m)),h.add(m.relPath))}if(e.scanLocal){let m=await A0(r,o,c,this.paths),w=await k0(r,c);for(let I of[...m,...w])h.has(I.relPath)||(h.add(I.relPath),x.push(I.skill))}return{skills:x}}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((x,h)=>[x.skillId,h])),u=[];for(let x of o){let h=await yo({agentId:r,workspace:i.workspace,framework:i.framework,skill:x,paths:this.paths});bo(c,d,h),u.push(x)}return await ci(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=[],{base:u}=Lr(i.framework,r,i.workspace,this.paths);for(let x of c){if(!o.has(x.skillId)){d.push(x);continue}let h=fe(u,x.relPath);ne.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:r,skillId:x.skillId,relPath:x.relPath,skillBase:u,absDir:h}),await ad(h,{recursive:!0,force:!0}),ne.info("skill removed",{agentId:r,skillId:x.skillId,relPath:x.relPath})}return await ci(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=$n(e._meta);if(!e.skillName)throw new T("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");ne.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??Fe(r,this.paths).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=await By(r,o,c,e.skillName,d,this.paths);if(!u){let L=d?"global":"workspace";throw new T("SKILL_NOT_FOUND",`skill not found in ${L}: ${e.skillName}`)}let{absDir:x,relPath:h,dirName:m}=u,w=fe(x,"SKILL.md"),I=new xd.default;I.addLocalFolder(x,m);let b=I.toBuffer();if(b.length>g0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${b.length} bytes exceeds limit ${g0}`);let S=await wo(w,{encoding:"utf8"}).then(L=>S0(L).description).catch(()=>{}),A={};this.opts.publishSkillToMarketplace?A=await this.opts.publishSkillToMarketplace({zip:b,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...S?{description:S}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):ne.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let k=A.version??"v1.0",P=A.skillId??e.skillId??v0(r,h);if(i&&!d){let L=i.skills??[],E=L.find(D=>D.relPath===h);E?(E.version=k,E.skillId=P):L.push({skillId:P,skillName:e.skillName,relPath:h,version:k,installedAt:Date.now(),...S?{description:S}:{}}),await ci(r,L)}return ne.info("skill published",{agentId:r,skillName:e.skillName,relPath:h,zipBytes:b.length,skillId:P,version:k}),{ok:!0,skillId:P,version:k}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,ne.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let x=c.downstream;c.downstream=void 0,ne.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),x.stop(r).catch(h=>ne.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(h)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return ne.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await ve(r);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return ne.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await xr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw ne.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 ze(i),ne.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 ve(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=Oy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&Py.test(d)&&o.push("--env",d);let u=await Ly(o);return ne.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 ve(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await ze(i),ne.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}):(ne.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",`${ht.DELETE}: missing agentId`);ne.warn("[AUDIT] deleteAgent handler entry",{agentId:r,reason:e.reason??"",forceParamDeployType:e.deployType,metaDeployType:e._meta?.cozeDeployType,callerStack:new Error("deleteAgent-caller").stack?.split(`
100
- `).slice(1,6).join(" | ")});let i=await ve(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=Fe(r);return c==="cloud"?(ne.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:r,path:d.root,deployType:c,reason:e.reason??""}),await ad(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await ze(i)),ne.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Pr(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Qc(e.model)??It,i=await ve(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 ze(i),ne.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return ne.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model,d=o.modelInfo;o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(h=>ne.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(h)}));let u=o.framework==="hermes"&&Ny(d,o.modelInfo);if(o.framework==="hermes"&&!u){let h=[];for(let[m,w]of o.allSessionQueues())h.push(w.enqueue(async()=>{let I=o.sessions.get(m);if(!(!I?.downstream||!I.acpSessionId))try{await I.downstream.setSessionModel?.({sessionId:I.acpSessionId,modelId:r})}catch(b){ne.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:m,acpId:I.acpSessionId,err:String(b)})}}));return await Promise.all(h),ne.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:r,cloudSessions:h.length}),{ok:!0}}let x=[];for(let[h,m]of o.allSessionQueues())x.push(m.enqueue(async()=>{let w=o.sessions.get(h);w?.downstream&&(await w.downstream.stop(`switchModel: ${r}`).catch(()=>{}),w.downstream=void 0)}));return await Promise.all(x),ne.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:x.length}),{ok:!0}}async resetAgent(e){if(Pr(e._meta,ht.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ht.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ht.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(r=>ne.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(r)})),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),ne.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,permissionMode:d.permissionMode,cozeGroupId:d.cozeGroupId});await ai(e,o)}async clearPersistedAcpSessionIds(e){let r=await ve(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await ze(r)}async repairAgent(e){if(Pr(e._meta,ht.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ht.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("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){ne.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){ne.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){ne.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Pr(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 sd(d).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await oi(d,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let x=Zy(e.depth);return u.isDirectory()?{tree:await Xy(o,d,c,x)}:{tree:[{name:Qy(c),path:P0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Pr(e._meta,"_agent/getFileContent");let r=$n(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 sd(o).catch(()=>null);if(!c||!c.isFile())throw new T("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await oi(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>p0)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${p0})`);let d=await wo(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 ve(e).catch(()=>null))?.workspace??Fe(e).workspace}safeJoin(e,r){let i=dd(e,r||"."),o=fd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${w0}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return ve(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 b0(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 Lr(t,e,r,i){switch(t){case"claude-code":return{base:r,subdir:fe(".claude","skills")};case"codex":case"openclaw":return{base:r,subdir:fe(".agents","skills")};case"hermes":return{base:Yn(e,i??J()),subdir:"skills"}}}function E0(t){let e=Sy();if(t==="claude-code")return[fe(e,".claude","skills")];if(t==="codex")return[fe(e,".agents","skills"),fe(e,".codex","skills")];if(t==="openclaw")return[fe(e,".agents","skills"),fe(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA||fe(e,"AppData","Local");return[fe(r,"hermes","skills"),fe(e,".hermes","skills")]}return[fe(e,".hermes","skills")]}return[]}async function My(t,e,r,i,o,c){let d=async u=>ud(fe(u,"SKILL.md")).then(x=>x.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:x}=Lr(r,t,e,c),h=fe(x,i),m=fe(u,h);return await d(m)?{absDir:m,relPath:h}:null}for(let u of E0(r)){let x=fe(u,i);if(await d(x))return{absDir:x,relPath:x}}return null}async function By(t,e,r,i,o,c){let d=b0(i),u=await My(t,e,r,d,o,c);if(u)return{...u,dirName:d};let h=(o?await k0(t,r):await A0(t,e,r,c)).filter(I=>I.skill.skillName===i);if(h.length>1)throw new T("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${h.map(I=>h0(I.relPath)).join(", ")} \u2014 rename or remove duplicates`);let m=h[0];return m?{absDir:o?m.relPath:fe(e,m.relPath),relPath:m.relPath,dirName:h0(m.relPath)}:null}function v0(t,e){return(vy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function S0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
- ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
102
- `)){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 I0(t,e,r,i){let o=await m0(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 ud(fe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let x=d.name,h=fe(r,x),m=fe(e,x,"SKILL.md"),w=await wo(m,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let I=S0(w);c.push({relPath:h,skill:{skillId:v0(t,h),skillName:I.name||x,...I.description?{description:I.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function A0(t,e,r,i){let{base:o,subdir:c}=Lr(r,t,e,i);return I0(t,fe(o,c),c,!1)}async function k0(t,e){let r=[],i=new Set;for(let o of E0(e)){let c=await I0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var Fy=3e4,zy=50*1024*1024,g0=10*1024*1024,Or=3e4;async function yo(t){let{agentId:e,workspace:r,framework:i,skill:o,paths:c}=t;if(!o.skillName)throw new T("IPC_BAD_REQUEST","skill missing skillName");let d=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!d&&!u)throw new T("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let x=b0(o.skillName),{base:h,subdir:m}=Lr(i,e,r,c),w=fe(m,x),I=fe(h,w);if(await od(I,{recursive:!0}),d){let S=Buffer.from(o.content,"utf8");Hi(S.length),await cd(fe(I,"SKILL.md"),S,"utf8")}else{let S=await Gy(o.downloadUrl);jy(S)?await Vy(S,I):Wy(S)?await Ky(S,I):await cd(fe(I,"SKILL.md"),S.toString("utf8"),"utf8")}let b={skillId:o.skillId,skillName:o.skillName,relPath:w,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 ne.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:w,source:d?"content":"downloadUrl"}),b}function bo(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 Uy(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 Hy(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 T0(t,e){let r=await ve(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Lt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=new Map(c.map((w,I)=>[w.skillId,I])),u=c.filter(w=>w.builtin===!0&&!!w.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"noop",count:0};let x=0,h=0,{base:m}=Lr(r.framework,t,r.workspace,e);ne.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:r.framework,prev:o,current:i,skillBase:m,builtinCount:u.length,builtinRelPaths:u.map(w=>w.relPath)});for(let w of u)try{let I=fe(m,w.relPath);ne.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:w.skillId,relPath:w.relPath,rmTarget:I}),await ad(I,{recursive:!0,force:!0});let b=await yo({agentId:t,workspace:r.workspace,framework:r.framework,skill:Hy(w),...e?{paths:e}:{}});bo(c,d,b),x+=1}catch(I){h+=1,ne.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:w.skillId,skillName:w.skillName,err:String(I)})}return r.skills=c,h===0&&(r.skillsRefreshedForVersion=i),await ze(r,e),ne.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:x,failed:h}),{status:"refreshed",count:x}}async function Gy(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Hi(e);let r=qy(t);return Hi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await wo(e);return Hi(r.length),r}if(Ni(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),Fy);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 Hi(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 Hi(t){if(t>zy)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function qy(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 jy(t){return t.length>=2&&t[0]===31&&t[1]===139}function Wy(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 ld(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Ky(t,e){let r,i;try{r=new xd.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||ld(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new T("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(h=>h===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let x=d.header.attr>>>16&61440;if(x!==0&&x!==32768&&x!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${x.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=$y(i),c=dd(e);for(let d of i){if(ld(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let x=dd(e,u),h=fd(c,x);if(h.startsWith("..")||h==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await od(x,{recursive:!0});continue}await od(Iy(x),{recursive:!0});let m;try{m=d.getData()}catch(w){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await cd(x,m)}}function $y(t){let e;for(let r of t){let i=r.entryName;if(!i||ld(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 Yy(t);let r=Uf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await y0(_0.from(t),r)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Yy(t){let e=[],r=Cr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(h=>h==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await y0(_0.from(t),r)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Jy=5e3;async function Xy(t,e,r,i){return C0(t,e,r,i,{count:0})}async function C0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await m0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(Cy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Jy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let x=fe(e,u.name),h=Ay(fe(r,u.name)),m=null;try{m=await sd(x)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let w={name:u.name,path:P0(fd(t,x)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(w.children=await C0(t,x,h,i-1,o)),d.push(w)}return d.sort((u,x)=>u.isDir!==x.isDir?u.isDir?-1:1:u.name.localeCompare(x.name)),d}function Zy(t){return!t||t<=0?ky:Math.min(t,Ty)}function Qy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function P0(t){return t.split(w0).join("/")}te();var In=j("agent-health-reporter"),eb=1e4,tb=3,Gi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??eb,this.livenessFailureThreshold=e.livenessFailureThreshold??tb}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=nb(d);if(!u)continue;let x={agentId:d.agentId,status:u};d.patToken&&(x.patToken=d.patToken),d.accountId&&(x.accountId=d.accountId),r.push(x)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Lt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(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 nb(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}qt();import{mkdir as md,rm as eE,stat as tE}from"node:fs/promises";import{homedir as nE}from"node:os";import{join as cx}from"node:path";ln();import{existsSync as xb}from"node:fs";import{release as hb}from"node:os";import{basename as pb,isAbsolute as gb}from"node:path";function qi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Nr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Mr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function An(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ke();var Eo=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 R0(t){return"method"in t&&"id"in t&&t.id!==void 0}function D0(t){return"method"in t&&!("id"in t)}function vo(t){return!("method"in t)&&"id"in t}var rb={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 ib(t){if(t!=null)return t instanceof Error?{name:t.name,message:ji(t.message)}:typeof t=="string"?ji(t):typeof t=="object"?ob(t):t}var sb=[[/\/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 ji(t){let e=t;for(let[r,i]of sb)e=e.replace(r,i);return e}function ob(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=ji(i):e[r]=i;return e}function Wi(t){if(t instanceof T){let e=ib(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:rb[t.code]??X.INTERNAL_ERROR,message:ji(t.message),data:r}}return{code:X.INTERNAL_ERROR,message:ji(t instanceof Error?t.message:String(t))}}function O0(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 N0(t){return`${JSON.stringify(t)}
103
- `}var L0=10*1024*1024,So=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>L0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${L0} bytes`)}),[]}let r=this.buffer.split(`
104
- `);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 B0={"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"},TT=Object.fromEntries(Object.entries(B0).map(([t,e])=>[e,t])),ab={"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:[]},Br=class{seq=0;next(e,r){this.seq+=1;let i=B0[e]??cb(e),o=ab[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(x=>M0(r?.[x]??"")),u=db(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>M0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function cb(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function M0(t){return t.replace(/[:_\s]+/g,"-")}function db(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Jt();ar();Ke();te();Ce();import{execFileSync as lb,spawnSync as ub}from"node:child_process";function Ki(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function $i(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),ub("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var hd=new Set;function F0(t){typeof t=="number"&&t>0&&hd.add(t)}function z0(t){typeof t=="number"&&hd.delete(t)}function U0(){for(let t of hd)$i(t,"SIGKILL")}var Fr="coze-bridge-daemon";function H0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return lb("pgrep",["-U",String(o),"-f",Fr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
105
- `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function G0(t,e){if(t.length===0)return;let r=e?.killFn??$i,i=e?.isAliveFn??Ki,o=e?.sleepFn??(u=>new Promise(x=>setTimeout(x,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(x=>i(x));u+=d)await o(Math.min(d,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var fb=[{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:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{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 q0(t,e){if(!e)return null;for(let r of fb)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function j0(t,e){return q0(t,e)}function W0(t,e){return q0(t,e)}function zr(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 K0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let h=t.suspendedMs+o,m=r-t.startedAt-h;return{action:"suspend",suspendedDeltaMs:o,rearmMs:zr(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:zr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:zr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:zr(c,!1,e)}}var $0=Ye("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),mb=200,wb=40,_b=Ye("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),yb=Ye("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),bb=Ye("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Eb=Ye("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),vb=Ye("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Sb=Ye("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),V0=500;function Ib(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=V0?t:`${e.slice(0,V0)}...<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 Y0(t){try{return xb(t)}catch{return}}function kb(t,e){return{platform:process.platform,osRelease:hb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:gb(e.command)?Y0(e.command):void 0,cwd:e.cwd,cwdExists:Y0(e.cwd),envKeys:e.envKeys}}function Tb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${pb(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var pt=class{constructor(e){this.opts=e;this.log=j(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new So({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Br;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=Vf(process.env,this.opts.agentEnvFile??J().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=it(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,F0(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>mb&&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,z0(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=kb(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",Tb(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()));$i(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||$i(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:vb,phase2GateMs:_b,livenessWindowMs:yb,absoluteMaxMs:bb,approvalMaxMs:Sb,suspendThresholdMs:Eb,...r};return this.call("session/prompt",e,$0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Nr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",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(Mr(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=$0,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=qi(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let x=r.sessionId;return typeof x=="string"?x:void 0})();return new Promise((x,h)=>{let m={resolve:x,reject:h,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),I={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:zr(0,!1,o),sessionId:u};m.promptTimeout=I;let b=()=>{let S={startedAt:I.startedAt,lastActivityAt:I.lastActivityAt,firstFrameSeen:I.firstFrameSeen,hasActiveTool:I.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:I.suspendedMs,armedAt:I.armedAt,expectedIntervalMs:I.expectedIntervalMs},A=this.now(),k=K0(S,I.cfg,A),P=L=>{I.armedAt=A,I.expectedIntervalMs=L,m.timer=setTimeout(b,L)};if(k.action==="suspend"){I.suspendedMs+=k.suspendedDeltaMs,I.lastActivityAt=A,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:k.suspendedDeltaMs,suspendedMs:I.suspendedMs,...I.sessionId?{sessionId:I.sessionId}:{}}),P(k.rearmMs);return}if(k.action==="continue"){P(k.rearmMs);return}this.pending.delete(c),k.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:k.awaitingApproval,...I.sessionId?{sessionId:I.sessionId}:{}}),h(k.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${I.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${I.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...I.sessionId?{sessionId:I.sessionId}:{}}),h(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${I.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(b,I.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}),h(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(d)}catch(w){m.timer&&clearTimeout(m.timer),this.pending.delete(c),h(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(N0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(vo(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:Ib(e.result)}),r.resolve(e.result));return}if(D0(e)){if(e.method==="session/update"){let r=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,r))}for(let i of this.updateHandlers)try{Promise.resolve(i(r)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(R0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(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,Wi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=O0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=W0(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(wb).join(`
106
- `),o=j0(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 Cb(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 Io=class extends pt{framework="claude-code";constructor(e){let{command:r,args:i}=si("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return Cb(e)}};ln();import{mkdtempSync as Pb,rmSync as Rb}from"node:fs";import{tmpdir as Db}from"node:os";import{join as Ob}from"node:path";var J0=["default","acceptEdits","plan","auto","bypassPermissions"],X0=["read-only","auto","full-access"];var Z0=["default","accept_edits","dont_ask"];function Nt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return J0.includes(e);case"codex":return X0.includes(e);case"hermes":return Z0.includes(e);case"openclaw":return!1}}function Ao(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Q0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function pd(t){switch(t){case"claude-code":return J0.join("/");case"codex":return X0.join("/");case"hermes":return Z0.join("/");case"openclaw":return""}}var ko=class extends pt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=si("codex",e.command,i),d=e.isolateCodexHome?Pb(Ob(Db(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(x),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=Nt("codex",e.modeId)?Ao(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e(Lb(r)))}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Rb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function Lb(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=Q0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}te();var Nb=j("hermes-downstream"),To=class extends pt{framework="hermes";modelId;constructor(e){let r={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(r),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(r){Nb.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(r)})}}};Ke();var Mb=3e4,Ur=class extends pt{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}`}]},Mb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Gt();Ke();te();Ce();function gd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}ln();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 Co=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)Vi(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 Vi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Xt(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Jt();te();import{constants as ex}from"node:fs";import{access as Bb,readFile as Fb}from"node:fs/promises";import{delimiter as zb,dirname as Ub,join as tx}from"node:path";var Qe=j("framework-detector"),nx={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},Hb=[".exe",".cmd",".bat",".ps1"],Jn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??it,access:e.access??Bb,readFile:e.readFile??Fb}}async detect(e){let r=nx[e],i=await this.which(r);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return Qe.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(nx).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(zb).filter(Boolean),i=this.env.platform==="win32"?["",...Hb]:[""];for(let o of r)for(let c of i){let d=tx(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?ex.F_OK:ex.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let r;try{r=await this.env.readFile(e,"utf8")}catch(d){return Qe.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let o=r.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return Qe.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let c=tx(Ub(o),"hermes-acp");return await this.isExecutable(c)?(Qe.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:c}),c):(Qe.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:c}),null)}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return Qe.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return Qe.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 Qe.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 Qe.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?(Qe.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}:(Qe.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return Qe.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 Qe.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||Qe.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){Qe.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&&(qb(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,d,u=x=>{c||(c=!0,d&&clearTimeout(d),i(x))};try{let x=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{x.kill("SIGKILL"),u(null)},15e3),x.stdout?.on("data",h=>{o+=h.toString("utf8")}),x.on("error",()=>u(null)),x.on("close",h=>u({code:h,stdout:o}))}catch{u(null)}})}},Gb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function qb(t){return t.replace(Gb,"")}import{homedir as jb}from"node:os";import{join as Wb}from"node:path";Gt();Jt();ar();Ke();te();async function sx(){let t=Wb(jb(),".openclaw/openclaw.json");return ur(t)}async function ox(){return(await sx())?.gateway?.auth?.token??""}var rx=j("openclaw.config"),Kb=[0,5e3,5e3],$b=Ye("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),ix="models.providers.",Po="agents.defaults.models",Ro=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new kn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Kb,this.cliTimeoutMs=e.cliTimeoutMs??$b}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,rx.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new T("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=it(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=h=>{d||(d=!0,clearTimeout(x),h())};o.stderr?.on("data",h=>{c+=h.toString("utf8")});let x=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);x.unref(),o.on("error",h=>u(()=>i(h))),o.on("close",h=>u(()=>{h===0?r():i(new Error(`exit ${h}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",r],["Config path not found","Nothing was changed"])))}catch(i){rx.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",`${ix}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${ix}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Po}[${e}]`,()=>this.runCli(["config","set",Po,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Po}[${e}]`,`${Po}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await sx())?.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 Vb,writeFile as Yb}from"node:fs/promises";import{join as Jb}from"node:path";var Xb=["```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(`
107
- `),Zb=["# 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(`
108
- `);function Qb(t){return t.length===0?t:`${(t.endsWith(`
97
+ `}var Vn=K("hermes-config"),f0="dont_ask",h0="default";function Jn(t,e){return Hi(Ue(t,e).root,"hermes-home")}async function by(t){let e=Jn(t.agentId,t.paths);await yy(e,{recursive:!0,mode:448});let n=zi({...process.env,...Fi(t.paths.agentEnvFile)});await ht(Hi(e,".env"),n,{mode:384});let i=od(t.modelConfig,t.cozeEnv,t.mockScenario);await ht(Hi(e,"config.yaml"),i,{mode:384}),Vn.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function x0(t){let e=Jn(t.agentId,t.paths),n=Hi(e,"state.db"),i=Hi(e,"config.yaml");Vn.warn("[AUDIT] ABOUT TO RM hermes state.db (resetHermesHome)",{src:"hermes-config.resetHermesHome",agentId:t.agentId,home:e,stateDb:n,callerStack:new Error("resetHermesHome-caller").stack?.split(`
98
+ `).slice(1,6).join(" | ")}),await u0(n,{force:!0}).catch(c=>Vn.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(c)}));let o=od({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await ht(i,o,{mode:384}).catch(c=>Vn.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(c)})),Vn.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function cd(t,e){let n=Jn(t,e);Vn.warn("[AUDIT] ABOUT TO RM hermes-home (cleanupHermesHome)",{src:"hermes-config.cleanupHermesHome",agentId:t,home:n,callerStack:new Error("cleanupHermesHome-caller").stack?.split(`
99
+ `).slice(1,6).join(" | ")}),await u0(n,{recursive:!0,force:!0}).catch(i=>Vn.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var ad=new Map;function p0(t){let e=ad.get(t.agentId);if(e)return e;let n=by(t).finally(()=>ad.delete(t.agentId));return ad.set(t.agentId,n),n}var re=K("agent-handlers"),g0=5*1024*1024,Ay=1,ky=6,Ty=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ry=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Py=/^[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)||Py.test(e)?e:(re.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Oy(t){return new Promise((e,n)=>{let i=at("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=l=>{o||(o=!0,l?n(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",l=>c(l))})}function Ly(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var vo=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??Y()}async listSkills(e){e._meta;let n=$n(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Ue(n,this.paths).workspace,c=i?.framework??"claude-code",l=i?.skills??[],{base:u}=Lr(c,n,o,this.paths),h=[],x=new Set;for(let w of l){let v=he(u,w.relPath,"SKILL.md");await pd(v).then(E=>E.isFile()).catch(()=>!1)&&(h.push(zy(w)),x.add(w.relPath))}if(e.scanLocal){let w=await T0(n,o,c,this.paths),v=await R0(n,c);for(let _ of[...w,...v])x.has(_.relPath)||(x.add(_.relPath),h.push(_.skill))}return{skills:c==="hermes"?h.filter(w=>w.skillName!=="yuanbao"):h}}async addSkills(e){e._meta;let n=$n(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],c=[...i.skills??[]],l=new Map(c.map((h,x)=>[h.skillId,x])),u=[];for(let h of o){let x=await So({agentId:n,workspace:i.workspace,framework:i.framework,skill:h,paths:this.paths});Io(c,l,x),u.push(h)}return await li(n,c),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=$n(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),c=i.skills??[],l=[],{base:u}=Lr(i.framework,n,i.workspace,this.paths);for(let h of c){if(!o.has(h.skillId)){l.push(h);continue}let x=he(u,h.relPath);re.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:h.skillId,relPath:h.relPath,skillBase:u,absDir:x}),await ud(x,{recursive:!0,force:!0}),re.info("skill removed",{agentId:n,skillId:h.skillId,relPath:h.relPath})}return await li(n,l),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=$n(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");re.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),o=i?.workspace??Ue(n,this.paths).workspace,c=i?.framework??"claude-code",l=e.isGlobal??!1,u=await My(n,o,c,e.skillName,l,this.paths);if(!u){let O=l?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${O}: ${e.skillName}`)}let{absDir:h,relPath:x,dirName:m}=u,w=he(h,"SKILL.md"),v=new gd.default;v.addLocalFolder(h,m);let _=v.toBuffer();if(_.length>w0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${w0}`);let E=await Eo(w,{encoding:"utf8"}).then(O=>A0(O).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...E?{description:E}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):re.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??I0(n,x);if(i&&!l){let O=i.skills??[],b=O.find(D=>D.relPath===x);b?(b.version=A,b.skillId=T):O.push({skillId:T,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...E?{description:E}:{}}),await li(n,O)}return re.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:T,version:A}),{ok:!0,skillId:T,version:A}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let l=c.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,re.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:l});continue}let h=c.downstream;c.downstream=void 0,re.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:l}),h.stop(n).catch(x=>re.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return re.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await Se(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return re.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await hr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw re.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Ge(i),re.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:i.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async upgradeBridge(e){let n=e.agentId||e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Se(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&Bi(e.registry)&&o.push(`--registry=${e.registry}`);let c=Dy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&Ry.test(l)&&o.push("--env",l);let u=await Oy(o);return re.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Se(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ge(i),re.info("agent disconnected",{agentId:n,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(n,e.reason??"disconnect"),{ok:!0}):(re.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST",`${mt.DELETE}: missing agentId`);re.warn("[AUDIT] deleteAgent handler entry",{agentId:n,reason:e.reason??"",forceParamDeployType:e.deployType,metaDeployType:e._meta?.cozeDeployType,callerStack:new Error("deleteAgent-caller").stack?.split(`
100
+ `).slice(1,6).join(" | ")});let i=await Se(n),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let l=Ue(n);return c==="cloud"?(re.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:n,path:l.root,deployType:c,reason:e.reason??""}),await ud(l.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ge(i)),re.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Pr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=rd(e.model)??kt,i=await Se(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ge(i),re.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return re.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model,l=o.modelInfo;o.model=n,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(x=>re.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=o.framework==="hermes"&&Ly(l,o.modelInfo);if(o.framework==="hermes"&&!u){let x=[];for(let[m,w]of o.allSessionQueues())x.push(w.enqueue(async()=>{let v=o.sessions.get(m);if(!(!v?.downstream||!v.acpSessionId))try{await v.downstream.setSessionModel?.({sessionId:v.acpSessionId,modelId:n})}catch(_){re.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:m,acpId:v.acpSessionId,err:String(_)})}}));return await Promise.all(x),re.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:x.length}),{ok:!0}}let h=[];for(let[x,m]of o.allSessionQueues())h.push(m.enqueue(async()=>{let w=o.sessions.get(x);w?.downstream&&(await w.downstream.stop(`switchModel: ${n}`).catch(()=>{}),w.downstream=void 0)}));return await Promise.all(h),re.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:h.length}),{ok:!0}}async resetAgent(e){if(Pr(e._meta,mt.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${mt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,mt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>re.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,mt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),re.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(n);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,l]of i.sessions)o.set(c,{modelToken:l.modelToken,tokenGeneratedAt:l.tokenGeneratedAt,permissionMode:l.permissionMode,cozeGroupId:l.cozeGroupId});await di(e,o)}async clearPersistedAcpSessionIds(e){let n=await Se(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let o of Object.values(n.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await Ge(n)}async repairAgent(e){if(Pr(e._meta,mt.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${mt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${mt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){re.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,mt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){re.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){re.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Pr(e._meta,"_agent/getFileTree");let n=e._meta,i=$n(n),o=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(o,c),u=await dd(l).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await ci(l,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=Yy(e.depth);return u.isDirectory()?{tree:await Zy(o,l,c,h)}:{tree:[{name:Xy(c),path:D0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Pr(e._meta,"_agent/getFileContent");let n=$n(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await dd(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 ci(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>g0)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${g0})`);let l=await Eo(o);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:c.size}:{content:l.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let n=this.opts.agents.get(e);return n?n.workspace:(await Se(e).catch(()=>null))?.workspace??Ue(e).workspace}safeJoin(e,n){let i=hd(e,n||"."),o=md(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${y0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return Se(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function v0(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new k("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new k("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function Lr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:he(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:he(".agents","skills")};case"hermes":return{base:Jn(e,i??Y()),subdir:"skills"}}}function S0(t){let e=vy();if(t==="claude-code")return[he(e,".claude","skills")];if(t==="codex")return[he(e,".agents","skills"),he(e,".codex","skills")];if(t==="openclaw")return[he(e,".agents","skills"),he(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||he(e,"AppData","Local");return[he(n,"hermes","skills"),he(e,".hermes","skills")]}return[he(e,".hermes","skills")]}return[]}async function Ny(t,e,n,i,o,c){let l=async u=>pd(he(u,"SKILL.md")).then(h=>h.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:h}=Lr(n,t,e,c),x=he(h,i),m=he(u,x);return await l(m)?{absDir:m,relPath:x}:null}for(let u of S0(n)){let h=he(u,i);if(await l(h))return{absDir:h,relPath:h}}return null}async function My(t,e,n,i,o,c){let l=v0(i),u=await Ny(t,e,n,l,o,c);if(u)return{...u,dirName:l};let x=(o?await R0(t,n):await T0(t,e,n,c)).filter(v=>v.skill.skillName===i);if(x.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${x.map(v=>m0(v.relPath)).join(", ")} \u2014 rename or remove duplicates`);let m=x[0];return m?{absDir:o?m.relPath:he(e,m.relPath),relPath:m.relPath,dirName:m0(m.relPath)}:null}function I0(t,e){return(Ey("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function A0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
+ ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let o of n.split(`
102
+ `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let l=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[l]=u)}return i}async function k0(t,e,n,i){let o=await _0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let l of o){let u=l.isDirectory();if(!u&&l.isSymbolicLink()&&(u=!!(await pd(he(e,l.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=l.name,x=he(n,h),m=he(e,h,"SKILL.md"),w=await Eo(m,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let v=A0(w);c.push({relPath:x,skill:{skillId:I0(t,x),skillName:v.name||h,...v.description?{description:v.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function T0(t,e,n,i){let{base:o,subdir:c}=Lr(n,t,e,i);return k0(t,he(o,c),c,!1)}async function R0(t,e){let n=[],i=new Set;for(let o of S0(e)){let c=await k0(t,o,o,!0);for(let l of c)i.has(l.relPath)||(i.add(l.relPath),n.push(l))}return n}var By=3e4,Fy=50*1024*1024,w0=10*1024*1024,Or=3e4;async function So(t){let{agentId:e,workspace:n,framework:i,skill:o,paths:c}=t;if(!o.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let l=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!l&&!u)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let h=v0(o.skillName),{base:x,subdir:m}=Lr(i,e,n,c),w=he(m,h),v=he(x,w);if(await ld(v,{recursive:!0}),l){let E=Buffer.from(o.content,"utf8");qi(E.length),await fd(he(v,"SKILL.md"),E,"utf8")}else{let E=await Gy(o.downloadUrl);qy(E)?await $y(E,v):jy(E)?await Ky(E,v):await fd(he(v,"SKILL.md"),E.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:w,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 re.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:w,source:l?"content":"downloadUrl"}),_}function Io(t,e,n){let i=e.get(n.skillId);if(i!==void 0){t[i]=n;return}e.set(n.skillId,t.length),t.push(n)}function zy(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 Uy(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 P0(t,e){let n=await Se(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Mt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await Ge(n,e),{status:"seeded",count:0};let c=[...n.skills??[]],l=new Map(c.map((w,v)=>[w.skillId,v])),u=c.filter(w=>w.builtin===!0&&!!w.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Ge(n,e),{status:"noop",count:0};let h=0,x=0,{base:m}=Lr(n.framework,t,n.workspace,e);re.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:m,builtinCount:u.length,builtinRelPaths:u.map(w=>w.relPath)});for(let w of u)try{let v=he(m,w.relPath);re.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:w.skillId,relPath:w.relPath,rmTarget:v}),await ud(v,{recursive:!0,force:!0});let _=await So({agentId:t,workspace:n.workspace,framework:n.framework,skill:Uy(w),...e?{paths:e}:{}});Io(c,l,_),h+=1}catch(v){x+=1,re.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:w.skillId,skillName:w.skillName,err:String(v)})}return n.skills=c,x===0&&(n.skillsRefreshedForVersion=i),await Ge(n,e),re.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function Gy(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);qi(e);let n=Hy(t);return qi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Eo(e);return qi(n.length),n}if(Bi(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),By);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return qi(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function qi(t){if(t>Fy)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Hy(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let n=!!e[2],i=e[3]??"";return n?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function qy(t){return t.length>=2&&t[0]===31&&t[1]===139}function jy(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],n=t[3];return e===3&&n===4||e===5&&n===6}function xd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Ky(t,e){let n,i;try{n=new gd.default(t),i=n.getEntries()}catch(l){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${l.message}`,{cause:l})}for(let l of i){let u=l.entryName;if(!u||xd(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 h=l.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=Wy(i),c=hd(e);for(let l of i){if(xd(l.entryName))continue;let u=l.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=hd(e,u),x=md(c,h);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await ld(h,{recursive:!0});continue}await ld(Sy(h),{recursive:!0});let m;try{m=l.getData()}catch(w){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${w.message}`,{cause:w})}await fd(h,m)}}function Wy(t){let e;for(let n of t){let i=n.entryName;if(!i||xd(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 $y(t,e){await Vy(t);let n=Hf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await E0(b0.from(t),n)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Vy(t){let e=[],n=Rr({onReadEntry:c=>{let l=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${l.slice(0,100)}`);return}if(l.startsWith("/")||l.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(l)){e.push(`tar entry absolute path: ${l}`);return}l.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${l}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await E0(b0.from(t),n)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Jy=5e3;async function Zy(t,e,n,i){return C0(t,e,n,i,{count:0})}async function C0(t,e,n,i,o){if(i<=0)return[];let c;try{c=await _0(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if(Ty.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Jy){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=he(e,u.name),x=Iy(he(n,u.name)),m=null;try{m=await dd(h)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let w={name:u.name,path:D0(md(t,h)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(w.children=await C0(t,h,x,i-1,o)),l.push(w)}return l.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),l}function Yy(t){return!t||t<=0?Ay:Math.min(t,ky)}function Xy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function D0(t){return t.split(y0).join("/")}ne();var In=K("agent-health-reporter"),Qy=1e4,eb=3,ji=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Qy,this.livenessFailureThreshold=e.livenessFailureThreshold??eb}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 n=[];for(let l of this.opts.core.agents.values()){let u=tb(l);if(!u)continue;let h={agentId:l.agentId,status:u};l.patToken&&(h.patToken=l.patToken),l.accountId&&(h.accountId=l.accountId),n.push(h)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Mt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(l){this.consecutiveFailures+=1,In.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let c=o?.authFailures;if(c&&c.length>0&&(In.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(l=>l.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(l){In.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){In.warn("onTickEnd hook failed",{err:String(n)})}}};function tb(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Kt();import{mkdir as bd,rm as Qb,stat as eE}from"node:fs/promises";import{homedir as tE}from"node:os";import{join as lh}from"node:path";ln();import{existsSync as fb}from"node:fs";import{release as hb}from"node:os";import{basename as xb,isAbsolute as pb}from"node:path";function Ki(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Nr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Mr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function An(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ve();var Ao=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},X={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function O0(t){return"method"in t&&"id"in t&&t.id!==void 0}function L0(t){return"method"in t&&!("id"in t)}function ko(t){return!("method"in t)&&"id"in t}var nb={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 rb(t){if(t!=null)return t instanceof Error?{name:t.name,message:Wi(t.message)}:typeof t=="string"?Wi(t):typeof t=="object"?sb(t):t}var ib=[[/\/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 Wi(t){let e=t;for(let[n,i]of ib)e=e.replace(n,i);return e}function sb(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Wi(i):e[n]=i;return e}function $i(t){if(t instanceof k){let e=rb(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(n.reason=e.reason),{code:nb[t.code]??X.INTERNAL_ERROR,message:Wi(t.message),data:n}}return{code:X.INTERNAL_ERROR,message:Wi(t instanceof Error?t.message:String(t))}}function N0(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:l,...u}=e;c=u}return new k(n,o,{retriable:e?.retriable??!1,cause:c})}function B0(t){return`${JSON.stringify(t)}
103
+ `}var M0=10*1024*1024,To=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>M0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${M0} bytes`)}),[]}let n=this.buffer.split(`
104
+ `);this.buffer=n.pop()??"";let i=[];for(let o of n){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(l){this.onError?.({line:c,error:l})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(n){return this.onError?.({line:e,error:n}),[]}}};var z0={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission","session/set_mode":"session.setMode",initialize:"initialize"},kT=Object.fromEntries(Object.entries(z0).map(([t,e])=>[e,t])),ob={"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:[]},Br=class{seq=0;next(e,n){this.seq+=1;let i=z0[e]??ab(e),o=ob[i]??[],c=[i,String(this.seq)];if(o.length>0){let l=o.map(h=>F0(n?.[h]??"")),u=cb(l).join(":");u&&c.push(u)}else n&&Object.values(n).some(l=>l)&&c.push(Object.values(n).filter(Boolean).map(l=>F0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function ab(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function F0(t){return t.replace(/[:_\s]+/g,"-")}function cb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Xt();ar();Ve();ne();Pe();import{execFileSync as db,spawnSync as lb}from"node:child_process";function Vi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Ji(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),lb("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var wd=new Set;function U0(t){typeof t=="number"&&t>0&&wd.add(t)}function G0(t){typeof t=="number"&&wd.delete(t)}function H0(){for(let t of wd)Ji(t,"SIGKILL")}var Fr="coze-bridge-daemon";function q0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return db("pgrep",["-U",String(o),"-f",Fr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
105
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function j0(t,e){if(t.length===0)return;let n=e?.killFn??Ji,i=e?.isAliveFn??Vi,o=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),c=e?.graceMs??3e3,l=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<c&&t.some(h=>i(h));u+=l)await o(Math.min(l,c-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var ub=[{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:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function K0(t,e){if(!e)return null;for(let n of ub)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function W0(t,e){return K0(t,e)}function $0(t,e){return K0(t,e)}function zr(t,e,n){return!e&&n.firstUpdateMs>0&&t<n.firstUpdateMs?Math.max(1,n.firstUpdateMs-t):t<n.phase2GateMs?Math.max(1,n.phase2GateMs-t):Math.max(1,n.livenessWindowMs)}function V0(t,e,n){let o=n-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,m=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:zr(m,t.firstFrameSeen,e)}}let c=n-t.startedAt-t.suspendedMs,l=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=l?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:zr(c,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:zr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:zr(c,!1,e)}}var J0=Xe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),mb=200,gb=40,wb=Xe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),_b=Xe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),yb=Xe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),bb=Xe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Eb=Xe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),vb=Xe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Z0=500;function Sb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Z0?t:`${e.slice(0,Z0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Ib(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:n}=t;if(typeof n=="string")e.push(n);else if(n&&typeof n=="object")try{e.push(JSON.stringify(n))}catch{}return e.join(" ")}function Y0(t){try{return fb(t)}catch{return}}function Ab(t,e){return{platform:process.platform,osRelease:hb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:pb(e.command)?Y0(e.command):void 0,cwd:e.cwd,cwdExists:Y0(e.cwd),envKeys:e.envKeys}}function kb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${xb(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var gt=class{constructor(e){this.opts=e;this.log=K(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new To({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Br;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=Zf(process.env,this.opts.agentEnvFile??Y().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=at(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,U0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>mb&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,c)=>{this.stopped=!0,G0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,l=Ab(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(o),diag:l}),this.failAllPending(new k("AGENT_SPAWN_FAILED",kb(c,l),{cause:l}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let n=this.child,i=new Promise(c=>n.once("exit",()=>c()));Ji(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||Ji(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:Eb,phase2GateMs:wb,livenessWindowMs:_b,absoluteMaxMs:yb,approvalMaxMs:vb,suspendThresholdMs:bb,...n};return this.call("session/prompt",e,J0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Nr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Mr(e,n))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(An(e,n))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,n,i=J0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=Ki(c,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let h=n.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let m={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),v={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:zr(0,!1,o),sessionId:u};m.promptTimeout=v;let _=()=>{let E={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},I=this.now(),A=V0(E,v.cfg,I),T=O=>{v.armedAt=I,v.expectedIntervalMs=O,m.timer=setTimeout(_,O)};if(A.action==="suspend"){v.suspendedMs+=A.suspendedDeltaMs,v.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(_,v.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 k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(l)}catch(w){m.timer&&clearTimeout(m.timer),this.pending.delete(c),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(B0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(ko(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new k("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:Sb(e.result)}),n.resolve(e.result));return}if(L0(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(O0(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let l=typeof i.status=="string"?i.status:void 0,u=l==="completed"||l==="failed"||l==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(An(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let n of this.agentRequestHandlers)try{await n(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(An(e.id,$i(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=N0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=$0(this.framework,Ib(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):n}buildExitError(e,n){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(gb).join(`
106
+ `),o=W0(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:n,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Tb(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&(n.startsWith("CLAUDE")||n==="AI_AGENT"||n==="BAGGAGE"||(e[n]=i));return e}var Ro=class extends gt{framework="claude-code";constructor(e){let{command:n,args:i}=ai("claude-code",e.command,e.args??[]),o={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return Tb(e)}};ln();import{mkdtempSync as Rb,rmSync as Pb}from"node:fs";import{tmpdir as Cb}from"node:os";import{join as Db}from"node:path";var X0=["default","acceptEdits","plan","auto","bypassPermissions"],Q0=["read-only","auto","full-access"];var eh=["default","accept_edits","dont_ask"];function Bt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return X0.includes(e);case"codex":return Q0.includes(e);case"hermes":return eh.includes(e);case"openclaw":return!1}}function Po(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function th(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function _d(t){switch(t){case"claude-code":return X0.join("/");case"codex":return Q0.join("/");case"hermes":return eh.join("/");case"openclaw":return""}}var Co=class extends gt{framework="codex";authMethodId;codexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:c}=ai("codex",e.command,i),l=e.isolateCodexHome?Rb(Db(Cb(),"coze-bridge-codex-home-")):void 0,u=l?{...e.env??{},CODEX_HOME:l}:e.env,h={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(h),this.authMethodId=e.authMethodId,this.codexHomeDir=l}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}setSessionMode(e){let n=Bt("codex",e.modeId)?Po(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(Ob(n)))}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Pb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function Ob(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=th(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}ne();var Lb=K("hermes-downstream"),Do=class extends gt{framework="hermes";modelId;constructor(e){let n={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(n),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(n){Lb.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}};Ve();var Nb=3e4,Ur=class extends gt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},Nb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};jt();Ve();ne();Pe();function yd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}ln();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((n,i)=>{this.slots.push({task:e,resolve:n,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let n=await e.task();e.resolve(n)}catch(n){e.reject(n)}}}finally{this.running=!1}}}};var Oo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new kn,this.sessionQueues.set(e,n)),n}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let n=this.sessionQueues.get(e);return!!n&&!n.isDisposed}async dispose(e){this.status="stopped";let n=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(n);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let n=[];for(let[,i]of this.sessions)Zi(i),i.downstream&&(n.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(n),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Zi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Qt(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Xt();ne();import{constants as nh}from"node:fs";import{access as Mb,readFile as Bb}from"node:fs/promises";import{delimiter as Fb,dirname as zb,join as rh}from"node:path";var rt=K("framework-detector"),ih={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},Ub=[".exe",".cmd",".bat",".ps1"],Zn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??at,access:e.access??Mb,readFile:e.readFile??Bb}}async detect(e){let n=ih[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return rt.debug("framework binary not found",{framework:e,bin:n}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,l]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return l&&(u.defaultAgent=l),u}async detectAll(){let e=await Promise.all(Object.keys(ih).map(async i=>[i,await this.detect(i)])),n={};for(let[i,o]of e)o&&(n[i]=o);return n}async which(e){let n=this.env.pathEnv.split(Fb).filter(Boolean),i=this.env.platform==="win32"?["",...Ub]:[""];for(let o of n)for(let c of i){let l=rh(o,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?nh.F_OK:nh.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let n;try{n=await this.env.readFile(e,"utf8")}catch(l){return rt.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(l)}),null}let o=n.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return rt.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let c=rh(zb(o),"hermes-acp");return await this.isExecutable(c)?(rt.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:c}),c):(rt.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:c}),null)}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return rt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return rt.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return rt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return rt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(l=>l?.isDefault===!0);return c?!c.id||!c.workspace?(rt.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}:(rt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return rt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return rt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||rt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let o={reachable:i},c=n.stdout.match(/\{[\s\S]*\}/);if(c)try{let l=JSON.parse(c[0]);typeof l.gateway?.port=="number"&&(o.port=l.gateway.port),typeof l.service?.runtime?.status=="string"&&(o.runtime=l.service.runtime.status),!i&&typeof l.rpc?.error=="string"&&(o.detail=l.rpc.error)}catch(l){rt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(l)})}return o}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(Hb(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let o="",c=!1,l,u=h=>{c||(c=!0,l&&clearTimeout(l),i(h))};try{let h=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});l=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)}})}},Gb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Hb(t){return t.replace(Gb,"")}import{homedir as qb}from"node:os";import{join as jb}from"node:path";jt();Xt();ar();Ve();ne();async function ah(){let t=jb(qb(),".openclaw/openclaw.json");return ur(t)}async function ch(){return(await ah())?.gateway?.auth?.token??""}var sh=K("openclaw.config"),Kb=[0,5e3,5e3],Wb=Xe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),oh="models.providers.",Lo="agents.defaults.models",No=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new kn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Kb,this.cliTimeoutMs=e.cliTimeoutMs??Wb}async withRetry(e,n){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(l=>setTimeout(l,c));try{return await n()}catch(l){i=l,sh.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(l)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=at(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",l=!1,u=x=>{l||(l=!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?n():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let o=String(i);if(n.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",n],["Config path not found","Nothing was changed"])))}catch(i){sh.warn(`${e} failed (best-effort)`,{configPath:n,err:String(i)})}}ensureProvider(e,n){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${oh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${oh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Lo}[${e}]`,()=>this.runCli(["config","set",Lo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Lo}[${e}]`,`${Lo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await ah())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,c=[];for(let l of Object.keys(i))l.startsWith(o)&&c.push(l.slice(o.length));return c}ensureAgent(e,n,i){let o=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}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 $b,writeFile as Vb}from"node:fs/promises";import{join as Jb}from"node:path";var Zb=["```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(`
107
+ `),Yb=["# 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(`
108
+ `);function Xb(t){return t.length===0?t:`${(t.endsWith(`
109
109
  `)?t.slice(0,-1):t).split(`
110
110
  `).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
111
111
  `)}
112
- `}async function ax(t){let e=Jb(t,"HEARTBEAT.md"),r=await Vb(e,"utf8");return Qb(r)!==Xb?!1:(await Yb(e,Zb),!0)}var se=j("agent-manager"),_d="acceptEdits",ux="full-access",fx="read-only";function rE(t){return{INITIAL_AGENT_MODE:Ao(t)}}var iE=(t,e,r,i,o,c,d,u,x,h)=>{switch(t){case"claude-code":{let m={...o?{...i0(o),...a0(o,d,u)}:{},...x??{},IS_SANDBOX:"1"};return new Io({cwd:r,env:m,agentId:i})}case"codex":{let m=ux;h!==void 0&&(Nt("codex",h)?m=h:se.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:h}));let w=!!o,I={...o?{...o0(o),...s0(o,d,u)}:{},...rE(m),...w?{NO_BROWSER:"1"}:{},...x??{}};return new ko({cwd:r,agentId:i,...Object.keys(I).length>0?{env:I}:{},...w?{authMethodId:"api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Ur({command:e,cwd:r,agentId:i,...c?{sessionName:gd(c)}:{}});case"hermes":return new To({command:e,cwd:r,agentId:i,...x&&Object.keys(x).length>0?{env:{...x}}:{},...o?.model?{modelId:o.model}:{}})}};function wd(t){return t==="claude-code"||t==="codex"}var sE={path:"",version:"cloud-deployed"},dx="openclaw_gateway_unavailable",oE="openclaw_default_agent_missing";function lx(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 aE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},cE=6e4,Do=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??iE,this.createTimeoutMs=e.createTimeoutMs??cE,this.detectorFactory=e.detectorFactory??(()=>new Jn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Ro({command:r})),this.openclawConfigDir=e.openclawConfigDir??cx(nE(),".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=>{se.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=cx(e,".env");if(await tE(r).then(c=>c.isFile()).catch(()=>!1)){se.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=Bi({...process.env,...Mi(this.paths.agentEnvFile)});await ut(r,o,{mode:384}),se.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),se.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 ve(e.agentId,this.paths).catch(()=>null),o=xo(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")se.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(P=>se.warn("dispose stale agent failed (ignored)",{err:String(P)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")se.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(P=>se.warn("dispose drifted agent failed (ignored)",{err:String(P)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){se.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let P=await ve(e.agentId,this.paths).catch(()=>null);P&&(P.patToken=e.patToken,await ze(P,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){se.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let P=await ve(e.agentId,this.paths).catch(()=>null);P&&(P.modelInfo=e.modelInfo,await ze(P,this.paths))}return se.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]){let L=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${L}`)}let u=Fe(e.agentId,this.paths),x=o?"cloud":"local",h=e.framework==="openclaw"&&x==="local",m;h&&!r?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=m??(h?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),I=e.workspace??w??u.workspace,b=new AbortController,S=setTimeout(()=>b.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),A,k=!1;try{o&&wd(e.framework)&&await lr(e.framework,b.signal);let P=()=>{if(b.signal.aborted)throw b.signal.reason instanceof Error?b.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await md(u.root,{recursive:!0}),await md(I,{recursive:!0}),await md(u.logs,{recursive:!0}),P(),h||await xr(I,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(x==="cloud"?await Ha(I,"cloud"):await Ha(I,"local",_d)),P();let L=i,E=n0({model:e.model??L?.model}),D=Gf(e._meta)??L?.accountId,N=e.patToken??L?.patToken,z=x==="cloud"?e.modelInfo??L?.modelInfo:void 0;if(A=new Co({agentId:e.agentId,framework:e.framework,workspace:I,model:E.model??It,deployType:x,...D?{accountId:D}:{},...N?{patToken:N}:{},...z?{modelInfo:z}:{}}),A.status="ok",L?.sessions){let V=e.framework==="hermes"||x==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Z,oe]of Object.entries(L.sessions)){let ce={acpSessionId:oe.acpSessionId,modelToken:oe.modelToken,tokenGeneratedAt:oe.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?oe.permissionMode===void 0?(ce.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",se.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Z,framework:e.framework,fallback:ce.permissionMode})):Nt(e.framework,oe.permissionMode)?ce.permissionMode=oe.permissionMode:se.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Z,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&se.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Z,framework:e.framework,deployType:x}),oe.cozeGroupId&&(ce.cozeGroupId=oe.cozeGroupId),A.sessions.set(Z,ce)}let re=Object.keys(L.sessions).length;re>0&&se.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(A),k=!0;let B={agentId:e.agentId,framework:e.framework,workspace:I,cozeIdentity:e.cozeIdentity,createdAt:L?.createdAt??Date.now(),sessions:L?.sessions??{},model:E.model};if(x==="cloud"&&(B.deployType="cloud"),D&&(B.accountId=D),N&&(B.patToken=N),z&&(B.modelInfo=z),L?.skills&&(B.skills=L.skills),L?.agentName&&(B.agentName=L.agentName),L?.description&&(B.description=L.description),B.skillsRefreshedForVersion=L?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&x==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,I)):se.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await ax(I)&&se.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:I})}catch(V){se.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:I,err:String(V)})}}let Y=e.initialSkills??[];if(Y.length>0){let V=[...B.skills??[]],re=new Map(V.map((ce,R)=>[ce.skillId,R])),Z=await Promise.allSettled(Y.map(ce=>yo({agentId:e.agentId,workspace:I,framework:e.framework,skill:ce,paths:this.paths}))),oe=0;for(let[ce,R]of Z.entries()){let G=Y[ce];G&&(R.status==="fulfilled"?(bo(V,re,R.value),oe++):se.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:G.skillId,skillName:G.skillName,err:String(R.reason)}))}oe>0&&(B.skills=V,se.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:Y.length}))}return await ze(B,this.paths),se.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:x}),{ok:!0,agentId:e.agentId,workspace:I,framework:e.framework}}catch(P){throw se.error("agent create failed, rolling back",{agentId:e.agentId,err:String(P)}),k&&A&&(await A.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),se.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:r?.revive===!0,framework:e.framework,errStack:P instanceof Error?P.stack:String(P)}),await eE(u.root,{recursive:!0,force:!0}).catch(L=>se.warn("rm agent dir failed (ignored)",{err:String(L)})),P instanceof T?P:new T("AGENT_SPAWN_FAILED",String(P),{cause:P})}finally{clearTimeout(S)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&wd(e.framework))u=sE;else throw e.framework==="hermes"?new T("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);wd(e.framework)&&!_s(e.framework)&&(se.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await lr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,h;if(e.framework==="openclaw")h=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else if(e.framework==="hermes"){let m={...this.buildBinShimPathEnv()};x&&(await x0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:o,mockScenario:c}),m.HERMES_HOME=Yn(e.agentId,this.paths)),h=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,c,m)}else{let m=e.sessions.get(i),w=Xt(e)?m?.permissionMode??ux:"full-access";h=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,c,this.buildBinShimPathEnv(),w)}try{return await h.start(),await h.initialize(aE),h}catch(m){let w=h instanceof pt?h.getStderrTail():[];throw w.length>0&&se.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof T?m.code:"unknown",recentStderr:w}),await h.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",lx(o),{cause:{reason:dx}})}catch(o){se.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};se.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 se.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:oE}})}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",lx(r),{cause:{reason:dx}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,x=gd(o);if(r.deployType==="local"){let w=await this.ensureOpenclawDefaultAgent();return new Ur({command:u,cwd:w.workspace,agentId:w.id,sessionName:x})}let h=await ox(),m;if(i?.modelToken){let w=ed(o),I=td(i),b=`${w}/${I}`;if(!this.ensuredProviders.has(b)){let S=this.getOpenclawConfig(),A=await S.getAllowlistModelsForProvider(w),k=c0(i,c,d,A);k&&(await S.ensureProvider(w,k),await S.addModelToAllowlist(b),this.ensuredProviders.add(b))}m=b}return new Ur({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:x,...h?{gatewayToken:h}:{},...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=ed(c),u=`${d}/${o}`,x=!0;try{await i.removeProvider(d)}catch(h){x=!1,se.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(h)})}try{await i.removeModelFromAllowlist(u)}catch(h){x=!1,se.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(h)})}x&&this.ensuredProviders.delete(u)}}};import{randomUUID as mx}from"node:crypto";import{promises as pE}from"node:fs";import{basename as _x}from"node:path";Ke();te();import{promises as dE}from"node:fs";import{basename as lE}from"node:path";var xx=j("file-upload"),uE="/api/coze_claw/file/agent_upload",fE=6e4;async function hx(t,e={}){let i=`${Rr(Dr(e.handshakeBase))}${uE}`,o=e.timeoutMs??fE,c=await dE.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}:{}},x=new AbortController,h=setTimeout(()=>x.abort(),o);xx.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:x.signal}),w=m.headers.get("x-tt-logid")??"";if(!m.ok){let S=await m.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${w}: ${S.slice(0,200)}`)}let I=await m.json();if(I.code!==void 0&&I.code!==0)throw new T("UPLOAD_FAILED",`upload code=${I.code} msg=${I.msg??"-"} logid=${w}`);let b=I.data?.file?.file_url;if(!b)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(I).slice(0,200)}`);return xx.info("file upload ok",{uri:b,logid:w}),{uri:b}}catch(m){throw m instanceof T?m:m.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${lE(t.path)}`):new T("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(h)}}Ke();te();import{extname as xE}from"node:path";var hE={".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 px(t){let e=xE(t).toLowerCase();return hE[e]??"application/octet-stream"}Ce();var Oo=j("agent-send"),gx=50*1024*1024;function yx(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 bx(t,e,r,i,o,c){let u;for(let x=0;x<=2;x++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(h){u=h,x<2&&(Oo.warn("sendAgentFileUpdate failed, retrying",{attempt:x+1,err:String(h)}),await new Promise(m=>setTimeout(m,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function Ex(t,e){let{session:r,runtime:i}=yx(e.core,t.agentId,t.sessionId);if(!await oi(t.path,r.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await pE.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>gx)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${gx}`);let c=await px(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??_x(t.path),u;try{u=await hx({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(h){throw Oo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:h instanceof T?h.code:"UNKNOWN",message:h instanceof Error?h.message:String(h)}),h}let x={sessionUpdate:"agent_file",messageId:mx(),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 bx(e,r,i,t.sessionId,x,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Oo.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 vx(t,e){let{session:r,runtime:i}=yx(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??_x(t.path),c={sessionUpdate:"group_file",messageId:mx(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await bx(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Oo.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 Sx(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}Jt();te();ln();var Mt=j("coze-cli-installer"),Ix="@coze/cli@latest",gE="coze",Ax="0.1.8",mE=5e3,wE=5e3,_E=9e4,kx=1e4,Yi=null,Lo=!1;async function bd(t,e={}){if(Lo)return;if(Yi)return Yi;let r=e.exec??$f;return Yi=(async()=>{try{let i=await yE(gE,r),o=!1;if(i){let d=await bE(r);if(d===void 0)Mt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Sx(d,Ax))Mt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:Ax}),o=!0;else{Mt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Lo=!0;return}}let c=o?"upgrade-only":"full";Mt.info("coze-cli install start",{package:Ix,mode:c});try{await r("npm",["i","-g","--prefer-online",Ix],{timeout:_E,maxBuffer:10*1024*1024}),Mt.info("coze-cli install ok")}catch(d){Mt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Lo=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:kx}),Mt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Mt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:kx}),Mt.info("coze auth login ok")}catch(d){Mt.warn("coze auth login failed",{err:String(d)});return}Lo=!0}finally{Yi=null}})(),Yi}async function yE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:mE});return za(i)}catch{return}}async function bE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:wE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}qt();Gt();Ce();var EE=10*6e4;function Tx(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?EE:e}function No(t){return ur(t??J().configFile)}function Ji(t,e){return fr(e??J().configFile,t)}import{randomBytes as GE}from"node:crypto";ar();Ke();te();import{createReadStream as vE}from"node:fs";import{mkdir as SE,readFile as IE,realpath as AE,stat as kE,writeFile as TE}from"node:fs/promises";import{basename as CE,dirname as Ed,isAbsolute as PE,join as RE,relative as DE,resolve as Cx,sep as OE}from"node:path";import{createInterface as LE}from"node:readline";var Rx=j("fs-rpc"),Xi=Ye("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Dx(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Xi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Xi} bytes`);let i=await Lx(t.path,e);return await SE(Ed(i),{recursive:!0}),await TE(i,t.content,"utf8"),Rx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Ox(t,e){let r=await Lx(t.path,e),i=await kE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Xi&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Xi} bytes`);let c;if(o&&i.size>Xi)c=await NE(r,t.line??1,t.limit);else{let d=await IE(r,"utf8");if(o){let u=d.split(`
113
- `),x=Math.max(0,(t.line??1)-1),h=typeof t.limit=="number"?x+t.limit:void 0;c=u.slice(x,h).join(`
114
- `)}else c=d}return Rx.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function NE(t,e,r){let i=LE({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 x of i)if(u>=o&&u<c&&d.push(x),u++,u>=c)break}finally{i.close()}return d.join(`
115
- `)}async function Lx(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([Px(Cx(e)),Px(Cx(t))]),o=DE(r,i);if(ME(o,OE,PE(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 Px(t){let e=[],r=t;for(;r!==Ed(r);)try{let i=await AE(r);return e.length?RE(i,...e.reverse()):i}catch{e.push(CE(r)),r=Ed(r)}return t}te();var Nx=j("prompt-multimodal"),Mx=10*1024*1024,BE=15e3,FE=6;async function Bx(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 zE(d))}}let o=Array.from({length:Math.min(FE,t.length)},()=>i());return await Promise.all(o),e}function Fx(t){return t.some(e=>e.type==="image")}async function zE(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 HE(e.uri),o=e.mimeType||UE(i)||"application/octet-stream";return Nx.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 Nx.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function UE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function HE(t){let e=new AbortController,r=setTimeout(()=>e.abort(),BE);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>Mx)throw new Error(`image too large: ${o.byteLength} bytes (max ${Mx})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}qt();Ke();te();var $=j("core"),qE=3e4,jE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,WE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",KE="\u5BA1\u6279\u5DF2\u8D85\u65F6",$E=3e4,Mo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Br;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=Tx(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){$.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&$.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,d)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),Vi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){$.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(An(o,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(d=>$.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)){$.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(vo(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&&jE.test(i)?this.currentCozeEnv=i:i&&$.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Mr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Mr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Mr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(o){$.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(An(r,Wi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new T("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new T("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new T("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new T("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let x=o.sessions.get(c);if(x?.pendingPermission){let h=r._meta?.cozeTriggerMsgId,m=ho(r._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,x,c,WE,h,m)}}let d=Date.now(),u=!1;try{let x=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,x}finally{$.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}=jf(i);switch(r){case"session/new":{let c=VE();return $.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return $.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,d=c.sessionId;if(!d)throw new T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Xt(e)?qf(i._meta):void 0;if(u!==void 0&&!Nt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${pd(e.framework)}`);let x=await this.ensureRuntime(e,d);if(u!==void 0&&x.permissionMode===void 0&&(x.permissionMode=u,await this.persistSessionMapping(e)),x.replySeq=0,await this.ensureDownstream(e,d,x),!x.downstream||!x.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&x.permissionMode!==void 0&&x.permissionMode!==u){let I=x.permissionMode;x.permissionMode=u,await this.persistSessionMapping(e);try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(b){throw x.permissionMode=I,await this.persistSessionMapping(e).catch(()=>{}),b}}let h=i._meta?.cozeTriggerMsgId;h?e.activeTriggers.set(x.acpSessionId,h):e.activeTriggers.delete(x.acpSessionId);let m=ho(i._meta);if(m?e.activeGroupIds.set(x.acpSessionId,m):e.activeGroupIds.delete(x.acpSessionId),m&&x.cozeGroupId!==m&&(x.cozeGroupId=m,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Fx(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let w=await Bx(c.prompt);try{let I=await x.downstream.sessionPrompt({...c,sessionId:x.acpSessionId,prompt:w});return x.lastActiveAt=Date.now(),I}catch(I){if(I instanceof T&&I.code==="AGENT_APPROVAL_TIMEOUT"){let b=x.pendingPermission;b&&(b.downstream.respondAgentRequest(b.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(b.upstreamId),x.pendingPermission=void 0);let S=x.acpSessionId,A=S?e.activeTriggers.get(S):void 0,k=S?e.activeGroupIds.get(S):void 0;return $.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,x,d,KE,A,k)}throw I}finally{if(e.activeTriggers.delete(x.acpSessionId),e.activeGroupIds.delete(x.acpSessionId),x.pendingPermission=void 0,x.reloadAfterTurn){x.reloadAfterTurn=!1;let I=x.downstream;I&&(x.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:x.acpSessionId}),I.stop("reload-after-turn").catch(b=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(b)})))}else x.downstream?.isAlive()&&this.armIdleTimer(e,d,x)}}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 x=e.getSessionQueue(d);x.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:x.size}),x.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,x=ho(i._meta);if(!d)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Xt(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(!Nt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${pd(e.framework)}`);if(x)return await this.handleGroupSetMode(e,x,u);let h=e.sessions.get(d)??await this.ensureRuntime(e,d);if(h.permissionMode===u)return{};let m=h.permissionMode;if(h.permissionMode=u,await this.persistSessionMapping(e),h.downstream?.isAlive()&&h.acpSessionId)try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(w){throw h.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),w}else $.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 $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};$.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of o){let u=d.runtime.downstream,x=d.runtime.acpSessionId;u?.isAlive()&&x&&c.push({downstream:u,acpSessionId:x,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 x of o)x.runtime.permissionMode=x.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r){let i=e.sessions.get(r);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Xt(e)&&(e.framework==="hermes"?c.permissionMode=e.deployType==="cloud"?l0:u0:c.permissionMode=e.framework==="claude-code"?_d:fx),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,$E);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(Vi(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 x;try{x=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(h){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&($.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),h}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=x,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await x.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),$.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(h){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),i.acpSessionId=void 0;let m=await x.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let h=await x.sessionNew({cwd:e.workspace});i.acpSessionId=h.sessionId,await this.persistSessionMapping(e)}}catch(h){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),await x.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,h}if(x.afterSessionEstablished&&i.acpSessionId&&await x.afterSessionEstablished(i.acpSessionId),Xt(e)&&i.acpSessionId&&i.permissionMode)try{await x.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(h){$.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(h)})}}armIdleTimer(e,r,i){if(Vi(i),this.isRuntimeBusy(e,i)){$.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}$.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>$.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let 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(Nr("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(Nr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(x=>$.warn("synthesizePromptReply update send failed (ignored)",{err:String(x)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){$.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){$.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(XE(r)){$.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"&&Xt(e)){let m=d.currentModeId;Nt(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(w=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof m=="string"&&!Nt(e.framework,m)&&$.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},x=e.activeTriggers.get(i);x&&(u.cozeTriggerMsgId=x);let h=e.activeGroupIds.get(i);h&&(u.cozeGroupId=h),this.upstream.send(Nr("session/update",{...r,sessionId:o,_meta:u})).catch(m=>$.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}$.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 Dx(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await Ox(c,o);r.respondAgentRequest(i.id,d)}}catch(o){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Wi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,x=u?e.activeTriggers.get(u):void 0,h={cozeAgentId:e.agentId};x&&(h.cozeTriggerMsgId=x);let m=u?e.activeGroupIds.get(u):void 0;m&&(h.cozeGroupId=m);let w=u?this.reverseSessionId(e,u):void 0,I=w?e.sessions.get(w):void 0;I&&(I.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let b={...c,...w?{sessionId:w}:{},_meta:h};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:w}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:w,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(S=>({optionId:S.optionId,kind:S.kind,name:S.name}))}),this.upstream.send(qi(o,"session/request_permission",b)).catch(S=>{this.pendingUpstream.delete(o),$.error("forward permission request failed",{agentId:e.agentId,err:String(S)}),r.respondAgentRequestError(i.id,{code:X.INTERNAL_ERROR,message:`upstream send failed: ${String(S)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?($.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&YE(e.result,o),$.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new Eo(e.error)):i.value.resolve(e.result);return}$.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),d=e.get(c);if(d)return $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:d,key:c}}}sendRequest(e,r,i=qE){let o=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(qi(o,e,r)).catch(x=>{let h=this.pendingBridge.get(o);h&&(clearTimeout(h.timer),this.pendingBridge.delete(o)),d(x)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Xt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await ai(e.agentId,r,this.paths)}catch(r){$.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(An(e,{code:r,message:i,data:{bridgeVersion:Lt}}))}};function VE(){return GE(16).toString("hex")}function YE(t,e){if(!t||typeof t!="object"){$.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){$.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){$.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&$.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var JE=["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."],zx="Warning: ";function XE(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(zx)?i.text.slice(zx.length):i.text;return JE.some(c=>o.startsWith(c))}Gt();te();Ce();import{randomBytes as ZE}from"node:crypto";import{createServer as QE}from"node:http";var ev=1e6,Ux=j("ipc"),Bo=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??J()}async start(){this.token=ZE(32).toString("hex");let e=QE((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(),Ux.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 ut(this.paths.portFile,String(this.port)),await ut(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Zi(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Zi(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await tv(e)}catch(u){Zi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Zi(r,200,u??{ok:!0})}catch(u){Ux.error("IPC handler failed",{key:o,err:String(u)}),Zi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Zi(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function tv(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>ev)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 E1=Ht(Nh(),1),v1=Ht(Ko(),1),S1=Ht(qr(),1),I1=Ht(Od(),1),A1=Ht(Md(),1),k1=Ht(Gd(),1),jh=Ht(Jo(),1),T1=Ht(qh(),1);var Wh=jh.default;Ke();te();var{FWS:j1}=np(),De=j("upstream.frontier"),ip="application/json",sp="none",W1=15e3;function K1(t){class e extends Wh{constructor(i){super(i,Jf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>De.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(Ol("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");De.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){De.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var as=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){De.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Xf,...Sn(this.opts.ppeOverride)},r=K1(e),i=Qf(this.opts.urlOverride),o={url:i,ws:r,fpID:Yf,aID:po,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:ip,force:!0},payloadEncoding:{encoding:sp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new j1(o),d=!1,u=null,x,h,m=new Promise((b,S)=>{x=b,h=S}),w=b=>{d||(d=!0,u&&(clearTimeout(u),u=null),b?h(b):x())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let b=this.openCount===1;De.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:b,openCount:this.openCount}),b&&w();for(let S of this.connectHandlers)Promise.resolve(S({initial:b})).catch(A=>De.warn("onConnect handler threw (ignored)",{err:String(A)}))},c.onclose=b=>{this.opened=!1,De.info("frontier closed",{code:b.code,reason:b.reason,willReconnect:b.willReconnect})},c.onerror=b=>{De.warn("frontier error",{code:b.code,msg:b.message}),w(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${b.code} msg=${b.message??""}`))},c.onmessage=b=>this.handleMessage(b),this.fws=c;let I=this.opts.openTimeoutMs??W1;u=setTimeout(()=>{w(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${I}ms (handshake or upgrade slow)`))},I),await c.connect();try{await m}catch(b){try{c.close(1e3,"open failed")}catch(S){De.warn("fws close during start failure threw (ignored)",{err:String(S)})}throw this.fws=null,this.opened=!1,b}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){De.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw De.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?(De.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;op(c)||De.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:ip,payloadEncoding:sp})}catch(u){throw De.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){De.debug("drop non-adapter frontier frame",{service:r});return}let i=Y1(e);if(!i){De.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){De.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){De.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;op(c)||De.info("frontier frame in",{logid:V1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:$1(i)}),Promise.resolve(this.handler(o)).catch(d=>De.warn("frontier frame handler threw",{err:String(d)}))}};function op(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var ap=2e3;function $1(t){return t.length<=ap?t:`${t.slice(0,ap)}...<truncated, total ${t.length} chars>`}function V1(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}}Ke();te();var Kd=j("skill-publish"),J1="/api/marketplace/product/skill/publish_with_assets",X1=15e4;async function cp(t,e={}){let i=`${Rr(Dr(e.handshakeBase))}${J1}`,o=e.timeoutMs??X1,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,x=setTimeout(()=>u.abort(),o);Kd.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 h=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),m=h.headers.get("x-tt-logid")??"";if(!h.ok){let b=await h.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${h.status} logid=${m}: ${b.slice(0,200)}`)}let w=await h.json();if(Kd.info("skill publish response",{logid:m,httpStatus:h.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${m}`);let I={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(I.skillId=String(w.data.skill_id)),w.data?.version&&(I.version=w.data.version),Kd.info("skill publish ok",{logid:m,skillId:I.skillId??"",version:I.version??""}),I}catch(h){throw h instanceof T?h:h.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(h),{cause:h})}finally{clearTimeout(x)}}te();var $d=j("upstream.switchable"),sa=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;$d.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 $d.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>$d.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};te();var Vd=j("upstream"),Yr=class{handler=null;async start(){Vd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Vd.info("NoopUpstream stopped",{reason:e})}async send(e){Vd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Ke();te();Gt();te();Ce();import{promises as Z1}from"node:fs";var dp=j("pat-token-store");async function oa(t=J()){try{let r=(await Z1.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(dp.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"&&dp.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function cs(t,e=J()){if(!t)throw new Error("writePatToken: empty patToken");await ut(e.patTokenFile,t,{mode:384})}Ce();Ce();import{promises as aa}from"node:fs";import{join as Q1}from"node:path";function eS(t,e){return`#!/bin/sh
112
+ `}async function dh(t){let e=Jb(t,"HEARTBEAT.md"),n=await $b(e,"utf8");return Xb(n)!==Zb?!1:(await Vb(e,Yb),!0)}var ae=K("agent-manager"),vd="acceptEdits",hh="full-access",xh="read-only";function nE(t){return{INITIAL_AGENT_MODE:Po(t)}}var rE=(t,e,n,i,o,c,l,u,h,x)=>{switch(t){case"claude-code":{let m={...o?{...o0(o),...d0(o,l,u)}:{},...h??{},IS_SANDBOX:"1"};return new Ro({cwd:n,env:m,agentId:i})}case"codex":{let m=hh;x!==void 0&&(Bt("codex",x)?m=x:ae.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let w=!!o,v={...o?{...c0(o),...a0(o,l,u)}:{},...nE(m),...w?{NO_BROWSER:"1"}:{},...h??{}};return new Co({cwd:n,agentId:i,...Object.keys(v).length>0?{env:v}:{},...w?{authMethodId:"api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Ur({command:e,cwd:n,agentId:i,...c?{sessionName:yd(c)}:{}});case"hermes":return new Do({command:e,cwd:n,agentId:i,...h&&Object.keys(h).length>0?{env:{...h}}:{},...o?.model?{modelId:o.model}:{}})}};function Ed(t){return t==="claude-code"||t==="codex"}var iE={path:"",version:"cloud-deployed"},uh="openclaw_gateway_unavailable",sE="openclaw_default_agent_missing";function fh(t){let e=[t.port!==void 0?`port=${t.port}`:"",t.runtime?`runtime=${t.runtime}`:"",t.detail??""].filter(Boolean).join(", ");return`openclaw gateway \u672A\u8FD0\u884C/\u4E0D\u53EF\u8FBE${e?` (${e})`:""}; \u8BF7\u542F\u52A8 openclaw gateway`}var oE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},aE=6e4,Mo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??rE,this.createTimeoutMs=e.createTimeoutMs??aE,this.detectorFactory=e.detectorFactory??(()=>new Zn),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new No({command:n})),this.openclawConfigDir=e.openclawConfigDir??lh(tE(),".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=>{ae.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=lh(e,".env");if(await eE(n).then(c=>c.isFile()).catch(()=>!1)){ae.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=zi({...process.env,...Fi(this.paths.agentEnvFile)});await ht(n,o,{mode:384}),ae.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ae.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await Se(e.agentId,this.paths).catch(()=>null),o=go(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")ae.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>ae.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")ae.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>ae.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){ae.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await Se(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Ge(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ae.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await Se(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Ge(T,this.paths))}return ae.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]){let O=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${O}`)}let u=Ue(e.agentId,this.paths),h=o?"cloud":"local",x=e.framework==="openclaw"&&h==="local",m;x&&!n?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=m??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??w??u.workspace,_=new AbortController,E=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&Ed(e.framework)&&await lr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await bd(u.root,{recursive:!0}),await bd(v,{recursive:!0}),await bd(u.logs,{recursive:!0}),T(),x||await hr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await Ka(v,"cloud"):await Ka(v,"local",vd)),T();let O=i,b=i0({model:e.model??O?.model}),D=jf(e._meta)??O?.accountId,L=e.patToken??O?.patToken,G=h==="cloud"?e.modelInfo??O?.modelInfo:void 0;if(I=new Oo({agentId:e.agentId,framework:e.framework,workspace:v,model:b.model??kt,deployType:h,...D?{accountId:D}:{},...L?{patToken:L}:{},...G?{modelInfo:G}:{}}),I.status="ok",O?.sessions){let J=e.framework==="hermes"||h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Q,ce]of Object.entries(O.sessions)){let de={acpSessionId:ce.acpSessionId,modelToken:ce.modelToken,tokenGeneratedAt:ce.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};J?ce.permissionMode===void 0?(de.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",ae.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Q,framework:e.framework,fallback:de.permissionMode})):Bt(e.framework,ce.permissionMode)?de.permissionMode=ce.permissionMode:ae.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Q,framework:e.framework,value:ce.permissionMode}):ce.permissionMode!==void 0&&ae.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Q,framework:e.framework,deployType:h}),ce.cozeGroupId&&(de.cozeGroupId=ce.cozeGroupId),I.sessions.set(Q,de)}let ie=Object.keys(O.sessions).length;ie>0&&ae.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ie})}this.registry.register(I),A=!0;let U={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:O?.createdAt??Date.now(),sessions:O?.sessions??{},model:b.model};if(h==="cloud"&&(U.deployType="cloud"),D&&(U.accountId=D),L&&(U.patToken=L),G&&(U.modelInfo=G),O?.skills&&(U.skills=O.skills),O?.agentName&&(U.agentName=O.agentName),O?.description&&(U.description=O.description),U.skillsRefreshedForVersion=O?.skillsRefreshedForVersion??Mt,e.framework==="openclaw"&&h==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):ae.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await dh(v)&&ae.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:v})}catch(J){ae.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:v,err:String(J)})}}let Z=e.initialSkills??[];if(Z.length>0){let J=[...U.skills??[]],ie=new Map(J.map((de,P)=>[de.skillId,P])),Q=await Promise.allSettled(Z.map(de=>So({agentId:e.agentId,workspace:v,framework:e.framework,skill:de,paths:this.paths}))),ce=0;for(let[de,P]of Q.entries()){let H=Z[de];H&&(P.status==="fulfilled"?(Io(J,ie,P.value),ce++):ae.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:H.skillId,skillName:H.skillName,err:String(P.reason)}))}ce>0&&(U.skills=J,ae.info("initialSkills installed",{agentId:e.agentId,installed:ce,requested:Z.length}))}return await Ge(U,this.paths),ae.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(T){throw ae.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),ae.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:n?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await Qb(u.root,{recursive:!0,force:!0}).catch(O=>ae.warn("rm agent dir failed (ignored)",{err:String(O)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,n,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&Ed(e.framework))u=iE;else throw e.framework==="hermes"?new k("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Ed(e.framework)&&!vs(e.framework)&&(ae.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await lr(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else if(e.framework==="hermes"){let m={...this.buildBinShimPathEnv()};h&&(await p0({paths:this.paths,agentId:e.agentId,modelConfig:h,cozeEnv:o,mockScenario:c}),m.HERMES_HOME=Jn(e.agentId,this.paths)),x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,o,c,m)}else{let m=e.sessions.get(i),w=Qt(e)?m?.permissionMode??hh:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,o,c,this.buildBinShimPathEnv(),w)}try{return await x.start(),await x.initialize(oE),x}catch(m){let w=x instanceof gt?x.getStderrTail():[];throw w.length>0&&ae.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof k?m.code:"unknown",recentStderr:w}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,m)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let o=await this.detectorFactory().probeOpenclawGateway(n);if(!o.reachable)return new k("AGENT_ENV_NOT_READY",fh(o),{cause:{reason:uh}})}catch(o){ae.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};ae.warn("openclaw default agent stale or missing, attempting lazy re-detect");let n=await this.detectorFactory().detect("openclaw");if(n?.defaultAgent?.id&&n.defaultAgent.workspace)return ae.info("openclaw lazy re-detect success",{agentId:n.defaultAgent.id,workspace:n.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=n,{id:n.defaultAgent.id,workspace:n.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:sE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new k("AGENT_ENV_NOT_READY",fh(n),{cause:{reason:uh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:l,command:u}=e,h=yd(o);if(n.deployType==="local"){let w=await this.ensureOpenclawDefaultAgent();return new Ur({command:u,cwd:w.workspace,agentId:w.id,sessionName:h})}let x=await ch(),m;if(i?.modelToken){let w=id(o),v=sd(i),_=`${w}/${v}`;if(!this.ensuredProviders.has(_)){let E=this.getOpenclawConfig(),I=await E.getAllowlistModelsForProvider(w),A=l0(i,c,l,I);A&&(await E.ensureProvider(w,A),await E.addModelToAllowlist(_),this.ensuredProviders.add(_))}m=_}return new Ur({command:u,cwd:n.workspace,agentId:n.agentId,sessionName:h,...x?{gatewayToken:x}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=n??e.model;for(let c of e.sessions.keys()){let l=id(c),u=`${l}/${o}`,h=!0;try{await i.removeProvider(l)}catch(x){h=!1,ae.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:l,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,ae.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as _h}from"node:crypto";import{promises as xE}from"node:fs";import{basename as yh}from"node:path";Ve();ne();import{promises as cE}from"node:fs";import{basename as dE}from"node:path";var ph=K("file-upload"),lE="/api/coze_claw/file/agent_upload",uE=6e4;async function mh(t,e={}){let i=`${Cr(Dr(e.handshakeBase))}${lE}`,o=e.timeoutMs??uE,c=await cE.readFile(t.path),l=new FormData;l.append("agent_id",t.agentId),l.append("session_id",t.sessionId),l.append("file_name",t.name),l.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Sn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),o);ph.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:l,signal:h.signal}),w=m.headers.get("x-tt-logid")??"";if(!m.ok){let E=await m.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${w}: ${E.slice(0,200)}`)}let v=await m.json();if(v.code!==void 0&&v.code!==0)throw new k("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${w}`);let _=v.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(v).slice(0,200)}`);return ph.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(m){throw m instanceof k?m:m.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${dE(t.path)}`):new k("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(x)}}Ve();ne();import{extname as fE}from"node:path";var hE={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function gh(t){let e=fE(t).toLowerCase();return hE[e]??"application/octet-stream"}Pe();var Bo=K("agent-send"),wh=50*1024*1024;function bh(t,e,n){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(n);if(!o)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function Eh(t,e,n,i,o,c){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,n,i,o);return}catch(x){u=x,h<2&&(Bo.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(m=>setTimeout(m,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function vh(t,e){let{session:n,runtime:i}=bh(e.core,t.agentId,t.sessionId);if(!await ci(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await xE.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>wh)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${wh}`);let c=await gh(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let l=t.name??yh(t.path),u;try{u=await mh({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:l,sizeBytes:o.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Bo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:x instanceof k?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:_h(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:l,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Eh(e,n,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Bo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:l,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Sh(t,e){let{session:n,runtime:i}=bh(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??yh(t.path),c={sessionUpdate:"group_file",messageId:_h(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Eh(e,n,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Bo.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:o,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function Ih(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(n.length,i.length);for(let c=0;c<o;c++){let l=n[c]??0,u=i[c]??0;if(l<u)return!0;if(l>u)return!1}return!1}Xt();ne();ln();var Ft=K("coze-cli-installer"),Ah="@coze/cli@latest",pE="coze",kh="0.1.8",mE=5e3,gE=5e3,wE=9e4,Th=1e4,Yi=null,Fo=!1;async function Id(t,e={}){if(Fo)return;if(Yi)return Yi;let n=e.exec??Jf;return Yi=(async()=>{try{let i=await _E(pE,n),o=!1;if(i){let l=await yE(n);if(l===void 0)Ft.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Ih(l,kh))Ft.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:kh}),o=!0;else{Ft.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),Fo=!0;return}}let c=o?"upgrade-only":"full";Ft.info("coze-cli install start",{package:Ah,mode:c});try{await n("npm",["i","-g","--prefer-online",Ah],{timeout:wE,maxBuffer:10*1024*1024}),Ft.info("coze-cli install ok")}catch(l){Ft.warn("coze-cli install failed (skip subsequent steps)",{err:String(l)});return}if(o){Fo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:Th}),Ft.info("coze config set xTTEnv ok",{env:t.env})}catch(l){Ft.warn("coze config set failed (continue to auth login)",{err:String(l)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:Th}),Ft.info("coze auth login ok")}catch(l){Ft.warn("coze auth login failed",{err:String(l)});return}Fo=!0}finally{Yi=null}})(),Yi}async function _E(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:mE});return qa(i)}catch{return}}async function yE(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:gE});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Kt();jt();Pe();var bE=10*6e4;function Rh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?bE:e}function zo(t){return ur(t??Y().configFile)}function Xi(t,e){return fr(e??Y().configFile,t)}import{randomBytes as GE}from"node:crypto";ar();Ve();ne();import{createReadStream as EE}from"node:fs";import{mkdir as vE,readFile as SE,realpath as IE,stat as AE,writeFile as kE}from"node:fs/promises";import{basename as TE,dirname as Ad,isAbsolute as RE,join as PE,relative as CE,resolve as Ph,sep as DE}from"node:path";import{createInterface as OE}from"node:readline";var Dh=K("fs-rpc"),Qi=Xe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Oh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>Qi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${Qi} bytes`);let i=await Nh(t.path,e);return await vE(Ad(i),{recursive:!0}),await kE(i,t.content,"utf8"),Dh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Lh(t,e){let n=await Nh(t.path,e),i=await AE(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Qi&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Qi} bytes`);let c;if(o&&i.size>Qi)c=await LE(n,t.line??1,t.limit);else{let l=await SE(n,"utf8");if(o){let u=l.split(`
113
+ `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;c=u.slice(h,x).join(`
114
+ `)}else c=l}return Dh.info("fs/read_text_file ok",{path:n,size:c.length}),{content:c}}async function LE(t,e,n){let i=OE({input:EE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof n=="number"?o+n:Number.POSITIVE_INFINITY,l=[],u=0;try{for await(let h of i)if(u>=o&&u<c&&l.push(h),u++,u>=c)break}finally{i.close()}return l.join(`
115
+ `)}async function Nh(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([Ch(Ph(e)),Ch(Ph(t))]),o=CE(n,i);if(NE(o,DE,RE(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function NE(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Ch(t){let e=[],n=t;for(;n!==Ad(n);)try{let i=await IE(n);return e.length?PE(i,...e.reverse()):i}catch{e.push(TE(n)),n=Ad(n)}return t}ne();var Mh=K("prompt-multimodal"),Bh=10*1024*1024,ME=15e3,BE=6;async function Fh(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let c=n++,l=t[c];l!==void 0&&(e[c]=await FE(l))}}let o=Array.from({length:Math.min(BE,t.length)},()=>i());return await Promise.all(o),e}function zh(t){return t.some(e=>e.type==="image")}async function FE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Bi(e.uri))return t;try{let{buf:n,contentType:i}=await UE(e.uri),o=e.mimeType||zE(i)||"application/octet-stream";return Mh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:o}),{type:"image",data:n.toString("base64"),mimeType:o}}catch(n){return Mh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function zE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function UE(t){let e=new AbortController,n=setTimeout(()=>e.abort(),ME);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>Bh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Bh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}Kt();Ve();ne();var V=K("core"),HE=3e4,qE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,jE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",KE="\u5BA1\u6279\u5DF2\u8D85\u65F6",WE=3e4,Uo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Br;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=Rh(e.bridgeConfig)}registerExtension(e,n){this.extensions[e]=n}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}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(n=>n.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of n)await this.agents.get(i)?.killAllRuntimes("reload");return n}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),V.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(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,n,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,l)=>{V.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:c,signal:l}),Zi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){V.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(An(o,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(l=>V.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:X.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){V.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:X.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(ko(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&qE.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){n!==null?await this.sendError(n,X.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);n!==null&&await this.upstream.send(Mr(n,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Mr(n,o));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Mr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,X.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)}),n!==null&&await this.upstream.send(An(n,$i(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,n);if(e.method==="session/prompt"){let h=o.sessions.get(c);if(h?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,m=wo(n._meta);return V.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,h,c,jE,x,m)}}let l=Date.now(),u=!1;try{let h=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return u=!0,h}finally{V.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-l,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=Wf(i);switch(n){case"session/new":{let c=$E();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,l=c.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Qt(e)?Kf(i._meta):void 0;if(u!==void 0&&!Bt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${_d(e.framework)}`);let h=await this.ensureRuntime(e,l);if(u!==void 0&&h.permissionMode===void 0&&(h.permissionMode=u,await this.persistSessionMapping(e)),h.replySeq=0,await this.ensureDownstream(e,l,h),!h.downstream||!h.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&h.permissionMode!==void 0&&h.permissionMode!==u){let v=h.permissionMode;h.permissionMode=u,await this.persistSessionMapping(e);try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(_){throw h.permissionMode=v,await this.persistSessionMapping(e).catch(()=>{}),_}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(h.acpSessionId,x):e.activeTriggers.delete(h.acpSessionId);let m=wo(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&&zh(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let w=await Fh(c.prompt);try{let v=await h.downstream.sessionPrompt({...c,sessionId:h.acpSessionId,prompt:w});return h.lastActiveAt=Date.now(),v}catch(v){if(v instanceof k&&v.code==="AGENT_APPROVAL_TIMEOUT"){let _=h.pendingPermission;_&&(_.downstream.respondAgentRequest(_.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(_.upstreamId),h.pendingPermission=void 0);let E=h.acpSessionId,I=E?e.activeTriggers.get(E):void 0,A=E?e.activeGroupIds.get(E):void 0;return V.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:l}),await this.synthesizePromptReply(e,h,l,KE,I,A)}throw v}finally{if(e.activeTriggers.delete(h.acpSessionId),e.activeGroupIds.delete(h.acpSessionId),h.pendingPermission=void 0,h.reloadAfterTurn){h.reloadAfterTurn=!1;let v=h.downstream;v&&(h.downstream=void 0,V.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:h.acpSessionId}),v.stop("reload-after-turn").catch(_=>V.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(_)})))}else h.downstream?.isAlive()&&this.armIdleTimer(e,l,h)}}case"session/cancel":{let l=o.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(l);if(e.hasSessionQueue(l)){let h=e.getSessionQueue(l);h.size>0&&(V.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:h.size}),h.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${l}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,l=c.sessionId,u=c.modeId,h=wo(i._meta);if(!l)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Qt(e))throw e.framework==="openclaw"?new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new k("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Bt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${_d(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(l)??await this.ensureRuntime(e,l);if(x.permissionMode===u)return{};let m=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(w){throw x.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),w}else V.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:l,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[l,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&o.push({cloudId:l,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:n,modeId:i}),{};V.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:o.length});for(let l of o)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let l of o){let u=l.runtime.downstream,h=l.runtime.acpSessionId;u?.isAlive()&&h&&c.push({downstream:u,acpSessionId:h,oldMode:l.oldMode,runtime:l.runtime})}for(let l of c)try{await l.downstream.setSessionMode({sessionId:l.acpSessionId,modeId:i})}catch(u){for(let h of o)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n){let i=e.sessions.get(n);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Qt(e)&&(e.framework==="hermes"?c.permissionMode=e.deployType==="cloud"?f0:h0:c.permissionMode=e.framework==="claude-code"?vd:xh),e.sessions.set(n,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,n){let i={sessionId:n,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(mt.GEN_MODEL_TOKEN,i,WE);if(!o?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);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,n,i){if(Zi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=o&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${l} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let h;try{h=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=l+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(V.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=h,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await h.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),V.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){V.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let m=await h.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw V.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),Qt(e)&&i.acpSessionId&&i.permissionMode)try{await h.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:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(Zi(i),this.isRuntimeBusy(e,i)){V.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){V.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}V.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>V.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let l=e.activeTriggers.get(n.acpSessionId);l&&(c.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(n.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Nr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,n,i,o,c,l){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return c&&(u.cozeTriggerMsgId=c),l&&(u.cozeGroupId=l),await this.upstream.send(Nr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(h=>V.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.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(ZE(n)){V.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=n.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&Qt(e)){let m=l.currentModeId;Bt(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(w=>V.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof m=="string"&&!Bt(e.framework,m)&&V.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(Nr("session/update",{...n,sessionId:o,_meta:u})).catch(m=>V.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}V.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:X.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},l=await Oh(c,o);n.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await Lh(c,o);n.respondAgentRequest(i.id,l)}}catch(o){V.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,$i(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,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 w=u?this.reverseSessionId(e,u):void 0,v=w?e.sessions.get(w):void 0;v&&(v.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...c,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:w}),V.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:w,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(Ki(o,"session/request_permission",_)).catch(E=>{this.pendingUpstream.delete(o),V.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),n.respondAgentRequestError(i.id,{code:X.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let o=n.value;this.clearPendingPermissionFor(o),e.error?(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"&&VE(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 Ao(e.error)):i.value.resolve(e.result);return}V.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let o=e.get(n);if(o)return{value:o,key:n};if(typeof n=="number"){let c=String(n),l=e.get(c);if(l)return V.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:c}),{value:l,key:c}}}sendRequest(e,n,i=HE){let o=this.upstreamIds.next(e);return new Promise((c,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),l(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:l,timer:u}),this.upstream.send(Ki(o,e,n)).catch(h=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),l(h)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Qt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),n.set(i,c)}await di(e.agentId,n,this.paths)}catch(n){V.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(An(e,{code:n,message:i,data:{bridgeVersion:Mt}}))}};function $E(){return GE(16).toString("hex")}function VE(t,e){if(!t||typeof t!="object"){V.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){V.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=n.outcome;if(!i||typeof i!="object"){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 JE=["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."],Uh="Warning: ";function ZE(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let o=i.text.startsWith(Uh)?i.text.slice(Uh.length):i.text;return JE.some(c=>o.startsWith(c))}jt();ne();Pe();import{randomBytes as YE}from"node:crypto";import{createServer as XE}from"node:http";var QE=1e6,Gh=K("ipc"),Go=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(n=>[`${n.method} ${n.path}`,n])),this.paths=e.paths??Y()}async start(){this.token=YE(32).toString("hex");let e=XE((i,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),Gh.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(o=>o?i(o):n())}),this.server=null)}async persistAuthFiles(){await ht(this.paths.portFile,String(this.port)),await ht(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){es(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){es(n,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await ev(e)}catch(u){es(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);es(n,200,u??{ok:!0})}catch(u){Gh.error("IPC handler failed",{key:o,err:String(u)}),es(n,500,{error:u instanceof Error?u.message:String(u)})}}};function es(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function ev(t){let e=[],n=0;for await(let o of t){let c=o;if(n+=c.length,n>QE)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 bS=qt(Bx(),1),ES=qt(Zo(),1),vS=qt(qr(),1),SS=qt(Bd(),1),IS=qt(Ud(),1),AS=qt(Wd(),1),Wx=qt(ea(),1),kS=qt(Kx(),1);var $x=Wx.default;Ve();ne();var{FWS:qS}=ip(),Oe=K("upstream.frontier"),op="application/json",ap="none",jS=15e3;function KS(t){class e extends $x{constructor(i){super(i,Xf,{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(Nl("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let l=Buffer.from(c.slice(0,128)).toString("hex");Oe.debug("WS raw frame out",{bytes:c.byteLength,headHex:l})}catch(c){Oe.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var ds=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Oe.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Qf,...Sn(this.opts.ppeOverride)},n=KS(e),i=t0(this.opts.urlOverride),o={url:i,ws:n,fpID:Yf,aID:_o,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:op,force:!0},payloadEncoding:{encoding:ap,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new qS(o),l=!1,u=null,h,x,m=new Promise((_,E)=>{h=_,x=E}),w=_=>{l||(l=!0,u&&(clearTimeout(u),u=null),_?x(_):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Oe.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&w();for(let E of this.connectHandlers)Promise.resolve(E({initial:_})).catch(I=>Oe.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=_=>{this.opened=!1,Oe.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{Oe.warn("frontier error",{code:_.code,msg:_.message}),w(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let v=this.opts.openTimeoutMs??jS;u=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await c.connect();try{await m}catch(_){try{c.close(1e3,"open failed")}catch(E){Oe.warn("fws close during start failure threw (ignored)",{err:String(E)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Oe.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)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:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;cp(c)||Oe.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:op,payloadEncoding:ap})}catch(u){throw 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 n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=n(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Oe.debug("drop non-adapter frontier frame",{service:n});return}let i=VS(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(l){Oe.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let c=o;cp(c)||Oe.info("frontier frame in",{logid:$S(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:WS(i)}),Promise.resolve(this.handler(o)).catch(l=>Oe.warn("frontier frame handler threw",{err:String(l)}))}};function cp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var dp=2e3;function WS(t){return t.length<=dp?t:`${t.slice(0,dp)}...<truncated, total ${t.length} chars>`}function $S(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function VS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}Ve();ne();var Zd=K("skill-publish"),JS="/api/marketplace/product/skill/publish_with_assets",ZS=15e4;async function lp(t,e={}){let i=`${Cr(Dr(e.handshakeBase))}${JS}`,o=e.timeoutMs??ZS,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let l={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Sn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=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:{...l,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:l,body:c,signal:u.signal}),m=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${m}: ${_.slice(0,200)}`)}let w=await x.json();if(Zd.info("skill publish response",{logid:m,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${m}`);let v={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(v.skillId=String(w.data.skill_id)),w.data?.version&&(v.version=w.data.version),Zd.info("skill publish ok",{logid:m,skillId:v.skillId??"",version:v.version??""}),v}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}ne();var Yd=K("upstream.switchable"),da=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;Yd.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw Yd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>Yd.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var Xd=K("upstream"),Jr=class{handler=null;async start(){Xd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Xd.info("NoopUpstream stopped",{reason:e})}async send(e){Xd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Ve();ne();jt();ne();Pe();import{promises as YS}from"node:fs";var up=K("pat-token-store");async function la(t=Y()){try{let n=(await YS.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(up.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):n}catch(e){let n=e?.code;return n!=="ENOENT"&&up.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ls(t,e=Y()){if(!t)throw new Error("writePatToken: empty patToken");await ht(e.patTokenFile,t,{mode:384})}Pe();Pe();import{promises as ua}from"node:fs";import{join as XS}from"node:path";function QS(t,e){return`#!/bin/sh
116
116
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
117
- `}function tS(t,e){return`@echo off\r
117
+ `}function e1(t,e){return`@echo off\r
118
118
  "${e}" "${t}" %*\r
119
- `}async function lp(t,e=J()){let r=e.binDir;await aa.mkdir(r,{recursive:!0});let i=Q1(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?tS(t,o):eS(t,o);return await aa.readFile(i,"utf8").catch(()=>null)===c||(await aa.writeFile(i,c,"utf8"),process.platform!=="win32"&&await aa.chmod(i,493)),r}te();Ce();import{execSync as up}from"node:child_process";import{readFileSync as fp,unlinkSync as nS}from"node:fs";import{mkdir as rS,open as iS,readFile as xp,unlink as Yd,writeFile as sS}from"node:fs/promises";import{dirname as oS}from"node:path";var aS=j("single-instance"),cS=t=>new Promise(e=>setTimeout(e,t)),ca=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??J().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Ki(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&&aS.warn("removing stale pid file",{stalePid:i}),await sS(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 xp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Yd(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 xp(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 rS(oS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await iS(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 cS(this.claimLockIntervalMs);continue}await Yd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Yd(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=fp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Fr)||r.includes("lib/index.js"))}catch{}try{let r=up(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Fr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=up(`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{fp(this.pidFile,"utf8").trim()===String(this.selfPid)&&nS(this.pidFile)}catch{}})}};da();te();var nr=j("daemon.upstream-watchdog"),gS=12e4,mS=9e5,wS=3e4;function Xd(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var la=class{constructor(e){this.opts=e;this.softMs=e.softMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",gS),this.hardMs=e.hardMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",mS),this.intervalMs=e.intervalMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",wS),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),nr.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&nr.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&nr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,nr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){nr.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,nr.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>nr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var K=j("daemon");async function gp(){let t=J();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Rl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:R=>Fe(R,t).logs,listAgentIds:()=>ys(t)});try{let{writeFileSync:R}=await import("node:fs");R(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
119
+ `}async function fp(t,e=Y()){let n=e.binDir;await ua.mkdir(n,{recursive:!0});let i=XS(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?e1(t,o):QS(t,o);return await ua.readFile(i,"utf8").catch(()=>null)===c||(await ua.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ua.chmod(i,493)),n}ne();Pe();import{execSync as hp}from"node:child_process";import{readFileSync as xp,unlinkSync as t1}from"node:fs";import{mkdir as n1,open as r1,readFile as pp,unlink as Qd,writeFile as i1}from"node:fs/promises";import{dirname as s1}from"node:path";var o1=K("single-instance"),a1=t=>new Promise(e=>setTimeout(e,t)),fa=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Y().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Vi(n),isDaemon:n=>this.matchesDaemonTitle(n)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let n=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&o1.warn("removing stale pid file",{stalePid:i}),await i1(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return n.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),n}async release(){if(this.acquired){try{(await pp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Qd(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let n=await pp(e,"utf8"),i=Number.parseInt(n.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(n){if(n.code==="ENOENT")return null;throw n}}async withClaimLock(e){let n=`${this.pidFile}.lock`;await n1(s1(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await r1(n,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=await this.readPidFrom(n);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await a1(this.claimLockIntervalMs);continue}await Qd(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Qd(n).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${n} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=xp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Fr)||n.includes("lib/index.js"))}catch{}try{let n=hp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Fr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=hp(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let o=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return o.includes("node")||o.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{xp(this.pidFile,"utf8").trim()===String(this.selfPid)&&t1(this.pidFile)}catch{}})}};ha();ne();var nr=K("daemon.upstream-watchdog"),p1=12e4,m1=9e5,g1=3e4;function tl(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var xa=class{constructor(e){this.opts=e;this.softMs=e.softMs??tl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",p1),this.hardMs=e.hardMs??tl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",m1),this.intervalMs=e.intervalMs??tl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",g1),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),nr.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&nr.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&nr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,nr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){nr.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:n,hardMs:this.hardMs}),this.opts.onFatal(n);return}n>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,nr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>nr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var $=K("daemon");async function wp(){let t=Y();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Ol({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Ue(P,t).logs,listAgentIds:()=>Ss(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
120
120
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
121
121
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
122
- `)}catch{}}let e=new ca({processTitle:Fr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await No(),o=i??{};ms({pid:process.pid}),K.info(i?"loaded bridge config":"initialized bridge config");let c=new sa(new Yr),d=null,u=new Mo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(R,G,W,ee)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(R,G,W,ee)}}),x=new Do({paths:t,config:o,registry:u});d=x;let h,m,w=null,I={},b,S=null,A=null,k=null,P=new kn;function L(R,G){return P.enqueue(()=>D(R,G))}function E(){A||(A=new la({isConnected:()=>c.isConnected()&&!(S?.isLivenessLost()??!1),forceReconnect:()=>k?L(k,{force:!0}):void 0,onFatal:R=>{if(process.env[ds]==="1"){K.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:R});return}K.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:R}),process.exit(1)}})),A.start()}async function D(R,G){let W=R,ee=W?.privatecode;if(!ee)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let Ve=zi(W.env),pe=W.handshake_url,ge=W.frontier_url,kt=pp(W.env,pe,ge);if(k=W,!G?.force&&h===ee&&m===kt){let _e=await _S(t);return u.agents.size===0&&_e?(K.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),fa(t,x).catch(ke=>K.warn("connect-noop auto-revive error (ignored)",{err:String(ke)}))):K.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let wt=!!h&&h!==ee,rn=m!==void 0&&m!==kt,Ut=wt||rn,sn=await Xc({privatecode:ee,...pe?{endpoint:pe}:{},ppeOverride:Ve});if(Ut){K.warn("connect config switched, resetting agents",{pcChanged:wt,envChanged:rn,previousPc:h?ua(h):"",nextPc:ua(ee)});for(let _e of[...u.agents.values()])await _e.dispose("connect config switch").catch(()=>{}),u.agents.delete(_e.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 Yr,"connect switch").catch(()=>{})}w=sn.deviceId,ms({deviceId:w,pid:process.pid}),bd({patToken:ee,env:W.env}).catch(_e=>K.warn("coze-cli setup error (ignored)",{err:String(_e)}));let ei=new as({handshake:sn,privatecode:ee,...ge?{urlOverride:ge}:{},ppeOverride:Ve,getPatTokenForAgent:_e=>u.agents.get(_e)?.patToken});return await c.swap(ei,"connect"),h=ee,m=kt,I=Ve,b=pe,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),K.info("mock scenario set",{scenario:W.mock_scenario})),S||(S=new Gi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(_e=>K.warn("detailSync.retryPending failed (ignored)",{err:String(_e)})),onAuthFailures:Y})),S.start(),E(),Ut&&fa(t,x).catch(_e=>K.warn("post-connect-switch auto-revive error (ignored)",{err:String(_e)})),cs(ee,t).catch(_e=>K.warn("writePatToken after /connect failed (ignored)",{err:String(_e)})),K.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async R=>x.createAgent(R.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let N={},z=new _o({agents:u.agents,paths:t,publishSkillToMarketplace:async R=>{let G=u.agents.get(R.agentId)?.patToken??h;if(!G)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return cp({patToken:G,zip:R.zip,...R.skillId?{skillId:R.skillId}:{},skillName:R.skillName,...R.description?{description:R.description}:{},agentId:R.agentId,...R.accountId?{accountId:R.accountId}:{}},{handshakeBase:b,ppeOverride:I})},disposeAndMarkDisconnected:async(R,G)=>{let W=u.agents.get(R);if(W){await x.cleanupOpenclawSessionProviders(W).catch(Ve=>K.warn("cleanup openclaw providers failed (ignored)",{agentId:R,err:String(Ve)})),W.framework==="hermes"&&W.deployType==="cloud"&&await id(R,t).catch(Ve=>K.warn("cleanup hermes-home failed (ignored)",{agentId:R,err:String(Ve)}));let ee=!0;try{await W.dispose(`disconnect: ${G}`)}catch(Ve){ee=!1,K.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:R,err:String(Ve)}),W.status="error"}ee&&(W.status="disconnected",u.unregister(R),u.disconnectedAgents.add(R))}else u.disconnectedAgents.add(R)},disposeForDelete:async(R,G)=>{let W=u.agents.get(R);W&&(await x.cleanupOpenclawSessionProviders(W).catch(ee=>K.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:R,err:String(ee)})),W.framework==="hermes"&&W.deployType==="cloud"&&await id(R,t).catch(ee=>K.warn("cleanup hermes-home during delete failed (ignored)",{agentId:R,err:String(ee)})),await W.dispose(`delete: ${G}`).catch(ee=>K.warn("dispose during delete failed (ignored)",{agentId:R,err:String(ee)})),u.unregister(R)),u.disconnectedAgents.delete(R)},detailSyncer:async R=>{if(!N.ref)throw new Error("agent-detail-sync not initialized yet");await N.ref.syncOne(R)},cleanupOpenclawProviders:async(R,G)=>{await x.cleanupOpenclawSessionProviders(R,G)},openclawRepair:async(R,G)=>{await x.openclawRepair(R,G)},hermesReset:async(R,G)=>{let W=await ve(R).catch(()=>null);!W||W.framework!=="hermes"||W.deployType!=="cloud"||await f0({paths:t,agentId:R,model:W.model,modelInfo:W.modelInfo,cozeEnv:G,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:R=>u.hasPendingPermissionFor(R)});u.registerExtension("_agent/listSkills",R=>z.listSkills(R.params)),u.registerExtension("_agent/addSkills",R=>z.addSkills(R.params)),u.registerExtension("_agent/removeSkills",R=>z.removeSkills(R.params)),u.registerExtension("_agent/publishSkill",R=>z.publishSkill(R.params)),u.registerExtension("_agent/getFileTree",R=>z.getFileTree(R.params)),u.registerExtension("_agent/getFileContent",R=>z.getFileContent(R.params)),u.registerExtension("_agent/update",R=>z.updateAgent(R.params)),u.registerExtension("_agent/disconnect",R=>z.disconnectAgent(R.params)),u.registerExtension("_agent/switchModel",R=>z.switchModel(R.params)),u.registerExtension("_agent/reset",R=>z.resetAgent(R.params)),u.registerExtension("_agent/repair",R=>z.repairAgent(R.params)),u.registerExtension("_agent/delete",R=>z.deleteAgent(R.params)),u.registerExtension("_agent/upgrade",R=>z.upgradeBridge(R.params));let B=new vs({paths:t,handlers:z,agentManager:x,sendDetail:R=>u.sendRequest("_agent/detail",R)});N.ref=B;let Y=async R=>{await Promise.allSettled(R.map(async G=>{try{await z.disconnectAgent({agentId:G.agentId,reason:`auth_failure: code=${G.code} ${G.message}`}),K.info("agent disconnected due to auth failure from heartbeat response",{agentId:G.agentId,code:G.code,message:G.message})}catch(W){K.warn("disconnect during authFailure handling failed (ignored)",{agentId:G.agentId,err:String(W)})}}))};c.onConnect(({initial:R})=>{K.info("frontier upstream connected, triggering detail sync",{initial:R}),B.syncAll(R?"initial-connect":"reconnect").catch(G=>K.warn("detail sync top-level error (ignored)",{err:String(G)}))});let V=new Bo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let R=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[ds]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...R?{mockScenario:R}:{}}}},{method:"POST",path:"/pair",handler:async R=>{let G=R,W=G?.privatecode,ee=G?.pairing_code;if(!W||!ee)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ve=zi(G.env),pe=G.handshake_url,ge=G.frontier_url,kt=pp(G.env,pe,ge),wt=!!h&&h!==W,rn=m!==void 0&&m!==kt,Ut=wt||rn,sn=await Xc({privatecode:W,...pe?{endpoint:pe}:{},ppeOverride:Ve});if(Ut){K.warn("pair config switched, resetting agents",{pcChanged:wt,envChanged:rn,previousPc:h?ua(h):"",nextPc:ua(W),previousEnvKey:m??"",nextEnvKey:kt});for(let ke of[...u.agents.values()])await ke.dispose("pair config switch").catch(()=>{}),u.agents.delete(ke.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 Yr,"pair switch").catch(()=>{})}w=sn.deviceId,ms({deviceId:w,pid:process.pid}),bd({patToken:W,env:G.env}).catch(ke=>K.warn("coze-cli setup error (ignored)",{err:String(ke)}));let ei=new as({handshake:sn,privatecode:W,...ge?{urlOverride:ge}:{},ppeOverride:Ve,getPatTokenForAgent:ke=>u.agents.get(ke)?.patToken});await c.swap(ei,"pair");try{let ke=new Jn;o.frameworksCache=await ke.detectAll(),await Ji(o),K.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(ke){K.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(ke)})}let _e=Object.keys(o.frameworksCache??{});try{let ke=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:W,frameworks:_e,_meta:{cozeDeviceId:w}});K.info("_agent/pair ok",{pairResult:ke}),h=W,m=kt,I=Ve,b=pe,G.mock_scenario!==void 0&&(u.setMockScenario(G.mock_scenario),K.info("mock scenario set",{scenario:G.mock_scenario})),cs(W,t).catch(Le=>K.warn("writePatToken after /pair failed (ignored)",{err:String(Le)})),S||(S=new Gi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(Le=>K.warn("detailSync.retryPending failed (ignored)",{err:String(Le)})),onAuthFailures:Y})),S.start(),E(),Ut&&fa(t,x).catch(Le=>K.warn("post-pair-switch auto-revive error (ignored)",{err:String(Le)}));let rr;return G.agent_id&&(rr=await bS(G.agent_id,t,x,Le=>u.sendRequest("_agent/detail",Le),W).catch(Le=>(K.error("--agent-id ensureAgent failed",{agentId:G.agent_id,err:String(Le)}),{ok:!1,agentId:G.agent_id??"",note:String(Le)}))),{ok:!0,note:"paired with cloud",...rr?{agent:rr}:{}}}catch(ke){return K.error("_agent/pair failed",{err:String(ke)}),{ok:!1,note:`pair failed: ${String(ke)}`}}}},{method:"POST",path:"/connect",handler:R=>L(R)},{method:"POST",path:"/_agent/create",handler:async R=>{let G=R;return{ok:!0,result:await x.createAgent(G)}}},{method:"POST",path:"/agent/send",handler:async R=>{let G=R;if(!G?.agentId||!G?.sessionId||!G?.kind||!G?.path)throw new T("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!h)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let W=G;return await(W.groupFile?vx:Ex)(W,{core:u,patToken:h,handshakeBase:b,ppeOverride:I})}catch(W){if(W instanceof T)return{ok:!1,code:W.code,message:W.message};throw W}}},{method:"POST",path:"/reload",handler:async R=>{let G=R?.agent_id,W=await u.reloadAgents(G);return K.info("IPC /reload: recycled agent subprocesses",{agentId:G??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>(K.info("IPC /shutdown received"),setImmediate(()=>{ce.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:Z}=await V.start();try{await lp(t.libEntry,t)}catch(R){K.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(R)})}await u.start(),ES({paths:t,core:u,agentManager:x,detectAll:async()=>(o.frameworksCache=await new Jn().detectAll(),await Ji(o),o.frameworksCache)}).catch(R=>K.warn("startup warmup error (ignored)",{err:String(R)})),Hl().then(async()=>{let{probeAcpVersion:R}=await Promise.resolve().then(()=>(ln(),zl));for(let G of["claude-code","codex"]){let W=await R(G);W&&K.info("acp wrapper version",{framework:G,version:W})}}).catch(R=>K.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(R)}));let oe=null,ce={port:re,token:Z,core:u,ipc:V,shutdown(R){return oe||(K.info("daemon shutdown",{reason:R}),oe=(async()=>{S?.stop(),A?.stop(),await u.stop(R),await V.stop(),await e.release()})(),oe)}};for(let R of["SIGTERM","SIGINT"])process.on(R,()=>{ce.shutdown(R).then(()=>process.exit(0))});return process.on("exit",()=>U0()),process.on("unhandledRejection",R=>{K.error("unhandledRejection",{reason:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0})}),process.on("uncaughtException",R=>{K.error("uncaughtException (will exit, supervisor will restart)",{message:R.message,stack:R.stack,name:R.name});try{process.stderr.write(`FATAL uncaughtException: ${R.stack??R.message}
123
- `)}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"}),SS({cliSpawned:process.env[ds]==="1",readPatToken:()=>oa(t),connect:L}).catch(R=>K.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(R)})),ce}async function _S(t){return ys(t).length>0}function ua(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function pp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function yS(t,e){let r=ys(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(qt(),Es));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 bS(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(qt(),Es)),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`);K.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let m=mp(d),w={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(w),{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 T("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let x={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(x);let h=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:h?"cloud agent acknowledged":"created from cloud detail"}}async function ES(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 yS(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await fa(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await vS(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function fa(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(()=>(qt(),Es));K.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let x;try{x=await o(u,t)}catch(h){K.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(h)}),d+=1;continue}if(!x){d+=1;continue}if(x.deletedAt){K.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:x.deletedAt}),d+=1;continue}if(x.disconnectedAt){K.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:x.disconnectedAt}),d+=1;continue}try{K.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:x.framework});let h=mp(x);await e.createAgent({agentId:x.agentId,framework:x.framework,...x.cozeIdentity?{cozeIdentity:x.cozeIdentity}:{},...x.model?{model:x.model}:{},...h?{_meta:h}:{}},{revive:!0}),c+=1}catch(h){K.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:x.framework,err:String(h)}),d+=1}}return K.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function vS(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 T0(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 SS(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 mp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}da();Ce();import{readFile as wp}from"node:fs/promises";var nn=class{paths;constructor(e){this.paths=e??J()}async probe(e=1e3){let r=await xa(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:AS(i)}}}async request(e){let r=await xa(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}),x=await u.text();return{status:u.status,body:IS(x)}}finally{clearTimeout(d)}}};async function xa(t){try{let[e,r]=await Promise.all([wp(t.portFile,"utf8"),wp(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 IS(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function AS(t){return t instanceof Error?t.message:String(t)}Jt();te();ar();import{spawn as kS}from"node:child_process";import{userInfo as yp}from"node:os";var Zd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",TS=new Set(["bash","zsh","sh","dash","ksh"]),_p=Ye("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),CS=2e3;function PS(t,e=Zd){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(`
124
- `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function RS(){let t=(process.env.SHELL??"").trim()||(yp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return TS.has(e)?t:null}function DS(t){return new Promise(e=>{let r=`printf '%s' '${Zd}'; env; printf '%s' '${Zd}'`,i;try{i=kS(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??yp().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(x),clearTimeout(h),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 x=setTimeout(()=>d("SIGTERM"),_p),h=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},_p+CS)})}async function Qd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=RS();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??DS)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=PS(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Ce();function Pn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],d=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||r.push(c)}return{value:i,rest:r}}ln();import{chmod as OS,copyFile as bp,mkdir as vp,readFile as us,rename as Ep,rm as nl,stat as Sp,writeFile as LS}from"node:fs/promises";import{homedir as gO}from"node:os";import{dirname as NS,join as Oe,resolve as rl,sep as ls}from"node:path";import{fileURLToPath as MS}from"node:url";Jt();te();Ce();function Jr(t,e,r,i){nt(t.bridgeLogsDir,e,"dist-install",r,i)}function Ip(){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 BS(){return{darwin:{arm64:Oe("vendor","aarch64-apple-darwin","bin","codex"),x64:Oe("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Oe("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Oe("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Oe("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Oe("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function FS(t){let e=MS(t),r=NS(e),i=`${ls}src${ls}`;if(r.includes(i)||r.endsWith(`${ls}src${ls}cli`))return null;let o=rl(r,"index.js"),c=rl(r,"..","package.json");return{dist:o,pkgJson:c}}async function il(t={}){let e=t.paths??J(),r=FS(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 S=JSON.parse(await us(o,"utf8"));c=S.version??"unknown",d=S.dependencies??{}}catch(S){throw Jr(e,"error","cannot read source package.json",{err:String(S)}),new Error(`cannot read source package.json: ${String(S)}`,{cause:S})}let u=ws.map(S=>({name:S,spec:d[S]??"latest"})),x=u.map(({name:S,spec:A})=>`${S}@${A}`),h=await No(e.configFile)??{},m=h.libVersion,w=await us(e.libEntry).then(()=>!0).catch(()=>!1),I=m===c,b=await Ap(e,u);if(I&&w&&b)return{kind:"already-current",libVersion:c};if(!I||!w){await vp(e.libDir,{recursive:!0}),await bp(i,e.libEntry),await bp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let S=rl(e.libDir,"package.json"),A=`${JSON.stringify({type:"module"},null,2)}
125
- `;await us(S,"utf8").catch(()=>null)!==A&&await LS(S,A)}return b||(t.installWrappers?await t.installWrappers(e,x):await HS(e,x,u)),h.libVersion=c,await Ji(h,e.configFile),Jr(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),I&&w?{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 Ap(t,e){for(let r of e){let i=Oe(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await us(i,"utf8"))}catch(d){return Jr(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 Jr(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!zS(c,r.spec))return Jr(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await kp(Oe(t.libDir,"node_modules"))}function zS(t,e){let r=el(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=el(i.slice(1));if(!c)return!0;if(tl(r,c)<0)return!1;let d=US(c);return tl(r,d)<0}let o=el(i);return o?tl(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 el(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function tl(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 HS(t,e,r){await jS(t.installLock,async()=>{if(await Ap(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${ls}.staging-${process.pid}-${i}`,c=Oe(o,"node_modules"),d=Oe(t.libDir,"node_modules");try{await vp(o,{recursive:!0}),await GS(e,o),await qS(c);let u=`${d}.trash-${i}`;await Ep(d,u).catch(()=>{}),await Ep(c,d),await nl(u,{recursive:!0,force:!0}).catch(()=>{}),Jr(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await nl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function GS(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=it("npm",r,{stdio:["ignore","pipe","pipe"]}),d="";c.stderr?.on("data",x=>{d.length<8192&&(d+=x.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",x=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(x)}`))}),c.once("close",x=>{clearTimeout(u),x===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${x}: ${d.trim().slice(0,2e3)}`))})})}async function qS(t){for(let e of ws){let r=Oe(t,...e.split("/")),i=JSON.parse(await us(Oe(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=Oe(t,".bin",o),d=await Sp(c);process.platform!=="win32"&&!(d.mode&73)&&await OS(c,d.mode|73).catch(()=>{})}if(!await kp(t)){let e=Ip()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function kp(t){let e=Ip(),r=BS();if(!e||!r)return!0;let i=Oe(t,"@openai","codex"),o=Oe(t,...e.split("/")),c=[Oe(i,"package.json"),Oe(i,"bin","codex.js"),Oe(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Oe(o,"package.json"),Oe(o,r)];return(await Promise.all(c.map(u=>Sp(u).then(x=>x.isFile()).catch(()=>!1)))).every(Boolean)}async function jS(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 nl(t,{force:!0}).catch(()=>{})}}Na();te();Ce();import{closeSync as Cp,fstatSync as Pp,openSync as Rp,readFileSync as WS,readSync as KS,readdirSync as $S,statSync as VS}from"node:fs";import{join as ha}from"node:path";var YS=new Set(["debug","info","warn","error"]);function Dp(t){let e=t,r=Pn(e,"--agent-id");e=r.rest;let i=Pn(e,"--date");e=i.rest;let o=Pn(e,"-n","--lines");e=o.rest;let c=Pn(e,"--level");e=c.rest;let d=Pn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),x=Number.isInteger(u)&&u>=0?u:200,h=c.value&&YS.has(c.value)?c.value:void 0,m={lines:x,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),h&&(m.level=h),d.value&&(m.grep=d.value),m}function JS(t,e){return t.agentId?ha(Fe(t.agentId,e).logs,cr("agent",t.date)):ha(e.bridgeLogsDir,cr("bridge",t.date))}function XS(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function ZS(t,e){let r;try{r=$S(t)}catch{return[]}let i=[];for(let o of r){let c=La(o,e);if(!c)continue;let d=0;try{d=VS(ha(t,o)).size}catch{}i.push({file:ha(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Op(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let r;try{r=JSON.parse(t).level}catch{return!0}if(typeof r=="string"&&!Ll(r,e.level))return!1}return!0}var Tp={debug:"90",info:"36",warn:"33",error:"31"},QS=new Set(["ts","level","module","msg"]);function e2(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Lp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=e2(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&Tp[o]&&(c=`\x1B[${Tp[o]}m${c}\x1B[0m`);let d=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",x=Object.entries(r).filter(([h])=>!QS.has(h)).map(([h,m])=>` ${h}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${d} ${u}${x}`}function t2(t,e,r){let c=WS(t,"utf8").split(`
126
- `).filter(d=>d.length>0).filter(d=>Op(d,{level:e.level,grep:e.grep}));for(let d of XS(c,e.lines))process.stdout.write(`${Lp(d,{raw:e.raw,color:r})}
127
- `)}async function Np(t,e){let r=e.paths??J(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Fe(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",x=ZS(d,u);if(x.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
128
- `),1;for(let h of x)process.stdout.write(`${h.date} ${(h.size/1024).toFixed(1)}KB ${h.file}
129
- `);return 0}let o=t.date??Dn(new Date),c=JS({agentId:t.agentId,date:o},r);try{t2(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
122
+ `)}catch{}}let e=new fa({processTitle:Fr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await zo(),o=i??{};bs({pid:process.pid}),$.info(i?"loaded bridge config":"initialized bridge config");let c=new da(new Jr),l=null,u=new Uo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,H,W,te)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(P,H,W,te)}}),h=new Mo({paths:t,config:o,registry:u});l=h;let x,m,w=null,v={},_,E=null,I=null,A=null,T=new kn;function O(P,H){return T.enqueue(()=>D(P,H))}function b(){I||(I=new xa({isConnected:()=>c.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>A?O(A,{force:!0}):void 0,onFatal:P=>{if(process.env[us]==="1"){$.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}$.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),I.start()}async function D(P,H){let W=P,te=W?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Ze=Gi(W.env),me=W.handshake_url,ge=W.frontier_url,Rt=gp(W.env,me,ge);if(A=W,!H?.force&&x===te&&m===Rt){let ye=await w1(t);return u.agents.size===0&&ye?($.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ma(t,h).catch(Te=>$.warn("connect-noop auto-revive error (ignored)",{err:String(Te)}))):$.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let yt=!!x&&x!==te,on=m!==void 0&&m!==Rt,Ht=yt||on,an=await td({privatecode:te,...me?{endpoint:me}:{},ppeOverride:Ze});if(Ht){$.warn("connect config switched, resetting agents",{pcChanged:yt,envChanged:on,previousPc:x?pa(x):"",nextPc:pa(te)});for(let ye of[...u.agents.values()])await ye.dispose("connect config switch").catch(()=>{}),u.agents.delete(ye.agentId);u.disconnectedAgents.size>0&&($.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Jr,"connect switch").catch(()=>{})}w=an.deviceId,bs({deviceId:w,pid:process.pid}),Id({patToken:te,env:W.env}).catch(ye=>$.warn("coze-cli setup error (ignored)",{err:String(ye)}));let ei=new ds({handshake:an,privatecode:te,...ge?{urlOverride:ge}:{},ppeOverride:Ze,getPatTokenForAgent:ye=>u.agents.get(ye)?.patToken});return await c.swap(ei,"connect"),x=te,m=Rt,v=Ze,_=me,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),$.info("mock scenario set",{scenario:W.mock_scenario})),E||(E=new ji({core:u,getDeviceId:()=>w??"",onTickEnd:()=>U.retryPending().catch(ye=>$.warn("detailSync.retryPending failed (ignored)",{err:String(ye)})),onAuthFailures:Z})),E.start(),b(),Ht&&ma(t,h).catch(ye=>$.warn("post-connect-switch auto-revive error (ignored)",{err:String(ye)})),ls(te,t).catch(ye=>$.warn("writePatToken after /connect failed (ignored)",{err:String(ye)})),$.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>h.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let L={},G=new vo({agents:u.agents,paths:t,publishSkillToMarketplace:async P=>{let H=u.agents.get(P.agentId)?.patToken??x;if(!H)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return lp({patToken:H,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:_,ppeOverride:v})},disposeAndMarkDisconnected:async(P,H)=>{let W=u.agents.get(P);if(W){await h.cleanupOpenclawSessionProviders(W).catch(Ze=>$.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(Ze)})),W.framework==="hermes"&&W.deployType==="cloud"&&await cd(P,t).catch(Ze=>$.warn("cleanup hermes-home failed (ignored)",{agentId:P,err:String(Ze)}));let te=!0;try{await W.dispose(`disconnect: ${H}`)}catch(Ze){te=!1,$.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(Ze)}),W.status="error"}te&&(W.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,H)=>{let W=u.agents.get(P);W&&(await h.cleanupOpenclawSessionProviders(W).catch(te=>$.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(te)})),W.framework==="hermes"&&W.deployType==="cloud"&&await cd(P,t).catch(te=>$.warn("cleanup hermes-home during delete failed (ignored)",{agentId:P,err:String(te)})),await W.dispose(`delete: ${H}`).catch(te=>$.warn("dispose during delete failed (ignored)",{agentId:P,err:String(te)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!L.ref)throw new Error("agent-detail-sync not initialized yet");await L.ref.syncOne(P)},cleanupOpenclawProviders:async(P,H)=>{await h.cleanupOpenclawSessionProviders(P,H)},openclawRepair:async(P,H)=>{await h.openclawRepair(P,H)},hermesReset:async(P,H)=>{let W=await Se(P).catch(()=>null);!W||W.framework!=="hermes"||W.deployType!=="cloud"||await x0({paths:t,agentId:P,model:W.model,modelInfo:W.modelInfo,cozeEnv:H,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>G.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>G.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>G.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>G.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>G.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>G.getFileContent(P.params)),u.registerExtension("_agent/update",P=>G.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>G.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>G.switchModel(P.params)),u.registerExtension("_agent/reset",P=>G.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>G.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>G.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>G.upgradeBridge(P.params));let U=new ks({paths:t,handlers:G,agentManager:h,sendDetail:P=>u.sendRequest("_agent/detail",P)});L.ref=U;let Z=async P=>{await Promise.allSettled(P.map(async H=>{try{await G.disconnectAgent({agentId:H.agentId,reason:`auth_failure: code=${H.code} ${H.message}`}),$.info("agent disconnected due to auth failure from heartbeat response",{agentId:H.agentId,code:H.code,message:H.message})}catch(W){$.warn("disconnect during authFailure handling failed (ignored)",{agentId:H.agentId,err:String(W)})}}))};c.onConnect(({initial:P})=>{$.info("frontier upstream connected, triggering detail sync",{initial:P}),U.syncAll(P?"initial-connect":"reconnect").catch(H=>$.warn("detail sync top-level error (ignored)",{err:String(H)}))});let J=new Go({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[us]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let H=P,W=H?.privatecode,te=H?.pairing_code;if(!W||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ze=Gi(H.env),me=H.handshake_url,ge=H.frontier_url,Rt=gp(H.env,me,ge),yt=!!x&&x!==W,on=m!==void 0&&m!==Rt,Ht=yt||on,an=await td({privatecode:W,...me?{endpoint:me}:{},ppeOverride:Ze});if(Ht){$.warn("pair config switched, resetting agents",{pcChanged:yt,envChanged:on,previousPc:x?pa(x):"",nextPc:pa(W),previousEnvKey:m??"",nextEnvKey:Rt});for(let Te of[...u.agents.values()])await Te.dispose("pair config switch").catch(()=>{}),u.agents.delete(Te.agentId);u.disconnectedAgents.size>0&&($.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Jr,"pair switch").catch(()=>{})}w=an.deviceId,bs({deviceId:w,pid:process.pid}),Id({patToken:W,env:H.env}).catch(Te=>$.warn("coze-cli setup error (ignored)",{err:String(Te)}));let ei=new ds({handshake:an,privatecode:W,...ge?{urlOverride:ge}:{},ppeOverride:Ze,getPatTokenForAgent:Te=>u.agents.get(Te)?.patToken});await c.swap(ei,"pair");try{let Te=new Zn;o.frameworksCache=await Te.detectAll(),await Xi(o),$.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Te){$.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Te)})}let ye=Object.keys(o.frameworksCache??{});try{let Te=await u.sendRequest("_agent/pair",{pairCode:te,patToken:W,frameworks:ye,_meta:{cozeDeviceId:w}});$.info("_agent/pair ok",{pairResult:Te}),x=W,m=Rt,v=Ze,_=me,H.mock_scenario!==void 0&&(u.setMockScenario(H.mock_scenario),$.info("mock scenario set",{scenario:H.mock_scenario})),ls(W,t).catch(Ne=>$.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),E||(E=new ji({core:u,getDeviceId:()=>w??"",onTickEnd:()=>U.retryPending().catch(Ne=>$.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:Z})),E.start(),b(),Ht&&ma(t,h).catch(Ne=>$.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let rr;return H.agent_id&&(rr=await y1(H.agent_id,t,h,Ne=>u.sendRequest("_agent/detail",Ne),W).catch(Ne=>($.error("--agent-id ensureAgent failed",{agentId:H.agent_id,err:String(Ne)}),{ok:!1,agentId:H.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...rr?{agent:rr}:{}}}catch(Te){return $.error("_agent/pair failed",{err:String(Te)}),{ok:!1,note:`pair failed: ${String(Te)}`}}}},{method:"POST",path:"/connect",handler:P=>O(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let H=P;return{ok:!0,result:await h.createAgent(H)}}},{method:"POST",path:"/agent/send",handler:async P=>{let H=P;if(!H?.agentId||!H?.sessionId||!H?.kind||!H?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let W=H;return await(W.groupFile?Sh:vh)(W,{core:u,patToken:x,handshakeBase:_,ppeOverride:v})}catch(W){if(W instanceof k)return{ok:!1,code:W.code,message:W.message};throw W}}},{method:"POST",path:"/reload",handler:async P=>{let H=P?.agent_id,W=await u.reloadAgents(H);return $.info("IPC /reload: recycled agent subprocesses",{agentId:H??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>($.info("IPC /shutdown received"),setImmediate(()=>{de.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ie,token:Q}=await J.start();try{await fp(t.libEntry,t)}catch(P){$.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),b1({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new Zn().detectAll(),await Xi(o),o.frameworksCache)}).catch(P=>$.warn("startup warmup error (ignored)",{err:String(P)})),ql().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(ln(),Gl));for(let H of["claude-code","codex"]){let W=await P(H);W&&$.info("acp wrapper version",{framework:H,version:W})}}).catch(P=>$.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let ce=null,de={port:ie,token:Q,core:u,ipc:J,shutdown(P){return ce||($.info("daemon shutdown",{reason:P}),ce=(async()=>{E?.stop(),I?.stop(),await u.stop(P),await J.stop(),await e.release()})(),ce)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{de.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>H0()),process.on("unhandledRejection",P=>{$.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{$.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}
123
+ `)}catch{}process.exit(1)}),$.info("daemon ready",{port:ie,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),v1({cliSpawned:process.env[us]==="1",readPatToken:()=>la(t),connect:O}).catch(P=>$.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),de}async function w1(t){return Ss(t).length>0}function pa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function gp(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function _1(t,e){let n=Ss(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(Kt(),As));for(let c of n){await o(c,t).catch(l=>$.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.deletedAt?(e.disconnectedAgents.add(c),$.info("agent marked deleted on startup",{agentId:c,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(c),$.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){$.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function y1(t,e,n,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Kt(),As)),l=await c(t,e);if(l){if(l.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${l.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);$.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let m=_p(l),w={agentId:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...o?{patToken:o}:{},...m?{_meta:m}:{}};return await n.createAgent(w),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}$.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 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 n.createAgent(h);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function b1(t){let e=t.logger??$;try{let n=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(n??{})})}catch(n){e.warn("framework detection failed (using cached)",{err:String(n)})}await _1(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await ma(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await E1(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function ma(t,e){let{readdir:n}=await import("node:fs/promises"),i;try{i=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>(Kt(),As));$.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,l=0;for(let u of i){let h;try{h=await o(u,t)}catch(x){$.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),l+=1;continue}if(!h){l+=1;continue}if(h.deletedAt){$.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),l+=1;continue}if(h.disconnectedAt){$.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),l+=1;continue}try{$.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=_p(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){$.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),l+=1}}return $.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,total:i.length}}async function E1(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let o of n)try{(await P0(o,t)).status==="refreshed"&&(i+=1)}catch(c){$.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&$.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function v1(t){let e=t.logger??$;if(t.cliSpawned)return"skipped-cli";let n=await t.readPatToken();return n?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:n}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function _p(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ha();Pe();import{readFile as yp}from"node:fs/promises";var sn=class{paths;constructor(e){this.paths=e??Y()}async probe(e=1e3){let n=await ga(this.paths);if(!n)return{kind:"not-running"};try{let i=await this.fetch(n,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...n,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:I1(i)}}}async request(e){let n=await ga(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let i=n.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,l=setTimeout(()=>c.abort(),n.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:o,body:i?JSON.stringify(n.body):void 0,signal:c.signal}),h=await u.text();return{status:u.status,body:S1(h)}}finally{clearTimeout(l)}}};async function ga(t){try{let[e,n]=await Promise.all([yp(t.portFile,"utf8"),yp(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=n.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function S1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function I1(t){return t instanceof Error?t.message:String(t)}Xt();ne();ar();import{spawn as A1}from"node:child_process";import{userInfo as Ep}from"node:os";var nl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",k1=new Set(["bash","zsh","sh","dash","ksh"]),bp=Xe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),T1=2e3;function R1(t,e=nl){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let o=t.slice(n+e.length,i),c={};for(let l of o.split(`
124
+ `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.slice(u+1))}return c}function P1(){let t=(process.env.SHELL??"").trim()||(Ep().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return k1.has(e)?t:null}function C1(t){return new Promise(e=>{let n=`printf '%s' '${nl}'; env; printf '%s' '${nl}'`,i;try{i=A1(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Ep().homedir}})}catch{e(null);return}let o="",c=!1,l=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(()=>l("SIGTERM"),bp),x=setTimeout(()=>{l("SIGKILL"),u(o.length>0?o:null)},bp+T1)})}async function rl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=P1();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??C1)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=R1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Pe();function Pn(t,...e){let n=[],i;for(let o=0;o<t.length;o++){let c=t[o],l=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,l=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),l=!0;break}}l||n.push(c)}return{value:i,rest:n}}ln();import{chmod as D1,copyFile as vp,mkdir as Ip,readFile as hs,rename as Sp,rm as ol,stat as Ap,writeFile as O1}from"node:fs/promises";import{homedir as pO}from"node:os";import{dirname as L1,join as Le,resolve as al,sep as fs}from"node:path";import{fileURLToPath as N1}from"node:url";Xt();ne();Pe();function Zr(t,e,n,i){st(t.bridgeLogsDir,e,"dist-install",n,i)}function kp(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function M1(){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 B1(t){let e=N1(t),n=L1(e),i=`${fs}src${fs}`;if(n.includes(i)||n.endsWith(`${fs}src${fs}cli`))return null;let o=al(n,"index.js"),c=al(n,"..","package.json");return{dist:o,pkgJson:c}}async function cl(t={}){let e=t.paths??Y(),n=B1(import.meta.url),i=t.sourceDist??n?.dist,o=t.sourcePackageJson??n?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,l;try{let E=JSON.parse(await hs(o,"utf8"));c=E.version??"unknown",l=E.dependencies??{}}catch(E){throw Zr(e,"error","cannot read source package.json",{err:String(E)}),new Error(`cannot read source package.json: ${String(E)}`,{cause:E})}let u=Es.map(E=>({name:E,spec:l[E]??"latest"})),h=u.map(({name:E,spec:I})=>`${E}@${I}`),x=await zo(e.configFile)??{},m=x.libVersion,w=await hs(e.libEntry).then(()=>!0).catch(()=>!1),v=m===c,_=await Tp(e,u);if(v&&w&&_)return{kind:"already-current",libVersion:c};if(!v||!w){await Ip(e.libDir,{recursive:!0}),await vp(i,e.libEntry),await vp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=al(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
125
+ `;await hs(E,"utf8").catch(()=>null)!==I&&await O1(E,I)}return _||(t.installWrappers?await t.installWrappers(e,h):await U1(e,h,u)),x.libVersion=c,await Xi(x,e.configFile),Zr(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),v&&w?{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 Tp(t,e){for(let n of e){let i=Le(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await hs(i,"utf8"))}catch(l){return Zr(t,"debug","wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(l)}),!1}let c=o.version;if(!c)return Zr(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!F1(c,n.spec))return Zr(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:c,expected:n.spec}),!1}return!!await Rp(Le(t.libDir,"node_modules"))}function F1(t,e){let n=il(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=il(i.slice(1));if(!c)return!0;if(sl(n,c)<0)return!1;let l=z1(c);return sl(n,l)<0}let o=il(i);return o?sl(n,o)===0:!0}function z1(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function il(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function sl(t,e){for(let n=0;n<3;n++){let i=(t[n]??0)-(e[n]??0);if(i!==0)return i}return 0}async function U1(t,e,n){await q1(t.installLock,async()=>{if(await Tp(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${fs}.staging-${process.pid}-${i}`,c=Le(o,"node_modules"),l=Le(t.libDir,"node_modules");try{await Ip(o,{recursive:!0}),await G1(e,o),await H1(c);let u=`${l}.trash-${i}`;await Sp(l,u).catch(()=>{}),await Sp(c,l),await ol(u,{recursive:!0,force:!0}).catch(()=>{}),Zr(t,"info","wrapper closure installed",{liveNm:l,specs:e})}finally{await ol(o,{recursive:!0,force:!0}).catch(()=>{})}})}function G1(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=at("npm",n,{stdio:["ignore","pipe","pipe"]}),l="";c.stderr?.on("data",h=>{l.length<8192&&(l+=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}: ${l.trim().slice(0,2e3)}`))})})}async function H1(t){for(let e of Es){let n=Le(t,...e.split("/")),i=JSON.parse(await hs(Le(n,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let c=Le(t,".bin",o),l=await Ap(c);process.platform!=="win32"&&!(l.mode&73)&&await D1(c,l.mode|73).catch(()=>{})}if(!await Rp(t)){let e=kp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function Rp(t){let e=kp(),n=M1();if(!e||!n)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,n)];return(await Promise.all(c.map(u=>Ap(u).then(h=>h.isFile()).catch(()=>!1)))).every(Boolean)}async function q1(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await ol(t,{force:!0}).catch(()=>{})}}za();ne();Pe();import{closeSync as Cp,fstatSync as Dp,openSync as Op,readFileSync as j1,readSync as K1,readdirSync as W1,statSync as $1}from"node:fs";import{join as wa}from"node:path";var V1=new Set(["debug","info","warn","error"]);function Lp(t){let e=t,n=Pn(e,"--agent-id");e=n.rest;let i=Pn(e,"--date");e=i.rest;let o=Pn(e,"-n","--lines");e=o.rest;let c=Pn(e,"--level");e=c.rest;let l=Pn(e,"--grep");e=l.rest;let u=o.value===void 0?200:Number(o.value),h=Number.isInteger(u)&&u>=0?u:200,x=c.value&&V1.has(c.value)?c.value:void 0,m={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(m.agentId=n.value),i.value&&(m.date=i.value),x&&(m.level=x),l.value&&(m.grep=l.value),m}function J1(t,e){return t.agentId?wa(Ue(t.agentId,e).logs,cr("agent",t.date)):wa(e.bridgeLogsDir,cr("bridge",t.date))}function Z1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function Y1(t,e){let n;try{n=W1(t)}catch{return[]}let i=[];for(let o of n){let c=Fa(o,e);if(!c)continue;let l=0;try{l=$1(wa(t,o)).size}catch{}i.push({file:wa(t,o),date:c,size:l})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Np(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let n;try{n=JSON.parse(t).level}catch{return!0}if(typeof n=="string"&&!Ml(n,e.level))return!1}return!0}var Pp={debug:"90",info:"36",warn:"33",error:"31"},X1=new Set(["ts","level","module","msg"]);function Q1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Mp(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=Q1(n.ts),o=typeof n.level=="string"?n.level:"",c=o.toUpperCase().padEnd(5);e.color&&Pp[o]&&(c=`\x1B[${Pp[o]}m${c}\x1B[0m`);let l=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",h=Object.entries(n).filter(([x])=>!X1.has(x)).map(([x,m])=>` ${x}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${l} ${u}${h}`}function eI(t,e,n){let c=j1(t,"utf8").split(`
126
+ `).filter(l=>l.length>0).filter(l=>Np(l,{level:e.level,grep:e.grep}));for(let l of Z1(c,e.lines))process.stdout.write(`${Mp(l,{raw:e.raw,color:n})}
127
+ `)}async function Bp(t,e){let n=e.paths??Y(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?Ue(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=Y1(l,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
128
+ `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
129
+ `);return 0}let o=t.date??Dn(new Date),c=J1({agentId:t.agentId,date:o},n);try{eI(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
130
130
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
131
- (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
132
- `),1}return t.follow&&await i2(c,t,i),0}var n2=500;function r2(t){try{let e=Rp(t,"r");try{return Pp(e).size}finally{Cp(e)}}catch{return 0}}async function i2(t,e,r){let i=r2(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let x=Rp(t,"r");try{let h=Pp(x).size;if(h>i){let m=Buffer.allocUnsafe(h-i),w=KS(x,m,0,m.length,i);u=m.subarray(0,w).toString("utf8"),i+=w}}finally{Cp(x)}}catch{}if(u){let x=(o+u).split(`
133
- `);o=x.pop()??"";for(let h of x)h.length>0&&Op(h,{level:e.level,grep:e.grep})&&process.stdout.write(`${Lp(h,{raw:e.raw,color:r})}
134
- `)}await new Promise(x=>setTimeout(x,n2))}}finally{process.off("SIGINT",d)}}import{basename as s2,resolve as o2}from"node:path";Ce();var a2=9e4,c2={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 d2(t){return c2[t]??1}async function Mp(t,e={}){let r=e.paths??J();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
131
+ (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
132
+ `),1}return t.follow&&await rI(c,t,i),0}var tI=500;function nI(t){try{let e=Op(t,"r");try{return Dp(e).size}finally{Cp(e)}}catch{return 0}}async function rI(t,e,n){let i=nI(t),o="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let h=Op(t,"r");try{let x=Dp(h).size;if(x>i){let m=Buffer.allocUnsafe(x-i),w=K1(h,m,0,m.length,i);u=m.subarray(0,w).toString("utf8"),i+=w}}finally{Cp(h)}}catch{}if(u){let h=(o+u).split(`
133
+ `);o=h.pop()??"";for(let x of h)x.length>0&&Np(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Mp(x,{raw:e.raw,color:n})}
134
+ `)}await new Promise(h=>setTimeout(h,tI))}}finally{process.off("SIGINT",l)}}import{basename as iI,resolve as sI}from"node:path";Pe();var oI=9e4,aI={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 cI(t){return aI[t]??1}async function Fp(t,e={}){let n=e.paths??Y();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
135
135
  `),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.
136
- `),3;let i=await xa(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.
137
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:o2(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 l2(i,"/agent/send",o,a2)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
136
+ `),3;let i=await ga(n).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${n.portFile} / ${n.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
137
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:sI(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 dI(i,"/agent/send",o,oI)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
138
138
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
139
- `),d2(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
140
- `);else{let d=t.name??s2(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})
141
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${u2(c.bytes)})
142
- `)}return 0}async function l2(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(),x=u?JSON.parse(u):null;return x&&typeof x=="object"&&"ok"in x?x:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function u2(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Kp=j("cli");function We(t,e){let{value:r,rest:i}=Pn(t,e);return{value:r,rest:i}}function ya(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
143
- `)}function N2(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:L}=We(e.slice(1),"--agent-id");return L?{mode:"reload",agentId:L}:{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 M2(e.slice(1));if(e[0]==="log")return{mode:"log",...Dp(e.slice(1))};if(e[0]==="connect")return B2(e.slice(1));if(e.includes("--status"))return ya("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ya("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ya("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ya("--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}=We(r,"--pat-token");r=o;let{value:c,rest:d}=We(r,"--pair-code");r=d;let{value:u,rest:x}=We(r,"--env");r=x;let{value:h,rest:m}=We(r,"--handshake-url");r=m;let{value:w,rest:I}=We(r,"--frontier-url");r=I;let{value:b,rest:S}=We(r,"--mock-scenario");r=S;let{value:A}=We(r,"--agent-id"),k=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let P={mode:"pair",privatecode:i,pairingCode:c};return u&&(P.env=u),h&&(P.handshakeUrl=h),w&&(P.frontierUrl=w),b&&(P.mockScenario=b),A&&(P.agentId=A),k&&(P.skipRebuildEnv=!0),P}function M2(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}=We(i,"--caption");i=c;let{value:d,rest:u}=We(i,"--name");i=u;let{value:x,rest:h}=We(i,"--agent-id");i=h;let{value:m,rest:w}=We(i,"--session-id");i=w;let{value:I,rest:b}=We(i,"--mime");i=b;let S=i.includes("--group-file");i=i.filter(P=>P!=="--group-file");let A=i.includes("--json"),k={mode:"send",kind:e,path:r,json:A};return o&&(k.caption=o),d&&(k.name=d),x&&(k.agentId=x),m&&(k.sessionId=m),S&&(k.groupFile=!0),I&&(k.mimeType=I),k}function B2(t){let e=t,{value:r,rest:i}=We(e,"--pat-token");e=i;let{value:o,rest:c}=We(e,"--env");e=c;let{value:d,rest:u}=We(e,"--handshake-url");e=u;let{value:x,rest:h}=We(e,"--frontier-url");e=h;let{value:m,rest:w}=We(e,"--mock-scenario");e=w;let I=e.includes("--skip-rebuild-env"),b={mode:"connect"};return r&&(b.privatecode=r),o&&(b.env=o),d&&(b.handshakeUrl=d),x&&(b.frontierUrl=x),m&&(b.mockScenario=m),I&&(b.skipRebuildEnv=!0),b}var F2=`
139
+ `),cI(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
140
+ `);else{let l=t.name??iI(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${l} (uri=${u})
141
+ `)}else process.stdout.write(`Sent ${t.kind} ${l} (${lI(c.bytes)})
142
+ `)}return 0}async function dI(t,e,n,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let l=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:o.signal}),u=await l.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=${l.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function lI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Vp=K("cli");function $e(t,e){let{value:n,rest:i}=Pn(t,e);return{value:n,rest:i}}function Sa(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
143
+ `)}function LI(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:O}=$e(e.slice(1),"--agent-id");return O?{mode:"reload",agentId:O}:{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 NI(e.slice(1));if(e[0]==="log")return{mode:"log",...Lp(e.slice(1))};if(e[0]==="connect")return MI(e.slice(1));if(e.includes("--status"))return Sa("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Sa("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Sa("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Sa("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:i,rest:o}=$e(n,"--pat-token");n=o;let{value:c,rest:l}=$e(n,"--pair-code");n=l;let{value:u,rest:h}=$e(n,"--env");n=h;let{value:x,rest:m}=$e(n,"--handshake-url");n=m;let{value:w,rest:v}=$e(n,"--frontier-url");n=v;let{value:_,rest:E}=$e(n,"--mock-scenario");n=E;let{value:I}=$e(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:c};return u&&(T.env=u),x&&(T.handshakeUrl=x),w&&(T.frontierUrl=w),_&&(T.mockScenario=_),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function NI(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=$e(i,"--caption");i=c;let{value:l,rest:u}=$e(i,"--name");i=u;let{value:h,rest:x}=$e(i,"--agent-id");i=x;let{value:m,rest:w}=$e(i,"--session-id");i=w;let{value:v,rest:_}=$e(i,"--mime");i=_;let E=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return o&&(A.caption=o),l&&(A.name=l),h&&(A.agentId=h),m&&(A.sessionId=m),E&&(A.groupFile=!0),v&&(A.mimeType=v),A}function MI(t){let e=t,{value:n,rest:i}=$e(e,"--pat-token");e=i;let{value:o,rest:c}=$e(e,"--env");e=c;let{value:l,rest:u}=$e(e,"--handshake-url");e=u;let{value:h,rest:x}=$e(e,"--frontier-url");e=x;let{value:m,rest:w}=$e(e,"--mock-scenario");e=w;let v=e.includes("--skip-rebuild-env"),_={mode:"connect"};return n&&(_.privatecode=n),o&&(_.env=o),l&&(_.handshakeUrl=l),h&&(_.frontierUrl=h),m&&(_.mockScenario=m),v&&(_.skipRebuildEnv=!0),_}var BI=`
144
144
  coze-bridge - local bridge daemon for cloud Agent Service
145
145
 
146
146
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -221,57 +221,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
221
221
 
222
222
  Internal:
223
223
  <node> <entry> --daemon daemon mode (OS supervisor only)
224
- `.trimStart();async function $p(t=process.argv,e={}){let r=N2(t);switch(r.mode){case"help":return process.stdout.write(F2),0;case"version":return process.stdout.write(`${Lt}
225
- `),0;case"daemon":{try{await gp()}catch(i){return Kp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return z2(e);case"stop":return Yp(e);case"reload":return G2(r.agentId,e);case"log":return Np(r,e);case"update":return U2(e);case"purge":return j2(e);case"service-install":return W2(e);case"service-uninstall":return K2(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),$2(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),V2(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Mp({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 Vp(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 z2(t){let e=t.paths??J(),r=new nn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
226
- `),1;if(i.kind==="stale")return await Vp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
227
- `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
224
+ `.trimStart();async function Jp(t=process.argv,e={}){let n=LI(t);switch(n.mode){case"help":return process.stdout.write(BI),0;case"version":return process.stdout.write(`${Mt}
225
+ `),0;case"daemon":{try{await wp()}catch(i){return Vp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return FI(e);case"stop":return Yp(e);case"reload":return GI(n.agentId,e);case"log":return Bp(n,e);case"update":return zI(e);case"purge":return qI(e);case"service-install":return jI(e);case"service-uninstall":return KI(e);case"pair":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),WI(n.privatecode,n.pairingCode,e,i,n.agentId,n.skipRebuildEnv)}case"connect":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),$I(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return Fp({kind:n.kind,path:n.path,...n.agentId?{agentId:n.agentId}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.caption?{caption:n.caption}:{},...n.name?{name:n.name}:{},...n.groupFile?{groupFile:!0}:{},...n.mimeType?{mimeType:n.mimeType}:{},json:n.json},e)}}async function Zp(t){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(t.pidFile).catch(()=>{}),e(t.portFile).catch(()=>{}),e(t.tokenFile).catch(()=>{})])}async function FI(t){let e=t.paths??Y(),n=new sn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
226
+ `),1;if(i.kind==="stale")return await Zp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
227
+ `),1;let o=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
228
228
  ${JSON.stringify(o.body,null,2)}
229
- `),0}async function Yp(t){let e=t.paths??J(),r=new nn(e),i=t.daemonSweep??(async()=>{let x=H0();return await G0(x),x}),o=async()=>{t.skipProcessKill||await i(e)},c=await xs(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(x){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(x)}
230
- `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
229
+ `),0}async function Yp(t){let e=t.paths??Y(),n=new sn(e),i=t.daemonSweep??(async()=>{let h=q0();return await j0(h),h}),o=async()=>{t.skipProcessKill||await i(e)},c=await ps(t),l=!1;if(c)try{await c.uninstall(),l=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
230
+ `)}let u=await n.probe();if(u.kind==="not-running")return await o(),process.stdout.write(l?`coze-bridge: stopped
231
231
  `:`coze-bridge: not running
232
- `),0;if(u.kind==="stale")return await Vp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
233
- `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
234
- `),0}catch(x){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
235
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(x)}
236
- `),1)}}async function U2(t){return await Yp(t),(t.spawnNpx??H2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function H2(t){return new Promise(e=>{let r=it("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
237
- `),e(1)})})}async function G2(t,e){let r=new nn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
238
- `),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)
232
+ `),0;if(u.kind==="stale")return await Zp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
233
+ `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
234
+ `),0}catch(h){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
235
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
236
+ `),1)}}async function zI(t){return await Yp(t),(t.spawnNpx??UI)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function UI(t){return new Promise(e=>{let n=at("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
237
+ `),e(1)})})}async function GI(t,e){let n=new sn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
238
+ `),1;try{let o=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let c=o.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
239
239
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
240
240
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
241
241
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
242
- `),1}}async function xs(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(qp(),Gp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Jp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??Y2,c=t.paths??J();if(r.kind==="connected"){if(!q2(r.body))return r;nt(c.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:r.body}),await e.request({method:"POST",path:"/shutdown"}).catch(x=>nt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(x)})),await Wp(c.pidFile,o)}let d=t.spawnDaemon??hp,u=await xs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let x=await jp(e,i,o);if(x.kind==="connected")return x;nt(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(x){nt(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(x)})}nt(c.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await Wp(c.pidFile,o)}else u&&await u.install({activate:!1}).catch(x=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(x)}
242
+ `),1}}async function ps(t){if(t.supervisor){let c=t.supervisor,l={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(l,u),uninstall:()=>c.uninstall(l)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(Kp(),jp)),i=e(),o=n();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Xp(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??VI,c=t.paths??Y();if(n.kind==="connected"){if(!HI(n.body))return n;st(c.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:n.body}),await e.request({method:"POST",path:"/shutdown"}).catch(h=>st(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await $p(c.pidFile,o)}let l=t.spawnDaemon??mp,u=await ps(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await Wp(e,i,o);if(h.kind==="connected")return h;st(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){st(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}st(c.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await $p(c.pidFile,o)}else u&&await u.install({activate:!1}).catch(h=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(h)}
243
243
  `));return process.stdout.write(`coze-bridge: starting daemon...
244
- `),await d({paths:t.paths}),jp(e,i,o)}function q2(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 j2(t){let e=new nn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
245
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
246
- `)}await new Promise(d=>setTimeout(d,500))}let i=await xs(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
247
- `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
248
- `)}let o=t.paths??J(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
249
- `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
244
+ `),await l({paths:t.paths}),Wp(e,i,o)}function HI(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 qI(t){let e=new sn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
245
+ `);try{await e.request({method:"POST",path:"/shutdown"})}catch(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
246
+ `)}await new Promise(l=>setTimeout(l,500))}let i=await ps(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
247
+ `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
248
+ `)}let o=t.paths??Y(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
249
+ `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
250
250
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
251
- `),0}async function W2(t){let e=await xs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
251
+ `),0}async function jI(t){let e=await ps(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
252
252
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
253
- `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
254
- `),1}}async function K2(t){let e=await xs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
255
- `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
256
- `),1}}async function Xp(t,e,r){if(e)return nt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(nt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(nt(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
257
- `),nt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function $2(t,e,r,i={},o,c){let d=new nn(r.paths),u=r.paths??J(),x=await Xp(u,c,r.reconstructEnv??Qd);if(await Jc(u,x).catch(w=>nt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!r.skipDistInstall){let w=await il({paths:r.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
258
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(b=>setTimeout(b,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
259
- `)}let h=await Jp(r,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
260
- `),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 w=await d.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let I=w.body.agent;return I&&!I.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${I.agentId}): ${I.note}
253
+ `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
254
+ `),1}}async function KI(t){let e=await ps(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
255
+ `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
256
+ `),1}}async function Qp(t,e,n){if(e)return st(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(st(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(st(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)
257
+ `),st(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function WI(t,e,n,i={},o,c){let l=new sn(n.paths),u=n.paths??Y(),h=await Qp(u,c,n.reconstructEnv??rl);if(await ed(u,h).catch(w=>st(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!n.skipDistInstall){let w=await cl({paths:n.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
258
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
259
+ `)}let x=await Xp(n,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
260
+ `),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 w=await l.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let v=w.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
261
261
  `),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"
262
262
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
263
263
  `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
264
- `),1}}async function V2(t,e,r={},i){let o=e.paths??J(),c=t??await oa(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new nn(e.paths),u=await Xp(o,i,e.reconstructEnv??Qd);if(await Jc(o,u).catch(m=>nt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await il({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
265
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(I=>setTimeout(I,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
266
- `)}let x=await Jp(e,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
267
- `),1;let h={privatecode:c};r.env&&(h.env=r.env),r.handshakeUrl&&(h.handshake_url=r.handshakeUrl),r.frontierUrl&&(h.frontier_url=r.frontierUrl),r.mockScenario&&(h.mock_scenario=r.mockScenario);try{let m=await d.request({method:"POST",path:"/connect",body:h,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
268
- `),t!==void 0&&await cs(c,o).catch(w=>Kp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
264
+ `),1}}async function $I(t,e,n={},i){let o=e.paths??Y(),c=t??await la(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let l=new sn(e.paths),u=await Qp(o,i,e.reconstructEnv??rl);if(await ed(o,u).catch(m=>st(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await cl({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
265
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
266
+ `)}let h=await Xp(e,l);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
267
+ `),1;let x={privatecode:c};n.env&&(x.env=n.env),n.handshakeUrl&&(x.handshake_url=n.handshakeUrl),n.frontierUrl&&(x.frontier_url=n.frontierUrl),n.mockScenario&&(x.mock_scenario=n.mockScenario);try{let m=await l.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
268
+ `),t!==void 0&&await ls(c,o).catch(w=>Vp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
269
269
  `),1)}catch(m){return process.stderr.write(`coze-bridge: connect failed: ${String(m)}
270
- `),1}}async function jp(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 Wp(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||!Ki(u))return;await e(i)}}function Y2(t){return new Promise(e=>setTimeout(e,t))}te();function J2(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=J2(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
271
- `),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
270
+ `),1}}async function Wp(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await n(200)}return t.probe(500)}async function $p(t,e,n=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<n;c++){let l;try{l=await o(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!Vi(u))return;await e(i)}}function VI(t){return new Promise(e=>setTimeout(e,t))}ne();function JI(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let n=Number(e[1]),i=Number(e[2]??0);return n<18||n===18&&i<4?"fatal":n<20?"warn":"ok"}function em(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){let i=JI(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
271
+ `),n(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${o},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
272
272
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
273
273
  npx -y coze-bridge@latest stop
274
274
  npx -y coze-bridge@latest connect
275
275
 
276
- `)}Zp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Dl("warn");$p(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
276
+ `)}em();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Ll("warn");Jp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
277
277
  `),process.exit(1)});