coze-bridge 0.2.2-beta.1 → 0.2.3-alpha.1

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 +102 -100
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var vg=Object.create;var ba=Object.defineProperty;var Sg=Object.getOwnPropertyDescriptor;var Ig=Object.getOwnPropertyNames;var Ag=Object.getPrototypeOf,kg=Object.prototype.hasOwnProperty;var ue=(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 Qe=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),va=(t,e)=>{for(var n in e)ba(t,n,{get:e[n],enumerable:!0})},Tg=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ig(e))!kg.call(t,s)&&s!==n&&ba(t,s,{get:()=>e[s],enumerable:!(i=Sg(e,s))||i.enumerable});return t};var Gt=(t,e,n)=>(n=t!=null?vg(Ag(t)):{},Tg(e||!t||!t.__esModule?ba(n,"default",{value:t,enumerable:!0}):n,t));function Ke(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var sr=Qe(()=>{"use strict"});import{createWriteStream as Rg,mkdirSync as Cg,readdirSync as Pg,unlinkSync as Dg}from"node:fs";import{join as yl}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 or(t,e){return`${t}-${e}.log`}function Sa(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Og(t,e,n){let i=c=>{let[d,u,h]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>n}function cs(t,e,n,i){let s;try{s=Pg(t)}catch{return}for(let c of s){let d=Sa(c,e);if(d&&Og(d,n,i))try{Dg(yl(t,c))}catch{}}}var ei,Ia=Qe(()=>{"use strict";ei=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{Cg(this.dir,{recursive:!0});let n=Rg(yl(this.dir,or(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&&cs(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Lg,mkdirSync as Ng}from"node:fs";import{join as Mg}from"node:path";function bl(t){let e=t.retentionDays??zg,n=t.clock??(()=>Dn(new Date));ls={bridgeSink:new ei(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:s=>new ei(t.agentLogsDir(s),"agent",{retentionDays:e,clock:n})};let i=n();cs(t.bridgeLogsDir,"bridge",i,e);for(let s of t.listAgentIds?.()??[])cs(t.agentLogsDir(s),"agent",i,e)}function Ug(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function vl(t){Aa=t}function Sl(t){return ar[Aa]<=ar[t]}function Il(t,e){let n=ar[t];return n===void 0?!0:n>=ar[e]}function us(t){El={...t}}function Al(t){let e=(u,h=2)=>String(u).padStart(h,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",s=Math.abs(n),c=e(Math.floor(s/60)),d=e(s%60);return`${Dn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function dt(t,e,n,i,s){try{let c=`${JSON.stringify({ts:Al(new Date),level:e,module:n,msg:i,...s})}
11
- `;Ng(t,{recursive:!0}),Lg(Mg(t,or("bridge",Dn(new Date))),c)}catch{}}function Gg(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function ds(t,e,n,i,s){if(ar[t]<ar[Aa])return;let c=`${JSON.stringify({ts:Al(new Date),level:t,module:e,msg:n,...El,...i})}
12
- `;if(ls){let d=Gg(s,i),u=d?Ug(ls,d):ls.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Fg.write(c):Bg.write(c)}function H(t,e){return{debug:(n,i)=>ds("debug",t,n,i,e),info:(n,i)=>ds("info",t,n,i,e),warn:(n,i)=>ds("warn",t,n,i,e),error:(n,i)=>ds("error",t,n,i,e),child:n=>H(`${t}.${n}`,e),forAgent:n=>H(t,n)}}var ar,Aa,Bg,Fg,El,zg,ls,ne=Qe(()=>{"use strict";sr();Ia();ar={debug:10,info:20,warn:30,error:40},Aa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Bg=process.stdout,Fg=process.stderr,El={},zg=Ke("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ls=null});var k,je=Qe(()=>{"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 Cl={};va(Cl,{ACP_WRAPPER_NPM_PACKAGES:()=>fs,_resetAcpInstallerForTests:()=>$g,_setBinaryPathCacheForTests:()=>Vg,buildAcpSpawn:()=>ni,ensureAcpInstalled:()=>cr,getAcpBinaryPath:()=>hs,pickWhichLine:()=>Ra,probeAcpVersion:()=>Kg,resolveAcpCommand:()=>Rl});import{readFileSync as kl}from"node:fs";import{createRequire as qg}from"node:module";import{dirname as Hg,resolve as jg}from"node:path";function Ra(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=i=>e.find(s=>s.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function Wg(t){let e=Tl.resolve(`${t.npmPackage}/package.json`),n=Hg(e),i=JSON.parse(kl(e,"utf8")),s=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!s)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return jg(n,s)}async function cr(t,e){let n=Ta[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ti.get(t);if(i)return i;try{let s=Wg(n);return ti.set(t,s),ka.info("acp wrapper resolved",{framework:t,binary:n.binary,path:s}),s}catch(s){throw ka.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(s)}),new 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:s})}}async function Kg(t){let e=Ta[t];if(e)try{let n=Tl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(kl(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){ka.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function hs(t){return ti.get(t)}function Rl(t,e){if(e)return e;let n=hs(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 ni(t,e,n){if(e)return{command:e,args:[...n]};let i=Rl(t);return{command:process.execPath,args:[i,...n]}}function $g(){ti.clear()}function Vg(t,e){ti.set(t,e)}var ka,Ta,fs,Tl,ti,on=Qe(()=>{"use strict";je();ne();ka=H("agents.acp-installer"),Ta={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},fs=Object.values(Ta).filter(t=>t!==void 0).map(t=>t.npmPackage),Tl=qg(import.meta.url),ti=new Map});import{chmod as Jg,mkdir as Zg,readFile as Xg,rename as Qg,rm as em,writeFile as tm}from"node:fs/promises";import{dirname as nm}from"node:path";async function dr(t){try{let e=await Xg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function an(t,e,n){await Zg(nm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await tm(i,e,{encoding:"utf8",mode:n?.mode}),await Qg(i,t),n?.mode!==void 0&&await Jg(t,n.mode)}catch(s){throw await em(i,{force:!0}).catch(()=>{}),s}}async function lr(t,e,n){await an(t,`${JSON.stringify(e,null,2)}
14
- `,n)}var cn=Qe(()=>{"use strict"});import{promises as Ol,readdirSync as rm}from"node:fs";import{homedir as im}from"node:os";import{sep as sm,join as ke,resolve as Ll}from"node:path";function ee(t){let e=t??im(),n=ke(e,".coze"),i=ke(n,"bridge"),s=ke(i,"lib"),c=ke(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:s,libEntry:ke(s,"index.js"),binDir:ke(i,"bin"),pidFile:ke(i,"bridge.pid"),portFile:ke(i,"bridge.port"),tokenFile:ke(i,"bridge.token"),patTokenFile:ke(i,"pat-token"),agentEnvFile:ke(i,"agent-env.json"),logFile:ke(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:ke(c,"daemon-stdio.log"),installLock:ke(i,"install.lock"),configFile:ke(i,"config.json"),agentsRoot:ke(n,"agents")}}function $e(t,e=ee()){let n=ke(e.agentsRoot,t);return{root:n,config:ke(n,"config.json"),workspace:ke(n,"workspace"),logs:ke(n,"logs")}}function xs(t=ee()){try{return rm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ri(t,e){let n=await Ol.realpath(Ll(t)).catch(()=>null);if(!n)return!1;let i=await Ol.realpath(Ll(e)).catch(()=>null);if(!i)return!1;let s=process.platform==="win32"?n.toLowerCase():n,c=process.platform==="win32"?i.toLowerCase():i;return s===c||s.startsWith(c+sm)}var Le=Qe(()=>{"use strict"});var gs={};va(gs,{AGENT_CONFIG_FILE_MODE:()=>ps,enforceAgentConfigMode:()=>cm,loadAgentConfig:()=>Te,persistAgentSessions:()=>ii,persistAgentSkills:()=>si,saveAgentConfig:()=>Be});import{chmod as om,stat as am}from"node:fs/promises";function Te(t,e){return dr($e(t,e).config)}function Be(t,e){return lr($e(t.agentId,e).config,t,{mode:ps})}async function cm(t,e){if(process.platform==="win32")return;let n=$e(t,e).config;try{let i=await am(n);if(!i.isFile())return;let s=i.mode&511;s!==ps&&(await om(n,ps),Nl.warn("agent config mode auto-corrected to 0600",{path:n,from:s.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Nl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function ii(t,e,n){let i=await Te(t,n);i&&(i.sessions=Object.fromEntries(e),await Be(i,n))}async function si(t,e,n){let i=await Te(t,n);i&&(i.skills=e,await Be(i,n))}var Nl,ps,dn=Qe(()=>{"use strict";cn();ne();Le();Nl=H("agent-config"),ps=384});var Da=ae((Q2,Fl)=>{Fl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var ws=ae(Ul=>{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 xm(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))Ul[t]=xm(zl[t])});var Wl=ae((tI,jl)=>{var pm=ue("fs"),Ne=ue("path"),Gl=Da(),gm=ws(),mm=typeof process=="object"&&process.platform==="win32",ql=t=>typeof t=="object"&&t!==null,Hl=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 ve(t){this.sep=Ne.sep,this.fs=pm,ql(t)&&ql(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}jl.exports=ve;ve.prototype.makeDir=function(t){let e=this;function n(i){let s=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){s+=e.sep+c;var d;try{d=e.fs.statSync(s)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw u}if(d&&d.isFile())throw gm.FILE_IN_THE_WAY(`"${s}"`)}})}n(t)};ve.prototype.writeFileTo=function(t,e,n,i){let s=this;if(s.fs.existsSync(t)){if(!n)return!1;var c=s.fs.statSync(t);if(c.isDirectory())return!1}var d=Ne.dirname(t);s.fs.existsSync(d)||s.makeDir(d);var u;try{u=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),u=s.fs.openSync(t,"w",438)}if(u)try{s.fs.writeSync(u,e,0,e.length,0)}finally{s.fs.closeSync(u)}return s.fs.chmodSync(t,i||438),!0};ve.prototype.writeFileToAsync=function(t,e,n,i,s){typeof i=="function"&&(s=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!n)return s(!1);c.fs.stat(t,function(u,h){if(d&&h.isDirectory())return s(!1);var x=Ne.dirname(t);c.fs.exists(x,function(g){g||c.makeDir(x),c.fs.open(t,"w",438,function(w,S){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,v){c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){s(!0)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,function(){c.fs.chmod(t,i||438,function(){s(!0)})})}):c.fs.chmod(t,i||438,function(){s(!0)})})})})})};ve.prototype.findFiles=function(t){let e=this;function n(i,s,c){typeof s=="boolean"&&(c=s,s=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let h=Ne.join(i,u),x=e.fs.statSync(h);(!s||s.test(h))&&d.push(Ne.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(n(h,s,c)))}),d}return n(t,void 0,!0)};ve.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(s,c){if(s)return e(s);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Ne.join(t,u),n.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Ne.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(g,w){if(g)return e(g);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};ve.prototype.getAttributes=function(){};ve.prototype.setAttributes=function(){};ve.crc32update=function(t,e){return Hl[(t^e)&255]^t>>>8};ve.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=ve.crc32update(n,t[i++]);return~n>>>0};ve.methodToString=function(t){switch(t){case Gl.STORED:return"STORED ("+t+")";case Gl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ve.canonical=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.join(".",e)};ve.zipnamefix=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.posix.join(".",e)};ve.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]};ve.sanitize=function(t,e){t=Ne.resolve(Ne.normalize(t));for(var n=e.split("/"),i=0,s=n.length;i<s;i++){var c=Ne.normalize(Ne.join(t,n.slice(i,s).join(Ne.sep)));if(c.indexOf(t)===0)return c}return Ne.normalize(Ne.join(t,Ne.basename(e)))};ve.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};ve.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};ve.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)};ve.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};ve.isWin=mm;ve.crcTable=Hl});var $l=ae((nI,Kl)=>{var wm=ue("path");Kl.exports=function(t,{fs:e}){var n=t||"",i=c(),s=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(s=e.statSync(n),i.directory=s.isDirectory(),i.mtime=s.mtime,i.atime=s.atime,i.executable=(73&s.mode)!==0,i.readonly=(128&s.mode)===0,i.hidden=wm.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 Yl=ae((rI,Vl)=>{Vl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var hr=ae((iI,fr)=>{fr.exports=Wl();fr.exports.Constants=Da();fr.exports.Errors=ws();fr.exports.FileAttr=$l();fr.exports.decoder=Yl()});var Zl=ae((sI,Jl)=>{var ln=hr(),z=ln.Constants;Jl.exports=function(){var t=20,e=10,n=0,i=0,s=0,c=0,d=0,u=0,h=0,x=0,g=0,w=0,S=0,y=0,v=0;t|=ln.isWin?2560:768,n|=z.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,R=E=>Math.max(0,E)&65535,D=E=>Math.max(0,E)&255;return s=ln.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return n},set flags(E){n=E},get flags_efs(){return(n&z.FLG_EFS)>0},set flags_efs(E){E?n|=z.FLG_EFS:n&=~z.FLG_EFS},get flags_desc(){return(n&z.FLG_DESC)>0},set flags_desc(E){E?n|=z.FLG_DESC:n&=~z.FLG_DESC},get method(){return i},set method(E){switch(E){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=E},get time(){return ln.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=ln.fromDate2DOS(E)},get timeval(){return s},set timeval(E){s=A(E)},get timeHighByte(){return D(s>>>8)},get crc(){return c},set crc(E){c=A(E)},get compressedSize(){return d},set compressedSize(E){d=A(E)},get size(){return u},set size(E){u=A(E)},get fileNameLength(){return h},set fileNameLength(E){h=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return g},set commentLength(E){g=E},get diskNumStart(){return w},set diskNumStart(E){w=A(E)},get inAttr(){return S},set inAttr(E){S=A(E)},get attr(){return y},set attr(E){y=A(E)},get fileAttr(){return(y||0)>>16&4095},get offset(){return v},set offset(E){v=A(E)},get encrypted(){return(n&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+x+g},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var C=E.slice(v,v+z.LOCHDR);if(C.readUInt32LE(0)!==z.LOCSIG)throw ln.Errors.INVALID_LOC();I.version=C.readUInt16LE(z.LOCVER),I.flags=C.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=C.readUInt16LE(z.LOCHOW),I.time=C.readUInt32LE(z.LOCTIM),I.crc=C.readUInt32LE(z.LOCCRC),I.compressedSize=C.readUInt32LE(z.LOCSIZ),I.size=C.readUInt32LE(z.LOCLEN),I.fnameLen=C.readUInt16LE(z.LOCNAM),I.extraLen=C.readUInt16LE(z.LOCEXT);let O=v+z.LOCHDR+I.fnameLen,F=O+I.extraLen;return E.slice(O,F)},loadFromBinary:function(E){if(E.length!==z.CENHDR||E.readUInt32LE(0)!==z.CENSIG)throw ln.Errors.INVALID_CEN();t=E.readUInt16LE(z.CENVEM),e=E.readUInt16LE(z.CENVER),n=E.readUInt16LE(z.CENFLG),i=E.readUInt16LE(z.CENHOW),s=E.readUInt32LE(z.CENTIM),c=E.readUInt32LE(z.CENCRC),d=E.readUInt32LE(z.CENSIZ),u=E.readUInt32LE(z.CENLEN),h=E.readUInt16LE(z.CENNAM),x=E.readUInt16LE(z.CENEXT),g=E.readUInt16LE(z.CENCOM),w=E.readUInt16LE(z.CENDSK),S=E.readUInt16LE(z.CENATT),y=E.readUInt32LE(z.CENATX),v=E.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(z.LOCHDR);return E.writeUInt32LE(z.LOCSIG,0),E.writeUInt16LE(e,z.LOCVER),E.writeUInt16LE(n,z.LOCFLG),E.writeUInt16LE(i,z.LOCHOW),E.writeUInt32LE(s,z.LOCTIM),E.writeUInt32LE(c,z.LOCCRC),E.writeUInt32LE(d,z.LOCSIZ),E.writeUInt32LE(u,z.LOCLEN),E.writeUInt16LE(h,z.LOCNAM),E.writeUInt16LE(I.extraLen,z.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(z.CENHDR+h+x+g);return E.writeUInt32LE(z.CENSIG,0),E.writeUInt16LE(t,z.CENVEM),E.writeUInt16LE(e,z.CENVER),E.writeUInt16LE(n,z.CENFLG),E.writeUInt16LE(i,z.CENHOW),E.writeUInt32LE(s,z.CENTIM),E.writeUInt32LE(c,z.CENCRC),E.writeUInt32LE(d,z.CENSIZ),E.writeUInt32LE(u,z.CENLEN),E.writeUInt16LE(h,z.CENNAM),E.writeUInt16LE(x,z.CENEXT),E.writeUInt16LE(g,z.CENCOM),E.writeUInt16LE(w,z.CENDSK),E.writeUInt16LE(S,z.CENATT),E.writeUInt32LE(y,z.CENATX),E.writeUInt32LE(v,z.CENOFF),E},toJSON:function(){let E=function(C){return C+" bytes"};return{made:t,version:e,flags:n,method:ln.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(h),extraLength:E(x),commentLength:E(g),diskNumStart:w,inAttr:S,attr:y,offset:v,centralHeaderSize:E(z.CENHDR+h+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ql=ae((oI,Xl)=>{var xr=hr(),ye=xr.Constants;Xl.exports=function(){var t=0,e=0,n=0,i=0,s=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return n},set size(c){n=c},get offset(){return i},set offset(c){i=c},get commentLength(){return s},set commentLength(c){s=c},get mainHeaderSize(){return ye.ENDHDR+s},loadFromBinary:function(c){if((c.length!==ye.ENDHDR||c.readUInt32LE(0)!==ye.ENDSIG)&&(c.length<ye.ZIP64HDR||c.readUInt32LE(0)!==ye.ZIP64SIG))throw xr.Errors.INVALID_END();c.readUInt32LE(0)===ye.ENDSIG?(t=c.readUInt16LE(ye.ENDSUB),e=c.readUInt16LE(ye.ENDTOT),n=c.readUInt32LE(ye.ENDSIZ),i=c.readUInt32LE(ye.ENDOFF),s=c.readUInt16LE(ye.ENDCOM)):(t=xr.readBigUInt64LE(c,ye.ZIP64SUB),e=xr.readBigUInt64LE(c,ye.ZIP64TOT),n=xr.readBigUInt64LE(c,ye.ZIP64SIZE),i=xr.readBigUInt64LE(c,ye.ZIP64OFF),s=0)},toBinary:function(){var c=Buffer.alloc(ye.ENDHDR+s);return c.writeUInt32LE(ye.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,ye.ENDSUB),c.writeUInt16LE(e,ye.ENDTOT),c.writeUInt32LE(n,ye.ENDSIZ),c.writeUInt32LE(i,ye.ENDOFF),c.writeUInt16LE(s,ye.ENDCOM),c.fill(" ",ye.ENDHDR),c},toJSON:function(){let c=function(d,u){let h=d.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:c(i,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var La=ae(Oa=>{Oa.EntryHeader=Zl();Oa.MainHeader=Ql()});var tu=ae((cI,eu)=>{eu.exports=function(t){var e=ue("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var s=e.createDeflateRaw(n),c=[],d=0;s.on("data",function(u){c.push(u),d+=u.length}),s.on("end",function(){var u=Buffer.alloc(d),h=0;u.fill(0);for(var x=0;x<c.length;x++){var g=c[x];g.copy(u,h),h+=g.length}i&&i(u)}),s.end(t)}}}});var ru=ae((dI,nu)=>{var _m=+(process.versions?process.versions.node:"").split(".")[0]||0;nu.exports=function(t,e){var n=ue("zlib");let i=_m>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(s){var c=n.createInflateRaw(i),d=[],u=0;c.on("data",function(h){d.push(h),u+=h.length}),c.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var g=0;g<d.length;g++){var w=d[g];w.copy(h,x),x+=w.length}s&&s(h)}),c.end(t)}}}});var cu=ae((lI,au)=>{"use strict";var{randomFillSync:iu}=ue("crypto"),ym=ws(),Em=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}),ou=(t,e)=>Math.imul(t,e)>>>0,su=(t,e)=>Em[(t^e)&255]^t>>>8,oi=()=>typeof iu=="function"?iu(Buffer.alloc(12)):oi.node();oi.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 _s={genSalt:oi};function ys(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])}ys.prototype.updateKeys=function(t){let e=this.keys;return e[0]=su(e[0],t),e[1]+=e[0]&255,e[1]=ou(e[1],134775813)+1,e[2]=su(e[2],e[1]>>>24),t};ys.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return ou(t,t^1)>>8&255};function bm(t){let e=new ys(t);return function(n){let i=Buffer.alloc(n.length),s=0;for(let c of n)i[s++]=e.updateKeys(c^e.next());return i}}function vm(t){let e=new ys(t);return function(n,i,s=0){i||(i=Buffer.alloc(n.length));for(let c of n){let d=e.next();i[s++]=c^d,e.updateKeys(c)}return i}}function Sm(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=bm(n),s=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==c)throw ym.WRONG_PASSWORD();return i(t.slice(12))}function Im(t){Buffer.isBuffer(t)&&t.length>=12?_s.genSalt=function(){return t.slice(0,12)}:t==="node"?_s.genSalt=oi.node:_s.genSalt=oi}function Am(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=vm(n),c=_s.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return s(c,d),s(t,d,12)}au.exports={decrypt:Sm,encrypt:Am,_salter:Im}});var du=ae(Es=>{Es.Deflater=tu();Es.Inflater=ru();Es.ZipCrypto=cu()});var Ma=ae((fI,lu)=>{var ce=hr(),km=La(),Se=ce.Constants,Na=du();lu.exports=function(t,e){var n=new km.EntryHeader,i=Buffer.alloc(0),s=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let g=t,w=typeof g.decoder=="object"?g.decoder:ce.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function y(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(ce.crc32(E)!==n.localHeader.crc)return!1}else{let C={},O=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(O)==Se.LOCSIG||e.readUInt32LE(O)==Se.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Se.EXTSIG)C.crc=e.readUInt32LE(O+Se.EXTCRC),C.compressedSize=e.readUInt32LE(O+Se.EXTSIZ),C.size=e.readUInt32LE(O+Se.EXTLEN);else if(e.readUInt16LE(O+12)===19280)C.crc=e.readUInt32LE(O+Se.EXTCRC-4),C.compressedSize=e.readUInt32LE(O+Se.EXTSIZ-4),C.size=e.readUInt32LE(O+Se.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(C.compressedSize!==n.compressedSize||C.size!==n.size||C.crc!==n.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(E)!==C.crc)return!1}return!0}function v(E,C,O){if(typeof C>"u"&&typeof E=="string"&&(O=E,E=void 0),c)return E&&C&&C(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return E&&C&&C(F),F;if(n.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ce.Errors.INVALID_PASS_PARAM();F=Na.ZipCrypto.decrypt(F,n,O)}var B=Buffer.alloc(n.size);switch(n.method){case ce.Constants.STORED:if(F.copy(B),y(B))return E&&C&&C(B),B;throw E&&C&&C(B,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var Y=new Na.Inflater(F,n.size);if(E)Y.inflateAsync(function(V){V.copy(V,0),C&&(y(V)?C(V):C(V,ce.Errors.BAD_CRC()))});else{if(Y.inflate(B).copy(B,0),!y(B))throw ce.Errors.BAD_CRC(`"${w.decode(i)}"`);return B}break;default:throw E&&C&&C(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(E,C){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&C&&C(S()),S();if(d.length&&!c){var O;switch(n.method){case ce.Constants.STORED:return n.compressedSize=n.size,O=Buffer.alloc(d.length),d.copy(O),E&&C&&C(O),O;default:case ce.Constants.DEFLATED:var F=new Na.Deflater(d);if(E)F.deflateAsync(function(Y){O=Buffer.alloc(Y.length),n.compressedSize=Y.length,Y.copy(O),C&&C(O)});else{var B=F.deflate();return n.compressedSize=B.length,B}F=null;break}}else if(E&&C)C(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,C){return ce.readBigUInt64LE(E,C)}function R(E){try{for(var C=0,O,F,B;C+4<E.length;)O=E.readUInt16LE(C),C+=2,F=E.readUInt16LE(C),C+=2,B=E.slice(C,C+F),C+=F,Se.ID_ZIP64===O&&D(B)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(E){var C,O,F,B;E.length>=Se.EF_ZIP64_SCOMP&&(C=A(E,Se.EF_ZIP64_SUNCOMP),n.size===Se.EF_ZIP64_OR_32&&(n.size=C)),E.length>=Se.EF_ZIP64_RHO&&(O=A(E,Se.EF_ZIP64_SCOMP),n.compressedSize===Se.EF_ZIP64_OR_32&&(n.compressedSize=O)),E.length>=Se.EF_ZIP64_DSN&&(F=A(E,Se.EF_ZIP64_RHO),n.offset===Se.EF_ZIP64_OR_32&&(n.offset=F)),E.length>=Se.EF_ZIP64_DSN+4&&(B=E.readUInt32LE(Se.EF_ZIP64_DSN),n.diskNumStart===Se.EF_ZIP64_OR_16&&(n.diskNumStart=B))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(E){i=ce.toBuffer(E,w.encode);var C=i[i.length-1];c=C===47||C===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,n.extraLength=E.length,R(E)},get comment(){return w.decode(s)},set comment(E){if(s=ce.toBuffer(E,w.encode),n.commentLength=s.length,s.length>65535)throw ce.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 I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){d=ce.toBuffer(E,ce.decoder.encode),!c&&d.length?(n.size=d.length,n.method=ce.Constants.DEFLATED,n.crc=ce.crc32(E),n.changed=!0):n.method=ce.Constants.STORED},getData:function(E){return n.changed?d:v(!1,null,E)},getDataAsync:function(E,C){n.changed?E(d):v(!0,E,C)},set attr(E){n.attr=E},get attr(){return n.attr},set header(E){n.loadFromBinary(E)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var E=n.centralHeaderToBinary(),C=ce.Constants.CENHDR;return i.copy(E,C),C+=i.length,u.copy(E,C),C+=n.extraLength,s.copy(E,C),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=h.length;let C=n.localHeaderToBinary(),O=Buffer.alloc(C.length+i.length+n.extraLocalLength);return C.copy(O,E),E+=C.length,i.copy(O,E),E+=i.length,h.copy(O,E),E+=h.length,O},toJSON:function(){let E=function(C){return"<"+(C&&C.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var hu=ae((hI,fu)=>{var uu=Ma(),Tm=La(),We=hr();fu.exports=function(t,e){var n=[],i={},s=Buffer.alloc(0),c=new Tm.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:g,decoder:w}=x;t?v(x.readEntries):d=!0;function S(){let A=new Set;for(let R of Object.keys(i)){let D=R.split("/");if(D.pop(),!!D.length)for(let E=0;E<D.length;E++){let C=D.slice(0,E+1).join("/")+"/";A.add(C)}}for(let R of A)if(!(R in i)){let D=new uu(x);D.entryName=R,D.attr=16,D.temporary=!0,n.push(D),i[D.entryName]=D,h.add(D)}}function y(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/We.Constants.CENHDR)throw We.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(c.diskEntries);for(var A=c.offset,R=0;R<n.length;R++){var D=A,E=new uu(x,t);E.header=t.slice(D,D+=We.Constants.CENHDR),E.entryName=t.slice(D,D+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(D,D+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(D,D+E.header.commentLength)),A+=E.header.centralHeaderSize,n[R]=E,i[E.entryName]=E}h.clear(),S()}function v(A){var R=t.length-We.Constants.ENDHDR,D=Math.max(0,R-65535),E=D,C=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(D=0),R;R>=E;R--)if(t[R]===80){if(t.readUInt32LE(R)===We.Constants.ENDSIG){O=R,F=R,C=R+We.Constants.ENDHDR,E=R-We.Constants.END64HDR;continue}if(t.readUInt32LE(R)===We.Constants.END64SIG){E=D;continue}if(t.readUInt32LE(R)===We.Constants.ZIP64SIG){O=R,C=R+We.readBigUInt64LE(t,R+We.Constants.ZIP64SIZE)+We.Constants.ZIP64LEAD;break}}if(O==-1)throw We.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,C)),c.commentLength&&(s=t.slice(F+We.Constants.ENDHDR)),A&&y()}function I(){n.length>1&&!g&&n.sort((A,R)=>A.entryName.toLowerCase().localeCompare(R.entryName.toLowerCase()))}return{get entries(){return d||y(),n.filter(A=>!h.has(A))},get comment(){return w.decode(s)},set comment(A){s=We.toBuffer(A,w.encode),c.commentLength=s.length},getEntryCount:function(){return d?n.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||y(),i[A]||null},setEntry:function(A){d||y(),n.push(A),i[A.entryName]=A,c.totalEntries=n.length},deleteFile:function(A,R=!0){d||y();let D=i[A];this.getEntryChildren(D,R).map(C=>C.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let R=i[A],D=n.indexOf(R);D>=0&&(n.splice(D,1),delete i[A],c.totalEntries=n.length)},getEntryChildren:function(A,R=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&R){let D=[],E=A.entryName;for(let C of n)C.entryName.startsWith(E)&&D.push(C);return D}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let R=this.getEntryChildren(A);return R.includes(A)?R.length-1:R.length}return 0},compressToBuffer:function(){d||y(),I();let A=[],R=[],D=0,E=0;c.size=0,c.offset=0;let C=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,A.push(V),A.push(Y);let X=B.packCentralHeader();R.push(X),c.size+=X.length,D+=re+X.length,C++}D+=c.mainHeaderSize,c.offset=E,c.totalEntries=C,E=0;let O=Buffer.alloc(D);for(let B of A)B.copy(O,E),E+=B.length;for(let B of R)B.copy(O,E),E+=B.length;let F=c.toBinary();return s&&s.copy(F,We.Constants.ENDHDR),F.copy(O,E),t=O,d=!1,O},toAsyncBuffer:function(A,R,D,E){try{d||y(),I();let C=[],O=[],F=0,B=0,Y=0;c.size=0,c.offset=0;let V=function(re){if(re.length>0){let X=re.shift(),se=X.entryName+X.extra.toString();D&&D(se),X.getCompressedDataAsync(function(oe){E&&E(se),X.header.offset=B;let P=X.packLocalHeader(),U=P.length+oe.length;B+=U,C.push(P),C.push(oe);let K=X.packCentralHeader();O.push(K),c.size+=K.length,F+=U+K.length,Y++,V(re)})}else{F+=c.mainHeaderSize,c.offset=B,c.totalEntries=Y,B=0;let X=Buffer.alloc(F);C.forEach(function(oe){oe.copy(X,B),B+=oe.length}),O.forEach(function(oe){oe.copy(X,B),B+=oe.length});let se=c.toBinary();s&&s.copy(se,We.Constants.ENDHDR),se.copy(X,B),t=X,d=!1,A(X)}};V(Array.from(this.entries))}catch(C){R(C)}}}}});var gu=ae((xI,pu)=>{var be=hr(),Ee=ue("path"),Rm=Ma(),Cm=hu(),On=(...t)=>be.findLast(t,e=>typeof e=="boolean"),xu=(...t)=>be.findLast(t,e=>typeof e=="string"),Pm=(...t)=>be.findLast(t,e=>typeof e=="function"),Dm={noSort:!1,readEntries:!1,method:be.Constants.NONE,fs:null};pu.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),Dm);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=be.Constants.BUFFER,t=void 0)),Object.assign(i,e);let s=new be(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=be.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))i.method=be.Constants.FILE,i.filename=t,n=s.fs.readFileSync(t);else throw be.Errors.INVALID_FILENAME();let c=new Cm(n,i),{canonical:d,sanitize:u,zipnamefix:h}=be;function x(y){if(y&&c){var v;if(typeof y=="string"&&(v=c.getEntry(Ee.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(v=c.getEntry(y.entryName)),v)return v}return null}function g(y){let{join:v,normalize:I,sep:A}=Ee.posix;return v(Ee.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function w(y){return y instanceof RegExp?(function(v){return function(I){return v.test(I)}})(y):typeof y!="function"?()=>!0:y}let S=(y,v)=>{let I=v.slice(-1);return I=I===s.sep?s.sep:"",Ee.relative(y,v)+I};return{readFile:function(y,v){var I=x(y);return I&&I.getData(v)||null},childCount:function(y){let v=x(y);if(v)return c.getChildCount(v)},readFileAsync:function(y,v){var I=x(y);I?I.getDataAsync(v):v(null,"getEntry failed for:"+y)},readAsText:function(y,v){var I=x(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(y,v,I){var A=x(y);A?A.getDataAsync(function(R,D){if(D){v(R,D);return}R&&R.length?v(R.toString(I||"utf8")):v("")}):v("")},deleteFile:function(y,v=!0){var I=x(y);I&&c.deleteFile(I.entryName,v)},deleteEntry:function(y){var v=x(y);v&&c.deleteEntry(v.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,v){var I=x(y);I&&(I.comment=v)},getZipEntryComment:function(y){var v=x(y);return v&&v.comment||""},updateFile:function(y,v){var I=x(y);I&&I.setData(v)},addLocalFile:function(y,v,I,A){if(s.fs.existsSync(y)){v=v?g(v):"";let R=Ee.win32.basename(Ee.win32.normalize(y));v+=I||R;let D=s.fs.statSync(y),E=D.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);D.isDirectory()&&(v+=s.sep),this.addFile(v,E,A,D)}else throw be.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,v){y=typeof y=="object"?y:{localPath:y};let I=Ee.resolve(y.localPath),{comment:A}=y,{zipPath:R,zipName:D}=y,E=this;s.fs.stat(I,function(C,O){if(C)return v(C,!1);R=R?g(R):"";let F=Ee.win32.basename(Ee.win32.normalize(I));if(R+=D||F,O.isFile())s.fs.readFile(I,function(B,Y){return B?v(B,!1):(E.addFile(R,Y,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return R+=s.sep,E.addFile(R,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(y,v,I){if(I=w(I),v=v?g(v):"",y=Ee.normalize(y),s.fs.existsSync(y)){let A=s.findFiles(y),R=this;if(A.length)for(let D of A){let E=Ee.join(v,S(y,D));I(E)&&R.addLocalFile(D,Ee.dirname(E))}}else throw be.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,v,I,A){A=w(A),I=I?g(I):"",y=Ee.normalize(y);var R=this;s.fs.open(y,"r",function(D){if(D&&D.code==="ENOENT")v(void 0,be.Errors.FILE_NOT_FOUND(y));else if(D)v(void 0,D);else{var E=s.findFiles(y),C=-1,O=function(){if(C+=1,C<E.length){var F=E[C],B=S(y,F).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(B)?s.fs.stat(F,function(Y,V){Y&&v(void 0,Y),V.isFile()?s.fs.readFile(F,function(re,X){re?v(void 0,re):(R.addFile(I+B,X,"",V),O())}):(R.addFile(I+B+"/",Buffer.alloc(0),"",V),O())}):process.nextTick(()=>{O()})}else v(!0,void 0)};O()}})},addLocalFolderAsync2:function(y,v){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=Ee.resolve(g(y.localPath));let{zipPath:A,filter:R,namefix:D}=y;R instanceof RegExp?R=(function(O){return function(F){return O.test(F)}})(R):typeof R!="function"&&(R=function(){return!0}),A=A?g(A):"",D=="latin1"&&(D=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=O=>O);let E=O=>Ee.join(A,D(S(localPath,O))),C=O=>Ee.win32.basename(Ee.win32.normalize(D(O)));s.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?v(void 0,be.Errors.FILE_NOT_FOUND(localPath)):O?v(void 0,O):s.findFilesAsync(localPath,function(F,B){if(F)return v(F);B=B.filter(Y=>R(E(Y))),B.length||v(void 0,!1),setImmediate(B.reverse().reduce(function(Y,V){return function(re,X){if(re||X===!1)return setImmediate(Y,re,!1);I.addLocalFileAsync({localPath:V,zipPath:Ee.dirname(E(V)),zipName:C(V)},Y)}},v))})})},addLocalFolderPromise:function(y,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},v),(R,D)=>{R&&A(R),D&&I(this)})})},addFile:function(y,v,I,A){y=h(y);let R=x(y),D=R!=null;D||(R=new Rm(i),R.entryName=y),R.comment=I||"";let E=typeof A=="object"&&A instanceof s.fs.Stats;E&&(R.header.time=A.mtime);var C=R.isDirectory?16:0;let O=R.isDirectory?16384:32768;return E?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=R.isDirectory?493:420,C=(C|O<<16)>>>0,R.attr=C,R.setData(v),D||c.setEntry(R),R},getEntries:function(y){return c.password=y,c?c.entries:[]},getEntry:function(y){return x(y)},getEntryCount:function(){return c.getEntryCount()},forEach:function(y){return c.forEach(y)},extractEntryTo:function(y,v,I,A,R,D){A=On(!1,A),R=On(!1,R),I=On(!0,I),D=xu(R,D);var E=x(y);if(!E)throw be.Errors.NO_ENTRY();var C=d(E.entryName),O=u(v,D&&!E.isDirectory?D:I?C:Ee.basename(C));if(E.isDirectory){var F=c.getEntryChildren(E);return F.forEach(function(V){if(V.isDirectory)return;var re=V.getData();if(!re)throw be.Errors.CANT_EXTRACT_FILE();var X=d(V.entryName),se=u(v,I?X:Ee.basename(X));let oe=R?V.header.fileAttr:void 0;s.writeFileTo(se,re,A,oe)}),!0}var B=E.getData(c.password);if(!B)throw be.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(O)&&!A)throw be.Errors.CANT_OVERRIDE();let Y=R?y.header.fileAttr:void 0;return s.writeFileTo(O,B,A,Y),!0},test:function(y){if(!c)return!1;for(var v in c.entries)try{if(v.isDirectory)continue;var I=c.entries[v].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,v,I,A){if(I=On(!1,I),A=xu(I,A),v=On(!1,v),!c)throw be.Errors.NO_ZIP();c.entries.forEach(function(R){var D=u(y,d(R.entryName));if(R.isDirectory){s.makeDir(D);return}var E=R.getData(A);if(!E)throw be.Errors.CANT_EXTRACT_FILE();let C=I?R.header.fileAttr:void 0;s.writeFileTo(D,E,v,C);try{s.fs.utimesSync(D,R.header.time,R.header.time)}catch{throw be.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,v,I,A){if(A=Pm(v,I,A),I=On(!1,I),v=On(!1,v),!A)return new Promise((O,F)=>{this.extractAllToAsync(y,v,I,function(B){B?F(B):O(this)})});if(!c){A(be.Errors.NO_ZIP());return}y=Ee.resolve(y);let R=O=>u(y,Ee.normalize(d(O.entryName))),D=(O,F)=>new Error(O+': "'+F+'"'),E=[],C=[];c.entries.forEach(O=>{O.isDirectory?E.push(O):C.push(O)});for(let O of E){let F=R(O),B=I?O.header.fileAttr:void 0;try{s.makeDir(F),B&&s.fs.chmodSync(F,B),s.fs.utimesSync(F,O.header.time,O.header.time)}catch{A(D("Unable to create folder",F))}}C.reverse().reduce(function(O,F){return function(B){if(B)O(B);else{let Y=Ee.normalize(d(F.entryName)),V=u(y,Y);F.getDataAsync(function(re,X){if(X)O(X);else if(!re)O(be.Errors.CANT_EXTRACT_FILE());else{let se=I?F.header.fileAttr:void 0;s.writeFileToAsync(V,re,v,se,function(oe){oe||O(D("Unable to write file",V)),s.fs.utimes(V,F.header.time,F.header.time,function(P){P?O(D("Unable to set times",V)):O()})})}})}}},A)()},writeZip:function(y,v){if(arguments.length===1&&typeof y=="function"&&(v=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=s.writeFileTo(y,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((R,D)=>{!y&&i.filename&&(y=i.filename),y||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let C=O=>O?R(O):D("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(y,E,I,A,C)},D)})},toBufferPromise:function(){return new Promise((y,v)=>{c.toAsyncBuffer(y,v)})},toBuffer:function(y,v,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,v,I,A),null):c.compressToBuffer()}}}});import{execFile as F_,spawn as z_,spawnSync as DA}from"node:child_process";import{promisify as U_}from"node:util";function q_(t){if(process.platform!=="win32")return!1;if(Mf.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(Mf,"").toLowerCase();return G_.has(n)}function Bf(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return q_(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function nt(t,e=[],n={}){return z_(t,e,Bf(t,n))}function Ff(t,e=[],n={}){return H_(t,e,Bf(t,n))}var G_,Mf,H_,Vt=Qe(()=>{"use strict";G_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Mf=/\.(cmd|bat|ps1)$/i;H_=U_(F_)});var Jt=ae((xC,Eh)=>{"use strict";var _h=["nodebuffer","arraybuffer","fragments"],yh=typeof Blob<"u";yh&&_h.push("blob");Eh.exports={BINARY_TYPES:_h,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:yh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var $i=ae((pC,To)=>{"use strict";var{EMPTY_BUFFER:Eb}=Jt(),hd=Buffer[Symbol.species];function bb(t,e){if(t.length===0)return Eb;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let s=0;s<t.length;s++){let c=t[s];n.set(c,i),i+=c.length}return i<e?new hd(n.buffer,n.byteOffset,i):n}function bh(t,e,n,i,s){for(let c=0;c<s;c++)n[i+c]=t[c]^e[c&3]}function vh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function vb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function xd(t){if(xd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new hd(t):ArrayBuffer.isView(t)?e=new hd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),xd.readOnly=!1),e}To.exports={concat:bb,mask:bh,toArrayBuffer:vb,toBuffer:xd,unmask:vh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ue("bufferutil");To.exports.mask=function(e,n,i,s,c){c<48?bh(e,n,i,s,c):t.mask(e,n,i,s,c)},To.exports.unmask=function(e,n){e.length<32?vh(e,n):t.unmask(e,n)}}catch{}});var Ah=ae((gC,Ih)=>{"use strict";var Sh=Symbol("kDone"),pd=Symbol("kRun"),gd=class{constructor(e){this[Sh]=()=>{this.pending--,this[pd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[pd]()}[pd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Sh])}}};Ih.exports=gd});var Ur=ae((mC,Ch)=>{"use strict";var Vi=ue("zlib"),kh=$i(),Sb=Ah(),{kStatusCode:Th}=Jt(),Ib=Buffer[Symbol.species],Ab=Buffer.from([0,0,255,255]),Co=Symbol("permessage-deflate"),Zt=Symbol("total-length"),Fr=Symbol("callback"),Tn=Symbol("buffers"),zr=Symbol("error"),Ro,md=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ro){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ro=new Sb(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[Fr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let s=n[i];if(s.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(s=s[0],i==="client_max_window_bits"){if(s!==!0){let c=+s;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let c=+s;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=s})}),e}decompress(e,n,i){Ro.add(s=>{this._decompress(e,n,(c,d)=>{s(),i(c,d)})})}compress(e,n,i){Ro.add(s=>{this._compress(e,n,(c,d)=>{s(),i(c,d)})})}_decompress(e,n,i){let s=this._isServer?"client":"server";if(!this._inflate){let c=`${s}_max_window_bits`,d=typeof this.params[c]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Vi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Co]=this,this._inflate[Zt]=0,this._inflate[Tn]=[],this._inflate.on("error",Tb),this._inflate.on("data",Rh)}this._inflate[Fr]=i,this._inflate.write(e),n&&this._inflate.write(Ab),this._inflate.flush(()=>{let c=this._inflate[zr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=kh.concat(this._inflate[Tn],this._inflate[Zt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Zt]=0,this._inflate[Tn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let s=this._isServer?"server":"client";if(!this._deflate){let c=`${s}_max_window_bits`,d=typeof this.params[c]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Vi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Zt]=0,this._deflate[Tn]=[],this._deflate.on("data",kb)}this._deflate[Fr]=i,this._deflate.write(e),this._deflate.flush(Vi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=kh.concat(this._deflate[Tn],this._deflate[Zt]);n&&(c=new Ib(c.buffer,c.byteOffset,c.length-4)),this._deflate[Fr]=null,this._deflate[Zt]=0,this._deflate[Tn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Ch.exports=md;function kb(t){this[Tn].push(t),this[Zt]+=t.length}function Rh(t){if(this[Zt]+=t.length,this[Co]._maxPayload<1||this[Zt]<=this[Co]._maxPayload){this[Tn].push(t);return}this[zr]=new RangeError("Max payload size exceeded"),this[zr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[zr][Th]=1009,this.removeListener("data",Rh),this.reset()}function Tb(t){if(this[Co]._inflate=null,this[zr]){this[Fr](this[zr]);return}t[Th]=1007,this[Fr](t)}});var Gr=ae((wC,Po)=>{"use strict";var{isUtf8:Ph}=ue("buffer"),{hasBlob:Rb}=Jt(),Cb=[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 Pb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function wd(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 Db(t){return Rb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Po.exports={isBlob:Db,isValidStatusCode:Pb,isValidUTF8:wd,tokenChars:Cb};if(Ph)Po.exports.isValidUTF8=function(t){return t.length<24?wd(t):Ph(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ue("utf-8-validate");Po.exports.isValidUTF8=function(e){return e.length<32?wd(e):t(e)}}catch{}});var vd=ae((_C,Fh)=>{"use strict";var{Writable:Ob}=ue("stream"),Dh=Ur(),{BINARY_TYPES:Lb,EMPTY_BUFFER:Oh,kStatusCode:Nb,kWebSocket:Mb}=Jt(),{concat:_d,toArrayBuffer:Bb,unmask:Fb}=$i(),{isValidStatusCode:zb,isValidUTF8:Lh}=Gr(),Do=Buffer[Symbol.species],ht=0,Nh=1,Mh=2,Bh=3,yd=4,Ed=5,Oo=6,bd=class extends Ob{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Lb[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[Mb]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ht}_write(e,n,i){if(this._opcode===8&&this._state==ht)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 Do(i.buffer,i.byteOffset+e,i.length-e),new Do(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],s=n.length-e;e>=i.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),s),this._buffers[0]=new Do(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 ht:this.getInfo(e);break;case Nh:this.getPayloadLength16(e);break;case Mh:this.getPayloadLength64(e);break;case Bh:this.getMask();break;case yd:this.getData(e);break;case Ed:case Oo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let i=(n[0]&64)===64;if(i&&!this._extensions[Dh.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Nh:this._payloadLength===127?this._state=Mh:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Bh:this._state=yd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=yd}getData(e){let n=Oh;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&&Fb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Ed,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[Dh.extensionName].decompress(e,this._fin,(s,c)=>{if(s)return n(s);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(d);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let d=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(d);return}this._fragments.push(c)}this.dataMessage(n),this._state===ht&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ht;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=_d(i,n):this._binaryType==="arraybuffer"?s=Bb(_d(i,n)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=ht):(this._state=Oo,setImmediate(()=>{this.emit("message",s,!0),this._state=ht,this.startLoop(e)}))}else{let s=_d(i,n);if(!this._skipUTF8Validation&&!Lh(s)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Ed||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=ht):(this._state=Oo,setImmediate(()=>{this.emit("message",s,!1),this._state=ht,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Oh),this.end();else{let i=e.readUInt16BE(0);if(!zb(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(c);return}let s=new Do(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Lh(s)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(c);return}this._loop=!1,this.emit("conclude",i,s),this.end()}this._state=ht;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ht):(this._state=Oo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ht,this.startLoop(n)}))}createError(e,n,i,s,c){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=c,d[Nb]=s,d}};Fh.exports=bd});var Ad=ae((EC,Gh)=>{"use strict";var{Duplex:yC}=ue("stream"),{randomFillSync:Ub}=ue("crypto"),{types:{isUint8Array:Gb}}=ue("util"),zh=Ur(),{EMPTY_BUFFER:qb,kWebSocket:Hb,NOOP:jb}=Jt(),{isBlob:qr,isValidStatusCode:Wb}=Gr(),{mask:Uh,toBuffer:Yn}=$i(),xt=Symbol("kByteLength"),Kb=Buffer.alloc(4),Lo=8*1024,Jn,Hr=Lo,vt=0,$b=1,Vb=2,Sd=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=vt,this.onerror=jb,this[Hb]=void 0}static frame(e,n){let i,s=!1,c=2,d=!1;n.mask&&(i=n.maskBuffer||Kb,n.generateMask?n.generateMask(i):(Hr===Lo&&(Jn===void 0&&(Jn=Buffer.alloc(Lo)),Ub(Jn,0,Lo),Hr=0),i[0]=Jn[Hr++],i[1]=Jn[Hr++],i[2]=Jn[Hr++],i[3]=Jn[Hr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!n.mask||d)&&n[xt]!==void 0?u=n[xt]:(e=Buffer.from(e),u=e.length):(u=e.length,s=n.mask&&n.readOnly&&!d);let h=u;u>=65536?(c+=8,h=127):u>125&&(c+=2,h=126);let x=Buffer.allocUnsafe(s?u+c:c);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],d?[x,e]:s?(Uh(e,i,x,c,u),[x]):(Uh(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,s){let c;if(e===void 0)c=qb;else{if(typeof e!="number"||!Wb(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(Gb(n))c.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[xt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==vt?this.enqueue([this.dispatch,c,!1,d,s]):this.sendFrame(t.frame(c,d),s)}ping(e,n,i){let s,c;if(typeof e=="string"?(s=Buffer.byteLength(e),c=!1):qr(e)?(s=e.size,c=!1):(e=Yn(e),s=e.length,c=Yn.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[xt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};qr(e)?this._state!==vt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==vt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let s,c;if(typeof e=="string"?(s=Buffer.byteLength(e),c=!1):qr(e)?(s=e.size,c=!1):(e=Yn(e),s=e.length,c=Yn.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[xt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};qr(e)?this._state!==vt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==vt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let s=this._extensions[zh.extensionName],c=n.binary?2:1,d=n.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):qr(e)?(u=e.size,h=!1):(e=Yn(e),u=e.length,h=Yn.readOnly),this._firstFragment?(this._firstFragment=!1,d&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=s._threshold),this._compress=d):(d=!1,c=0),n.fin&&(this._firstFragment=!0);let x={[xt]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:d};qr(e)?this._state!==vt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==vt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,s){this._bufferedBytes+=i[xt],this._state=Vb,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Id,this,u,s);return}this._bufferedBytes-=i[xt];let d=Yn(c);n?this.dispatch(d,n,i,s):(this._state=vt,this.sendFrame(t.frame(d,i),s),this.dequeue())}).catch(c=>{process.nextTick(Yb,this,c,s)})}dispatch(e,n,i,s){if(!n){this.sendFrame(t.frame(e,i),s);return}let c=this._extensions[zh.extensionName];this._bufferedBytes+=i[xt],this._state=$b,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");Id(this,h,s);return}this._bufferedBytes-=i[xt],this._state=vt,i.readOnly=!1,this.sendFrame(t.frame(u,i),s),this.dequeue()})}dequeue(){for(;this._state===vt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][xt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][xt],this._queue.push(e)}sendFrame(e,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)}};Gh.exports=Sd;function Id(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let s=t._queue[i],c=s[s.length-1];typeof c=="function"&&c(e)}}function Yb(t,e,n){Id(t,e,n),t.onerror(e)}});var Jh=ae((bC,Yh)=>{"use strict";var{kForOnEventAttribute:Yi,kListener:kd}=Jt(),qh=Symbol("kCode"),Hh=Symbol("kData"),jh=Symbol("kError"),Wh=Symbol("kMessage"),Kh=Symbol("kReason"),jr=Symbol("kTarget"),$h=Symbol("kType"),Vh=Symbol("kWasClean"),Xt=class{constructor(e){this[jr]=null,this[$h]=e}get target(){return this[jr]}get type(){return this[$h]}};Object.defineProperty(Xt.prototype,"target",{enumerable:!0});Object.defineProperty(Xt.prototype,"type",{enumerable:!0});var Zn=class extends Xt{constructor(e,n={}){super(e),this[qh]=n.code===void 0?0:n.code,this[Kh]=n.reason===void 0?"":n.reason,this[Vh]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[qh]}get reason(){return this[Kh]}get wasClean(){return this[Vh]}};Object.defineProperty(Zn.prototype,"code",{enumerable:!0});Object.defineProperty(Zn.prototype,"reason",{enumerable:!0});Object.defineProperty(Zn.prototype,"wasClean",{enumerable:!0});var Wr=class extends Xt{constructor(e,n={}){super(e),this[jh]=n.error===void 0?null:n.error,this[Wh]=n.message===void 0?"":n.message}get error(){return this[jh]}get message(){return this[Wh]}};Object.defineProperty(Wr.prototype,"error",{enumerable:!0});Object.defineProperty(Wr.prototype,"message",{enumerable:!0});var Ji=class extends Xt{constructor(e,n={}){super(e),this[Hh]=n.data===void 0?null:n.data}get data(){return this[Hh]}};Object.defineProperty(Ji.prototype,"data",{enumerable:!0});var Jb={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Yi]&&s[kd]===e&&!s[Yi])return;let i;if(t==="message")i=function(c,d){let u=new Ji("message",{data:d?c:c.toString()});u[jr]=this,No(e,this,u)};else if(t==="close")i=function(c,d){let u=new Zn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[jr]=this,No(e,this,u)};else if(t==="error")i=function(c){let d=new Wr("error",{error:c,message:c.message});d[jr]=this,No(e,this,d)};else if(t==="open")i=function(){let c=new Xt("open");c[jr]=this,No(e,this,c)};else return;i[Yi]=!!n[Yi],i[kd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[kd]===e&&!n[Yi]){this.removeListener(t,n);break}}};Yh.exports={CloseEvent:Zn,ErrorEvent:Wr,Event:Xt,EventTarget:Jb,MessageEvent:Ji};function No(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Mo=ae((vC,Zh)=>{"use strict";var{tokenChars:Zi}=Gr();function Mt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Zb(t){let e=Object.create(null),n=Object.create(null),i=!1,s=!1,c=!1,d,u,h=-1,x=-1,g=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(g===-1&&Zi[x]===1)h===-1&&(h=w);else if(w!==0&&(x===32||x===9))g===-1&&h!==-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let y=t.slice(h,g);x===44?(Mt(e,y,n),n=Object.create(null)):d=y,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(g===-1&&Zi[x]===1)h===-1&&(h=w);else if(x===32||x===9)g===-1&&h!==-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w),Mt(n,t.slice(h,g),!0),x===44&&(Mt(e,d,n),n=Object.create(null),d=void 0),h=g=-1}else if(x===61&&h!==-1&&g===-1)u=t.slice(h,w),h=g=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(s){if(Zi[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);h===-1?h=w:i||(i=!0),s=!1}else if(c)if(Zi[x]===1)h===-1&&(h=w);else if(x===34&&h!==-1)c=!1,g=w;else if(x===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)c=!0;else if(g===-1&&Zi[x]===1)h===-1&&(h=w);else if(h!==-1&&(x===32||x===9))g===-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let y=t.slice(h,g);i&&(y=y.replace(/\\/g,""),i=!1),Mt(n,u,y),x===44&&(Mt(e,d,n),n=Object.create(null),d=void 0),u=void 0,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=w);let S=t.slice(h,g);return d===void 0?Mt(e,S,n):(u===void 0?Mt(n,S,!0):i?Mt(n,u,S.replace(/\\/g,"")):Mt(n,u,S),Mt(e,d,n)),e}function Xb(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(s=>{let c=i[s];return Array.isArray(c)||(c=[c]),c.map(d=>d===!0?s:`${s}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Zh.exports={format:Xb,parse:Zb}});var Uo=ae((AC,dx)=>{"use strict";var Qb=ue("events"),e1=ue("https"),t1=ue("http"),ex=ue("net"),n1=ue("tls"),{randomBytes:r1,createHash:i1}=ue("crypto"),{Duplex:SC,Readable:IC}=ue("stream"),{URL:Td}=ue("url"),Rn=Ur(),s1=vd(),o1=Ad(),{isBlob:a1}=Gr(),{BINARY_TYPES:Xh,CLOSE_TIMEOUT:c1,EMPTY_BUFFER:Bo,GUID:d1,kForOnEventAttribute:Rd,kListener:l1,kStatusCode:u1,kWebSocket:qe,NOOP:tx}=Jt(),{EventTarget:{addEventListener:f1,removeEventListener:h1}}=Jh(),{format:x1,parse:p1}=Mo(),{toBuffer:g1}=$i(),nx=Symbol("kAborted"),Cd=[8,13],Qt=["CONNECTING","OPEN","CLOSING","CLOSED"],m1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends Qb{constructor(e,n,i){super(),this._binaryType=Xh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Bo,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]),rx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Xh.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let s=new s1({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 o1(e,this._extensions,i.generateMask);this._receiver=s,this._sender=c,this._socket=e,s[qe]=this,c[qe]=this,e[qe]=this,s.on("conclude",y1),s.on("drain",E1),s.on("error",b1),s.on("message",v1),s.on("ping",S1),s.on("pong",I1),c.onerror=A1,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",ox),e.on("data",zo),e.on("end",ax),e.on("error",cx),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){ot(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),sx(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){Pd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Bo,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){Pd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Bo,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){Pd(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Rn.extensionName]||(s.compress=!1),this._sender.send(e||Bo,s,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ot(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,"CONNECTING",{enumerable:!0,value:Qt.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:Qt.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:Qt.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:Qt.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:Qt.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:Qt.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:Qt.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:Qt.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[Rd])return e[l1];return null},set(e){for(let n of this.listeners(t))if(n[Rd]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Rd]:!0})}})});we.prototype.addEventListener=f1;we.prototype.removeEventListener=h1;dx.exports=we;function rx(t,e,n,i){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:c1,protocolVersion:Cd[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Cd.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Cd.join(", ")})`);let c;if(e instanceof Td)c=e;else try{c=new Td(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let d=c.protocol==="wss:",u=c.protocol==="ws+unix:",h;if(c.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?h="The URL's pathname is empty":c.hash&&(h="The URL contains a fragment identifier"),h){let I=new SyntaxError(h);if(t._redirects===0)throw I;Fo(t,I);return}let x=d?443:80,g=r1(16).toString("base64"),w=d?e1.request:t1.request,S=new Set,y;if(s.createConnection=s.createConnection||(d?_1:w1),s.defaultPort=s.defaultPort||x,s.port=c.port||x,s.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},s.path=c.pathname+c.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(y=new Rn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=x1({[Rn.extensionName]:y.offer()})),n.length){for(let I of n){if(typeof I!="string"||!m1.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(c.username||c.password)&&(s.auth=`${c.username}:${c.password}`),u){let I=s.path.split(":");s.socketPath=I[0],s.path=I[1]}let v;if(s.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?s.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,R]of Object.entries(I))i.headers[A.toLowerCase()]=R}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete s.headers.authorization,delete s.headers.cookie,I||delete s.headers.host,s.auth=void 0)}s.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),v=t._req=w(s),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=w(s);s.timeout&&v.on("timeout",()=>{ot(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[nx]||(v=t._req=null,Fo(t,I))}),v.on("response",I=>{let A=I.headers.location,R=I.statusCode;if(A&&s.followRedirects&&R>=300&&R<400){if(++t._redirects>s.maxRedirects){ot(t,v,"Maximum redirects exceeded");return}v.abort();let D;try{D=new Td(A,e)}catch{let C=new SyntaxError(`Invalid URL: ${A}`);Fo(t,C);return}rx(t,D,n,i)}else t.emit("unexpected-response",v,I)||ot(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,R)=>{if(t.emit("upgrade",I),t.readyState!==we.CONNECTING)return;v=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){ot(t,A,"Invalid Upgrade header");return}let E=i1("sha1").update(g+d1).digest("base64");if(I.headers["sec-websocket-accept"]!==E){ot(t,A,"Invalid Sec-WebSocket-Accept header");return}let C=I.headers["sec-websocket-protocol"],O;if(C!==void 0?S.size?S.has(C)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":S.size&&(O="Server sent no subprotocol"),O){ot(t,A,O);return}C&&(t._protocol=C);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!y){ot(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=p1(F)}catch{ot(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Y=Object.keys(B);if(Y.length!==1||Y[0]!==Rn.extensionName){ot(t,A,"Server indicated an extension that was not requested");return}try{y.accept(B[Rn.extensionName])}catch{ot(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Rn.extensionName]=y}t.setSocket(A,R,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(v,t):v.end()}function Fo(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function w1(t){return t.path=t.socketPath,ex.connect(t)}function _1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ex.isIP(t.host)?"":t.host),n1.connect(t)}function ot(t,e,n){t._readyState=we.CLOSING;let i=new Error(n);Error.captureStackTrace(i,ot),e.setHeader?(e[nx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Fo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Pd(t,e,n){if(e){let i=a1(e)?e.size:g1(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Qt[t.readyState]})`);process.nextTick(n,i)}}function y1(t,e){let n=this[qe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[qe]!==void 0&&(n._socket.removeListener("data",zo),process.nextTick(ix,n._socket),t===1005?n.close():n.close(t,e))}function E1(){let t=this[qe];t.isPaused||t._socket.resume()}function b1(t){let e=this[qe];e._socket[qe]!==void 0&&(e._socket.removeListener("data",zo),process.nextTick(ix,e._socket),e.close(t[u1])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Qh(){this[qe].emitClose()}function v1(t,e){this[qe].emit("message",t,e)}function S1(t){let e=this[qe];e._autoPong&&e.pong(t,!this._isServer,tx),e.emit("ping",t)}function I1(t){this[qe].emit("pong",t)}function ix(t){t.resume()}function A1(t){let e=this[qe];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,sx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function sx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ox(){let t=this[qe];if(this.removeListener("close",ox),this.removeListener("data",zo),this.removeListener("end",ax),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[qe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Qh),t._receiver.on("finish",Qh))}function zo(t){this[qe]._receiver.write(t)||this.pause()}function ax(){let t=this[qe];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function cx(){let t=this[qe];this.removeListener("error",cx),this.on("error",tx),t&&(t._readyState=we.CLOSING,this.destroy())}});var hx=ae((TC,fx)=>{"use strict";var kC=Uo(),{Duplex:k1}=ue("stream");function lx(t){t.emit("close")}function T1(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ux(t){this.removeListener("error",ux),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function R1(t,e){let n=!0,i=new k1({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,d){let u=!d&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(n=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,c){if(t.readyState===t.CLOSED){c(s),process.nextTick(lx,i);return}let d=!1;t.once("error",function(h){d=!0,c(h)}),t.once("close",function(){d||c(s),process.nextTick(lx,i)}),n&&t.terminate()},i._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(s,c,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(s,c,d)});return}t.send(s,d)},i.on("end",T1),i.on("error",ux),i}fx.exports=R1});var Dd=ae((RC,xx)=>{"use strict";var{tokenChars:C1}=Gr();function P1(t){let e=new Set,n=-1,i=-1,s=0;for(s;s<t.length;s++){let d=t.charCodeAt(s);if(i===-1&&C1[d]===1)n===-1&&(n=s);else if(s!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=s);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);i===-1&&(i=s);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(n,s);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}xx.exports={parse:P1}});var bx=ae((PC,Ex)=>{"use strict";var D1=ue("events"),Go=ue("http"),{Duplex:CC}=ue("stream"),{createHash:O1}=ue("crypto"),px=Mo(),Xn=Ur(),L1=Dd(),N1=Uo(),{CLOSE_TIMEOUT:M1,GUID:B1,kWebSocket:F1}=Jt(),z1=/^[+/0-9A-Za-z]{22}==$/,gx=0,mx=1,yx=2,Od=class extends D1{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:M1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:N1,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Go.createServer((i,s)=>{let c=Go.STATUS_CODES[426];s.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),s.end(c)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=U1(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,c,d)=>{this.handleUpgrade(s,c,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=gx}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===yx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xi,this);return}if(e&&this.once("close",e),this._state!==mx)if(this._state=mx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Xi,this):process.nextTick(Xi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Xi(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,s){n.on("error",_x);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Qn(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){Qn(this,e,n,400,"Invalid Upgrade header");return}if(c===void 0||!z1.test(c)){Qn(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Qn(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qi(n,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=L1.parse(h)}catch{Qn(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&g!==void 0){let S=new Xn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=px.parse(g);y[Xn.extensionName]&&(S.accept(y[Xn.extensionName]),w[Xn.extensionName]=S)}catch{Qn(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(S,(y,v,I,A)=>{if(!y)return Qi(n,v||401,I,A);this.completeUpgrade(w,c,x,e,n,i,s)});return}if(!this.options.verifyClient(S))return Qi(n,401)}this.completeUpgrade(w,c,x,e,n,i,s)}completeUpgrade(e,n,i,s,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[F1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>gx)return Qi(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${O1("sha1").update(n+B1).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),g._protocol=w)}if(e[Xn.extensionName]){let w=e[Xn.extensionName].params,S=px.format({[Xn.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",x,s),c.write(x.concat(`\r
8
+ var Og=Object.create;var Ca=Object.defineProperty;var Lg=Object.getOwnPropertyDescriptor;var Ng=Object.getOwnPropertyNames;var Mg=Object.getPrototypeOf,Bg=Object.prototype.hasOwnProperty;var ue=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var et=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ra=(t,e)=>{for(var r in e)Ca(t,r,{get:e[r],enumerable:!0})},Fg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ng(e))!Bg.call(t,o)&&o!==r&&Ca(t,o,{get:()=>e[o],enumerable:!(i=Lg(e,o))||i.enumerable});return t};var zt=(t,e,r)=>(r=t!=null?Og(Mg(t)):{},Fg(e||!t||!t.__esModule?Ca(r,"default",{value:t,enumerable:!0}):r,t));function Je(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ir=et(()=>{"use strict"});import{createWriteStream as zg,mkdirSync as Ug,readdirSync as Hg,unlinkSync as Gg}from"node:fs";import{join as Id}from"node:path";function Rn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function sr(t,e){return`${t}-${e}.log`}function Pa(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function qg(t,e,r){let i=c=>{let[l,u,f]=c.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>r}function fs(t,e,r,i){let o;try{o=Hg(t)}catch{return}for(let c of o){let l=Pa(c,e);if(l&&qg(l,r,i))try{Gg(Id(t,c))}catch{}}}var ei,Da=et(()=>{"use strict";ei=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Rn(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{Ug(this.dir,{recursive:!0});let r=zg(Id(this.dir,sr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
+ `)),this.stream=r}catch(r){process.stderr.write(`[log-sink] rotate failed: ${String(r)}
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&fs(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as jg,mkdirSync as Wg}from"node:fs";import{join as Kg}from"node:path";function Td(t){let e=t.retentionDays??Jg,r=t.clock??(()=>Rn(new Date));xs={bridgeSink:new ei(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ei(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();fs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])fs(t.agentLogsDir(o),"agent",i,e)}function Zg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function kd(t){Oa=t}function Cd(t){return or[Oa]<=or[t]}function Rd(t,e){let r=or[t];return r===void 0?!0:r>=or[e]}function ps(t){Ad={...t}}function Pd(t){let e=(u,f=2)=>String(u).padStart(f,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),l=e(o%60);return`${Rn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${l}`}function At(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Pd(new Date),level:e,module:r,msg:i,...o})}
11
+ `;Wg(t,{recursive:!0}),jg(Kg(t,sr("bridge",Rn(new Date))),c)}catch{}}function Yg(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function hs(t,e,r,i,o){if(or[t]<or[Oa])return;let c=`${JSON.stringify({ts:Pd(new Date),level:t,module:e,msg:r,...Ad,...i})}
12
+ `;if(xs){let l=Yg(o,i),u=l?Zg(xs,l):xs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Vg.write(c):$g.write(c)}function H(t,e){return{debug:(r,i)=>hs("debug",t,r,i,e),info:(r,i)=>hs("info",t,r,i,e),warn:(r,i)=>hs("warn",t,r,i,e),error:(r,i)=>hs("error",t,r,i,e),child:r=>H(`${t}.${r}`,e),forAgent:r=>H(t,r)}}var or,Oa,$g,Vg,Ad,Jg,xs,te=et(()=>{"use strict";ir();Da();or={debug:10,info:20,warn:30,error:40},Oa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),$g=process.stdout,Vg=process.stderr,Ad={},Jg=Je("COZE_BRIDGE_LOG_RETENTION_DAYS",30),xs=null});var T,We=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 Nd={};Ra(Nd,{ACP_WRAPPER_NPM_PACKAGES:()=>ni,_resetAcpInstallerForTests:()=>rm,_setBinaryPathCacheForTests:()=>im,buildAcpSpawn:()=>ri,ensureAcpInstalled:()=>ar,getAcpBinaryPath:()=>gs,pickWhichLine:()=>Ma,probeAcpVersion:()=>nm,resolveAcpCommand:()=>Ld});import{readFileSync as Dd}from"node:fs";import{createRequire as Xg}from"node:module";import{dirname as Qg,resolve as em}from"node:path";function Ma(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 tm(t){let e=Od.resolve(`${t.npmPackage}/package.json`),r=Qg(e),i=JSON.parse(Dd(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 em(r,o)}async function ar(t,e){let r=Na[t];if(!r)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ti.get(t);if(i)return i;try{let o=tm(r);return ti.set(t,o),La.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw La.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 nm(t){let e=Na[t];if(e)try{let r=Od.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Dd(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){La.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function gs(t){return ti.get(t)}function Ld(t,e){if(e)return e;let r=gs(t);if(!r)throw new T("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function ri(t,e,r){if(e)return{command:e,args:[...r]};let i=Ld(t);return{command:process.execPath,args:[i,...r]}}function rm(){ti.clear()}function im(t,e){ti.set(t,e)}var La,Na,ni,Od,ti,an=et(()=>{"use strict";We();te();La=H("agents.acp-installer"),Na={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ni=Object.values(Na).filter(t=>t!==void 0).map(t=>t.npmPackage),Od=Xg(import.meta.url),ti=new Map});import{chmod as om,mkdir as am,readFile as cm,rename as lm,rm as dm,writeFile as um}from"node:fs/promises";import{dirname as fm}from"node:path";async function cr(t){try{let e=await cm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function lt(t,e,r){await am(fm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await um(i,e,{encoding:"utf8",mode:r?.mode}),await lm(i,t),r?.mode!==void 0&&await om(t,r.mode)}catch(o){throw await dm(i,{force:!0}).catch(()=>{}),o}}async function lr(t,e,r){await lt(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var Ut=et(()=>{"use strict"});import{promises as Fd,readdirSync as hm}from"node:fs";import{homedir as xm}from"node:os";import{sep as pm,join as ke,resolve as zd}from"node:path";function J(t){let e=t??xm(),r=ke(e,".coze"),i=ke(r,"bridge"),o=ke(i,"lib"),c=ke(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:ke(o,"index.js"),binDir:ke(i,"bin"),pidFile:ke(i,"bridge.pid"),portFile:ke(i,"bridge.port"),tokenFile:ke(i,"bridge.token"),patTokenFile:ke(i,"pat-token"),agentEnvFile:ke(i,"agent-env.json"),logFile:ke(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:ke(c,"daemon-stdio.log"),installLock:ke(i,"install.lock"),configFile:ke(i,"config.json"),agentsRoot:ke(r,"agents")}}function Be(t,e=J()){let r=ke(e.agentsRoot,t);return{root:r,config:ke(r,"config.json"),workspace:ke(r,"workspace"),logs:ke(r,"logs")}}function ms(t=J()){try{return hm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ii(t,e){let r=await Fd.realpath(zd(t)).catch(()=>null);if(!r)return!1;let i=await Fd.realpath(zd(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+pm)}var Ce=et(()=>{"use strict"});var _s={};Ra(_s,{AGENT_CONFIG_FILE_MODE:()=>ws,enforceAgentConfigMode:()=>wm,loadAgentConfig:()=>Ee,persistAgentSessions:()=>si,persistAgentSkills:()=>oi,saveAgentConfig:()=>Fe});import{chmod as gm,stat as mm}from"node:fs/promises";function Ee(t,e){return cr(Be(t,e).config)}function Fe(t,e){return lr(Be(t.agentId,e).config,t,{mode:ws})}async function wm(t,e){if(process.platform==="win32")return;let r=Be(t,e).config;try{let i=await mm(r);if(!i.isFile())return;let o=i.mode&511;o!==ws&&(await gm(r,ws),Ud.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Ud.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function si(t,e,r){let i=await Ee(t,r);i&&(i.sessions=Object.fromEntries(e),await Fe(i,r))}async function oi(t,e,r){let i=await Ee(t,r);i&&(i.skills=e,await Fe(i,r))}var Ud,ws,Ht=et(()=>{"use strict";Ut();te();Ce();Ud=H("agent-config"),ws=384});var za=ae((d2,qd)=>{qd.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var bs=ae(Wd=>{var jd={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 Sm(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(jd))Wd[t]=Sm(jd[t])});var Zd=ae((f2,Jd)=>{var Im=ue("fs"),Le=ue("path"),Kd=za(),Am=bs(),Tm=typeof process=="object"&&process.platform==="win32",$d=t=>typeof t=="object"&&t!==null,Vd=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 ve(t){this.sep=Le.sep,this.fs=Im,$d(t)&&$d(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Jd.exports=ve;ve.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var l;try{l=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(l&&l.isFile())throw Am.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};ve.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var l=Le.dirname(t);o.fs.existsSync(l)||o.makeDir(l);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};ve.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(l){if(l&&!r)return o(!1);c.fs.stat(t,function(u,f){if(l&&f.isDirectory())return o(!1);var x=Le.dirname(t);c.fs.exists(x,function(p){p||c.makeDir(x),c.fs.open(t,"w",438,function(m,v){m?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,b){c.fs.write(b,e,0,e.length,0,function(){c.fs.close(b,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):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)})})})})})};ve.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let l=[];return e.fs.readdirSync(i).forEach(function(u){let f=Le.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&l.push(Le.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(l=l.concat(r(f,o,c)))}),l}return r(t,void 0,!0)};ve.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let l=c.length;if(!l)return e(null,i);c.forEach(function(u){u=Le.join(t,u),r.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Le.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(p,m){if(p)return e(p);i=i.concat(m),--l||e(null,i)}):--l||e(null,i))})})})};ve.prototype.getAttributes=function(){};ve.prototype.setAttributes=function(){};ve.crc32update=function(t,e){return Vd[(t^e)&255]^t>>>8};ve.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=ve.crc32update(r,t[i++]);return~r>>>0};ve.methodToString=function(t){switch(t){case Kd.STORED:return"STORED ("+t+")";case Kd.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ve.canonical=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.join(".",e)};ve.zipnamefix=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.posix.join(".",e)};ve.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]};ve.sanitize=function(t,e){t=Le.resolve(Le.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Le.normalize(Le.join(t,r.slice(i,o).join(Le.sep)));if(c.indexOf(t)===0)return c}return Le.normalize(Le.join(t,Le.basename(e)))};ve.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};ve.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};ve.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)};ve.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};ve.isWin=Tm;ve.crcTable=Vd});var Xd=ae((h2,Yd)=>{var km=ue("path");Yd.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=km.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 eu=ae((x2,Qd)=>{Qd.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var fr=ae((p2,ur)=>{ur.exports=Zd();ur.exports.Constants=za();ur.exports.Errors=bs();ur.exports.FileAttr=Xd();ur.exports.decoder=eu()});var nu=ae((g2,tu)=>{var cn=fr(),z=cn.Constants;tu.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,l=0,u=0,f=0,x=0,p=0,m=0,v=0,_=0,b=0;t|=cn.isWin?2560:768,r|=z.FLG_EFS;let I={extraLen:0},A=y=>Math.max(0,y)>>>0,k=y=>Math.max(0,y)&65535,P=y=>Math.max(0,y)&255;return o=cn.fromDate2DOS(new Date),{get made(){return t},set made(y){t=y},get version(){return e},set version(y){e=y},get flags(){return r},set flags(y){r=y},get flags_efs(){return(r&z.FLG_EFS)>0},set flags_efs(y){y?r|=z.FLG_EFS:r&=~z.FLG_EFS},get flags_desc(){return(r&z.FLG_DESC)>0},set flags_desc(y){y?r|=z.FLG_DESC:r&=~z.FLG_DESC},get method(){return i},set method(y){switch(y){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=y},get time(){return cn.fromDOS2Date(this.timeval)},set time(y){y=new Date(y),this.timeval=cn.fromDate2DOS(y)},get timeval(){return o},set timeval(y){o=A(y)},get timeHighByte(){return P(o>>>8)},get crc(){return c},set crc(y){c=A(y)},get compressedSize(){return l},set compressedSize(y){l=A(y)},get size(){return u},set size(y){u=A(y)},get fileNameLength(){return f},set fileNameLength(y){f=y},get extraLength(){return x},set extraLength(y){x=y},get extraLocalLength(){return I.extraLen},set extraLocalLength(y){I.extraLen=y},get commentLength(){return p},set commentLength(y){p=y},get diskNumStart(){return m},set diskNumStart(y){m=A(y)},get inAttr(){return v},set inAttr(y){v=A(y)},get attr(){return _},set attr(y){_=A(y)},get fileAttr(){return(_||0)>>16&4095},get offset(){return b},set offset(y){b=A(y)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+f+x+p},get realDataOffset(){return b+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(y){var R=y.slice(b,b+z.LOCHDR);if(R.readUInt32LE(0)!==z.LOCSIG)throw cn.Errors.INVALID_LOC();I.version=R.readUInt16LE(z.LOCVER),I.flags=R.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=R.readUInt16LE(z.LOCHOW),I.time=R.readUInt32LE(z.LOCTIM),I.crc=R.readUInt32LE(z.LOCCRC),I.compressedSize=R.readUInt32LE(z.LOCSIZ),I.size=R.readUInt32LE(z.LOCLEN),I.fnameLen=R.readUInt16LE(z.LOCNAM),I.extraLen=R.readUInt16LE(z.LOCEXT);let O=b+z.LOCHDR+I.fnameLen,F=O+I.extraLen;return y.slice(O,F)},loadFromBinary:function(y){if(y.length!==z.CENHDR||y.readUInt32LE(0)!==z.CENSIG)throw cn.Errors.INVALID_CEN();t=y.readUInt16LE(z.CENVEM),e=y.readUInt16LE(z.CENVER),r=y.readUInt16LE(z.CENFLG),i=y.readUInt16LE(z.CENHOW),o=y.readUInt32LE(z.CENTIM),c=y.readUInt32LE(z.CENCRC),l=y.readUInt32LE(z.CENSIZ),u=y.readUInt32LE(z.CENLEN),f=y.readUInt16LE(z.CENNAM),x=y.readUInt16LE(z.CENEXT),p=y.readUInt16LE(z.CENCOM),m=y.readUInt16LE(z.CENDSK),v=y.readUInt16LE(z.CENATT),_=y.readUInt32LE(z.CENATX),b=y.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var y=Buffer.alloc(z.LOCHDR);return y.writeUInt32LE(z.LOCSIG,0),y.writeUInt16LE(e,z.LOCVER),y.writeUInt16LE(r,z.LOCFLG),y.writeUInt16LE(i,z.LOCHOW),y.writeUInt32LE(o,z.LOCTIM),y.writeUInt32LE(c,z.LOCCRC),y.writeUInt32LE(l,z.LOCSIZ),y.writeUInt32LE(u,z.LOCLEN),y.writeUInt16LE(f,z.LOCNAM),y.writeUInt16LE(I.extraLen,z.LOCEXT),y},centralHeaderToBinary:function(){var y=Buffer.alloc(z.CENHDR+f+x+p);return y.writeUInt32LE(z.CENSIG,0),y.writeUInt16LE(t,z.CENVEM),y.writeUInt16LE(e,z.CENVER),y.writeUInt16LE(r,z.CENFLG),y.writeUInt16LE(i,z.CENHOW),y.writeUInt32LE(o,z.CENTIM),y.writeUInt32LE(c,z.CENCRC),y.writeUInt32LE(l,z.CENSIZ),y.writeUInt32LE(u,z.CENLEN),y.writeUInt16LE(f,z.CENNAM),y.writeUInt16LE(x,z.CENEXT),y.writeUInt16LE(p,z.CENCOM),y.writeUInt16LE(m,z.CENDSK),y.writeUInt16LE(v,z.CENATT),y.writeUInt32LE(_,z.CENATX),y.writeUInt32LE(b,z.CENOFF),y},toJSON:function(){let y=function(R){return R+" bytes"};return{made:t,version:e,flags:r,method:cn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:y(l),size:y(u),fileNameLength:y(f),extraLength:y(x),commentLength:y(p),diskNumStart:m,inAttr:v,attr:_,offset:b,centralHeaderSize:y(z.CENHDR+f+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var iu=ae((m2,ru)=>{var hr=fr(),_e=hr.Constants;ru.exports=function(){var t=0,e=0,r=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return r},set size(c){r=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return _e.ENDHDR+o},loadFromBinary:function(c){if((c.length!==_e.ENDHDR||c.readUInt32LE(0)!==_e.ENDSIG)&&(c.length<_e.ZIP64HDR||c.readUInt32LE(0)!==_e.ZIP64SIG))throw hr.Errors.INVALID_END();c.readUInt32LE(0)===_e.ENDSIG?(t=c.readUInt16LE(_e.ENDSUB),e=c.readUInt16LE(_e.ENDTOT),r=c.readUInt32LE(_e.ENDSIZ),i=c.readUInt32LE(_e.ENDOFF),o=c.readUInt16LE(_e.ENDCOM)):(t=hr.readBigUInt64LE(c,_e.ZIP64SUB),e=hr.readBigUInt64LE(c,_e.ZIP64TOT),r=hr.readBigUInt64LE(c,_e.ZIP64SIZE),i=hr.readBigUInt64LE(c,_e.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(_e.ENDHDR+o);return c.writeUInt32LE(_e.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,_e.ENDSUB),c.writeUInt16LE(e,_e.ENDTOT),c.writeUInt32LE(r,_e.ENDSIZ),c.writeUInt32LE(i,_e.ENDOFF),c.writeUInt16LE(o,_e.ENDCOM),c.fill(" ",_e.ENDHDR),c},toJSON:function(){let c=function(l,u){let f=l.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ha=ae(Ua=>{Ua.EntryHeader=nu();Ua.MainHeader=iu()});var ou=ae((_2,su)=>{su.exports=function(t){var e=ue("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],l=0;o.on("data",function(u){c.push(u),l+=u.length}),o.on("end",function(){var u=Buffer.alloc(l),f=0;u.fill(0);for(var x=0;x<c.length;x++){var p=c[x];p.copy(u,f),f+=p.length}i&&i(u)}),o.end(t)}}}});var cu=ae((y2,au)=>{var Cm=+(process.versions?process.versions.node:"").split(".")[0]||0;au.exports=function(t,e){var r=ue("zlib");let i=Cm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),l=[],u=0;c.on("data",function(f){l.push(f),u+=f.length}),c.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var p=0;p<l.length;p++){var m=l[p];m.copy(f,x),x+=m.length}o&&o(f)}),c.end(t)}}}});var hu=ae((b2,fu)=>{"use strict";var{randomFillSync:lu}=ue("crypto"),Rm=bs(),Pm=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),uu=(t,e)=>Math.imul(t,e)>>>0,du=(t,e)=>Pm[(t^e)&255]^t>>>8,ai=()=>typeof lu=="function"?lu(Buffer.alloc(12)):ai.node();ai.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var Es={genSalt:ai};function vs(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}vs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=du(e[0],t),e[1]+=e[0]&255,e[1]=uu(e[1],134775813)+1,e[2]=du(e[2],e[1]>>>24),t};vs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return uu(t,t^1)>>8&255};function Dm(t){let e=new vs(t);return function(r){let i=Buffer.alloc(r.length),o=0;for(let c of r)i[o++]=e.updateKeys(c^e.next());return i}}function Om(t){let e=new vs(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let l=e.next();i[o++]=c^l,e.updateKeys(c)}return i}}function Lm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Dm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Rm.WRONG_PASSWORD();return i(t.slice(12))}function Nm(t){Buffer.isBuffer(t)&&t.length>=12?Es.genSalt=function(){return t.slice(0,12)}:t==="node"?Es.genSalt=ai.node:Es.genSalt=ai}function Mm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Om(r),c=Es.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)}fu.exports={decrypt:Lm,encrypt:Mm,_salter:Nm}});var xu=ae(Ss=>{Ss.Deflater=ou();Ss.Inflater=cu();Ss.ZipCrypto=hu()});var qa=ae((v2,pu)=>{var ce=fr(),Bm=Ha(),Se=ce.Constants,Ga=xu();pu.exports=function(t,e){var r=new Bm.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,l=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let p=t,m=typeof p.decoder=="object"?p.decoder:ce.decoder;x=m.hasOwnProperty("efs")?m.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function _(y){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(y)!==r.localHeader.crc)return!1}else{let R={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==Se.LOCSIG||e.readUInt32LE(O)==Se.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Se.EXTSIG)R.crc=e.readUInt32LE(O+Se.EXTCRC),R.compressedSize=e.readUInt32LE(O+Se.EXTSIZ),R.size=e.readUInt32LE(O+Se.EXTLEN);else if(e.readUInt16LE(O+12)===19280)R.crc=e.readUInt32LE(O+Se.EXTCRC-4),R.compressedSize=e.readUInt32LE(O+Se.EXTSIZ-4),R.size=e.readUInt32LE(O+Se.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==r.compressedSize||R.size!==r.size||R.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(y)!==R.crc)return!1}return!0}function b(y,R,O){if(typeof R>"u"&&typeof y=="string"&&(O=y,y=void 0),c)return y&&R&&R(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=v();if(F.length===0)return y&&R&&R(F),F;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ce.Errors.INVALID_PASS_PARAM();F=Ga.ZipCrypto.decrypt(F,r,O)}var M=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(F.copy(M),_(M))return y&&R&&R(M),M;throw y&&R&&R(M,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var V=new Ga.Inflater(F,r.size);if(y)V.inflateAsync(function($){$.copy($,0),R&&(_($)?R($):R($,ce.Errors.BAD_CRC()))});else{if(V.inflate(M).copy(M,0),!_(M))throw ce.Errors.BAD_CRC(`"${m.decode(i)}"`);return M}break;default:throw y&&R&&R(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(y,R){if((!l||!l.length)&&Buffer.isBuffer(e))return y&&R&&R(v()),v();if(l.length&&!c){var O;switch(r.method){case ce.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(l.length),l.copy(O),y&&R&&R(O),O;default:case ce.Constants.DEFLATED:var F=new Ga.Deflater(l);if(y)F.deflateAsync(function(V){O=Buffer.alloc(V.length),r.compressedSize=V.length,V.copy(O),R&&R(O)});else{var M=F.deflate();return r.compressedSize=M.length,M}F=null;break}}else if(y&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(y,R){return ce.readBigUInt64LE(y,R)}function k(y){try{for(var R=0,O,F,M;R+4<y.length;)O=y.readUInt16LE(R),R+=2,F=y.readUInt16LE(R),R+=2,M=y.slice(R,R+F),R+=F,Se.ID_ZIP64===O&&P(M)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(y){var R,O,F,M;y.length>=Se.EF_ZIP64_SCOMP&&(R=A(y,Se.EF_ZIP64_SUNCOMP),r.size===Se.EF_ZIP64_OR_32&&(r.size=R)),y.length>=Se.EF_ZIP64_RHO&&(O=A(y,Se.EF_ZIP64_SCOMP),r.compressedSize===Se.EF_ZIP64_OR_32&&(r.compressedSize=O)),y.length>=Se.EF_ZIP64_DSN&&(F=A(y,Se.EF_ZIP64_RHO),r.offset===Se.EF_ZIP64_OR_32&&(r.offset=F)),y.length>=Se.EF_ZIP64_DSN+4&&(M=y.readUInt32LE(Se.EF_ZIP64_DSN),r.diskNumStart===Se.EF_ZIP64_OR_16&&(r.diskNumStart=M))}return{get entryName(){return m.decode(i)},get rawEntryName(){return i},set entryName(y){i=ce.toBuffer(y,m.encode);var R=i[i.length-1];c=R===47||R===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(y){u=y,r.extraLength=y.length,k(y)},get comment(){return m.decode(o)},set comment(y){if(o=ce.toBuffer(y,m.encode),r.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var y=m.decode(i);return c?y.substr(y.length-1).split("/").pop():y.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(y){I(!0,y)},setData:function(y){l=ce.toBuffer(y,ce.decoder.encode),!c&&l.length?(r.size=l.length,r.method=ce.Constants.DEFLATED,r.crc=ce.crc32(y),r.changed=!0):r.method=ce.Constants.STORED},getData:function(y){return r.changed?l:b(!1,null,y)},getDataAsync:function(y,R){r.changed?y(l):b(!0,y,R)},set attr(y){r.attr=y},get attr(){return r.attr},set header(y){r.loadFromBinary(y)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var y=r.centralHeaderToBinary(),R=ce.Constants.CENHDR;return i.copy(y,R),R+=i.length,u.copy(y,R),R+=r.extraLength,o.copy(y,R),y},packLocalHeader:function(){let y=0;r.flags_efs=this.efs,r.extraLocalLength=f.length;let R=r.localHeaderToBinary(),O=Buffer.alloc(R.length+i.length+r.extraLocalLength);return R.copy(O,y),y+=R.length,i.copy(O,y),y+=i.length,f.copy(O,y),y+=f.length,O},toJSON:function(){let y=function(R){return"<"+(R&&R.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:y(e),data:y(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var wu=ae((S2,mu)=>{var gu=qa(),Fm=Ha(),Ke=fr();mu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Fm.MainHeader,l=!1,u=null;let f=new Set,x=e,{noSort:p,decoder:m}=x;t?b(x.readEntries):l=!0;function v(){let A=new Set;for(let k of Object.keys(i)){let P=k.split("/");if(P.pop(),!!P.length)for(let y=0;y<P.length;y++){let R=P.slice(0,y+1).join("/")+"/";A.add(R)}}for(let k of A)if(!(k in i)){let P=new gu(x);P.entryName=k,P.attr=16,P.temporary=!0,r.push(P),i[P.entryName]=P,f.add(P)}}function _(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/Ke.Constants.CENHDR)throw Ke.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,k=0;k<r.length;k++){var P=A,y=new gu(x,t);y.header=t.slice(P,P+=Ke.Constants.CENHDR),y.entryName=t.slice(P,P+=y.header.fileNameLength),y.header.extraLength&&(y.extra=t.slice(P,P+=y.header.extraLength)),y.header.commentLength&&(y.comment=t.slice(P,P+y.header.commentLength)),A+=y.header.centralHeaderSize,r[k]=y,i[y.entryName]=y}f.clear(),v()}function b(A){var k=t.length-Ke.Constants.ENDHDR,P=Math.max(0,k-65535),y=P,R=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),k;k>=y;k--)if(t[k]===80){if(t.readUInt32LE(k)===Ke.Constants.ENDSIG){O=k,F=k,R=k+Ke.Constants.ENDHDR,y=k-Ke.Constants.END64HDR;continue}if(t.readUInt32LE(k)===Ke.Constants.END64SIG){y=P;continue}if(t.readUInt32LE(k)===Ke.Constants.ZIP64SIG){O=k,R=k+Ke.readBigUInt64LE(t,k+Ke.Constants.ZIP64SIZE)+Ke.Constants.ZIP64LEAD;break}}if(O==-1)throw Ke.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,R)),c.commentLength&&(o=t.slice(F+Ke.Constants.ENDHDR)),A&&_()}function I(){r.length>1&&!p&&r.sort((A,k)=>A.entryName.toLowerCase().localeCompare(k.entryName.toLowerCase()))}return{get entries(){return l||_(),r.filter(A=>!f.has(A))},get comment(){return m.decode(o)},set comment(A){o=Ke.toBuffer(A,m.encode),c.commentLength=o.length},getEntryCount:function(){return l?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return l||_(),i[A]||null},setEntry:function(A){l||_(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,k=!0){l||_();let P=i[A];this.getEntryChildren(P,k).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||_();let k=i[A],P=r.indexOf(k);P>=0&&(r.splice(P,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,k=!0){if(l||_(),typeof A=="object")if(A.isDirectory&&k){let P=[],y=A.entryName;for(let R of r)R.entryName.startsWith(y)&&P.push(R);return P}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let k=this.getEntryChildren(A);return k.includes(A)?k.length-1:k.length}return 0},compressToBuffer:function(){l||_(),I();let A=[],k=[],P=0,y=0;c.size=0,c.offset=0;let R=0;for(let M of this.entries){let V=M.getCompressedData();M.header.offset=y;let $=M.packLocalHeader(),ne=$.length+V.length;y+=ne,A.push($),A.push(V);let Y=M.packCentralHeader();k.push(Y),c.size+=Y.length,P+=ne+Y.length,R++}P+=c.mainHeaderSize,c.offset=y,c.totalEntries=R,y=0;let O=Buffer.alloc(P);for(let M of A)M.copy(O,y),y+=M.length;for(let M of k)M.copy(O,y),y+=M.length;let F=c.toBinary();return o&&o.copy(F,Ke.Constants.ENDHDR),F.copy(O,y),t=O,l=!1,O},toAsyncBuffer:function(A,k,P,y){try{l||_(),I();let R=[],O=[],F=0,M=0,V=0;c.size=0,c.offset=0;let $=function(ne){if(ne.length>0){let Y=ne.shift(),se=Y.entryName+Y.extra.toString();P&&P(se),Y.getCompressedDataAsync(function(oe){y&&y(se),Y.header.offset=M;let C=Y.packLocalHeader(),U=C.length+oe.length;M+=U,R.push(C),R.push(oe);let G=Y.packCentralHeader();O.push(G),c.size+=G.length,F+=U+G.length,V++,$(ne)})}else{F+=c.mainHeaderSize,c.offset=M,c.totalEntries=V,M=0;let Y=Buffer.alloc(F);R.forEach(function(oe){oe.copy(Y,M),M+=oe.length}),O.forEach(function(oe){oe.copy(Y,M),M+=oe.length});let se=c.toBinary();o&&o.copy(se,Ke.Constants.ENDHDR),se.copy(Y,M),t=Y,l=!1,A(Y)}};$(Array.from(this.entries))}catch(R){k(R)}}}}});var bu=ae((I2,yu)=>{var be=fr(),ye=ue("path"),zm=qa(),Um=wu(),Pn=(...t)=>be.findLast(t,e=>typeof e=="boolean"),_u=(...t)=>be.findLast(t,e=>typeof e=="string"),Hm=(...t)=>be.findLast(t,e=>typeof e=="function"),Gm={noSort:!1,readEntries:!1,method:be.Constants.NONE,fs:null};yu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Gm);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=be.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new be(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=be.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=be.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw be.Errors.INVALID_FILENAME();let c=new Um(r,i),{canonical:l,sanitize:u,zipnamefix:f}=be;function x(_){if(_&&c){var b;if(typeof _=="string"&&(b=c.getEntry(ye.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(b=c.getEntry(_.entryName)),b)return b}return null}function p(_){let{join:b,normalize:I,sep:A}=ye.posix;return b(ye.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function m(_){return _ instanceof RegExp?(function(b){return function(I){return b.test(I)}})(_):typeof _!="function"?()=>!0:_}let v=(_,b)=>{let I=b.slice(-1);return I=I===o.sep?o.sep:"",ye.relative(_,b)+I};return{readFile:function(_,b){var I=x(_);return I&&I.getData(b)||null},childCount:function(_){let b=x(_);if(b)return c.getChildCount(b)},readFileAsync:function(_,b){var I=x(_);I?I.getDataAsync(b):b(null,"getEntry failed for:"+_)},readAsText:function(_,b){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(b||"utf8")}return""},readAsTextAsync:function(_,b,I){var A=x(_);A?A.getDataAsync(function(k,P){if(P){b(k,P);return}k&&k.length?b(k.toString(I||"utf8")):b("")}):b("")},deleteFile:function(_,b=!0){var I=x(_);I&&c.deleteFile(I.entryName,b)},deleteEntry:function(_){var b=x(_);b&&c.deleteEntry(b.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,b){var I=x(_);I&&(I.comment=b)},getZipEntryComment:function(_){var b=x(_);return b&&b.comment||""},updateFile:function(_,b){var I=x(_);I&&I.setData(b)},addLocalFile:function(_,b,I,A){if(o.fs.existsSync(_)){b=b?p(b):"";let k=ye.win32.basename(ye.win32.normalize(_));b+=I||k;let P=o.fs.statSync(_),y=P.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);P.isDirectory()&&(b+=o.sep),this.addFile(b,y,A,P)}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,b){_=typeof _=="object"?_:{localPath:_};let I=ye.resolve(_.localPath),{comment:A}=_,{zipPath:k,zipName:P}=_,y=this;o.fs.stat(I,function(R,O){if(R)return b(R,!1);k=k?p(k):"";let F=ye.win32.basename(ye.win32.normalize(I));if(k+=P||F,O.isFile())o.fs.readFile(I,function(M,V){return M?b(M,!1):(y.addFile(k,V,A,O),setImmediate(b,void 0,!0))});else if(O.isDirectory())return k+=o.sep,y.addFile(k,Buffer.alloc(0),A,O),setImmediate(b,void 0,!0)})},addLocalFolder:function(_,b,I){if(I=m(I),b=b?p(b):"",_=ye.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),k=this;if(A.length)for(let P of A){let y=ye.join(b,v(_,P));I(y)&&k.addLocalFile(P,ye.dirname(y))}}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,b,I,A){A=m(A),I=I?p(I):"",_=ye.normalize(_);var k=this;o.fs.open(_,"r",function(P){if(P&&P.code==="ENOENT")b(void 0,be.Errors.FILE_NOT_FOUND(_));else if(P)b(void 0,P);else{var y=o.findFiles(_),R=-1,O=function(){if(R+=1,R<y.length){var F=y[R],M=v(_,F).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?o.fs.stat(F,function(V,$){V&&b(void 0,V),$.isFile()?o.fs.readFile(F,function(ne,Y){ne?b(void 0,ne):(k.addFile(I+M,Y,"",$),O())}):(k.addFile(I+M+"/",Buffer.alloc(0),"",$),O())}):process.nextTick(()=>{O()})}else b(!0,void 0)};O()}})},addLocalFolderAsync2:function(_,b){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=ye.resolve(p(_.localPath));let{zipPath:A,filter:k,namefix:P}=_;k instanceof RegExp?k=(function(O){return function(F){return O.test(F)}})(k):typeof k!="function"&&(k=function(){return!0}),A=A?p(A):"",P=="latin1"&&(P=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=O=>O);let y=O=>ye.join(A,P(v(localPath,O))),R=O=>ye.win32.basename(ye.win32.normalize(P(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?b(void 0,be.Errors.FILE_NOT_FOUND(localPath)):O?b(void 0,O):o.findFilesAsync(localPath,function(F,M){if(F)return b(F);M=M.filter(V=>k(y(V))),M.length||b(void 0,!1),setImmediate(M.reverse().reduce(function(V,$){return function(ne,Y){if(ne||Y===!1)return setImmediate(V,ne,!1);I.addLocalFileAsync({localPath:$,zipPath:ye.dirname(y($)),zipName:R($)},V)}},b))})})},addLocalFolderPromise:function(_,b){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},b),(k,P)=>{k&&A(k),P&&I(this)})})},addFile:function(_,b,I,A){_=f(_);let k=x(_),P=k!=null;P||(k=new zm(i),k.entryName=_),k.comment=I||"";let y=typeof A=="object"&&A instanceof o.fs.Stats;y&&(k.header.time=A.mtime);var R=k.isDirectory?16:0;let O=k.isDirectory?16384:32768;return y?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=k.isDirectory?493:420,R=(R|O<<16)>>>0,k.attr=R,k.setData(b),P||c.setEntry(k),k},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,b,I,A,k,P){A=Pn(!1,A),k=Pn(!1,k),I=Pn(!0,I),P=_u(k,P);var y=x(_);if(!y)throw be.Errors.NO_ENTRY();var R=l(y.entryName),O=u(b,P&&!y.isDirectory?P:I?R:ye.basename(R));if(y.isDirectory){var F=c.getEntryChildren(y);return F.forEach(function($){if($.isDirectory)return;var ne=$.getData();if(!ne)throw be.Errors.CANT_EXTRACT_FILE();var Y=l($.entryName),se=u(b,I?Y:ye.basename(Y));let oe=k?$.header.fileAttr:void 0;o.writeFileTo(se,ne,A,oe)}),!0}var M=y.getData(c.password);if(!M)throw be.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw be.Errors.CANT_OVERRIDE();let V=k?_.header.fileAttr:void 0;return o.writeFileTo(O,M,A,V),!0},test:function(_){if(!c)return!1;for(var b in c.entries)try{if(b.isDirectory)continue;var I=c.entries[b].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,b,I,A){if(I=Pn(!1,I),A=_u(I,A),b=Pn(!1,b),!c)throw be.Errors.NO_ZIP();c.entries.forEach(function(k){var P=u(_,l(k.entryName));if(k.isDirectory){o.makeDir(P);return}var y=k.getData(A);if(!y)throw be.Errors.CANT_EXTRACT_FILE();let R=I?k.header.fileAttr:void 0;o.writeFileTo(P,y,b,R);try{o.fs.utimesSync(P,k.header.time,k.header.time)}catch{throw be.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,b,I,A){if(A=Hm(b,I,A),I=Pn(!1,I),b=Pn(!1,b),!A)return new Promise((O,F)=>{this.extractAllToAsync(_,b,I,function(M){M?F(M):O(this)})});if(!c){A(be.Errors.NO_ZIP());return}_=ye.resolve(_);let k=O=>u(_,ye.normalize(l(O.entryName))),P=(O,F)=>new Error(O+': "'+F+'"'),y=[],R=[];c.entries.forEach(O=>{O.isDirectory?y.push(O):R.push(O)});for(let O of y){let F=k(O),M=I?O.header.fileAttr:void 0;try{o.makeDir(F),M&&o.fs.chmodSync(F,M),o.fs.utimesSync(F,O.header.time,O.header.time)}catch{A(P("Unable to create folder",F))}}R.reverse().reduce(function(O,F){return function(M){if(M)O(M);else{let V=ye.normalize(l(F.entryName)),$=u(_,V);F.getDataAsync(function(ne,Y){if(Y)O(Y);else if(!ne)O(be.Errors.CANT_EXTRACT_FILE());else{let se=I?F.header.fileAttr:void 0;o.writeFileToAsync($,ne,b,se,function(oe){oe||O(P("Unable to write file",$)),o.fs.utimes($,F.header.time,F.header.time,function(C){C?O(P("Unable to set times",$)):O()})})}})}}},A)()},writeZip:function(_,b){if(arguments.length===1&&typeof _=="function"&&(b=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof b=="function"&&b(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,b){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},b);return new Promise((k,P)=>{!_&&i.filename&&(_=i.filename),_||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(y=>{let R=O=>O?k(O):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,y,I,A,R)},P)})},toBufferPromise:function(){return new Promise((_,b)=>{c.toAsyncBuffer(_,b)})},toBuffer:function(_,b,I,A){return typeof _=="function"?(c.toAsyncBuffer(_,b,I,A),null):c.compressToBuffer()}}}});import{execFile as V_,spawn as J_,spawnSync as qA}from"node:child_process";import{promisify as Z_}from"node:util";function X_(t){if(process.platform!=="win32")return!1;if(Hf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Hf,"").toLowerCase();return Y_.has(r)}function Gf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return X_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function rt(t,e=[],r={}){return J_(t,e,Gf(t,r))}function qf(t,e=[],r={}){return Q_(t,e,Gf(t,r))}var Y_,Hf,Q_,Vt=et(()=>{"use strict";Y_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Hf=/\.(cmd|bat|ps1)$/i;Q_=Z_(V_)});var Zt=ae((VR,Lh)=>{"use strict";var Dh=["nodebuffer","arraybuffer","fragments"],Oh=typeof Blob<"u";Oh&&Dh.push("blob");Lh.exports={BINARY_TYPES:Dh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Oh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Xi=ae((JR,Lo)=>{"use strict";var{EMPTY_BUFFER:LE}=Zt(),_l=Buffer[Symbol.species];function NE(t,e){if(t.length===0)return LE;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 _l(r.buffer,r.byteOffset,i):r}function Nh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Mh(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function ME(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function yl(t){if(yl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new _l(t):ArrayBuffer.isView(t)?e=new _l(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),yl.readOnly=!1),e}Lo.exports={concat:NE,mask:Nh,toArrayBuffer:ME,toBuffer:yl,unmask:Mh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ue("bufferutil");Lo.exports.mask=function(e,r,i,o,c){c<48?Nh(e,r,i,o,c):t.mask(e,r,i,o,c)},Lo.exports.unmask=function(e,r){e.length<32?Mh(e,r):t.unmask(e,r)}}catch{}});var zh=ae((ZR,Fh)=>{"use strict";var Bh=Symbol("kDone"),bl=Symbol("kRun"),El=class{constructor(e){this[Bh]=()=>{this.pending--,this[bl]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[bl]()}[bl](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Bh])}}};Fh.exports=El});var Ur=ae((YR,qh)=>{"use strict";var Qi=ue("zlib"),Uh=Xi(),BE=zh(),{kStatusCode:Hh}=Zt(),FE=Buffer[Symbol.species],zE=Buffer.from([0,0,255,255]),Mo=Symbol("permessage-deflate"),Yt=Symbol("total-length"),Fr=Symbol("callback"),An=Symbol("buffers"),zr=Symbol("error"),No,vl=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,!No){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;No=new BE(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Fr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let o=r[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){No.add(o=>{this._decompress(e,r,(c,l)=>{o(),i(c,l)})})}compress(e,r,i){No.add(o=>{this._compress(e,r,(c,l)=>{o(),i(c,l)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?Qi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Qi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[Mo]=this,this._inflate[Yt]=0,this._inflate[An]=[],this._inflate.on("error",HE),this._inflate.on("data",Gh)}this._inflate[Fr]=i,this._inflate.write(e),r&&this._inflate.write(zE),this._inflate.flush(()=>{let c=this._inflate[zr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=Uh.concat(this._inflate[An],this._inflate[Yt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Yt]=0,this._inflate[An]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,l)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?Qi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Qi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[Yt]=0,this._deflate[An]=[],this._deflate.on("data",UE)}this._deflate[Fr]=i,this._deflate.write(e),this._deflate.flush(Qi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Uh.concat(this._deflate[An],this._deflate[Yt]);r&&(c=new FE(c.buffer,c.byteOffset,c.length-4)),this._deflate[Fr]=null,this._deflate[Yt]=0,this._deflate[An]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};qh.exports=vl;function UE(t){this[An].push(t),this[Yt]+=t.length}function Gh(t){if(this[Yt]+=t.length,this[Mo]._maxPayload<1||this[Yt]<=this[Mo]._maxPayload){this[An].push(t);return}this[zr]=new RangeError("Max payload size exceeded"),this[zr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[zr][Hh]=1009,this.removeListener("data",Gh),this.reset()}function HE(t){if(this[Mo]._inflate=null,this[zr]){this[Fr](this[zr]);return}t[Hh]=1007,this[Fr](t)}});var Hr=ae((XR,Bo)=>{"use strict";var{isUtf8:jh}=ue("buffer"),{hasBlob:GE}=Zt(),qE=[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 jE(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Sl(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 WE(t){return GE&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Bo.exports={isBlob:WE,isValidStatusCode:jE,isValidUTF8:Sl,tokenChars:qE};if(jh)Bo.exports.isValidUTF8=function(t){return t.length<24?Sl(t):jh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ue("utf-8-validate");Bo.exports.isValidUTF8=function(e){return e.length<32?Sl(e):t(e)}}catch{}});var Cl=ae((QR,Yh)=>{"use strict";var{Writable:KE}=ue("stream"),Wh=Ur(),{BINARY_TYPES:$E,EMPTY_BUFFER:Kh,kStatusCode:VE,kWebSocket:JE}=Zt(),{concat:Il,toArrayBuffer:ZE,unmask:YE}=Xi(),{isValidStatusCode:XE,isValidUTF8:$h}=Hr(),Fo=Buffer[Symbol.species],xt=0,Vh=1,Jh=2,Zh=3,Al=4,Tl=5,zo=6,kl=class extends KE{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||$E[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[JE]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=xt}_write(e,r,i){if(this._opcode===8&&this._state==xt)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Fo(i.buffer,i.byteOffset+e,i.length-e),new Fo(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 Fo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case xt:this.getInfo(e);break;case Vh:this.getPayloadLength16(e);break;case Jh:this.getPayloadLength64(e);break;case Zh:this.getMask();break;case Al:this.getData(e);break;case Tl:case zo: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[Wh.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=Vh:this._payloadLength===127?this._state=Jh:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),i=r.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=Zh:this._state=Al}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Al}getData(e){let r=Kh;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&&YE(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Tl,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[Wh.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return r(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(l);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let l=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(l);return}this._fragments.push(c)}this.dataMessage(r),this._state===xt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=xt;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Il(i,r):this._binaryType==="arraybuffer"?o=ZE(Il(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=xt):(this._state=zo,setImmediate(()=>{this.emit("message",o,!0),this._state=xt,this.startLoop(e)}))}else{let o=Il(i,r);if(!this._skipUTF8Validation&&!$h(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Tl||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=xt):(this._state=zo,setImmediate(()=>{this.emit("message",o,!1),this._state=xt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Kh),this.end();else{let i=e.readUInt16BE(0);if(!XE(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Fo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$h(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=xt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=xt):(this._state=zo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xt,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let l=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(l,this.createError),l.code=c,l[VE]=o,l}};Yh.exports=kl});var Dl=ae((tP,ex)=>{"use strict";var{Duplex:eP}=ue("stream"),{randomFillSync:QE}=ue("crypto"),{types:{isUint8Array:ev}}=ue("util"),Xh=Ur(),{EMPTY_BUFFER:tv,kWebSocket:nv,NOOP:rv}=Zt(),{isBlob:Gr,isValidStatusCode:iv}=Hr(),{mask:Qh,toBuffer:Vn}=Xi(),pt=Symbol("kByteLength"),sv=Buffer.alloc(4),Uo=8*1024,Jn,qr=Uo,St=0,ov=1,av=2,Rl=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=St,this.onerror=rv,this[nv]=void 0}static frame(e,r){let i,o=!1,c=2,l=!1;r.mask&&(i=r.maskBuffer||sv,r.generateMask?r.generateMask(i):(qr===Uo&&(Jn===void 0&&(Jn=Buffer.alloc(Uo)),QE(Jn,0,Uo),qr=0),i[0]=Jn[qr++],i[1]=Jn[qr++],i[2]=Jn[qr++],i[3]=Jn[qr++]),l=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||l)&&r[pt]!==void 0?u=r[pt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!l);let f=u;u>=65536?(c+=8,f=127):u>125&&(c+=2,f=126);let x=Buffer.allocUnsafe(o?u+c:c);return x[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(x[0]|=64),x[1]=f,f===126?x.writeUInt16BE(u,2):f===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),r.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],l?[x,e]:o?(Qh(e,i,x,c,u),[x]):(Qh(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=tv;else{if(typeof e!="number"||!iv(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 l={[pt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==St?this.enqueue([this.dispatch,c,!1,l,o]):this.sendFrame(t.frame(c,l),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Vn(e),o=e.length,c=Vn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==St?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Vn(e),o=e.length,c=Vn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==St?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,r,i){let o=this._extensions[Xh.extensionName],c=r.binary?2:1,l=r.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Gr(e)?(u=e.size,f=!1):(e=Vn(e),u=e.length,f=Vn.readOnly),this._firstFragment?(this._firstFragment=!1,l&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=u>=o._threshold),this._compress=l):(l=!1,c=0),r.fin&&(this._firstFragment=!0);let x={[pt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:f,rsv1:l};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==St?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[pt],this._state=av,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Pl,this,u,o);return}this._bufferedBytes-=i[pt];let l=Vn(c);r?this.dispatch(l,r,i,o):(this._state=St,this.sendFrame(t.frame(l,i),o),this.dequeue())}).catch(c=>{process.nextTick(cv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[Xh.extensionName];this._bufferedBytes+=i[pt],this._state=ov,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Pl(this,f,o);return}this._bufferedBytes-=i[pt],this._state=St,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===St&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][pt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][pt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};ex.exports=Rl;function Pl(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 cv(t,e,r){Pl(t,e,r),t.onerror(e)}});var lx=ae((nP,cx)=>{"use strict";var{kForOnEventAttribute:es,kListener:Ol}=Zt(),tx=Symbol("kCode"),nx=Symbol("kData"),rx=Symbol("kError"),ix=Symbol("kMessage"),sx=Symbol("kReason"),jr=Symbol("kTarget"),ox=Symbol("kType"),ax=Symbol("kWasClean"),Xt=class{constructor(e){this[jr]=null,this[ox]=e}get target(){return this[jr]}get type(){return this[ox]}};Object.defineProperty(Xt.prototype,"target",{enumerable:!0});Object.defineProperty(Xt.prototype,"type",{enumerable:!0});var Zn=class extends Xt{constructor(e,r={}){super(e),this[tx]=r.code===void 0?0:r.code,this[sx]=r.reason===void 0?"":r.reason,this[ax]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[tx]}get reason(){return this[sx]}get wasClean(){return this[ax]}};Object.defineProperty(Zn.prototype,"code",{enumerable:!0});Object.defineProperty(Zn.prototype,"reason",{enumerable:!0});Object.defineProperty(Zn.prototype,"wasClean",{enumerable:!0});var Wr=class extends Xt{constructor(e,r={}){super(e),this[rx]=r.error===void 0?null:r.error,this[ix]=r.message===void 0?"":r.message}get error(){return this[rx]}get message(){return this[ix]}};Object.defineProperty(Wr.prototype,"error",{enumerable:!0});Object.defineProperty(Wr.prototype,"message",{enumerable:!0});var ts=class extends Xt{constructor(e,r={}){super(e),this[nx]=r.data===void 0?null:r.data}get data(){return this[nx]}};Object.defineProperty(ts.prototype,"data",{enumerable:!0});var lv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[es]&&o[Ol]===e&&!o[es])return;let i;if(t==="message")i=function(c,l){let u=new ts("message",{data:l?c:c.toString()});u[jr]=this,Ho(e,this,u)};else if(t==="close")i=function(c,l){let u=new Zn("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[jr]=this,Ho(e,this,u)};else if(t==="error")i=function(c){let l=new Wr("error",{error:c,message:c.message});l[jr]=this,Ho(e,this,l)};else if(t==="open")i=function(){let c=new Xt("open");c[jr]=this,Ho(e,this,c)};else return;i[es]=!!r[es],i[Ol]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Ol]===e&&!r[es]){this.removeListener(t,r);break}}};cx.exports={CloseEvent:Zn,ErrorEvent:Wr,Event:Xt,EventTarget:lv,MessageEvent:ts};function Ho(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Go=ae((rP,dx)=>{"use strict";var{tokenChars:ns}=Hr();function Nt(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,l,u,f=-1,x=-1,p=-1,m=0;for(;m<t.length;m++)if(x=t.charCodeAt(m),l===void 0)if(p===-1&&ns[x]===1)f===-1&&(f=m);else if(m!==0&&(x===32||x===9))p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let _=t.slice(f,p);x===44?(Nt(e,_,r),r=Object.create(null)):l=_,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(u===void 0)if(p===-1&&ns[x]===1)f===-1&&(f=m);else if(x===32||x===9)p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),Nt(r,t.slice(f,p),!0),x===44&&(Nt(e,l,r),r=Object.create(null),l=void 0),f=p=-1}else if(x===61&&f!==-1&&p===-1)u=t.slice(f,m),f=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(o){if(ns[x]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);f===-1?f=m:i||(i=!0),o=!1}else if(c)if(ns[x]===1)f===-1&&(f=m);else if(x===34&&f!==-1)c=!1,p=m;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(x===34&&t.charCodeAt(m-1)===61)c=!0;else if(p===-1&&ns[x]===1)f===-1&&(f=m);else if(f!==-1&&(x===32||x===9))p===-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let _=t.slice(f,p);i&&(_=_.replace(/\\/g,""),i=!1),Nt(r,u,_),x===44&&(Nt(e,l,r),r=Object.create(null),l=void 0),u=void 0,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(f===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let v=t.slice(f,p);return l===void 0?Nt(e,v,r):(u===void 0?Nt(r,v,!0):i?Nt(r,u,v.replace(/\\/g,"")):Nt(r,u,v),Nt(e,l,r)),e}function uv(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(l=>l===!0?o:`${o}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}dx.exports={format:uv,parse:dv}});var Ko=ae((oP,vx)=>{"use strict";var fv=ue("events"),hv=ue("https"),xv=ue("http"),hx=ue("net"),pv=ue("tls"),{randomBytes:gv,createHash:mv}=ue("crypto"),{Duplex:iP,Readable:sP}=ue("stream"),{URL:Ll}=ue("url"),Tn=Ur(),wv=Cl(),_v=Dl(),{isBlob:yv}=Hr(),{BINARY_TYPES:ux,CLOSE_TIMEOUT:bv,EMPTY_BUFFER:qo,GUID:Ev,kForOnEventAttribute:Nl,kListener:vv,kStatusCode:Sv,kWebSocket:qe,NOOP:xx}=Zt(),{EventTarget:{addEventListener:Iv,removeEventListener:Av}}=lx(),{format:Tv,parse:kv}=Go(),{toBuffer:Cv}=Xi(),px=Symbol("kAborted"),Ml=[8,13],Qt=["CONNECTING","OPEN","CLOSING","CLOSED"],Rv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends fv{constructor(e,r,i){super(),this._binaryType=ux[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=qo,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]),gx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ux.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 wv({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 _v(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[qe]=this,c[qe]=this,e[qe]=this,o.on("conclude",Ov),o.on("drain",Lv),o.on("error",Nv),o.on("message",Mv),o.on("ping",Bv),o.on("pong",Fv),c.onerror=zv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",yx),e.on("data",Wo),e.on("end",bx),e.on("error",Ex),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Tn.extensionName]&&this._extensions[Tn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){at(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())}),_x(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){Bl(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||qo,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){Bl(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||qo,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){Bl(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Tn.extensionName]||(o.compress=!1),this._sender.send(e||qo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){at(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(me,"CONNECTING",{enumerable:!0,value:Qt.indexOf("CONNECTING")});Object.defineProperty(me.prototype,"CONNECTING",{enumerable:!0,value:Qt.indexOf("CONNECTING")});Object.defineProperty(me,"OPEN",{enumerable:!0,value:Qt.indexOf("OPEN")});Object.defineProperty(me.prototype,"OPEN",{enumerable:!0,value:Qt.indexOf("OPEN")});Object.defineProperty(me,"CLOSING",{enumerable:!0,value:Qt.indexOf("CLOSING")});Object.defineProperty(me.prototype,"CLOSING",{enumerable:!0,value:Qt.indexOf("CLOSING")});Object.defineProperty(me,"CLOSED",{enumerable:!0,value:Qt.indexOf("CLOSED")});Object.defineProperty(me.prototype,"CLOSED",{enumerable:!0,value:Qt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(me.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(me.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Nl])return e[vv];return null},set(e){for(let r of this.listeners(t))if(r[Nl]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Nl]:!0})}})});me.prototype.addEventListener=Iv;me.prototype.removeEventListener=Av;vx.exports=me;function gx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:bv,protocolVersion:Ml[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,!Ml.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ml.join(", ")})`);let c;if(e instanceof Ll)c=e;else try{c=new Ll(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let l=c.protocol==="wss:",u=c.protocol==="ws+unix:",f;if(c.protocol!=="ws:"&&!l&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?f="The URL's pathname is empty":c.hash&&(f="The URL contains a fragment identifier"),f){let I=new SyntaxError(f);if(t._redirects===0)throw I;jo(t,I);return}let x=l?443:80,p=gv(16).toString("base64"),m=l?hv.request:xv.request,v=new Set,_;if(o.createConnection=o.createConnection||(l?Dv:Pv),o.defaultPort=o.defaultPort||x,o.port=c.port||x,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Tn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Tv({[Tn.extensionName]:_.offer()})),r.length){for(let I of r){if(typeof I!="string"||!Rv.test(I)||v.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(I)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let b;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=l,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,k]of Object.entries(I))i.headers[A.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!l)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),b=t._req=m(o),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=m(o);o.timeout&&b.on("timeout",()=>{at(t,b,"Opening handshake has timed out")}),b.on("error",I=>{b===null||b[px]||(b=t._req=null,jo(t,I))}),b.on("response",I=>{let A=I.headers.location,k=I.statusCode;if(A&&o.followRedirects&&k>=300&&k<400){if(++t._redirects>o.maxRedirects){at(t,b,"Maximum redirects exceeded");return}b.abort();let P;try{P=new Ll(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);jo(t,R);return}gx(t,P,r,i)}else t.emit("unexpected-response",b,I)||at(t,b,`Unexpected server response: ${I.statusCode}`)}),b.on("upgrade",(I,A,k)=>{if(t.emit("upgrade",I),t.readyState!==me.CONNECTING)return;b=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){at(t,A,"Invalid Upgrade header");return}let y=mv("sha1").update(p+Ev).digest("base64");if(I.headers["sec-websocket-accept"]!==y){at(t,A,"Invalid Sec-WebSocket-Accept header");return}let R=I.headers["sec-websocket-protocol"],O;if(R!==void 0?v.size?v.has(R)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":v.size&&(O="Server sent no subprotocol"),O){at(t,A,O);return}R&&(t._protocol=R);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!_){at(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=kv(F)}catch{at(t,A,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(M);if(V.length!==1||V[0]!==Tn.extensionName){at(t,A,"Server indicated an extension that was not requested");return}try{_.accept(M[Tn.extensionName])}catch{at(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Tn.extensionName]=_}t.setSocket(A,k,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(b,t):b.end()}function jo(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Pv(t){return t.path=t.socketPath,hx.connect(t)}function Dv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hx.isIP(t.host)?"":t.host),pv.connect(t)}function at(t,e,r){t._readyState=me.CLOSING;let i=new Error(r);Error.captureStackTrace(i,at),e.setHeader?(e[px]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(jo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Bl(t,e,r){if(e){let i=yv(e)?e.size:Cv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Qt[t.readyState]})`);process.nextTick(r,i)}}function Ov(t,e){let r=this[qe];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[qe]!==void 0&&(r._socket.removeListener("data",Wo),process.nextTick(mx,r._socket),t===1005?r.close():r.close(t,e))}function Lv(){let t=this[qe];t.isPaused||t._socket.resume()}function Nv(t){let e=this[qe];e._socket[qe]!==void 0&&(e._socket.removeListener("data",Wo),process.nextTick(mx,e._socket),e.close(t[Sv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function fx(){this[qe].emitClose()}function Mv(t,e){this[qe].emit("message",t,e)}function Bv(t){let e=this[qe];e._autoPong&&e.pong(t,!this._isServer,xx),e.emit("ping",t)}function Fv(t){this[qe].emit("pong",t)}function mx(t){t.resume()}function zv(t){let e=this[qe];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,_x(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function _x(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function yx(){let t=this[qe];if(this.removeListener("close",yx),this.removeListener("data",Wo),this.removeListener("end",bx),t._readyState=me.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[qe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",fx),t._receiver.on("finish",fx))}function Wo(t){this[qe]._receiver.write(t)||this.pause()}function bx(){let t=this[qe];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function Ex(){let t=this[qe];this.removeListener("error",Ex),this.on("error",xx),t&&(t._readyState=me.CLOSING,this.destroy())}});var Tx=ae((cP,Ax)=>{"use strict";var aP=Ko(),{Duplex:Uv}=ue("stream");function Sx(t){t.emit("close")}function Hv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ix(t){this.removeListener("error",Ix),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Gv(t,e){let r=!0,i=new Uv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,l){let u=!l&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(Sx,i);return}let l=!1;t.once("error",function(f){l=!0,c(f)}),t.once("close",function(){l||c(o),process.nextTick(Sx,i)}),r&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,l){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,l)});return}t.send(o,l)},i.on("end",Hv),i.on("error",Ix),i}Ax.exports=Gv});var Fl=ae((lP,kx)=>{"use strict";var{tokenChars:qv}=Hr();function jv(t){let e=new Set,r=-1,i=-1,o=0;for(o;o<t.length;o++){let l=t.charCodeAt(o);if(i===-1&&qv[l]===1)r===-1&&(r=o);else if(o!==0&&(l===32||l===9))i===-1&&r!==-1&&(i=o);else if(l===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(r,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(r,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}kx.exports={parse:jv}});var Nx=ae((uP,Lx)=>{"use strict";var Wv=ue("events"),$o=ue("http"),{Duplex:dP}=ue("stream"),{createHash:Kv}=ue("crypto"),Cx=Go(),Yn=Ur(),$v=Fl(),Vv=Ko(),{CLOSE_TIMEOUT:Jv,GUID:Zv,kWebSocket:Yv}=Zt(),Xv=/^[+/0-9A-Za-z]{22}==$/,Rx=0,Px=1,Ox=2,zl=class extends Wv{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:Jv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Vv,...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=$o.createServer((i,o)=>{let c=$o.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=Qv(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=Rx}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===Ox){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(rs,this);return}if(e&&this.once("close",e),this._state!==Px)if(this._state=Px,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(rs,this):process.nextTick(rs,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{rs(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",Dx);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Xn(this,e,r,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){Xn(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!Xv.test(c)){Xn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Xn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){is(r,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=$v.parse(f)}catch{Xn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&p!==void 0){let v=new Yn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Cx.parse(p);_[Yn.extensionName]&&(v.accept(_[Yn.extensionName]),m[Yn.extensionName]=v)}catch{Xn(this,e,r,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,(_,b,I,A)=>{if(!_)return is(r,b||401,I,A);this.completeUpgrade(m,c,x,e,r,i,o)});return}if(!this.options.verifyClient(v))return is(r,401)}this.completeUpgrade(m,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,l,u){if(!c.readable||!c.writable)return c.destroy();if(c[Yv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rx)return is(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Kv("sha1").update(r+Zv).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;m&&(x.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[Yn.extensionName]){let m=e[Yn.extensionName].params,v=Cx.format({[Yn.extensionName]:[m]});x.push(`Sec-WebSocket-Extensions: ${v}`),p._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",_x),g.setSocket(c,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(g),g.on("close",()=>{this.clients.delete(g),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Xi,this)})),u(g,s)}};Ex.exports=Od;function U1(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 Xi(t){t._state=yx,t.emit("close")}function _x(){this.destroy()}function Qi(t,e,n,i){n=n||Go.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} ${Go.STATUS_CODES[e]}\r
17
- `+Object.keys(i).map(s=>`${s}: ${i[s]}`).join(`\r
16
+ `)),c.removeListener("error",Dx),p.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(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(rs,this)})),u(p,o)}};Lx.exports=zl;function Qv(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 rs(t){t._state=Ox,t.emit("close")}function Dx(){this.destroy()}function is(t,e,r,i){r=r||$o.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} ${$o.STATUS_CODES[e]}\r
17
+ `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+n)}function Qn(t,e,n,i,s,c){if(t.listenerCount("wsClientError")){let d=new Error(s);Error.captureStackTrace(d,Qn),t.emit("wsClientError",d,n,e)}else Qi(n,i,s,c)}});var Nx=ae(Pe=>{"use strict";var M=j;(function(t,e){let n=j,i=t();for(;;)try{if(-parseInt(n(1112))/1+parseInt(n(322))/2*(-parseInt(n(634))/3)+parseInt(n(1189))/4*(-parseInt(n(721))/5)+-parseInt(n(831))/6*(parseInt(n(470))/7)+-parseInt(n(190))/8+parseInt(n(1258))/9*(-parseInt(n(1088))/10)+parseInt(n(443))/11===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Vo,534701);var V1=Object["definePr"+M(462)],Y1=Object[M(1425)+M(1024)+M(716)],Cx=(t,e)=>function(){return t&&(e=(0,t[{kyvYz:function(s,c){return s(c)}}.kyvYz(Y1,t)[0]])(t=0)),e},J1=(t,e)=>{for(var n in e)V1(t,n,{get:e[n],enumerable:!0})};function Z1(){return Ix||(Ix=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function X1(){let t=M;return Ax||(Ax=[IDBCursor[t(829)+"e"].advance,IDBCursor.prototype[t(1505)],IDBCursor[t(829)+"e"][t(1505)+t(475)+"ey"]])}function Q1(t){let e=M,n={LWMCY:e(817),txhWm:function(s,c){return s(c)},YwrIz:function(s,c){return s===c},Zdkvh:e(631),Zraiv:"deRvj",MiBka:e(1284),HLcex:function(s,c,d,u){return s(c,d,u)},HCJKq:e(1291)+"er_qos",zuijm:"x_fronti"+e(649)+"k",ecEHt:function(s,c,d){return s(c,d)},uuCok:e(1291)+e(1408)+e(409),wwBQK:function(s,c){return s instanceof c},qmmYc:function(s,c){return s===c},PWCWw:e(832)},i=new Promise((s,c)=>{let d=e,u={TiBfA:function(w,S){return n[j(582)](w,S)},Cqpwo:n[d(247)],mDjGA:n.Zraiv,LWEbo:function(w,S){return w(S)}},h=()=>{let w=d;t["removeEv"+w(1133)+w(686)](n.LWMCY,x),t[w(704)+w(1133)+w(686)](w(1284),g)},x=()=>{let w=d,S={UztjS:function(y,v){return y>=v}};if(u[w(579)](u[w(638)],u.mDjGA))return S.UztjS(_0x12b4ce[w(1204)],_0xc6ea01[w(1234)]);s(u[w(1521)](Ft,t.result)),h()},g=()=>{let w=d;n[w(693)](c,t[w(1284)]),h()};t[d(476)+d(166)](n.LWMCY,x),t[d(476)+"Listener"](n[d(772)],g)});return i[e(830)](s=>{let c=e,d={zgvlT:function(u,h,x,g){return n[j(1329)](u,h,x,g)},ZQXnH:n[c(1535)],HiFif:function(u,h,x,g){return u(h,x,g)},fSYLn:n.zuijm,WHeaX:function(u,h,x){return n.ecEHt(u,h,x)},yHTLq:n.uuCok};if(n.wwBQK(s,IDBCursor))if(n[c(758)]("QhACQ",n[c(468)])){let u=!!this[c(388)][c(323)+"S"];if(!u)return{enabled:u,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let h=d[c(1369)](_0x3543ab,_0x59176b[c(143)][c(944)],d[c(352)],"2"),x=h&&d[c(1369)](_0x4f4b93,_0x1c1db2[c(143)][c(944)],c(1291)+c(1443)+"ck","1"),g=h&&d[c(624)](_0x5856f7,_0xbec5d1[c(143)].headers,d.fSYLn,"1"),w=g?d[c(741)](_0x2ec38d,_0x267493[c(143)][c(944)],d[c(787)])?.[c(1431)](",")[c(311)](_0x5b3899)||[]:[];return{enabled:u,isQoSMessage:h,isQoSAck:x,isAckCleanupMessage:g,ackMsgIds:w}}else Nd[c(769)](s,t)})[e(920)](()=>{}),Ko[e(769)](i,t),i}function ev(t){let e=M,n={qlnqO:function(s){return s()},vXNQj:function(s,c){return s(c)},LTCwg:function(s){return s()},iFNUH:e(1284),PNraY:e(556)};if(Wo.has(t))return;let i=new Promise((s,c)=>{let d=e,u={kGNNT:d(1284),EKppt:function(w){return n.qlnqO(w)},bHuoV:function(w,S){return n[d(883)](w,S)},AGGri:d(1229)+"or",BDjam:function(w){return n[d(1591)](w)}},h=()=>{let w=d;t["removeEv"+w(1133)+"ner"]("complete",x),t[w(704)+w(1133)+w(686)](u[w(1508)],g),t["removeEv"+w(1133)+"ner"](w(556),g)},x=()=>{let w=d;s(),u[w(196)](h)},g=()=>{let w=d;u[w(560)](c,t[w(1284)]||new DOMException(w(1229)+"or",u[w(393)])),u[w(1564)](h)};t[d(476)+d(166)](d(296),x),t[d(476)+d(166)](n[d(1241)],g),t[d(476)+"Listener"](n.PNraY,g)});Wo[e(769)](t,i)}function tv(t){$o={jtSUQ:function(i,s){return i(s)}}[M(422)](t,$o)}function nv(t){let e=M,n={madpa:function(i,s){return i(s)},jjEiK:function(i,s){return i(s)},nckNH:function(i,s){return i===s},BMUVe:function(i,s){return i instanceof s},WaXOx:function(i,s){return i+s},saZLe:function(i,s){return i+s},AgYKG:e(856),lxBFP:function(i,s){return i(s)},CRdpu:function(i,s){return i(s)},WMMwi:function(i,s){return i(s)},eAzVa:function(i,s){return i in s},pyAqZ:function(i,s){return i!==s},YVYUf:e(1322),eSCQD:function(i){return i()}};return t===IDBDatabase[e(829)+"e"][e(258)+e(835)]&&!n[e(1587)](e(501)+"oreNames",IDBTransaction.prototype)?n.pyAqZ(e(1523),n[e(534)])?function(i,...s){let c=e,d=t[c(525)](n[c(885)](es,this),i,...s);return Ld.set(d,i[c(894)]?i[c(894)]():[i]),n[c(672)](Ft,d)}:(this[e(379)+e(737)+e(1294)+"t"]=1,this[e(1533)+e(575)]++,this[e(401)+"s"][this["currentI"+e(575)]]):n.eSCQD(X1)[e(1485)](t)?function(...i){let s=e;if(n[s(962)](n[s(520)],n[s(520)]))return t.apply(n[s(380)](es,this),i),n[s(1033)](Ft,Nd[s(905)](this));{let c=this[s(1452)+"rs"][_0x48b170];if(c)c[s(1097)]().forEach(d=>d.fn.apply(d[s(1091)],_0x4ebe63));else if(n[s(962)](s(1284),_0x24eb44)&&!this[s(339)]){let d=_0x2544d6[s(1421)]&&_0x30cc54[0];if(n[s(659)](d,_0x797c8b))throw d;let u=new _0x5606a1(n[s(592)](s(794)+s(836),d?n.saZLe(" (",d[s(143)])+")":""));throw u[s(1045)]=d,d}return this}}:function(...i){let s=e;return n[s(305)](Ft,t[s(1512)](n[s(305)](es,this),i))}}function rv(t){let e=M,n={GsxZg:e(679),PTMqi:function(i,s){return i(s)},QAIxL:function(i,s){return i instanceof s},SNSEu:function(i,s,c){return i(s,c)},DgQYF:function(i){return i()}};return typeof t===n[e(410)]?n[e(1418)](nv,t):(n[e(320)](t,IDBTransaction)&&n[e(1418)](ev,t),n[e(1352)](Px,t,n[e(1450)](Z1))?new Proxy(t,$o):t)}function Ft(t){let e=M,n={DpWWr:function(s,c){return s instanceof c},xFnXV:function(s,c){return s(c)},nVRgw:function(s,c){return s!==c}};if(n.DpWWr(t,IDBRequest))return n[e(583)](Q1,t);if(Ho[e(413)](t))return Ho[e(905)](t);let i=n.xFnXV(rv,t);return n[e(783)](i,t)&&(Ho[e(769)](t,i),Ko.set(i,t)),i}var Px,Ix,Ax,Nd,Wo,Ld,Ho,Ko,$o,es,kx=Cx({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={hpCpd:function(n,i){return n instanceof i},tMpNW:function(n,i){return n===i},RWcIV:t(633),xSlWY:function(n,i){return n instanceof i},kGMIh:function(n,i){return n===i},ohweW:t(226),FmqXR:function(n,i){return n in i}};Px=(n,i)=>i.some(s=>n instanceof s),Nd=new WeakMap,Wo=new WeakMap,Ld=new WeakMap,Ho=new WeakMap,Ko=new WeakMap,$o={get(n,i,s){let c=t;if(e[c(345)](n,IDBTransaction)){if(i===c(226))return Wo[c(905)](n);if(e[c(1488)](i,c(501)+c(532)))return n.objectStoreNames||Ld[c(905)](n);if(e[c(1488)](i,e[c(1358)]))return s[c(501)+c(532)][1]?void 0:s[c(501)+c(1589)](s[c(501)+c(532)][0])}return Ft(n[i])},set(n,i,s){return n[i]=s,!0},has(n,i){let s=t;return e[s(1176)](n,IDBTransaction)&&(e[s(1337)](i,e[s(490)])||i===e.RWcIV)?!0:e[s(364)](i,n)}},es=n=>Ko[t(905)](n)}}),Dx={};J1(Dx,{deleteDB:()=>sv,openDB:()=>iv,unwrap:()=>es,wrap:()=>Ft});function iv(t,e,{blocked:n,upgrade:i,blocking:s,terminated:c}={}){let d=M,u={LxiRR:function(g,w,S,y,v){return g(w,S,y,v)},vTpqq:function(g,w){return g(w)},QILyi:d(689)+d(338)+d(610)+"imes in "+d(717),moSbe:function(g,w){return g===w},wgNVD:function(g,w){return g+w},SgCsz:"esxVh",oEQJU:d(450),Wvlaf:d(961),SLxYn:"versionchange",yjrwf:d(1604)+d(1190),FTpkk:"blocked"},h=indexedDB[d(718)](t,e),x=u[d(1314)](Ft,h);return i&&h[d(476)+d(166)](u[d(766)],g=>{let w=d;u[w(1547)](i,u[w(1314)](Ft,h[w(578)]),g.oldVersion,g.newVersion,u[w(1314)](Ft,h[w(258)+"ion"]))}),n&&h[d(476)+d(166)](u.FTpkk,()=>n()),x.then(g=>{let w=d;if(u[w(1161)](u[w(1397)],u.oEQJU))return _0x5d4f13<=_0xac5b8c?_0x5f1725.reject(new _0x5479fb(u[w(1493)])):(_0x2b91a3=_0x28aed2,u[w(1161)](_0x5b3977,_0x74e92b.length)?_0x4aad2e.resolve():_0x1eb293[_0x97e1b8][w(448)](_0x4c6985)(_0x169268,_0x519734[w(448)](null,u[w(243)](_0x36406a,1))));c&&g[w(476)+w(166)](u.Wvlaf,()=>c()),s&&g[w(476)+"Listener"](u.SLxYn,()=>s())})[d(920)](()=>{}),x}function sv(t,{blocked:e}={}){let n=M,i={qRHoq:"blocked",aHAPr:function(c,d){return c(d)}},s=indexedDB[n(663)+n(1157)](t);return e&&s.addEventListener(i[n(873)],()=>e()),i[n(1313)](Ft,s).then(()=>{})}function Tx(t,e){let n=M,i={riwsw:n(994)+"e",qhqnv:function(h,x){return h in x},msLNq:n(1198),Qhovq:function(h,x){return h!==x},WYjNZ:function(h,x){return h in x}};if(!(t instanceof IDBDatabase&&!i[n(1226)](e,t)&&typeof e===i[n(739)]))return;if(jo.get(e))return jo[n(905)](e);let s=e[n(523)](/FromIndex$/,""),c=i.Qhovq(e,s),d=Lx[n(1485)](s);if(!i[n(1585)](s,(c?IDBIndex:IDBObjectStore)[n(829)+"e"])||!(d||Ox.includes(s)))return;let u=async function(h,...x){let g=n,w=this[g(258)+g(835)](h,d?i[g(1372)]:g(1220)),S=w.store;return c&&(S=S[g(1061)](x[g(710)]())),(await Promise[g(568)]([S[s](...x),d&&w.done]))[0]};return jo.set(e,u),u}function j(t,e){t=t-140;let n=Vo(),i=n[t];if(j.ORDkny===void 0){var s=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",w="";for(let S=0,y,v,I=0;v=h.charAt(I++);~v&&(y=S%4?y*64+v:v,S++%4)?g+=String.fromCharCode(255&y>>(-2*S&6)):0)v=x.indexOf(v);for(let S=0,y=g.length;S<y;S++)w+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(w)};j.FgfFOa=s,j.FijWQA={},j.ORDkny=!0}let c=n[0],d=t+c,u=j.FijWQA[d];return u?i=u:(i=j.FgfFOa(i),j.FijWQA[d]=i),i}var Ox,Lx,jo,ov=Cx({"node_modules/idb/build/index.js"(){let t=M,e={bxeWK:t(254),JLNly:t(336),kAZwU:t(513)+"ys",QmSsX:t(1087),hfXpt:t(995),Dwayy:t(1078),BjkNM:t(777),IAfuT:"clear",rGELe:function(s,c){return s(c)}},n=("1|5|0|3|"+t(1346))[t(1431)]("|"),i=0;for(;;){switch(n[i++]){case"0":Ox=[t(905),e[t(435)],e[t(227)],e[t(854)],e.QmSsX];continue;case"1":kx();continue;case"2":jo=new Map;continue;case"3":Lx=[e.hfXpt,e[t(177)],e[t(612)],e.IAfuT];continue;case"4":e[t(222)](tv,s=>({...s,get:(c,d,u)=>Tx(c,d)||s[t(905)](c,d,u),has:(c,d)=>!!Tx(c,d)||s[t(413)](c,d)}));continue;case"5":kx();continue}break}}}),av={idb:function(t){let e=M,n={qvSRw:function(i,s){return i===s},UCFPQ:e(226),juTAk:"store",ngmFq:e(1598)};t[e(919)]=Promise[e(159)]().then(()=>(ov(),Dx))[e(830)](function(i){let s=e;return n[s(179)](s(927),n[s(142)])?_0x4aaa35 instanceof _0x3449b8&&(rviOeC[s(179)](_0x2a75ad,rviOeC.UCFPQ)||rviOeC[s(179)](_0x8f9e31,rviOeC[s(791)]))?!0:_0x19dd94 in _0x526066:i})}},Rx={};function Bt(t){let e=M;var n=Rx[t];if(n!==void 0)return n[e(919)];var i=Rx[t]={exports:{}};return av[t](i,i.exports,Bt),i[e(919)]}Bt.d=(t,e)=>{let n=j;for(var i in e)Bt.o(e,i)&&!Bt.o(t,i)&&Object[n(1492)+n(462)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Bt.o=(e,n)=>Object.prototype[t(1368)+t(462)][t(525)](e,n)})(),(()=>{let t=M,e={hWTNo:function(n,i){return n===i},hRhGr:"trYmF",GAmII:t(198)+"d",JpVFW:t(1249)+"le"};Bt.r=n=>{let i=t;e[i(669)](e[i(1266)],e[i(1266)])?(e[i(1292)]!=typeof Symbol&&Symbol[i(867)+i(743)]&&Object[i(1492)+i(462)](n,Symbol[i(867)+i(743)],{value:"Module"}),Object[i(1492)+i(462)](n,e[i(1179)],{value:!0})):_0x4730a1[i(159)]().then(()=>{Pe["_addWsLi"+i(1384)]()})}})();var Ce={};(()=>{let t=M,e={nKbQb:function(a,r){return a+r},yDOyw:function(a,r){return a+r},TUARK:t(1284),pUuUC:function(a,r){return a!==r},WWlOq:t(929),kEwrz:function(a,r){return a*r},YVSAB:function(a,r){return a(r)},jFULC:function(a,r,o){return a(r,o)},UeqPd:function(a,r){return a(r)},LWpNQ:function(a,r){return a+r},CkFHL:"0000",tKOBi:"ffff",RkvyM:function(a,r){return a(r)},dolcm:t(709)+t(709)+t(709)+"00000000",DzXrk:function(a,r,o){return a(r,o)},mossw:"cursor_name",TnYza:function(a,r){return a>r},hReMp:function(a,r){return a<r},tBXoi:function(a,r){return a>r},mXrQv:function(a,r){return a-r},qYCuf:function(a,r){return a!==r},hPzZk:function(a,r){return a-r},wLcka:function(a,r){return a<r},WIjTn:function(a,r){return a===r},mXcWa:t(242),wLpvG:function(a,r){return a<r},sKQaR:function(a,r){return a!==r},BoeiB:function(a,r){return a!==r},MIiNQ:function(a,r,o){return a(r,o)},kKTPT:function(a,r,o){return a(r,o)},HnhzH:function(a,r){return a!==r},enxpp:function(a,r){return a!==r},BzZdE:t(688),kUdfi:t(1605),hDgFA:function(a,r){return a(r)},urgJs:function(a,r){return a>>>r},kfdXB:function(a,r){return a(r)},bjDxB:function(a,r,o){return a(r,o)},YnBJt:function(a,r){return a(r)},cRjPc:function(a,r){return a&r},GJDok:t(1596)+t(1429)+t(840)+"key",ezfvp:function(a,r){return a===r},TWLUV:t(1596)+t(1429)+t(840)+"value",vnBFe:function(a){return a()},gPWNT:function(a,r,o){return a(r,o)},CNOFU:function(a,r){return a<<r},QpYga:function(a,r){return a&r},DFTdk:function(a,r,o){return a(r,o)},qpoCC:"message",RGSJB:function(a,r){return a===r},ckZxX:"DCZWT",klFHP:function(a,r,o){return a(r,o)},Xqxsi:t(1016),EHgTs:"uXyOy",PKuCB:function(a,r){return a!==r},Zimex:function(a,r){return a(r)},XJaBs:function(a,r,o){return a(r,o)},rZkDD:function(a,r){return a(r)},TRjis:function(a,r){return a!==r},INAVO:function(a,r,o){return a(r,o)},HfiaH:function(a,r){return a(r)},fSyfG:function(a,r,o){return a(r,o)},vUice:function(a,r){return a!==r},oDoed:function(a,r){return a!==r},BifkY:t(871),NuAvw:function(a,r,o){return a(r,o)},yPJeQ:"wyYSu",tYuuQ:t(461),bGttz:function(a,r,o){return a(r,o)},pSYUg:function(a,r,o){return a(r,o)},xSAfc:function(a,r){return a!==r},wPLNm:function(a,r,o){return a(r,o)},sKfol:function(a,r){return a(r)},zhYYG:function(a,r){return a(r)},ncjGN:function(a,r,o){return a(r,o)},vsSfo:function(a,r){return a(r)},AoezV:function(a,r){return a(r)},tzvgX:function(a,r){return a(r)},hguaA:function(a,r){return a(r)},JhrQm:function(a,r,o){return a(r,o)},whLrk:function(a,r){return a(r)},uteTS:function(a,r,o){return a(r,o)},IBNsZ:function(a,r){return a(r)},VlESj:function(a,r){return a(r)},uBHzP:function(a,r){return a(r)},NjAqT:function(a,r,o){return a(r,o)},MQjBg:function(a,r){return a===r},gRioc:function(a,r){return a===r},JUuwV:t(1596)+t(1429)+t(840)+t(1074),gKjwf:t(1596)+t(1429)+" field: "+t(949),BizQO:t(1596)+t(1429)+t(840)+t(833),niYDa:function(a,r){return a(r)},KAxfA:function(a,r,o){return a(r,o)},uFXEr:function(a,r,o){return a(r,o)},xKFpD:function(a,r){return a+r},rKRuP:t(1274)+t(416)+t(365),NnAOz:function(a,r){return a===r},OedxS:function(a,r){return a>r},fEXXv:function(a,r){return a+r},EPzon:function(a,r){return a>=r},aWEHs:function(a,r){return a>r},yHKln:function(a,r){return a>r},SbASR:function(a,r,o,l){return a(r,o,l)},JtlEn:t(1540),BXeTK:function(a,r){return a>r},ruyZw:function(a,r,o){return a(r,o)},AkbdY:function(a,r){return a+r},LFJwA:function(a,r){return a===r},DSHHE:function(a,r){return a>=r},GoQpZ:function(a,r){return a+r},bMEZv:function(a,r){return a+r},ElPuD:function(a,r){return a!==r},GtxfO:function(a,r){return a|r},eSunU:function(a,r){return a<<r},FRsKu:function(a,r){return a==r},bkynb:function(a,r){return a===r},TihRM:t(1391),sTgKt:function(a,r){return a+r},Ijfkg:function(a,r){return a<<r},htELm:function(a,r){return a|r},APygU:function(a,r){return a<<r},QjOUv:function(a,r){return a&r},JFakn:function(a,r){return a&r},RUxFv:function(a,r){return a<=r},VcjJi:function(a,r){return a==r},Vhgjn:function(a,r){return a+r},UWlvG:function(a,r){return a+r},Hozvv:function(a,r){return a+r},nIOqI:function(a,r){return a&r},AdHqx:function(a,r){return a|r},HSlBO:function(a,r){return a|r},FbiTh:function(a,r){return a|r},IwmjF:function(a,r){return a<<r},afxYB:function(a,r){return a<<r},TRPMi:function(a,r){return a<r},TcxKo:function(a,r){return a>r},GEUbe:function(a,r,o){return a(r,o)},HxSnr:function(a,r){return a>>r},JWWXg:function(a,r){return a&r},TmSzx:function(a,r){return a<=r},YtOXs:function(a,r){return a+r},YYBkd:function(a,r){return a>=r},FltcS:function(a,r){return a|r},pCBIv:t(1471),mkziJ:function(a,r){return a+r},ifIOj:function(a,r){return a<<r},XcwBV:function(a,r){return a<r},AxySB:function(a,r){return a<r},EYYdf:function(a,r){return a<r},scWeS:function(a,r){return a>=r},eglcg:function(a,r){return a+r},jnmMm:t(1553),HliCF:function(a,r){return a&r},GzfsW:function(a,r){return a<r},CqyfU:function(a,r){return a>>r},mqFHL:function(a,r){return a|r},aphxr:function(a,r){return a&r},qHofC:function(a,r,o){return a(r,o)},xGgGc:function(a,r){return a===r},vzoPw:t(522),mlRhH:function(a,r,o){return a(r,o)},nkeNG:function(a,r){return a(r)},Lrcwy:function(a,r){return a<<r},ewLFd:function(a,r){return a&r},yalAZ:function(a,r,o){return a(r,o)},bXaKU:function(a,r){return a instanceof r},nMGZV:function(a,r){return a==r},PldtD:function(a,r){return a&r},rkBBf:function(a,r){return a(r)},otzXi:function(a,r){return a&r},amVVo:function(a,r){return a(r)},WKkos:function(a,r){return a&r},STkai:function(a,r){return a(r)},AnBPE:function(a,r){return a<<r},sMnFf:function(a,r){return a&r},gEwNy:function(a,r){return a(r)},rFmhc:function(a,r){return a<<r},iNWES:function(a,r){return a&r},ePrPR:function(a,r){return a(r)},EbUCN:function(a,r){return a&r},JZyPw:function(a,r){return a(r)},wfgLX:function(a,r){return a&r},knIKk:function(a,r){return a(r)},mCnlo:function(a,r){return a===r},zJAOJ:t(590),JGLvB:function(a,r){return a|r},bzZXi:function(a,r){return a<<r},NAcGZ:"Yixmr",omyuN:function(a,r){return a>>>r},rLrzG:function(a,r){return a<<r},etfvG:function(a,r){return a>>>r},igqzB:function(a,r){return a===r},baKxU:function(a,r){return a<r},xNkuM:function(a,r){return a&r},KzngU:function(a,r){return a+r},bYLZV:function(a,r){return a!==r},rdGhi:function(a,r){return a&r},bSYnW:function(a,r){return a!==r},QzYfl:function(a,r){return a>>>r},XLCBd:function(a,r){return a&r},aknpz:function(a,r){return a>>>r},NgVoY:function(a,r){return a!==r},vOXkn:function(a,r){return a|r},PliSy:function(a,r){return a>>>r},tenEu:function(a,r){return a!==r},mFECi:function(a,r){return a|r},KVWIO:function(a,r){return a>>>r},SytEb:function(a,r){return a&r},YXXze:function(a,r){return a>>>r},LpmnK:function(a,r){return a&r},zfbCq:function(a,r){return a!==r},HauVT:function(a,r){return a+r},YnQUD:function(a,r){return a!==r},qzFyW:function(a,r){return a|r},zhWuU:function(a,r){return a>>>r},lxEel:function(a,r){return a>>>r},jNXJh:function(a,r){return a&r},SvCxH:function(a,r){return a|r},CSIoG:function(a,r){return a===r},jXYCm:t(1528),lhADK:function(a,r){return a(r)},AYvjO:function(a,r){return a|r},gaXeX:function(a,r){return a||r},VvlPd:t(287),OslDv:function(a,r){return a===r},fIieu:function(a,r){return a|r},msZDQ:function(a,r){return a<<r},ZRWzP:function(a,r){return a|r},KOumt:function(a,r){return a|r},QTOJM:function(a,r){return a<<r},EWfmM:function(a,r){return a<<r},JnKIN:function(a,r){return a>=r},IExjw:function(a,r){return a|r},qBEVd:function(a,r){return a<<r},DtcVp:function(a,r){return a|r},dJhNI:function(a,r){return a|r},Svest:function(a,r){return a<<r},uiLlR:function(a,r){return a|r},bVBoS:function(a,r){return a<<r},mEGXO:function(a,r){return a|r},DIXlR:function(a,r){return a|r},tTvCa:function(a,r){return a<<r},sdkKt:function(a,r){return a>>>r},TiqiN:function(a,r){return a>>>r},QjGeq:function(a,r){return a(r)},hqgVx:function(a,r){return a>=r},tmpbM:function(a,r){return a|r},mKOAS:function(a,r){return a/r},TkAzk:function(a,r){return a*r},ZBvBh:function(a,r){return a>>>r},Ecfld:function(a,r){return a+r},IczrK:function(a,r){return a===r},neYmf:function(a,r){return a===r},jEWps:function(a,r){return a>>>r},kjHKV:function(a,r){return a>>>r},LIQvz:function(a,r){return a+r},vapPd:function(a,r){return a>>>r},qFztV:function(a,r){return a+r},ayzIN:function(a,r){return a>>>r},EdxHK:function(a,r){return a|r},JrJVZ:function(a,r){return a<<r},JzYdP:function(a,r){return a!==r},vzmOj:function(a,r){return a===r},HScoE:function(a,r){return a>>>r},wAFcs:function(a,r){return a===r},AXrGx:function(a,r){return a===r},HisFJ:function(a,r){return a&r},wjczI:function(a,r){return a&r},KNxpk:function(a,r){return a>>>r},XTuRz:function(a,r){return a&r},ZwUVR:function(a,r){return a>>>r},yNBgF:t(1251)+t(909),dHIJt:t(396)+t(1086)+"R",MslKC:t(821)+t(500),gyJKw:t(1216)+"NG_ERROR",FvrWr:t(911)+"OR",tPnGA:t(1365)+t(900),MCSpQ:t(1560)+"1",zOCrJ:t(662),QMqUs:t(487),yRSRu:function(a,r){return a===r},HTQjJ:function(a,r){return a===r},ZoteJ:function(a,r){return a==r},wOEbk:function(a,r){return a>r},hOXIS:function(a,r){return a===r},Fzmfc:function(a,r){return a instanceof r},VCrRE:function(a,r){return a+r},xqfaM:t(794)+t(836),jkBkJ:function(a,r){return a+r},OAWPB:function(a,r){return a===r},GCnBE:"HHAEY",OIWUj:function(a,r){return a===r},sfGKQ:t(1104),kdwsh:t(382),sadgT:t(961),XZmPz:t(718),HzMVS:function(a,r){return a+r},aWjrM:t(383),Eslpv:function(a,r,o){return a(r,o)},kLYPw:function(a,r){return a&r},OjKuh:"DmcJc",DOUaf:t(1407),NqSma:"3|4|2|0|1",vflAt:function(a,r){return a!=r},uGPoW:"undefined",nLqjZ:"1|2|3|4|0",xaHpp:function(a,r){return a||r},gKzMY:function(a,r){return a!=r},IVjIv:"owyAo",fAdIl:t(689)+"alled mu"+t(610)+t(960)+t(717),OphiV:function(a,r){return a<r},awiKL:function(a,r){return a===r},PDGMf:"zXUAe",ZYENx:function(a,r){return a&r},XYITi:function(a,r){return a<r},BnqZm:function(a,r){return a<r},Bnpoc:function(a,r){return a<=r},FljOm:function(a,r){return a>=r},KnFCt:function(a,r){return a<r},qkUTA:function(a,r){return a>=r},gKdUo:function(a,r){return a<r},LJpXZ:function(a,r){return a&r},CRDVn:function(a,r){return a&r},epAMV:function(a,r){return a<<r},xzXul:function(a,r){return a>>r},ochtC:function(a,r){return a+r},ARsgE:function(a,r){return a&r},djAfx:function(a,r){return a<r},bBNKg:t(403),CuAww:function(a,r){return a<r},cTCQW:function(a,r){return a&r},VQAsM:function(a,r){return a===r},YTkib:function(a,r){return a&r},rWfAQ:function(a,r){return a===r},eVZuC:function(a,r){return a&r},KiqVJ:function(a,r){return a+r},zdshQ:function(a,r){return a+r},uTpgm:function(a,r){return a<<r},DrLsg:function(a,r){return a&r},uYrwo:function(a,r){return a&r},oJUHN:function(a,r){return a>>r},PhPzg:function(a,r){return a|r},fOvQh:function(a,r){return a&r},TnsRG:function(a,r){return a>>r},DwkqW:function(a,r){return a|r},EmGPB:function(a,r){return a|r},nVSse:t(1198),sIacP:function(a,r,o,l){return a(r,o,l)},dDdmy:function(a,r){return a instanceof r},dhjfi:function(a,r){return a&r},GQsBx:function(a,r,o,l){return a(r,o,l)},OBMFn:t(939),ubGJU:function(a,r){return a instanceof r},ilXyN:"applicat"+t(152),qQbxh:function(a,r){return a==r},gibqQ:"text/pla"+t(173)+t(644),rbRYz:t(174),bCdUu:t(432),mvHpd:function(a,r){return a>=r},DQAIW:function(a,r){return a(r)},NwEIL:"script",lCKUq:t(1557)+t(1103),KtHlX:function(a,r){return a===r},JoLkl:"RbzdT",XWmrD:function(a,r){return a(r)},ADjmS:t(608)+t(954),uOqyH:function(a,r){return a instanceof r},tlRew:t(1321)+t(152)+";charset"+t(210),qzoPr:t(554)+"e",yXiLO:t(1515),xArno:"idb",fWGDm:function(a,r,o,l){return a(r,o,l)},BiFsU:function(a,r){return a===r},Ekrzi:function(a,r){return a!==r},uqCeT:t(922),zkzFR:t(683),eXwnX:function(a,r){return a||r},cpUvn:t(1612)+t(585)+"d",SKBlx:function(a,r){return a!==r},vOuto:"VchRI",ZMsxM:function(a,r){return a||r},SmwPd:function(a,r){return a||r},IVUZc:function(a,r){return a||r},qfzsF:function(a,r){return a||r},FaXcS:function(a,r){return a>r},zeOTr:function(a,r){return a+r},AlbBV:"FIuel",Aeycv:"reconnect",nAbRV:t(1567),dURnS:function(a,r){return a===r},ECXLe:t(307),rJcIZ:function(a,r){return a||r},IsMYS:function(a,r){return a||r},dPaZf:function(a,r){return a||r},BoAzb:"tspVo",LsZkk:function(a,r){return a||r},UxccC:function(a,r){return a||r},mFlbY:t(1390),IgYpU:t(1152)+"id",aYFlx:function(a,r){return a==r},Qypie:t(947),xuShL:t(216),YRtKl:function(a,r){return a(r)},LvGyC:function(a,r,o,l){return a(r,o,l)},oynpi:"x_fronti"+t(649)+"k",DBarA:t(1291)+"er_ack_m"+t(409),NXhvT:t(1115),DNnyK:function(a,r,o,l){return a(r,o,l)},CesLC:function(a,r){return a&&r},UsQil:t(1235),gvNuD:t(1463),bRCop:function(a,r){return a||r},eeblC:t(751),jVPVq:t(600),kbiVT:function(a){return a()},SdAEQ:function(a,r){return a||r},qemaz:function(a,r){return a(r)},RyYmV:function(a,r){return a instanceof r},HqXuH:t(845),Gntqa:"wYHea",LDJvX:function(a,r){return a instanceof r},tnfKL:function(a,r,o,l){return a(r,o,l)},fXrcL:function(a,r){return a<r},UWdmQ:function(a,r){return a>r},LQXKq:function(a,r){return a!==r},ElUgz:t(1441),CamWZ:function(a,r){return a(r)},RnxfK:function(a,r){return a>>>r},pqqVV:function(a,r){return a(r)},htVPC:function(a,r){return a+r},pwwxY:function(a,r){return a+r},YManW:function(a,r){return a+r},eeoOr:t(978)+t(442)+t(652),JFPzK:t(1507),XjOaI:t(1040),DtCyt:t(636),JCOjc:"fwXLZ",CXoun:"integer "+t(1622)+"e",AEmal:function(a,r){return a&r},HUxSw:function(a,r,o,l){return a(r,o,l)},VvNbW:function(a,r){return a+r},OPkBM:function(a,r){return a!==r},pYloW:function(a,r,o){return a(r,o)},pJIfN:function(a,r,o){return a(r,o)},qLmNf:function(a,r){return a+r},LaQlV:function(a,r){return a!==r},RISlF:t(1181),CdhuI:"pvVSL",oOtaq:function(a,r,o){return a(r,o)},oZjvJ:function(a,r){return a>>>r},GsqJR:function(a,r){return a+r},xVNTw:function(a,r){return a|r},yzwBj:function(a,r){return a|r},UZlQk:function(a,r){return a+r},mnqiz:function(a,r){return a+r},pUwCv:function(a,r){return a+r},PraMD:function(a,r){return a<<r},SZtgj:function(a,r){return a+r},VppMB:function(a,r){return a<<r},rpBDl:function(a,r){return a+r},hkPGh:function(a,r){return a+r},ZsPlY:function(a,r){return a&r},ythyA:function(a,r){return a>>>r},gXBoB:function(a,r){return a+r},kusSd:function(a,r){return a>>>r},kmyyc:function(a,r){return a+r},zVVqE:function(a,r){return a&r},AyDYv:function(a,r){return a>>>r},DYLhE:function(a,r){return a&r},gKTBE:function(a,r){return a+r},IYgXe:function(a,r){return a&r},GJvBa:function(a,r){return a<r},PVjHd:function(a,r){return a>>>r},EOVsT:t(199),IeOXf:t(458)+t(825)+t(415)+"4",vCvrX:function(a,r){return a|r},XniAg:function(a,r){return a>>>r},MYrGr:function(a,r){return a|r},ipbjl:function(a,r){return a&r},eoupI:function(a,r){return a<r},FJwFw:function(a,r){return a+r},cuHtY:function(a,r){return a(r)},Mzkzb:t(870),sUEiy:"10|6|5|3"+t(1077)+"|2|4|0",wbgHY:t(1021),HzVTI:function(a,r,o,l){return a(r,o,l)},EaquX:t(1370),cUuTe:"service-"+t(1021),OhyeS:function(a,r){return a(r)},uIddF:t(793)+t(491),AWGxj:t(314),SYalB:function(a,r,o){return a(r,o)},VCczh:function(a,r){return a+r},xLPSi:function(a,r,o){return a(r,o)},xYzDb:t(641)+t(260),IsOnl:function(a,r){return a===r},nEKQM:t(1109),dJtfA:t(767),PrVYM:function(a,r){return a(r)},VCJLA:t(267),LzXPu:t(619),sJQfU:t(1438),pVLqH:function(a,r,o,l){return a(r,o,l)},XGKSU:function(a){return a()},gebVn:function(a,r){return a(r)},FamaF:"setcursor",BmrlI:function(a,r){return a||r},eHDct:function(a,r){return a+r},nMmxY:t(965),WHIuO:t(1291)+t(800),dmiEY:function(a,r){return a(r)},wIntA:t(1291)+t(1584),GuEJT:"x-msg-qos",YarZG:t(804)+"rsor_name",JuLbv:t(804)+t(558)+"ue",UcrZf:function(a){return a()},bRpTx:function(a,r){return a+r},flfzT:function(a){return a()},bfKRn:t(1385),FlEGY:function(a){return a()},YByfl:function(a){return a()},pkEFO:function(a,r){return a|r},UsesI:function(a,r){return a<<r},hQXHJ:function(a,r){return a&r},zkcEL:function(a,r){return a>=r},Vlvrr:function(a,r){return a(r)},mtJrE:function(a){return a()},voVoM:function(a,r,o){return a(r,o)},xZOJj:function(a){return a()},uSajT:t(337),RwWTj:function(a){return a()},GeDNV:function(a,r){return a(r)},Vwvhr:function(a,r){return a!==r},bBqIJ:function(a,r){return a<r},pujLN:function(a,r){return a===r},YbMLC:"Tvadq",tUgBs:function(a,r,o){return a(r,o)},PITMZ:function(a){return a()},iDfkL:t(886),YbFLz:t(1504),vnFEc:t(827),nuoZJ:function(a,r,o,l){return a(r,o,l)},ByuRW:t(852),wgsjB:function(a,r){return a===r},sxDlK:t(1257),TCkTd:t(371)+t(958)+"s",wktIh:function(a,r,o,l){return a(r,o,l)},tApBA:function(a,r,o){return a(r,o)},EQrIr:function(a,r){return a!==r},XFvMs:t(956),luvTS:"bye",vTsdF:t(732),VXphl:function(a,r,o){return a(r,o)},WkxYM:t(880),wFgPz:function(a,r){return a/r},bwxSj:function(a,r){return a==r},zZiNd:t(1113)+t(798)+"alid url",xAEmI:"please p"+t(768)+"s params"+t(681)+t(1363)+t(1351)+"is undefined",GIDkp:t(288),SwxKN:t(1371),sfLtD:"offline",oeoqY:t(1606),tolox:t(904),tJQus:function(a,r){return a||r},nUzEv:function(a,r){return a!==r},gTJGV:"pOXzN",mybup:function(a,r){return a!==r},ELHbH:function(a,r){return a+r},lEUMV:function(a,r){return a&r},sVCaW:function(a,r){return a<r},tqqAt:function(a,r){return a>r},YcvrQ:function(a,r){return a&r},pTiuZ:t(204),vaALk:t(630),njRJY:function(a,r){return a==r},dVYEl:t(747),NvTlQ:t(1451),IIlPm:t(614),fFFmp:t(1160),rVEMk:function(a,r){return a==r},YcBBz:t(679),TcuDg:function(a){return a()},QqJeK:function(a,r,o){return a(r,o)},UUBRA:"web",DwJce:"fws_1.0.0",Colsk:t(317),MKpIq:function(a,r){return a||r},OJtgH:function(a,r,o){return a(r,o)},mdVPJ:function(a,r){return a>r},DATPJ:function(a,r,o){return a(r,o)},BuwTU:function(a,r,o){return a(r,o)},AiXwO:function(a,r){return a(r)},wslSR:"FRONTIER>",mSHsq:function(a,r){return a-r},MQYct:function(a,r){return a===r},QufVo:t(371)+"e_timeout",rJsQs:t(1467),VLzYu:t(1123)+t(1062)+"reconnec"+t(606)+t(628),IGtyc:t(444)+t(428)+t(189)+"g",QtWnS:function(a,r){return a(r)},FSANm:function(a,r){return a===r},fNbjt:t(1359),oeqNW:function(a,r){return a!==r},YkWRN:t(1324),jlEky:t(621),okKgs:function(a,r){return a===r},CvUhw:t(230),ecTBN:"going aw"+t(354)+t(705)+"ine",xQVkL:function(a,r){return a!==r},QUwOm:t(381),Aflnn:function(a,r,o){return a(r,o)},vcath:t(774),eqlsM:t(1410),dXWJH:function(a,r){return a+r},cqsQH:"lQFqG",xYFml:t(1510)+t(1244),EsesD:function(a,r){return a===r},Vitrj:"close, ws instance not i"+t(1573)+"ed",iHQFR:function(a,r){return a==r},MdzwS:"please provide a"+t(858)+t(1079)+"a must b"+t(1102)+"ng or an"+t(1084)+t(1325),ofURq:function(a,r){return a(r)},imKWZ:function(a,r){return a||r},PBejL:function(a,r){return a instanceof r},rxdIm:function(a,r){return a(r)},erByG:t(1130),GkPFN:t(1143)+"econnecting",nynlB:function(a,r){return a!==r},gXGpk:t(657),QQEdL:"piRGl",mwSek:t(574)+"2",SKCnV:function(a,r){return a(r)},WnxSF:function(a,r,o){return a(r,o)},sJgcR:t(1614),HIYjp:function(a,r){return a*r},fzpuW:function(a,r){return a/r},cPjBI:function(a,r){return a!=r},nVMvW:function(a,r){return a===r},UVpCO:t(1295),zqWIb:function(a,r){return a!=r},vbGrR:t(1615)+"dWorkerG"+t(974)+"pe",Lsonx:t(1399),AgtKl:"SharedWo"+t(509)+t(282),ixKLM:"ServiceW"+t(315)+t(987),oJQCO:function(a,r){return a===r},ukIoj:function(a,r){return a!=r},qNFDD:function(a,r){return a!=r},GEPSk:function(a,r,o){return a(r,o)},SoHii:t(802)+t(557)};Bt.r(Ce),Bt.d(Ce,{FWS:()=>_g,CustomErrorEvent:()=>nl,createCloseEvent:()=>gt,ReconnectEvent:()=>tl,createErrorEvent:()=>at,decodedFrame:()=>tn,createOpenEvent:()=>cl,CustomCloseEvent:()=>rl,createReconnectEvent:()=>ua,FrontierMessageEvent:()=>sl,encodeFrame:()=>Ut,createMessageEvent:()=>al,OpenEvent:()=>ol,ErrorCode:()=>rn,Event:()=>nr,MessageEvent:()=>il});let n="";function i(a=""){let r=t,o="02",l=""+Date[r(275)](),f=n||(n=h(a)),m=Math[r(304)]()[r(867)](16).slice(-6);return e[r(623)](e[r(953)](e[r(953)](o,l),f),m)}function s(){let a=t,r={CKktn:e[a(533)]};if(e.pUuUC(e[a(1513)],a(1416)))return e[a(953)](e[a(167)](1e4,Date.now()),Math[a(144)](e[a(167)](1e4,Math[a(304)]())));this[a(438)](r.CKktn,_0x3488e1(a(1284),{message:this[a(293)+"rrorMess"+a(540)](_0x3a205c)}))}function c(a){let r=t;return e[r(623)](e.YVSAB(Array,8).join("0"),e[r(306)](parseInt,a,10)[r(867)](2))[r(1097)](-8)}function d(a){let r=t;return e[r(623)](e[r(761)](Array,4)[r(1297)]("0"),e[r(306)](parseInt,a,2).toString(16))[r(1097)](-4)}function u(a){let r=t,o=a.split(/\./).map(m=>c(m)),l=[];return l[0]=e[r(761)](d,o[0]+o[1]),l[1]=e[r(1353)](d,e[r(1053)](o[2],o[3])),[e[r(253)],e[r(253)],e[r(253)],r(1433),r(1433),e.tKOBi,l[0],l[1]][r(1297)]("")}function h(a){let r=t,o=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.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]))/[r(945)](a);return o?e[r(256)](u,a):l?e[r(256)](x,a):e[r(730)]}function x(a){let r=t,o={oqIyp:function(T,L,N){return e[j(324)](T,L,N)},dzxqT:e[r(446)]},l="",f=[],m=0,_=0,b=!0,p=r(1433);if(e[r(996)](a[r(898)]("::"),-1)){let T=a[r(1431)]("::");for(let N=0;e.hReMp(N,T[r(1421)]);N++){let G=T[N];if(e[r(1199)](G.indexOf(":"),0)){let q=G[r(1431)](":");b&&(m=q.length),_+=q.length;for(let J=0;e[r(1042)](J,q[r(1421)]);J++)if(q[J][r(1421)]!==4){let Xe=p[r(1054)+"g"](0,e[r(664)](4,q[J][r(1421)])),ct=Xe[r(569)](q[J]);f[r(527)](ct)}else f.push(q[J]);b=!1}else{if(e[r(1242)](4,G.length)){let q=p[r(1054)+"g"](0,e[r(622)](4,G[r(1421)])),J=q[r(569)](G);f[r(527)](J)}else f.push(G);b&&(m+=1),_+=1,b=!1}}let L="";for(let N=0;e.hReMp(N,8-_);N++)L=L[r(569)](p);for(let N=0;e[r(1020)](N,f[r(1421)]);N++)e[r(818)](N,m)?e.WIjTn(e[r(145)],e.mXcWa)?(l=l[r(569)](L),l=l.concat(f[N])):(this[r(1148)+r(237)]=_0x1a9d5d,this[r(1183)+r(232)]=_0x549660,this["_message"+r(1544)]=_0x286c83,this._qosDB=o[r(1145)](_0x70e471,this["_cursorN"+r(237)],o.dzxqT)):l=l.concat(f[N]);return l}{let T=a[r(1431)](":");for(let L=0;e[r(302)](L,T[r(1421)]);L++){let N=T[L];if(e[r(155)](4,T[L].length)){let G=p.substring(0,e[r(664)](4,T[L][r(1421)])),q=G.concat(N);l=l[r(569)](q)}else l=l[r(569)](N)}return l}}function g(a,r){let o=t,l=a[o(1402)];e[o(426)](void 0,l)&&(e.MIiNQ(pe,r,10),e[o(1563)](U,r,l));let f=a.value;e[o(1583)](void 0,f)&&(pe(r,18),e[o(392)](U,r,f))}function w(a){let r=t,o={RVAsI:function(l,f){return l||f}};if(e.enxpp(e[r(943)],e.kUdfi)){let l={};e:for(;!e[r(1036)](V,a);){let f=e[r(761)](xe,a);switch(e.urgJs(f,3)){case 0:break e;case 1:l[r(1402)]=P(a,e[r(647)](xe,a));break;case 2:l[r(1362)]=e[r(370)](P,a,e[r(588)](xe,a));break;default:e[r(392)](R,a,e.cRjPc(7,f))}}if(l[r(1402)]===void 0)throw new Error(e.GJDok);if(e.ezfvp(void 0,l[r(1362)]))throw new Error(e[r(1531)]);return l}else{let l=this[r(849)][r(881)](this[r(213)]),f=_0x2103cc.parse(o.RVAsI(l,"{}"));return f[_0x3afa7f||_0x18dc79[this[r(651)]]]=_0x34ebd0,this[r(849)][r(433)](this[r(213)],_0x5e1908[r(240)+"y"](f)),_0x56438a||_0x761337[this[r(651)]]}}function S(a){let r=t,o=e[r(807)](C);return e[r(1477)](y,a,o),B(o)}function y(a,r){let o=t,l={ggtpW:function(f,m){return e[j(1353)](f,m)},WauFW:function(f,m){return e[j(255)](f,m)},HKumH:function(f,m){return e[j(1150)](f,m)},FOJWa:function(f,m,_){return e[j(847)](f,m,_)},nExag:e[o(1186)],KDdUL:function(f,m,_){return e[o(847)](f,m,_)}};if(e[o(1338)](e.ckZxX,e.ckZxX)){let f=a.SeqID;f!==void 0&&(e.gPWNT(pe,r,8),e[o(1404)](pt,r,f));let m=a[o(1074)];e[o(1583)](void 0,m)&&(e[o(1583)](e[o(599)],e[o(241)])?(pe(r,16),pt(r,m)):(_0x8d12f8=l[o(1022)](_0x211e61,_0xb564d0),_0xd0f327|=l[o(1349)](l.HKumH(127,_0x1a24d0),7)));let _=a[o(949)];e[o(1057)](void 0,_)&&(pe(r,24),e[o(1477)](pt,r,e.Zimex(D,_)));let b=a[o(833)];b!==void 0&&(e[o(284)](pe,r,32),e[o(1404)](pt,r,e[o(154)](D,b)));let p=a.headers;if(e[o(975)](void 0,p))for(let ct of p){e[o(392)](pe,r,42);let It=C();g(ct,It),e[o(1168)](pe,r,It[o(1234)]),e.XJaBs(K,r,It),e[o(559)](O,It)}let T=a[o(1173)+"ncoding"];e[o(1242)](void 0,T)&&(e.fSyfG(pe,r,50),U(r,T));let L=a.payloadType;e.BoeiB(void 0,L)&&(e[o(1563)](pe,r,58),U(r,L));let N=a[o(914)];e[o(1282)](void 0,N)&&(e.jFULC(pe,r,66),pe(r,N[o(1421)]),oe(r,N));let G=a[o(484)];if(e.oDoed(void 0,G)){if(e[o(182)]!=="PWVdl")return _0x1753ef[o(455)+"8"]?{value:_0x2ba56b[o(455)+"8"](_0x2df61e),offset:_0x301cbb+1}:{value:e[o(281)](255,_0x20719f[_0x478be9]),offset:e[o(623)](_0x516f8c,1)};pe(r,74),e[o(169)](U,r,G)}let q=a[o(913)+o(779)];q!==void 0&&(e[o(818)](e[o(1601)],e.tYuuQ)?(_0x2ab72d(_0x1c3ed7,74),l.FOJWa(_0x3a0a0e,_0x57a72f,_0x5153e9)):(e.bGttz(pe,r,82),U(r,q)));let J=a[o(878)];e[o(1242)](void 0,J)&&(e.pSYUg(pe,r,90),e[o(472)](U,r,J));let Xe=a[o(330)+"e"];e.xSAfc(void 0,Xe)&&(pe(r,96),e[o(549)](pt,r,e[o(639)](D,Xe)))}else this[o(438)](l[o(810)],l[o(385)](_0x47dbe2,"message",{..._0x1f961a}))}function v(a){return I(e.Zimex(F,a))}function I(a){let r=t,o={};e:for(;!e[r(355)](V,a);){let l=e[r(355)](xe,a);switch(e.urgJs(l,3)){case 0:break e;case 1:o.SeqID=St(a,!0);break;case 2:o[r(1074)]=e[r(771)](St,a,!0);break;case 3:o[r(949)]=e[r(1333)](xe,a);break;case 4:o.method=e[r(148)](xe,a);break;case 5:{let f=e.rZkDD(A,a);(o[r(944)]||(o[r(944)]=[]))[r(527)](e[r(559)](w,a)),a.limit=f;break}case 6:o["payloadE"+r(1134)]=P(a,e[r(915)](xe,a));break;case 7:o[r(538)+r(576)]=e.ncjGN(P,a,e[r(1197)](xe,a));break;case 8:o[r(914)]=e[r(546)](se,a,e.whLrk(xe,a));break;case 9:o.LogIDNew=e[r(1303)](P,a,e[r(761)](xe,a));break;case 10:o[r(913)+r(779)]=P(a,e[r(465)](xe,a));break;case 11:o[r(878)]=P(a,e[r(377)](xe,a));break;case 12:o.frameType=e[r(408)](xe,a);break;default:e[r(1530)](R,a,7&l)}}if(e[r(1032)](void 0,o[r(268)]))throw new Error(r(1596)+r(1429)+r(840)+"SeqID");if(e[r(912)](void 0,o[r(1074)]))throw new Error(e.JUuwV);if(o.service===void 0)throw new Error(e.gKjwf);if(e[r(1338)](void 0,o.method))throw new Error(e[r(1187)]);return o}function A(a){let r=t,o=xe(a),l=a[r(1234)];return a[r(1234)]=e[r(953)](a.offset,o),l}function R(a,r){let o=t;switch(r){case 0:for(;e[o(281)](128,e.niYDa(te,a)););break;case 2:Y(a,e.AoezV(xe,a));break;case 5:e[o(700)](Y,a,4);break;case 1:e.uFXEr(Y,a,8);break;default:throw new Error(e[o(572)](e[o(1448)],r))}}function D(a){return a|=0,{low:a,high:a>>31,unsigned:a>=0}}let E=[];function C(){let a=t,r=E[a(1207)]();return r?(r[a(1204)]=r[a(1234)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){E[t(527)](a)}function F(a){return{bytes:a,offset:0,limit:a[t(1421)]}}function B(a){let r=t,o=a[r(1609)],l=a.limit;return e[r(1299)](o[r(1421)],l)?o:o.subarray(0,l)}function Y(a,r){let o=t;if(e[o(563)](e.fEXXv(a[o(1204)],r),a[o(1234)]))throw new Error(o(1445)+o(759));a[o(1204)]+=r}function V(a){let r=t;return e[r(151)](a[r(1204)],a[r(1234)])}function re(a,r){let o=t,l=a.bytes,f=a.offset,m=a[o(1234)],_=e[o(1287)](f,r);if(e[o(1440)](_,l.length)){let b=new Uint8Array(e[o(167)](2,_));b[o(769)](l),a[o(1609)]=b}return a[o(1204)]=_,e[o(1469)](_,m)&&(a.limit=_),f}function X(a,r){let o=t;if(e[o(912)](e[o(1085)],o(1540))){let l=a[o(1204)];if(e.BXeTK(l+r,a[o(1234)]))throw new Error(o(1320)+o(759));return a.offset+=r,l}else e[o(1149)](_0x575ed5,this,_0x57ec1e,[_0x15de37,_0x7d8aed,_0x4dc3d4])}function se(a,r){let o=t,l=X(a,r);return a[o(1609)][o(205)](l,l+r)}function oe(a,r){let o=t,l=e[o(1530)](re,a,r.length);a[o(1609)].set(r,l)}function P(a,r){let o=t,l=e[o(283)](X,a,r),f=String[o(1437)+o(209)],m=a.bytes,_="\uFFFD",b="";for(let p=0;e[o(1042)](p,r);p++){let T=m[e[o(577)](p,l)],L,N,G,q;if(e[o(1299)](128&T,0))b+=e[o(256)](f,T);else if(e[o(1279)](224&T,192))e[o(404)](e.GoQpZ(p,1),r)?b+=_:(L=m[e[o(757)](p+l,1)],e.ElPuD(e[o(281)](192,L),128)?b+=_:(q=e[o(353)](e[o(224)](31&T,6),e[o(1150)](63,L)),q<128?b+=_:(b+=e[o(639)](f,q),p++)));else if(e.FRsKu(e[o(1150)](240,T),224))if(e[o(953)](p,2)>=r)b+=_;else if(e[o(1005)](e[o(1256)],e[o(1256)]))L=m[p+l+1],N=m[e[o(429)](p+l,2)],e.TRjis(e[o(353)](L,e[o(412)](N,8))&49344,32896)?b+=_:(q=e[o(353)](e[o(1155)](e[o(1010)](e[o(1008)](15,T),12),e[o(255)](e[o(1008)](63,L),6)),e[o(1182)](63,N)),q<2048||q>=55296&&e[o(1387)](q,57343)?b+=_:(b+=e[o(148)](f,q),p+=2));else return this._isMiniTT||this[o(775)+"X"]?this["_miniNav"+o(1081)+o(373)]:(this[o(562)+"er"]||this._isWorker)&&this[o(388)][o(519)+"tworkCha"+o(1442)]?_0x47dd27.onLine:!0;else e.VcjJi(e[o(1008)](248,T),240)?e.AkbdY(p,3)>=r?b+=_:(L=m[e.bMEZv(p+l,1)],N=m[e[o(1180)](e[o(235)](p,l),2)],G=m[e[o(504)](e.Vhgjn(p,l),3)],e.nIOqI(e[o(666)](e[o(1499)](L,e[o(255)](N,8)),G<<16),12632256)!==8421504?b+=_:(q=e[o(666)](e[o(353)](e.FbiTh(e[o(1117)](7&T,18),e.afxYB(63&L,12)),e[o(412)](e.nIOqI(63,N),6)),63&G),e[o(512)](q,65536)||e.TcxKo(q,1114111)?b+=_:(q-=65536,b+=e[o(815)](f,e[o(466)](q,10)+55296,e[o(891)](1023,q)+56320),p+=3))):b+=_}return b}function U(a,r){let o=t,l={fNnUb:function(f,m){return e[j(389)](f,m)},AjXRz:function(f,m,_){return e[j(169)](f,m,_)},LxkpT:function(f,m){return e[j(706)](f,m)},TuaRf:function(f,m){return e[j(1150)](f,m)}};if(e[o(176)]!==o(1471)){for(_0x326a3a>>>=0;l[o(1236)](_0x10d256,128);)l[o(1561)](_0x5b1161,_0x146142,l[o(1038)](l.TuaRf(127,_0x108bea),128)),_0x1c9149>>>=7;l[o(1561)](_0x4283aa,_0x198784,_0x41258c)}else{let f=r[o(1421)],m=0;for(let p=0;e[o(1020)](p,f);p++){let T=r.charCodeAt(p);e[o(389)](T,55296)&&e[o(1381)](T,56319)&&e[o(1357)](p,1)<f&&(T=e[o(424)](T,10)+r[o(738)+"At"](++p)-56613888),m+=e[o(1058)](T,128)?1:T<2048?2:e.AxySB(T,65536)?3:4}e.wPLNm(pe,a,m);let _=re(a,m),b=a[o(1609)];for(let p=0;e[o(715)](p,f);p++){let T=r[o(738)+"At"](p);if(e[o(1153)](T,55296)&&e[o(1387)](T,56319)&&e[o(302)](e[o(518)](p,1),f)&&(T=e.nKbQb(e.APygU(T,10),r[o(738)+"At"](++p))-56613888),e[o(1042)](T,128))b[_++]=T;else if(e[o(1005)](e.jnmMm,e[o(936)]))T<2048?b[_++]=e.htELm(e[o(635)](e[o(466)](T,6),31),192):(e[o(548)](T,65536)?b[_++]=e.GtxfO(e.CqyfU(T,12)&15,224):(b[_++]=e[o(1007)](e[o(335)](T>>18,7),240),b[_++]=e[o(875)](e[o(466)](T,12)&63,128)),b[_++]=e.CqyfU(T,6)&63|128),b[_++]=e[o(875)](63&T,128);else{if(e[o(1381)](_0x3497da,-_0x46b94c))return _0x9cc609;if(e[o(151)](e[o(439)](_0x34824d,1),_0x56ea03))return _0x39489b}}}}function K(a,r){let o=t,l=e[o(1063)](re,a,r.limit),f=a[o(1609)],m=r[o(1609)];for(let _=0,b=r.limit;_<b;_++)f[e[o(757)](_,l)]=m[_]}function te(a){let r=t;if(e[r(359)](e[r(964)],e[r(964)]))return a.bytes[e[r(1303)](X,a,1)];_0x454abc(_0x4f2c74,16),e.pSYUg(_0x3ccf28,_0x23a092,_0x1a063a)}function Ze(a,r){let o=t,l=e[o(290)](re,a,1);a.bytes[l]=r}function xe(a){let r=t,o=0,l=0,f;do f=e[r(417)](te,a),e[r(906)](o,32)&&(l|=e[r(514)](e.ewLFd(127,f),o)),o+=7;while(e[r(1278)](128,f));return l}function pe(a,r){let o=t;for(r>>>=0;e.EPzon(r,128);)Ze(a,e[o(891)](127,r)|128),r>>>=7;e[o(333)](Ze,a,r)}function St(a,r){let o=t,l={GzDaS:function(p,T){return p!=T},kXLOC:function(p,T){return e.bXaKU(p,T)},FmIZi:function(p,T){return e[j(1542)](p,T)},krYCd:o(1198),WleCp:function(p,T){return e.nMGZV(p,T)}},f=0,m=0,_=0,b;if(b=te(a),f=127&b,e[o(720)](128,b)&&(b=e[o(272)](te,a),f|=e[o(589)](127,b)<<7,128&b&&(b=e.amVVo(te,a),f|=e.eSunU(e[o(245)](127,b),14),e[o(328)](128,b)&&(b=e[o(537)](te,a),f|=e.AnBPE(e[o(1420)](127,b),21),e[o(635)](128,b)&&(b=te(a),m=127&b,128&b&&(b=e[o(581)](te,a),m|=e[o(762)](e.iNWES(127,b),7),e.PldtD(128,b)&&(b=e[o(990)](te,a),m|=e.IwmjF(e[o(335)](127,b),14),e[o(1120)](128,b)&&(b=e[o(289)](te,a),m|=e.CNOFU(127&b,21),e[o(860)](128,b)&&(b=e[o(231)](te,a),_=127&b,e[o(1427)](128,b))))))))))if(e[o(1306)](e[o(1034)],e[o(1034)]))b=te(a),_|=e.Ijfkg(e.HliCF(127,b),7);else try{return l[o(580)](o(1198),typeof _0x345ff0)&&(l[o(1586)](_0x548006,_0xc6f955)||_0xa1acb9[o(890)]&&l[o(1500)](_0x7e5a28[o(890)],_0x3583f8))||l[o(1027)]!=typeof _0x1ea47e?"":(_0xd24eb6.parse(_0x5652a1),o(1321)+"ion/json")}catch{return l[o(1446)]("string",typeof _0x430508)?o(318)+o(173)+o(644):""}return{low:f|m<<28,high:e.JGLvB(e[o(1272)](m,4),e.bzZXi(_,24)),unsigned:r}}function pt(a,r){let o=t;if(e[o(818)](e[o(1142)],e[o(1142)])){let l=e[o(1272)](r.low,0),f=(e[o(1286)](r.low,28)|e[o(1304)](r[o(701)],4))>>>0,m=e.etfvG(r[o(701)],24),_=e[o(1618)](0,m)?e[o(1005)](0,f)?l<16384?l<128?1:2:e[o(368)](l,2097152)?3:4:e[o(906)](f,16384)?e[o(1058)](f,128)?5:6:e[o(906)](f,2097152)?7:8:e[o(548)](m,128)?9:10,b=e[o(815)](re,a,_),p=a[o(1609)];switch(_){case 10:p[b+9]=e[o(1395)](e[o(611)](m,7),1);case 9:p[e[o(229)](b,8)]=e[o(587)](9,_)?128|m:e[o(1158)](127,m);case 8:p[e[o(1287)](b,7)]=e[o(1177)](8,_)?e.JGLvB(e[o(665)](f,21),128):e[o(1107)](e[o(1222)](f,21),127);case 7:p[b+6]=e[o(998)](7,_)?e[o(1208)](e[o(969)](f,14),128):e[o(860)](e[o(611)](f,14),127);case 6:p[e[o(439)](b,5)]=e[o(418)](6,_)?e[o(384)](e.KVWIO(f,7),128):e[o(1184)](e[o(1578)](f,7),127);case 5:p[b+4]=_!==5?e[o(1208)](128,f):e[o(988)](127,f);case 4:p[b+3]=e[o(876)](4,_)?e[o(384)](e.etfvG(l,21),128):e[o(860)](l>>>21,127);case 3:p[e.HauVT(b,2)]=e[o(785)](3,_)?e[o(421)](e[o(1164)](l,14),128):e.lxEel(l,14)&127;case 2:p[e[o(572)](b,1)]=e[o(426)](2,_)?e[o(421)](l>>>7,128):e[o(187)](e[o(1348)](l,7),127);case 1:p[b]=_!==1?e.SvCxH(128,l):e[o(589)](127,l)}}else return _0x2b084f[o(159)]()}function tn(a){return v(a)}function Ut(a){let r=t;return e[r(934)](e.jXYCm,e[r(158)])?e[r(1233)](S,a):null}let nn=65536,Zr=e.sJgcR,_e=e[t(474)](nn,nn),Ae=e[t(594)](_e,_e),tr=e[t(977)](Ae,2),Oe=String[t(829)+"e"][t(738)+"At"];class fe{constructor(r,o,l){let f=t;this[f(488)]=!0,this[f(1111)]=e.AYvjO(0,r),this.high=e.htELm(0,o),this[f(931)]=!!l}static isLong(r){let o=t,l={TkmLM:function(f,m){return e[j(387)](f,m)}};if(e.tenEu(e[o(792)],e[o(792)])){let f=this[o(849)].getItem(this[o(213)]),m=_0x1628d2[o(1305)](l[o(746)](f,"{}"));return _0x406b03[o(755)](m)}else return r&&e[o(1296)](!0,r.isLong)}static[t(505)](r,o,l){return new fe(r,o,l)}static[t(351)+"s"](r,o,l){let f=t;return l?fe[f(351)+"sLE"](r,o):fe[f(351)+f(903)](r,o)}static["fromByte"+t(778)](r,o){let l=t;return new fe(e[l(735)](e[l(421)](r[0],e.rFmhc(r[1],8))|r[2]<<16,e[l(406)](r[3],24)),e.ZRWzP(e[l(1129)](e[l(1302)](r[4],e[l(460)](r[5],8)),e[l(940)](r[6],16)),e[l(762)](r[7],24)),o)}static[t(351)+"sBE"](r,o){let l=t,f={jDVrp:function(m,_){return e.JnKIN(m,_)}};if(e.NnAOz(l(1548),l(1548)))return new fe(e[l(1302)](e[l(976)](e[l(1499)](r[4]<<24,e[l(1117)](r[5],16)),e[l(1405)](r[6],8)),r[7]),e[l(1049)](e[l(1541)](e[l(595)](r[0],24),r[1]<<16)|r[2]<<8,r[3]),o);if(f.jDVrp(_0x1ce982,_0x193c7e))return _0x2e5e39}static fromHash(r){let o=t;return r===Zr?el:new fe(e[o(1164)](e[o(735)](e[o(1623)](Oe.call(r,0)|Oe[o(525)](r,1)<<8,e[o(702)](Oe[o(525)](r,2),16)),e[o(412)](Oe[o(525)](r,3),24)),0),e[o(1286)](e[o(907)](e.DIXlR(Oe.call(r,4),e[o(234)](Oe[o(525)](r,5),8)),e.QTOJM(Oe[o(525)](r,6),16))|Oe[o(525)](r,7)<<24,0),!0)}[t(699)](){let r=t;return String[r(1437)+r(209)](255&this[r(1111)],e[r(1184)](e.urgJs(this[r(1111)],8),255),e[r(1578)](this[r(1111)],16)&255,e.sdkKt(this[r(1111)],24),e[r(1120)](255,this[r(701)]),e[r(891)](e[r(780)](this.high,8),255),e[r(175)](this[r(701)],16)&255,e[r(1578)](this[r(701)],24))}static[t(1318)+"er"](r,o=!0){let l=t;if(e.QjGeq(isNaN,r))return o?Pp:el;if(o){if(r>=Ae)return Op}else{if(e.RUxFv(r,-tr))return Lp;if(e.hqgVx(r+1,tr))return Dp}return fe.fromBits(e[l(1613)](r%_e,0),e[l(503)](r,_e)|0,o)}toNumber(){let r=t;return this[r(931)]?e[r(518)](e[r(594)](e[r(692)](this[r(701)],0),_e),this[r(1111)]>>>0):e[r(596)](this[r(701)]*_e,e[r(692)](this[r(1111)],0))}isZero(){let r=t;return e[r(1327)](0,this[r(701)])&&e[r(1128)](0,this[r(1111)])}[t(1078)](r){let o=t;fe[o(488)](r)||(r=fe[o(1318)+"er"](r));let l=e[o(1272)](this[o(701)],16),f=65535&this[o(701)],m=e[o(367)](this[o(1111)],16),_=e.XLCBd(65535,this[o(1111)]),b=e[o(1116)](r[o(701)],16),p=e[o(860)](65535,r[o(701)]),T=e[o(969)](r[o(1111)],16),L=e[o(720)](65535,r.low),N=0,G=0,q=0,J=0;return J+=e[o(454)](_,L),q+=J>>>16,J&=65535,q+=e[o(1053)](m,T),G+=e[o(201)](q,16),q&=65535,G+=e.qFztV(f,p),N+=e[o(1569)](G,16),G&=65535,N+=l+b,N&=65535,fe[o(505)](e[o(1620)](e.JrJVZ(q,16),J),e[o(1597)](N,16)|G,this[o(931)])}[t(660)](r){let o=t;return fe[o(488)](r)||(r=fe.fromNumber(r)),e[o(1200)](this[o(931)],r[o(931)])&&e[o(1527)](e.HScoE(this[o(701)],31),1)&&e[o(367)](r[o(701)],31)===1?!1:e[o(1308)](this[o(701)],r.high)&&e[o(1127)](this[o(1111)],r.low)}[t(1265)](){let r=t;return e.neYmf(-1,this[r(1111)])&&e.AXrGx(-1,this.high)?fe[r(505)](0,0,this.unsigned):e.MQjBg(-1,this.low)?fe[r(505)](0,e.Ecfld(this[r(701)],1),this[r(931)]):fe[r(505)](e[r(623)](this[r(1111)],1),this[r(701)],this.unsigned)}toBytes(r){let o=t;return r?this[o(1464)+"E"]():this[o(1009)+"E"]()}toBytesLE(){let r=t,o=this[r(701)],l=this[r(1111)];return[e.QjOUv(255,l),e[r(607)](e[r(780)](l,8),255),e[r(1158)](l>>>16,255),e.ZBvBh(l,24),e[r(1395)](255,o),e.wjczI(e.KNxpk(o,8),255),e[r(334)](o,16)&255,e[r(896)](o,24)]}[t(1009)+"E"](){let r=t,o=this[r(701)],l=this[r(1111)];return[e[r(1286)](o,24),e[r(1468)](e.omyuN(o,16),255),e[r(367)](o,8)&255,e[r(187)](255,o),e[r(316)](l,24),e.PldtD(e[r(1578)](l,16),255),l>>>8&255,255&l]}}let el=new fe(0,0,!1),Pp=new fe(0,0,!0),Dp=fe[t(505)](-1,2147483647,!1),Op=fe[t(505)](-1,-1,!0),Lp=fe.fromBits(0,-2147483648,!1);var rn=(function(a){let r=t,o=(r(239)+r(1415)).split("|"),l=0;for(;;){switch(o[l++]){case"0":a[a[e[r(423)]]=5004]=r(1251)+r(909);continue;case"1":a[a[r(396)+"IES_ERROR"]=5003]=e[r(972)];continue;case"2":a[a[e[r(1026)]]=5001]=e[r(1026)];continue;case"3":return a;case"4":a[a[e.gyJKw]=5002]=e.gyJKw;continue;case"5":a[a[e[r(219)]]=5005]=e[r(219)];continue}break}})({});class nr{constructor(r){let o=t;this[o(1460)]=r,this[o(1012)]=null}}class tl extends nr{constructor(r,o){let l=t;super(r),this[l(143)]=o&&o[l(143)]||null}}class nl extends nr{constructor(r,o){let l=t,f=e.tPnGA[l(1431)]("|"),m=0;for(;;){switch(f[m++]){case"0":this.error=o&&o[l(1284)]||null;continue;case"1":this[l(950)]=o&&o[l(950)]||"";continue;case"2":this[l(1590)]=o&&o[l(1590)]||0;continue;case"3":this[l(965)]=o&&o[l(965)]||5001;continue;case"4":this.message=o&&o.message||"";continue;case"5":super(r);continue;case"6":this[l(1366)]=o&&o[l(1366)]||0;continue}break}}}class rl extends nr{constructor(r,o){let l=t,f=e[l(1137)][l(1431)]("|"),m=0;for(;;){switch(f[m++]){case"0":this[l(954)]=o&&o[l(954)]||"";continue;case"1":this[l(1401)+l(494)]=o&&o[l(1401)+l(494)]||!1;continue;case"2":this[l(965)]=o&&o[l(965)]||0;continue;case"3":this[l(471)]=o&&o[l(471)]||!1;continue;case"4":super(r);continue}break}}}class il extends nr{constructor(r,o){let l=t;super(r),this[l(921)]=o&&o.data||null}}class sl extends il{constructor(r,o){let l=t;super(r),this[l(921)]=o&&o[l(921)]||null,this[l(143)]=o&&o[l(143)]||null}}class ol extends nr{constructor(r,o){let l=t,f={zivuq:function(m,_,b){return e[j(1063)](m,_,b)},fqSNM:e[l(533)]};if(e[l(1306)](l(194),e[l(1409)])){let m=f[l(1617)](_0x350741,f.fqSNM,{message:_0x2f3b73[l(143)],code:_0xae43dd.OPEN_ERROR,error:_0x4f606f});this._dispatchErrorEvent(m)}else super(r),this[l(921)]=o&&o.data||null}}function at(a,{message:r,code:o,error:l}){return new nl(a,{message:r,code:o,error:l})}function gt(a,{code:r,reason:o,wasClean:l,willReconnect:f}){return new rl(a,{code:r,reason:o,wasClean:l,willReconnect:f})}function al(a,{data:r,message:o}){return new sl(a,{data:r,message:o})}function cl(a,{data:r}){return new ol(a,{data:r})}function ua(a,{message:r}){return new tl(a,{message:r})}class dl{constructor(r,o){let l=t;this[l(401)+"s"]=r,this.maxRetries=o,this["currentI"+l(575)]=0,this["currentEndpointT"+l(1294)+"t"]=0}[t(183)+t(605)+t(1486)](){let r=t;this["currentI"+r(575)]=0,this[r(379)+r(737)+r(1294)+"t"]=0}[t(806)+"es"](){let r=t;this[r(379)+r(737)+"riesCount"]=0}[t(1017)+t(1422)+"nt"](){let r=t;return this.endpoints[this["currentI"+r(575)]]}[t(1017)+t(1422)+t(246)+"ount"](){let r=t;if(e[r(155)](e[r(436)],r(1138)))return this["currentE"+r(737)+r(1294)+"t"];this[r(274)]&&this[r(274)][r(654)](_0x5593e8),this._debug("send_ack",_0x16f1ab)}[t(980)+t(1551)+"es"](){let r=t;return!!(e[r(1153)](this[r(1533)+r(575)],this.endpoints[r(1421)])||e.yRSRu(this["currentI"+r(575)],e[r(664)](this[r(401)+"s"][r(1421)],1))&&e.HTQjJ(this["currentE"+r(737)+r(1294)+"t"],this[r(1141)+"es"]))}[t(1132)+t(632)+t(985)+t(1089)+t(1110)](){let r=t;return e.ZoteJ(this["currentI"+r(575)],this[r(401)+"s"][r(1421)])?!0:e.wOEbk(this["currentEndpointT"+r(1294)+"t"],this[r(1141)+"es"])}["replaceB"+t(859)+t(694)+t(349)+t(999)](){let r=t;return this[r(379)+r(737)+r(1294)+"t"]=1,this[r(1533)+"ndex"]++,this[r(401)+"s"][this[r(1533)+r(575)]]}["getCurrentEndpointAndUpd"+t(1095)](){let r=t;return this[r(379)+r(737)+r(1294)+"t"]++,this[r(1017)+"ntEndpoint"]()}}let rr=(e[t(1524)](t(198)+"d",typeof globalThis)&&e[t(750)]("Window",globalThis[t(203)+"tor"][t(1021)])||e[t(1524)](e.uGPoW,typeof window)&&e[t(1279)](e.UVpCO,window["construc"+t(327)][t(1021)]))&&e[t(399)](e[t(1194)],typeof document),Pn=e[t(1194)]!=typeof globalThis&&(e[t(236)](t(1399),globalThis[t(203)+"tor"][t(1021)])||e.HTQjJ(e[t(279)],globalThis[t(203)+"tor"][t(1021)]))&&e[t(399)](e[t(1194)],typeof tt),Xr=(e[t(1611)](e[t(1194)],typeof globalThis)&&e[t(570)](e[t(1271)],globalThis[t(203)+t(327)][t(1021)])||e[t(1194)]==typeof globalThis||e[t(399)]("undefined",typeof globalThis)&&!!globalThis[t(391)+t(1393)])&&e[t(1194)]!=typeof wx,Qr=e.gKzMY(e[t(1194)],typeof globalThis)&&(e[t(1546)](e[t(279)],globalThis[t(203)+"tor"][t(1021)])||e[t(1279)](e[t(983)],globalThis["construc"+t(327)].name)||e.hOXIS(e[t(1466)],globalThis[t(203)+t(327)][t(1021)]))&&e[t(1524)](t(198)+"d",typeof self),Np=e[t(399)](e[t(1194)],typeof globalThis)&&e.oJQCO(e[t(1271)],globalThis[t(203)+t(327)][t(1021)])&&e[t(358)](e[t(1194)],typeof global)&&e[t(1279)](e[t(1271)],global[t(203)+"tor"][t(1021)])&&e.zqWIb(t(198)+"d",typeof process)&&!!process[t(1461)];class fa{constructor(){this._listeners={}}[t(438)](r,...o){let l=t,f=this._listeners[r];if(f)f[l(1097)]()[l(1599)](m=>m.fn[l(1512)](m[l(1091)],o));else if(e[l(1435)](e.TUARK,r)&&!this.onerror){let m=o[l(1421)]&&o[0];if(e.Fzmfc(m,Error))throw m;let _=new Error(e[l(197)](e[l(1268)],m?e[l(197)](" (",m[l(143)])+")":""));throw _[l(1045)]=m,m}return this}[t(425)](r,o){let l=t;if(e[l(799)](e[l(1377)],"JfPVj")){let f=0,m={};for(let _=0;_<_0x44870f[l(1421)];_++)m[_0x5942f1[_][l(1082)+"ame"]]=e[l(231)](_0x54b2b7,_0x5e8f01[_]["cursor_n"+l(970)]),f+=e[l(536)](14,m[_0x1875f4[_]["cursor_n"+l(970)]]);return[f,m]}else{if(r===void 0)this[l(1452)+"rs"]={};else if(e[l(192)](void 0,o))this[l(1452)+"rs"][r]=null;else{let f=this[l(1452)+"rs"][r];if(f)for(let m=0;e.baKxU(m,f[l(1421)]);)e[l(1127)](f[m].fn,o)?f[l(206)](m,1):++m}return this}}on(r,o,l){let f=t;return(this[f(1452)+"rs"][r]||(this[f(1452)+"rs"][r]=[]))[f(527)]({fn:o,ctx:l||this}),this}}class Mp extends fa{["_formatErrorMess"+t(540)](r){let o=t;return r[o(215)]||r[o(1502)]?(o(1125)+" "+(r[o(215)]||"")+o(1356)+(r[o(1502)]||""))[o(168)]():JSON[o(240)+"y"](r)}constructor(r,o,l){let f=t;super(),this._socket=null,Xr&&wx[f(244)+f(1124)]&&(this._socket=wx["connectS"+f(1124)]({url:r,protocols:o,header:l,fail:this[f(1509)+f(511)+f(811)][f(448)](this),success:this["_createS"+f(1378)+f(1572)+f(797)].bind(this)})),Pn&&tt[f(244)+f(1124)]&&(this._socket=tt[f(244)+f(1124)]({url:r,protocols:o,header:l,fail:this[f(1509)+"ocketFai"+f(811)][f(448)](this),success:this[f(1509)+"ocketSuccessHandler"][f(448)](this)}))}[t(1509)+t(1378)+"cessHand"+t(797)](){let r=t;Promise[r(159)]()[r(830)](()=>{this["_addWsLi"+r(1384)]()})}["_createS"+t(511)+t(811)](r){let o=t,l={jomUm:function(f,m){return e[j(1242)](f,m)},Ogbhx:e[o(591)],Hlheb:e[o(989)],RHJan:function(f,m,_){return e[o(1303)](f,m,_)},SxhEl:e[o(533)],CeGnY:function(f,m,_){return e[o(306)](f,m,_)},YxcSp:e[o(1015)]};Promise.resolve().then(()=>{let f=o;if(l.jomUm(l[f(809)],l[f(722)])){let m=l[f(1093)](at,l[f(217)],{message:this["_formatE"+f(419)+f(540)](r)});this[f(438)](l[f(217)],m);let _=l[f(266)](gt,l[f(348)],{reason:this[f(293)+f(419)+f(540)](r)});this[f(438)](l[f(348)],_)}else _0x52f3ac[f(1219)](_0x96c915)})}[t(1396)+t(1384)](){let r=t,o={ptkwB:e[r(1582)],Ccitd:function(l,f,m){return e[r(771)](l,f,m)},YPTvW:e[r(1015)],UYAyF:function(l,f){return e[r(368)](l,f)},vMXgI:function(l,f){return e.tBXoi(l,f)},KwakC:function(l,f){return e[r(1574)](l,f)},AUazL:function(l,f){return l&f},tOorB:function(l,f){return e.qzFyW(l,f)},hwqdn:e[r(533)]};this._socket.onOpen(l=>{let f=r;this[f(438)](o[f(427)],o.Ccitd(cl,o[f(427)],{...l,data:l[f(215)]||""}))}),this[r(1577)][r(252)](l=>{let f=r;this[f(438)](o[f(357)],o[f(180)](gt,o[f(357)],{...l}))}),this[r(1577)][r(149)+"e"](l=>{let f=r;this.emit(e.qpoCC,e[f(700)](al,e.qpoCC,{...l}))}),this[r(1577)][r(303)](l=>{let f=r,m={MfKTF:function(_,b){return o.UYAyF(_,b)},CqexO:function(_,b){return o[j(1277)](_,b)},dxrlV:function(_,b){return _(b)},FjMBA:function(_,b){return o[j(893)](_,b)},vczaJ:function(_,b){return o[j(1070)](_,b)},iwgFG:function(_,b){return o.tOorB(_,b)},pWRNZ:function(_,b){return _||b}};if(f(171)===f(171))this[f(438)](o[f(658)],o[f(180)](at,o[f(658)],{...l,message:l[f(215)]||""}));else{let _=m[f(729)](_0x6c3317,8192),b=_>>>1,p=null,T=_;return function(L){let N=f;if(m[N(1311)](L,1)||m[N(1019)](L,b))return m[N(1331)](_0x3863c8,L);m[N(571)](T,L)>_&&(p=_0x277f85(_),T=0);let G=_0x37b15d[N(525)](p,T,T+=L);return m[N(259)](7,T)&&(T=m[N(1317)](7,T)+1),G}}})}[t(654)](r){let o=t,l={FNWGk:o(1284),aqHRL:function(f,m,_){return f(m,_)},TSgzy:function(f,m){return e[o(1333)](f,m)},yGnHU:function(f){return f()},wbKiP:function(f,m){return e[o(975)](f,m)},qggAQ:e[o(1478)],ySzDC:function(f,m,_){return e.Eslpv(f,m,_)}};if(r instanceof Uint8Array){let f=r[o(890)][o(1097)](r.byteOffset,r[o(918)+"th"]+r.byteOffset);this[o(1577)]&&this._socket[o(654)]({data:f,fail:m=>{let _=o;this[_(438)](l[_(1519)],l[_(1419)](at,l[_(1519)],{message:this[_(293)+_(419)+_(540)](m)}))}})}else this[o(1577)]&&this[o(1577)].send({data:r,fail:f=>{let m=o,_={yvZQR:function(b,p){return l.TSgzy(b,p)},UQZqi:function(b){return l[j(1262)](b)}};l[m(698)](l[m(1004)],l[m(1004)])?(VPSJTz[m(1459)](_0x5c53cb,_0x10672d(_0x26d700[m(578)])),VPSJTz.UQZqi(_0x46db5a)):this[m(438)](m(1284),l[m(930)](at,l[m(1519)],{message:this["_formatE"+m(419)+m(540)](f)}))}})}[t(961)](r,o){let l=t;this[l(1577)]&&this._socket[l(961)]({code:r,reason:o})}[t(476)+t(166)](r,o){this.on(r,o)}[t(704)+t(1133)+"ner"](r,o){let l=t,f={GsSZQ:function(m,_){return m(_)},gRjRh:function(m,_){return e[j(496)](m,_)},Pvmvy:function(m,_){return e[j(1184)](m,_)},qiYFN:function(m,_){return e[j(376)](m,_)}};e[l(1128)]("AJmVR",l(1003))?this[l(425)](r,o):(_0x1d6dd1=aUZZnx.GsSZQ(_0x5f2d00,_0x4ff1dd),_0x3965a0=aUZZnx[l(1126)](127,_0x2bba26),aUZZnx[l(863)](128,_0x5139fe)&&(_0x5eaee8=aUZZnx[l(478)](_0x4cb0db,_0x2f8701),_0xd7d1a8|=aUZZnx[l(163)](aUZZnx.gRjRh(127,_0x381f46),7)))}get[t(553)+"te"](){let r=t;return e.xGgGc(e[r(1575)],e.DOUaf)?this[r(274)]?this[r(274)][r(813)]:"":this[r(1577)][r(553)+"te"]}get[t(329)+"pe"](){let r=t;return this[r(1577)][r(329)+"pe"]}set[t(329)+"pe"](r){}get url(){let r=t;return this._socket[r(942)]}get[t(813)](){let r=t;return this[r(1577)][r(813)]}get[t(1347)+"ns"](){let r=t,o={CptEK:e[r(862)]};if(e[r(587)](r(517),r(517))){if(!this[r(524)+"Lock"]){let l=o[r(378)][r(1431)]("|"),f=0;for(;;){switch(l[f++]){case"0":this._isInit=!0;continue;case"1":this._connect();continue;case"2":this._readyClosed=!1;continue;case"3":this[r(1185)+r(1075)]?.[r(183)+r(605)+"fig"]();continue;case"4":this[r(1135)+r(1619)]?.[r(545)+r(506)]();continue}break}}}else return this._socket[r(1347)+"ns"]}get[t(543)+t(1342)](){return 0}}function Bp(a,r){let o=t;if(r)return new r(a[o(942)],a[o(813)]);if(e[o(387)](Xr,Pn))return new Mp(a[o(942)],a.protocol,a[o(944)]);if(e.gaXeX(rr,Qr)&&e[o(1611)](e[o(1194)],typeof WebSocket)&&WebSocket)return new WebSocket(a[o(942)],a[o(813)+"s"])}function Fp(a){let r=t,o=e.nLqjZ[r(1431)]("|"),l=0;for(;;){switch(o[l++]){case"0":return!1;case"1":if(a)return!0;continue;case"2":if(Xr&&wx[r(244)+r(1124)])return!0;continue;case"3":if(Pn&&tt["connectS"+r(1124)])return!0;continue;case"4":if(e[r(207)](rr,Qr)&&e[r(1550)](r(198)+"d",typeof WebSocket)&&WebSocket)return!0;continue}break}}function ll(a,r,o){let l=t,f={gDNuk:e[l(1406)],ldDvZ:function(b,p){return e[l(1381)](b,p)},uTVbz:e.fAdIl,bJnfT:function(b,p){return b===p},mBkKl:function(b,p){return e.HauVT(b,p)}},m=-1;async function _(b){let p=l;return f.gDNuk===f[p(1105)]?f[p(653)](b,m)?Promise.reject(new Error(f[p(1067)])):(m=b,f[p(341)](b,o[p(1421)])?Promise[p(159)]():o[b][p(448)](a)(r,_[p(448)](null,f[p(1011)](b,1)))):new _0xb2dc86(_0x1bb361,{message:_0x36f630})}e[l(355)](_,0)}function ul(a){let r=t,o=0,l=0;for(let f=0;e[r(1558)](f,a[r(1421)]);++f){if(e[r(1546)](e.PDGMf,"wkshQ"))return!!this[r(849)];l=a[r(738)+"At"](f),e[r(1042)](l,128)?o+=1:l<2048?o+=2:e[r(1527)](e[r(1468)](64512,l),55296)&&e[r(463)](64512,a[r(738)+"At"](f+1))===56320?(++f,o+=4):o+=3}return o}function fl(a,r,o){let l=t;if(e[l(161)](e.hPzZk(o,r),1))return"";let f="";for(let m=r;e[l(902)](m,o);){let _=a[m++];if(e[l(285)](_,127))f+=String[l(1437)+l(209)](_);else if(e[l(816)](_,192)&&e[l(955)](_,224))f+=String[l(1437)+l(209)](e[l(412)](31&_,6)|e[l(1150)](63,a[m++]));else if(e[l(733)](_,224)&&e[l(1472)](_,240))f+=String[l(1437)+l(209)](e[l(839)](e[l(661)](e[l(1379)](15,_)<<12,e.Ijfkg(e[l(271)](63,a[m++]),6)),63&a[m++]));else if(_>=240){let b=e[l(664)](e[l(1613)](e[l(1208)](e[l(412)](e.otzXi(7,_),18),e.Lrcwy(e.aphxr(63,a[m++]),12))|e.epAMV(63&a[m++],6),e[l(1468)](63,a[m++])),65536);f+=String[l(1437)+l(209)](e.mkziJ(55296,e[l(535)](b,10))),f+=String[l(1437)+"Code"](e[l(687)](56320,e.ARsgE(1023,b)))}}return f}function ha(a,r,o){let l=t,f={wIigR:e.XZmPz},m=o,_,b;for(let p=0;e[l(1206)](p,a[l(1421)]);++p)e[l(1336)]===e[l(1336)]?(_=a[l(738)+"At"](p),e[l(302)](_,128)?r[o++]=_:e[l(1252)](_,2048)?(r[o++]=e.CqyfU(_,6)|192,r[o++]=e.AYvjO(e.cTCQW(63,_),128)):e[l(497)](e.YTkib(64512,_),55296)&&e[l(1568)](e.eVZuC(64512,b=a[l(738)+"At"](e.Ecfld(p,1))),56320)?(_=e[l(667)](e[l(1076)](65536,e[l(879)](e[l(971)](1023,_),10)),e[l(1529)](1023,b)),++p,r[o++]=e[l(1593)](_>>18,240),r[o++]=e[l(613)](_,12)&63|128,r[o++]=e.PhPzg(_>>6&63,128),r[o++]=e[l(1007)](e[l(369)](63,_),128)):(r[o++]=e.TnsRG(_,12)|224,r[o++]=e[l(326)](e[l(535)](_,6)&63,128),r[o++]=e[l(789)](e[l(463)](63,_),128))):this[l(438)](Dybxdg.wIigR,_0x5a0f69(Dybxdg[l(221)],{..._0x4c8629,data:_0x3bf1a2.errMsg||""}));return e[l(622)](o,m)}async function hl(a){let r=t;if(e.FRsKu(e[r(1178)],typeof a)){let o=new Uint8Array(e[r(289)](ul,a));return e[r(1043)](ha,a,o,0),o}return e.dDdmy(a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[r(890)],a[r(1288)+"et"],a.byteLength)}function zp(a){let r=t,o={oKTJH:function(l,f){return e.dhjfi(l,f)},JSxwG:function(l,f,m,_){return e[j(620)](l,f,m,_)},LKZVt:function(l,f){return e[j(439)](l,f)}};try{if(e[r(567)]===e.OBMFn)return e[r(1611)](e[r(1178)],typeof a)&&(e[r(678)](a,ArrayBuffer)||a.buffer&&e[r(1066)](a[r(890)],ArrayBuffer))||e[r(1550)](r(1198),typeof a)?"":(JSON[r(1305)](a),e[r(331)]);{let l=o[r(162)](255,_0x5b8ff2);o[r(1476)](_0x57e470,l,_0x550d6a,o[r(495)](_0x5ad7c2,_0x52db7a)),_0x1a5200>>>=8,_0x4a5e2d--}}catch{return e[r(1335)](e.nVSse,typeof a)?e[r(544)]:""}}let Up=(a,r)=>{let o=t;switch(a){case e.rbRYz:case e[o(1532)]:return{["x-use-"+a]:1,"x-tt-env":r};default:return{}}};class Gp{constructor(r){let o=t;this[o(473)+o(1013)]=r,this.count=0}[t(695)](){let r=t;this[r(1087)]++}["checkRea"+t(946)+"nt"](){let r=t;return e[r(951)](this[r(1087)],this[r(473)+"ount"])}[t(545)+t(506)](r=0){let o=t;this.maxLossCount=r,this[o(1087)]=0}}async function qp(a){let r=t,o={zqaYz:function(l,f){return e.zhYYG(l,f)},yNrPJ:function(l,f){return e.ubGJU(l,f)},jbBLN:function(l,f){return e[j(1210)](l,f)},CikQx:e[r(331)],cTRJs:e[r(824)],VAJfY:"string",QxTHs:e[r(1600)],LiHUz:e[r(165)]};return new Promise(l=>{let f=r;if(!rr)return e[f(1046)](l,f(608)+f(954));try{let m=document[f(225)+f(645)](e[f(146)]);window[f(1537)+f(1522)]=_=>{let b=f;document[b(948)][b(719)+b(516)](m),window["frontier"+b(1522)]=void 0,o[b(853)](l,_&&_[b(223)]||b(608)+b(954))},m[f(1460)]=e[f(593)],m[f(467)]=e[f(235)](a[f(523)](/^ws/,f(685)),"&jscallback=frontierJSONP");try{document[f(948)]["appendCh"+f(516)](m)}catch{document[f(948)][f(719)+f(516)](m)}}catch{if(e.KtHlX(e[f(1248)],e.JoLkl))window["frontier"+f(1522)]=void 0,e.XWmrD(l,e.ADjmS);else if(o[f(677)](_0xc8cf85[f(914)],_0x5792b5)){let m=o[f(1139)](this[f(388)]["payloadE"+f(1134)],_0x5eb7bd)?{force:!!this[f(388)][f(1173)+"ncoding"].force,encoding:this[f(388)][f(1173)+f(1134)].encoding?this._options[f(1173)+"ncoding"][f(1098)][f(523)](/\s/g,"")[f(674)+f(1473)]():""}:{force:!1,encoding:this[f(388)][f(1173)+f(1134)]?this[f(388)]["payloadE"+f(1134)][f(523)](/\s/g,"")[f(674)+f(1473)]():""},_=_0x245356[f(1173)+f(1134)]?_0x458033[f(1173)+"ncoding"].replace(/\s/g,"")["toLowerC"+f(1473)]():"",b=this[f(388)][f(538)+f(576)]instanceof _0x2f1945?{force:!!this[f(388)].payloadType[f(1211)],type:this[f(388)][f(538)+f(576)][f(1460)]?this[f(388)][f(538)+f(576)].type[f(523)](/\s/g,"")["toLowerC"+f(1473)]():""}:{force:!1,type:this._options[f(538)+"ype"]?this[f(388)][f(538)+f(576)][f(523)](/\s/g,"")[f(674)+f(1473)]():""},p=_0x34157a.payloadType?_0x3005e0[f(538)+"ype"][f(523)](/\s/g,"")[f(674)+f(1473)]():"",T=b[f(1211)]?b[f(1460)]:p||b.type,L=m[f(1211)]?m[f(1098)]:_||m[f(1098)],N=[f(318)+f(173)+f(644),o[f(803)],o[f(1301)],o[f(1223)]],G=[o[f(1025)],o[f(1595)]];this[f(388)][f(1565)+f(1231)+f(459)+"ad"]&&N[f(1485)](T)&&(!L||G[f(1485)](L))?_0x3d4149["textPayl"+f(312)]=_0x4cef93(_0x3fc499.payload,0,_0x5df5cd[f(914)][f(918)+"th"]):_0x1b3c25[f(1412)+"oad"]=""}else _0x5efa86[f(1412)+f(312)]=""}})}function sn(a,r,o){let l=t;return!!a?.[l(1230)](f=>f[l(1402)]===r&&f[l(1362)]===o)}function ir(a,r){let o=t;return a?.[o(1230)](l=>l[o(1402)]===r)?.[o(1362)]}let xa=null;async function Hp(){let a=t;return xa||(xa=Promise[a(159)]()[a(830)](Bt[a(448)](Bt,e[a(1484)]))),xa}class jp extends fa{constructor(r,o){let l=t;super(),this[l(555)]=r,this[l(153)]=o,this._qosDB=void 0,this[l(1603)+l(1023)]=null}async openDB(){await this[t(697)]()}async[t(697)](){let r=t,o={hSDTS:function(l){return e.vnBFe(l)},kGJxe:function(l,f,m,_){return e.fWGDm(l,f,m,_)}};if(!this[r(849)]){if(this[r(1603)+r(1023)])return this[r(1603)+r(1023)];try{let l=this[r(555)],f=this[r(153)];this[r(1603)+"mise"]=(async()=>{let m=r,{openDB:_}=await o.hSDTS(Hp);this[m(849)]=await o[m(668)](_,m(1537)+"_"+l,1,{upgrade(b){let p=m;b[p(1503)+p(1576)+"e"](l,{keyPath:f})}})})(),await this[r(1603)+r(1023)]}catch(l){console.log(l)}finally{this[r(1603)+r(1023)]=null}}}async[t(905)](r){let o=t;try{return await this[o(697)](),this._qosDB?.[o(905)](this[o(555)],r)}catch(l){console.log(l)}}async[t(769)](r,o){let l=t;return await this._init(),this._qosDB?.[l(995)](this[l(555)],r)}async del(r){let o=t,l={WyKUP:function(f,m){return e[j(1018)](f,m)},pQESx:function(f,m){return e.BiFsU(f,m)}};try{return e[o(184)](e[o(1526)],e[o(300)])?(await this[o(697)](),this[o(849)]?.[o(777)](this[o(555)],r)):!!(ffkqEk[o(565)](this["currentI"+o(575)],this[o(401)+"s"].length)||this[o(1533)+"ndex"]===this[o(401)+"s"][o(1421)]-1&&ffkqEk[o(1001)](this[o(379)+"ndpointT"+o(1294)+"t"],this.maxRetries))}catch(f){console[o(1219)](f)}}async[t(1470)](){let r=t,o={jbOVz:function(l,f){return e.xaHpp(l,f)},wHovS:function(l,f){return e[j(1611)](l,f)},vJFlS:function(l,f){return e.eXwnX(l,f)},hvXrJ:e[r(1194)],VxlUq:e[r(713)]};if(e[r(1414)]("oBfDm",r(855)))try{return await this[r(697)](),this[r(849)]?.[r(1470)](this[r(555)])}catch(l){console[r(1219)](l)}else{if(_0x5c463b||_0x1339d2)return new _0x2c02cb(_0x544442,_0x249964);if(o.jbOVz(_0x774b55,_0x40db47)&&o[r(1228)](r(198)+"d",typeof _0xf162b4))return new _0x10716b(_0x3af2df,_0x20e7e8);if(o[r(1035)](_0x14e152,_0x1e5f47)&&o.hvXrJ!=typeof _0x50e192)return new _0x48a260(_0x2f8017,_0x114587);throw new _0x48dd00(o.VxlUq)}}async[t(755)](){let r=t;return await this[r(697)](),this[r(849)]?.[r(513)+"ys"](this[r(555)])}async getAll(){let r=t;return await this[r(697)](),this[r(849)]?.getAll(this[r(555)])}async[t(1588)](){let r=t;try{this[r(849)]?.[r(961)](),this[r(849)]=void 0}catch(o){console[r(1219)](o)}}get[t(1119)](){let r=t;try{return!!this[r(849)]}catch(o){return console[r(1219)](o),!1}}}class Wp{constructor(r,o){let l=t;this[l(1131)]=r,this[l(651)]=o,this._qosDB=localStorage}async[t(456)](){}get _prefix(){let r=t;return e[r(1350)](e[r(795)],e[r(795)])?r(1537)+"_"+this[r(1131)]:this[r(849)]?.isReady}async get(r){let o=t,l=this[o(849)][o(881)](this[o(213)]);return JSON[o(1305)](l||"{}")[r]}async[t(769)](r,o){let l=t,f=this[l(849)][l(881)](this[l(213)]),m=JSON[l(1305)](e[l(257)](f,"{}"));return m[o||r[this[l(651)]]]=r,this[l(849)][l(433)](this[l(213)],JSON.stringify(m)),o||r[this[l(651)]]}async[t(1101)](r){let o=t,l=this[o(849)][o(881)](this[o(213)]),f=JSON[o(1305)](e[o(1328)](l,"{}"));return f[r]=void 0,this[o(849)][o(433)](this[o(213)],JSON.stringify(f))}async[t(1470)](){let r=t;return this[r(849)][r(1470)]()}async[t(755)](){let r=t,o=this[r(849)][r(881)](this[r(213)]),l=JSON[r(1305)](e[r(430)](o,"{}"));return Object[r(755)](l)}async getAll(){let r=t,o=this[r(849)][r(881)](this[r(213)]),l=JSON.parse(e[r(690)](o,"{}"));return Object.values(l)}[t(1588)](){return Promise[t(159)]()}get[t(1119)](){return!!this[t(849)]}}class Kp{constructor(r,o){let l=t;this[l(1131)]=r,this[l(651)]=o,this[l(849)]=Pn?tt:Xr?wx:null}async openDB(){}get[t(213)](){let r=t;if(e[r(975)](r(872),e[r(1424)])){if(e.FaXcS(_0x2bbffd,_0x184341))throw new _0x3f30ac(r(1166)+r(1622)+"e");let o=3;for(;e[r(404)](o,0);){let l=255&_0x2f3f99;_0x697e17(l,_0x39d3cf,e.zeOTr(_0x36a7a4,o)),_0x5a832e>>>=8,o--}return _0x36e7a2+4}else return r(1537)+"_"+this[r(1131)]}async[t(905)](r){let o=t,l={XCQTa:function(f,m,_){return e[j(1063)](f,m,_)},tSuDC:e.Aeycv,trgZB:e[o(278)]};if(e[o(1480)](e[o(498)],e.ECXLe)){let f=this[o(849)][o(957)+o(1030)](this._prefix);return JSON[o(1305)](f||"{}")[r]}else{let f=l[o(823)](_0x54ee6b,l.tSuDC,{message:l.trgZB});this[o(1360)+o(601)]&&this[o(1360)+"econnect"](f)}}async[t(769)](r,o){let l=t,f=this[l(849)][l(957)+l(1030)](this[l(213)]),m=JSON[l(1305)](e[l(1475)](f,"{}"));return m[o||r[this[l(651)]]]=r,this._qosDB[l(1520)+l(1030)](this._prefix,JSON[l(240)+"y"](m)),o||r[this[l(651)]]}async[t(1101)](r){let o=t,l=this[o(849)]["getStora"+o(1030)](this._prefix),f=JSON[o(1305)](e.IsMYS(l,"{}"));return f[r]=void 0,this[o(849)]["setStora"+o(1030)](this[o(213)],JSON[o(240)+"y"](f))}async[t(1470)](){let r=t;return this[r(849)][r(1562)+r(895)]()}async keys(){let r=t,o=this[r(849)]["getStora"+r(1423)+"nc"](this._prefix),l=JSON[r(1305)](e[r(598)](o,"{}"));return Object[r(755)](l)}async[t(336)](){let r=t,o=this[r(849)][r(957)+r(1423)+"nc"](this._prefix),l=JSON[r(1305)](e.IsMYS(o,"{}"));return Object[r(908)](l)}[t(1588)](){return Promise[t(159)]()}get isReady(){return!!this[t(849)]}}function xl(a,r){let o=t;if(e[o(899)]===o(1193))this[o(388)][o(1290)]&&_0x5ee0e5[o(1219)].apply(_0x297f83,["FRONTIER>",..._0x15188e]);else{if(e[o(1037)](Pn,Pn))return new Kp(a,r);if(e[o(1247)](rr,Qr)&&e.gKzMY(e[o(1194)],typeof indexedDB))return new jp(a,r);if((rr||Qr)&&e[o(1611)](o(198)+"d",typeof localStorage))return new Wp(a,r);throw new Error(e[o(713)])}}class $p{constructor(){let r=t;this[r(597)+r(1224)+"Id"]=null,this[r(597)+"l"]=36e5,this[r(849)]=e[r(306)](xl,e[r(1259)],e[r(861)])}async["_interva"+t(671)](){let r=t;e[r(231)](clearInterval,this._intervalTimeoutId),this[r(597)+"lTimeoutId"]=e[r(815)](setInterval,()=>{let o=r;this[o(493)+o(760)]()},this[r(597)+"l"])}async openDB(){let r=t;await this[r(849)][r(456)]().then(()=>{this._intervalFlush()})}async flushExpired(){let r=t,o={wujPB:function(m,_){return e[j(1069)](m,_)},InNKB:e[r(1178)],ISiEd:e.gibqQ,CxBsG:e[r(485)]};(await this[r(849)]?.getAll()||[])[r(311)](({timestamp:m})=>m<Date[r(275)]()).forEach(m=>{let _=r;if(o.CxBsG!==_(947))return uQesSk[_(924)](uQesSk.InNKB,typeof _0x48ddcf)?uQesSk[_(310)]:"";this[_(849)]?.del(m[_(1152)+"id"])})}async del(r){let o=t;return this._qosDB?.[o(1101)](r)}async[t(769)](r,o){let l=t;return this[l(849)]?.[l(769)]({message_id:r,timestamp:o})}async[t(905)](r){let o=t;return e[o(497)](o(216),e[o(933)])?this._qosDB?.get(r):this[o(849)]?.[o(769)]({message_id:_0x2bd74f,timestamp:_0x52c980})}async[t(1588)](){let r=t;e[r(1213)](clearInterval,this[r(597)+"lTimeoutId"]),await this[r(849)]?.[r(1588)]()}get[t(1119)](){return this[t(849)]?.isReady}}function pa(a){let r=t,o=!!this[r(388)][r(323)+"S"];if(!o)return{enabled:o,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e.sIacP(sn,a[r(143)][r(944)],r(1291)+"er_qos","2"),f=l&&sn(a.message[r(944)],r(1291)+"er_qos_ack","1"),m=l&&e[r(740)](sn,a[r(143)][r(944)],e[r(748)],"1"),_=m?e.Eslpv(ir,a[r(143)].headers,e.DBarA)?.split(",")[r(311)](Boolean)||[]:[];return{enabled:o,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:m,ackMsgIds:_}}async function pl(){let a=t;return this["_QoSMana"+a(1340)]||(this[a(214)+a(1340)]=new $p),this["_QoSMana"+a(1340)][a(1119)]||await this["_QoSMana"+a(1340)][a(456)](),this[a(214)+a(1340)]}async function Vp(a,r){let o=t,{enableAutoAck:l}=this[o(388)],f=e[o(1436)](sn,a[o(143)][o(944)],e[o(626)],"1"),m=e.DNnyK(sn,a.message[o(944)],o(1235),"1"),_=pa[o(525)](this,a);if(e[o(499)](l,f)){let{SeqID:b,LogID:p,service:T,LogIDNew:L,method:N}=a[o(143)];this[o(1052)]({SeqID:b,LogID:p,LogIDNew:L,service:T,method:N,headers:[{key:e[o(564)],value:"1"},{key:e[o(1444)],value:e[o(1217)](L,"")},{key:e.eeblC,value:"0"}]})}m&&!_[o(991)]&&this[o(1454)+"hAckMess"+o(756)](a),r()}async function Yp(a,r){let o=t;this[o(586)](e[o(1243)],a.message),e.kbiVT(r)}async function Jp(a,r){let o=t,l=e.zhYYG(tn,await e.qemaz(hl,a.data));try{if(e[o(1281)](l[o(914)],Uint8Array))if(e[o(1068)]!==e.Gntqa){let f=e.Fzmfc(this._options[o(1173)+o(1134)],Object)?{force:!!this[o(388)][o(1173)+o(1134)].force,encoding:this[o(388)][o(1173)+o(1134)][o(1098)]?this[o(388)][o(1173)+o(1134)][o(1098)][o(523)](/\s/g,"")[o(674)+o(1473)]():""}:{force:!1,encoding:this[o(388)][o(1173)+o(1134)]?this[o(388)][o(1173)+o(1134)][o(523)](/\s/g,"")[o(674)+o(1473)]():""},m=l[o(1173)+o(1134)]?l[o(1173)+o(1134)][o(523)](/\s/g,"")["toLowerC"+o(1473)]():"",_=e[o(1388)](this._options["payloadT"+o(576)],Object)?{force:!!this[o(388)].payloadType[o(1211)],type:this[o(388)][o(538)+o(576)][o(1460)]?this[o(388)][o(538)+o(576)].type[o(523)](/\s/g,"")[o(674)+"ase"]():""}:{force:!1,type:this[o(388)][o(538)+"ype"]?this[o(388)][o(538)+o(576)].replace(/\s/g,"")[o(674)+o(1473)]():""},b=l[o(538)+o(576)]?l["payloadT"+o(576)].replace(/\s/g,"")[o(674)+"ase"]():"",p=_[o(1211)]?_[o(1460)]:b||_[o(1460)],T=f[o(1211)]?f[o(1098)]:m||f[o(1098)],L=[e[o(544)],o(1321)+o(152),e[o(824)],e[o(1178)]],N=[e[o(1600)],e[o(165)]];this[o(388)][o(1565)+o(1231)+"extPayload"]&&L[o(1485)](p)&&(!T||N[o(1485)](T))?l.textPayload=e[o(1498)](fl,l[o(914)],0,l.payload.byteLength):l[o(1412)+o(312)]=""}else{let{SeqID:f,LogID:m,service:_,LogIDNew:b,method:p}=_0x38e449.message;this[o(1052)]({SeqID:f,LogID:m,LogIDNew:b,service:_,method:p,headers:[{key:e[o(564)],value:"1"},{key:e[o(1444)],value:e[o(1163)](b,"")},{key:o(751),value:"0"}]})}else l[o(1412)+o(312)]=""}catch(f){l["textPayl"+o(312)]="",console[o(1219)](f)}a[o(143)]=l,e.kbiVT(r)}function Zp(a,r,o){let l=t,f=e[l(1217)](o,8192),m=e[l(753)](f,1),_=null,b=f;return function(p){let T=l;if(e.fXrcL(p,1)||e[T(573)](p,m))return e[T(154)](a,p);e[T(1263)](e[T(577)](b,p),f)&&(e[T(277)](e[T(156)],T(1307))?(_=e[T(1162)](a,f),b=0):_0x463f1d.log(_0x9b0224));let L=r[T(525)](_,b,b+=p);return e[T(720)](7,b)&&(b=(7|b)+1),L}}let Xp=4294967295;function Qp(a,r,o){let l=t;return e[l(1289)](RangeError,e[l(917)](e[l(618)](e[l(788)](e.HzMVS(e[l(350)],a),e[l(1373)])+(r||1),e[l(910)]),o))}function eg(a,r,o){let l=t;if(e[l(785)](e[l(483)],e.JCOjc)){if(o>Xp)throw new Error(e.CXoun);let f=3;for(;e[l(389)](f,0);){let m=e[l(185)](255,o);e[l(1051)](ma,m,a,r+f),o>>>=8,f--}return e.VvNbW(r,4)}else return this[l(274)]?this[l(274)].binaryType:this["_binaryT"+l(576)]}function tg(a,r){let o=t,l=0,f=r,m=e[o(786)](r,4);for(;e[o(368)](f,m);)if(e[o(1545)](e[o(449)],e[o(313)])){let{value:_,offset:b}=e.oOtaq(ga,a,f);f=b,l=e[o(452)](e[o(879)](l,8),0),l+=_}else{let _=_0x59ed83.key;e[o(616)](void 0,_)&&(e.qHofC(_0x59106f,_0x167e6c,10),e[o(1430)](_0x2f83f4,_0x300bac,_));let b=_0x6d6e46[o(1362)];b!==void 0&&(_0x38bb40(_0x3e3e05,18),e[o(486)](_0x2e78e9,_0x2f01de,b))}return{value:l,offset:m}}function ng(a,r,o){let l=t,f="1|0|2|3|4"[l(1431)]("|"),m=0;for(;;){switch(f[m++]){case"0":if(e.baKxU(a[l(1421)],40))return ha(a,r,o)+o;continue;case"1":if(!a)return o;continue;case"2":if(r[l(1250)+"e"])return e[l(1180)](r.utf8Write(a,o),o);continue;case"3":if(r[l(469)])return e.HzMVS(r[l(469)](a,o),o);continue;case"4":return e[l(160)](e[l(973)](ha,a,r,o),o)}break}}function rg(a,r){let o=t,l=new fe(e.xVNTw(e[o(1108)](e[o(1417)](e[o(1117)](a[e[o(1574)](r,4)],24),a[e.UZlQk(r,5)]<<16),a[e[o(407)](r,6)]<<8),a[e[o(790)](r,7)]),e[o(801)](e[o(172)](a[e[o(343)](r,0)],24)|e[o(172)](a[r+1],16),e[o(529)](a[r+2],8))|a[e[o(1462)](r,3)],!0);return r+=8,{value:l,offset:e.hkPGh(r,8)}}function ig(a,r,o){let l=t,f=a.low,m=a[l(701)];return r[o]=m>>>24,r[e[l(1287)](o,1)]=e[l(150)](e[l(1029)](m,16),255),r[e[l(1039)](o,2)]=e[l(233)](m,8)&255,r[e.kmyyc(o,3)]=e.zVVqE(255,m),r[e[l(1170)](o,4)]=e[l(1293)](f,24),r[o+5]=e[l(703)](e[l(848)](f,16),255),r[e[l(577)](o,6)]=e[l(1293)](f,8)&255,r[e[l(675)](o,7)]=e.IYgXe(255,f),o+=8,o}function ga(a,r){let o=t;return a.readUInt8?{value:a.readUInt8(r),offset:r+1}:{value:e[o(369)](255,a[r]),offset:r+1}}function ma(a,r,o){let l=t;return r[l(1453)+"t8"]?r[l(1453)+"t8"](a,o):r[o]=e[l(185)](255,a),o+1}let sg=function(a){return new Uint8Array(a)},og=e.qNFDD(e[t(1194)],typeof Buffer)?Buffer[t(1100)+t(1031)]:e[t(489)](Zp,sg,Uint8Array.prototype[t(205)]);(()=>{let a=t,r={BOHML:function(l,f){return e[j(480)](l,f)},SpWkM:function(l,f,m){return e[j(370)](l,f,m)},PJezn:function(l,f){return e.PVjHd(l,f)},TLCjG:function(l,f){return e.tTvCa(l,f)},lFLyk:e[a(838)],eyrpa:e[a(191)],ttdUd:function(l,f){return l<f},ZQEKD:function(l,f){return e.EmGPB(l,f)},iCZpQ:function(l,f){return e[a(261)](l,f)},gWAkt:function(l,f){return e[a(971)](l,f)},FAEpY:function(l,f){return e[a(955)](l,f)},dFXJR:function(l,f,m,_){return e[a(1051)](l,f,m,_)},xYzVq:function(l,f){return e[a(703)](l,f)},PHvCf:function(l,f){return l>>>f},JRhWO:function(l,f){return l&f},QcKOf:function(l,f){return e[a(161)](l,f)},bUyyR:function(l,f){return l|f},TzgpY:function(l,f){return e.XniAg(l,f)},NVJtY:function(l,f){return e[a(1449)](l,f)},UmHbR:function(l,f){return e.ipbjl(l,f)}},o=4294967295;return function(l,f,m=!0){let _=a,b={QEZUT:function(p,T){return r[j(1238)](p,T)},nBeKE:function(p,T,L){return r[j(1339)](p,T,L)},jTkmG:function(p,T){return r[j(1267)](p,T)},qpSdo:function(p,T){return r.TLCjG(p,T)}};if(r.lFLyk!==r.lFLyk){let p=0,T=_0x5c391b,L=_0xb98678+4;for(;JNqjcR.QEZUT(T,L);){let{value:N,offset:G}=JNqjcR.nBeKE(_0x13d2f8,_0x22f777,T);T=G,p=JNqjcR[_(1432)](JNqjcR.qpSdo(p,8),0),p+=N}return{value:p,offset:L}}else{let p=r[_(966)][_(1431)]("|"),T=0;for(;;){switch(p[T++]){case"0":if(r[_(981)](l[f++],128))return{value:m?o:r[_(531)](0,o),offset:f};continue;case"1":if(r[_(981)](l[f++],128))return{value:m?o:r[_(531)](0,o),offset:f};continue;case"2":if(r[_(981)](l[f++],128))return{value:m?o:r[_(531)](0,o),offset:f};continue;case"3":o=r[_(1121)](o,r[_(925)](15,l[f])<<28)>>>0;continue;case"4":return{value:m?o:0|o,offset:f};case"5":if(r.FAEpY(l[f++],128))return{value:m?o:r[_(531)](0,o),offset:f};continue;case"6":if((f+=5)>l.length)throw f=l.length,r[_(897)](Qp,f,10,l[_(1421)]);continue;case"7":o=r[_(1267)](r[_(342)](127,l[f]),0);continue;case"8":o=r[_(1283)](o|r.JRhWO(127,l[f])<<14,0);continue;case"9":if(r[_(959)](l[f++],128))return{value:m?o:r[_(1205)](0,o),offset:f};continue;case"10":o=r.TzgpY(r[_(1497)](o,r.TLCjG(r[_(181)](127,l[f]),21)),0);continue;case"11":o=r[_(1175)](o|r[_(342)](127,l[f])<<7,0);continue}break}}}})();let ag=16,wa=32;function cg(a){let r=t,o=0,l={};for(let f=0;e[r(186)](f,a.length);f++)l[a[f][r(1082)+r(970)]]=e.QjGeq(ul,a[f][r(1082)+"ame"]),o+=e[r(725)](14,l[a[f][r(1082)+"ame"]]);return[o,l]}function gl(a,r,o){let l=t,f={yBvfy:function(T,L){return e[j(837)](T,L)},HvNfN:function(T,L){return e[j(1279)](T,L)},dMfDU:e.Mzkzb,oeHsv:l(541),SMVgt:e[l(682)],IZKli:l(170),zcaNi:function(T,L,N,G){return T(L,N,G)},AjaAG:e.wbgHY,giqnZ:function(T,L,N,G){return e[l(723)](T,L,N,G)},PRtRZ:e[l(1400)],rYKyt:l(949),gkvZH:e[l(742)],zNFld:l(712)+l(609)},[m,_]=e.cuHtY(cg,a),b=e[l(1394)](og,m),p=0;return a.forEach(T=>{let L=l,N={ZWuly:function(G,q,J){return G(q,J)},vBYAk:function(G,q){return f.yBvfy(G,q)}};if(f[L(1192)](f[L(1310)],f[L(1059)]))KBoYDl[L(1122)](_0x48122c,_0x1b75b2,32),KBoYDl.ZWuly(_0x29151e,_0x2aa87d,KBoYDl[L(347)](_0x26b59d,_0x24d4e1));else{let G=f[L(1621)][L(1431)]("|"),q=0;for(;;){switch(G[q++]){case"0":console[L(1219)](f.IZKli,p);continue;case"1":p=f.zcaNi(ma,_[T["cursor_n"+L(970)]],b,p);continue;case"2":console.log(f[L(1479)],p);continue;case"3":p=f[L(1090)](eg,b,p,T[L(949)]||0);continue;case"4":p=f[L(1227)](ig,fe.fromNumber(T[L(1330)]||r),b,p);continue;case"5":console.log(f[L(1607)],p);continue;case"6":p=f.giqnZ(ma,0,b,p);continue;case"7":console[L(1219)](f[L(1270)],p);continue;case"8":p=ng(T[L(1082)+"ame"],b,p);continue;case"9":console[L(1219)](f[L(1514)],p);continue;case"10":console[L(1219)](f[L(1332)],T,T[L(949)]);continue}break}}}),{frameType:wa,headers:[{key:e[l(212)],value:o}],payload:b}}function dg(a){let r=t,o={fUuFY:function(m,_){return m(_)}},l=0,f=[];for(;l<a[r(918)+"th"];)if(r(314)===e[r(1212)]){let{offset:m}=ga(a,l);l=m;let _={cursor_name:"",cursor:0,service:0},{value:b,offset:p}=e[r(805)](tg,a,l);_[r(949)]=b,l=p;let{value:T,offset:L}=e.SYalB(ga,a,l);l=L,_[r(1082)+r(970)]=e[r(973)](fl,a,l,e.VCczh(l,T)),l+=T;let{value:N,offset:G}=e.xLPSi(rg,a,l);_[r(1330)]=N.toNumber(),l=G,f[r(527)](_)}else{let m=_0x12e434[r(525)](_0x2de9f1(this),_0x1da353,..._0x1331a4);return _0x2f0e7e[r(769)](m,_0x14353d.sort?_0x4c70da.sort():[_0x3d73bc]),pSIMtL[r(851)](_0xf4f062,m)}return f}function lg(){let a=t;return{frameType:wa,headers:[{key:e.uIddF,value:e[a(276)]}],payload:void 0}}class ug{constructor(r,o,l){let f=t;if(e[f(1566)](e.nEKQM,e[f(1269)])){let m=this["_endpoin"+f(1075)]?.["getCurre"+f(1422)+"nt"](),_=this[f(388)][f(1455)+"tInterce"+f(308)](_0x275c1c[f(965)],_0x4b7043[f(954)]);this[f(1454)+"hCloseEv"+f(346)](e[f(1430)](_0x50accc,e[f(1015)],{code:1006,reason:_0x361fbd[f(954)]||f(547)+f(309)+f(1315)+"wn reaso"+f(1169)+"ame: "+m,willReconnect:_})),_&&this._connect();return}else this[f(1148)+f(237)]=r,this[f(1183)+"ileName"]=o,this[f(1496)+f(1544)]=l,this[f(849)]=e[f(1477)](xl,this["_cursorN"+f(237)],f(1082)+f(970))}async openDB(){let r=t;await this[r(849)][r(456)]()}async[t(552)+"rs"](){let r=t;if(e.MQjBg("LPgLQ",e.VCJLA))return(e[r(521)](_0x3b9454,4)[r(1297)]("0")+e[r(392)](_0x4d71db,_0x4f3045,2)[r(867)](16))[r(1097)](-4);{if(!this._qosDB[r(1119)])return;let o=this[r(1496)+r(1544)],l=await this._qosDB.getAll();switch(console[r(1219)]("allCursorValues",l),o){case r(877):return l&&l[r(1421)]?e[r(1051)](gl,l,0,this[r(1183)+r(232)]):void 0;case e[r(1380)]:return;case e[r(648)]:return l&&l[r(1421)]?e.pVLqH(gl,l,0,this[r(1183)+r(232)]):e[r(808)](lg)}}}async[t(769)](r,o,l){let f=t;return console.log(f(1245),r,o,l),this[f(849)][f(769)]({cursor_name:r,cursor:o,service:l})}async[t(1202)+"rs"](r){let o=t,l=e[o(727)](dg,r);for(let f of l)console[o(1219)](e.FamaF,l),await this._qosDB.set(f)}async get(r){let o=t;return(await this[o(849)][o(905)](r))?.[o(1330)]}async closeDB(){let r=t;await this[r(849)][r(1588)]()}["updateCu"+t(319)+t(1458)](r){let o=t;this[o(1183)+"ileName"]=r}get[t(1119)](){let r=t;return this[r(849)][r(1119)]}}let fg=e[t(1323)];async function ml(a){let r=t;if(!this[r(388)][r(323)+"S"])return null;let{aID:o,fpID:l,messageStrategy:f}=this._options,m=e.BmrlI(a,fg);try{return this["_cursorM"+r(398)]?a&&this["_cursorM"+r(398)][r(1345)+r(319)+r(1458)](a):this[r(1276)+"anager"]=new ug(l+"_"+o+"_"+m,m,f),this[r(1276)+r(398)][r(1119)]||await this["_cursorM"+r(398)][r(456)](),this[r(1276)+"anager"]}catch{return null}}async function hg(a,r){let o=t,l={SFygm:function(q,J){return e.NnAOz(q,J)},EPGpf:function(q,J){return e[j(799)](q,J)},vvJOm:function(q,J){return e[j(1527)](q,J)},CkOsv:function(q,J){return e[j(1254)](q,J)}},f=e[o(1051)](sn,a[o(143)][o(944)],e.nMmxY,"-1"),m=e[o(1436)](sn,a[o(143)][o(944)],e[o(564)],"1"),_=ir(a[o(143)].headers,e.WHIuO),b=e.dmiEY(Number,e[o(1404)](ir,a[o(143)].headers,e.wIntA))||0,p=pa[o(525)](this,a),T=e[o(1043)](sn,a[o(143)].headers,e[o(188)],"2"),L=e[o(1168)](ir,a.message[o(944)],e.YarZG),N=Number(e[o(1303)](ir,a[o(143)][o(944)],e.JuLbv));if(p[o(991)])return e[o(482)](r);let G=p[o(1447)+o(1071)]?await pl.call(this):null;if(a[o(143)].service>0&&m&&!f||e[o(1440)](a[o(143)][o(949)],0)){if(_&&p[o(1447)+"sage"]&&G)return!!!await G[o(905)](_)&&(this[o(1454)+o(1140)+o(1491)](a),await G[o(769)](_,e.bRpTx(Date[o(275)](),b))),e[o(1055)](r);if(T){let q=await ml.call(this);if(!q)return o(1385)!==e[o(1501)]?HoVhpd[o(784)](-1,this[o(1111)])&&HoVhpd[o(218)](-1,this[o(701)])?_0x12f573[o(505)](0,0,this[o(931)]):HoVhpd[o(820)](-1,this[o(1111)])?_0x29a50a[o(505)](0,this[o(701)]+1,this[o(931)]):_0x4d9303[o(505)](HoVhpd[o(889)](this[o(1111)],1),this[o(701)],this.unsigned):(this[o(1454)+o(1140)+o(1491)](a),e[o(937)](r));let J=await q.get(L)??-1;if(J<N)this[o(1454)+o(1140)+o(1491)](a),q[o(769)](L,N,a[o(143)][o(949)]);else throw new Error(o(1343)+o(646)+o(1538)+N+(o(1383)+o(295)+o(445)+"r ")+J);return r()}return this[o(1454)+o(1140)+o(1491)](a),r()}}async function xg(a,r){let o=t,l=pa.call(this,a);if(!l[o(1447)+o(1071)])return r();let f=await pl[o(525)](this);if(l[o(397)+"anupMess"+o(540)]&&l[o(1114)+"s"].length)for(let m of l[o(1114)+"s"])await f.del(m);e[o(1300)](r)}async function pg(a,r){let o=t,l=e[o(1308)](a[o(143)][o(330)+"e"],ag),f=e.KtHlX(a[o(143)][o(330)+"e"],wa);if(e[o(499)](!l,!f))return e[o(542)](r);let m=e[o(1456)](ir,a[o(143)][o(944)],o(793)+o(491));if(!m)return e[o(1092)](r);let _=await ml[o(525)](this,m);if(!_)return r();if(l){let b=await _[o(552)+"rs"](),p={frameType:b?.[o(330)+"e"],SeqID:fe[o(1318)+"er"](this[o(140)]++),LogID:fe[o(1318)+"er"](this[o(388)][o(1260)+o(269)]()),service:9e3,method:5,headers:b?.headers,payload:b?.payload},T=e[o(465)](S,p);this[o(274)]&&this[o(274)][o(553)+"te"]&&this[o(274)][o(654)](T)}if(f)if(e[o(763)]!==e.uSajT)_0x3acad3=e.pkEFO(e.SvCxH(e[o(1354)](e.hQXHJ(15,_0x4051c3),12),e[o(406)](e[o(1278)](63,_0x266c56),6)),e[o(361)](63,_0x7ed935)),e[o(512)](_0x4c1be1,2048)||e.zkcEL(_0x57d9e3,55296)&&_0x509f25<=57343?_0x496f37+=_0xdcd389:(_0x3e34ff+=e[o(1060)](_0x2eef1a,_0x55d0a8),_0x16e7fe+=2);else{let b=a[o(143)][o(914)];b&&_[o(1202)+"rs"](b)}}let gg=async function(a,r){let o=t;this[o(1218)]=!1,e.YnBJt(clearTimeout,this[o(524)+"ionTimeo"+o(617)]),e.RwWTj(r)},mg=async function(a,r){let o=t,l={emUTm:function(_,b){return e[j(728)](_,b)},ruYmY:function(_,b){return e[j(879)](_,b)},rjxOx:function(_,b){return _&b}};if(!this._ws||e[o(263)](this._ws[o(553)+"te"],this.OPEN))return r();let{pingInterval:f}=this[o(388)];this["_endpoin"+o(1075)]?.[o(183)+o(605)+"fig"]();for(let _=0;e[o(642)](_,this[o(1496)+o(673)][o(1421)]);_++){let b=this[o(1496)+o(673)][_];if(e[o(765)](this[o(274)][o(553)+"te"],this.OPEN)&&e[o(1583)](null,b))o(1487)===e.YbMLC?(this[o(274)]&&this._ws[o(654)](b),this[o(1496)+o(673)][_]=null):(_0xe425a=QorGOH[o(1398)](_0x2e9b4b,_0x4dee19),_0x54b33b<32&&(_0x5dce89|=QorGOH[o(344)](QorGOH[o(714)](127,_0x4ccc19),_0x334940)),_0x11e0f3+=7);else break}this[o(1496)+"Queue"]=this._messageQueue[o(311)](_=>!!_),this[o(193)+"gTimeoutId"]=e.tUgBs(setTimeout,()=>this[o(420)](),f),this[o(1454)+"hOpenEvent"](a),this._isBrowser&&this._ws&&(this[o(274)][o(329)+"pe"]=this["_binaryT"+o(576)]);let m=this[o(1185)+o(1075)]?.[o(1017)+o(1422)+"nt"]();this[o(586)](o(502)+m+o(1543)),e[o(982)](r)},wg=async function(a,r){let o=t,l=this[o(1185)+o(1075)]?.[o(1017)+o(1422)+"nt"]();this[o(586)]("open "+l),r()};class _g extends fa{constructor(r){let o=t,l={HcuKl:function(b,p,T,L){return e[j(782)](b,p,T,L)},SWQod:function(b,p,T){return e[j(1563)](b,p,T)},SBoZd:e[o(533)],ZuBPn:function(b,p){return b===p},Mnxro:function(b,p){return e[o(1128)](b,p)},jRiIi:e[o(195)],xzbEu:function(b,p){return e.wgsjB(b,p)},lkZhn:e.sxDlK,eJNdG:e[o(1511)],FsOJm:function(b,p){return b===p},WVDeo:function(b,p,T,L){return e.wktIh(b,p,T,L)},MlYWE:function(b,p,T){return b(p,T)},Rwlkp:e[o(1015)],WRVAc:function(b,p,T){return e[o(691)](b,p,T)},aYRXe:function(b,p,T){return e[o(1303)](b,p,T)},fHhxe:function(b,p){return e[o(888)](b,p)},iJUiL:e[o(1072)],FwdkZ:e[o(1374)],TZcVT:e[o(147)],eSwLT:"qGDZf",uDKEv:function(b,p,T){return e.VXphl(b,p,T)},dBCZE:o(817)};super(),this[o(992)+o(1081)+o(373)]=!0,this[o(562)+"er"]=rr,this[o(1556)]=Np,this[o(400)+"T"]=Pn,this._isMiniWX=Xr,this[o(464)+"r"]=Qr,this[o(1496)+o(673)]=[],this["_endpoin"+o(1075)]=null,this["_readyCl"+o(864)]=!1,this[o(1221)+o(576)]="arraybuf"+o(1361),this[o(524)+"Lock"]=!1,this[o(524)+o(629)+o(617)]=null,this[o(1581)+o(325)+"tId"]=null,this[o(193)+o(1167)+"Id"]=null,this[o(140)]=0,this[o(1218)]=!1,this[o(202)]="",this[o(214)+o(1340)]=null,this[o(1276)+"anager"]=null,this[o(1135)+o(1619)]=null,this[o(1232)+"ls"]=e[o(781)],this[o(726)]=3,this[o(1216)+"NG"]=0,this[o(299)]=1,this[o(1426)]=2,this[o(928)]=b=>{let p=o;try{l[p(1334)](ll,this,b,[gg,mg,wg])}catch(T){let L=l.SWQod(at,l[p(250)],{message:T[p(143)],code:rn[p(911)+"OR"],error:T});this[p(1454)+p(1392)+p(346)](L)}},this[o(1171)+"ge"]=async b=>{let p=o,{pingInterval:T,pingFrequency:L}=this[p(388)];if((l[p(602)]("hi",b.data)&&l[p(776)](l.jRiIi,L)||l.xzbEu(l.lkZhn,L))&&(this["_clearPi"+p(270)](),this.emit(l[p(938)],p(817)),this[p(193)+"gTimeoutId"]=l[p(1525)](setTimeout,this[p(420)].bind(this),T)),!l[p(157)]("hi",b[p(921)]))try{l[p(1592)](ll,this,b,[Jp,Vp,xg,pg,hg,Yp])}catch(N){let G=l[p(390)](at,l[p(250)],{message:N[p(143)],code:rn["MESSAGE_"+p(909)],error:N});this[p(1454)+p(1392)+"ent"](G)}},this._onError=b=>{let p=o;if(e[p(178)]===p(395))return!!this[p(849)];{let T=this[p(1185)+p(1075)]?.checkReachMaxTries(),L=this[p(1185)+"tManager"]?.[p(1017)+p(1422)+"nt"]();if(T&&!b[p(143)])if(e.YbFLz!==e.vnFEc){let N=p(1376)+L+(" fail, m"+p(1273)+p(1457)+"ed");this[p(1454)+p(1392)+p(346)](e.bjDxB(at,e[p(533)],{message:N,code:rn["MAX_RETR"+p(1086)+"R"],error:b}));return}else this[p(438)](nGCzcS[p(1602)],_0x46a2a3(p(961),{..._0x570e4a}));this._ws&&e[p(1338)](this._ws[p(553)+"te"],this.OPEN)&&this[p(1516)+p(711)](),this[p(1454)+p(1392)+"ent"](e.INAVO(at,e[p(533)],{message:b.message,code:rn["NATIVE_E"+p(500)],error:b}))}},this[o(1483)]=async b=>{let p=o,T={dXqBu:function(L,N){return l.fHhxe(L,N)}};if(p(892)!==l[p(986)]){this[p(1482)+p(1413)](),this._clearPingTimer(),this[p(1253)+"sListeners"](),this[p(274)]=null,this[p(524)+p(842)]=!1;let L=this["_endpoin"+p(1075)]?.["checkRea"+p(1551)+"es"]();if(!L&&this[p(1014)+"orOnline"]()&&!this[p(141)+p(864)]){let N=this[p(1185)+p(1075)]?.[p(1017)+p(1422)+"nt"](),G=this[p(388)][p(1455)+p(550)+p(308)](b[p(965)],b[p(954)]);this[p(1454)+p(1246)+p(346)](l[p(1316)](gt,l[p(1602)],{code:1006,reason:b[p(954)]||p(547)+p(309)+p(1315)+p(1489)+p(1169)+p(372)+N,willReconnect:G})),G&&this[p(524)]();return}if(l.fHhxe(1e3,b.code)&&this[p(141)+p(864)]){this["_dispatc"+p(1246)+"ent"](l[p(390)](gt,l[p(1602)],{code:1e3,reason:l.FwdkZ})),this[p(1185)+p(1075)]?.["resetEnd"+p(605)+"fig"](),this[p(1135)+p(1619)]?.[p(545)+"nter"]();return}if(l.fHhxe(1e3,b[p(965)])&&L){let N=this[p(1185)+p(1075)]?.[p(1017)+"ntEndpoint"](),G=b[p(954)];G||(G=await qp(this[p(202)])),G="connecting faile"+p(1375)+G+(p(294)+p(515))+N+(p(1494)+p(773)+p(1261)),this["_dispatc"+p(1246)+p(346)](l[p(390)](gt,l.Rwlkp,{code:b[p(965)],reason:G}));let q=p(1376)+N+(p(670)+"ax retri"+p(1457)+"ed");this[p(1454)+p(1392)+p(346)](l[p(1316)](at,l[p(250)],{message:q,code:rn[p(396)+p(1086)+"R"]})),this["_endpoin"+p(1075)]?.[p(183)+p(605)+p(1486)](),this[p(1135)+"sCounter"]?.[p(545)+p(506)]();return}if(l.fHhxe(1e3,b.code)&&!b[p(954)])if(l[p(539)]===l.eSwLT){let N=_0x3e27fc[p(1431)](":");_0xa8d643&&(_0x342ea7=N[p(1421)]),_0x208a56+=N[p(1421)];for(let G=0;G<N[p(1421)];G++)if(RUvPbF.dXqBu(4,N[G].length)){let q=_0x146a42[p(1054)+"g"](0,4-N[G][p(1421)]),J=q[p(569)](N[G]);_0xa53510[p(527)](J)}else _0x2e3258[p(527)](N[G]);_0x559c0b=!1}else{let N=this[p(1185)+p(1075)]?.[p(1017)+p(1422)+"nt"]();this[p(1454)+p(1246)+p(346)](l[p(1146)](gt,p(961),{code:b[p(965)],reason:p(547)+p(309)+p(1315)+p(1489)+"n, hostn"+p(372)+N})),this[p(1185)+p(1075)]?.[p(183)+p(605)+p(1486)](),this[p(1135)+p(1619)]?.["resetCou"+p(506)]();return}this[p(1454)+p(1246)+p(346)](b),this[p(1185)+p(1075)]?.[p(183)+"pointCon"+p(1486)](),this[p(1135)+"sCounter"]?.["resetCou"+p(506)]()}else{let{offset:L}=_0x294397(_0x4884c4,_0x568a30);_0x6dbaf0=L;let N={cursor_name:"",cursor:0,service:0},{value:G,offset:q}=nGCzcS[p(1316)](_0x3a9adb,_0x587b7d,_0x2b4bcc);N[p(949)]=G,_0x1c8082=q;let{value:J,offset:Xe}=nGCzcS[p(643)](_0x473774,_0x2da5c7,_0x29686d);_0x4ffab5=Xe,N[p(1082)+p(970)]=nGCzcS[p(1592)](_0x21af13,_0x263839,_0x3ea65b,_0x54639d+J),_0x22b51d+=J;let{value:ct,offset:It}=_0xed4e3b(_0x399604,_0x4ca275);N[p(1330)]=ct[p(884)](),_0xc77433=It,_0x3ef285[p(527)](N)}},this[o(967)]=null,this.onerror=null,this[o(1165)+"e"]=null,this.onopen=null,this[o(1360)+o(601)]=null,this[o(1367)+"eAck"]=null,this["onStopIm"+o(1554)+"yReconnect"]=null,this[o(414)+o(526)]=this["_handleO"+o(526)].bind(this),this[o(414)+"ffLine"]=this[o(414)+o(248)][o(448)](this),this["_handleP"+o(1434)]=this["_handleP"+o(1434)][o(448)](this),this[o(1389)+"ageShow"]=this["_handleP"+o(1341)][o(448)](this),this[o(388)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e.wFgPz(1,0),service:0,logIDGenerator:s,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:o(1257),pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[o(648)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:m}=r,_=Array[o(1006)](f)?f:e[o(356)](e.nVSse,typeof f)?[f]:[];if(!_||_.length===0)throw new Error(e[o(1490)]);if(!Fp(m))throw new Error(e[o(1506)]);Object[o(1203)](this._options,r),this["_endpoin"+o(1075)]=new dl(_,this[o(388)].maxRetries),this[o(1135)+o(1619)]=new Gp(this[o(388)][o(273)+o(332)]),this[o(388)][o(297)+o(841)]&&(e[o(865)]==="NHHCz"?(_0x540b32["removeEv"+o(1133)+o(686)](nGCzcS[o(993)],_0x41cc77),_0x535466[o(704)+"entListe"+o(686)](nGCzcS.SBoZd,_0x101380)):(this._isInit=!0,this[o(524)]())),this[o(388)][o(519)+"tworkCha"+o(1442)]&&(this[o(400)+"T"]||this._isMiniWX?this["_onPageN"+o(1571)+o(764)]():this[o(562)+"er"]&&this[o(1048)+o(997)+"Listener"]())}[t(414)+"nLine"](){let r=t;this[r(388)][r(923)+r(676)+r(251)]||this[r(141)+r(864)]||this[r(434)+r(601)]()}[t(414)+"ffLine"](){let r=t;this[r(637)+r(264)+"t"]();let o=ua(e.Aeycv,{message:"stop imm"+r(882)+" reconnect"});this[r(640)+r(1554)+r(1309)+"ct"]&&this[r(640)+r(1554)+"yReconnect"](o)}[t(1048)+"balEvent"+t(166)](){let r=t;this[r(562)+"er"]&&window[r(476)+r(166)](e[r(479)],this["_handleO"+r(526)]),this[r(562)+"er"]&&window[r(476)+r(166)](e.sfLtD,this[r(414)+r(248)]),this[r(562)+"er"]&&window[r(476)+"Listener"](e[r(1539)],this[r(1389)+r(1434)]),this[r(562)+"er"]&&window[r(476)+"Listener"](e[r(1495)],this[r(1389)+r(1341)])}[t(292)+t(997)+t(166)](){let r=t;this._isBrowser&&window.removeEventListener(e[r(479)],this[r(414)+r(526)]),this._isBrowser&&window[r(704)+r(1133)+r(686)](e[r(1403)],this[r(414)+"ffLine"]),this[r(562)+"er"]&&window[r(704)+"entListener"](r(1606),this[r(1389)+"ageHide"]),this._isBrowser&&window["removeEv"+r(1133)+r(686)](e[r(1495)],this[r(1389)+r(1341)])}[t(1389)+"ageHide"](r){let o=t,l={WSlsC:function(f,m){return e.tJQus(f,m)}};if(e.nUzEv(e.gTJGV,e[o(1580)])){let f=this._qosDB.getItem(this[o(213)]);return _0x1aad99[o(1305)](TuSZvi[o(301)](f,"{}"))[_0x3840da]}else!r[o(1096)+"d"]&&(this[o(562)+"er"]&&window[o(704)+o(1133)+"ner"](o(1606),this[o(1389)+"ageHide"]),this._isBrowser&&window["removeEv"+o(1133)+"ner"](e[o(1495)],this[o(1389)+"ageShow"]),this.close()),this[o(562)+"er"]&&window[o(704)+o(1133)+"ner"](e[o(479)],this[o(414)+o(526)]),this[o(562)+"er"]&&window[o(704)+o(1133)+o(686)](e.sfLtD,this[o(414)+o(248)])}[t(1389)+"ageShow"](r){let o=t;r[o(1096)+"d"]&&(this[o(1014)+o(1344)]()&&(!this[o(274)]||e[o(941)](this[o(274)][o(553)+"te"],this[o(299)])||this[o(274)].readyState!==this[o(1216)+"NG"])&&this[o(414)+o(526)](),this[o(562)+"er"]&&window[o(476)+o(166)](e[o(479)],this._handleOnLine),this[o(562)+"er"]&&window[o(476)+"Listener"](o(1264),this["_handleO"+o(248)]))}async["_generat"+t(431)](r){let o=t,l={AFUbD:function(f,m){return e[j(1285)](f,m)},lWqBe:function(f,m){return f+m},QPGXV:function(f,m){return e[j(185)](f,m)},lLZnw:function(f,m){return e[j(1623)](f,m)},umPOA:function(f,m){return f<<m},poZol:function(f,m){return e[j(412)](f,m)},jOJkv:function(f,m){return e[j(1056)](f,m)},lqUYs:function(f,m){return e[j(451)](f,m)},oYrDm:function(f,m){return e.tqqAt(f,m)},OmlPQ:function(f,m,_){return f(m,_)},HknCz:function(f,m){return e[j(1076)](f,m)},DSSHe:function(f,m){return f>>m},jQGFS:function(f,m){return e[j(453)](f,m)}};if(e.pTiuZ!==e.vaALk){let{fpID:f,deviceID:m,bddID:_,ttwID:b,accessKey:p,aID:T,customParams:L={},enableAutoAck:N,enableQoS:G,QoSLevel:q,env:J}=this[o(388)],Xe,ct,It;this._isBrowser||this[o(775)+"X"]||this[o(400)+"T"]?(Xe=location&&e[o(362)](e.dVYEl,location[o(813)])?e.NvTlQ:e[o(770)],ct=r[o(523)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),It=/^wss(.*:\/\/)/[o(945)](r)?r:""+Xe+ct):(Xe=e.NvTlQ,ct=r[o(523)](/(^http)((?:[s]*:\/\/))/,""),It=/(^ws)((?:[s]*:\/\/))/[o(945)](ct)?ct:""+Xe+ct);let wl=_?"bd_did":b?e[o(447)]:"device_id",_l=_||b||m;if(!_l||!wl)throw new Error(o(1113)+o(1172)+o(1225)+"viceID o"+o(386));let yg=e[o(603)](e[o(507)],typeof L)?await e.TcuDg(L):L,Eg=J?e[o(457)](Up,J[o(1201)],J[o(745)]):{},_a=Object[o(1203)]({device_platform:e[o(477)],version_code:e[o(1570)],access_key:p,fpid:f,aid:T,[wl]:_l,xsack:N?1:0,xaack:N?1:0,xsqos:G?1:0,qos_level:G?q:void 0,qos_sdk_version:2,...Eg},yg),bg=Object[o(755)](_a)[o(1579)]((ya,Ea)=>_a[Ea]!==void 0?""+ya+(ya?"&":"?")+Ea+"="+_a[Ea]:ya,"");return It+"/ws/v2"+bg}else _0x51102e=_0xc23aba[QYhNIv[o(1481)](_0x51bd19,_0x21c9b4)+1],_0xbd6059=_0x37206c[QYhNIv.lWqBe(_0x24fc60+_0x37582f,2)],_0x269944=_0x3ac925[QYhNIv[o(1481)](_0x27b52a,_0x3d04d4)+3],QYhNIv.QPGXV(QYhNIv.lLZnw(QYhNIv[o(844)](_0xcfd12c,_0x1acc42<<8),QYhNIv[o(754)](_0xc5eb5b,16)),12632256)!==8421504?_0x563c5e+=_0x5443d5:(_0x57c3ad=QYhNIv[o(844)](QYhNIv[o(844)](QYhNIv[o(844)](QYhNIv[o(754)](7&_0x4b7c2e,18),QYhNIv[o(1555)](63&_0x4b4902,12)),QYhNIv.jOJkv(63,_0xdc2505)<<6),63&_0x591544),QYhNIv[o(625)](_0xabe438,65536)||QYhNIv[o(1326)](_0x50ef3e,1114111)?_0x37d1a3+=_0x15ed14:(_0x914346-=65536,_0x2f70c8+=QYhNIv[o(481)](_0x22749d,QYhNIv[o(528)](QYhNIv[o(440)](_0x5b2ef9,10),55296),QYhNIv[o(220)](1023,_0x2bd66e)+56320),_0x517563+=3))}async _connect(){let r=t,o={jRjdn:function(l,f){return l!==f},xsZbL:e.SwxKN,ctJvK:e.sfLtD};if(e[r(492)]!==r(317))_0x502ed0[r(1096)+"d"]&&(this["_navigat"+r(1344)]()&&(!this[r(274)]||YGpgxP[r(402)](this._ws[r(553)+"te"],this.OPEN)||YGpgxP[r(402)](this._ws[r(553)+"te"],this[r(1216)+"NG"]))&&this[r(414)+"nLine"](),this[r(562)+"er"]&&_0x10ca45[r(476)+"Listener"](YGpgxP[r(1106)],this[r(414)+"nLine"]),this[r(562)+"er"]&&_0xeec885[r(476)+"Listener"](YGpgxP.ctJvK,this[r(414)+"ffLine"]));else{if(this[r(524)+"Lock"]||this[r(141)+r(864)])return;this[r(524)+"Lock"]=!0;try{let l=this[r(1185)+r(1075)]?.[r(1132)+r(632)+r(985)+r(1089)+r(1110)](),{timeoutInterval:f}=this._options;if(l){let _=this["_endpoin"+r(1075)]?.[r(1017)+r(1422)+"nt"](),b=this["_endpoin"+r(1075)]?.[r(696)+r(859)+r(694)+r(349)+"unt"](),p=this[r(1185)+r(1075)]?.["getCurre"+r(1422)+r(246)+"ount"]();if(b){let T=r(1376)+_+(r(819)+r(1494)+r(773)+r(1028)+"ill use "+r(604)+r(1159))+b+(r(437)+"y"),L=e[r(700)](at,e[r(533)],{message:T,code:rn[r(396)+r(1086)+"R"]});this._debug(T),this[r(1454)+"hErrorEv"+r(346)](L),this[r(202)]=await this[r(724)+"eUrl"](b),this[r(586)]("connect "+b+" "+p+r(887)),this[r(1253)+r(394)+"rs"]()}else{let T="connect "+_+(r(819)+r(1494)+"tries re"+r(1261));this[r(586)](T),this[r(1454)+"hErrorEvent"](e[r(546)](at,e[r(533)],{message:T,code:rn[r(396)+r(1086)+"R"]}));return}}else{let _=this["_endpoin"+r(1075)]?.[r(1017)+r(1422)+r(1280)+"ateCount"](),b=this["_endpoin"+r(1075)]?.["getCurre"+r(1422)+r(246)+r(1013)]();this[r(202)]=await this[r(724)+"eUrl"](e.MKpIq(_,"")),this._debug(r(1376)+_+" "+b+" times"),this[r(1253)+r(394)+"rs"]()}if(this[r(1218)])this[r(1218)]=!1;else{let _=e[r(1610)](ua,e[r(1094)],{message:e[r(278)]});this[r(1360)+r(601)]&&this[r(1360)+"econnect"](_)}let m=this._endpointManager?.["getCurre"+r(1422)+"ntTriesC"+r(1013)]()||0;e[r(1439)](m,1)&&await this[r(708)](e[r(622)](m,1)),this[r(586)](r(547)+r(1118)+this._url+(r(1154)+r(814))+this._protocols),this._ws=e[r(530)](Bp,{url:this._url,protocols:[this[r(1232)+"ls"]],headers:this[r(388)][r(979)+r(926)+"s"][r(200)+"tpHeader"]},this._options.ws),(this[r(562)+"er"]||this[r(464)+"r"])&&this[r(274)]&&(this._ws[r(329)+"pe"]=this[r(1221)+r(576)]),this[r(1396)+r(1384)](),this["_connectionTimeo"+r(617)]=e[r(828)](setTimeout,this[r(731)+"ut"].bind(this),f)}catch(l){throw this[r(524)+r(842)]=!1,l}}}[t(1482)+t(1413)](){let r=t;e[r(834)](clearTimeout,this[r(524)+r(629)+r(617)]),this[r(524)+r(629)+"utId"]=null}["_clearPi"+t(270)](){let r=t;e[r(1036)](clearTimeout,this["_pingPon"+r(1167)+"Id"]),e[r(1213)](clearTimeout,this[r(1581)+"ctTimeou"+r(868)]),this["_pingPon"+r(1167)+"Id"]=null,this[r(1581)+r(325)+r(868)]=null}[t(586)](...r){let o=t;this[o(388)].debug&&console[o(1219)][o(1512)](console,[e[o(228)],...r])}[t(1239)+t(249)+"e"](r){let o=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:m}=this[o(388)],_=l*Math[o(984)](m,e[o(1188)](r,1));return e[o(286)](_,f)?f:_}_ping(){let r=t;if(this[r(274)]&&e[r(551)](this[r(274)][r(553)+"te"],this[r(1216)+"NG"])){this[r(238)+r(270)](),this[r(193)+r(1167)+"Id"]=setTimeout(this[r(420)][r(448)](this),this._options[r(375)+r(366)]);return}if(!this[r(274)]||e.OPkBM(this[r(274)][r(553)+"te"],this[r(299)]))return void this[r(434)+r(601)]();this[r(274)]&&this[r(274)][r(654)]("hi"),this["_reconne"+r(325)+r(868)]=e[r(1411)](setTimeout,this["_handleReconnect"+r(441)].bind(this),this._options["pingTime"+r(1214)+r(744)])}["_handleR"+t(601)+"Timeout"](){let r=t;this[r(1135)+r(1619)]?.addCount(),this[r(438)](e[r(1e3)],e.rJsQs),this[r(1135)+"sCounter"]?.[r(980)+r(946)+"nt"]()?this[r(434)+"econnect"]():this._ping()}[t(1014)+t(1344)](){let r=t;return this._isMiniTT||this[r(775)+"X"]?this[r(992)+r(1081)+r(373)]:(this[r(562)+"er"]||this._isWorker)&&this._options[r(519)+"tworkCha"+r(1442)]?navigator[r(796)]:!0}[t(434)+t(601)](){let r=t;!this[r(1014)+r(1344)]()||this[r(141)+"osed"]||(this[r(1185)+r(1075)]?.["resetEnd"+r(605)+r(1486)](),this[r(1135)+r(1619)]?.[r(545)+r(506)](),this[r(274)]?this["_disconn"+r(711)](1001,e.VLzYu,!0):this[r(524)]())}[t(1518)+t(1571)+t(764)](){let r=t;this._isMiniTT?tt["onNetwor"+r(1298)+r(826)](({isConnected:o})=>{let l=r;this[l(992)+l(1081)+l(373)]=o,o?this[l(414)+"nLine"]():this[l(414)+"ffLine"]()}):this._isMiniWX&&wx[r(655)+r(1298)+r(826)](({isConnected:o})=>{let l=r;this[l(992)+l(1081)+"line"]=o,o?this[l(414)+"nLine"]():this[l(414)+l(248)]()})}[t(708)](r){return new Promise(o=>{let l=j;e[l(1209)](setTimeout,o,this[l(1239)+l(249)+"e"](r))})}[t(1516)+t(711)](r=1e3,o="",l=!1){let f=t;this[f(274)]&&this[f(637)+f(264)+"t"](r,o,l)}[t(731)+"ut"](){let r=t,o=this[r(1185)+r(1075)]?.[r(1017)+r(1422)+"nt"]();this._debug(r(1376)+o+" timeout"),this["_disconn"+r(711)](1001,e.IGtyc,!0)}[t(1052)](r){let o=t,l=e.QtWnS(Ut,r);this[o(274)]&&e[o(280)](this[o(274)][o(553)+"te"],this[o(299)])&&(this[o(274)]&&this._ws[o(654)](l),this[o(586)](o(901),r))}[t(1253)+t(394)+"rs"](){let r=t;this[r(274)]&&(this[r(274)][r(704)+"entListe"+r(686)]("open",this._onOpen),this._ws[r(704)+r(1133)+"ner"](e[r(1015)],this[r(1483)]),this[r(274)]["removeEv"+r(1133)+"ner"](e.qpoCC,this[r(1171)+"ge"]),this[r(274)][r(704)+r(1133)+r(686)](e[r(533)],this[r(510)]))}["_addWsLi"+t(1384)](){let r=t,o=(r(1151)+"4").split("|"),l=0;for(;;){switch(o[l++]){case"0":this[r(274)][r(476)+r(166)](e[r(1015)],this[r(1483)]);continue;case"1":this[r(274)][r(476)+r(166)](r(143),this[r(1171)+"ge"]);continue;case"2":this[r(274)][r(476)+"Listener"](e[r(1582)],this._onOpen);continue;case"3":if(!this[r(274)])return;continue;case"4":this[r(274)][r(476)+r(166)](r(1284),this[r(510)]);continue}break}}[t(1047)+"nceClose"](r=1e3,o=""){let l=t,f={hrLdi:l(608)+"reason"};try{l(968)!==e[l(1382)]?this[l(274)]&&this[l(274)].close(r,o):(_0x3aa180[l(948)][l(719)+l(516)](_0x1e8fb1),_0x44a26e[l(1537)+l(1522)]=void 0,_0xb6de94(_0xa379af&&_0x2647cd[l(223)]||LjOHkV[l(1594)]))}catch{}}["_destroy"+t(264)+"t"](r=1e3,o="",l=!1){let f=t;if(e.oeqNW(e[f(1312)],e[f(1195)])){if(this[f(238)+f(270)](),this[f(1482)+f(1413)](),this[f(1253)+f(394)+"rs"](),this[f(1047)+f(1196)](1e3,o),this[f(524)+"Lock"]=!1,l&&this[f(1014)+f(1344)]()&&!this[f(141)+f(864)])if(e[f(1616)]("QxKYF",f(1237))){if(this[f(1185)+f(1075)]?.[f(980)+f(1551)+"es"]()){let _=this[f(1185)+f(1075)]?.["getCurre"+f(1422)+"nt"]();this[f(1454)+f(1246)+"ent"](gt(f(961),{code:1006,reason:f(1376)+_+(f(819)+", max re"+f(773)+f(1261)),wasClean:!0}))}else if(e.HTQjJ(e[f(1465)],f(230))){let _=this[f(388)][f(1455)+f(550)+f(308)](r,o);this[f(1454)+f(1246)+f(346)](gt(e[f(1015)],{code:r,reason:o,wasClean:!0,willReconnect:_})),_&&this[f(524)]()}else return _0x5e892d[f(501)+f(532)][1]?void 0:_0x21607d[f(501)+f(1589)](_0x193b30[f(501)+"oreNames"][0]);return}else return{bytes:_0x2e7fa0,offset:0,limit:_0x2c4594.length};this[f(1014)+f(1344)]()||this[f(141)+"osed"]?this["_dispatc"+f(1246)+"ent"](gt(e[f(1015)],{code:r,reason:e.luvTS})):this[f(1454)+f(1246)+f(346)](e.ruyZw(gt,"close",{code:1006,reason:e.ecTBN})),this[f(274)]=null,this[f(1185)+f(1075)]?.[f(183)+f(605)+f(1486)](),this[f(1135)+f(1619)]?.[f(545)+f(506)]()}else this[f(438)](f(1284),e[f(656)](_0x2d5c11,f(1284),{message:this[f(293)+f(419)+f(540)](_0x5bbc6c)}))}[t(1454)+t(749)+"nt"](r){let o=t;this[o(438)](e[o(1582)],r),this[o(340)]&&this[o(340)](r)}["_dispatc"+t(1140)+t(1491)](r){let o=t;this[o(438)](o(143),r),this[o(1165)+"e"]&&this[o(1165)+"e"](r)}[t(1454)+"hAckMess"+t(756)](r){let o=t;this[o(438)](o(1549),r),this["onReceiv"+o(1428)]&&this[o(1367)+"eAck"](r)}[t(1454)+t(1392)+t(346)](r){let o=t;this[o(438)](e[o(533)],r),this[o(339)]&&this[o(339)](r)}[t(1454)+"hCloseEv"+t(346)](r){let o=t;this[o(438)](e[o(1015)],r),this[o(967)]&&this[o(967)](r)}get[t(329)+"pe"](){let r=t,o={Tjmtz:function(l,f){return l(f)},fYVtj:function(l,f){return e[j(1002)](l,f)},rhGGx:function(l,f){return e[j(1044)](l,f)},tOXQh:function(l,f){return e[j(529)](l,f)},jSWpL:function(l,f){return l&f},VfOvD:function(l,f){return l<<f}};if(e[r(1144)]("EVbzt",e[r(584)]))_0x264264=nPPsOE[r(1065)](_0xdf33d0,_0x953c5b),_0x5cf292|=nPPsOE[r(1080)](127&_0x3b9ada,14),nPPsOE[r(932)](128,_0x4359fa)&&(_0x3cd1e9=nPPsOE[r(1065)](_0x307de7,_0x3c6a00),_0x14e706|=nPPsOE[r(812)](nPPsOE.jSWpL(127,_0x263b09),21),nPPsOE.jSWpL(128,_0x3be3c1)&&(_0x1c041f=_0x304a49(_0x45eff4),_0x4876d5=127&_0x593fa8,nPPsOE[r(932)](128,_0x488468)&&(_0x48f6eb=_0x2470cd(_0x2ce9b0),_0x28fa5e|=nPPsOE[r(1536)](127&_0x22e784,7))));else return this[r(274)]?this[r(274)][r(329)+"pe"]:this["_binaryT"+r(576)]}set[t(329)+"pe"](r){let o=t;this[o(1221)+o(576)]=r,this._ws&&(this[o(274)][o(329)+"pe"]=r)}get[t(874)+"nt"](){let r=t;return e.vcath===e.eqlsM?paHMVq[r(1480)](typeof _0x356e64,r(679))?paHMVq[r(231)](_0x5d75d3,_0x1e971e):(paHMVq[r(1388)](_0x40a508,_0x1e9ca3)&&paHMVq[r(728)](_0x116df4,_0x53a0d3),paHMVq[r(508)](_0x4ab679,_0x157b01,_0x5ef8e7())?new _0x2a213d(_0x5b8014,_0x2df471):_0x54c5fd):this[r(1185)+r(1075)]?.["getCurre"+r(1422)+r(246)+r(1013)]()||0}get[t(543)+"Amount"](){let r=t,o=this["_message"+r(673)].reduce((l,f)=>(l+=f&&f[r(918)+"th"]||0,l),0);return e[r(1364)](o,this[r(274)]?this[r(274)][r(543)+r(1342)]:0)}get[t(1347)+"ns"](){let r=t;return this[r(274)]?this[r(274)][r(1347)+"ns"]:""}get[t(813)](){let r=t;return this[r(274)]?this[r(274)][r(813)]:""}get[t(553)+"te"](){let r=t,o={yEraL:e.TUARK};if(e[r(1005)](e[r(822)],e[r(822)]))return this[r(274)]?this[r(274)][r(553)+"te"]:this[r(388)][r(297)+r(841)]?this[r(1216)+"NG"]:this.CLOSED;{let l=r(1376)+_0x3f3ec7+(" timeout, max re"+r(773)+"ached");this[r(586)](l),this[r(1454)+r(1392)+"ent"](_0x1fef87(hnRupu[r(707)],{message:l,code:_0x70246f[r(396)+r(1086)+"R"]}));return}}get url(){let r=t;return this._ws?this[r(274)][r(942)]:this[r(202)]}[t(961)](r=1e3,o){let l=t,f=e[l(1275)][l(1431)]("|"),m=0;for(;;){switch(f[m++]){case"0":this["_readyCl"+l(864)]=!0;continue;case"1":this[l(214)+l(1340)]?.closeDB();continue;case"2":this[l(1482)+l(1413)]();continue;case"3":this[l(238)+l(270)]();continue;case"4":this[l(292)+l(997)+l(166)]();continue;case"5":if(e[l(265)](this[l(274)].readyState,this[l(726)])||e[l(1527)](this[l(274)][l(553)+"te"],this[l(1426)]))return void this._debug("close, w"+l(1608)+l(1559));continue;case"6":if(!this._ws)return void this[l(586)](e[l(164)]);continue;case"7":this["_destroy"+l(264)+"t"](r,o);continue}break}}async[t(654)](r,o){let l=t;if(e[l(615)](null,r))throw new Error(e.MdzwS);e.nMGZV(l(1355),typeof r)&&(r=JSON.stringify(r)),l(1198)!=typeof r&&!(r instanceof ArrayBuffer)&&!(r[l(890)]&&e[l(1210)](r[l(890)],ArrayBuffer))&&(r=JSON[l(240)+"y"](r));let f=await e[l(1333)](hl,r),m=e[l(417)](zp,r),{method:_=0,service:b=this[l(388)][l(949)],logID:p=this[l(388)][l(1260)+"erator"](),headers:T=this[l(388)][l(944)],payloadEncoding:L=this[l(388)][l(1173)+l(1134)],payloadType:N=this[l(388)][l(538)+l(576)],logIDNew:G=this[l(388)][l(298)+"Config"][l(262)+"toGenera"+l(866)+"ew"]?e[l(405)](i,this[l(388)].logIDNewConfig[l(680)]):""}=e[l(952)](o,{});if(!b)throw new Error(l(1113)+l(752)+l(1174)+l(609));let q={SeqID:fe[l(1318)+"er"](this[l(140)]++),LogID:fe[l(1318)+"er"](p),service:b,method:_,headers:T,payloadEncoding:e[l(1388)](L,Object)?L[l(1098)]?L.encoding:"":L,payloadType:e[l(1083)](N,Object)?N[l(1460)]?N[l(1460)]:m:N||m,payload:f,LogIDNew:G},J=e[l(734)](Ut,q);return this[l(274)]&&e[l(1616)](this[l(274)][l(553)+"te"],this.OPEN)?(this[l(274)]&&this[l(274)][l(654)](J),this._debug(e[l(916)],q)):e.fXrcL(this["_message"+l(673)][l(1421)],this[l(388)]["maxMessa"+l(1147)+l(1041)])?(this[l(1496)+"Queue"][l(527)](J),this[l(586)]("enqueue",q)):(this[l(1496)+l(673)][l(710)](),this[l(1496)+l(673)][l(527)](J)),{seqID:this[l(140)],logID:p,logIDNew:G}}async[t(1455)+"t"](r){let o=t,{url:l}=e[o(952)](r,{}),f=Array[o(1006)](l)?l:e[o(1552)](e[o(1178)],typeof l)?[l]:[];r&&Object[o(1203)](this[o(388)],r),f&&f[o(1421)]?this[o(1185)+o(1075)]=new dl(f,this._options[o(1141)+"es"]):this[o(1185)+o(1075)]?.[o(183)+o(605)+o(1486)](),this[o(1135)+o(1619)]?.["resetCou"+o(506)](this._options["pingLoss"+o(332)]),this[o(141)+o(864)]=!1,this[o(274)]&&this[o(274)][o(553)+"te"]!==this[o(726)]?this._disconnect(1e3,e[o(321)],!0):(this[o(1218)]=!0,this._connect())}async[t(1136)](){let r=t;if(!this["_connect"+r(842)])if(e.nynlB(e[r(1050)],e[r(566)])){let o=e[r(1215)].split("|"),l=0;for(;;){switch(o[l++]){case"0":this[r(1218)]=!0;continue;case"1":this["_readyCl"+r(864)]=!1;continue;case"2":this[r(524)]();continue;case"3":this[r(1185)+r(1075)]?.[r(183)+r(605)+r(1486)]();continue;case"4":this[r(1135)+r(1619)]?.[r(545)+"nter"]();continue}break}}else this[r(473)+r(1013)]=_0x42c8e4,this[r(1087)]=0}[t(476)+"Listener"](r,o){this.on(r,o)}["dispatch"+t(1491)](r){let o=t,{type:l}=r;this[o(438)](l,r)}["removeEv"+t(1133)+"ner"](r,o){this.off(r,o)}[t(1255)](){let r=t,o={NuduG:function(l,f){return e[j(869)](l,f)},dAtzT:e[r(1511)],aeOGo:e[r(1386)],fwAZw:function(l,f,m){return e.WnxSF(l,f,m)},pHJIt:e[r(1e3)]};return new Promise((l,f)=>{let m=r,_={tkYkS:function(T,L){return o.NuduG(T,L)},GcGfC:o[m(1319)],JEGTu:"ping_once_timeout",sfgyo:o.aeOGo};this[m(238)+m(270)](),this[m(193)+m(1167)+"Id"]=o.fwAZw(setTimeout,this[m(420)][m(448)](this),this._options[m(375)+m(366)]);let b=()=>{let T=m;_[T(1517)](l,T(817)),this.off(_[T(963)],b),this[T(425)](_[T(363)],p)},p=()=>{let T=m;f(_[T(1191)]),this[T(425)](_[T(963)],b),this[T(425)](T(371)+"e_timeout",p)};this.on(o[m(1319)],b),this.on(o.pHJIt,p),this[m(420)]()})}}})(),Pe["CustomCl"+M(684)]=Ce[M(1240)+M(684)],Pe[M(561)+"rorEvent"]=Ce[M(561)+M(1156)],Pe.ErrorCode=Ce[M(208)+"e"],Pe[M(1491)]=Ce[M(1491)],Pe[M(650)]=Ce[M(650)],Pe[M(935)+M(374)+M(411)]=Ce[M(935)+M(374)+M(411)],Pe[M(374)+M(411)]=Ce[M(374)+M(411)],Pe[M(627)+"t"]=Ce[M(627)+"t"],Pe["Reconnec"+M(846)]=Ce[M(211)+M(846)],Pe[M(1474)+M(684)]=Ce[M(1474)+M(684)],Pe[M(1099)+M(1156)]=Ce[M(1099)+M(1156)],Pe[M(850)+M(1073)+"nt"]=Ce[M(850)+M(1073)+"nt"],Pe[M(857)+M(843)]=Ce[M(857)+M(843)],Pe[M(1064)+M(291)+M(411)]=Ce[M(1064)+"connectE"+M(411)],Pe["decodedF"+M(360)]=Ce[M(736)+M(360)],Pe[M(1534)+M(970)]=Ce[M(1534)+"ame"];function Vo(){let t=["yxbWBhK","v1DSt3e","z2T2wKG","yMLUyxj5","x2rPC2nVBM4","DgTzA1m","x29UugfNzu4","rK5xr2S","C2v0u3rVCMe","tfDfyM8","sLnptLa","vMXzCgm","y1bQqKK","u1DrB2q","Dxfdzvq","DNPTt2O","tNDJqKS","DvLYD28","tMPbCvq","vfDmvvy","yKnKvxu","y3vYCMvUDeK","zw5JB2rLrNi","senks3e","vMzpDKq","zNjVBNrPzxi","ign1CNnVCIa","B2vVCvK","ChvVz2G","zePOtKK","yLHHs1u","ihn1y2nLC3m","u3rYyxrLz3K","tgfrBfy","yxDPs0W","thHPuLi","terOtLK","ywnR","z0T6tvK","y2HnyxHuCMK","BK1hwLy","y3fmrMO","BwvKAwf0zwW","Cg9AB2W","x2LZtM9Kzq","Dgv4Dc9Qyxy","t3bOAvy","EsbJBg9Zzwq","nhWYFdb8m3W","qwPyuNO","y2XLyxjtDg8","A0Tuufq","qKrQyw0","zw5HyMXLvhi","sxnpBMW","C3rHCNq","CLDMqve","yxL6su4","rhDky2u","zxrxB3jRq2G","y2vZC0HHBMq","BML0AwfSAxO","shPnvLm","t2PlDwG","AMvJDfn0B3i","x3nVy2TLDa","wvHyEMu","CMvKDwnL","z1rkr1y","x3jLy29UBMu","wfPTuhO","sg5OEKG","zxjFDhrS","v1LQtLO","A1Hmt0m","zuf6vMe","y2XVC2veqG","B3jL","BgLUzw5V","tfrdD2C","v1zezw8","u3zdEeG","AhjmzgK","tgLivxO","twLZC2LUzYa","ywz4wui","ze9IA2y","zM9YrwfJAa","CxPVuhi","Evbkzve","uNDSA3a","x2LUAxrqCM8","DxbNCMfKzw4","uxHXwKO","CgfNzwHPzgu","ufj0uLO","CYbHBhjLywq","yNL0zxm","t0P0z0G","DMzSqxq","Aw5PDcbrB1m","Dg1WyK0","aaaaaaaaaaa","rgvKAwnHDgu","B2Tlz3m","EML2Dxe","AwDXEKi","C0nVDw50zxi","rwr4seS","u01wz3q","Dg9VigXHCMC","DwLmBfi","x3nLCuLK","x3jLywr5q2W","BMDTrNe","BwvZC2fNzq","zMXVB3i","BvHJv2e","tNDfsuW","DLrZzey","qw9LELy","B25nzxnZywC","wNnqBfK","rvb6B24","Aw9Ul2PZB24","x2TLEvbHDgG","CLPRreq","C0Tryvi","rwXvz3O","rNnpsM0","ALHzq20","CMvZB2X2zq","r3nXsLi","wfLjvgK","B0TusKG","CwLzrK4","vML0CMO","EvHPte8","tgLZDgvUzxi","A0v3CNO","DhjPBq","tNvbDNC","y3vYDMfSDwu","AKHID2m","uhjHtuq","Aw47y2HHCNm","yM9L","C2rRs3q","Cencsxy","rhDHExK","AurMA0W","CxztuNC","q2nPDgq","vw1iyLi","qMLMA1K","CMvZzxrfBMq","rwTYEMK","quvTywW","zw91CeK","AK5ysMG","r3vfsLq","B25Uzwn0Aw4","nteWmJGWref4AfDh","swvpwgy","t0LxvwO","x3bPBMDqB24","zxrmrhC","qNL1uLC","ruTWChq","vKnYuKu","Dw5KzwzPBMu","qwf2zey","y3vZDg9Tshq","DMfWugq","x3vYBa","y29UC3rYDwm","AuPvChy","C3vIyxjYyxK","C3bSAwnL","EgfiCha","rxjYB3jdB2q","q29Kzq","pxv0zI04","uMvJB25Uzwm","DuLKzey","x3bYzwzPEa","x1fVu01HBMe","zxjYtxnN","tuv6u1O","u3HOrwW","rvbhCgy","rNzYv3i","ALfhrLm","D0LPz1i","CKDftgu","BxnN","zvn1BLu","y3jLyxrLrwW","zg9Uzq","sKXoBhK","D3nSu1i","s3PUz1u","vKXzEKm","A25js2S","AwXLtMfTzq","A3vZu2q","Dfr2q2e","vvDSDKC","EvjtuNu","yw1Lu3bHy2u","x2nSzwfYugK","mNW0Fdf8mhW","C3rYAw5NAwy","ruHNvhm","ENvQtuW","D2DovKq","y29UBMvJDfm","BKLpCuK","BNruCMLLC0m","wMrRDMG","zMzmAw5L","CNzHBfzHBhu","u0jVwMq","BMvJDa","B25dBg9Zzq","q2TgseW","z2v0s2v5","q05prLu","uMT2Eu0","wK1ZEe0","DhjHBNnHy3q","DMn6yuO","x0vysvnu","DKn2CLG","zw5HyMXLqxu","vND2Ahi","v2vIu29JA2u","rxnLC0q","q2vhBLK","vxfezxy","u2vXsuq","zxjHDg9Y","BMDuAw1LCG","q1jevM4","CMTcqMy","CgLUz0XVC3m","x3DZ","BM93","EfL6rgi","tffys3e","BKfIuLy","DMjhCLi","rLnbtM0","y1jQugm","ywXty29Wzq","CNv5wNC","wePHqNm","qM5WB2m","rMfyy1m","vM1wBw0","vMDOr2O","sLP5uhC","BwXsAeG","y29UBMvJDeu","x2rYB3bhBg8","x2zVCM1HDeu","lcbOB3n0BMe","DgHHBIbSB2m","y29TCgXLDgu","yxv0B21HDgK","Bg9NsurozxC","t1bftG","EMT6rLi","v1nSC0m","D0XWDKC","B25fCNjVCG","CMfUzg9T","v01nD2K","AKzvtem","zezRwKK","ChrVCG","BMCGzMfPBgu","svnPrwq","zMLSDgvY","B2fK","q2rODuK","D3fAqxG","B3jRzxjhBg8","wNDvvLi","sKftqNa","Dgv4Dc9WBge","CNnVCKzPBgu","uufjEeW","r2TqrK4","mZbSzLDrvNy","zw5HyMXLuw8","rhPyCMS","y3ruAw1LB3u","rhDRCvC","Dg9Y","v0TRB3m","yMLUyxj5vhK","zNjHBwvuExa","AwXyEu4","q291BNq","EwfSqvO","sfnJB0u","yxbOEhi","z2v0qwXS","vNLJre8","ywXSzwqGBxu","B25LCNjVCG","B25VCgvU","yKPUzLq","EfL6vNe","u1P0z2O","CNvzBvK","AhbdCgq","zw50","DKjzqwS","wxHJu3a","vxbKyxrLq28","zwvVt3i","zNjVBuj5Dgu","wLfyBKG","r3r4zK8","yxKSig5LDhC","EMHzwuC","yND4u2O","wvbuDLC","DwTjB2O","EeDNr2m","CMfTzq","wvrRAwi","BMPssLK","sKvhvhu","rM1Xwfi","Cgu6ia","CNzHBa","AKvxChm","yMflEfu","zK92uwG","yMPeEei","CgLUz19VBMm","yw1LoIa","BgLUzq","twvZC2fNzuu","CgLUz0LUDgu","qw5cueu","vMXfu2O","q3b0ruS","y3vYCMvUDeu","BhHcrLa","rvzIENq","C3vsu0S","AMXAuLu","Buzfq2K","s0rKvuW","CIb0DhDjra","z2fyzvG","x29WDgLVBNm","wvLcA2q","twXzv0u","v2vPEgLUsLm","tuLPtLe","quDhCMK","C0XPC3rLBMu","Ber4Buu","tufyx1jfvfi","Axnby2TdBgu","yw5Hz2vY","ENfxswi","x2LZtwLUAvq","zw5KCg9PBNq","ALjQzg4","CKjNA2e","rfniseu","B2zvuNe","BxnArfe","Bw5XAxO","DujiELa","C2DPza","r3n4wMC","DMvUDa","swPMA2C","AgfZ","x2HHBMrSzu8","mhWZFdj8nNW","zw50zwqGDhK","BMTLtKC","DgvUrxu","CNjVCK1LC3m","x3bPBMC","CxPgEvC","ANrtvve","Eu5cz0y","Awzjt2O","B2zM","qM9LAui","ChrRD0i","ihrYEsbYzwm","C1rNs3q","svzvwMm","zvvYBa","ChbL","C2v0sxrLBq","x2HHBMrSzvi","yNHLv0S","uu1Xvxm","ihrVihjLDhi","zw1PDa","wxrpwhm","rfntsgu","vgLTzw91Da","DcbVzIbYyw4","mJCYmdKWotrTEKvHzeW","DgLTzw91DcW","ywWGy3vYC28","Bw9ZC3C","zKzgBxa","yMLUza","uKLtBey","ueT1Buy","C1zdyvC","B1PQDKO","wwn2CLe","teLrDNO","CMvHzfvjBNq","B3bLBKrc","uxfkzuS","n3W5FdeXFde","zxH0ugf5Bg8","uvrpsK0","qNPfBge","B3bLCNr5","wLLftNG","x2LZv29YA2u","sujoC1O","shHtBNi","C3jJ","ufDdv3C","D3jPDgu","mZiWnZuWnw5KBLrwwa","D2fZq2XLyw4","zLn5zKC","Bwf4tg9ZC0m","seLzANa","uhjPBwfYEuS","ywrKrxzLBNq","vvvcuKe","r3ntwLe","u3D4s04","r0P2qMe","t21Sufe","vwnYwMy","rhrdExq","tg9NsurozxC","uxLWAwu","CePjzK4","t09HC0y","AxnmB25N","r0vqu2S","B2H3zvC","AwXLx25HBwu","q29SC2S","zMX1C2HfEha","BM5Ly3q","teTAvNq","A0XzuhC","vLfbC00","runytgu","q2vZtem","uLjpuG","B2jQzwn0u3q","B3bLBIa","BuTpqvm","sg96DNy","zNjVBujPDhm","BNrLCG","wwncqNO","qwzSBM4","CMTLCKDSB2i","x29UrxjYB3i","B2nRzxrgywK","vfjqtwK","z2v0qwXSs2u","thjJD3K","Bwu6ia","AwXK","rMHIr0q","zwDSy2C","BgLZDgvUtMu","qwDzs0C","uhjwwu0","C2DQr2S","CMvWBgfJzq","x2nVBM5Ly3q","y2fSBa","BKXPBMu","ChvZAa","sgTUq3O","vNbWtui","refuueO","wLffs0q","B3jLtMfTzxm","vfvbuKS","wvzzvwy","EhPyDwW","AMTcA0O","u1rRywK","Cgf5Bg9Hzfq","vfPJvLq","ywDL","rMH5s3y","BxrkCKu","yNvMzMvYzwq","z2LICve","CMvZzxrdB3u","sMHYuw0","y29UBMvJDgK","r3PMC1C","D1bmtM0","DeLUDgvYy2u","tvfzy3q","z2v0q3vYC28","CMvHzhLtDge","BM9Uzv9UB24","x2rItMfTzq","ywjVCNq","Cw9Zx18","CNnVCL92ywW","sgzPyuG","yKH1B1y","q3vZDg9Trxi","x2LZqNjVD3m","t2vKEfm","vxnrAwW","v3Llvva","uvffzeW","t0jnrM4","ywXS","y29Uy2f0","sfrrAKO","rMPnqKe","EeTgCeq","vvDKBve","m3W0Fdf8mhW","BMrLEa","ExbL","qwTIzfK","CMvZDwX0","vgLczKe","r3Peyvm","z0v3tNK","wxDYsxO","EezUwfy","uvv3t20","reiGzMfPBgu","x2rLyNvN","yLLmwLy","ww5csNq","B3r6wgK","CeTeAKe","C2zhs1e","v2fyt3G","Benlvxe","vgTbEMS","u3zLC3q","rwnMBgq","x2LUDgvYDMe","zfbHwMy","whf4C2K","CMvJzwL2zwq","zwnVBM5Ly3q","wNvcug4","CLzftwS","yMfJA3vWigu","Cg9PBNrdB24","DgLUzYbZzxi","sgLZrKO","Dw5RBM93BIa","zxj2AwnL","BhrPCgXLihq","zxrMDKC","qMPRtK0","B0Pvse4","D3m6lY8","AuHrrLi","t1bRqK0","Dxrjza","ChD3EfK","su5tvefova","r1fZqNG","AK5nDhi","Afb6wMS","BKTIuwi","sgLgAwy","Bhfvwxm","tLHODLq","t3bLBKv2zw4","DMvY","Aw9UvgLTzw8","B01osfG","DKfjyNy","CMvUDevUzha","C3rVCMu","mZC0ndL0wePHv0i","sgXPq0y","A2rtquO","x2rLC3rYB3K","q3fWD28","C0TMB2W","B25tDg9Wsw0","rKLmrv9ot1q","yKjXsuO","yvLswgu","zxq9DxrMltG","zw1LBNq","ig1LC3nHz2u","A2zKwei","C0PrzLu","zxjFAxnFywm","rLDt","x3bHDgHlzxK","z2u6ia","BgreDLO","C2vUza","B25ozxr3B3i","vLHWAgW","s0nmALy","AhDXzg4","qK1vvMu","zxf1ywXZ","wLjxELa","A3H1q3m","zgvSzxrLrge","BvHYuxy","uxPzzMW","qwriCxG","s2LXvKO","A0DkEgu","AfDutM8","igzHAwWSig0","BezSDxnO","AMPfAuS","uxvLDwu","Dg9mB3DLCKm","z0TuqKu","DxrVuMvJB24","Eu5YueO","rNPTzMm","zNvUy3rPB24","DxnLCKLW","lcbxzwjtB2m","C1vfAxK","rMHrshC","B3nLrxzLBNq","Ahr0Ca","BMvY","B2nODem","u2fWAMy","BMv4DcGPigm","Cwz6C0y","DefWqKe","wKj2qMG","DhHOv20","Cg9PBNrbBMq","ywrKq291BNq","CMvWBgfJzui","x2LUAxq","D2jlAva","Dg9iyxnO","s0f4zKe","AgLNAa","yLzcB1m","rfLmAeu","CMvTB3zLrxy","B3jRig9MzMW","rMX0y1m","EuvYyuW","x3DHAxq","mdaWmdaWmda","C2HPzNq","zwn0","y3vYC29YlNm","y3bvDM4","CMP4t3G","rvLzzgy","BwvZ","ChjVy2vZCW","B3bLBG","CMvTB3zLq2G","ugXKDeq","nZC4nxHpBgHbAa","sgXOzwi","shPwveK","x2DLBMvYyxq","rKP3rNC","q0Xpu0ve","z2vIvM4","r2vetLy","CfDstLO","zg9Sy20","x29UvgLTzw8","DuD1wK4","CwTvvee","CNHKsw0","zKLPzxu","zgvJB2rLzey","BMrWB2LUDfq","y2HHCKnVzgu","BxnmtNe","thzhEum","v0HLyvG","y1v1vgu","vgfN","DMfS","Efrurw52","vgTTte0","Ahr0Chm6","B3LUCgK","Ae9Wzw5fDMu","BLznDLC","ywnRx2nVzgu","CM92AwrLige","uM54zKS","Dw1qt0e","A2v5CW","ywDLrxzLBNq","yK1fwNy","Cw1Twwm","DcbSAw1PDa","AxjLza","wvztqui","CKzTAgm","DvnHALq","yw5Nzq","ChvQte4","EwPYD2y","ywjczuG","CM92AwrLihC","C2v0","suLSug0","BMnQr04","twLcA2e","DhjPzxmGCMu","s1fjEwq","x2LZtwLUAvC","tw54CM8","zgvSzxrL","C0Xf","BwLUzW","vgLXAu4","v2T4wu0","BNvVwKO","BLzsz3C","u0z5z20","ww5rvuq","CuXTtMy","EuHuthe","wu1HBLC","rw1huei","Cfv3q3y","ANvuqwS","vNzSugq","y3vYC29Yx2y","vw5Oyw5KBgu","DK91Dg8","B25mAw5L","BgvY","CM92AwrLihy","t0fxuei","zxjFBxnNAwq","ugHqEMC","x194x21Zz18","q2LRuxG","Ec1TC2CTy3u","B090yxe","CMvZzxruCMK","DM5crMu","weDlu1u","t2DIAhG","BKv4ywC","BeHHBMrSzxi","De9yuwG","ChjVDg9JB2W","Bhm6ia","r0vvyMu","rMXQt20","C3vJy2vZCW","v0LQvg4","ihrPBwvVDxq","DNzkt20","tKfusvzfx0u","y3fZuuG","wenrvge","DgXszxC","FdH8nxWXmhW","AgfUz2u","BuLLEgy","qNv3vfu","ChjVDg90Exa","DgHLBG","nMPwAwniAa","vKzws2i","Bwv0Ag9K","qwLyD08","Aw9U","zcbLCNjVCI4","y3viDfK","ru9wC1q","sKDmDKi","igzPzwXKoIa","y09Wzw4","tg9JAW","zw5fDMvUDa","BeXABNC","C2PrvLK","Dev2zw50","rezuzgS","s054CgS","x3fVC0rc","y3jLyxrLtwu","zLv1rLK","ywX3yxLZ","ENfHwxO","A0fAD1u","B0vHs3C","weXuBeG","y3jLyxrLt3a","ihzHBgLKigq","ywnRDxbfBMq","D2zNtfG","swDzCfu","tNftBwe","uhzTDNK","B3nLza","r0LeA3a","DgvmB2Djre4","Dg9tDhjPBMC","DeLK","u0TdBLy","yMHxBfu","ufDwzgW","rKL1zwW","CvjiB3e","CMv0CNLdB3u","rMjPvgG","EMzIq3e","quXm","BxnNsuq","DvrWz20","CgjICdi","z2v0sxrLBq","zwrPyxrLBhK","DLHouwO","Dg9oDw1Izxi","BwfKCge","wwzos2S","ihrPBwvZ","rvfYsxi","q2TpC3y","yNvMzMvY","sLDxwgC","zwrhyLK","s3DHA0m","C29YDa","CMfNzvn5BMm","BhHfzwW","zezysLi","Aw5KzxHpzG","qM9bEMi","mNW0Fdm","C2vUzf9Hy2S","qM5XwM0","C0jf","CgfNzxnOB3C","z2v0","qxH5u0i","Buvhwe8","DMfSDwvZ","rvjst1i","wgPpyuK","t1bftL9fuLi","z1jPB2m","C2vYDMvYvgK","Cgf5Bg9Hza","DhP2z1G","zxjcEuC","Ahrwuem","yNL0zuXLBMC","zxHWB3j0CW","y2f0y2G","zgf0yq","u2n2AxC","zgLZywjSzue","D3vQuei","z1DbA3q","CMfTugfYyw0","v3fLC3O","x29Ut3bLBG","t1LOz1q","Evn6rem","Dw5ZAwDUzwq","CMHhr3G","EhvtAeW","q1njB0C","rNjVBNrPzxi","AM5Ttw0","rMXfr1K","zuPozeC","A2rfsgS","rvDMBu0","BxLIDxa","DxjS","qNPAzeu","AgvHzgvYCW","DgvZDa","y2HnyxHdB3u","ywXmvMu","yM9KEq","C2vYDMLJzq","zMLSzw5HBwu","BxziCgq","Aw1lv1O","EurpExC","CMvHC29U","s25gq3q","DMzzvhm","z2v0u3rVCMe","zv9ZDwnJzxm","uwnlt2y","Aw1LCYbPBIa","y2XVC2u","BMnRtKG","r2nhzKm","DNPVuhC","y29Kzq","zxLYCge","B25JBg9Zzq","DurUD2m","ugXPu3K","yw1L","rhjmC2C","zeHjsNq","re5UEuS","Bg9IywXty28","vfjQAxm","suv4ANC","zNPWDvC","Aw5KzxGGB3u","BwLUAvbYB2C","y2HLy2Tszwe","DhrKvwq","ueLutvO","qwD0s2W","Cg93","B2LUDfjLywm","AuPvAuW","yMfSu2nVCgu","thbTBKS","A2r3C2G","zvbYufi","AxnrB1nby2S","x21PBMLoyxy","zejdwKu","CMvHzhDYAxq","Chv0","vg5zEMe","yMfSrxzLBNq","tMDwB1K","Dw50","uxvMvM8","Cfffu3G","yNPAwgK","quPTvLi","CwDNqve","yMT5BMi","AxnbCNjHEq","BxfgseW","uwPpvxy","Dg9cExrLC0i","qvb5z1u","BujRs2W","DgfYz2v0","B3vUDa","x25HDMLNyxq","C2fKz1q","zw5kBe4","z2v0q3vYCMu","sM5lsu4","q3fLEe8","D0XJA2e","BMfTzq","z2D0CfC","BwLZzq","B3bLCNr5tMe","uxHushm","txnSs0m","A3jzq2q","ywnOzwqSihC","ExrOEue","z2vtEw5J","ywzL","tvfQqMC","q1jKChu","EKPbt0O","DKPgBfm","AerNrKe","thnAA2S","thHRCfq","z1HcB0i","id4G","zw5NDgG","AfjLtxa","C0LHy1a","D2PJEKK","y29UDgv4Da","rffbsvC","x3DZsw5ZDge","x2LUAxrhBg8","rhrJvNa","z1HhCgS","sfv4u3C","x3nLBMrby2S","tfDWtLe","C3vIC3rYAw4","zMXMELq","Bevvtvy","ueT1q0i","wgn3qLy","B2viC3y","vMX2CNi","Aw5KzxG","yxKSihrYEsa","CuHVzKm","y3jLyxrLuMu","vgPTDhO","DwjhsLu","DvrwyNO","shfyDuG","yvLgBhG","qvvHEKW","C2fNzq","wez2txm","C3nHz2vfDMu","tg9Nsuq","De1HBMfNzxi","EMrZAfe","FdD8mxW5FdG","ywrK","yxrHlcbKyxq","zLLwDgO","AwDHDg9Yt24","y3vYC29Yx24","uejLAKW","igfYCMf5yNu","sNrSrw4","suvtx0vsuK8","y291BNq","nJbxAg5sCw4","AgvKtwf4uMu","EMnHtMK","y3r4","EfPpsMO","uKHkyw4","qwv5y3y","yxrLq291BNq","CgvYC2LZDgu","C2XPy2u","zw5JB2rPBMC","y3jLyxrLrxi","ywXSB2nvBNm","zgvS","zsbHihn0CMK","yxnJCMLWDa","v2LuBNe","z0roDwS","EhnAyKW","weXdqMq","ExP3qMO","tMHwzMu","DhjPzxm","Bg93","nZK2ndC3tfzAsLvj","CgXLyxnLiha","ywnRtxnNswq","BMvLzf9Hy2S","A2Pis1y","sxDTAKy","BMCGDxjSoIa","AxnszwfKEq","rwjvq04","AunACfe","wLD1BhK","z29PBMCGyxC","B2nRzxq","BwvZC2fNztO","z1jQuMG","qvHYr3G","BMvzBwy","qvL2AK8","C2vUDa","x0rctMfTzq","y2HLy2TdDxi","zw50tgLZDgu","BMnVzgLUzW","x3bPBMDmB3m","y29UBMvJDa","tuntCfe","DMzkBuu","AMjcte4","Ae1LC3nHz2u","Bwf4uMv0CMK","tKfJr1O","BwfUDwfSihi","EffwA0W","B3fjExa","Durlrxy","z2vrDwv1zuW","x2n1CNnVCK4","u2jbu1i","uxbzz2e","m3WYFdb8mxW","BwvZC2fNzv8","C2nxzvm","ihbYB3rVy28","Ahrftg0","CM9YrxzLBNq","DgfIyxnL","CMrhAgK","BMrWB2LUDca","Dhr3Awq","Bw9tyMu","q2fTv1O","u2rbrve","EMHxDvu","B25TzxnZywC","Aw50zwDLCIa","z1rPBwvVDxq","su5bvK8","BIWGAg9ZDg4","A215Ewm","x29UtwvZC2e","CM92AwrLigi","Cgf5Bg9Hzeu","ihzHBgLKihm","vhPNCfK","EfnSv1K","yLnzBLC","BLztC2u","sNbwrLC","vMHNAM4","uLDYB3m","sKzHA24","x2n1CNnVCKy","u3L0rwi","x2vUzhbVAw4","CxbVq0m","qML6uu8","BvniC3e","mJi4DwrduwrK","zwvKzwq","C2zNEw8","shzozK4","BKPVBw8","DuDqB1C","AMXfA3K","BMnLq2XVC2u","AgD1yue","C3rYAw5N","DejyB2K","sNPzzfa","EfvZzuvUDG","C2v0q3vYC28","yxnZAwDU","B2zMC2v0","yLv5Evi","zgPbzNG","Cg9W","DK9yA24","yKD0DhO","Du9XEuG","zM9Yy2u","qvDhEgO","wvj0s2W","B3v0sw50zxi","BxDtzwS","q09otKvdveK","yLjdB3a","x2LZsw5PDa","Bg9N","CMvHzg9UBhK","x2jPBMfYEvq","ywTUChO","vKfkzLK","BfrPBwvVDxq","zgrjrcWGzgu","CwHXBNy","z2LXBLO","D0HVDLm","qwjVCNrfCNi","zMLUza","yw5ZzM9YBvq","x3bYB3rVy28","BgHbreS","BgLTAxq","AxnFywnR","zK5Uvwi","uxHlwuy","qK9ituW","x2DLDeLUDgu","q3vZDg9Tq2W","AuzovuG","CvLdDwy","ALzqvNe","mxW2Fdv8nW","C2v0zgi","AenSB3nLrxy","vxHJy0m","sM9mA2W","x19LC01Vzhu","DxrMofDYAxq","tuvtu0fhrv8","q3vbD3C","x3jLBw92zvC","zuHey3q","CgLUz09Uy2u","vgLOuK0","yxv0BW","nte2ntCZyMfouMTU","BuzSyLK","Bg9Nsurhzw4","ywnOzwq","EuDUsfu","vgn4s28","B2zMBgLUzq","ywrKt25L","AfjOr3i","uePLEM4","EhfMyu0","zeP0zKe","CLLlExq","thnVBNG","DxjNsNm","yxGGCMv0CMK","vw5PBxbSzw0","EfLgBwW","x2n1CNnVCK0","DK1yz0K","zxDmrMq","tezkD0e","BNrbBMrvCgq","uNLzBvy","DLvPy2u","ueH2q2y","zxjYB3i","ruXiyKG","B215Du4","zKvywhy","yNL0zu9MzNm","ChfXvLy","zgvIDwC","Ef9MCM9UDgK","r0fTsuK","qxLewxy","CMLLC0nVDw4","v2LUzg93","t3nSrhy","AM9PBG","A1n0yxr1C0m","tM5bt3O","wuj5zMW","y1rssNm","s091Bxq","DxrLvfm","CKXYEKC","CgfYC2u","BunUBg8","zwjyrhi","D0fgy3m","EvjLy29UBMu","ze1Mrfu","twzlvey","wwTxuK4","yuHbuhi","DLrWCxe","zcWGDw5RBM8","v1jwqwm","AxDNrKC","zNjVBu51Bwi","zef0ELq","uMvHzcbWyxm","yxbWBgLJyxq","sKPZvxa","u29iAwK","AhLTqK4","zMzLCG","B1LYrg0","swn6CKS","u213ugq","seXJzxG","y3vYC29Y","zhHYBfy","EK5gBgq","DNntzM8","sgn1s2W","CvfIEgG","yKjos2C","A0DnswG","uKDtsKi","u3bxA00","z2vY","ywDLu2HVDW","qw1VDw50","CMvJzxzPzwq","B3jpBMXPBMu","DxbKyxrLq3u","mNW0","zxH0zw5ZAw8","s1zxsu8","v2f1rLC","zxPMDNa","Dhj1y3rVCIa","u05trxu","vwvXugq","vxnLC0K","BNvTyMvY","ignVzgu6ia","BwT6AuO","uLDJsvy","qvHcANi","B25tDgfYDfi","zMvY","DMfSDwu","A2v0ignVBNm","zfHxsKG","nxWWFdz8mxW","y29SBM8","B25szwnLAxy","AgfZt3DUuhi","EMD2Bfq","AgvHzgvY","B25SAw5L","CML3C3C","sKzqEKS","Bhv2vfm","zcWG","y29UBMvJDca","r0nUqKu","B2nRzxrtDwm","tePWwfO","thPyuhu","vg1tENG","zK5IANq","igXHCMDLCIa","C3rLBMvYCW","BNvTCfa","CKPZuxm","uLv4rNy","terkDLG","x2HHBMrSzva","Cw9Z","DLzmsva","AevYCM9Yrxy","qNjPzgDL","t2H5zvm","Ee5RDu0","x2fKzfDZtgK","u2DdC3O","zw1vvg0","t2jQzwn0","rwfXDvG","D2LSBfjLy28","A2v5","C2zmDeq","A2Xgsfa","CujfvMq","svzQsxy","s055vNG","zxjFywnRx20","EK9dCKO","u2vetKu","u1LHBei","Dgv4DfbHEwW","BwvY","u0TcBhG","nxWZ","y3fdquq","reLyBfi","ufrnCwK","yxfiuKW","C01UrMy","BgvUz3rO","BNrfBMrWB2K","z2vjBMzVu3K","qwXIqLy","z2v0t3DUuhi","q0Xpu0LorW","Au5xrvm","zufJAW","CMvXDwLYzwq","CfLSB1C","C3bSAxq","ALrRBuC","mdaWma","ywDLsgLKzq","Ae9ysvm","zLDhrg0","zNjVBunOyxi","q09oveLovuu","BwrwueO","yvDfshm","ufLYvNa","BMDLza","zxjFCw9Zx2e","z3zoDuq","u2TPCcbWyxm","v2XLq3a","AxnrB1nnzxm","CKTsDva","tvLYr3i","rgDrwuy","D3nZoI8V","x2XPC3rLBMu","D3jPDgvvAw4","x2rPC3bHDgm","CMvJB25Uzwm","DM9wB00","zxmGCMvHy2G","tMfTzq","ExzAuvi","DhLWzq","DMvYC2LVBG","CNbcrgW","ywnRx2LK","Dg9cExrLC0W","q3zvAhC","AxHlte0","DgLTzw91Da","wfr1uNO","EuHlBg4","y2XLyxi","q05pBLm","z0TKvw8","yxnL","y3jLyxrLq2W","CKPJsvO","sLn4D0C","z1bxtLq","yvDQCK0","qwPHquC","zfvsBLm","quzvyKq","x2nSzwfYvgK","x29Uq2XVC2u","EefYBM8","Aw5JBhvKzxm","zMLN","vhzHzhe","De1WtLC","D24GCMvHC28","ELPPtMq","rxzLBNq","zgvMAw5Luhi","uuLmEwK","lcbTyxGGCMu","Dg9SB3G","x21LC3nHz2u","tLzkDfK","Dg5Ms0W","sfnSqK8","rM1jwMK","yMzluM4","zxjYtM8","y3jLyxrLt2i","qKDkDgK","y29UDgLUDwu","EeffBuK","icSG","A0DotLq","x2nYzwf0zvm","mhWYFdn8nhW","venRvgq"];return Vo=function(){return t},Vo()}for(qo in Ce)["CustomCloseEvent",M(561)+"rorEvent",M(208)+"e",M(1491),M(650),"Frontier"+M(374)+M(411),M(374)+"vent",M(627)+"t","Reconnec"+M(846),M(1474)+M(684),M(1099)+M(1156),M(850)+M(1073)+"nt",M(857)+"enEvent",M(1064)+M(291)+"vent",M(736)+"rame",M(1534)+M(970)][M(898)](qo)===-1&&(Pe[qo]=Ce[qo]);var qo;Object[M(1492)+M(462)](Pe,M(1249)+"le",{value:!0})});import{existsSync as Tv,openSync as Rv}from"node:fs";import{mkdir as Cv}from"node:fs/promises";import{dirname as Pv}from"node:path";import{fileURLToPath as Dv}from"node:url";function Lv(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Ud(t=ee()){return Tv(t.libEntry)?t.libEntry:Dv(new URL("../index.ts",import.meta.url))}async function $x(t={}){let e=t.paths??ee(),n=t.entryOverride??Ud(e),i=Lv(e,process.env.COZE_BRIDGE_LOG_MODE);await Cv(Pv(i),{recursive:!0});let s=Rv(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=nt(process.execPath,d,{detached:!0,stdio:["ignore",s,s],env:{...process.env,[rs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return Ov.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var Ov,rs,Qo=Qe(()=>{"use strict";Vt();ne();Le();Ov=H("spawn-daemon"),rs="COZE_BRIDGE_DAEMON"});import{spawn as CS}from"node:child_process";import{mkdir as PS,unlink as DS,writeFile as OS}from"node:fs/promises";import{dirname as LS,join as NS}from"node:path";function Yr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function MS(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${Yr(n)}</key>
21
- <string>${Yr(i)}</string>`).join(`
20
+ `+r)}function Xn(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let l=new Error(o);Error.captureStackTrace(l,Xn),t.emit("wsClientError",l,r,e)}else is(r,i,o,c)}});var Vx=ae(Me=>{"use strict";var N=j;(function(t,e){let r=j,i=t();for(;;)try{if(-parseInt(r(399))/1+-parseInt(r(497))/2+parseInt(r(1579))/3+-parseInt(r(674))/4*(parseInt(r(1023))/5)+parseInt(r(1270))/6+parseInt(r(1098))/7*(parseInt(r(1539))/8)+-parseInt(r(1714))/9*(-parseInt(r(1632))/10)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Yo,799130);function Yo(){let t=["u2TPCcbWyxm","rhLTteq","y2HnyxHuCMK","Fdn8mxW1Fde","DgvmB2Djre4","sNLUyLi","C2v0u3rVCMe","vNPsCem","txrxtLO","rwjqzxO","q0v4Chm","BLPxBxe","DMfSDwvZ","AxnrB1nnzxm","zuX2CwK","m3W1Fdy","q2vJshu","txj0DLK","B2jQzwn0u3q","DNn2qKq","y09Wzw4","BNrLCG","s01Vz2u","Dg5rwgu","AgfZ","BKDqtwK","whj1s2S","sNDOz2m","C3PHDei","ruHPzfG","zMjfD2i","BMv3vMvYC2K","ChrVCG","tw9iBKq","CMjir0i","Afrqveu","Aw5Lza","CezjseG","B25ozxr3B3i","u3Lzuwu","yxrLq291BNq","CMvXDwLYzwq","vw1jDuy","Exz5tuu","z2u6ia","x29Uq2XVC2u","Bwu6ia","x2TLEvbHDgG","x3jLywr5q2W","Dev2zw50","DKnQuuS","CvrisgS","C3vJy2vZCW","B25szwnLAxy","qNz0C0i","uK9Irxq","vhbmD1i","C0Xf","ywjVCNq","icSG","mZi2ode3s1jHrhju","zvDKzue","tNnJEuy","terhBhy","s0rdC24","mdaWmdaWmda","CMvJzxzPzwq","C3bSAxq","y29UBMvJDa","ANHUEwC","Bg9N","ENrrv3m","uxPPBNC","rKL4Ceu","zhf1CMO","ENneBg4","DgvZDa","qunIEKG","x2LZsw5PDa","DxbKyxrLq3u","DhDVCMTdAge","sKrYz2W","Dg9cExrLC0W","D3rizfm","yxbWBhK","id4G","D3jPDgvvAw4","sNPlsMu","s2vrrMe","yMLUyxj5","r2vNANC","Bev2wgy","z2vtEw5J","DMLJzuLeig8","zxjFBxnNAwq","DMD4uKq","Befzshm","zNjVBuj5Dgu","ChfhBuK","EKztze0","qufyvey","vhnHz2S","AvvgqLe","Bwf4twvZC2e","B3jpBMXPBMu","B2XKvMvYC2K","sxPlvum","x2zVCM1HDeu","zuXzEg4","BeHHBMrSzxi","BezvAMm","u3jPBKC","ChjVDg90Exa","vNvzzM4","vuPQu0u","x2HHBMrSzu8","vLHpyvi","y3vYC29Yx24","uNLLuK4","rvPstue","DLvVzKK","AKnfwNK","v0LZA28","B25dBg9Zzq","DvHyEfy","Avj0qve","qNnOqNu","uhfOuKe","v2LUzg93","EfD0wgG","AxnFywnR","vfr2C1a","sxzgDwS","x2LUAxrhBg8","wgnmAhK","r3HPB2y","zw5JB2rPBMC","vKDdA3O","pxv0zI04","D2fZq2XLyw4","AxnszwfKEq","B3zTz28","C2v0","EMvZt3e","DvPiEgy","BefoAvK","CxDxDxe","vLbMzMG","Aw5KzxGGB3u","v1f2v0u","ChbL","CfHKrMq","yLfWugy","yMfSrxzLBNq","y3vYCMvUDeu","yw5Hz2vY","AxH3wKi","tgLZDgvUzxi","Aw5JBhvKzxm","AuTxD1K","Cg9PBNrdB24","CYbWyxjHBxm","B2D3t2u","sKL6vMO","B2nRzxq","zxjprgi","u2vXsuq","x2XPC3rLBMu","zfbzvhC","CNfZsvq","te5AA1C","CMfTzq","A0TqA2i","C3rLBMvYCW","y29UC3rYDwm","twvZC2fNzuu","AhHgwM0","CM92AwrLihC","B3DvrLe","B2zM","x3DZsw5ZDge","CMfUzg9T","qwjWC2K","ihrVihjLDhi","BwfzseC","x25HDMLNyxq","DcbVzIbYyw4","x2vUzhbVAw4","qLD4qNy","svvPC0y","CNnVCKzPBgu","yuPxBNa","rgnVs0e","u05LtMi","CMvZDwX0","v3DrwwK","AwXK","y3jzsfO","z1rTwvK","B25nzxnZywC","CwzXtu0","CM92AwrLige","ExDZCuu","ueTJsLu","zNjHBwvuExa","A1zSCg8","B3nLrxzLBNq","zv90Aw1LB3u","qw5VEeS","uhDqzNC","ugDbzNq","zgvSzxrL","zgvJB2rLzey","Cunbteu","q3P5Deq","CMvJzwL2zwq","Efrurw52","s1fKBKC","rLLRuw0","quvuBLu","ywnRx2nVzgu","rM5YB1K","zw1LBNq","Dxrjza","yxv0BW","ChLHBxi","AezzsuC","qw1AAxq","C0POCNe","mtq1nZm2mwjWsNfhBW","AgvHzgvY","BM9lAMi","r2j3uw4","AK1TAum","thjyAe0","CNnVCL9Uyw0","BwvKAwf0zwW","sxnrCLy","t0TTALq","yM9TAMS","zw5fDMvUDa","rM5LA1u","A0n0uuG","m3WWFdf8mNW","uuzIwKK","zKvXDxq","BMrWB2LUDfq","Dg9oDw1Izxi","zxnXBwm","ywX3yxLZ","D3DQChm","Bg93","vg1MtfK","wuf4yM8","DgLLCKPtt04","ywrKq291BNq","BeD0zgu","Aw9Ul2PZB24","y3vYCMvUDeK","ig1LC3nHz2u","D3jPDgu","uuDXtfa","BMnLq2XVC2u","wg1JAvy","x3bYB3rVy28","zxjYB3i","x3DHAxq","x2rLyNvN","sLnptLa","BMDLza","wgvqzvG","CMvHzfvjBNq","tevJqKS","Bw9Hzuu","twLZC2LUzYa","EunhBvm","x21PBMLoyxy","x2rYB3bhBg8","tLDODMW","A09jthy","BwvZC2fNzv8","C2v0zgi","AxDYBK4","CgjICdi","wwDvrgS","CgLUz0XVC3m","C3rVCMu","DhLWzq","quXm","z2vxCNK","tgvUzKG","C2fNzq","AMrLELq","CK5WrNC","CMvjwgq","AfvxDeC","x29UrxjYB3i","BM9OuMm","y05nEfm","BgvY","CxLpufi","DhjHBNnHy3q","sfD4twm","zK91Ag4","EKjLBKq","Bwf4tg9ZC0m","C2v0sxrLBq","DNL4vKe","CfPbsu0","vMPLAgS","Ae5sr04","uMLhzKG","EfHdB1q","BMCGDxjSoIa","CMvWBgfJzq","x29UtwvZC2e","vgfN","tKTJuw8","rxjYB3jdB2q","Dfr1A3u","q291BNq","r01Aq3i","shLACwi","Exn6sxm","AKruDuO","x2rItMfTzq","rxvJq0u","mJC2mdjpC2zRCKO","BgLTAxq","x2fKzfDZtgK","zuf3qwO","y3jLyxrLt3a","y0Tgrui","EuXPqK4","uLjpuG","igXHCMDLCIa","uuzuv3a","z2vrDwv1zuW","sMrQEMW","C1LKAwy","AMvJDfn0B3i","vxv1D1q","x3DZ","CMvTB3zLq2G","q2jqzNy","wLbAD3a","Axnby2TdBgu","ignVzgu6ia","Cgf5Bg9Hzfq","x2DLDeLUDgu","zuLzqu8","AfvbwM0","BNbTt3e","Cu9qEKG","CMvKDwnL","vM5sBMu","r1nkC2G","z0Xluwu","ywDLsgLKzq","zgvMAw5Luhi","zKXls0m","tKXXDKe","y2XVC2u","Ahr0Ca","AevvCuG","CMTLCKDSB2i","BMTcquy","y29UBMvJDfm","x2LZtM9Kzq","z3fMBfe","Aw9U","tNPeB0e","BLHoBMK","teLet1u","DxnLCKLW","CeHqDvi","x3bPBMC","tLj0rKi","Bvj5ugO","qxrgvMy","B3v2qvu","yM9KEq","DfzVCgK","t1jiwwq","A2TfreC","t1LUu2C","ywjZAgW","qxnTBxu","y3jLyxrLtwu","BM9Uzv9UB24","yvPkBha","u1LyCem","rKLJCuu","tvbpq2K","rNjVBNrPzxi","ihbYB3rVy28","rwjtvLa","CujduM4","x2HHBMrSzva","qM9UtMm","D0HwtNe","vM1nzxu","Ee9Lt1a","yKrfquy","sMHptMC","zMLUza","D24GCMvHC28","rxvvsKK","x2nSzwfYugK","rLrQALa","rff0ue8","DcbSAw1PDa","y1jnqxu","BvjyBLq","uu5Kv2S","rg5gtvG","u0PdDu8","rvrSBg0","uwX6Cvi","r2rNuLe","q29UzMLN","A05PDuK","BMvLzf9Hy2S","AgfZt3DUuhi","r3Hqsee","BwvY","z2v0q3vYCMu","wNnjvvq","zMX1C2HfEha","yw51Ce1LC3m","BgLZDgvUtMu","t2DzrLG","C2vYDMvYvgK","svrfBLi","yxP2wfK","A0H2vw0","qvL4AxC","tfviCK0","x3bPBMDmB3m","zwLvAeC","r0zRD3m","yxKSig5LDhC","tuLzEfi","AwvpyuW","Cuf3yNi","y0TvyKq","zw5JB2rLrNi","AwXLx25HBwu","C29YDa","sw9WCge","ueHxCNe","CNb4wLq","ihzHBgLKihm","qM1Hz3G","BxDhwLm","wuj1rhe","De1mshq","suvtx0vsuK8","qxbdy2m","rfnoCKC","sKnrBu8","Dw50","zuXtsvy","yxKSihrYEsa","CYbHBhjLywq","sg9csfy","EvffCxi","DNbXAeO","ywXSq3vYC28","B3fSsum","CMvHC29U","sensEgq","D2vI","zwvKzwq","DhvsqvK","De9wAvy","zMLN","CMvZzxrdB3u","rwDSELm","igfYCMf5yNu","CMLdswO","vwHSAKC","z2v0","yxbWBgLJyxq","AvDRtxq","y291BNq","mNWZFdr8mxW","rvjRq2i","zuvnvei","EM5gyNq","zNLKzwC","BNrbBMrvCgq","DeLK","DhHJvwm","zKjMrgy","rhrbAxe","qwzWzwi","C1LTB0G","AvLKwgq","AgvKtwf4uMu","yuXbveO","Bvrnvvy","vfjUt24","sNPTCeS","mZuWnJyXmLnVwgvMCW","EvjLy29UBMu","zuLtvfq","rvjst1i","tMfTzq","zw50zwqGDhK","BKTMEeK","Agv0B2m","mdaWma","zw5NDgG","q3DoD28","y3vYC29Yx2y","zxjYtxnN","BMCGzMfPBgu","Cw5ysMe","EMnZquC","x2LZv29YA2u","y2f0y2G","ywDLu2HVDW","mhWZFdD8mq","Dhbyzhm","wef4CKW","vMTZyMS","v0fbCu0","zNjVBuHHC2G","ANPxwLO","BK5YD0O","C3v4AuS","D1jVtxK","x3jLy29UBMu","sfPdCLq","yNr6wMO","tNLzCNq","sxzytMG","Ae1LC3nHz2u","u3rYyxrLz3K","EKnuu2y","EerQAKu","y29TCgXLDgu","s0rht2e","zNjVBunOyxi","EhrRqve","rLjAwKy","Ae1AB3G","lcbTyxGGCMu","zvnWB2e","De1HBMfNzxi","x2jPBMfYEvq","vK15rui","z2vY","y2XLyxjtDg8","AwTxufy","zxH0ugf5Bg8","sM9pzhi","y0zzweO","y1Pgq2C","z2r5t1u","wMzADK8","CMvWBgfJzui","AevYCM9Yrxy","zhDkruu","Ew1pCKe","ww9Jthu","zxj2AwnL","uhvJDvC","zfbys0y","t3foELq","qLvRB3i","rwvWCvi","y3jLyxrLrxi","x21LC3nHz2u","y29UDgv4Da","q1HqAvy","DMfSDwu","vu5VteS","BfrPBwvVDxq","mtb8mxW5Fdu","DeTZCKO","zvztDvO","yNHJzhO","uufpzMm","x2rPC3bHDgm","uhDWEvu","z2vjBMzVu3K","C3rYAw5N","vuLTzha","BwLUAvbYB2C","DM9bEuq","CYbPBNn0yw4","Ec1TC2CTy3u","DuXcDvG","svDIAha","CxPizxa","Aw9UvgLTzw8","seHpsKi","B25JBg9Zzq","ywnRx2LK","zuT6ENG","x2rLC3rYB3K","zuv3u1y","r0jXuMW","Aw1LCYbPBIa","zw50tgLZDgu","ihn1y2nLC3m","r0vYzNu","y2uGBM90igK","q3rjEfG","EKnrzMy","vufxqNK","mNWXFdr8m3W","y0P0Cfy","vxjAu1y","s3PMAM0","rhDbwMm","wMf6wxq","zwrhDxO","EfvZzuvUDG","qNjPzgDL","tKDFrvjst1i","D3Dbsem","z2zbBu4","x2DLBMvYyxq","yxnJCMLWDa","B0HvugC","CMvQzwn0","y2HLy2TdDxi","BML0AwfSAxO","rvbLrLy","tKrjB04","x29WDgLVBNm","wwrqvLu","wwnitMO","Aw5KzxG","B0HAvgy","nhWYFdf8m3W","tNLPwhi","tg9NsurozxC","y2XVC2uSihC","y0LNzue","BM5Ly3q","zgLZCgf0y2G","BMrWB2LUDca","rvvyzfi","Bg9TvKG","C3rZrw8","Cgf5Bg9Hzeu","tgvLD1a","sM1uzeG","DMLKuLq","rxzLBNq","Cg9IzKG","uMfgrLm","AxnmB25N","zw5HyMXLvhi","EgTcAhi","zMLSDgvY","zxjFAxnFywm","C0XPC3rLBMu","yLvjD2K","CNH0rhO","EvjLsNC","BwfUDwfSihi","ELzftgm","yxv0B21HDgK","ihrYEsbYzwm","zKXMrfu","q0Xpu0LorW","CgnUCe8","vgDoDxq","CK9HA2y","zxjHDg9Y","Bez1y0W","AM5mteG","CxrfCvu","zwn0","BMDVz08","C3LAD2K","vfbeDuW","CfbrA2O","BhDKDLu","zg9Uzq","ywDLrxzLBNq","CxvywwS","B3jRig9MzMW","yNvMzMvY","q29Kzq","x3jLBw92zvC","Dg9mB3DLCKm","B25TzxnZywC","AM9PBG","B1n4A1q","tvjnAxO","ywXSzwqGBxu","C2rJyvu","C0nVDw50zxi","vvbhtve","x2LZtwLUAvC","y2HnyxHdB3u","uvzuz3y","C2vYDMLJzs0","CwnlA1u","Dg9cExrLC0i","B3jRzxjhBg8","ue5fvgC","u2HHCMvKv28","ueDHsMW","wvfpru4","AefJA01LC3m","uw1yzLm","ANP2Dgy","B3jLtMfTzxm","D1bwwfa","B2nRzxrgywK","C3nHz2vfDMu","Cgf5Bg9Hza","vKPbqMK","rev5C08","DLj5Bg4","m3WWFdf8nhW","rvL3Bhq","CgvYC2LZDgu","y2HHCKnVzgu","x1fVu01HBMe","rwzsEgW","y3ruAw1LB3u","rLzlBey","B2zMBgLUzq","swTIqM0","DhjPzxm","zePnCLa","tuvtu0fhrv8","z0fQt2u","Eff5Bu8","thrTweG","x3bHDgHlzxK","zw5HyMXLuw8","qKvYtNO","x3nVy2TLDa","Eg92Ehe","wefUvKS","Cg93","CNnVCL92ywW","x2n1CNnVCK0","zM9Yy2u","yK1yDue","rLr5wxC","x2nYzwf0zvm","ywnRtxnNswq","yNPeC3m","yw5Nzq","zv9ZDwnJzxm","q0PMDgu","zcWG","v3vnsfu","ihrPBwvVDxq","Dvjctfq","C0jnBK4","v1PtAhC","BMfTzq","CNrtzwq","BMvJDa","x2LUAxq","qujRDLC","lcbxzwjtB2m","uMvJB25Uzwm","yujPEue","BeP4yxy","B3bLBKrc","x2LUAxrqCM8","B2XuyKC","Ec11C2uT","uuHAB3m","Bwf4uMv0CMK","Bg9IywXty28","yxGGCMv0CMK","C3rHCNq","C21Ysg4","sgvfDeS","DMTZwwG","wKPqyvG","yNvMzMvYzwq","v2Trwfy","u2HQqMi","su5tvefova","CMvHzhLtDge","z2TmtfO","y3jLyxrLq2W","Dhj1y3rVCIa","q0LTDMG","s2PhqLC","vKrLBxi","AgnTzwC","Cw9Zx18","vuDUs3m","A1n0yxr1C0m","z1jRC3i","wMvQB2i","Aw50zwDLCIa","y3jLyxrLt2i","z2v0u3rVCMe","Cxz1Dxi","mhW0Fdj8m3W","uhjPBwfYEuS","zLzHr2m","C3jJ","rfv5uMm","ExbL","yNL0zxm","rwP4v1O","BxnN","tvzfBhi","D2zvAeq","rgT0vfK","CMvHzhDYAxq","CwPnyKy","zxHTqwi","BNrfBMrWB2K","A0zTse0","rLHmv1q","BKXPBMu","DMvY","BeT5C2G","zwnVBM5Ly3q","Bvvtvee","C2fmDeC","DKDbrKS","CM92AwrLigi","zxjYtM8","y29SBM8","DgHLBG","B3vUDa","BMPyzuy","zeLzA2i","wM9Su3i","vgLTzw91Da","EK9NrLq","B2fK","Ee5qBwe","u1vxD04","zgf0yq","C3vIyxjYyxK","z2v0sxrLBq","qvHjqxK","o2nOyxjZzxq","D016vhG","zgvIDwC","vhfSz2O","zxzOyuG","B25VCgvU","nvreEfLbtW","uxvLDwu","yxnL","AeHdBLG","ywrK","yNHqCxO","tuzpqvC","C3bSAwnL","x2LZqNjVD3m","uLbUzMe","wwvRwhK","A2rnyKi","DeLUDgvYy2u","zunjwNi","BvPAC2C","svH0sMO","Fdb8n3WZFdy","Ec1TC2CTCw8","AenSB3nLrxy","B2nRzxrtDwm","CMfNzvn5BMm","C2v0q3vYC28","ywLhwKy","r1vmB0m","wfrvr0C","yuXbvNq","t25guwG","CwnxwNm","EeTzrvC","zw5KCg9PBNq","r1LnzgC","DgHHBIbSB2m","wgH6A2S","C2XPy2u","mxWWFdn8nxW","zNDZxZeUmc4","zwfxtui","tePdANe","wxrdzKm","u1jQqva","EgvWEvu","ywXty29Wzq","DKnrqxC","ww5SsgO","A3fHBwq","CMvJB25Uzwm","q2XTwhO","BvvrAKq","zw50","AgfUz2u","BNruCMLLC0m","DgLTzw91DcW","zxHWB3j0CW","BKX5DeO","BKTizvq","qKjSCNi","tuTLthy","CxPlBfy","z29PBMCGyxC","v1Dpu0e","wgL6qNq","yMLUyxj5vhK","Cujhy3G","qKjnCg8","tg9Nsuq","BNDWCLq","DLfHtMu","ywzRuLG","Ahr0Chm6","rw9ctMW","BMfjquq","sKfirgy","zgnkB2W","x2n1CNnVCKy","rMDzy0m","n2DhCvDpAa","CNjcrKW","B25pCgvU","AwXSihvZzsa","y1LswMy","zw5XDwv1zq","AfbqwM4","Dw5KzwzPBMu","u1D6shq","nhW1","x2LUDgvYDMe","wfj2Chm","veHKAwe","uwXcz2K","zxDuAKG","zMzmAw5L","s0rxrxO","CvbUwKW","uuXZENm","D2LSBfjLy28","yLbqt0S","wuDbCfe","B3bLBIa","y2XVC2veqG","DfzpuhG","BNjkyuC","Eu9UC3C","nhW2Fdj8nxW","qwXOuhy","zNvUy3rPB24","Bwv0Ag9K","ywDL","reiGzMfPBgu","EuPsBKO","zwHWAw0","qMnMwgq","x29Ut3bLBG","yK5SwKG","BIWGAg9ZDg4","q3zRs3m","B21rDfa","ywvRzMG","ChvZAa","DhDlz3e","tKfusvzfx0u","tNj2CK0","qxbkrM0","AhvuDKG","qMXbD3C","B01vvNm","DhjPBq","C2DwyNO","y3vYC29Y","yvLwr1G","r2Dttum","qxDmv0O","sgfjvg4","Dw5RBM93BIa","yxnZAwDU","Bhm6ia","uhr3vuS","Ef9MCM9UDgK","Dg9VigXHCMC","qLLOtNu","vvjWtey","B3nLza","C2vUDa","wufOD3G","CM92AwrLihy","CMvZzxrfBMq","C29Tzq","wuPYqKy","suLor1u","rhHxz0C","uMLMAve","CwnyAwe","yw1Lu3bHy2u","zujSEfu","DxHhqKG","zejtuue","DMfUr0C","DgvSBe8","CM9YrxzLBNq","CgLbrgO","BwLUzW","uuHizwW","AhfjDMG","BMDuAw1LCG","x3bPBMDqB24","B25SAw5L","BvnYvKO","q2L1B1a","t3bLBKv2zw4","x29UugfNzu4","whvYy08","BwvZC2fNzq","EMr5zfu","z2v0t3DUuhi","x2rPC2nVBM4","DwDbBfO","vKzxsu4","CMvZzxruCMK","zgvS","sMjbEMm","BgPxsMG","x2LZtwLUAvq","mNW0","yMfSu2nVCgu","zxjFDhrS","B3LuELa","Aw5N","s1nxv0K","x3nLCuLK","s2f5v2W","ufvYEvq","r2TlvLO","A2v5","zcWGDw5RBM8","yw1L","C3rYAw5NAwy","AvLvD3u","uLbhDeG","qNjmuMO","vLfjtvG","wLnPExa","C2vUza","u3ffA2S","wg53z3m","tMvAA2K","ywrKrxzLBNq","A0zwDxC","y3jLyxrLrwW","C2HPzNq","Dg9Y","zuLizwO","zxjFCw9Zx2e","mhWYFdf8nhW","A1vdzuq","uxvrvvO","tejvq3u","EvrLuKy","yLPvC0S","zNLiBKC","tuD0z3a","uK9Qq0q","sxrpwLK","v3vYA3a","wMjzA1K","yNLL","y2nVrwu","uxDnAvG","x19LC01Vzhu","Fdr8ohWY","B2LUDfjLywm","CNzHBa","y29UBMvJDgK","vwfZCxu","CNj5wwK","A1PIy2u","zhDYtK0","Bw9OANa","y0HMz3C","BMvY","sefNvg8","BgLUzw5V","v2D0vKu","ELrXD2K","BeHTChC","C1Dyswe","BhrPCgXLihq","tg9JAW","AMfxuhu","mtm2mtm0nKHWsKn0Ca","te5QD3C","ALfctMC","y29Kzq","C2vYDMLJzq","y29Uy2f0","DMvUDa","y0TSqNi","z2D0veW","CMfTugfYyw0","ihzHBgLKigq","C2XSEKW","zxH0zw5ZAw8","r2DTu3y","y2HLy2Tszwe","z2rVB2C","DxrMofDYAxq","Evviuuu","z1rPBwvVDxq","wervreu","DMvYC2LVBMm","CgXLyxnLiha","D0zOy2u","y2vZC0HHBMq","rK5At2C","rKzly04","Ae9Wzw5fDMu","CKP5u3O","wKfkAMK","vfbswem","vw5Oyw5KBgu","tw9KDwXL","z2v0q3vYC28","zMLSzw5HBwu","CgLUz19VBMm","zxjFCw9Z","tMDXrhi","x0rctMfTzq","B25tDg9Wsw0","Cw1XwxK","twXbwMG","t29PCeK","vhDIDMS","DLPyEvy","AxjLza","t2jQzwn0","rgvKAwnHDgu","ChjVDg9JB2W","BNvTyMvY","qMfHtKG","tgDNCNO","AKfHELu","z2j0yuu","DgHZtNe","Ee13BM0","sLnqCLK","CwPSugi","wuTMqLm","Dg9tDhjPBMC","s2D6rfy","y29UBMvJDca","tw1Tr0G","wKDXANO","x2n1CNnVCK4","Cg9PBNrbBMq","CMvUDevUzha","zxjmCei","DKf1AMG","yMfJA3vWigu","AursEgS","BLbhteG","DhbQu3u","Bg1Js0e","BwvZ","wu5xs3q","Dw5ZAwDUzwq","y2XLyxi","DxjS","Bg9Nsurhzw4","BurqExG","yw5ZzM9YBvq","q3vZDg9Tq2W","zxrxB3jRq2G","q3vZDg9Trxi","C2vUzf9Hy2S","x3fVC0rc","EMTmwgi","Dgv4DfbHEwW","EwXHu04","rLDt","x3vYBa","mhW0Fdf8m3W","ywzL","EuP1yxa","rw9useW","qLjnzva","CMvHzg9UBhK","qw1VDw50","BeLIA1a","s0DwBKW","tvLWA0m","zNjVBujPDhm","rvfvt1m","B2zMC2v0","rvbjvg0","Dgv4Dc9Qyxy","ywWGy3vYC28","qwj1uui","wgX2rKi","zNHSq2y","Dg9iyxnO","AMzPEhC","uujQAgy","y0reD3y","wvzHzKe","AxnAzxjV","t21nsLm","tgHysfC","qvHqwxe","BgLUzq","zufJAW","Aw5KzxHpzG","ELrXyLq","rNjdre0","rKDQyMC","DLrzB2S","tNvyBMm","vMPWAu0","Cg9W","uePZthi","wMXXvui","x2HHBMrSzvi","zK5ZzvK","z052Avq","CgLUz1rPBwu","qu9Yzhe","AhD5z0e","rvHwt1y","vhvMvha","wNn5ve4","CNzHBfzHBhu","AgLNAa","uK1xEha","BM9vAfu","qNnmrhG","A2ntALi","Dgv4Dc9WBge","DMvYC2LVBG","tgLVtfa","wLzize0","AxnrB1nby2S","CNjVCK1LC3m","tgrxtMy","AeLPrxa","y3jLyxrLuMu","yMLUza","r2v1y1m","zsbHihn0CMK","ExvlELC","B3bLBG","sK5xBMK","D01vr1G","CgfNzxnOB3C","AgvHzgvYCW","uNjJDhO","CMvTB3zLrxy","C3vIC3rYAw4","vhb6Bfy","BezSDxnO","CNHRCM8","vufOshC","Chv0","BeHMrwi","rfHctMK","CwjRqwW","ihrPBwvZ","zxf1ywXZ","Dhr3Awq","zMXVB3i","CgfNzwHPzgu","D3fmD0W","zvvYBa","zhLPrgi","r21JEKG","ywDjCLO","wefRvfa","zvHWChC","jMPZy2fSBgi","y3bPywi","uNPgtgS","t0fWr3u","B25LCNjVCG","CgfYC2u","z1boC2O","AxnbCNjHEq","twjUEhG","CMLLC0nVDw4","yw1LoIa","CMntt0i","ywnRDxbfBMq","mhW1","BwLZzq","ywnRpwzYB24","tNLJzeG","qxHRvNG","tKHfBwK","tufyx1jfvfi","x2nVBM5Ly3q","y0jvuxe","AMDdBw4","zxmGCMvHy2G","B25tDgfYDfi","sfnisuu","zg14Avu","ywXS","y3znz0G","B3bLCNr5tMe","suTHvva","zKrgD2S","wvvquLy","lcbOB3n0BMe","yNL0zu9MzNm","Aw5PDcbrB1m","vhHlshi","uNH3AKK","x29UvgLTzw8","AKrKqNm","tLvkveC","q0vPA3G","BKvIy0K","CvvlDNG","zfDVCMTLCKC","y2fSBa","wNrSD0u","q09oveLovuu","BM93","DhjPzxmGCMu","vKr5Chu","q0Xpu0ve","q1PVt2e","swPZwei","zwrPyxrLBhK","y29UBMvJDeu","v2vIu29JA2u","rMvyAxy","yLP1sfG","zxq9DxrMltG","zw1PDa","igzHAwWSig0","vfnMA3K","ugPKENy","zw1iyKe","ANHAB3C","BLPyD1i","yKLyv3q","Dg5oDve","CwXjwve","BNviu3K","Eu1dvvu","ywr2yw5Jzq","u3vkseG","yM9L","yuzms08","A2v5CW","vwjiwfu","Bg9NsurozxC","zNvdwve","vhrOuu0","wMnyAxG","odu5nduWne9buvjtuq","ywnOzwq","C3bes1C","Dg9cExrLCW","x3nLBMrby2S","DhbizwfKzxi","sejdv08","q09ete8","Dwf3yKW","B254svu","CMvZB2X2zq","yNv3B0K","y3rsy00","rMHxAuG","zNjVBu51Bwi","ANncAfm","qNneD2e","sK1Xr2C","twj3vwq","zM9YrwfJAa","quL2u1i","ueroy1K","igzPzwXKoIa","runKzva","yu5nreC","ysbTDxn0igi","rLjptLrjrvi","yurAthe","CgLUz0LUDgu","BxnNsuq","AMjrrKi","seDKDuK","zgrjrcWGzgu","yxrHlcbKyxq","EgTwwNm","B0vVrMG","z2v0qwXS","DgjTDvy","u1DMEeW","yNL0zuXLBMC","mJi2ota1m2HluMvvEa","t1bftL9fuLi","r3zSCey","EfnYsxC","zKH2rfC","wfPtzgW","tfLbCue","ign1CNnVCIa","rKLmrv9ot1q","z2f1zLu","vxbKyxrLq28","seTbtwC","vNfNsMq","BgvUz3rO","BMrLEa","CKndvw4","sgvSBNq","Dg9hzw5LCMe","ywXPzcb1CMW","suLVwxO","CxrfwMK","sgLOsKq","CLzHBhvLCW","x2nSzwfYvgK","B25mAw5L","Dgv3shO","x3bYzwzPEa","ihjLy29UBMu","t1bftG","zNjVBNrPzxi","sxPhvxu","yLPSAK0","D3nLqKS","A2v0ignVBNm","z2v0qwXSs2u","uM5utem","v3bQzhy","zMzMzG","BwvZC2fNztO","txfKqwS","uevTruy","C3rVCcbPBw0","BMnVzgLUzW","uMfRywe","EwHMu1u","DgfIyxnL","yKvJzvC","BxbnDwi","y3r4","wKnKB3O","B1PIuMK","BKzZDKG","D0T5rKu","mZaWEenZtKfT","ugHuvwy","q0j4tvG","C0jf","rePAtMu","wxnvAwi","vhPWzKy","vuXjEvu","C2nYAxb0","sM9LtgC","vgDjwMm","vKPiENe","wefAsKq","AwXLtMfTzq","sefHBeK","Dez1zKe","aaaaaaaaaaa","B3bLCNr5","wfL5se0","EgL2BMm","q09otKvdveK","uwrPqu0"];return Yo=function(){return t},Yo()}var aS=Object[N(529)+"operty"],cS=Object[N(1195)+N(1486)+N(1343)],qx=(t,e)=>function(){return t&&(e=(0,t[{VQIMX:function(c,l){return c(l)}}[N(1221)](cS,t)[0]])(t=0)),e},lS=(t,e)=>{let r=N,i={tVopi:function(c,l,u,f){return c(l,u,f)}};for(var o in e)i[r(552)](aS,t,o,{get:e[o],enumerable:!0})};function dS(){return Fx||(Fx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function uS(){let t=N;return zx||(zx=[IDBCursor[t(1766)+"e"][t(1529)],IDBCursor[t(1766)+"e"].continue,IDBCursor[t(1766)+"e"]["continue"+t(976)+"ey"]])}function fS(t){let e=N,r={kUCeD:function(o,c){return o(c)},NUJTG:function(o){return o()},ovmgo:e(435),bDEAF:function(o,c){return o+c},kdMbB:e(797),zCQff:e(1123),Zejob:function(o,c){return o(c)},BonNc:function(o,c){return o(c)},lEvXf:function(o){return o()},MIYxR:e(1706),bZUsK:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let l=e,u={EepqR:r.ovmgo,tVOPx:function(m,v){return m>v},aZJlp:function(m,v){return r[j(573)](m,v)},jkPOJ:function(m,v){return m===v},XAZJD:r[l(1034)],wwjps:r[l(781)],MrtvY:function(m,v){return r[l(970)](m,v)},yszIs:function(m,v){return r[l(569)](m,v)},EbPez:function(m){return r[l(1745)](m)}},f=()=>{let m=l;t[m(1435)+m(776)+m(1260)]("success",x),t["removeEv"+m(776)+"ner"](u[m(742)],p)},x=()=>{let m=l,v={tOVOH:function(_,b){return u[j(1122)](_,b)},UAWBy:function(_,b){return u[j(560)](_,b)},bUTZF:"Read pas"+m(581)};if(u.jkPOJ(u[m(1644)],u[m(420)])){let _=_0x1aaddc[m(1373)];if(v.tOVOH(v[m(782)](_,_0xa08893),_0x42f9e6.limit))throw new _0x29e32e(v.bUTZF);return _0x45b862[m(1373)]+=_0x486f2f,_}else u[m(1671)](o,u[m(493)](Bt,t[m(364)])),u[m(1663)](f)},p=()=>{let m=l;r[m(1235)](c,t[m(435)]),r[m(1497)](f)};t["addEvent"+l(1811)](r[l(612)],x),t[l(1227)+l(1811)](r[l(1795)],p)});return i.then(o=>{let c=e;r[c(1239)](o,IDBCursor)&&Hl[c(1796)](o,t)})[e(691)](()=>{}),Qo.set(i,t),i}function hS(t){let e=N,r={nPGLH:function(o,c){return o(c)},xkBhr:"AbortError",KFNCu:function(o){return o()},xMwnm:e(712),WQvWE:e(435),lJxav:e(1712)};if(Xo[e(1678)](t))return;let i=new Promise((o,c)=>{let l=e,u={rgeea:r[l(1324)],FnekU:r[l(1803)],dmxiU:r[l(940)],nNrwJ:function(m){return r.KFNCu(m)}},f=()=>{let m=l;t[m(1435)+m(776)+m(1260)](u.rgeea,x),t["removeEventListe"+m(1260)](u[m(411)],p),t[m(1435)+m(776)+m(1260)](u[m(1483)],p)},x=()=>{let m=l;u[m(700)](o),u[m(700)](f)},p=()=>{let m=l;r[m(1340)](c,t[m(435)]||new DOMException(r.xkBhr,r[m(828)])),r.KFNCu(f)};t[l(1227)+l(1811)](l(712),x),t["addEvent"+l(1811)](r.WQvWE,p),t[l(1227)+l(1811)](r[l(940)],p)});Xo[e(1796)](t,i)}function xS(t){ea={JIkeh:function(r,i){return r(i)}}.JIkeh(t,ea)}function pS(t){let e=N,r={TzpfF:function(i,o){return i(o)},GvlpF:function(i,o){return i(o)},PcyNO:function(i,o){return i!==o},XQzXP:"yiNJC",fEqut:function(i,o){return i(o)},BUkor:function(i,o){return i(o)},EYwlt:function(i,o){return i===o},GIwwO:function(i,o){return i in o},SNeNb:e(1672)+e(884),YAxbo:function(i){return i()}};return r[e(893)](t,IDBDatabase[e(1766)+"e"][e(471)+e(540)])&&!r.GIwwO(r[e(363)],IDBTransaction[e(1766)+"e"])?function(i,...o){let c=e,l=t[c(1502)](r[c(1638)](ss,this),i,...o);return Ul[c(1796)](l,i.sort?i[c(618)]():[i]),r[c(1638)](Bt,l)}:r[e(423)](uS).includes(t)?function(...i){let o=e,c={VclBI:function(l,u){return r[j(1581)](l,u)},zTqwi:function(l,u){return r[j(1638)](l,u)}};if(r.PcyNO(o(956),r.XQzXP))return t[o(1738)](r[o(415)](ss,this),i),Bt(Hl[o(652)](this));{let l={mPQlT:function(u,f){return uCTMps.VclBI(u,f)},ZJPaX:function(u,f){let x=o;return uCTMps[x(1264)](u,f)}};return function(...u){let f=o;return _0x4e4dac[f(1738)](l.mPQlT(_0x591e21,this),u),l[f(953)](_0x26b771,_0x3be290[f(652)](this))}}}:function(...i){let o=e;return r[o(741)](Bt,t[o(1738)](ss(this),i))}}function gS(t){let e=N,r={JSPrY:function(i,o){return i===o},gqflQ:function(i,o){return i(o)},VwFcW:function(i,o){return i instanceof o},BeezL:function(i,o,c){return i(o,c)},Yswze:function(i){return i()}};return r[e(1325)](typeof t,e(1127))?r[e(539)](pS,t):(r.VwFcW(t,IDBTransaction)&&hS(t),r.BeezL(jx,t,r.Yswze(dS))?new Proxy(t,ea):t)}function Bt(t){let e=N,r={TthQM:function(o,c){return o instanceof c},YBuDq:function(o,c){return o(c)}};if(r[e(1537)](t,IDBRequest))return r.YBuDq(fS,t);if(Jo[e(1678)](t))return Jo[e(652)](t);let i=r[e(625)](gS,t);return i!==t&&(Jo[e(1796)](t,i),Qo[e(1796)](i,t)),i}var jx,Fx,zx,Hl,Xo,Ul,Jo,Qo,ea,ss,Ux=qx({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={emHbA:function(r,i){return r===i},gTUuY:"done",IyYex:t(1672)+t(884),amRTD:function(r,i){return r instanceof i},SRjAP:"EAnnf",ggtTL:function(r,i){return r in i}};jx=(r,i)=>i[t(1168)](o=>r instanceof o),Hl=new WeakMap,Xo=new WeakMap,Ul=new WeakMap,Jo=new WeakMap,Qo=new WeakMap,ea={get(r,i,o){let c=t;if(r instanceof IDBTransaction){if(e[c(1521)](i,e.gTUuY))return Xo[c(652)](r);if(e[c(1521)](i,e.IyYex))return r[c(1672)+c(884)]||Ul[c(652)](r);if(i===c(456))return o[c(1672)+c(884)][1]?void 0:o[c(1672)+"ore"](o[c(1672)+c(884)][0])}return Bt(r[i])},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;if(e.amRTD(r,IDBTransaction)&&(e[o(1521)](i,o(854))||i==="store")){if(e.emHbA(e[o(1062)],e[o(1062)]))return!0;++_0x4edd85,_0x36fa66+=4}return e[o(1278)](i,r)}},ss=r=>Qo[t(652)](r)}}),Wx={};function j(t,e){t=t-345;let r=Yo(),i=r[t];if(j.lPqjvZ===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",m="";for(let v=0,_,b,I=0;b=f.charAt(I++);~b&&(_=v%4?_*64+b:b,v++%4)?p+=String.fromCharCode(255&_>>(-2*v&6)):0)b=x.indexOf(b);for(let v=0,_=p.length;v<_;v++)m+="%"+("00"+p.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(m)};j.wkBXHa=o,j.UPevKW={},j.lPqjvZ=!0}let c=r[0],l=t+c,u=j.UPevKW[l];return u?i=u:(i=j.wkBXHa(i),j.UPevKW[l]=i),i}lS(Wx,{deleteDB:()=>wS,openDB:()=>mS,unwrap:()=>ss,wrap:()=>Bt});function mS(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let l=N,u={zpcJg:function(p,m,v,_,b){return p(m,v,_,b)},JhouP:function(p,m){return p(m)},xWtXh:function(p,m){return p(m)},esqmc:l(532),RxwjI:function(p,m){return p(m)},QFbZI:"upgraden"+l(643),LdWNf:"blocked"},f=indexedDB.open(t,e),x=u[l(1494)](Bt,f);return i&&f[l(1227)+"Listener"](u[l(414)],p=>{let m=l;u.zpcJg(i,u.JhouP(Bt,f[m(364)]),p[m(1759)+"on"],p[m(1685)+"on"],u[m(1783)](Bt,f["transact"+m(540)]))}),r&&f["addEvent"+l(1811)](u[l(1422)],()=>r()),x.then(p=>{let m=l;c&&p[m(1227)+m(1811)](u[m(418)],()=>c()),o&&p[m(1227)+m(1811)](m(1290)+"hange",()=>o())})[l(691)](()=>{}),x}function wS(t,{blocked:e}={}){let r=N,i={CZoOa:"blocked",PUryT:function(c,l){return c(l)}},o=indexedDB["deleteDa"+r(1624)](t);return e&&o[r(1227)+"Listener"](i[r(1509)],()=>e()),i[r(1212)](Bt,o).then(()=>{})}function Hx(t,e){let r=N,i={QDdRh:r(1706),LrWFS:r(1304)+r(377)+"t",uLBuX:r(532),NWhvl:r(1290)+r(1072),VJHzq:r(987)+"e",maYHG:function(f,x){return f instanceof x},TgIZc:function(f,x){return f in x},VXOaR:function(f,x){return f===x},xOeOP:r(758),PhTUf:r(701),tOViV:r(1651),dwJEE:function(f,x){return f!==x},QAOfc:r(511)};if(!(i[r(354)](t,IDBDatabase)&&!i[r(1642)](e,t)&&i.VXOaR(typeof e,i[r(572)])))if(i[r(1770)](i[r(1633)],i[r(645)]))_0x157b7b(i.QDdRh),this[r(349)](r(1304)+"e_success",_0x584880),this[r(349)](i.LrWFS,_0x26c114);else return;if(Zo.get(e))return Zo[r(652)](e);let o=e.replace(/FromIndex$/,""),c=i[r(734)](e,o),l=$x[r(1812)](o);if(!(o in(c?IDBIndex:IDBObjectStore).prototype)||!(l||Kx[r(1812)](o)))if(i[r(754)]!==i[r(754)])_0x2d5003&&_0x563841[r(1227)+"Listener"](CWGxti[r(764)],()=>_0x537607()),_0x3eb999&&_0xd0df02[r(1227)+r(1811)](CWGxti[r(448)],()=>_0x50a559());else return;let u=async function(f,...x){let p=r,m=this[p(471)+"ion"](f,l?i[p(1643)]:p(1366)),v=m.store;return c&&(v=v[p(806)](x[p(1230)]())),(await Promise[p(1484)]([v[o](...x),l&&m[p(854)]]))[0]};return Zo[r(1796)](e,u),u}var Kx,$x,Zo,_S=qx({"node_modules/idb/build/index.js"(){let t=N,e={kKPkb:function(o){return o()},qIhrK:t(652),iYUwu:"getKey",FEExk:t(1575),VGCkz:t(1613)+"ys",Asmmu:"count",pqGmI:function(o,c){return o(c)},eHxIH:t(1441),GUNMD:t(1027),QVTgv:"delete",VuYfn:"clear"},r=(t(1057)+t(1204))[t(1721)]("|"),i=0;for(;;){switch(r[i++]){case"0":e[t(1826)](Ux);continue;case"1":e[t(1826)](Ux);continue;case"2":Zo=new Map;continue;case"3":Kx=[e.qIhrK,e[t(1218)],e.FEExk,e[t(1791)],e[t(557)]];continue;case"4":e[t(1752)](xS,o=>({...o,get:(c,l,u)=>Hx(c,l)||o[t(652)](c,l,u),has:(c,l)=>!!Hx(c,l)||o[t(1678)](c,l)}));continue;case"5":$x=[e.eHxIH,e.GUNMD,e[t(872)],e[t(1767)]];continue}break}}}),yS={idb:function(t){let e=N;t[e(1075)]=Promise[e(1549)]().then(()=>(_S(),Wx))[e(1003)](function(r){return r})}},Gx={};function Mt(t){let e=N,r={dPYTw:function(u,f){return u!==f}},i=(e(892)+"2")[e(1721)]("|"),o=0;for(;;){switch(i[o++]){case"0":if(r[e(1822)](void 0,l))return l[e(1075)];continue;case"1":var c=Gx[t]={exports:{}};continue;case"2":return c[e(1075)];case"3":var l=Gx[t];continue;case"4":yS[t](c,c[e(1075)],Mt);continue}break}}(()=>{let t=N,e={pXdFd:t(975)+"1",umIMb:function(r,i){return r!==i},Helnt:function(r,i){return r!==i},qcXia:t(1240)};Mt.d=(r,i)=>{let o=t,c={NeZki:e[o(1805)],YQOEN:function(x,p){return e.umIMb(x,p)}};if(e[o(1595)](e[o(1173)],o(1005)))for(var l in i)Mt.o(i,l)&&!Mt.o(r,l)&&Object[o(529)+o(1649)](r,l,{enumerable:!0,get:i[l]});else{let x=c[o(1226)][o(1721)]("|"),p=0;for(;;){switch(x[p++]){case"0":var u=_0x49c011[_0x1b1fbe];continue;case"1":return f[o(1075)];case"2":var f=_0x4db61d[_0x20e3d0]={exports:{}};continue;case"3":_0x2dfa6d[_0x2e2695](f,f[o(1075)],_0x34b616);continue;case"4":if(IMohMu[o(880)](void 0,u))return u.exports;continue}break}}}})(),(()=>{let t=N;Mt.o=(e,r)=>Object[t(1766)+"e"][t(593)+t(1649)][t(1502)](e,r)})(),(()=>{let t=N,e={hwygA:function(r,i){return r!=i},BBMpo:t(1105)+"d",KQdnG:t(1301)};Mt.r=r=>{let i=t;e[i(1406)](e[i(1086)],typeof Symbol)&&Symbol[i(1328)+i(486)]&&Object[i(529)+i(1649)](r,Symbol[i(1328)+i(486)],{value:e[i(387)]}),Object[i(529)+i(1649)](r,i(1249)+"le",{value:!0})}})();var Pe={};(()=>{let t=N,e={tellO:function(a,n){return a+n},aFLKO:function(a,n){return a*n},Rakaa:function(a,n,s){return a(n,s)},PDuaq:t(738),YVafA:function(a,n,s){return a(n,s)},fHvDW:function(a,n){return a(n)},QBjhf:function(a,n){return a(n)},exmAb:function(a,n){return a+n},iUFBQ:function(a,n){return a(n)},mSrVJ:t(682),XZSdl:t(1616),QlBgi:function(a,n){return a===n},QHZos:"BshBu",MmmGH:function(a,n){return a(n)},saLtG:t(1719)+t(1719)+t(1719)+t(1719),VFWIN:function(a,n){return a===n},QlzqR:"JUhPL",WZShw:function(a,n){return a<n},nFsvH:function(a,n){return a!==n},HihJD:function(a,n){return a-n},jnLLH:function(a,n){return a!==n},qCALE:function(a,n){return a<n},LNjww:function(a,n){return a===n},HHOJB:function(a,n){return a<n},JynbR:function(a,n){return a!==n},Wpjdv:function(a,n,s){return a(n,s)},OoipI:function(a,n,s){return a(n,s)},EfRxl:function(a,n){return a(n)},cFYXJ:function(a,n){return a>>>n},QJyRA:function(a,n,s){return a(n,s)},rNpFw:function(a,n,s){return a(n,s)},TpzlV:function(a,n){return a&n},oHZTf:t(444)+t(1695)+t(1561)+t(1214),JoOdr:function(a){return a()},Wurkp:function(a,n){return a|n},qzKlV:function(a,n){return a|n},AXIAy:function(a,n){return a<<n},ORHYd:function(a,n){return a&n},rOakf:function(a,n){return a<<n},yJuap:function(a,n){return a&n},qfqMM:function(a,n){return a&n},zdydU:function(a,n){return a>>n},moaeE:function(a,n){return a&n},erODb:function(a,n){return a!==n},rtSed:t(1705),mwGZS:t(992),GeucS:function(a,n,s){return a(n,s)},PwpyU:function(a,n,s){return a(n,s)},sozit:function(a,n,s){return a(n,s)},QNdWk:function(a,n){return a(n)},CiuoP:t(361),IzKUC:function(a,n,s){return a(n,s)},gdyOU:function(a,n,s){return a(n,s)},MtWNZ:function(a,n,s){return a(n,s)},PgAft:function(a,n){return a(n)},eaWMB:function(a,n){return a!==n},xXCoT:"RbEYx",YdPVU:function(a,n,s){return a(n,s)},nKfxI:function(a,n){return a!==n},ECdeP:function(a,n,s){return a(n,s)},BlSqA:function(a,n,s){return a(n,s)},jgCmn:function(a,n,s){return a(n,s)},HKAMg:function(a,n,s){return a(n,s)},DSNrG:function(a,n,s){return a(n,s)},MRMiz:function(a,n){return a+n},CODLO:t(1070),EoBNl:function(a,n){return a(n)},qtEqU:function(a,n){return a(n)},Lggrz:function(a,n,s){return a(n,s)},IINGU:function(a,n,s){return a(n,s)},fzylE:function(a,n){return a(n)},qnXJa:function(a,n){return a(n)},aDZLq:function(a,n){return a(n)},Hmaoj:function(a,n){return a(n)},hqIvh:function(a,n,s){return a(n,s)},vyxVA:function(a,n,s){return a(n,s)},kXXIP:function(a,n){return a(n)},cpiab:function(a,n){return a===n},oZbRi:t(444)+t(1695)+t(1561)+t(1820),XAnVK:function(a,n){return a===n},NyiXr:t(444)+t(1695)+t(1561)+"LogID",ZtlwE:function(a,n){return a===n},kVKcW:t(444)+"required"+t(1561)+"service",thsNq:function(a,n){return a(n)},LhXHW:function(a,n){return a+n},jQBNg:function(a,n){return a+n},vGAFK:"Unimplem"+t(679)+"pe: ",yQEqr:t(1141),dPXKF:t(1569),XAkTP:function(a,n){return a>>n},qPnZL:function(a,n){return a>=n},NyYrt:function(a,n){return a>>>n},sWXIa:function(a,n){return a|n},UYPmh:function(a,n){return a<<n},bJxFv:function(a,n){return a<<n},vUofI:function(a,n){return a!==n},wtDeu:"MBbYp",Tqlgj:t(479),idkVN:function(a,n){return a===n},wMzTx:"error",FeXiv:t(532),fydeg:t(1800),RPnfa:function(a,n){return a>n},ARBlZ:t(1654)+t(581),BvtsB:function(a,n){return a*n},pcnpO:function(a,n){return a>n},VmMeu:"Read pas"+t(581),GYMdg:function(a,n,s){return a(n,s)},qbkAl:function(a,n){return a&n},bxcdz:function(a,n){return a>>>n},NKcQo:function(a,n){return a&n},HyZqb:function(a,n){return a>>>n},NzDoA:function(a,n,s){return a(n,s)},ndPhx:function(a,n){return a<n},FTjjP:t(842),ETllm:function(a,n){return a+n},vCQAw:function(a,n){return a===n},JoeLg:function(a,n){return a&n},eWdeA:function(a,n){return a(n)},QGqLP:function(a,n){return a===n},kOILv:function(a,n){return a&n},CecHu:function(a,n){return a>=n},DtAiq:function(a,n){return a+n},iRUIP:function(a,n){return a+n},PEmEF:function(a,n){return a&n},DymLD:function(a,n){return a|n},bNlZH:function(a,n){return a<<n},VPffh:function(a,n){return a(n)},KgzDV:function(a,n){return a==n},NscyF:function(a,n){return a+n},sdcaU:function(a,n){return a+n},yLiBN:function(a,n){return a+n},uXXxV:function(a,n){return a+n},syZwi:function(a,n){return a!==n},EbSVP:function(a,n){return a&n},cKUbD:function(a,n){return a<<n},CwNwo:function(a,n){return a|n},ylaSN:function(a,n){return a&n},PqhRA:function(a,n){return a&n},vibvS:function(a,n){return a<=n},Ubmqy:function(a,n){return a>=n},smrHn:function(a,n){return a+n},aYVGX:function(a,n){return a!==n},PGaJl:function(a,n){return a+n},ywsqE:function(a,n){return a+n},DEysO:function(a,n){return a+n},ctRcM:function(a,n){return a+n},hUAZm:function(a,n){return a<<n},tewHz:function(a,n){return a|n},MGtgp:function(a,n){return a|n},eePuJ:function(a,n){return a&n},vanGG:function(a,n){return a<<n},SxMkd:function(a,n){return a&n},Gxiof:function(a,n){return a<<n},VJABi:function(a,n){return a>n},gbtaE:function(a,n,s){return a(n,s)},MYpkC:function(a,n){return a>>n},RMWxp:function(a,n){return a<n},EmmsR:function(a,n){return a>=n},TpLwR:function(a,n){return a<=n},VMyEB:function(a,n){return a<<n},eSpoa:function(a,n){return a<n},BrLRj:function(a,n,s){return a(n,s)},pnzAT:function(a,n,s){return a(n,s)},Abpsi:function(a,n){return a>=n},yUHQE:function(a,n){return a-n},rcSOB:function(a,n){return a+n},dyiDb:function(a,n){return a<n},FFKcN:function(a,n){return a<n},kCtQH:function(a,n){return a&n},bIXWt:"teHbP",XruKk:function(a,n){return a>>n},tFufA:function(a,n){return a|n},RiGfH:function(a,n){return a&n},xtkAQ:function(a,n,s){return a(n,s)},Vksbk:function(a,n,s){return a(n,s)},gLKQe:function(a,n){return a<<n},ljWJh:function(a,n){return a&n},guVJC:function(a,n){return a>=n},VqgJd:function(a,n,s){return a(n,s)},xSrIw:function(a,n){return a|n},ayKNC:function(a,n,s){return a(n,s)},IWbhp:function(a,n,s){return a(n,s)},RnTLC:function(a,n,s){return a(n,s)},wwAHC:function(a,n){return a!==n},tpXds:t(397),ZlqUB:function(a,n){return a(n)},dBSQA:function(a,n){return a<<n},rrBFL:function(a,n){return a&n},BcfXd:function(a,n){return a&n},eLvqi:function(a,n){return a!==n},edUXc:"EwCrY",LioLP:function(a,n){return a&n},tbmuV:function(a,n){return a&n},lFucL:function(a,n){return a(n)},vCjQK:function(a,n){return a&n},yTeRF:function(a,n){return a(n)},ZbYkY:function(a,n){return a(n)},uxGBH:function(a,n){return a(n)},geWry:function(a,n){return a&n},nXNni:function(a,n){return a<<n},abshl:function(a,n){return a<<n},cKFEB:function(a,n){return a|n},fOuhn:function(a,n){return a>>>n},CExps:function(a,n){return a|n},ZAJji:function(a,n){return a>>>n},cNMxS:function(a,n){return a===n},cZFCg:function(a,n){return a<n},bPPOK:function(a,n){return a<n},eEwSV:function(a,n){return a<n},wKyFE:function(a,n){return a<n},EoTHL:function(a,n,s){return a(n,s)},lomVH:function(a,n){return a&n},ItOZY:function(a,n){return a|n},MKeLv:function(a,n){return a+n},lwdvU:function(a,n){return a|n},uZHxf:function(a,n){return a>>>n},JMqGg:function(a,n){return a+n},yJRnJ:function(a,n){return a>>>n},RaFFS:function(a,n){return a>>>n},gPNsj:function(a,n){return a+n},pFIHH:function(a,n){return a!==n},UbHXU:function(a,n){return a|n},bUIwi:function(a,n){return a&n},KDWEz:function(a,n){return a>>>n},xTmxH:function(a,n){return a+n},JIzVj:function(a,n){return a!==n},nZXwR:function(a,n){return a&n},JhONg:function(a,n){return a>>>n},OApGu:function(a,n){return a!==n},GSfCz:function(a,n){return a&n},lgVPU:"LZYBW",nfObE:t(478),nKHeT:function(a,n){return a(n)},oMUVs:function(a,n){return a===n},KDGOa:t(1500),AYxiw:function(a,n){return a|n},HBCWO:function(a,n){return a<<n},vRyln:function(a,n){return a<<n},vidRT:function(a,n){return a<<n},zTqbT:function(a,n){return a|n},mTMUV:function(a,n){return a<<n},noKjb:function(a,n){return a<<n},zAcWO:function(a,n){return a|n},cvMgH:function(a,n){return a|n},gRksr:function(a,n){return a<<n},AtFVf:function(a,n){return a===n},ZazYt:function(a,n){return a<<n},NrvrM:function(a,n){return a>>>n},bYxFd:function(a,n){return a|n},XizBt:function(a,n){return a<<n},LJCjq:function(a,n){return a>>>n},jxZow:function(a,n){return a&n},iYdXd:function(a,n){return a&n},bMXuA:function(a,n){return a(n)},GgmSv:function(a,n){return a<=n},lIbkP:function(a,n){return a|n},rxtDz:function(a,n){return a+n},HSHIE:function(a,n){return a>>>n},qcWZs:function(a,n){return a>>>n},xkVZs:function(a,n){return a>>>n},eLSIV:t(1706),LBUCu:function(a,n){return a===n},xapTC:t(816),HaITn:function(a,n){return a&n},Jwhgc:function(a,n){return a>>>n},hEWNU:"YkMeI",oRBZN:t(1679),hNRGN:function(a,n){return a&n},yMCUU:function(a,n){return a&n},BBlrr:function(a,n){return a>>>n},vglom:function(a,n){return a&n},KDCsn:function(a,n){return a+n},PDNcY:function(a,n){return a>>>n},eISTT:function(a,n){return a+n},KSWWI:function(a,n){return a+n},xKYEW:function(a,n){return a|n},nZWmq:function(a,n){return a<<n},WgtVE:function(a,n){return a!==n},HWYqK:function(a,n){return a>>>n},vQaNe:function(a,n){return a===n},naIAD:function(a,n){return a===n},QdiAM:function(a,n,s){return a(n,s)},QLszs:function(a,n,s){return a(n,s)},wyrbf:function(a,n){return a===n},Pjdzv:t(1799),jAazU:"cBVjZ",JbAzc:function(a,n){return a&n},HGduI:function(a,n){return a>>>n},TRnOn:function(a,n){return a>>>n},XAxrL:function(a,n){return a>>>n},edGuz:function(a,n){return a&n},wseBK:t(1326),tnNuQ:"shzPe",FVKlF:"3|2|1|0|"+t(1107),IvFuk:"MESSAGE_"+t(677),EPeFV:t(1476)+"IES_ERROR",wMMPd:t(1652)+t(792),ABkvW:"NATIVE_E"+t(504),VBWvv:t(1580)+"OR",UAhHw:function(a,n){return a===n},gaufU:"JvYEP",jfixw:function(a,n){return a===n},LNZkW:function(a,n){return a===n},ztQWs:function(a,n){return a==n},iDRxk:function(a,n){return a>n},HAalI:t(534),FIxpE:function(a,n){return a===n},TmfLY:t(1300)+"d error.",PtwUK:function(a,n){return a+n},XePeX:function(a,n){return a+n},KayWl:function(a,n){return a===n},KObYF:function(a,n){return a===n},JmTdH:function(a,n,s){return a(n,s)},pIbKo:t(630),mRXnT:t(1232),erLpB:function(a,n,s){return a(n,s)},riCIj:t(1429),oqlIC:function(a,n){return a===n},dJMrP:t(1327),VzRpC:function(a,n,s){return a(n,s)},ULIyU:function(a,n,s){return a(n,s)},cDDwv:function(a,n){return a instanceof n},piADj:function(a,n){return a===n},CzytD:t(1085),oEoFh:function(a,n){return a===n},yvyME:t(1749),TTvsP:function(a,n){return a||n},yReJw:"undefined",eiUhG:function(a,n){return a<<n},xovxq:function(a,n){return a!=n},ZVHdM:function(a,n){return a<=n},IkbBm:"next() c"+t(866)+t(1267)+t(775)+"process",OqNzT:t(1797),VjpiM:function(a,n){return a===n},onxIU:function(a,n){return a===n},ewTjH:function(a,n){return a+n},qlIYQ:function(a,n){return a<n},EucCE:function(a,n){return a>=n},Twbvk:function(a,n){return a<n},ERkCb:function(a,n){return a|n},UJjSE:function(a,n){return a<<n},CEikx:function(a,n){return a&n},HreFb:function(a,n){return a<n},ftKDR:function(a,n){return a&n},XRvps:function(a,n){return a-n},LeewP:function(a,n){return a|n},bzDss:function(a,n){return a<<n},vksYh:function(a,n){return a&n},tMLHt:function(a,n){return a&n},ccoEe:t(577),WnFdC:t(1137),ZCdoz:function(a,n){return a>>n},zcsAG:function(a,n){return a|n},BlAww:function(a,n){return a===n},ytYTd:function(a,n){return a&n},vDIuB:t(808)+t(1470),YJrBF:function(a,n){return a+n},YocLu:function(a,n){return a&n},cRMAu:function(a,n){return a>>n},fMcnf:function(a,n){return a&n},WkQXV:function(a,n){return a|n},HZCrT:function(a,n){return a&n},fLKKC:function(a,n){return a-n},rJySz:t(758),QuQUZ:function(a,n){return a instanceof n},UrZSV:t(717),GFkws:"ZCTuk",NuXnc:function(a,n){return a!=n},PJsLr:t(653)+"ion/json",TPDuL:t(1416)+"in;chars"+t(1516),nkBAF:"ppe",MVElr:"idb",YgUDk:t(1310),WWOSA:function(a,n){return a(n)},JzmpK:t(1155)+t(640),PlmCT:t(1375)+t(796),NycdH:"start",PKcJU:function(a,n){return a|n},RifiQ:function(a,n){return a|n},fxlCf:function(a,n){return a+n},rbIgC:function(a,n){return a|n},olxrz:function(a,n){return a+n},WuMHU:function(a,n){return a<<n},vewIy:function(a,n){return a+n},nuHSy:function(a,n){return a!==n},AnoxK:t(1344),Kpvzw:t(1255),ymcDp:t(1393),mDPyx:t(1332),dVdbg:"2|4|0|1|3",Ioppa:t(731),Uasqu:"TuRbR",bZljM:function(a,n){return a||n},XJbWf:"KMoge",kZbce:function(a,n,s){return a(n,s)},Rbwaq:function(a,n){return a!==n},RPGtH:t(1388),sYdif:function(a,n){return a||n},MFOAW:"reconnect",iWkMt:t(491),qAwbr:t(613),NLqvA:function(a,n){return a||n},SrinG:function(a,n){return a||n},hFYIG:function(a,n){return a===n},IvXNh:t(1737),hIiEp:function(a,n){return a||n},CCjWc:t(766),dIYkb:function(a,n){return a!=n},amfgm:t(1492)+t(1130)+"d",pocFk:t(413)+"4",zVELc:"message",aJyet:t(1413),ouvAU:t(930),kkEDG:function(a,n){return a!==n},YUPRV:t(1021),VnhgC:function(a,n){return a*n},IKaUP:"CqGlD",fJVnF:t(1248),afkRX:function(a,n){return a(n)},vAujh:function(a,n,s,d){return a(n,s,d)},Xnwgs:t(1159)+t(1305),BRMeP:t(1159)+t(1233)+"ck",BaaNH:"x_fronti"+t(830)+"k",ITEnR:function(a,n){return a(n)},FgYcC:function(a,n,s,d){return a(n,s,d)},kHvUm:function(a,n){return a!==n},lHfEb:"ElBOo",hetoc:t(592),URpLF:function(a,n,s,d){return a(n,s,d)},cYRZf:t(1784),pBzHk:function(a,n){return a&&n},cBUQq:t(770),SUWwN:function(a,n){return a||n},aNMDG:t(390),HCRxd:function(a){return a()},qcKkU:t(385),nHZEN:function(a,n){return a===n},Gegjw:"ZFUDb",wPVXP:function(a,n){return a(n)},omQtP:function(a,n){return a instanceof n},gNviT:t(653)+t(427)+t(1017)+t(1792),QFTWp:t(559)+"e",LtmXH:t(1743),lKysh:function(a,n){return a(n)},EglzS:function(a,n){return a+n},fuCYQ:t(1739),WjisH:t(783)+"0",azvXY:t(1066),njwtN:function(a,n){return a>=n},AwLWJ:function(a,n,s,d){return a(n,s,d)},JzKJe:function(a,n){return a+n},UPGMQ:t(794),vsvBD:t(1414),tMfrb:function(a,n){return a+n},ApJFm:function(a,n){return a<n},qjMbF:function(a,n,s){return a(n,s)},RObEt:function(a,n){return a<<n},rHPQw:"0|2|4|1|3",VDypu:function(a,n){return a+n},DcoKA:function(a,n){return a<n},npmOq:function(a,n){return a|n},vxKfP:function(a,n){return a+n},oyTzP:function(a,n){return a|n},CJfte:function(a,n){return a|n},wRoMy:function(a,n){return a<<n},bEceW:function(a,n){return a+n},BKRsK:function(a,n){return a+n},yhfSU:function(a,n){return a+n},nohRc:function(a,n){return a+n},XlvFB:function(a,n){return a>>>n},xepyU:function(a,n){return a>>>n},eKzzx:function(a,n){return a===n},aBiyA:t(1292),zXqWj:t(1806),GgSMC:function(a,n){return a+n},IIoYz:function(a,n){return a&n},YAhwx:function(a,n){return a<n},IjsXB:function(a,n){return a|n},vpqhJ:function(a,n){return a<<n},nbGFW:function(a,n){return a<n},aNgYW:function(a,n){return a+n},LGBlz:t(750)+t(1039)+t(1250),QmXfS:t(1274),PwPfw:function(a,n,s,d){return a(n,s,d)},oSxkT:"curvalue",uRBLT:t(400),HeEtK:"cursor.s"+t(737),psvjV:function(a,n){return a(n)},qvuur:function(a,n,s){return a(n,s)},OmMJS:function(a,n){return a+n},CtIxX:t(685)+t(617),akDfE:t(1771)+t(1216),ZcXix:t(638)+t(1601),SWfxL:t(458),GdgRQ:t(957),ogwOe:t(1504),hUWtG:function(a){return a()},dcJol:"setcursor",fLfDU:t(1717),UXvYC:t(1106),RzFLk:function(a,n){return a!==n},fDFwk:t(919),ehpim:t(494),ROjCD:t(489),nwprT:function(a,n,s){return a(n,s)},LEcBK:function(a,n){return a(n)},tKsrJ:t(1599),eVSuZ:function(a,n,s){return a(n,s)},stsEo:function(a,n,s){return a(n,s)},QtZAj:"x_fronti"+t(1206),dDESF:t(1040)+"s",hTPTE:function(a,n,s){return a(n,s)},ZSiyp:t(763)+t(405)+"e",DktTY:function(a,n){return a(n)},FGjbg:t(763)+t(915)+"ue",TSfky:function(a){return a()},GwWvF:function(a,n){return a>n},DxWgG:t(1309),EBXJE:function(a,n){return a!==n},kYiGV:t(906),lAYHs:t(561),AIvSR:function(a){return a()},Xhzkk:function(a){return a()},XYyHM:function(a,n){return a+n},AbuQB:t(1823),VnRne:function(a,n){return a&&n},SbGAz:function(a){return a()},Vxrpx:function(a,n){return a(n)},mRyPj:function(a){return a()},LUHrM:function(a,n){return a===n},yuKzW:function(a,n){return a!==n},buwoI:function(a,n){return a===n},AlhPv:t(419),mohjp:function(a,n){return a===n},ngogO:function(a,n,s){return a(n,s)},FjHJH:function(a,n){return a===n},owUFQ:t(1007),Tsagk:function(a,n,s){return a(n,s)},ggLak:function(a,n,s){return a(n,s)},pPQkj:function(a,n,s){return a(n,s)},bZuHX:function(a,n,s){return a(n,s)},pobfH:t(1246),mUSTA:function(a,n){return a(n)},eCIZr:t(1415),Jdjzl:"arraybuffer",DJZNe:t(453),YGApQ:function(a,n){return a/n},iQwJV:t(394),jrOmJ:function(a,n){return a==n},SqEkk:function(a,n){return a===n},OnFQh:t(1291)+t(1166)+t(1597),FeVNZ:t(1291)+t(347)+t(1815)+t(937)+t(1612)+t(961)+"is undef"+t(1690),CImvh:t(1620)+"ediately"+t(1606)+"ct",Mbnxx:t(1187),sYmoH:t(900),LrXhM:t(1449),quXYk:"pageshow",AAXTF:function(a,n){return a!==n},QOLMs:t(1530),txcUc:function(a,n){return a!==n},DRDtu:function(a,n){return a===n},dqurj:"ALvcb",QHHel:function(a,n){return a==n},BWxBv:"ws://",GxPHA:"wss://",gTmYY:t(1447),jCEZy:t(1291)+t(1e3)+t(1571)+t(1747)+"r ttwID",TufTp:t(1127),RyeRN:function(a){return a()},JAHDf:function(a,n,s){return a(n,s)},WAAqM:t(642),PNETg:function(a,n){return a===n},NRtFB:t(965),hPPZn:t(1554),BYhNu:function(a,n,s){return a(n,s)},YekXy:function(a,n){return a||n},wfUhD:function(a,n,s){return a(n,s)},zkLXb:function(a,n){return a-n},nozXO:function(a,n,s){return a(n,s)},YtCfC:function(a,n){return a!==n},aekfh:function(a,n){return a===n},ymOrA:t(1037),TxKHr:function(a,n){return a(n)},wqLwL:t(1565)+">",ACbzH:function(a,n){return a-n},lGtde:function(a,n){return a>n},YfQgD:function(a,n,s){return a(n,s)},aiGZF:function(a,n,s){return a(n,s)},yOnsw:t(1304)+t(377)+"t",ZPZwp:"timeout",VDemr:t(1531),LYAqA:"VusXs",SJCuO:"going aw"+t(633)+t(1068)+"ting ser"+t(994),eXppw:function(a,n){return a!==n},UNoLK:t(1038),GSJsh:t(402),hHCnX:function(a,n){return a(n)},uawbL:function(a,n){return a(n)},MqdAk:t(1299),spDKW:"TJOio",xDjjE:t(1074)+t(838)+"onnecting",qOPzH:function(a,n){return a(n)},RaFEb:t(1354),IVbGl:"4|0|2|3|1",HilTg:function(a,n){return a>=n},lYEHA:function(a,n){return a<n},iwrnN:function(a,n){return a&n},aLAVt:function(a,n){return a>=n},DjhWR:function(a,n){return a-n},REyVK:function(a,n){return a|n},PMKas:function(a,n){return a<<n},ZHFIJ:function(a,n){return a<<n},FsqSN:function(a,n){return a<<n},mGnxT:function(a,n){return a>>n},DQtPO:function(a,n){return a===n},FnroY:"EYfSl",tnQXe:t(656)+"0",Bmagx:function(a,n){return a(n)},GULoC:t(1688),NtzDb:t(651),jzWZZ:t(1257),IPEsQ:function(a,n){return a(n)},DUyRc:"FzSqe",reIXd:"ack",ugAlZ:function(a,n,s){return a(n,s)},cJtpV:function(a,n){return a===n},FeVbQ:t(1149),Rrctz:function(a,n){return a!==n},DEBXU:t(1773),vTYok:function(a,n){return a+n},aLATJ:t(811)+t(762)+t(779)+t(800)+"ed",bomjk:function(a,n){return a===n},LenfH:t(811)+t(634)+"y closed",KZwQq:function(a,n){return a==n},lHmpw:t(1291)+t(371)+t(1280)+t(1572)+t(1564)+t(1427)+"ng or an"+t(649)+"ffer",MbwUd:function(a,n){return a==n},qyCEp:t(1318),CBxMX:function(a,n){return a instanceof n},zBenD:function(a,n){return a instanceof n},FNZOg:t(1291)+t(371)+t(622)+t(737),ZsIUT:function(a,n){return a===n},cIgeA:t(1164),mpMub:t(1103),gAjOe:function(a,n){return a||n},UGnKs:function(a,n){return a!==n},NgqDr:t(835)+t(996)+t(1208),SVgBQ:function(a,n,s){return a(n,s)},pyamr:function(a,n,s){return a(n,s)},KGVnL:function(a,n){return a!==n},OQSze:t(1430),zOgFT:function(a,n){return a instanceof n},DnFMX:function(a,n,s,d){return a(n,s,d)},iRtAQ:t(514),xsccc:function(a,n){return a>>>n},lFUjc:t(982),yWAfK:function(a,n){return a(n)},nLytJ:t(1304)+"e_success",hxFZm:t(1648),dupvD:function(a,n){return a/n},pHPuR:function(a,n){return a!=n},zsDln:function(a,n){return a===n},nEbcI:t(1782),EPITm:t(1315),MabHS:function(a,n){return a===n},LIDOU:function(a,n){return a!=n},GErfu:function(a,n){return a!=n},bxxdy:function(a,n){return a===n},NHEmi:function(a,n){return a===n},eAwAj:"ServiceW"+t(876)+t(1205),THdia:function(a,n){return a===n},FDJAf:function(a,n){return a!=n},LIcJm:function(a,n,s){return a(n,s)}};Mt.r(Pe),Mt.d(Pe,{FWS:()=>Cg,CustomErrorEvent:()=>ad,createCloseEvent:()=>mt,ReconnectEvent:()=>od,createErrorEvent:()=>ct,decodedFrame:()=>tn,createOpenEvent:()=>hd,CustomCloseEvent:()=>cd,createReconnectEvent:()=>wa,FrontierMessageEvent:()=>dd,encodeFrame:()=>Ft,createMessageEvent:()=>fd,OpenEvent:()=>ud,ErrorCode:()=>rn,Event:()=>tr,MessageEvent:()=>ld});let r="";function i(a=""){let n=t,s="02",d=""+Date[n(1505)](),h=r||(r=f(a)),w=Math[n(351)]()[n(1328)](16)[n(1056)](-6);return e.tellO(e.tellO(s,d)+h,w)}function o(){let a=t;return e.tellO(e[a(1532)](1e4,Date[a(1505)]()),Math[a(1448)](e[a(1532)](1e4,Math[a(351)]())))}function c(a){let n=t,s={XTUGG:function(d,h,w){return e[j(1622)](d,h,w)}};return n(738)!==e.PDuaq?new _0x5e13bc(d=>{let h=n;s[h(1047)](_0x18daf2,d,this[h(519)+h(1410)+"e"](_0x4d3b77))}):(Array(8)[n(863)]("0")+e[n(1384)](parseInt,a,10).toString(2))[n(1056)](-8)}function l(a){let n=t;return(e[n(1583)](Array,4)[n(863)]("0")+e.YVafA(parseInt,a,2)[n(1328)](16))[n(1056)](-4)}function u(a){let n=t,s=a[n(1721)](/\./).map(w=>c(w)),d=[];return d[0]=e[n(1382)](l,e[n(989)](s[0],s[1])),d[1]=e[n(1756)](l,e[n(989)](s[2],s[3])),[e[n(1188)],n(682),e[n(1188)],n(682),e[n(1188)],e[n(1584)],d[0],d[1]][n(863)]("")}function f(a){let n=t;if(e[n(1111)](e[n(945)],n(1780))){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}/[n(1730)](a),d=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[n(1730)](a);return s?e[n(1331)](u,a):d?x(a):e[n(998)]}else{let s=this._endpointManager?.[n(596)+"ntEndpoint"]();this[n(437)](n(1120)+s),_0x10e390()}}function x(a){let n=t;if(e[n(1198)](e[n(588)],e.QlzqR)){let s="",d=[],h=0,w=0,S=!0,E=e[n(1188)];if(a.indexOf("::")>-1){let g=a[n(1721)]("::");for(let L=0;e[n(931)](L,g[n(1592)]);L++){let B=g[L];if(B.indexOf(":")>0){let W=B[n(1721)](":");S&&(h=W[n(1592)]),w+=W.length;for(let X=0;X<W.length;X++)if(e[n(1630)](4,W[X][n(1592)])){let re=E[n(1436)+"g"](0,e[n(1600)](4,W[X][n(1592)])),Te=re[n(1275)](W[X]);d[n(1140)](Te)}else d[n(1140)](W[X]);S=!1}else{if(e[n(846)](4,B[n(1592)])){let W=E[n(1436)+"g"](0,4-B[n(1592)]),X=W[n(1275)](B);d[n(1140)](X)}else d[n(1140)](B);S&&(h+=1),w+=1,S=!1}}let D="";for(let L=0;e.qCALE(L,8-w);L++)D=D[n(1275)](E);for(let L=0;L<d[n(1592)];L++)e[n(1271)](L,h)&&(s=s[n(1275)](D)),s=s[n(1275)](d[L]);return s}{let g=a.split(":");for(let D=0;e[n(768)](D,g.length);D++){let L=g[D];if(e[n(1659)](4,g[D][n(1592)])){let B=E.substring(0,4-g[D][n(1592)]),W=B[n(1275)](L);s=s[n(1275)](W)}else s=s[n(1275)](L)}return s}}else{let s=_0x20f1e2[n(1436)+"g"](0,4-_0xe1234[_0x21a5b9].length),d=s[n(1275)](_0x2f9aff[_0x5d2110]);_0x4eea72[n(1140)](d)}}function p(a,n){let s=t,d=a[s(1214)];e[s(846)](void 0,d)&&(pe(n,10),e[s(1615)](U,n,d));let h=a[s(747)];e[s(1630)](void 0,h)&&(e[s(1311)](pe,n,18),e[s(1311)](U,n,h))}function m(a){let n=t,s={};e:for(;!e[n(897)]($,a);){let d=e[n(1331)](xe,a);switch(e[n(728)](d,3)){case 0:break e;case 1:s[n(1214)]=e.QJyRA(C,a,xe(a));break;case 2:s[n(747)]=e.rNpFw(C,a,e[n(1756)](xe,a));break;default:e[n(463)](k,a,e[n(1437)](7,d))}}if(e.VFWIN(void 0,s[n(1214)]))throw new Error(e[n(807)]);if(e[n(1271)](void 0,s[n(747)]))throw new Error(n(444)+n(1695)+n(1561)+n(747));return s}function v(a){let n=t,s=e[n(727)](R);return _(a,s),e[n(1331)](M,s)}function _(a,n){let s=t;if(e.erODb(e[s(933)],e[s(624)])){let d=a[s(1820)];e[s(846)](void 0,d)&&(e[s(1426)](pe,n,8),gt(n,d));let h=a[s(1087)];e.JynbR(void 0,h)&&(pe(n,16),e[s(756)](gt,n,h));let w=a[s(1274)];w!==void 0&&(pe(n,24),e[s(1384)](gt,n,e[s(1756)](P,w)));let S=a.method;S!==void 0&&(e.sozit(pe,n,32),e[s(1311)](gt,n,e[s(584)](P,S)));let E=a[s(1433)];if(e[s(1819)](void 0,E))for(let Te of E)if(e[s(846)](e[s(1189)],s(361)))this._isMiniTT||this[s(870)+"X"]?this[s(1191)+s(1352)+s(923)]():this[s(1031)+"er"]&&this["_initGlo"+s(1807)+"Listener"]();else{e[s(1760)](pe,n,42);let on=e[s(727)](R);e[s(730)](p,Te,on),pe(n,on[s(498)]),e.MtWNZ(G,n,on),e[s(380)](O,on)}let g=a[s(819)+s(1621)];if(e[s(1059)](void 0,g))if(e.nFsvH(e[s(482)],e[s(482)])){let Te=e[s(1244)](e[s(1080)](e.Wurkp(e[s(1016)](e[s(553)](7,_0x25ab9c),18),e[s(1437)](63,_0x87446[_0x21ed3a++])<<12),e[s(843)](e[s(1363)](63,_0x5a92da[_0x68c30f++]),6)),e[s(370)](63,_0x49070f[_0xf44053++]))-65536;_0x5522c9+=_0x53617a[s(714)+"Code"](e[s(989)](55296,e.zdydU(Te,10))),_0x56bc50+=_0x240fd1[s(714)+s(859)](e[s(1179)](56320,e[s(443)](1023,Te)))}else e[s(1622)](pe,n,50),U(n,g);let D=a[s(518)+"ype"];e[s(1659)](void 0,D)&&(pe(n,58),e[s(804)](U,n,D));let L=a[s(888)];e[s(680)](void 0,L)&&(pe(n,66),e[s(1662)](pe,n,L[s(1592)]),e[s(1562)](oe,n,L));let B=a[s(810)];e[s(1630)](void 0,B)&&(pe(n,74),U(n,B));let W=a[s(602)+s(1182)];W!==void 0&&(e.BlSqA(pe,n,82),e[s(1479)](U,n,W));let X=a[s(1568)];X!==void 0&&(e[s(1590)](pe,n,90),e[s(629)](U,n,X));let re=a[s(374)+"e"];e[s(1059)](void 0,re)&&(e[s(756)](pe,n,96),e[s(629)](gt,n,e.fHvDW(P,re)))}else return new _0x2354af(_0x5ed2c5,{data:_0x4ffee1})}function b(a){let n=t;return e[n(897)](I,e[n(1382)](F,a))}function I(a){let n=t;if(e[n(1198)](e[n(1546)],e[n(1546)])){let s={};e:for(;!e[n(1092)]($,a);){let d=e[n(847)](xe,a);switch(d>>>3){case 0:break e;case 1:s[n(1820)]=e[n(1320)](It,a,!0);break;case 2:s[n(1087)]=e[n(1170)](It,a,!0);break;case 3:s[n(1274)]=e.fzylE(xe,a);break;case 4:s[n(1128)]=e.QBjhf(xe,a);break;case 5:{let h=e[n(688)](A,a);(s[n(1433)]||(s[n(1433)]=[])).push(e[n(584)](m,a)),a.limit=h;break}case 6:s[n(819)+n(1621)]=e[n(1320)](C,a,e[n(1566)](xe,a));break;case 7:s[n(518)+"ype"]=C(a,e.Hmaoj(xe,a));break;case 8:s[n(888)]=se(a,e[n(1331)](xe,a));break;case 9:s[n(810)]=e[n(629)](C,a,e[n(897)](xe,a));break;case 10:s[n(602)+n(1182)]=e[n(1184)](C,a,xe(a));break;case 11:s[n(1568)]=e.vyxVA(C,a,e.kXXIP(xe,a));break;case 12:s[n(374)+"e"]=xe(a);break;default:k(a,e[n(370)](7,d))}}if(e.cpiab(void 0,s[n(1820)]))throw new Error(e[n(1629)]);if(e.XAnVK(void 0,s.LogID))throw new Error(e[n(809)]);if(e.ZtlwE(void 0,s[n(1274)]))throw new Error(e.kVKcW);if(e.QlBgi(void 0,s[n(1128)]))throw new Error("Missing "+n(1695)+n(1561)+n(1128));return s}else _0x3efe72=_0x3049e2.charCodeAt(_0x34465c),_0x5a4be5<128?_0x2c3cb7+=1:e[n(768)](_0x175701,2048)?_0x1b11f4+=2:e[n(1198)](e[n(1363)](64512,_0x735cc2),55296)&&e[n(443)](64512,_0x486be4[n(895)+"At"](e[n(865)](_0x7242c,1)))===56320?(++_0x3881e2,_0x4bbb41+=4):_0x4b0af1+=3}function A(a){let n=t,s=e[n(1323)](xe,a),d=a[n(498)];return a.limit=e[n(1387)](a.offset,s),d}function k(a,n){let s=t;switch(n){case 0:for(;e.TpzlV(128,ee(a)););break;case 2:e[s(1562)](V,a,xe(a));break;case 5:e[s(1320)](V,a,4);break;case 1:e[s(1184)](V,a,8);break;default:throw new Error(e[s(1272)](e[s(999)],n))}}function P(a){let n=t;return e[n(636)]!==e[n(739)]?(a|=0,{low:a,high:e.XAkTP(a,31),unsigned:e.qPnZL(a,0)}):this[n(357)+n(720)]?.[n(596)+"ntEndpoi"+n(1073)+n(1004)]()||0}let y=[];function R(){let a=t,n=y[a(1398)]();return n?(n[a(1373)]=n[a(498)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){y.push(a)}function F(a){let n=t;if(e[n(1774)](e.wtDeu,e[n(1020)]))return{bytes:a,offset:0,limit:a[n(1592)]};{_0x170e6e[n(826)](_0x1e145f)||(_0x9f175b=_0x20a618[n(1553)+"er"](_0x5f429f));let s=this.high>>>16,d=e.yJuap(65535,this[n(1411)]),h=e.cFYXJ(this[n(421)],16),w=e[n(553)](65535,this.low),S=e[n(728)](_0x138505[n(1411)],16),E=e[n(443)](65535,_0x76dd81[n(1411)]),g=_0x577255.low>>>16,D=e[n(1363)](65535,_0x10fdf7[n(421)]),L=0,B=0,W=0,X=0;return X+=e[n(1272)](w,D),W+=e[n(728)](X,16),X&=65535,W+=h+g,B+=e[n(706)](W,16),W&=65535,B+=d+E,L+=B>>>16,B&=65535,L+=s+S,L&=65535,_0x219767.fromBits(e[n(1266)](e.UYPmh(W,16),X),e.bJxFv(L,16)|B,this.unsigned)}}function M(a){let n=t,s=a[n(981)],d=a.limit;return e.idkVN(s[n(1592)],d)?s:s[n(1014)](0,d)}function V(a,n){let s=t;if(e[s(913)](e[s(660)],e[s(660)])){if(e[s(1032)](a[s(1373)]+n,a[s(498)]))throw new Error(e.ARBlZ);a[s(1373)]+=n}else{let d=_0x582a9a(e[s(1018)],{message:this[s(1761)+s(1421)+s(1129)](_0x53f764)});this[s(1517)]("error",d);let h=e.Wpjdv(_0xd56cbc,"close",{reason:this[s(1761)+s(1421)+s(1129)](_0xc79e3f)});this.emit(e[s(1514)],h)}}function $(a){let n=t;return e[n(1115)](a[n(1373)],a[n(498)])}function ne(a,n){let s=t,d=a[s(981)],h=a[s(1373)],w=a.limit,S=h+n;if(e[s(1032)](S,d[s(1592)])){let E=new Uint8Array(e[s(1708)](2,S));E.set(d),a[s(981)]=E}return a.offset=S,e[s(841)](S,w)&&(a[s(498)]=S),h}function Y(a,n){let s=t,d=a[s(1373)];if(e[s(841)](e[s(989)](d,n),a[s(498)]))throw new Error(e[s(571)]);return a.offset+=n,d}function se(a,n){let s=t,d=e.vyxVA(Y,a,n);return a[s(981)][s(1014)](d,e.MRMiz(d,n))}function oe(a,n){let s=t,d=e[s(1053)](ne,a,n[s(1592)]);a.bytes[s(1796)](n,d)}function C(a,n){let s=t,d={vZXyV:function(D,L){return e[j(1444)](D,L)},OgYFX:function(D,L){return e[j(753)](D,L)},wHVNq:function(D,L){return e[j(487)](D,L)},szatB:function(D,L){return e[j(492)](D,L)},kFVuw:function(D,L){return e[j(1437)](D,L)},KeQFa:function(D,L){return e[j(728)](D,L)},GHset:function(D,L,B){return e[j(541)](D,L,B)}},h=e[s(1311)](Y,a,n),w=String[s(714)+s(859)],S=a[s(981)],E="\uFFFD",g="";for(let D=0;e.ndPhx(D,n);D++)if(e[s(1774)](e[s(579)],e[s(579)])){let L=this[s(1411)],B=this.low;return[255&B,d[s(1313)](d[s(601)](B,8),255),d[s(570)](B>>>16,255),d[s(1682)](B,24),d[s(1313)](255,L),d[s(1228)](d[s(601)](L,8),255),d.wHVNq(d[s(601)](L,16),255),d[s(1742)](L,24)]}else{let L=S[e[s(587)](D,h)],B,W,X,re;if(e[s(1065)](e.JoeLg(128,L),0))g+=e[s(1715)](w,L);else if(e[s(431)](e.kOILv(224,L),192))e[s(1670)](D+1,n)?g+=E:(B=S[e[s(665)](e.iRUIP(D,h),1)],e[s(1619)](192,B)!==128?g+=E:(re=e.DymLD(e[s(1135)](31&L,6),e[s(1437)](63,B)),e[s(383)](re,128)?g+=E:(g+=e[s(1801)](w,re),D++)));else if(e.KgzDV(e[s(1437)](240,L),224))e.CecHu(e[s(665)](D,2),n)?g+=E:(B=S[e[s(1716)](e[s(867)](D,h),1)],W=S[e.yLiBN(e[s(1778)](D,h),2)],e[s(850)](e[s(566)](e[s(1244)](B,e[s(615)](W,8)),49344),32896)?g+=E:(re=e[s(684)](e[s(1266)](e.AXIAy(e[s(1358)](15,L),12),e[s(615)](63&B,6)),e[s(1781)](63,W)),e.WZShw(re,2048)||re>=55296&&e.vibvS(re,57343)?g+=E:(g+=e[s(1756)](w,re),D+=2)));else if(e[s(1329)](e[s(1444)](248,L),240))if(e.Ubmqy(e.smrHn(D,3),n))g+=E;else if(e[s(1151)](s(567),s(567))){let Te=d.GHset(_0x24beb5,s(435),{message:_0x33e1ed[s(1193)],code:_0x42ad24.OPEN_ERROR,error:_0x4e0132});this[s(755)+s(733)+s(1071)](Te)}else B=S[e[s(879)](e[s(372)](D,h),1)],W=S[e[s(890)](e[s(989)](D,h),2)],X=S[e[s(1551)](D,h)+3],e[s(1151)](e[s(1437)](e[s(1655)](B|W<<8,e[s(521)](X,16)),12632256),8421504)?g+=E:(re=e[s(1604)](e.MGtgp(e[s(684)](e[s(1135)](e.eePuJ(7,L),18),e[s(1178)](e.SxMkd(63,B),12)),e.Gxiof(e.kOILv(63,W),6)),e[s(1444)](63,X)),re<65536||e[s(889)](re,1114111)?g+=E:(re-=65536,g+=e[s(1322)](w,e[s(587)](e[s(1370)](re,10),55296),e[s(867)](1023&re,56320)),D+=3));else g+=E}return g}function U(a,n){let s=t,d={PHWrq:function(g,D,L,B){return g(D,L,B)}},h=n.length,w=0;for(let g=0;e.RMWxp(g,h);g++){let D=n[s(895)+"At"](g);e.EmmsR(D,55296)&&e[s(1710)](D,56319)&&e[s(1412)](e.jQBNg(g,1),h)&&(D=e[s(1600)](e[s(722)](D,10)+n[s(895)+"At"](++g),56613888)),w+=e[s(719)](D,128)?1:D<2048?2:D<65536?3:4}e.BrLRj(pe,a,w);let S=e.pnzAT(ne,a,w),E=a[s(981)];for(let g=0;g<h;g++){let D=n.charCodeAt(g);if(e[s(352)](D,55296)&&e[s(1710)](D,56319)&&e.exmAb(g,1)<h&&(D=e[s(1287)](e[s(1468)](D<<10,n.charCodeAt(++g)),56613888)),e[s(1452)](D,128))E[S++]=D;else{if(e[s(1295)](D,2048))E[S++]=e[s(412)](D>>6,31)|192;else if(e[s(1524)]!==e[s(1524)]){let L=255&_0x62bcf6;d[s(620)](_0x3f6b51,L,_0x4c9e60,_0x443981+_0x335ff2),_0x370bd5>>>=8,_0x5ed7d1--}else e.WZShw(D,65536)?E[S++]=e[s(1680)](D,12)&15|224:(E[S++]=e[s(1647)](e.RiGfH(D>>18,7),240),E[S++]=e[s(1647)](D>>12&63,128)),E[S++]=e.Wurkp(e[s(1363)](e[s(1194)](D,6),63),128);E[S++]=e[s(1604)](e[s(566)](63,D),128)}}}function G(a,n){let s=t,d=e[s(715)](ne,a,n.limit),h=a[s(981)],w=n[s(981)];for(let S=0,E=n[s(498)];e[s(768)](S,E);S++)h[S+d]=w[S]}function ee(a){let n=t;return a.bytes[e[n(696)](Y,a,1)]}function Ve(a,n){let s=t,d=e[s(1426)](ne,a,1);a.bytes[d]=n}function xe(a){let n=t,s=0,d=0,h;do h=e.qtEqU(ee,a),e[n(931)](s,32)&&(d|=e[n(527)](127&h,s)),s+=7;while(e[n(1202)](128,h));return d}function pe(a,n){let s=t;for(n>>>=0;e.guVJC(n,128);)e[s(1591)](Ve,a,e[s(1582)](127&n,128)),n>>>=7;e.ayKNC(Ve,a,n)}function It(a,n){let s=t,d={voAyD:function(h,w,S){return e[j(765)](h,w,S)},XDUDE:function(h,w,S){return e[j(1614)](h,w,S)},XurcO:function(h,w){return e[j(1801)](h,w)}};if(e.wwAHC(e[s(694)],"mWnbo")){let h=0,w=0,S=0,E;if(E=e[s(1400)](ee,a),h=e[s(370)](127,E),128&E&&(E=ee(a),h|=e[s(1177)](127&E,7),e.rrBFL(128,E)&&(E=ee(a),h|=e[s(615)](127&E,14),e.BcfXd(128,E)))){if(e[s(1668)](e.edUXc,e.edUXc))return this[s(1808)+"ndpointTriesCount"]++,this[s(596)+s(990)+"nt"]();E=ee(a),h|=e[s(1177)](e[s(1418)](127,E),21),e[s(1576)](128,E)&&(E=e[s(845)](ee,a),w=e[s(1358)](127,E),e[s(1704)](128,E)&&(E=e[s(1238)](ee,a),w|=(127&E)<<7,128&E&&(E=e[s(1245)](ee,a),w|=e.rOakf(127&E,14),e[s(1704)](128,E)&&(E=e[s(1176)](ee,a),w|=e[s(459)](127,E)<<21,e[s(553)](128,E)&&(E=ee(a),S=127&E,128&E&&(E=e.EoBNl(ee,a),S|=e[s(542)](e[s(1641)](127,E),7)))))))}return{low:e.Wurkp(h,e[s(556)](w,28)),high:e[s(502)](w>>>4,S<<24),unsigned:n}}else xYqHER[s(761)](_0x44adfa,_0x139ac4,96),xYqHER[s(1289)](_0x499b53,_0x5ccc78,xYqHER[s(1192)](_0x5902e8,_0x3cb616))}function gt(a,n){let s=t,d=e[s(492)](n[s(421)],0),h=e[s(473)](e[s(1664)](e.ZAJji(n[s(421)],28),n[s(1411)]<<4),0),w=n[s(1411)]>>>24,S=e[s(1065)](0,w)?e[s(468)](0,h)?e[s(729)](d,16384)?d<128?1:2:e[s(1118)](d,2097152)?3:4:e.WZShw(h,16384)?e[s(773)](h,128)?5:6:e[s(1631)](h,2097152)?7:8:w<128?9:10,E=e[s(1364)](ne,a,S),g=a[s(981)];switch(S){case 10:g[e.ctRcM(E,9)]=e.lomVH(e[s(1298)](w,7),1);case 9:g[E+8]=e[s(1151)](9,S)?e[s(1243)](128,w):e[s(370)](127,w);case 8:g[e[s(1079)](E,7)]=e[s(793)](8,S)?e.lwdvU(e[s(492)](h,21),128):e[s(443)](e[s(1798)](h,21),127);case 7:g[e[s(1556)](E,6)]=e[s(1659)](7,S)?e[s(684)](e[s(1131)](h,14),128):e[s(825)](h,14)&127;case 6:g[e.gPNsj(E,5)]=e[s(1691)](6,S)?e[s(1534)](h>>>7,128):e[s(832)](e[s(1298)](h,7),127);case 5:g[E+4]=S!==5?e[s(1647)](128,h):e[s(1444)](127,h);case 4:g[E+3]=e[s(1819)](4,S)?e[s(1298)](d,21)|128:e[s(1576)](e[s(1114)](d,21),127);case 3:g[e.xTmxH(E,2)]=e[s(1817)](3,S)?e.CExps(e[s(728)](d,14),128):e[s(1523)](e[s(753)](d,14),127);case 2:g[e.tellO(E,1)]=e.syZwi(2,S)?e[s(1582)](d>>>7,128):e[s(574)](d,7)&127;case 1:g[E]=e.OApGu(1,S)?e[s(684)](128,d):e.GSfCz(127,d)}}function tn(a){let n=t;if(e.lgVPU!==e.nfObE)return e[n(1077)](b,a);this["_initPro"+n(1471)]=null}function Ft(a){let n=t;return e[n(1147)](e[n(713)],n(1145))?_0x46b90b.resolve():v(a)}let nn=65536,Yr=e[t(346)],we=nn*nn,Ae=we*we,er=e.dupvD(Ae,2),Oe=String[t(1766)+"e"][t(895)+"At"];class he{constructor(n,s,d){let h=t;this[h(826)]=!0,this[h(421)]=e[h(606)](0,n),this[h(1411)]=e[h(1664)](0,s),this[h(1345)]=!!d}static[t(826)](n){return n&&n.isLong===!0}static fromBits(n,s,d){return new he(n,s,d)}static[t(1751)+"s"](n,s,d){return d?he[t(1751)+"sLE"](n,s):he.fromBytesBE(n,s)}static[t(1751)+t(1711)](n,s){let d=t;return new he(e[d(1241)](n[0]|e.HBCWO(n[1],8)|n[2]<<16,e.vRyln(n[3],24)),e.ItOZY(n[4],n[5]<<8)|e.vidRT(n[6],16)|e[d(615)](n[7],24),s)}static["fromByte"+t(1635)](n,s){let d=t;return new he(e[d(1392)](e[d(606)](e[d(1392)](n[4]<<24,e.mTMUV(n[5],16)),e.noKjb(n[6],8)),n[7]),e.zAcWO(e.cvMgH(e[d(969)](n[0],24)|n[1]<<16,e.noKjb(n[2],8)),n[3]),s)}static[t(698)](n){let s=t;return e[s(549)](n,Yr)?sd:new he(e[s(606)](e[s(1655)](e.CwNwo(Oe[s(1502)](n,0),e[s(671)](Oe[s(1502)](n,1),8)),e[s(401)](Oe[s(1502)](n,2),16)),e[s(788)](Oe.call(n,3),24))>>>0,e[s(1143)](e.bYxFd(Oe[s(1502)](n,4)|Oe[s(1502)](n,5)<<8,e.XizBt(Oe[s(1502)](n,6),16))|e[s(843)](Oe[s(1502)](n,7),24),0),!0)}[t(1380)](){let n=t;return String[n(714)+n(859)](255&this[n(421)],e[n(817)](e[n(1060)](this[n(421)],8),255),e[n(1522)](e.LJCjq(this.low,16),255),e[n(574)](this.low,24),255&this[n(1411)],e[n(825)](this[n(1411)],8)&255,e[n(668)](e.HyZqb(this[n(1411)],16),255),e[n(706)](this[n(1411)],24))}static[t(1553)+"er"](n,s=!0){let d=t;if(e.bMXuA(isNaN,n))return s?Hp:sd;if(s){if(e.EmmsR(n,Ae))return qp}else{if(e[d(1283)](n,-er))return jp;if(e[d(503)](n,1)>=er)return Gp}return he[d(1371)](e.MGtgp(n%we,0),e[d(1368)](n/we,0),s)}[t(417)](){let n=t;return this[n(1345)]?e[n(833)](e[n(1482)](this[n(1411)],0)*we,e[n(1050)](this[n(421)],0)):e[n(503)](e.BvtsB(this.high,we),e[n(1573)](this[n(421)],0))}[t(1385)](){let n=t;if(e[n(1237)]("IbrqW",e.xapTC))this[n(578)+n(1185)](),this[n(1517)]("ping_onc"+n(924)+"s",e.eLSIV),this[n(1186)+n(1288)+"Id"]=e[n(463)](_0x1fd3c1,this._ping[n(1425)](this),_0xa7ce9);else return this[n(1411)]===0&&e[n(1458)](0,this[n(421)])}add(n){let s=t,d={kFmHM:function(h,w){return h>>>w},fNseY:function(h,w){return e.HaITn(h,w)},AxkVx:function(h,w){return e[j(1681)](h,w)},NDIoN:function(h,w){return e[j(1099)](h,w)},MPOCi:function(h,w){return e[j(728)](h,w)}};if(e[s(1059)](e.hEWNU,e.oRBZN)){he[s(826)](n)||(n=he[s(1553)+"er"](n));let h=e.NyYrt(this[s(1411)],16),w=65535&this[s(1411)],S=e[s(1482)](this[s(421)],16),E=e.hNRGN(65535,this[s(421)]),g=e[s(1143)](n[s(1411)],16),D=e[s(1528)](65535,n[s(1411)]),L=e[s(1078)](n[s(421)],16),B=e.vglom(65535,n[s(421)]),W=0,X=0,re=0,Te=0;return Te+=e[s(1718)](E,B),re+=Te>>>16,Te&=65535,re+=S+L,X+=e[s(1560)](re,16),re&=65535,X+=e[s(676)](w,D),W+=e[s(1143)](X,16),X&=65535,W+=e.KSWWI(h,g),W&=65535,he[s(1371)](e[s(1051)](e[s(1665)](re,16),Te),e[s(1789)](W,16)|X,this[s(1345)])}else{let h=this[s(1411)],w=this[s(421)];return[d[s(991)](h,24),d[s(1402)](d.kFmHM(h,16),255),d[s(1402)](d[s(991)](h,8),255),d.fNseY(255,h),d[s(1474)](w,24),d.NDIoN(d[s(563)](w,16),255),d[s(802)](d[s(1474)](w,8),255),d[s(802)](255,w)]}}[t(1446)](n){let s=t;return he[s(826)](n)||(n=he.fromNumber(n)),e[s(1263)](this[s(1345)],n[s(1345)])&&e.HWYqK(this[s(1411)],31)===1&&e.KDWEz(n[s(1411)],31)===1?!1:e[s(1089)](this.high,n[s(1411)])&&this.low===n[s(421)]}addOne(){let n=t;return e[n(1093)](-1,this[n(421)])&&e[n(1503)](-1,this[n(1411)])?he[n(1371)](0,0,this[n(1345)]):e[n(1271)](-1,this[n(421)])?he.fromBits(0,e[n(1778)](this[n(1411)],1),this[n(1345)]):he[n(1371)](e[n(1387)](this[n(421)],1),this[n(1411)],this[n(1345)])}[t(1542)](n){let s=t;if(e.wyrbf(e[s(1520)],e[s(1321)]))e[s(1653)](_0x11a7a5,_0x24d9d1,24),e[s(1116)](_0x9cd898,_0x22f0ad,e[s(380)](_0x3a65a5,_0xd8e093));else return n?this[s(1736)+"E"]():this[s(875)+"E"]()}[t(1736)+"E"](){let n=t,s=this[n(1411)],d=this[n(421)];return[e[n(1444)](255,d),e.kCtQH(d>>>8,255),e[n(668)](e.fOuhn(d,16),255),e[n(728)](d,24),e.jxZow(255,s),s>>>8&255,e[n(1201)](e[n(1570)](s,16),255),s>>>24]}toBytesBE(){let n=t,s=this.high,d=this[n(421)];return[e.xkVZs(s,24),e[n(449)](e[n(1681)](s,16),255),e[n(672)](s,8)&255,255&s,e[n(1482)](d,24),e.HyZqb(d,16)&255,e[n(459)](e[n(695)](d,8),255),e[n(789)](255,d)]}}let sd=new he(0,0,!1),Hp=new he(0,0,!0),Gp=he.fromBits(-1,2147483647,!1),qp=he[t(1371)](-1,-1,!0),jp=he.fromBits(0,-2147483648,!1);var rn=(function(a){let n=t;if(e[n(1611)]!==e[n(1525)]){let s=e[n(899)][n(1721)]("|"),d=0;for(;;){switch(s[d++]){case"0":a[a[e[n(1786)]]=5004]=n(904)+n(677);continue;case"1":a[a[e[n(801)]]=5003]=e[n(801)];continue;case"2":a[a[e.wMMPd]=5002]=n(1652)+n(792);continue;case"3":a[a[e[n(936)]]=5001]=e[n(936)];continue;case"4":a[a[e.VBWvv]=5005]=n(1580)+"OR";continue;case"5":return a}break}}else return this._qosDB[n(1346)]()})({});class tr{constructor(n){let s=t;this[s(457)]=n,this.target=null}}class od extends tr{constructor(n,s){let d=t;super(n),this[d(1193)]=s&&s[d(1193)]||null}}class ad extends tr{constructor(n,s){let d=t,h=(d(1234)+d(1669))[d(1721)]("|"),w=0;for(;;){switch(h[w++]){case"0":super(n);continue;case"1":this[d(1002)]=s&&s[d(1002)]||0;continue;case"2":this[d(435)]=s&&s[d(435)]||null;continue;case"3":this[d(1262)]=s&&s[d(1262)]||0;continue;case"4":this[d(1303)]=s&&s[d(1303)]||"";continue;case"5":this.message=s&&s[d(1193)]||"";continue;case"6":this[d(1273)]=s&&s[d(1273)]||5001;continue}break}}}class cd extends tr{constructor(n,s){let d=t,h=(d(1361)+"2")[d(1721)]("|"),w=0;for(;;){switch(h[w++]){case"0":super(n);continue;case"1":this[d(640)]=s&&s[d(640)]||"";continue;case"2":this["willReco"+d(813)]=s&&s[d(1117)+d(813)]||!1;continue;case"3":this[d(1793)]=s&&s.wasClean||!1;continue;case"4":this[d(1273)]=s&&s[d(1273)]||0;continue}break}}}class ld extends tr{constructor(n,s){let d=t;super(n),this[d(1013)]=s&&s[d(1013)]||null}}class dd extends ld{constructor(n,s){let d=t;super(n),this[d(1013)]=s&&s.data||null,this[d(1193)]=s&&s[d(1193)]||null}}class ud extends tr{constructor(n,s){let d=t;super(n),this[d(1013)]=s&&s[d(1013)]||null}}function ct(a,{message:n,code:s,error:d}){return new ad(a,{message:n,code:s,error:d})}function mt(a,{code:n,reason:s,wasClean:d,willReconnect:h}){return new cd(a,{code:n,reason:s,wasClean:d,willReconnect:h})}function fd(a,{data:n,message:s}){return new dd(a,{data:n,message:s})}function hd(a,{data:n}){return new ud(a,{data:n})}function wa(a,{message:n}){return new od(a,{message:n})}class xd{constructor(n,s){let d=t;this.endpoints=n,this[d(946)+"es"]=s,this[d(428)+d(1593)]=0,this[d(1808)+"ndpointT"+d(1466)+"t"]=0}[t(1167)+t(1814)+t(646)](){let n=t;if(e[n(1440)](e[n(1588)],e.gaufU))this["currentI"+n(1593)]=0,this[n(1808)+n(416)+n(1466)+"t"]=0;else return _0x10d216?_0x19fb57.fromBytesLE(_0x2f788e,_0x1dfc1e):_0x3c4821[n(1751)+n(1635)](_0x45bb3b,_0x31a70e)}[t(1199)+"es"](){let n=t;this[n(1808)+n(416)+n(1466)+"t"]=0}["getCurre"+t(990)+"nt"](){let n=t;return this.endpoints[this[n(428)+"ndex"]]}[t(596)+"ntEndpoi"+t(1073)+t(1004)](){let n=t;return this[n(1808)+n(416)+"riesCount"]}[t(1284)+t(1656)+"es"](){let n=t;return!!(this[n(428)+n(1593)]>=this.endpoints[n(1592)]||e[n(1381)](this["currentI"+n(1593)],this[n(1052)+"s"].length-1)&&e[n(1824)](this[n(1808)+"ndpointTriesCount"],this.maxRetries))}[t(799)+"rentEndp"+t(1251)+t(669)+"tries"](){let n=t;return e[n(1725)](this[n(428)+"ndex"],this[n(1052)+"s"][n(1592)])?!0:e[n(1339)](this["currentE"+n(416)+n(1466)+"t"],this[n(946)+"es"])}[t(732)+t(1469)+t(1334)+t(1589)+t(631)](){let n=t;if(e[n(1646)]!==e[n(1646)])this["_binaryT"+n(980)]=_0x19c413,this._ws&&(this[n(512)][n(1084)+"pe"]=_0x42eb1b);else return this[n(1808)+n(416)+"riesCount"]=1,this[n(428)+n(1593)]++,this[n(1052)+"s"][this[n(428)+"ndex"]]}[t(596)+"ntEndpointAndUpd"+t(1694)](){let n=t;return this["currentE"+n(416)+n(1466)+"t"]++,this.getCurrentEndpoint()}}let nr=(e[t(545)](t(1105)+"d",typeof globalThis)&&t(1782)===globalThis[t(1828)+"tor"].name||e.pHPuR(e[t(834)],typeof window)&&e[t(1729)](e[t(1499)],window["construc"+t(1231)][t(932)]))&&e[t(545)](e[t(834)],typeof document),Cn=e[t(912)](t(1105)+"d",typeof globalThis)&&(e[t(1374)]===globalThis["construc"+t(1231)][t(932)]||e.MabHS(t(1316)+t(1501)+t(947)+"pe",globalThis[t(1828)+t(1231)].name))&&e[t(543)](t(1105)+"d",typeof tt),Xr=(e[t(834)]!=typeof globalThis&&e[t(1211)](e[t(1374)],globalThis[t(1828)+"tor"][t(932)])||e[t(834)]==typeof globalThis||e[t(1006)](e[t(834)],typeof globalThis)&&!!globalThis["WeixinJS"+t(791)])&&e[t(1396)](e[t(834)],typeof wx),Qr=e[t(778)](e[t(834)],typeof globalThis)&&(e.bxxdy(t(1316)+"dWorkerG"+t(947)+"pe",globalThis[t(1828)+"tor"][t(932)])||t(878)+t(535)+t(1064)===globalThis[t(1828)+t(1231)][t(932)]||e[t(1475)](e[t(500)],globalThis[t(1828)+t(1231)].name))&&e[t(1006)](e[t(834)],typeof self),Wp=e[t(834)]!=typeof globalThis&&e[t(1110)](e.EPITm,globalThis["construc"+t(1231)].name)&&e.NuXnc(e[t(834)],typeof global)&&e[t(1374)]===global[t(1828)+t(1231)][t(932)]&&e[t(834)]!=typeof process&&!!process[t(1417)];class _a{constructor(){this._listeners={}}emit(n,...s){let d=t,h=this._listeners[n];if(h)h[d(1056)]().forEach(w=>w.fn[d(1738)](w[d(1627)],s));else if(e[d(1727)](e[d(1018)],n)&&!this[d(1461)]){let w=s.length&&s[0];if(w instanceof Error)throw w;let S=new Error(e[d(1209)](e[d(422)],w?e[d(1158)](e[d(440)](" (",w[d(1193)]),")"):""));throw S[d(745)]=w,w}return this}[t(349)](n,s){let d=t;if(e[d(1211)](void 0,n))this._listeners={};else if(s===void 0)this[d(1821)+"rs"][n]=null;else{let h=this._listeners[n];if(h)for(let w=0;e[d(1295)](w,h[d(1592)]);)e.KObYF(h[w].fn,s)?h[d(1030)](w,1):++w}return this}on(n,s,d){let h=t;return(this[h(1821)+"rs"][n]||(this[h(1821)+"rs"][n]=[])).push({fn:s,ctx:d||this}),this}}class Kp extends _a{[t(1761)+t(1421)+t(1129)](n){let s=t;return n.errMsg||n.errNo?(s(1617)+" "+(n[s(686)]||"")+" code: "+(n[s(1001)]||""))[s(1148)]():JSON.stringify(n)}constructor(n,s,d){let h=t;super(),this[h(911)]=null,Xr&&wx["connectS"+h(1818)]&&(this[h(911)]=wx[h(537)+"ocket"]({url:n,protocols:s,header:d,fail:this[h(920)+h(886)+h(1763)][h(1425)](this),success:this[h(920)+h(1042)+h(1293)+h(469)][h(1425)](this)})),Cn&&tt[h(537)+h(1818)]&&(this[h(911)]=tt["connectS"+h(1818)]({url:n,protocols:s,header:d,fail:this["_createS"+h(886)+h(1763)][h(1425)](this),success:this[h(920)+h(1042)+h(1293)+"ler"][h(1425)](this)}))}[t(920)+t(1042)+t(1293)+t(469)](){let n=t,s={ikWPV:function(d,h,w){return e[j(821)](d,h,w)},gkLLZ:function(d,h){return d!==h},UImdp:e.pIbKo};e.VFWIN(n(407),e[n(583)])?this["flushExp"+n(1314)]():Promise[n(1549)]()[n(1003)](()=>{let d=n;s[d(959)]("UhQaV",s[d(759)])?this[d(499)+d(1827)]():this[d(1517)](d(1429),s[d(725)](_0x14faa9,"open",{..._0x513182,data:_0x524ebb[d(686)]||""}))})}[t(920)+t(886)+t(1763)](n){let s=t,d={KjGBW:function(h,w,S){return e[j(1336)](h,w,S)},IzGUu:e[s(1018)],HWxMc:e[s(1514)]};Promise[s(1549)]()[s(1003)](()=>{let h=s,w=d[h(963)](ct,h(435),{message:this[h(1761)+"rrorMess"+h(1129)](n)});this[h(1517)](d[h(1609)],w);let S=mt(d[h(472)],{reason:this[h(1761)+"rrorMess"+h(1129)](n)});this[h(1517)](h(532),S)})}[t(499)+"steners"](){let n=t,s={eEMTB:e[n(650)],fVaGc:function(d,h){return e[n(639)](d,h)},MvXaQ:e[n(903)],iGwAX:n(1193),lmcKA:function(d,h,w){return e[n(1661)](d,h,w)}};this[n(911)][n(1100)](d=>{let h=n;this.emit(s.eEMTB,hd(s[h(658)],{...d,data:d[h(686)]||""}))}),this[n(911)][n(1777)](d=>{let h=n;this.emit(e[h(1514)],e.ECdeP(mt,h(532),{...d}))}),this._socket[n(369)+"e"](d=>{let h=n;if(s[h(977)](s.MvXaQ,s.MvXaQ))this[h(1517)](s.iGwAX,s[h(1342)](fd,h(1193),{...d}));else return this[h(1355)]?.get(_0x209f59)}),this._socket.onError(d=>{let h=n;this.emit(e[h(1018)],ct(e[h(1018)],{...d,message:d[h(686)]||""}))})}[t(1223)](n){let s=t,d={MoHnD:e.wMzTx,BErNz:function(h,w,S){return e[j(1322)](h,w,S)}};if(e.cDDwv(n,Uint8Array)){let h=n.buffer[s(1056)](n.byteOffset,e[s(1551)](n[s(1578)+"th"],n.byteOffset));this[s(911)]&&this[s(911)][s(1223)]({data:h,fail:w=>{let S=s;this[S(1517)](e[S(1018)],e[S(1639)](ct,e[S(1018)],{message:this["_formatErrorMess"+S(1129)](w)}))}})}else this[s(911)]&&this[s(911)][s(1223)]({data:n,fail:h=>{let w=s;this[w(1517)](d[w(1687)],d[w(910)](ct,d[w(1687)],{message:this[w(1761)+w(1421)+w(1129)](h)}))}})}[t(532)](n,s){let d=t,h={crYHZ:function(w,S){return e[j(1704)](w,S)}};e[d(1181)](e[d(384)],e[d(384)])?this[d(911)]&&this[d(911)][d(532)]({code:n,reason:s}):(_0x47e70e(_0x18f79f,zfUOBP[d(367)](127,_0x456c3c)|128),_0x2b68e8>>>=7)}[t(1227)+t(1811)](n,s){this.on(n,s)}[t(1435)+t(776)+"ner"](n,s){this[t(349)](n,s)}get[t(958)+"te"](){let n=t;return this[n(911)][n(958)+"te"]}get[t(1084)+"pe"](){let n=t;return this[n(911)][n(1084)+"pe"]}set[t(1084)+"pe"](n){}get url(){let n=t;return this[n(911)][n(1347)]}get protocol(){let n=t;if(e.oEoFh(e[n(1697)],e[n(1697)]))return this[n(911)][n(1317)];_0xabcdaf[n(1549)]().then(()=>{this["_addWsLi"+n(1827)]()})}get[t(1282)+"ns"](){let n=t;return this[n(911)][n(1282)+"ns"]}get[t(954)+t(1367)](){return 0}}function $p(a,n){let s=t;if(n)return new n(a[s(1347)],a[s(1317)]);if(e[s(1785)](Xr,Cn))return new Kp(a[s(1347)],a.protocol,a[s(1433)]);if(e[s(1785)](nr,Qr)&&e[s(834)]!=typeof WebSocket&&WebSocket)return new WebSocket(a[s(1347)],a[s(1317)+"s"])}function Vp(a){let n=t,s={retJC:function(d,h){return e[j(768)](d,h)},jzvtf:function(d,h){return e[j(1060)](d,h)},ClmXz:function(d,h){return e[j(609)](d,h)}};if(e[n(1630)](n(1175),n(1175))){let d=0,h=_0x240642,w=_0x19abab+4;for(;s.retJC(h,w);){let{value:S,offset:E}=_0x33c8c7(_0x39284a,h);h=E,d=s[n(883)](s[n(1069)](d,8),0),d+=S}return{value:d,offset:w}}else return!!(a||Xr&&wx[n(537)+n(1818)]||Cn&&tt["connectS"+n(1818)]||e[n(1785)](nr,Qr)&&e[n(912)](e.yReJw,typeof WebSocket)&&WebSocket)}function pd(a,n,s){let d=t,h={sllzL:function(E,g){return e[j(1419)](E,g)},jdezT:e[d(901)],UNTMI:function(E,g){return E===g},tuRAY:function(E,g){return e.LhXHW(E,g)}},w=-1;async function S(E){let g=d;return h[g(1281)](E,w)?Promise[g(798)](new Error(h[g(462)])):(w=E,h.UNTMI(E,s[g(1592)])?Promise[g(1549)]():s[E][g(1425)](a)(n,S.bind(null,h[g(644)](E,1))))}e[d(1400)](S,0)}function gd(a){let n=t;if(e[n(1691)](n(1341),e[n(740)])){let s=0,d=0;for(let h=0;h<a[n(1592)];++h)d=a.charCodeAt(h),e[n(729)](d,128)?s+=1:e[n(1452)](d,2048)?s+=2:e[n(1397)](e.rrBFL(64512,d),55296)&&e[n(1548)](64512&a.charCodeAt(e[n(1112)](h,1)),56320)?(++h,s+=4):s+=3;return s}else _0x4ebf27.o=(s,d)=>_0x3fce0f[n(1766)+"e"][n(593)+n(1649)][n(1502)](s,d)}function md(a,n,s){let d=t;if(e[d(1526)](s-n,1))return"";let h="";for(let w=n;e[d(931)](w,s);){let S=a[w++];if(e[d(1710)](S,127))h+=String["fromChar"+d(859)](S);else if(e[d(496)](S,192)&&e.Twbvk(S,224))h+=String[d(714)+d(859)](e[d(657)](e[d(1768)](e[d(1498)](31,S),6),e[d(443)](63,a[w++])));else if(S>=224&&e.HreFb(S,240))h+=String[d(714)+"Code"](e.eiUhG(e.ftKDR(15,S),12)|(63&a[w++])<<6|e[d(817)](63,a[w++]));else if(S>=240){let E=e[d(1109)](e[d(820)](e[d(922)](e[d(952)](7,S),18)|e[d(671)](e.edGuz(63,a[w++]),12),e[d(1177)](63&a[w++],6))|e[d(789)](63,a[w++]),65536);h+=String[d(714)+d(859)](e[d(440)](55296,e[d(1455)](E,10))),h+=String[d(714)+d(859)](e[d(665)](56320,e[d(626)](1023,E)))}}return h}function ya(a,n,s){let d=t,h=s,w,S;for(let E=0;e[d(1452)](E,a[d(1592)]);++E)if(e[d(1247)]!==e.WnFdC)if(w=a[d(895)+"At"](E),e[d(931)](w,128))n[s++]=w;else if(w<2048)n[s++]=e[d(1628)](w,6)|192,n[s++]=e[d(689)](e.ylaSN(63,w),128);else if(e[d(1146)](e.ytYTd(64512,w),55296)&&e.AtFVf(64512&(S=a[d(895)+"At"](E+1)),56320)){let g=e.vDIuB[d(1721)]("|"),D=0;for(;;){switch(g[D++]){case"0":n[s++]=e[d(1266)](e[d(1781)](w>>6,63),128);continue;case"1":n[s++]=e[d(1664)](e.zdydU(w,18),240);continue;case"2":++E;continue;case"3":n[s++]=e[d(1485)](e.edGuz(e[d(1455)](w,12),63),128);continue;case"4":w=e.YJrBF(65536,e[d(1177)](1023&w,10))+e[d(736)](1023,S);continue;case"5":n[s++]=63&w|128;continue}break}}else n[s++]=e[d(1392)](e[d(582)](w,12),224),n[s++]=e[d(1243)](e.fMcnf(e.cRMAu(w,6),63),128),n[s++]=e[d(955)](e.HZCrT(63,w),128);else return;return e[d(530)](s,h)}async function wd(a){let n=t;if(e.KgzDV(e[n(1297)],typeof a)){let s=new Uint8Array(gd(a));return ya(a,s,0),s}return e[n(1236)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[n(858)],a.byteOffset,a[n(1578)+"th"])}function Jp(a){let n=t;try{if(e.vCQAw(e[n(785)],e[n(610)]))this[n(1307)]=_0x2bf05c,this[n(908)]=_0xccba6f,this[n(1355)]=_0x5f2fd9;else return e.xovxq(e[n(1297)],typeof a)&&(a instanceof ArrayBuffer||a.buffer&&e[n(1383)](a[n(858)],ArrayBuffer))||e[n(1396)](e.rJySz,typeof a)?"":(JSON[n(1462)](a),e[n(1399)])}catch{return e[n(1329)]("string",typeof a)?e[n(851)]:""}}let Zp=(a,n)=>{let s=t;switch(a){case s(1531):case e[s(536)]:return{[s(944)+a]:1,"x-tt-env":n};default:return{}}};class Yp{constructor(n){let s=t;this[s(475)+s(1004)]=n,this[s(655)]=0}[t(425)](){this.count++}[t(1284)+"chMaxCount"](){let n=t;return e[n(1115)](this[n(655)],this[n(475)+n(1004)])}[t(647)+"nter"](n=0){let s=t,d={Xvzhe:e[s(984)]};if(e.piADj(e[s(454)],e[s(454)]))this[s(475)+"ount"]=n,this[s(655)]=0;else return _0x3a4e21||(_0x233d8f=_0x617ff6[s(1549)]().then(_0x41d471[s(1425)](_0x367806,d.Xvzhe))),_0x2b348b}}async function Xp(a){let n=t,s={BsDwa:function(d,h){return e[j(1082)](d,h)},rpxZT:e[n(673)],WNOcV:e.PlmCT,zvHfp:n(533)};return new Promise(d=>{let h=n;if(!nr)return d(s[h(621)]);try{let w=document[h(1229)+h(392)](h(1640));window["frontier"+h(438)]=S=>{let E=h;document[E(551)].removeChild(w),window[E(1608)+E(438)]=void 0,s[E(1555)](d,S&&S[E(983)]||s.rpxZT)},w[h(457)]=s.WNOcV,w[h(978)]=a[h(484)](/^ws/,s.zvHfp)+(h(1457)+h(1472)+h(424)+"P");try{document[h(551)]["appendCh"+h(366)](w)}catch{document[h(551)][h(513)+h(366)](w)}}catch{window[h(1608)+h(438)]=void 0,d(s.rpxZT)}})}function sn(a,n,s){let d=t;if(d(388)===d(388))return!!a?.find(h=>h[d(1214)]===n&&h[d(747)]===s);{let h=_0x2846ab(d(1068)+"t",{message:e[d(1473)]});this[d(1481)+d(996)]&&this["onStartR"+d(996)](h)}}function rr(a,n){let s=t;return a?.[s(575)](d=>d[s(1214)]===n)?.[s(747)]}let ba=null;async function Qp(){let a=t;return ba||(ba=Promise[a(1549)]()[a(1003)](Mt[a(1425)](Mt,e[a(984)]))),ba}class eg extends _a{constructor(n,s){let d=t;super(),this._dbName=n,this._keyPath=s,this._qosDB=void 0,this[d(942)+"mise"]=null}async[t(941)](){await this[t(935)]()}async[t(935)](){let n=t,s={Qzinw:function(d){return d()}};if(!this._qosDB){if(this["_initPro"+n(1471)])return this[n(942)+n(1471)];try{let d=this[n(495)],h=this[n(1701)];this["_initPro"+n(1471)]=(async()=>{let w=n,{openDB:S}=await s[w(1726)](Qp);this[w(1355)]=await S(w(1608)+"_"+d,1,{upgrade(E){let g=w;E[g(972)+g(510)+"e"](d,{keyPath:h})}})})(),await this._initPromise}catch(d){console[n(1724)](d)}finally{this[n(942)+n(1471)]=null}}}async[t(652)](n){let s=t;try{return await this._init(),this[s(1355)]?.[s(652)](this[s(495)],n)}catch(d){console[s(1724)](d)}}async[t(1796)](n,s){let d=t;if(e[d(1527)]("YNWKt",e[d(378)])){let h=new _0x3b9b1c(e[d(373)](e[d(1172)](e[d(689)](e[d(1665)](_0x1bf3fe[e[d(1379)](_0x3eea11,4)],24),e[d(1177)](_0x181cef[_0x10e86d+5],16)),_0x29a004[e[d(1556)](_0x5b2834,6)]<<8),_0x2497c6[e[d(867)](_0x57d229,7)]),e[d(373)](e.rbIgC(e.abshl(_0x353b8d[e.olxrz(_0x3a1393,0)],24),e[d(927)](_0x391423[e.vewIy(_0x1baf50,1)],16)),e.gLKQe(_0x2e70f7[e[d(867)](_0x34edb2,2)],8))|_0x4c5c01[e[d(1468)](_0x30be80,3)],!0);return _0x5a6976+=8,{value:h,offset:e.yLiBN(_0x1503c2,8)}}else return await this[d(935)](),this._qosDB?.[d(1441)](this[d(495)],n)}async[t(1200)](n){let s=t;try{return await this[s(935)](),this._qosDB?.[s(381)](this[s(495)],n)}catch(d){console[s(1724)](d)}}async[t(1346)](){let n=t;try{return await this[n(935)](),this[n(1355)]?.[n(1346)](this._dbName)}catch(s){e.Kpvzw!==e.ymcDp?console[n(1724)](s):(this[n(1517)]("message",_0x3c9626),this.onmessage&&this[n(862)+"e"](_0x7986ee))}}async[t(1533)](){let n=t;return await this[n(935)](),this[n(1355)]?.[n(1613)+"ys"](this[n(495)])}async getAll(){let n=t;if(e[n(913)](e[n(1349)],e[n(1349)]))return await this[n(935)](),this[n(1355)]?.[n(1575)](this[n(495)]);try{this._ws&&this[n(512)].close(_0x4f047d,_0x1abb49)}catch{}}async[t(1121)](){let n=t;try{this[n(1355)]?.close(),this[n(1355)]=void 0}catch(s){console[n(1724)](s)}}get[t(1794)](){let n=t;try{return!!this[n(1355)]}catch(s){return console[n(1724)](s),!1}}}class tg{constructor(n,s){let d=t;this[d(1307)]=n,this[d(908)]=s,this._qosDB=localStorage}async openDB(){}get _prefix(){return"frontier_"+this[t(1307)]}async[t(652)](n){let s=t,d=this[s(1355)][s(1015)](this[s(1605)]);return JSON.parse(e[s(1785)](d,"{}"))[n]}async[t(1796)](n,s){let d=t,h={Kzfjm:e.dVdbg,gDFPG:e[d(1514)],satjc:d(1193),jaWPu:e[d(1018)],qZuPJ:e[d(650)]};if(e[d(619)]===e[d(1254)]){let w=h[d(786)][d(1721)]("|"),S=0;for(;;){switch(w[S++]){case"0":this[d(512)][d(1227)+"Listener"](h.gDFPG,this[d(1699)]);continue;case"1":this[d(512)][d(1227)+d(1811)](h.satjc,this[d(485)+"ge"]);continue;case"2":if(!this[d(512)])return;continue;case"3":this[d(512)][d(1227)+d(1811)](h[d(1269)],this[d(466)]);continue;case"4":this[d(512)][d(1227)+d(1811)](h.qZuPJ,this[d(1134)]);continue}break}}else{let w=this._qosDB[d(1015)](this[d(1605)]),S=JSON.parse(e[d(1610)](w,"{}"));return S[s||n[this[d(908)]]]=n,this[d(1355)].setItem(this[d(1605)],JSON[d(1217)+"y"](S)),s||n[this[d(908)]]}}async[t(1200)](n){let s=t;if(e[s(1727)](e.XJbWf,s(1676))){let d=this[s(1355)][s(1015)](this[s(1605)]),h=JSON[s(1462)](d||"{}");return h[n]=void 0,this._qosDB[s(476)](this[s(1605)],JSON[s(1217)+"y"](h))}else this[s(1355)]?.[s(1200)](_0x58db14[s(450)+"id"])}async[t(1346)](){let n=t;if(e.Rbwaq(e[n(1219)],e.RPGtH))this[n(1517)](e.wMzTx,e[n(1256)](_0x3f9fb5,e.wMzTx,{message:this["_formatErrorMess"+n(1129)](_0x25a881)}));else return this[n(1355)][n(1346)]()}async[t(1533)](){let n=t,s=this[n(1355)][n(1015)](this[n(1605)]),d=JSON[n(1462)](e[n(509)](s,"{}"));return Object[n(1533)](d)}async getAll(){let n=t,s=this._qosDB[n(1015)](this[n(1605)]),d=JSON.parse(e[n(1785)](s,"{}"));return Object[n(1666)](d)}[t(1121)](){return Promise.resolve()}get[t(1794)](){return!!this[t(1355)]}}class ng{constructor(n,s){let d=t;this._DBName=n,this[d(908)]=s,this[d(1355)]=Cn?tt:Xr?wx:null}async openDB(){}get[t(1605)](){let n=t;if(e[n(1381)](e[n(654)],e[n(614)])){this[n(772)+n(1513)+"t"]();let s=e[n(1184)](_0xbdad86,e.MFOAW,{message:n(1620)+n(1511)+n(1606)+"ct"});this["onStopIm"+n(406)+"yReconnect"]&&this[n(1308)+n(406)+n(675)+"ct"](s)}else return n(1608)+"_"+this[n(1307)]}async[t(652)](n){let s=t,d=this[s(1355)].getStorageSync(this[s(1605)]);return JSON[s(1462)](d||"{}")[n]}async[t(1796)](n,s){let d=t,h=this[d(1355)][d(973)+d(1746)](this[d(1605)]),w=JSON[d(1462)](e[d(531)](h,"{}"));return w[s||n[this[d(908)]]]=n,this[d(1355)]["setStora"+d(1746)](this[d(1605)],JSON[d(1217)+"y"](w)),s||n[this[d(908)]]}async del(n){let s=t,d=this._qosDB["getStora"+s(1746)](this[s(1605)]),h=JSON.parse(e.SrinG(d,"{}"));return h[n]=void 0,this[s(1355)][s(1660)+"geSync"](this[s(1605)],JSON[s(1217)+"y"](h))}async clear(){let n=t;return this[n(1355)][n(724)+n(1043)]()}async keys(){let n=t,s=this[n(1355)]["getStora"+n(757)+"nc"](this._prefix),d=JSON[n(1462)](e[n(1785)](s,"{}"));return Object[n(1533)](d)}async getAll(){let n=t;if(e[n(396)](e.IvXNh,e[n(707)])){let s=this[n(1355)][n(973)+"geInfoSync"](this[n(1605)]),d=JSON[n(1462)](e[n(1423)](s,"{}"));return Object[n(1666)](d)}else{let s=e.EoBNl(_0x36f65e,_0x31725a),d=_0x33ee16[n(498)];return _0x228734.limit=e.eISTT(_0x1965eb[n(1373)],s),d}}[t(1121)](){let n=t;return e[n(1440)](e.CCjWc,n(766))?Promise.resolve():_0x4bb0d9||(_0x15903a=[_0x41486f,_0x2929ab,_0x6529d2,_0xf357ac,_0x1e2f6c])}get[t(1794)](){return!!this[t(1355)]}}function _d(a,n){let s=t;if(e[s(1765)](Cn,Cn))return new ng(a,n);if((nr||Qr)&&e[s(1006)](e.yReJw,typeof indexedDB))return new eg(a,n);if(e[s(1423)](nr,Qr)&&s(1105)+"d"!=typeof localStorage)return new tg(a,n);throw new Error(e.amfgm)}class rg{constructor(){let n=t;this[n(1108)+n(749)+"Id"]=null,this[n(1108)+"l"]=36e5,this[n(1355)]=_d("qos",n(450)+"id")}async[t(1108)+t(1438)](){let n=t,s={bjrfE:e.pocFk,Afpeb:e[n(650)],DXBNi:e[n(1514)],AOrdq:e[n(836)],wMUGX:e[n(1018)]};if(e.eLvqi(e.aJyet,e[n(550)]))e[n(1082)](clearInterval,this._intervalTimeoutId),this[n(1108)+"lTimeoutId"]=e[n(1311)](setInterval,()=>{let d=n;this[d(598)+d(1314)]()},this[n(1108)+"l"]);else{let d=s.bjrfE.split("|"),h=0;for(;;){switch(d[h++]){case"0":this[n(512)][n(1435)+n(776)+"ner"](s[n(666)],this[n(1134)]);continue;case"1":this[n(512)][n(1435)+n(776)+n(1260)](s[n(1443)],this[n(1699)]);continue;case"2":this[n(512)][n(1435)+n(776)+n(1260)](s[n(1405)],this[n(485)+"ge"]);continue;case"3":if(!this[n(512)])return;continue;case"4":this._ws["removeEv"+n(776)+"ner"](s[n(1431)],this[n(466)]);continue}break}}}async[t(941)](){let n=t;await this[n(1355)][n(941)]()[n(1003)](()=>{let s=n;this[s(1108)+s(1438)]()})}async[t(598)+t(1314)](){let n=t,s={agIrZ:function(w,S){return e.VnhgC(w,S)}};(await this._qosDB?.[n(1575)]()||[])[n(829)](({timestamp:w})=>w<Date.now())[n(1558)](w=>{let S=n;if(e[S(554)](e[S(1489)],e[S(1489)])){let E=new _0x59482c(iLQZYN[S(1454)](2,_0x45d7a4));E[S(1796)](_0x320f25),_0x15bc3c[S(981)]=E}else this[S(1355)]?.[S(1200)](w[S(450)+"id"])})}async[t(1200)](n){if(e[t(1487)]!==e.fJVnF)return this._qosDB?.del(n)}async[t(1796)](n,s){let d=t;return this[d(1355)]?.[d(1796)]({message_id:n,timestamp:s})}async[t(652)](n){let s=t;return this._qosDB?.[s(652)](n)}async closeDB(){let n=t;e[n(1090)](clearInterval,this["_interva"+n(749)+"Id"]),await this[n(1355)]?.[n(1121)]()}get[t(1794)](){let n=t;return this[n(1355)]?.[n(1794)]}}function Ea(a){let n=t,s=!!this[n(803)][n(909)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let d=e[n(1337)](sn,a.message[n(1433)],e[n(1225)],"2"),h=d&&sn(a[n(1193)].headers,e[n(1365)],"1"),w=d&&e[n(1337)](sn,a[n(1193)][n(1433)],e[n(1319)],"1"),S=w?rr(a[n(1193)][n(1433)],n(1159)+"er_ack_msgid")?.[n(1721)](",")[n(829)](Boolean)||[]:[];return{enabled:s,isQoSMessage:d,isQoSAck:h,isAckCleanupMessage:w,ackMsgIds:S}}async function yd(){let a=t;return this[a(896)+a(723)]||(this[a(896)+a(723)]=new rg),this[a(896)+a(723)][a(1794)]||await this[a(896)+a(723)][a(941)](),this[a(896)+a(723)]}async function ig(a,n){let s=t;if(e[s(605)](e[s(1442)],"ElBOo")){if(e[s(1725)](e.rJySz,typeof _0x1480d1)){let d=new _0x1b945b(e[s(603)](_0x3400aa,_0x26fe1e));return e.FgYcC(_0x5b5c16,_0x5e07a6,d,0),d}return e[s(1236)](_0x4d1860,_0x4f6b08)?new _0x165765(_0x5a77b5):new _0x2c08c5(_0x2aa12d[s(858)],_0x3473d1[s(1491)+"et"],_0x50feb0.byteLength)}else{let{enableAutoAck:d}=this[s(803)],h=sn(a[s(1193)][s(1433)],e[s(681)],"1"),w=e[s(1162)](sn,a.message.headers,e[s(1102)],"1"),S=Ea[s(1502)](this,a);if(e.pBzHk(d,h)){let{SeqID:E,LogID:g,service:D,LogIDNew:L,method:B}=a[s(1193)];this[s(1543)]({SeqID:E,LogID:g,LogIDNew:L,service:D,method:B,headers:[{key:"is_ack",value:"1"},{key:e[s(1478)],value:e[s(1012)](L,"")},{key:e[s(1563)],value:"0"}]})}w&&!S[s(1420)]&&this[s(755)+s(881)+s(855)](a),e[s(641)](n)}}async function sg(a,n){let s=t;this[s(437)](e[s(874)],a.message),n()}async function og(a,n){let s=t;if(e[s(1824)](e[s(1744)],e.Gegjw)){let d=e[s(885)](tn,await e[s(584)](wd,a[s(1013)]));try{if(d[s(888)]instanceof Uint8Array){let h=this[s(803)][s(819)+"ncoding"]instanceof Object?{force:!!this[s(803)][s(819)+"ncoding"][s(917)],encoding:this._options["payloadE"+s(1621)][s(1790)]?this[s(803)].payloadEncoding[s(1790)][s(484)](/\s/g,"")["toLowerC"+s(1025)]():""}:{force:!1,encoding:this[s(803)][s(819)+s(1621)]?this[s(803)][s(819)+"ncoding"].replace(/\s/g,"")[s(861)+s(1025)]():""},w=d[s(819)+s(1621)]?d[s(819)+s(1621)][s(484)](/\s/g,"")[s(861)+"ase"]():"",S=e[s(1138)](this[s(803)][s(518)+s(980)],Object)?{force:!!this[s(803)].payloadType[s(917)],type:this[s(803)].payloadType[s(457)]?this[s(803)].payloadType.type[s(484)](/\s/g,"")[s(861)+s(1025)]():""}:{force:!1,type:this[s(803)][s(518)+s(980)]?this._options["payloadT"+s(980)][s(484)](/\s/g,"")[s(861)+"ase"]():""},E=d[s(518)+s(980)]?d["payloadT"+s(980)][s(484)](/\s/g,"")[s(861)+s(1025)]():"",g=S[s(917)]?S[s(457)]:E||S[s(457)],D=h[s(917)]?h.encoding:w||h[s(1790)],L=[e[s(851)],e[s(1399)],e[s(1403)],e.rJySz],B=[e.QFTWp,e.LtmXH];this[s(803)][s(827)+s(1350)+s(726)+"ad"]&&L[s(1812)](g)&&(!D||B[s(1812)](D))?d["textPayl"+s(1010)]=md(d[s(888)],0,d[s(888)][s(1578)+"th"]):d[s(1357)+s(1010)]=""}else d[s(1357)+s(1010)]=""}catch(h){d[s(1357)+s(1010)]="",console.log(h)}a[s(1193)]=d,e[s(641)](n)}else return!!(e[s(1670)](this[s(428)+s(1593)],this.endpoints[s(1592)])||e.wyrbf(this[s(428)+s(1593)],e[s(530)](this[s(1052)+"s"][s(1592)],1))&&e.nHZEN(this[s(1808)+"ndpointT"+s(1466)+"t"],this[s(946)+"es"]))}function ag(a,n,s){let d=t,h=e[d(1785)](s,8192),w=e[d(672)](h,1),S=null,E=h;return function(g){let D=d;if(g<1||e[D(889)](g,w))return e[D(995)](a,g);E+g>h&&(S=a(h),E=0);let L=n.call(S,E,E+=g);return 7&E&&(E=e[D(648)](e.lwdvU(7,E),1)),L}}let cg=4294967295;function lg(a,n,s){let d=t;return RangeError(e[d(648)](e.tellO(e[d(587)](d(1802)+d(356)+d(1698),a)+d(1713)+(n||1),e[d(1536)]),s))}function dg(a,n,s){let d=t,h={mRBNx:e.WjisH,ApCcc:function(w,S){return w!=S},gdoog:e[d(834)]};if(e[d(604)]!==e[d(604)]){let w=h.mRBNx[d(1721)]("|"),S=0;for(;;){switch(w[S++]){case"0":return!1;case"1":if(_0x593ef3&&_0x59c448[d(537)+d(1818)])return!0;continue;case"2":if(_0x235884)return!0;continue;case"3":if((_0x5034ed||_0x444979)&&cVLHry[d(628)](cVLHry[d(1285)],typeof _0x5584b2)&&_0x1d6e45)return!0;continue;case"4":if(_0x22b537&&_0x2a7b54[d(537)+d(1818)])return!0;continue}break}}else{if(e[d(841)](s,cg))throw new Error(d(971)+d(1160)+"e");let w=3;for(;e.njwtN(w,0);){let S=255&s;e[d(1153)](Sa,S,a,e[d(1741)](n,w)),s>>>=8,w--}return e[d(950)](n,4)}}function ug(a,n){let s=t;if(e[s(1460)](e[s(869)],e[s(1673)])){let d=0,h=n,w=e.tMfrb(n,4);for(;e[s(1144)](h,w);){let{value:S,offset:E}=e[s(988)](va,a,h);h=E,d=e[s(1482)](e[s(1709)](d,8),0),d+=S}return{value:d,offset:w}}else{let d=_0xb7a905.bytes,h=_0x294b19[s(498)];return d[s(1592)]===h?d:d[s(1014)](0,h)}}function fg(a,n,s){let d=t,h=e.rHPQw.split("|"),w=0;for(;;){switch(h[w++]){case"0":if(!a)return s;continue;case"1":if(n[d(430)])return e[d(1507)](n[d(430)](a,s),s);continue;case"2":if(e[d(362)](a[d(1592)],40))return e.tMfrb(e[d(1097)](ya,a,n,s),s);continue;case"3":return e[d(1112)](ya(a,n,s),s);case"4":if(n[d(1286)+"e"])return n.utf8Write(a,s)+s;continue}break}}function hg(a,n){let s=t,d=new he(e[s(1655)](e[s(522)](e[s(1368)](a[e[s(1179)](n,4)]<<24,e[s(822)](a[n+5],16)),e.nZWmq(a[e.vxKfP(n,6)],8)),a[n+7]),e[s(1207)](e[s(1604)](e[s(925)](a[e[s(1387)](n,0)]<<24,e[s(702)](a[e[s(1625)](n,1)],16)),a[e[s(665)](n,2)]<<8),a[e.BKRsK(n,3)]),!0);return n+=8,{value:d,offset:e[s(1623)](n,8)}}function xg(a,n,s){let d=t,h=a[d(421)],w=a[d(1411)];return n[s]=e[d(1143)](w,24),n[e[d(467)](s,1)]=e[d(1154)](w>>>16,255),n[e[d(676)](s,2)]=e.qbkAl(e[d(1378)](w,8),255),n[s+3]=e[d(704)](255,w),n[e[d(1463)](s,4)]=e[d(473)](h,24),n[s+5]=h>>>16&255,n[e[d(1556)](s,6)]=e[d(1437)](e[d(1063)](h,8),255),n[s+7]=e[d(1202)](255,h),s+=8,s}function va(a,n){let s=t;return e[s(771)](e[s(939)],e.zXqWj)?this[s(911)][s(958)+"te"]:a[s(441)+"8"]?{value:a[s(441)+"8"](n),offset:e[s(1152)](n,1)}:{value:e[s(1598)](255,a[n]),offset:n+1}}function Sa(a,n,s){let d=t;return n[d(1740)+"t8"]?n[d(1740)+"t8"](a,s):n[s]=e[d(481)](255,a),e.EglzS(s,1)}let pg=function(a){return new Uint8Array(a)},gg=e.FDJAf(e[t(834)],typeof Buffer)?Buffer["allocUns"+t(1362)]:e.LIcJm(ag,pg,Uint8Array[t(1766)+"e"][t(1014)]),mg=16,Ia=32;function wg(a){let n=t,s=0,d={};for(let h=0;e.nbGFW(h,a[n(1592)]);h++)d[a[h][n(1771)+n(1216)]]=e[n(918)](gd,a[h][n(1771)+n(1216)]),s+=e.aNgYW(14,d[a[h][n(1771)+"ame"]]);return[s,d]}function bd(a,n,s){let d=t,h={dCpmj:e.LGBlz,CrMvK:e[d(882)],bxPqz:function(D,L,B,W){return e[d(379)](D,L,B,W)},kqamd:e[d(864)],jMmiC:"name",vGJBY:e[d(929)],kNiuI:e[d(951)]},[w,S]=e.psvjV(wg,a),E=e[d(1801)](gg,w),g=0;return a[d(1558)](D=>{let L=d,B=h.dCpmj.split("|"),W=0;for(;;){switch(B[W++]){case"0":console[L(1724)](h.CrMvK,g);continue;case"1":g=h[L(1028)](Sa,0,E,g);continue;case"2":console[L(1724)](h[L(1067)],g);continue;case"3":console.log(L(873)+L(932),g);continue;case"4":console.log(h[L(403)],g);continue;case"5":g=dg(E,g,D.service||0);continue;case"6":g=fg(D[L(1771)+L(1216)],E,g);continue;case"7":g=Sa(S[D[L(1771)+L(1216)]],E,g);continue;case"8":g=h[L(1028)](xg,he.fromNumber(D[L(1150)]||n),E,g);continue;case"9":console[L(1724)](h.vGJBY,g);continue;case"10":console[L(1724)](h[L(591)],D,D[L(1274)]);continue}break}}),{frameType:Ia,headers:[{key:d(685)+d(617),value:s}],payload:E}}function _g(a){let n=t,s=0,d=[];for(;e[n(1312)](s,a[n(1578)+"th"]);){let{offset:h}=e[n(1336)](va,a,s);s=h;let w={cursor_name:"",cursor:0,service:0},{value:S,offset:E}=e[n(974)](ug,a,s);w[n(1274)]=S,s=E;let{value:g,offset:D}=va(a,s);s=D,w[n(1771)+n(1216)]=e.URpLF(md,a,s,e[n(1386)](s,g)),s+=g;let{value:L,offset:B}=e.RnTLC(hg,a,s);w[n(1150)]=L[n(417)](),s=B,d[n(1140)](w)}return d}function yg(){let a=t;return{frameType:Ia,headers:[{key:e[a(780)],value:a(1587)+"_EXIST"}],payload:void 0}}class bg{constructor(n,s,d){let h=t;this[h(1333)+h(1174)]=n,this[h(1096)+h(1645)]=s,this["_message"+h(709)]=d,this[h(1355)]=e.qjMbF(_d,this[h(1333)+h(1174)],e.akDfE)}async[t(941)](){let n=t;await this[n(1355)][n(941)]()}async[t(1302)+"rs"](){let n=t;if(!this[n(1355)].isReady)return;let s=this[n(744)+"Strategy"],d=await this._qosDB.getAll();switch(console[n(1724)](e[n(1538)],d),s){case e[n(1577)]:return d&&d[n(1592)]?e[n(1337)](bd,d,0,this[n(1096)+n(1645)]):void 0;case e[n(589)]:return;case e[n(1816)]:return d&&d[n(1592)]?e[n(1097)](bd,d,0,this[n(1096)+n(1645)]):e.hUWtG(yg)}}async[t(1796)](n,s,d){let h=t;return console.log(h(451),n,s,d),this._qosDB[h(1796)]({cursor_name:n,cursor:s,service:d})}async[t(1044)+"rs"](n){let s=t,d=e.ZbYkY(_g,n);for(let h of d)console[s(1724)](e[s(1095)],d),await this._qosDB[s(1796)](h)}async[t(652)](n){let s=t;return(await this[s(1355)][s(652)](n))?.cursor}async[t(1121)](){let n=t;await this._qosDB[n(1121)]()}[t(1733)+t(360)+t(678)](n){let s=t;this[s(1096)+s(1645)]=n}get isReady(){let n=t;if(e.erODb(e[n(839)],e.UXvYC))return this[n(1355)][n(1794)];try{return!!this[n(1355)]}catch(s){return _0x3b61c7[n(1724)](s),!1}}}let Eg="__x_msg_"+t(966);async function Ed(a){let n=t,s={WwQYi:function(E,g,D){return E(g,D)},jDdBs:e[n(1514)],WIsko:n(1246)};if(!this._options[n(909)+"S"])return null;let{aID:d,fpID:h,messageStrategy:w}=this[n(803)],S=e.SrinG(a,Eg);try{if(this[n(916)+n(1809)])if(e.RzFLk(e[n(1488)],e[n(1132)]))a&&this[n(916)+n(1809)][n(1733)+n(360)+n(678)](a);else{let E=_0x211134(_0x21c1eb,_0x1bf95e[n(1592)]);_0x404484[n(981)].set(_0x30cada,E)}else this["_cursorM"+n(1809)]=new bg(h+"_"+d+"_"+S,S,w);return this[n(916)+n(1809)][n(1794)]||await this[n(916)+n(1809)].openDB(),this._cursorManager}catch{if(e[n(1527)](e[n(1242)],n(489))){this["_dispatc"+n(1041)+"ent"](s[n(365)](_0x549eed,s[n(1496)],{code:1e3,reason:s[n(1776)]})),this[n(357)+n(720)]?.[n(1167)+n(1814)+n(646)](),this[n(608)+n(868)]?.["resetCou"+n(1675)]();return}else return null}}async function vg(a,n){let s=t;if(e[s(1691)](e[s(751)],e[s(751)]))_0xd3e5ef[_0x55a7e1++]=_0x1467ad>>6|192,_0x5e78f4[_0x342190++]=63&_0x1df197|128;else{let d=e.FgYcC(sn,a[s(1193)].headers,s(1273),"-1"),h=sn(a[s(1193)][s(1433)],e[s(1102)],"1"),w=e[s(752)](rr,a.message.headers,"x_fronti"+s(1748)),S=Number(e[s(818)](rr,a[s(1193)][s(1433)],e.QtZAj))||0,E=Ea.call(this,a),g=e[s(1097)](sn,a[s(1193)].headers,e.dDESF,"2"),D=e[s(1689)](rr,a[s(1193)][s(1433)],e[s(1222)]),L=e[s(986)](Number,rr(a[s(1193)][s(1433)],e[s(1394)]));if(E[s(1420)])return e[s(1519)](n);let B=E[s(1667)+s(461)]?await yd[s(1502)](this):null;if(e.GwWvF(a[s(1193)].service,0)&&h&&!d||e[s(841)](a[s(1193)][s(1274)],0)){if(w&&E[s(1667)+s(461)]&&B)return!!!await B[s(652)](w)&&(e[s(793)](s(1309),e[s(1171)])?(e[s(1088)](_0x1fb80b,_0x15db14,32),_0x31ee65(_0x2e3afe,e[s(442)](_0x10c06c,_0x504cbd))):(this._dispatchMessageEvent(a),await B[s(1796)](w,e[s(676)](Date[s(1505)](),S)))),n();if(g)if(e.EBXJE(e.kYiGV,e[s(1750)])){let W=await Ed.call(this);if(!W)return this[s(755)+s(708)+s(823)](a),e[s(465)](n);let X=await W[s(652)](D)??-1;if(e.ndPhx(X,L))this[s(755)+s(708)+s(823)](a),W[s(1796)](D,L,a[s(1193)].service);else throw new Error(s(1720)+s(429)+s(1586)+L+(s(505)+s(1054)+s(1376)+"r ")+X);return n()}else _0xdd3dd2(this[s(1477)+s(767)+s(393)]),this._connectionTimeoutId=null;return this[s(755)+s(708)+s(823)](a),e[s(1559)](n)}}}async function Sg(a,n){let s=t,d=Ea[s(1502)](this,a);if(!d[s(1667)+s(461)])return e[s(727)](n);let h=await yd[s(1502)](this);if(d[s(516)+s(599)+s(1129)]&&d[s(921)+"s"].length)for(let w of d[s(921)+"s"])await h[s(1200)](w);e[s(1055)](n)}async function Ig(a,n){let s=t,d={XmciV:function(h,w){return e[j(1339)](h,w)},CXPiV:function(h,w){return e[j(1583)](h,w)},YcHNj:function(h,w){return e[j(1650)](h,w)},cHfgw:function(h,w){return h&w},JbCAN:function(h,w){return e.bYxFd(h,w)}};if(e[s(1377)]!=="rqsIT"){if(_0x3315fa<1||rNoQcG[s(433)](_0x51ea77,_0x265383))return rNoQcG[s(746)](_0x138e7b,_0x1e6d71);rNoQcG[s(805)](_0x67b7c9,_0x971504)>_0x5e2a27&&(_0xf6e46e=rNoQcG[s(746)](_0x2f6941,_0x23902a),_0x165a34=0);let h=_0x3f4827[s(1502)](_0x2511a3,_0x5cfd8f,_0xbaf6f5+=_0x49ce8c);return rNoQcG[s(1259)](7,_0x780de)&&(_0x2a87b0=rNoQcG[s(805)](rNoQcG.JbCAN(7,_0x5b0baa),1)),h}else{let h=e[s(1503)](a[s(1193)].frameType,mg),w=e[s(1503)](a[s(1193)][s(374)+"e"],Ia);if(e[s(525)](!h,!w))return e[s(641)](n);let S=rr(a.message[s(1433)],e[s(780)]);if(!S)return e.SbGAz(n);let E=await Ed.call(this,S);if(!E)return e[s(641)](n);if(h){let g=await E[s(1302)+"rs"](),D={frameType:g?.["frameType"],SeqID:he[s(1553)+"er"](this[s(1210)]++),LogID:he[s(1553)+"er"](this[s(803)]["logIDGen"+s(844)]()),service:9e3,method:5,headers:g?.[s(1433)],payload:g?.[s(888)]},L=v(D);this[s(512)]&&this[s(512)][s(958)+"te"]&&this[s(512)][s(1223)](L)}if(w){let g=a[s(1193)][s(888)];g&&E[s(1044)+"rs"](g)}}}let Ag=async function(a,n){let s=t;this[s(1732)]=!1,e.Vxrpx(clearTimeout,this[s(1477)+s(767)+"utId"]),n()},Tg=async function(a,n){let s=t;if(!this[s(512)]||e[s(1459)](this[s(512)].readyState,this[s(1607)]))return e[s(548)](n);let{pingInterval:d}=this[s(803)];this[s(357)+"tManager"]?.[s(1167)+s(1814)+s(646)]();for(let w=0;e[s(1526)](w,this[s(744)+s(1024)].length);w++){let S=this._messageQueue[w];if(e[s(607)](this._ws[s(958)+"te"],this[s(1607)])&&e[s(1428)](null,S))this[s(512)]&&this[s(512)][s(1223)](S),this._messageQueue[w]=null;else break}this[s(744)+s(1024)]=this[s(744)+s(1024)][s(829)](w=>!!w),this["_pingPon"+s(1288)+"Id"]=setTimeout(()=>this._ping(),d),this[s(755)+s(1296)+"nt"](a),this[s(1031)+"er"]&&this._ws&&(this._ws[s(1084)+"pe"]=this[s(721)+s(980)]);let h=this[s(357)+"tManager"]?.[s(596)+s(990)+"nt"]();this[s(437)](s(1120)+h+s(777)),e[s(1559)](n)},kg=async function(a,n){let s=t,d=this[s(357)+s(720)]?.["getCurre"+s(990)+"nt"]();this[s(437)](s(1120)+d),n()};class Cg extends _a{constructor(n){let s=t,d={HMHhN:function(h,w,S,E){return e[j(379)](h,w,S,E)},sJhrq:function(h,w,S){return e.stsEo(h,w,S)},zCTSf:"error"};if(e.KObYF(e[s(1036)],e.eCIZr)){super(),this[s(446)+"igatorOn"+s(1389)]=!0,this._isBrowser=nr,this[s(538)]=Wp,this._isMiniTT=Cn,this[s(870)+"X"]=Xr,this[s(690)+"r"]=Qr,this[s(744)+s(1024)]=[],this[s(357)+s(720)]=null,this[s(1702)+s(1163)]=!1,this[s(721)+s(980)]=e[s(508)],this[s(1477)+s(1268)]=!1,this[s(1477)+s(767)+s(393)]=null,this["_reconne"+s(898)+s(662)]=null,this["_pingPon"+s(1288)+"Id"]=null,this[s(1210)]=0,this[s(1732)]=!1,this._url="",this[s(896)+s(723)]=null,this[s(916)+s(1809)]=null,this._pingLossCounter=null,this._protocols=e[s(1636)],this.CLOSED=3,this[s(1652)+"NG"]=0,this[s(1607)]=1,this[s(840)]=2,this[s(1134)]=E=>{let g=s;try{d.HMHhN(pd,this,E,[Ag,Tg,kg])}catch(D){let L=d[g(398)](ct,d[g(710)],{message:D[g(1193)],code:rn[g(1580)+"OR"],error:D});this[g(755)+g(733)+g(1071)](L)}},this[s(485)+"ge"]=async E=>{let g=s,{pingInterval:D,pingFrequency:L}=this[g(803)];if((e[g(1550)]("hi",E.data)&&e[g(549)](e[g(1126)],L)||e[g(1258)](g(394),L))&&(this[g(578)+g(1185)](),this[g(1517)]("ping_onc"+g(924)+"s",g(1706)),this[g(1186)+"gTimeoutId"]=e[g(849)](setTimeout,this[g(546)][g(1425)](this),D)),!e.FjHJH("hi",E[g(1013)]))try{pd(this,E,[og,ig,Sg,Ig,vg,sg])}catch(B){let W=e[g(477)](ct,g(435),{message:B[g(1193)],code:rn[g(904)+g(677)],error:B});this["_dispatc"+g(733)+g(1071)](W)}},this[s(466)]=E=>{let g=s,D={OYnSg:function(L,B,W){return e[j(756)](L,B,W)},GmczH:e[g(1018)]};if(e[g(1774)](e[g(348)],e[g(348)])){let L="connect "+_0x305eb0+(g(928)+", max re"+g(1506)+g(1540));this[g(437)](L),this[g(755)+g(733)+"ent"](D[g(555)](_0x2d3273,D[g(1453)],{message:L,code:_0xde061e[g(1476)+g(627)+"R"]}));return}else{let L=this[g(357)+g(720)]?.["checkRea"+g(1656)+"es"](),B=this[g(357)+g(720)]?.[g(596)+"ntEndpoint"]();if(L&&!E[g(1193)]){let W="connect "+B+(g(1518)+g(948)+g(1480)+"ed");this[g(755)+"hErrorEvent"](e[g(1755)](ct,e[g(1018)],{message:W,code:rn["MAX_RETR"+g(627)+"R"],error:E}));return}this[g(512)]&&this[g(512)][g(958)+"te"]===this[g(1607)]&&this[g(1196)+g(848)](),this[g(755)+g(733)+g(1071)](e.ggLak(ct,g(435),{message:E[g(1193)],code:rn[g(1142)+"RROR"],error:E}))}},this[s(1699)]=async E=>{let g=s;this[g(1602)+g(595)](),this[g(578)+"ngTimer"](),this[g(860)+g(831)+"rs"](),this[g(512)]=null,this[g(1477)+"Lock"]=!1;let D=this[g(357)+g(720)]?.["checkRea"+g(1656)+"es"]();if(!D&&this[g(355)+g(1758)]()&&!this._readyClosed){let L=this[g(357)+g(720)]?.["getCurre"+g(990)+"nt"](),B=this[g(803)][g(1068)+"tInterce"+g(1686)](E.code,E[g(640)]);this[g(755)+"hCloseEvent"](e[g(852)](mt,e[g(1514)],{code:1006,reason:E[g(640)]||g(1253)+g(687)+"d, unkno"+g(576)+g(1136)+g(1467)+L,willReconnect:B})),B&&this[g(1477)]();return}if(E[g(1273)]!==1e3&&this[g(1702)+g(1163)]){this[g(755)+g(1041)+g(1071)](e[g(1515)](mt,e[g(1514)],{code:1e3,reason:e[g(824)]})),this[g(357)+g(720)]?.["resetEndpointCon"+g(646)](),this["_pingLos"+g(868)]?.[g(647)+g(1675)]();return}if(e.pFIHH(1e3,E[g(1273)])&&D){let L=this[g(357)+"tManager"]?.[g(596)+g(990)+"nt"](),B=E[g(640)];B||(B=await e[g(997)](Xp,this[g(1360)])),B=g(1253)+"ng faile"+g(926)+B+(g(1490)+g(1700))+L+(g(718)+"tries re"+g(1540)),this[g(755)+g(1041)+g(1071)](e.erLpB(mt,e.FeXiv,{code:E[g(1273)],reason:B}));let W=g(1330)+L+(" fail, m"+g(948)+"es reached");this[g(755)+g(733)+g(1071)](e[g(1515)](ct,e.wMzTx,{message:W,code:rn[g(1476)+g(627)+"R"]})),this[g(357)+g(720)]?.["resetEnd"+g(1814)+g(646)](),this[g(608)+g(868)]?.resetCounter();return}if(E.code!==1e3&&!E[g(640)]){let L=this[g(357)+g(720)]?.["getCurre"+g(990)+"nt"]();this["_dispatc"+g(1041)+g(1071)](mt(g(532),{code:E[g(1273)],reason:g(1253)+"ng faile"+g(1215)+g(576)+g(1136)+g(1467)+L})),this[g(357)+"tManager"]?.[g(1167)+g(1814)+g(646)](),this[g(608)+"sCounter"]?.["resetCou"+g(1675)]();return}this[g(755)+g(1041)+"ent"](E),this["_endpoin"+g(720)]?.["resetEndpointCon"+g(646)](),this[g(608)+"sCounter"]?.[g(647)+g(1675)]()},this.onclose=null,this[s(1461)]=null,this[s(862)+"e"]=null,this[s(1022)]=null,this[s(1481)+s(996)]=null,this[s(1707)+s(1390)]=null,this.onStopImmediatelyReconnect=null,this[s(1769)+s(993)]=this[s(1769)+"nLine"][s(1425)](this),this[s(1769)+s(1113)]=this[s(1769)+s(1113)][s(1425)](this),this["_handleP"+s(528)]=this[s(568)+s(528)][s(1425)](this),this[s(568)+s(692)]=this["_handleP"+s(692)][s(1425)](this),this[s(803)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1119)](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.iQwJV,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:s(1504),env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:w}=n,S=Array[s(1464)](h)?h:e.jrOmJ(s(758),typeof h)?[h]:[];if(!S||e[s(1224)](0,S[s(1592)]))throw new Error(e[s(1049)]);if(!e.QBjhf(Vp,w))throw new Error(e.FeVNZ);Object[s(1156)](this[s(803)],n),this._endpointManager=new xd(S,this[s(803)][s(946)+"es"]),this._pingLossCounter=new Yp(this[s(803)][s(455)+s(490)]),this[s(803)][s(837)+s(1674)]&&(this[s(1732)]=!0,this[s(1477)]()),this[s(803)][s(600)+s(1734)+"nged"]&&(this[s(1203)+"T"]||this[s(870)+"X"]?this[s(1191)+s(1352)+s(923)]():this._isBrowser&&this[s(1787)+"balEventListener"]())}else return this[s(911)].binaryType}[t(1769)+t(993)](){let n=t;this._options["disableAutoRecon"+n(934)]||this[n(1702)+"osed"]||this[n(1401)+n(996)]()}[t(1769)+t(1113)](){let n=t;this[n(772)+n(1513)+"t"]();let s=wa(e[n(1029)],{message:e[n(962)]});this["onStopIm"+n(406)+n(675)+"ct"]&&this[n(1308)+n(406)+n(675)+"ct"](s)}[t(1787)+t(1807)+"Listener"](){let n=t;this[n(1031)+"er"]&&window[n(1227)+n(1811)](e[n(1465)],this["_handleO"+n(993)]),this[n(1031)+"er"]&&window["addEvent"+n(1811)](e[n(667)],this["_handleO"+n(1113)]),this[n(1031)+"er"]&&window[n(1227)+n(1811)](e[n(404)],this[n(568)+"ageHide"]),this[n(1031)+"er"]&&window[n(1227)+n(1811)](e[n(856)],this[n(568)+"ageShow"])}["_dropGlobalEvent"+t(1811)](){let n=t;this[n(1031)+"er"]&&window[n(1435)+n(776)+n(1260)](n(1187),this[n(1769)+"nLine"]),this[n(1031)+"er"]&&window["removeEv"+n(776)+n(1260)](e[n(667)],this[n(1769)+n(1113)]),this[n(1031)+"er"]&&window[n(1435)+n(776)+n(1260)](n(1449),this[n(568)+n(528)]),this[n(1031)+"er"]&&window[n(1435)+n(776)+n(1260)](n(1432),this[n(568)+"ageShow"])}[t(568)+t(528)](n){let s=t;!n[s(894)+"d"]&&(this[s(1031)+"er"]&&window["removeEv"+s(776)+s(1260)](s(1449),this[s(568)+"ageHide"]),this[s(1031)+"er"]&&window["removeEventListe"+s(1260)](e[s(856)],this[s(568)+s(692)]),this.close()),this[s(1031)+"er"]&&window["removeEv"+s(776)+s(1260)](e.Mbnxx,this[s(1769)+s(993)]),this[s(1031)+"er"]&&window[s(1435)+s(776)+s(1260)](s(900),this[s(1769)+s(1113)])}["_handleP"+t(692)](n){let s=t;if(e[s(1754)](s(1696),e.QOLMs))n.persisted&&(this[s(355)+s(1758)]()&&(!this[s(512)]||e.eaWMB(this[s(512)][s(958)+"te"],this[s(1607)])||e[s(663)](this[s(512)][s(958)+"te"],this.CONNECTING))&&this["_handleO"+s(993)](),this._isBrowser&&window["addEvent"+s(1811)](e[s(1465)],this[s(1769)+s(993)]),this[s(1031)+"er"]&&window[s(1227)+s(1811)](s(900),this[s(1769)+s(1113)]));else return this["currentEndpointT"+s(1466)+"t"]=1,this[s(428)+s(1593)]++,this[s(1052)+"s"][this[s(428)+s(1593)]]}async["_generat"+t(1451)](n){let s=t;if(e[s(1728)]!=="ALvcb"){let d=this[s(357)+s(720)]?.["checkRea"+s(1656)+"es"](),h=this[s(357)+"tManager"]?.["getCurre"+s(990)+"nt"]();if(d&&!_0x167865[s(1193)]){let w=s(1330)+h+(s(1518)+s(948)+s(1480)+"ed");this[s(755)+s(733)+s(1071)](_0x2dfa1c(e[s(1018)],{message:w,code:_0x5e2727[s(1476)+s(627)+"R"],error:_0xf4eaa3}));return}this[s(512)]&&e.DRDtu(this[s(512)][s(958)+"te"],this[s(1607)])&&this[s(1196)+"ect"](),this["_dispatchErrorEv"+s(1071)](e.Tsagk(_0x2a7cc3,s(435),{message:_0x5b48cc[s(1193)],code:_0x5b8db1["NATIVE_E"+s(504)],error:_0x53ef5a}))}else{let{fpID:d,deviceID:h,bddID:w,ttwID:S,accessKey:E,aID:g,customParams:D={},enableAutoAck:L,enableQoS:B,QoSLevel:W,env:X}=this[s(803)],re,Te,on;this[s(1031)+"er"]||this._isMiniWX||this._isMiniTT?(re=location&&e[s(1183)](s(1091),location.protocol)?"wss://":e[s(358)],Te=n[s(484)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),on=/^wss(.*:\/\/)/[s(1730)](n)?n:""+re+Te):(re=e[s(594)],Te=n[s(484)](/(^http)((?:[s]*:\/\/))/,""),on=/(^ws)((?:[s]*:\/\/))/[s(1730)](Te)?Te:""+re+Te);let vd=w?"bd_did":S?e[s(368)]:"device_id",Sd=w||S||h;if(!Sd||!vd)throw new Error(e[s(1775)]);let Rg=e[s(1408)]==typeof D?await e[s(1772)](D):D,Pg=X?e[s(1094)](Zp,X[s(790)],X[s(386)]):{},Aa=Object[s(1156)]({device_platform:e[s(697)],version_code:s(1058)+"0",access_key:E,fpid:d,aid:g,[vd]:Sd,xsack:L?1:0,xaack:L?1:0,xsqos:B?1:0,qos_level:B?W:void 0,qos_sdk_version:2,...Pg},Rg),Dg=Object[s(1533)](Aa).reduce((Ta,ka)=>Aa[ka]!==void 0?""+Ta+(Ta?"&":"?")+ka+"="+Aa[ka]:Ta,"");return on+"/ws/v2"+Dg}}async[t(1477)](){let n=t;if(!(this._connectLock||this[n(1702)+n(1163)])){this[n(1477)+n(1268)]=!0;try{if(e[n(1428)]("iVdnd",n(1788))){let s=this[n(357)+n(720)]?.[n(799)+n(1335)+n(1251)+n(669)+n(902)](),{timeoutInterval:d}=this[n(803)];if(s)if(e[n(877)](e[n(547)],e[n(547)])){let w=this[n(357)+n(720)]?.[n(596)+n(990)+"nt"](),S=this[n(357)+n(720)]?.[n(732)+n(1469)+"pointAnd"+n(1589)+"unt"](),E=this[n(357)+"tManager"]?.[n(596)+n(990)+n(1073)+n(1004)]();if(S)if(e[n(1104)]===e.hPPZn){let g="connect "+w+(n(928)+n(718)+n(1506)+"ached, w"+n(1101)+n(1338)+n(815))+S+(n(353)+"y"),D=e[n(1161)](ct,e[n(1018)],{message:g,code:rn[n(1476)+n(627)+"R"]});this[n(437)](g),this[n(755)+n(733)+n(1071)](D),this[n(1360)]=await this._generateUrl(S),this._debug("connect "+S+" "+E+" times"),this[n(860)+n(831)+"rs"]()}else return _0x471bbb[n(686)]||_0x1da01e[n(1001)]?(n(1617)+" "+(_0x4de877[n(686)]||"")+n(517)+(_0x5727d2[n(1001)]||""))[n(1148)]():_0x5c1f8c[n(1217)+"y"](_0x2cdd8a);else{let g="connect "+w+(" timeout"+n(718)+n(1506)+n(1540));this._debug(g),this[n(755)+"hErrorEv"+n(1071)](ct("error",{message:g,code:rn[n(1476)+"IES_ERROR"]}));return}}else _0xa103e5+=_0x1c088a(_0x24a87a),_0x3055f8++;else{let w=this["_endpoin"+n(720)]?.[n(596)+n(990)+n(661)+n(1694)](),S=this[n(357)+n(720)]?.["getCurre"+n(990)+n(1073)+"ount"]();this._url=await this[n(795)+n(1451)](e[n(1033)](w,"")),this[n(437)](n(1330)+w+" "+S+n(1445)),this["_removeW"+n(831)+"rs"]()}if(this[n(1732)])this[n(1732)]=!1;else{let w=e[n(985)](wa,e.MFOAW,{message:n(949)});this[n(1481)+n(996)]&&this[n(1481)+n(996)](w)}let h=this[n(357)+n(720)]?.[n(596)+"ntEndpoi"+n(1073)+n(1004)]()||0;e[n(889)](h,1)&&await this._wait(e[n(1356)](h,1)),this[n(437)](n(1253)+n(483)+this[n(1360)]+(n(565)+n(1157))+this[n(434)+"ls"]),this[n(512)]=e[n(1220)]($p,{url:this[n(1360)],protocols:[this[n(434)+"ls"]],headers:this._options[n(760)+n(1279)+"s"]["customHt"+n(1544)]},this[n(803)].ws),(this._isBrowser||this._isWorker)&&this[n(512)]&&(this._ws.binaryType=this[n(721)+n(980)]),this[n(499)+n(1827)](),this[n(1477)+n(767)+n(393)]=e.nozXO(setTimeout,this._onTimeout[n(1425)](this),d)}else return this[n(512)]?this[n(512)][n(1084)+"pe"]:this[n(721)+n(980)]}catch(s){if(e[n(1061)](n(1684),n(1684)))_0x222fba[n(1724)](_0x352244);else throw this["_connect"+n(1268)]=!1,s}}}[t(1602)+t(595)](){let n=t;if(e[n(1139)](e.ymOrA,e[n(735)]))clearTimeout(this[n(1477)+n(767)+n(393)]),this[n(1477)+n(767)+n(393)]=null;else return _0x215588+=_0x1fdc78&&_0x284e25.byteLength||0,_0x1b0033}[t(578)+"ngTimer"](){let n=t;e[n(1493)](clearTimeout,this[n(1186)+n(1288)+"Id"]),clearTimeout(this["_reconne"+n(898)+n(662)]),this[n(1186)+n(1288)+"Id"]=null,this[n(703)+n(898)+n(662)]=null}_debug(...n){let s=t;this._options[s(1019)]&&console.log.apply(console,[e[s(1450)],...n])}[t(519)+t(1410)+"e"](n){let s=t,{initReconnectInterval:d,maxReconnectInterval:h,reconnectIntervalGrowFactor:w}=this[s(803)],S=d*Math[s(914)](w,e[s(1731)](n,1));return e[s(426)](S,h)?h:S}[t(546)](){let n=t;if(this[n(512)]&&e.vCQAw(this[n(512)][n(958)+"te"],this[n(1652)+"NG"])){this[n(578)+n(1185)](),this[n(1186)+n(1288)+"Id"]=e.YfQgD(setTimeout,this[n(546)][n(1425)](this),this._options[n(1567)+n(1252)]);return}if(!this[n(512)]||this[n(512)].readyState!==this[n(1607)])return void this._handleReconnect();this[n(512)]&&this[n(512)].send("hi"),this["_reconne"+n(898)+"tId"]=e[n(1045)](setTimeout,this["_handleR"+n(996)+n(1008)].bind(this),this[n(803)][n(1404)+"outInterval"])}[t(1401)+t(996)+t(1008)](){let n=t;this[n(608)+n(868)]?.addCount(),this[n(1517)](e[n(1124)],e[n(515)]),this._pingLossCounter?.[n(1284)+n(871)+"nt"]()?this[n(1401)+n(996)]():this[n(546)]()}[t(355)+"orOnline"](){let n=t;return this[n(1203)+"T"]||this[n(870)+"X"]?this[n(446)+"igatorOnline"]:(this[n(1031)+"er"]||this[n(690)+"r"])&&this[n(803)]["listenNetworkCha"+n(439)]?navigator[n(1603)]:!0}[t(1401)+t(996)](){let n=t,s={ZsyTN:e[n(964)]};if(e.eKzzx(e[n(1585)],e[n(1585)])){if(!this._navigatorOnline()||this["_readyCl"+n(1163)])return;this[n(357)+n(720)]?.[n(1167)+n(1814)+n(646)](),this[n(608)+n(868)]?.["resetCou"+n(1675)](),this[n(512)]?this["_disconn"+n(848)](1001,e[n(586)],!0):this[n(1477)]()}else switch(_0x4a27ad){case fqozqh[n(1409)]:case n(1804):return{[n(944)+_0x106c82]:1,"x-tt-env":_0x2fbf39};default:return{}}}["_onPageN"+t(1352)+t(923)](){let n=t,s={eIYAO:"abort"};this._isMiniTT?tt[n(1692)+n(968)+n(1072)](({isConnected:d})=>{let h=n;this[h(446)+"igatorOn"+h(1389)]=d,d?this["_handleO"+h(993)]():this[h(1769)+h(1113)]()}):this[n(870)+"X"]&&wx[n(1692)+"kStatusC"+n(1072)](({isConnected:d})=>{let h=n;e[h(1456)](e[h(748)],h(716))?(this[h(446)+"igatorOn"+h(1389)]=d,d?this[h(1769)+h(993)]():this[h(1769)+h(1113)]()):(_0x2ff637[h(1435)+h(776)+"ner"](h(712),_0x5dcfcf),_0x34be31[h(1435)+h(776)+h(1260)](h(435),_0x2d7c64),_0x3ed0b9[h(1435)+h(776)+h(1260)](CdgTre[h(520)],_0x18d0ac))})}[t(436)](n){let s=t,d={fBfDf:function(h,w){return h===w},EHidX:e[s(526)],zFSdM:function(h,w,S){return e.ayKNC(h,w,S)}};return new Promise(h=>{let w=s;d[w(664)](d[w(1683)],d.EHidX)?d[w(1753)](setTimeout,h,this[w(519)+w(1410)+"e"](n)):_0x3ebda0[w(1140)](_0x3f05fc)})}[t(1196)+t(848)](n=1e3,s="",d=!1){let h=t,w={olTbG:function(S,E){return e[j(1026)](S,E)},EXVOV:function(S,E){return e[j(1547)](S,E)}};if(e[h(850)](e[h(1618)],e[h(1541)])){if(!this[h(512)])return;this[h(772)+h(1513)+"t"](n,s,d)}else AirJBL[h(943)](_0x22d585,this["_pingPon"+h(1288)+"Id"]),AirJBL[h(1407)](_0x4ee682,this[h(703)+h(898)+"tId"]),this[h(1186)+h(1288)+"Id"]=null,this[h(703)+h(898)+h(662)]=null}[t(1495)+"ut"](){let n=t,s=this[n(357)+n(720)]?.["getCurre"+n(990)+"nt"]();this[n(437)]("connect "+s+n(928)),this[n(1196)+n(848)](1001,e[n(711)],!0)}[t(1543)](n){let s=t,d=e[s(523)](Ft,n);this._ws&&this[s(512)][s(958)+"te"]===this[s(1607)]&&(this._ws&&this[s(512)][s(1223)](d),this[s(437)](e.RaFEb,n))}["_removeW"+t(831)+"rs"](){let n=t,s=e.IVbGl.split("|"),d=0;for(;;){switch(s[d++]){case"0":this[n(512)][n(1435)+n(776)+n(1260)](e.riCIj,this[n(1134)]);continue;case"1":this._ws[n(1435)+"entListe"+n(1260)](e[n(1018)],this[n(466)]);continue;case"2":this[n(512)][n(1435)+n(776)+n(1260)](e[n(1514)],this._onClose);continue;case"3":this[n(512)][n(1435)+"entListe"+n(1260)]("message",this[n(485)+"ge"]);continue;case"4":if(!this[n(512)])return;continue}break}}[t(499)+"steners"](){let n=t;if(e[n(580)](e[n(391)],e[n(391)])){let s=e[n(1677)][n(1721)]("|"),d=0;for(;;){switch(s[d++]){case"0":this._ws.addEventListener("error",this[n(466)]);continue;case"1":this[n(512)][n(1227)+n(1811)](e[n(836)],this[n(485)+"ge"]);continue;case"2":if(!this[n(512)])return;continue;case"3":this._ws[n(1227)+"Listener"](e[n(650)],this[n(1134)]);continue;case"4":this._ws["addEvent"+n(1811)](e[n(1514)],this._onClose);continue}break}}else{if(e.HihJD(_0x29e874,_0x5f4428)<1)return"";let s="";for(let d=_0x26c143;e[n(1312)](d,_0x431fbd);){let h=_0x333091[d++];if(h<=127)s+=_0x51ac27["fromChar"+n(859)](h);else if(e.HilTg(h,192)&&e.lYEHA(h,224))s+=_0x26ff0c[n(714)+n(859)](e[n(684)](e.nXNni(e[n(452)](31,h),6),e.NKcQo(63,_0x22eb51[d++])));else if(h>=224&&e[n(931)](h,240))s+=_0x2f4f4f[n(714)+n(859)](e.LeewP(e[n(1051)](e[n(1083)](e[n(1528)](15,h),12),(63&_0x522f7a[d++])<<6),e[n(1133)](63,_0x381b81[d++])));else if(e[n(1048)](h,240)){let w=e.DjhWR(e.REyVK(e.PKcJU(e.PMKas(7&h,18),e.ZHFIJ(63&_0x193797[d++],12))|e.FsqSN(e.SxMkd(63,_0x447bed[d++]),6),e[n(480)](63,_0x47440a[d++])),65536);s+=_0x3747c2[n(714)+n(859)](e[n(1169)](55296,e.mGnxT(w,10))),s+=_0x147248[n(714)+n(859)](56320+(1023&w))}}return s}}[t(350)+t(432)](n=1e3,s=""){let d=t;if(e[d(1046)]===e.NtzDb){let h=_0x29cad2[d(1502)](Tlunip[d(623)](_0x41a818,this),_0x4e1816,..._0x5ef680);return _0x2536d1[d(1796)](h,_0x1a2d5a[d(618)]?_0x2af214[d(618)]():[_0x572845]),Tlunip[d(1566)](_0x259b6b,h)}else try{this[d(512)]&&this[d(512)].close(n,s)}catch{}}[t(772)+t(1513)+"t"](n=1e3,s="",d=!1){let h=t,w={GkKVZ:function(S,E){return e[j(1165)](S,E)},gyCRb:function(S,E){return e.dyiDb(S,E)},JDrgl:function(S,E){return e.AtFVf(S,E)},btzZj:function(S,E){return e[j(1781)](S,E)},DwAZc:function(S,E){return e[j(1463)](S,E)}};if(this[h(578)+"ngTimer"](),this[h(1602)+h(595)](),this[h(860)+h(831)+"rs"](),this[h(350)+h(432)](1e3,s),this[h(1477)+"Lock"]=!1,d&&this[h(355)+h(1758)]()&&!this._readyClosed){if(this._endpointManager?.["checkRea"+h(1656)+"es"]()){let E=this[h(357)+h(720)]?.[h(596)+"ntEndpoint"]();this["_dispatchCloseEv"+h(1071)](mt(e[h(1514)],{code:1006,reason:h(1330)+E+(h(928)+h(718)+h(1506)+h(1540)),wasClean:!0}))}else if(e[h(1527)](e[h(699)],e[h(699)])){let E=0,g=0;for(let D=0;WvgfoF[h(1213)](D,_0xb0d8b.length);++D)g=_0x30a69d[h(895)+"At"](D),WvgfoF[h(1213)](g,128)?E+=1:WvgfoF.gyCRb(g,2048)?E+=2:WvgfoF.JDrgl(64512&g,55296)&&WvgfoF[h(1735)](WvgfoF[h(705)](64512,_0x1b1311[h(895)+"At"](WvgfoF[h(787)](D,1))),56320)?(++D,E+=4):E+=3;return E}else{let E=this._options[h(1068)+h(1035)+h(1686)](n,s);this[h(755)+h(1041)+h(1071)](e[h(1760)](mt,e.FeXiv,{code:n,reason:s,wasClean:!0,willReconnect:E})),E&&this[h(1477)]()}return}this[h(355)+"orOnline"]()||this[h(1702)+"osed"]?this[h(755)+h(1041)+h(1071)](e[h(1364)](mt,e.FeXiv,{code:n,reason:e.pobfH})):this[h(755)+"hCloseEv"+h(1071)](mt(h(532),{code:1006,reason:h(1081)+h(611)+h(857)+"ine"})),this[h(512)]=null,this._endpointManager?.[h(1167)+h(1814)+"fig"](),this[h(608)+h(868)]?.[h(647)+h(1675)]()}[t(755)+t(1296)+"nt"](n){let s=t;this[s(1517)](e[s(650)],n),this[s(1022)]&&this.onopen(n)}[t(755)+t(708)+t(823)](n){let s=t;e.nFsvH(e[s(979)],s(359))?(this[s(1517)](e[s(836)],n),this.onmessage&&this[s(862)+"e"](n)):_0x562302=Tlunip.IPEsQ(_0x400d7e,_0xc779b7)}[t(755)+t(881)+t(855)](n){let s=t;this[s(1517)](e[s(464)],n),this[s(1707)+s(1390)]&&this[s(1707)+s(1390)](n)}[t(755)+t(733)+t(1071)](n){let s=t;this[s(1517)](s(435),n),this[s(1461)]&&this.onerror(n)}[t(755)+"hCloseEv"+t(1071)](n){let s=t;this.emit(e.FeXiv,n),this[s(769)]&&this[s(769)](n)}get binaryType(){let n=t;return this[n(512)]?this._ws.binaryType:this["_binaryT"+n(980)]}set[t(1084)+"pe"](n){let s=t;this[s(721)+s(980)]=n,this[s(512)]&&(this._ws[s(1084)+"pe"]=n)}get retryCount(){let n=t,s={VZRZA:function(d,h,w){return e[j(1197)](d,h,w)},qyOPR:e[n(1018)]};if(e[n(784)](n(659),e.FeVbQ)){let d=EffrBt.VZRZA(_0x3b3789,EffrBt[n(470)],{message:_0x58ad63.message,code:_0x2365df[n(904)+"ERROR"],error:_0xe1e7d0});this[n(755)+n(733)+n(1071)](d)}else return this._endpointManager?.[n(596)+"ntEndpoi"+n(1073)+n(1004)]()||0}get["buffered"+t(1367)](){let n=t,s={yCGmS:function(d,h){return e[j(1824)](d,h)},HAgTo:function(d,h){return d<h}};if(e[n(1434)]("EZRMA",e.DEBXU)){if(llQQWh[n(445)](void 0,_0x4140d9))this[n(1821)+"rs"]={};else if(llQQWh[n(445)](void 0,_0xfbd65a))this[n(1821)+"rs"][_0x206175]=null;else{let d=this[n(1821)+"rs"][_0x4084cc];if(d)for(let h=0;llQQWh[n(1261)](h,d[n(1592)]);)d[h].fn===_0x20e1a8?d[n(1030)](h,1):++h}return this}else{let d=this[n(744)+"Queue"][n(524)]((h,w)=>(h+=w&&w[n(1578)+"th"]||0,h),0);return e[n(1395)](d,this[n(512)]?this._ws.bufferedAmount:0)}}get extensions(){let n=t;return this[n(512)]?this._ws[n(1282)+"ns"]:""}get[t(1317)](){let n=t;return this[n(512)]?this[n(512)].protocol:""}get readyState(){let n=t;return this._ws?this[n(512)][n(958)+"te"]:this._options[n(837)+"cOpen"]?this[n(1652)+"NG"]:this[n(1508)]}get[t(1347)](){let n=t;return this[n(512)]?this._ws[n(1347)]:this[n(1360)]}close(n=1e3,s){let d=t,h=(d(1125)+d(693))[d(1721)]("|"),w=0;for(;;){switch(h[w++]){case"0":this[d(896)+d(723)]?.[d(1121)]();continue;case"1":this[d(772)+"WebSocket"](n,s);continue;case"2":this[d(578)+"ngTimer"]();continue;case"3":if(!this[d(512)])return void this[d(437)](e[d(670)]);continue;case"4":this[d(1702)+"osed"]=!0;continue;case"5":this[d(447)+d(1807)+"Listener"]();continue;case"6":this[d(1602)+d(595)]();continue;case"7":if(e[d(409)](this[d(512)].readyState,this[d(1508)])||e[d(1574)](this[d(512)][d(958)+"te"],this[d(840)]))return void this[d(437)](e[d(460)]);continue}break}}async[t(1223)](n,s){let d=t;if(e.KZwQq(null,n))throw new Error(e[d(1265)]);e[d(1557)](e.qyCEp,typeof n)&&(n=JSON[d(1217)+"y"](n)),e[d(1006)](d(758),typeof n)&&!e[d(1634)](n,ArrayBuffer)&&!(n.buffer&&e[d(474)](n[d(858)],ArrayBuffer))&&(n=JSON.stringify(n));let h=await wd(n),w=Jp(n),{method:S=0,service:E=this[d(803)].service,logID:g=this[d(803)][d(1348)+d(844)](),headers:D=this[d(803)][d(1433)],payloadEncoding:L=this[d(803)]["payloadE"+d(1621)],payloadType:B=this[d(803)][d(518)+"ype"],logIDNew:W=this[d(803)][d(1535)+d(590)]["enableAu"+d(1596)+d(1658)+"ew"]?e[d(897)](i,this._options["logIDNew"+d(590)][d(544)]):""}=e[d(1610)](s,{});if(!E)throw new Error(e[d(1294)]);let X={SeqID:he[d(1553)+"er"](this[d(1210)]++),LogID:he[d(1553)+"er"](g),service:E,method:S,headers:D,payloadEncoding:e[d(1634)](L,Object)?L[d(1790)]?L.encoding:"":L,payloadType:e.omQtP(B,Object)?B[d(457)]?B[d(457)]:w:B||w,payload:h,LogIDNew:W},re=Ft(X);return this._ws&&e[d(597)](this._ws[d(958)+"te"],this[d(1607)])?(this[d(512)]&&this[d(512)].send(re),this[d(437)](e[d(812)],X)):e[d(1452)](this[d(744)+d(1024)].length,this[d(803)][d(1757)+d(507)+d(683)])?(this[d(744)+d(1024)][d(1140)](re),this[d(437)](e[d(1626)],X)):(this[d(744)+d(1024)][d(1230)](),this[d(744)+"Queue"][d(1140)](re)),{seqID:this[d(1210)],logID:g,logIDNew:W}}async[t(1068)+"t"](n){let s=t,{url:d}=e[s(905)](n,{}),h=Array[s(1464)](d)?d:s(758)==typeof d?[d]:[];n&&Object[s(1156)](this._options,n),h&&h.length?this._endpointManager=new xd(h,this._options[s(946)+"es"]):this["_endpoin"+s(720)]?.[s(1167)+s(1814)+s(646)](),this[s(608)+s(868)]?.[s(647)+s(1675)](this[s(803)][s(455)+s(490)]),this["_readyCl"+s(1163)]=!1,this[s(512)]&&e[s(967)](this[s(512)][s(958)+"te"],this.CLOSED)?this[s(1196)+"ect"](1e3,e[s(1306)],!0):(this[s(1732)]=!0,this._connect())}async[t(1722)](){let n=t;e[n(1369)](n(1813),n(1813))?(e.SVgBQ(_0x6b8dcc,_0x26dfa6,10),e[n(395)](_0x335a19,_0x2b71e5,_0x4e8c9f)):!this._connectLock&&(e.OQSze!=="JNWni"?this.count++:(this[n(357)+n(720)]?.[n(1167)+n(1814)+n(646)](),this[n(608)+n(868)]?.[n(647)+n(1675)](),this["_readyCl"+n(1163)]=!1,this._isInit=!0,this._connect()))}[t(1227)+t(1811)](n,s){let d=t;if(e[d(549)]("CbPfv",e[d(1779)]))this.on(n,s);else{let h=e[d(1009)](this._options[d(819)+d(1621)],_0xf9c045)?{force:!!this[d(803)][d(819)+d(1621)][d(917)],encoding:this[d(803)][d(819)+d(1621)].encoding?this[d(803)][d(819)+d(1621)][d(1790)][d(484)](/\s/g,"")[d(861)+d(1025)]():""}:{force:!1,encoding:this[d(803)]["payloadE"+d(1621)]?this[d(803)][d(819)+"ncoding"].replace(/\s/g,"")[d(861)+d(1025)]():""},w=_0x3a684e[d(819)+d(1621)]?_0xd05217[d(819)+d(1621)].replace(/\s/g,"")["toLowerC"+d(1025)]():"",S=e.CBxMX(this._options[d(518)+"ype"],_0x41fc84)?{force:!!this[d(803)][d(518)+"ype"][d(917)],type:this[d(803)][d(518)+"ype"][d(457)]?this._options[d(518)+d(980)][d(457)][d(484)](/\s/g,"")[d(861)+"ase"]():""}:{force:!1,type:this[d(803)][d(518)+d(980)]?this[d(803)][d(518)+d(980)][d(484)](/\s/g,"")[d(861)+"ase"]():""},E=_0x1e63d4[d(518)+d(980)]?_0x455355[d(518)+d(980)][d(484)](/\s/g,"").toLowerCase():"",g=S.force?S[d(457)]:E||S[d(457)],D=h.force?h[d(1790)]:w||h[d(1790)],L=[e[d(851)],e[d(1399)],e[d(1403)],"string"],B=[e[d(506)],e[d(907)]];this[d(803)]["enableTr"+d(1350)+"extPayload"]&&L[d(1812)](g)&&(!D||B[d(1812)](D))?_0x58b6e9["textPayl"+d(1010)]=e[d(585)](_0xb43f49,_0x27507c[d(888)],0,_0x2fa876[d(888)].byteLength):_0xae81e[d(1357)+d(1010)]=""}}[t(814)+"Event"](n){let s=t,{type:d}=n;this[s(1517)](d,n)}["removeEv"+t(776)+"ner"](n,s){this[t(349)](n,s)}pingOnce(){return new Promise((n,s)=>{let d=j,h={cKlBr:function(E,g){return e.xsccc(E,g)},xNPma:function(E,g){return e[j(702)](E,g)},rCCUn:e[d(1764)],OKmjT:function(E,g){return e.yWAfK(E,g)},HoBHV:e[d(632)],gmvsI:e[d(1076)],FIcqE:"timeout",GBqRl:e[d(1124)]};this["_clearPi"+d(1185)](),this[d(1186)+d(1288)+"Id"]=setTimeout(this[d(546)][d(1425)](this),this[d(803)][d(1567)+"rval"]);let w=()=>{let E=d,g={ixwZB:function(D,L){return h[j(1277)](D,L)},rxkro:function(D,L){return h[j(1011)](D,L)}};if(h[E(1594)]!==E(1372))h[E(408)](n,h[E(635)]),this[E(349)](h.gmvsI,w),this.off(E(1304)+E(377)+"t",S);else{let{value:D,offset:L}=_0x14f4a3(_0x4c4eb1,_0x24b8cc);_0x32ac86=L,_0x90a8d4=vRaQHw[E(1810)](vRaQHw[E(1439)](_0xfbe9aa,8),0),_0x423b6c+=D}},S=()=>{let E=d;s(h[E(562)]),this[E(349)](h.gmvsI,w),this[E(349)](h[E(774)],S)};this.on(e.nLytJ,w),this.on(d(1304)+d(377)+"t",S),this[d(546)]()})}}})(),Me[N(1351)+"oseEvent"]=Pe["CustomCl"+N(376)],Me[N(1353)+N(1180)]=Pe["CustomEr"+N(1180)],Me[N(488)+"e"]=Pe[N(488)+"e"],Me[N(823)]=Pe[N(823)],Me[N(1359)]=Pe[N(1359)],Me[N(564)+N(345)+N(1276)]=Pe[N(564)+N(345)+"vent"],Me[N(345)+N(1276)]=Pe["MessageE"+N(1276)],Me[N(1190)+"t"]=Pe[N(1190)+"t"],Me["Reconnec"+N(1703)]=Pe[N(938)+N(1703)],Me[N(960)+"oseEvent"]=Pe.createCloseEvent,Me["createEr"+N(1180)]=Pe[N(743)+N(1180)],Me[N(558)+N(887)+"nt"]=Pe[N(558)+N(887)+"nt"],Me[N(501)+N(410)]=Pe[N(501)+"enEvent"],Me[N(1424)+N(1512)+N(1276)]=Pe[N(1424)+N(1512)+"vent"],Me[N(382)+N(1825)]=Pe[N(382)+"rame"],Me[N(616)+N(1216)]=Pe["encodeFr"+N(1216)];for(Vo in Pe)[N(1351)+"oseEvent",N(1353)+"rorEvent",N(488)+"e",N(823),N(1359),"Frontier"+N(345)+"vent","MessageE"+N(1276),N(1190)+"t",N(938)+"tEvent",N(960)+N(376),N(743)+"rorEvent",N(558)+N(887)+"nt",N(501)+N(410),N(1424)+N(1512)+N(1276),"decodedF"+N(1825),N(616)+N(1216)][N(1391)](Vo)===-1&&(Me[Vo]=Pe[Vo]);var Vo;Object.defineProperty(Me,N(1249)+"le",{value:!0})});import{existsSync as HS,openSync as GS}from"node:fs";import{mkdir as qS}from"node:fs/promises";import{dirname as jS}from"node:path";import{fileURLToPath as WS}from"node:url";function $S(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Kl(t=J()){return HS(t.libEntry)?t.libEntry:WS(new URL("../index.ts",import.meta.url))}async function op(t={}){let e=t.paths??J(),r=t.entryOverride??Kl(e),i=$S(e,process.env.COZE_BRIDGE_LOG_MODE);await qS(jS(i),{recursive:!0});let o=GS(i,"a"),l=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=rt(process.execPath,l,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[cs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return KS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var KS,cs,sa=et(()=>{"use strict";Vt();te();Ce();KS=H("spawn-daemon"),cs="COZE_BRIDGE_DAEMON"});import{spawn as H1}from"node:child_process";import{mkdir as G1,unlink as q1,writeFile as j1}from"node:fs/promises";import{dirname as W1,join as K1}from"node:path";function Jr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function $1(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Jr(r)}</key>
21
+ <string>${Jr(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function BS(t,e){return new Promise((n,i)=>{let s=CS(t,e,{stdio:["ignore","pipe","pipe"]}),c="";s.stderr?.on("data",d=>{c+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var Vr,os,sa,Jd,pp=Qe(()=>{"use strict";ne();Vr=H("supervisor.launchd"),os="ai.coze.bridge",sa=BS,Jd={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function V1(t,e){return new Promise((r,i)=>{let o=H1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var Vr,ds,fa,td,Ap=et(()=>{"use strict";te();Vr=H("supervisor.launchd"),ds="ai.coze.bridge",fa=V1,td={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>${os}</string>
31
+ <string>${ds}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Yr(t.nodeBin)}</string>
35
- <string>${Yr(t.entry)}</string>
34
+ <string>${Jr(t.nodeBin)}</string>
35
+ <string>${Jr(t.entry)}</string>
36
36
  <string>--daemon</string>
37
37
  </array>
38
38
  <key>RunAtLoad</key>
@@ -42,13 +42,13 @@ ${e}
42
42
  <key>ThrottleInterval</key>
43
43
  <integer>10</integer>
44
44
  <key>StandardOutPath</key>
45
- <string>${Yr(t.logFile)}</string>
45
+ <string>${Jr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Yr(t.logFile)}</string>${MS(t.env)}
47
+ <string>${Jr(t.logFile)}</string>${$1(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return NS(t.homeDir,"Library","LaunchAgents",`${os}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await PS(LS(i),{recursive:!0}),await OS(i,this.renderConfig(t),"utf8"),Vr.info("plist written",{plistPath:i,activate:n}),!n)return;await sa("launchctl",["unload","-w",i]).catch(c=>Vr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await sa("launchctl",["load","-w",i]),Vr.info("launchd job loaded",{label:os});let s=process.getuid?.()??0;await sa("launchctl",["kickstart","-k",`gui/${s}/${os}`]),Vr.info("launchd job kickstarted",{label:os,uid:s})},async uninstall(t){let e=this.configPath(t);await sa("launchctl",["unload","-w",e]).catch(n=>Vr.warn("launchctl unload failed (ignored)",{err:String(n)})),await DS(e).catch(n=>{if(n.code!=="ENOENT")throw n}),Vr.info("launchd job removed",{plistPath:e})}}});import{spawn as FS}from"node:child_process";import{mkdir as zS,unlink as US,writeFile as GS}from"node:fs/promises";import{dirname as qS,join as gp}from"node:path";function aa(t,e){return t.isRoot?e:["--user",...e]}function jS(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function ca(t,e){return new Promise((n,i)=>{let s=FS(t,e,{stdio:["ignore","pipe","pipe"]}),c="";s.stderr?.on("data",d=>{c+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var oa,Jr,HS,Zd,mp=Qe(()=>{"use strict";ne();oa=H("supervisor.systemd"),Jr="coze-bridge.service",HS="/etc/systemd/system";Zd={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return K1(t.homeDir,"Library","LaunchAgents",`${ds}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await G1(W1(i),{recursive:!0}),await j1(i,this.renderConfig(t),"utf8"),Vr.info("plist written",{plistPath:i,activate:r}),!r)return;await fa("launchctl",["unload","-w",i]).catch(c=>Vr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await fa("launchctl",["load","-w",i]),Vr.info("launchd job loaded",{label:ds});let o=process.getuid?.()??0;await fa("launchctl",["kickstart","-k",`gui/${o}/${ds}`]),Vr.info("launchd job kickstarted",{label:ds,uid:o})},async uninstall(t){let e=this.configPath(t);await fa("launchctl",["unload","-w",e]).catch(r=>Vr.warn("launchctl unload failed (ignored)",{err:String(r)})),await q1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Vr.info("launchd job removed",{plistPath:e})}}});import{spawn as J1}from"node:child_process";import{mkdir as Z1,unlink as Y1,writeFile as X1}from"node:fs/promises";import{dirname as Q1,join as Tp}from"node:path";function xa(t,e){return t.isRoot?e:["--user",...e]}function tI(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function pa(t,e){return new Promise((r,i)=>{let o=J1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var ha,Zr,eI,nd,kp=et(()=>{"use strict";te();ha=H("supervisor.systemd"),Zr="coze-bridge.service",eI="/etc/systemd/system";nd={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
- ${jS(t.env)}
62
+ ${tI(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?gp(HS,Jr):gp(t.homeDir,".config","systemd","user",Jr)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),s=t.isRoot?"system":"user";await zS(qS(i),{recursive:!0}),await GS(i,this.renderConfig(t),"utf8"),oa.info("systemd unit written",{unitPath:i,mode:s,activate:n}),await ca("systemctl",aa(t,["daemon-reload"])),await ca("systemctl",aa(t,n?["enable","--now",Jr]:["enable",Jr])),oa.info("systemd unit enabled",{unitName:Jr,mode:s,activate:n})},async uninstall(t){let e=this.configPath(t);await ca("systemctl",aa(t,["disable","--now",Jr])).catch(n=>oa.warn("systemctl disable failed (ignored)",{err:String(n)})),await US(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await ca("systemctl",aa(t,["daemon-reload"])).catch(()=>{}),oa.info("systemd unit removed",{unitPath:e})}}});import{spawn as WS}from"node:child_process";import{join as KS}from"node:path";function wp(t,e){return new Promise((n,i)=>{let s=WS(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";s.stderr?.on("data",d=>{c+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var Xd,da,Qd,_p=Qe(()=>{"use strict";ne();Xd=H("supervisor.taskscheduler"),da="CozeBridge",Qd={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Tp(eI,Zr):Tp(t.homeDir,".config","systemd","user",Zr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await Z1(Q1(i),{recursive:!0}),await X1(i,this.renderConfig(t),"utf8"),ha.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await pa("systemctl",xa(t,["daemon-reload"])),await pa("systemctl",xa(t,r?["enable","--now",Zr]:["enable",Zr])),ha.info("systemd unit enabled",{unitName:Zr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await pa("systemctl",xa(t,["disable","--now",Zr])).catch(r=>ha.warn("systemctl disable failed (ignored)",{err:String(r)})),await Y1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await pa("systemctl",xa(t,["daemon-reload"])).catch(()=>{}),ha.info("systemd unit removed",{unitPath:e})}}});import{spawn as nI}from"node:child_process";import{join as rI}from"node:path";function Cp(t,e){return new Promise((r,i)=>{let o=nI(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var rd,ga,id,Rp=et(()=>{"use strict";te();rd=H("supervisor.taskscheduler"),ga="CozeBridge",id={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
66
66
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
67
67
  <RegistrationInfo>
68
68
  <Description>Coze Bridge daemon</Description>
@@ -86,50 +86,52 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return KS(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 wp("schtasks",["/Create","/SC","ONLOGON","/TN",da,"/TR",n,"/RU",t.userName,"/F"]),Xd.info("task scheduler entry created",{task:da,logFile:t.logFile})},async uninstall(t){await wp("schtasks",["/Delete","/TN",da,"/F"]).catch(e=>Xd.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Xd.info("task scheduler entry removed",{task:da})}}});var yp={};va(yp,{buildContext:()=>XS,getSupervisor:()=>YS,launchdSupervisor:()=>Jd,systemdSupervisor:()=>Zd,taskSchedulerSupervisor:()=>Qd});import{homedir as $S,userInfo as VS}from"node:os";function YS(t=process.platform){switch(t){case"darwin":return Jd;case"linux":return Zd;case"win32":return Qd;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function ZS(){let t={};for(let e of JS){let n=process.env[e];n&&(t[e]=n)}return t}function XS(){let t=ee();return{nodeBin:process.execPath,entry:Ud(t),logFile:t.logFile,homeDir:$S(),userName:VS().username,isRoot:process.getuid?.()===0,env:ZS()}}var JS,Ep=Qe(()=>{"use strict";Le();Qo();pp();mp();_p();JS=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();on();var Pl=H("acp-installer-warmup"),Yg=["claude-code","codex"];async function Dl(t={}){let e=t.ensure??cr,i=(await Promise.allSettled(Yg.map(async s=>{let c=await e(s);Pl.info("acp wrapper warmup ok",{framework:s,path:c})}))).filter(s=>s.status==="rejected");i.length>0&&Pl.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(s=>s.reason instanceof Error?s.reason.message:String(s.reason))})}dn();ne();import{readdir as um}from"node:fs/promises";import{mkdir as Ml,readFile as dm,writeFile as Bl}from"node:fs/promises";import{join as Ca}from"node:path";var lm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function ur(t,e,n){await Ml(t,{recursive:!0});let i=lm[e],s=Ca(t,i);return await Bl(s,n??"","utf8"),s}async function Pa(t,e,n){let i=Ca(t,".claude");await Ml(i,{recursive:!0});let s=Ca(i,"settings.local.json"),c={};try{let u=await dm(s,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(c=h)}catch{}let d=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return c.permissions=d,await Bl(s,JSON.stringify(c,null,2),"utf8"),s}var Ye=H("agent-detail-sync"),fm=6e4,hm=5*6e4,ms=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await um(n)}catch(s){Ye.info("agents dir not found, skip detail sync",{root:n,err:String(s)});return}Ye.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async s=>{let c=await Te(s,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Ye.debug("detail sync: skip disconnected agent",{agentId:s});return}try{await this.syncOne(s,c)}catch(d){Ye.warn("detail sync failed for agent, skipping",{agentId:s,err:String(d)})}}})),Ye.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,s]of this.retryQueue)e>=s.dueAt&&n.push(i);if(n.length!==0){Ye.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(s){Ye.debug("detail sync retry still failing, will try again",{agentId:i,err:String(s)})}}}async syncOne(e,n){let i=n??await Te(e,this.opts.paths);if(!i){Ye.info("detail sync: agent config missing, skip",{agentId:e});return}let s;try{s=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(h){Ye.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),g=x?Math.min(x.currentDelay*2,hm):fm;this.retryQueue.set(e,{dueAt:Date.now()+g,currentDelay:g});return}if(s.agentId&&s.agentId!==e){Ye.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:s.agentId});return}let c=!1,d=!1;s.agentName&&s.agentName!==i.agentName&&(i.agentName=s.agentName,c=!0),s.description!==void 0&&s.description!==i.description&&(i.description=s.description,c=!0),s.cozeIdentity&&s.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=s.cozeIdentity,c=!0,d=!0);let u=!1;if(s.deployType==="cloud"&&i.deployType!=="cloud"?(Ye.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):s.deployType&&Ye.info("detail.deployType",{agentId:e,deployType:s.deployType}),!c){Ye.debug("detail sync: no diff",{agentId:e});return}await Be(i,this.opts.paths),Ye.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Ye.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await ur(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var ed=Gt(gu(),1);import{createHash as $_}from"node:crypto";import{lstat as $c,mkdir as Vc,readFile as lo,readdir as t0,rm as Yc,stat as n0,writeFile as Jc}from"node:fs/promises";import{homedir as V_}from"node:os";import{dirname as Y_,join as me,normalize as J_,relative as Qc,resolve as Zc,sep as r0}from"node:path";import{Readable as i0}from"node:stream";import{pipeline as s0}from"node:stream/promises";import Nm from"events";import et from"fs";import{EventEmitter as Cc}from"node:events";import Zu from"node:stream";import{StringDecoder as Mm}from"node:string_decoder";import ef from"node:path";import vr from"node:fs";import{dirname as Ym,parse as Jm}from"path";import{EventEmitter as iw}from"events";import uc from"assert";import{Buffer as Hn}from"buffer";import*as Eu from"zlib";import sw from"zlib";import{posix as gr}from"node:path";import{basename as Dw}from"node:path";import Ys from"fs";import Rt from"fs";import Tu from"path";import{win32 as jw}from"node:path";import Nu from"path";import gf from"node:fs";import a_ from"node:assert";import{randomBytes as mf}from"node:crypto";import ie from"node:fs";import Me from"node:path";import wf from"fs";import io from"node:fs";import Si from"node:path";import st from"node:fs";import x_ from"node:fs/promises";import Xs from"node:path";import{join as Rf}from"node:path";import it from"node:fs";import Df from"node:path";var Om=Object.defineProperty,Lm=(t,e)=>{for(var n in e)Om(t,n,{get:e[n],enumerable:!0})},mu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Bm=t=>!!t&&typeof t=="object"&&(t instanceof Kn||t instanceof Zu||Fm(t)||zm(t)),Fm=t=>!!t&&typeof t=="object"&&t instanceof Cc&&typeof t.pipe=="function"&&t.pipe!==Zu.Writable.prototype.pipe,zm=t=>!!t&&typeof t=="object"&&t instanceof Cc&&typeof t.write=="function"&&typeof t.end=="function",qt=Symbol("EOF"),Ht=Symbol("maybeEmitEnd"),un=Symbol("emittedEnd"),bs=Symbol("emittingEnd"),ai=Symbol("emittedError"),vs=Symbol("closed"),wu=Symbol("read"),Ss=Symbol("flush"),_u=Symbol("flushChunk"),mt=Symbol("encoding"),pr=Symbol("decoder"),Fe=Symbol("flowing"),ci=Symbol("paused"),yr=Symbol("resume"),ze=Symbol("buffer"),Je=Symbol("pipes"),Ue=Symbol("bufferLength"),Ba=Symbol("bufferPush"),Is=Symbol("bufferShift"),Ve=Symbol("objectMode"),Ie=Symbol("destroyed"),Fa=Symbol("error"),za=Symbol("emitData"),yu=Symbol("emitEnd"),Ua=Symbol("emitEnd2"),At=Symbol("async"),Ga=Symbol("abort"),As=Symbol("aborted"),di=Symbol("signal"),Ln=Symbol("dataListeners"),rt=Symbol("discarded"),li=t=>Promise.resolve().then(t),Um=t=>t(),Gm=t=>t==="end"||t==="finish"||t==="prefinish",qm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Hm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Xu=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[yr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},jm=class extends Xu{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)}},Wm=t=>!!t.objectMode,Km=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Kn=class extends Cc{[Fe]=!1;[ci]=!1;[Je]=[];[ze]=[];[Ve];[mt];[At];[pr];[qt]=!1;[un]=!1;[bs]=!1;[vs]=!1;[ai]=null;[Ue]=0;[Ie]=!1;[di];[As]=!1;[Ln]=0;[rt]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Wm(e)?(this[Ve]=!0,this[mt]=null):Km(e)?(this[mt]=e.encoding,this[Ve]=!1):(this[Ve]=!1,this[mt]=null),this[At]=!!e.async,this[pr]=this[mt]?new Mm(this[mt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[ze]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Je]});let{signal:n}=e;n&&(this[di]=n,n.aborted?this[Ga]():n.addEventListener("abort",()=>this[Ga]()))}get bufferLength(){return this[Ue]}get encoding(){return this[mt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ve]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[At]}set async(t){this[At]=this[At]||!!t}[Ga](){this[As]=!0,this.emit("abort",this[di]?.reason),this.destroy(this[di]?.reason)}get aborted(){return this[As]}set aborted(t){}write(t,e,n){if(this[As])return!1;if(this[qt])throw new Error("write after end");if(this[Ie])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[At]?li:Um;if(!this[Ve]&&!Buffer.isBuffer(t)){if(Hm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(qm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ve]?(this[Fe]&&this[Ue]!==0&&this[Ss](!0),this[Fe]?this.emit("data",t):this[Ba](t),this[Ue]!==0&&this.emit("readable"),n&&i(n),this[Fe]):t.length?(typeof t=="string"&&!(e===this[mt]&&!this[pr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[mt]&&(t=this[pr].write(t)),this[Fe]&&this[Ue]!==0&&this[Ss](!0),this[Fe]?this.emit("data",t):this[Ba](t),this[Ue]!==0&&this.emit("readable"),n&&i(n),this[Fe]):(this[Ue]!==0&&this.emit("readable"),n&&i(n),this[Fe])}read(t){if(this[Ie])return null;if(this[rt]=!1,this[Ue]===0||t===0||t&&t>this[Ue])return this[Ht](),null;this[Ve]&&(t=null),this[ze].length>1&&!this[Ve]&&(this[ze]=[this[mt]?this[ze].join(""):Buffer.concat(this[ze],this[Ue])]);let e=this[wu](t||null,this[ze][0]);return this[Ht](),e}[wu](t,e){if(this[Ve])this[Is]();else{let n=e;t===n.length||t===null?this[Is]():typeof n=="string"?(this[ze][0]=n.slice(t),e=n.slice(0,t),this[Ue]-=t):(this[ze][0]=n.subarray(t),e=n.subarray(0,t),this[Ue]-=t)}return this.emit("data",e),!this[ze].length&&!this[qt]&&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[qt]=!0,this.writable=!1,(this[Fe]||!this[ci])&&this[Ht](),this}[yr](){this[Ie]||(!this[Ln]&&!this[Je].length&&(this[rt]=!0),this[ci]=!1,this[Fe]=!0,this.emit("resume"),this[ze].length?this[Ss]():this[qt]?this[Ht]():this.emit("drain"))}resume(){return this[yr]()}pause(){this[Fe]=!1,this[ci]=!0,this[rt]=!1}get destroyed(){return this[Ie]}get flowing(){return this[Fe]}get paused(){return this[ci]}[Ba](t){this[Ve]?this[Ue]+=1:this[Ue]+=t.length,this[ze].push(t)}[Is](){return this[Ve]?this[Ue]-=1:this[Ue]-=this[ze][0].length,this[ze].shift()}[Ss](t=!1){do;while(this[_u](this[Is]())&&this[ze].length);!t&&!this[ze].length&&!this[qt]&&this.emit("drain")}[_u](t){return this.emit("data",t),this[Fe]}pipe(t,e){if(this[Ie])return t;this[rt]=!1;let n=this[un];return e=e||{},t===mu.stdout||t===mu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[Je].push(e.proxyErrors?new jm(this,t,e):new Xu(this,t,e)),this[At]?li(()=>this[yr]()):this[yr]()),t}unpipe(t){let e=this[Je].find(n=>n.dest===t);e&&(this[Je].length===1?(this[Fe]&&this[Ln]===0&&(this[Fe]=!1),this[Je]=[]):this[Je].splice(this[Je].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[rt]=!1,this[Ln]++,!this[Je].length&&!this[Fe]&&this[yr]();else if(t==="readable"&&this[Ue]!==0)super.emit("readable");else if(Gm(t)&&this[un])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ai]){let i=e;this[At]?li(()=>i.call(this,this[ai])):i.call(this,this[ai])}return 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[rt]&&!this[Je].length&&(this[Fe]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[rt]&&!this[Je].length&&(this[Fe]=!1)),e}get emittedEnd(){return this[un]}[Ht](){!this[bs]&&!this[un]&&!this[Ie]&&this[ze].length===0&&this[qt]&&(this[bs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[vs]&&this.emit("close"),this[bs]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Ie&&this[Ie])return!1;if(t==="data")return!this[Ve]&&!n?!1:this[At]?(li(()=>this[za](n)),!0):this[za](n);if(t==="end")return this[yu]();if(t==="close"){if(this[vs]=!0,!this[un]&&!this[Ie])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(t==="error"){this[ai]=n,super.emit(Fa,n);let s=!this[di]||this.listeners("error").length?super.emit("error",n):!1;return this[Ht](),s}else if(t==="resume"){let s=super.emit("resume");return this[Ht](),s}else if(t==="finish"||t==="prefinish"){let s=super.emit(t);return this.removeAllListeners(t),s}let i=super.emit(t,...e);return this[Ht](),i}[za](t){for(let n of this[Je])n.dest.write(t)===!1&&this.pause();let e=this[rt]?!1:super.emit("data",t);return this[Ht](),e}[yu](){return this[un]?!1:(this[un]=!0,this.readable=!1,this[At]?(li(()=>this[Ua]()),!0):this[Ua]())}[Ua](){if(this[pr]){let e=this[pr].end();if(e){for(let n of this[Je])n.dest.write(e);this[rt]||super.emit("data",e)}}for(let e of this[Je])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ve]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Ve]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Ve])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[mt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Ie,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[rt]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[qt])return e();let i,s,c=x=>{this.off("data",d),this.off("end",u),this.off(Ie,h),e(),s(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(Ie,h),this.pause(),i({value:x,done:!!this[qt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Ie,h),e(),i({done:!0,value:void 0})},h=()=>c(new Error("stream destroyed"));return new Promise((x,g)=>{s=g,i=x,this.once(Ie,h),this.once("error",c),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[rt]=!1;let t=!1,e=()=>(this.pause(),this.off(Fa,e),this.off(Ie,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(Fa,e),this.once(Ie,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Ie])return t?this.emit("error",t):this.emit(Ie),this;this[Ie]=!0,this[rt]=!0,this[ze].length=0,this[Ue]=0;let e=this;return typeof e.close=="function"&&!this[vs]&&e.close(),t?this.emit("error",t):this.emit(Ie),this}static get isStream(){return Bm}},$m=et.writev,En=Symbol("_autoClose"),Et=Symbol("_close"),ui=Symbol("_ended"),de=Symbol("_fd"),qa=Symbol("_finished"),$t=Symbol("_flags"),Ha=Symbol("_flush"),dc=Symbol("_handleChunk"),lc=Symbol("_makeBuf"),bi=Symbol("_mode"),ks=Symbol("_needDrain"),Ir=Symbol("_onerror"),Ar=Symbol("_onopen"),ja=Symbol("_onread"),Er=Symbol("_onwrite"),bn=Symbol("_open"),yt=Symbol("_path"),gn=Symbol("_pos"),kt=Symbol("_queue"),br=Symbol("_read"),Wa=Symbol("_readSize"),Kt=Symbol("_reading"),fi=Symbol("_remain"),Ka=Symbol("_size"),Bs=Symbol("_write"),Nn=Symbol("_writing"),Fs=Symbol("_defaultFlag"),qn=Symbol("_errored"),Pc=class extends Kn{[qn]=!1;[de];[yt];[Wa];[Kt]=!1;[Ka];[fi];[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[qn]=!1,this[de]=typeof e.fd=="number"?e.fd:void 0,this[yt]=t,this[Wa]=e.readSize||16*1024*1024,this[Kt]=!1,this[Ka]=typeof e.size=="number"?e.size:1/0,this[fi]=this[Ka],this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[de]=="number"?this[br]():this[bn]()}get fd(){return this[de]}get path(){return this[yt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[bn](){et.open(this[yt],"r",(t,e)=>this[Ar](t,e))}[Ar](t,e){t?this[Ir](t):(this[de]=e,this.emit("open",e),this[br]())}[lc](){return Buffer.allocUnsafe(Math.min(this[Wa],this[fi]))}[br](){if(!this[Kt]){this[Kt]=!0;let t=this[lc]();if(t.length===0)return process.nextTick(()=>this[ja](null,0,t));et.read(this[de],t,0,t.length,null,(e,n,i)=>this[ja](e,n,i))}}[ja](t,e,n){this[Kt]=!1,t?this[Ir](t):this[dc](e,n)&&this[br]()}[Et](){if(this[En]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ir](t){this[Kt]=!0,this[Et](),this.emit("error",t)}[dc](t,e){let n=!1;return this[fi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[fi]<=0)&&(n=!1,this[Et](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[de]=="number"&&this[br](),!1;case"error":return this[qn]?!1:(this[qn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Vm=class extends Pc{[bn](){let t=!0;try{this[Ar](null,et.openSync(this[yt],"r")),t=!1}finally{t&&this[Et]()}}[br](){let t=!0;try{if(!this[Kt]){this[Kt]=!0;do{let e=this[lc](),n=e.length===0?0:et.readSync(this[de],e,0,e.length,null);if(!this[dc](n,e))break}while(!0);this[Kt]=!1}t=!1}finally{t&&this[Et]()}}[Et](){if(this[En]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.closeSync(t),this.emit("close")}}},Qs=class extends Nm{readable=!1;writable=!0;[qn]=!1;[Nn]=!1;[ui]=!1;[kt]=[];[ks]=!1;[yt];[bi];[En];[de];[Fs];[$t];[qa]=!1;[gn];constructor(t,e){e=e||{},super(e),this[yt]=t,this[de]=typeof e.fd=="number"?e.fd:void 0,this[bi]=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[Fs]=e.flags===void 0,this[$t]=e.flags===void 0?n:e.flags,this[de]===void 0&&this[bn]()}emit(t,...e){if(t==="error"){if(this[qn])return!1;this[qn]=!0}return super.emit(t,...e)}get fd(){return this[de]}get path(){return this[yt]}[Ir](t){this[Et](),this[Nn]=!0,this.emit("error",t)}[bn](){et.open(this[yt],this[$t],this[bi],(t,e)=>this[Ar](t,e))}[Ar](t,e){this[Fs]&&this[$t]==="r+"&&t&&t.code==="ENOENT"?(this[$t]="w",this[bn]()):t?this[Ir](t):(this[de]=e,this.emit("open",e),this[Nn]||this[Ha]())}end(t,e){return t&&this.write(t,e),this[ui]=!0,!this[Nn]&&!this[kt].length&&typeof this[de]=="number"&&this[Er](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[ui]?(this.emit("error",new Error("write() after end()")),!1):this[de]===void 0||this[Nn]||this[kt].length?(this[kt].push(t),this[ks]=!0,!1):(this[Nn]=!0,this[Bs](t),!0)}[Bs](t){et.write(this[de],t,0,t.length,this[gn],(e,n)=>this[Er](e,n))}[Er](t,e){t?this[Ir](t):(this[gn]!==void 0&&typeof e=="number"&&(this[gn]+=e),this[kt].length?this[Ha]():(this[Nn]=!1,this[ui]&&!this[qa]?(this[qa]=!0,this[Et](),this.emit("finish")):this[ks]&&(this[ks]=!1,this.emit("drain"))))}[Ha](){if(this[kt].length===0)this[ui]&&this[Er](null,0);else if(this[kt].length===1)this[Bs](this[kt].pop());else{let t=this[kt];this[kt]=[],$m(this[de],t,this[gn],(e,n)=>this[Er](e,n))}}[Et](){if(this[En]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Qu=class extends Qs{[bn](){let t;if(this[Fs]&&this[$t]==="r+")try{t=et.openSync(this[yt],this[$t],this[bi])}catch(e){if(e?.code==="ENOENT")return this[$t]="w",this[bn]();throw e}else t=et.openSync(this[yt],this[$t],this[bi]);this[Ar](null,t)}[Et](){if(this[En]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.closeSync(t),this.emit("close")}}[Bs](t){let e=!0;try{this[Er](null,et.writeSync(this[de],t,0,t.length,this[gn])),e=!1}finally{if(e)try{this[Et]()}catch{}}}},Zm=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),Xm=t=>!!t.sync&&!!t.file,Qm=t=>!t.sync&&!!t.file,ew=t=>!!t.sync&&!t.file,tw=t=>!t.sync&&!t.file,nw=t=>!!t.file,rw=t=>Zm.get(t)||t,Dc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let s=rw(n);e[s]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Pi=(t,e,n,i,s)=>Object.assign((c=[],d,u)=>{Array.isArray(c)&&(d=c,c={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let h=Dc(c);if(s?.(h,d),Xm(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(Qm(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(ew(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(h,d)}else if(tw(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:s}),ow=sw.constants||{ZLIB_VERNUM:4736},Pt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},ow)),aw=Hn.concat,bu=Object.getOwnPropertyDescriptor(Hn,"concat"),cw=t=>t,$a=bu?.writable===!0||bu?.set!==void 0?t=>{Hn.concat=t?cw:aw}:t=>{},jn=Symbol("_superWrite"),Ts=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Va=Symbol("flushFlag"),Oc=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 Eu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Eu[e](t)}catch(n){throw new Ts(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 Ts(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return uc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Hn.alloc(0),{[Va]: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=Hn.from(t,e)),this.#e)return;uc(this.#t,"zlib binding closed");let i=this.#t._handle,s=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},$a(!0);let d;try{let h=typeof t[Va]=="number"?t[Va]:this.#r;d=this.#t._processChunk(t,h),$a(!1)}catch(h){$a(!1),this.#o(new Ts(h,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=s,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",h=>this.#o(new Ts(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[jn](Hn.from(h));for(let x=1;x<d.length;x++)u=this[jn](d[x])}else u=this[jn](Hn.from(d));return n&&n(),u}},tf=class extends Oc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Pt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Pt.Z_FINISH,t.fullFlushFlag=Pt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Pt.Z_SYNC_FLUSH),uc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,s)=>{typeof i=="function"&&(s=i,i=this.flushFlag),this.flush(i),s?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},dw=class extends tf{#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)}},lw=class extends tf{constructor(t){super(t,"Unzip")}},nf=class extends Oc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Pt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Pt.BROTLI_OPERATION_FLUSH,super(t,e)}},uw=class extends nf{constructor(t){super(t,"BrotliCompress")}},fw=class extends nf{constructor(t){super(t,"BrotliDecompress")}},rf=class extends Oc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Pt.ZSTD_e_end,t.fullFlushFlag=Pt.ZSTD_e_flush,super(t,e)}},hw=class extends rf{constructor(t){super(t,"ZstdCompress")}},xw=class extends rf{constructor(t){super(t,"ZstdDecompress")}},pw=(t,e)=>{if(Number.isSafeInteger(t))t<0?mw(t,e):gw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},gw=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},mw=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var s=t&255;t=Math.floor(t/256),n?e[i-1]=sf(s):s===0?e[i-1]=0:(n=!0,e[i-1]=of(s))}},ww=t=>{let e=t[0],n=e===128?yw(t.subarray(1,t.length)):e===255?_w(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},_w=t=>{for(var e=t.length,n=0,i=!1,s=e-1;s>-1;s--){var c=Number(t[s]),d;i?d=sf(c):c===0?d=c:(i=!0,d=of(c)),d!==0&&(n-=d*Math.pow(256,e-s-1))}return n},yw=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var s=Number(t[i]);s!==0&&(n+=s*Math.pow(256,e-i-1))}return n},sf=t=>(255^t)&255,of=t=>(255^t)+1&255,Ew={};Lm(Ew,{code:()=>Lc,isCode:()=>zs,isName:()=>bw,name:()=>eo,normalFsTypes:()=>af});var zs=t=>eo.has(t),bw=t=>Lc.has(t),af=new Set(["0","","1","2","3","4","5","6","7","D"]),eo=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Lc=new Map(Array.from(eo).map(t=>[t[1],t[0]])),Wn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let s=Mn(t,e+156,1),c=af.has(s),d=c?n:void 0,u=c?i:void 0;if(this.path=d?.path??Mn(t,e,100),this.mode=d?.mode??u?.mode??mn(t,e+100,8),this.uid=d?.uid??u?.uid??mn(t,e+108,8),this.gid=d?.gid??u?.gid??mn(t,e+116,8),this.size=d?.size??u?.size??mn(t,e+124,12),this.mtime=d?.mtime??u?.mtime??Ya(t,e+136,12),this.cksum=mn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),zs(s)&&(this.#e=s||"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??mn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??mn(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??Ya(t,e+476,12),this.ctime=n?.ctime??i?.ctime??Ya(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=vw(this.path||"",n),s=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Bn(t,e,100,s)||this.needPax,this.needPax=wn(t,e+100,8,this.mode)||this.needPax,this.needPax=wn(t,e+108,8,this.uid)||this.needPax,this.needPax=wn(t,e+116,8,this.gid)||this.needPax,this.needPax=wn(t,e+124,12,this.size)||this.needPax,this.needPax=Ja(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=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=wn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=wn(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=Ja(t,e+476,12,this.atime)||this.needPax,this.needPax=Ja(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,wn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:eo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Lc.get(t));if(zs(e)||e==="Unsupported")this.#e=e;else if(zs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},vw=(t,e)=>{let n=t,i="",s,c=gr.parse(t).root||".";if(Buffer.byteLength(n)<100)s=[n,i,!1];else{i=gr.dirname(n),n=gr.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?s=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?s=[n.slice(0,99),i,!0]:(n=gr.join(gr.basename(i),n),i=gr.dirname(i));while(i!==c&&s===void 0);s||(s=[t.slice(0,99),"",!0])}return s},Mn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),Ya=(t,e,n)=>Sw(mn(t,e,n)),Sw=t=>t===void 0?void 0:new Date(t*1e3),mn=(t,e,n)=>Number(t[e])&128?ww(t.subarray(e,e+n)):Aw(t,e,n),Iw=t=>isNaN(t)?void 0:t,Aw=(t,e,n)=>Iw(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),kw={12:8589934591,8:2097151},wn=(t,e,n,i)=>i===void 0?!1:i>kw[n]||i<0?(pw(i,t.subarray(e,e+n)),!0):(Tw(t,e,n,i),!1),Tw=(t,e,n,i)=>t.write(Rw(i,n),e,n,"ascii"),Rw=(t,e)=>Cw(Math.floor(t).toString(8),e),Cw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Ja=(t,e,n,i)=>i===void 0?!1:wn(t,e,n,i.getTime()/1e3),Pw=new Array(156).join("\0"),Bn=(t,e,n,i)=>i===void 0?!1:(t.write(i+Pw,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),Vs=class cf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),s=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)s[c]=0;new Wn({path:("PaxHeader/"+Dw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(s),s.write(e,512,n,"utf8");for(let c=n+512;c<s.length;c++)s[c]=0;return s}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let n=this[e],i=n instanceof Date?n.getTime()/1e3:n,s=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
- `,c=Buffer.byteLength(s),d=Math.floor(Math.log(c)/Math.log(10))+1;return c+d>=Math.pow(10,d)&&(d+=1),d+c+s}static parse(e,n,i=!1){return new cf(Ow(Lw(e),n),i)}},Ow=(t,e)=>e?Object.assign({},e,t):t,Lw=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(Nw,Object.create(null)),Nw=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),s=i.shift();if(!s)return t;let c=s.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(d)*1e3):/^[0-9]+$/.test(d)?+d:d,t},Mw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=Mw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Bw=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,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=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),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=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},to=(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))},Fw=1024*1024,fc=Buffer.from([31,139]),hc=Buffer.from([40,181,47,253]),zw=Math.max(fc.length,hc.length),lt=Symbol("state"),Fn=Symbol("writeEntry"),jt=Symbol("readEntry"),Za=Symbol("nextEntry"),vu=Symbol("processEntry"),Tt=Symbol("extendedHeader"),hi=Symbol("globalExtendedHeader"),fn=Symbol("meta"),Su=Symbol("emitMeta"),ge=Symbol("buffer"),Wt=Symbol("queue"),hn=Symbol("ended"),Xa=Symbol("emittedEnd"),zn=Symbol("emit"),Re=Symbol("unzip"),Rs=Symbol("consumeChunk"),Cs=Symbol("consumeChunkSub"),Qa=Symbol("consumeBody"),Iu=Symbol("consumeMeta"),Au=Symbol("consumeHeader"),xi=Symbol("consuming"),ec=Symbol("bufferConcat"),Ps=Symbol("maybeEnd"),mr=Symbol("writing"),xn=Symbol("aborted"),Ds=Symbol("onDone"),Un=Symbol("sawValidEntry"),Os=Symbol("sawNullBlock"),Ls=Symbol("sawEOF"),ku=Symbol("closeStream"),Uw=()=>!0,Ci=class extends iw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Wt]=[];[ge];[jt];[Fn];[lt]="begin";[fn]="";[Tt];[hi];[hn]=!1;[Re];[xn]=!1;[Un];[Os]=!1;[Ls]=!1;[mr]=!1;[xi]=!1;[Xa]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ds,()=>{(this[lt]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ds,t.ondone):this.on(Ds,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Fw,this.filter=typeof t.filter=="function"?t.filter:Uw;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let n=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:n?!0:void 0,this.on("end",()=>this[ku]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){to(this,t,e,n)}[Au](t,e){this[Un]===void 0&&(this[Un]=!1);let n;try{n=new Wn(t,e,this[Tt],this[hi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Os]?(this[Ls]=!0,this[lt]==="begin"&&(this[lt]="header"),this[zn]("eof")):(this[Os]=!0,this[zn]("nullBlock"));else if(this[Os]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let s=this[Fn]=new Bw(n,this[Tt],this[hi]);if(!this[Un])if(s.remain){let c=()=>{s.invalid||(this[Un]=!0)};s.on("end",c)}else this[Un]=!0;s.meta?s.size>this.maxMetaEntrySize?(s.ignore=!0,this[zn]("ignoredEntry",s),this[lt]="ignore",s.resume()):s.size>0&&(this[fn]="",s.on("data",c=>this[fn]+=c),this[lt]="meta"):(this[Tt]=void 0,s.ignore=s.ignore||!this.filter(s.path,s),s.ignore?(this[zn]("ignoredEntry",s),this[lt]=s.remain?"ignore":"header",s.resume()):(s.remain?this[lt]="body":(this[lt]="header",s.end()),this[jt]?this[Wt].push(s):(this[Wt].push(s),this[Za]())))}}}[ku](){queueMicrotask(()=>this.emit("close"))}[vu](t){let e=!0;if(!t)this[jt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[jt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Za]()),e=!1);return e}[Za](){do;while(this[vu](this[Wt].shift()));if(this[Wt].length===0){let t=this[jt];!t||t.flowing||t.size===t.remain?this[mr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Qa](t,e){let n=this[Fn];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,s=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(s),n.blockRemain||(this[lt]="header",this[Fn]=void 0,n.end()),s.length}[Iu](t,e){let n=this[Fn],i=this[Qa](t,e);return!this[Fn]&&n&&this[Su](n),i}[zn](t,e,n){this[Wt].length===0&&!this[jt]?this.emit(t,e,n):this[Wt].push([t,e,n])}[Su](t){switch(this[zn]("meta",this[fn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Tt]=Vs.parse(this[fn],this[Tt],!1);break;case"GlobalExtendedHeader":this[hi]=Vs.parse(this[fn],this[hi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Tt]??Object.create(null);this[Tt]=e,e.path=this[fn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Tt]||Object.create(null);this[Tt]=e,e.linkpath=this[fn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[xn]=!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[xn])return n?.(),!1;if((this[Re]===void 0||this.brotli===void 0&&this[Re]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<zw)return this[ge]=t,n?.(),!0;for(let d=0;this[Re]===void 0&&d<fc.length;d++)t[d]!==fc[d]&&(this[Re]=!1);let s=!1;if(this[Re]===!1&&this.zstd!==!1){s=!0;for(let d=0;d<hc.length;d++)if(t[d]!==hc[d]){s=!1;break}}let c=this.brotli===void 0&&!s;if(this[Re]===!1&&c)if(t.length<512)if(this[hn])this.brotli=!0;else return this[ge]=t,n?.(),!0;else try{new Wn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Re]===void 0||this[Re]===!1&&(this.brotli||s)){let d=this[hn];this[hn]=!1,this[Re]=this[Re]===void 0?new lw({}):s?new xw({}):new fw({}),this[Re].on("data",h=>this[Rs](h)),this[Re].on("error",h=>this.abort(h)),this[Re].on("end",()=>{this[hn]=!0,this[Rs]()}),this[mr]=!0;let u=!!this[Re][d?"end":"write"](t);return this[mr]=!1,n?.(),u}}this[mr]=!0,this[Re]?this[Re].write(t):this[Rs](t),this[mr]=!1;let i=this[Wt].length>0?!1:this[jt]?this[jt].flowing:!0;return!i&&this[Wt].length===0&&this[jt]?.once("drain",()=>this.emit("drain")),n?.(),i}[ec](t){t&&!this[xn]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[Ps](){if(this[hn]&&!this[Xa]&&!this[xn]&&!this[xi]){this[Xa]=!0;let t=this[Fn];if(t&&t.blockRemain){let e=this[ge]?this[ge].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ge]&&t.write(this[ge]),t.end()}this[zn](Ds)}}[Rs](t){if(this[xi]&&t)this[ec](t);else if(!t&&!this[ge])this[Ps]();else if(t){if(this[xi]=!0,this[ge]){this[ec](t);let e=this[ge];this[ge]=void 0,this[Cs](e)}else this[Cs](t);for(;this[ge]&&this[ge]?.length>=512&&!this[xn]&&!this[Ls];){let e=this[ge];this[ge]=void 0,this[Cs](e)}this[xi]=!1}(!this[ge]||this[hn])&&this[Ps]()}[Cs](t){let e=0,n=t.length;for(;e+512<=n&&!this[xn]&&!this[Ls];)switch(this[lt]){case"begin":case"header":this[Au](t,e),e+=512;break;case"ignore":case"body":e+=this[Qa](t,e);break;case"meta":e+=this[Iu](t,e);break;default:throw new Error("invalid state: "+this[lt])}e<n&&(this[ge]=this[ge]?Buffer.concat([t.subarray(e),this[ge]]):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[xn]||(this[Re]?(t&&this[Re].write(t),this[Re].end()):(this[hn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ps]())),this}},vi=t=>{let e=t.length-1,n=-1;for(;e>-1&&t.charAt(e)==="/";)n=e,e--;return n===-1?t:t.slice(0,n)},Gw=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},df=(t,e)=>{let n=new Map(e.map(c=>[vi(c),!0])),i=t.filter,s=(c,d="")=>{let u=d||Jm(c).root||".",h;if(c===u)h=!1;else{let x=n.get(c);h=x!==void 0?x:s(Ym(c),u)}return n.set(c,h),h};t.filter=i?(c,d)=>i(c,d)&&s(vi(c)):c=>s(vi(c))},qw=t=>{let e=new Ci(t),n=t.file,i;try{i=vr.openSync(n,"r");let s=vr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(s.size<c){let d=Buffer.allocUnsafe(s.size),u=vr.readSync(i,d,0,s.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(c);for(;d<s.size;){let h=vr.readSync(i,u,0,c,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{vr.closeSync(i)}catch{}}},Hw=(t,e)=>{let n=new Ci(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("end",c),vr.stat(s,(u,h)=>{if(u)d(u);else{let x=new Pc(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},kr=Pi(qw,Hw,t=>new Ci(t),t=>new Ci(t),(t,e)=>{e?.length&&df(t,e),t.noResume||Gw(t)}),lf=(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:Ww,parse:Ru}=jw,Nc=t=>{let e="",n=Ru(t);for(;Ww(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Ru(t)}return[e,t]},no=["|","<",">","?",":"],Mc=no.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Kw=new Map(no.map((t,e)=>[t,Mc[e]])),$w=new Map(Mc.map((t,e)=>[t,no[e]])),Cu=t=>no.reduce((e,n)=>e.split(n).join(Kw.get(n)),t),Vw=t=>Mc.reduce((e,n)=>e.split(n).join($w.get(n)),t),uf=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),vi(e)+"/"+t):Q(t),Yw=16*1024*1024,Pu=Symbol("process"),Du=Symbol("file"),Ou=Symbol("directory"),xc=Symbol("symlink"),Lu=Symbol("hardlink"),pi=Symbol("header"),Us=Symbol("read"),pc=Symbol("lstat"),Gs=Symbol("onlstat"),gc=Symbol("onread"),mc=Symbol("onreadlink"),wc=Symbol("openfile"),_c=Symbol("onopenfile"),_n=Symbol("close"),Js=Symbol("mode"),yc=Symbol("awaitDrain"),tc=Symbol("ondrain"),Ct=Symbol("prefix"),ff=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 n=Dc(e);super(),this.path=Q(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||Yw,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=Q(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?Q(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=Nc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=Vw(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(n.absolute||Tu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let s=this.statCache.get(this.absolute);s?this[Gs](s):this[pc]()}warn(t,e,n={}){return to(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[pc](){Rt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Gs](e)})}[Gs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Xw(t),this.emit("stat",t),this[Pu]()}[Pu](){switch(this.type){case"File":return this[Du]();case"Directory":return this[Ou]();case"SymbolicLink":return this[xc]();default:return this.end()}}[Js](t){return lf(t,this.type==="Directory",this.portable)}[Ct](t){return uf(t,this.prefix)}[pi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Wn({path:this[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](this.linkpath):this.linkpath,mode:this[Js](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new Vs({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](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)}[Ou](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[pi](),this.end()}[xc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[mc](e)})}[mc](t){this.linkpath=Q(t),this[pi](),this.end()}[Lu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Tu.relative(this.cwd,t)),this.stat.size=0,this[pi](),this.end()}[Du](){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[Lu](e);this.linkCache.set(t,this.absolute)}if(this[pi](),this.stat.size===0)return this.end();this[wc]()}[wc](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[_c](e)})}[_c](t){if(this.fd=t,this.#e)return this[_n]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[Us]()}[Us](){let{fd:t,buf:e,offset:n,length:i,pos:s}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Rt.read(t,e,n,i,s,(c,d)=>{if(c)return this[_n](()=>this.emit("error",c));this[gc](d)})}[_n](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[gc](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[_n](()=>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[_n](()=>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[tc]():this[yc](()=>this[tc]())}[yc](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,n)}[tc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[_n](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[Us]()}},Jw=class extends ff{sync=!0;[pc](){this[Gs](Rt.lstatSync(this.absolute))}[xc](){this[mc](Rt.readlinkSync(this.absolute))}[wc](){this[_c](Rt.openSync(this.absolute,"r"))}[Us](){let t=!0;try{let{fd:e,buf:n,offset:i,length:s,pos:c}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let d=Rt.readSync(e,n,i,s,c);this[gc](d),t=!1}finally{if(t)try{this[_n](()=>{})}catch{}}}[yc](t){t()}[_n](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},Zw=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,n={}){return to(this,t,e,n)}constructor(t,e={}){let n=Dc(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=Q(t.path),this.mode=t.mode!==void 0?this[Js](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?Q(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let s=!1;if(!this.preservePaths){let[d,u]=Nc(this.path);d&&typeof u=="string"&&(this.path=u,s=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Wn({path:this[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),s&&this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute path`,{entry:this,path:s+this.path}),this.header.encode()&&!this.noPax&&super.write(new Vs({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](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)}[Ct](t){return uf(t,this.prefix)}[Js](t){return lf(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}},Xw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",Qw=class Sr{tail;head;length=0;static create(e=[]){return new Sr(e)}constructor(e=[]){for(let n of e)this.push(n)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let n=e.next,i=e.prev;return n&&(n.prev=i),i&&(i.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,i=e.length;n<i;n++)t_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)n_(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,s=0;i;s++)e.call(n,i.value,s,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,s=this.length-1;i;s--)e.call(n,i.value,s,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Sr;for(let s=this.head;s;)i.push(e.call(n,s.value,this)),s=s.next;return i}mapReverse(e,n){n=n||this;var i=new Sr;for(let s=this.tail;s;)i.push(e.call(n,s.value,this)),s=s.prev;return i}reduce(e,n){let i,s=this.head;if(arguments.length>1)i=n;else if(this.head)s=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;s;c++)i=e(i,s.value,c),s=s.next;return i}reduceReverse(e,n){let i,s=this.tail;if(arguments.length>1)i=n;else if(this.tail)s=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;s;c--)i=e(i,s.value,c),s=s.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Sr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.head,c=0;for(c=0;s&&c<e;c++)s=s.next;for(;s&&c<n;c++,s=s.next)i.push(s.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Sr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.length,c=this.tail;for(;c&&s>n;s--)c=c.prev;for(;c&&s>e;s--,c=c.prev)i.push(c.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let s=this.head;for(let d=0;s&&d<e;d++)s=s.next;let c=[];for(let d=0;s&&d<n;d++)c.push(s.value),s=this.removeNode(s);s?s!==this.tail&&(s=s.prev):s=this.tail;for(let d of i)s=e_(this,s,d);return c}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let s=i.prev;i.prev=i.next,i.next=s}return this.head=n,this.tail=e,this}};function e_(t,e,n){let i=e,s=e?e.next:t.head,c=new Bc(n,i,s,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function t_(t,e){t.tail=new Bc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function n_(t,e){t.head=new Bc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Bc=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}},Mu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Bu=Buffer.alloc(1024),qs=Symbol("onStat"),gi=Symbol("ended"),wt=Symbol("queue"),mi=Symbol("pendingLinks"),pn=Symbol("current"),Gn=Symbol("process"),wi=Symbol("processing"),Ns=Symbol("processJob"),_t=Symbol("jobs"),nc=Symbol("jobDone"),Hs=Symbol("addFSEntry"),Fu=Symbol("addTarEntry"),Ec=Symbol("stat"),bc=Symbol("readdir"),js=Symbol("onreaddir"),Ws=Symbol("pipe"),zu=Symbol("entry"),rc=Symbol("entryOpt"),Ks=Symbol("writeEntryClass"),hf=Symbol("write"),ic=Symbol("ondrain"),ro=class extends Kn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Ks];onWriteEntry;[wt];[mi]=new Map;[_t]=0;[wi]=!1;[gi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[Ks]=ff,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 dw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new uw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new hw(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[ic]()),this.on("resume",()=>e.resume())}else this.on("drain",this[ic]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[wt]=new Qw,this[_t]=0,this.jobs=Number(t.jobs)||4,this[wi]=!1,this[gi]=!1}[hf](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[gi]=!0,this[Gn](),n&&n(),this}write(t){if(this[gi])throw new Error("write after end");return typeof t=="string"?this[Hs](t):this[Fu](t),this.flowing}[Fu](t){let e=Q(Nu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new Mu(t.path,e);n.entry=new Zw(t,this[rc](n)),n.entry.on("end",()=>this[nc](n)),this[_t]+=1,this[wt].push(n)}this[Gn]()}[Hs](t){let e=Q(Nu.resolve(this.cwd,t));this[wt].push(new Mu(t,e)),this[Gn]()}[Ec](t){t.pending=!0,this[_t]+=1;let e=this.follow?"stat":"lstat";Ys[e](t.absolute,(n,i)=>{t.pending=!1,this[_t]-=1,n?this.emit("error",n):this[qs](t,i)})}[qs](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[pn])this[Ns](t);else{let n=`${e.dev}:${e.ino}`,i=this[mi].get(n);i?i.push(t):this[mi].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Gn]()}[bc](t){t.pending=!0,this[_t]+=1,Ys.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[_t]-=1,e)return this.emit("error",e);this[js](t,n)})}[js](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Gn]()}[Gn](){if(!this[wi]){this[wi]=!0;for(let t=this[wt].head;t&&this[_t]<this.jobs;t=t.next)if(this[Ns](t.value),t.value.ignore){let e=t.next;this[wt].removeNode(t),t.next=e}this[wi]=!1,this[gi]&&this[wt].length===0&&this[_t]===0&&(this.zip?this.zip.end(Bu):(super.write(Bu),super.end()))}}get[pn](){return this[wt]&&this[wt].head&&this[wt].head.value}[nc](t){this[wt].shift(),this[_t]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[mi].get(n);if(i){this[mi].delete(n);for(let s of i)s.pending=!1,this[Ns](s)}}this[Gn]()}[Ns](t){if(t.pending&&t.pendingLink&&t===this[pn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[pn]&&!t.piped&&this[Ws](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[qs](t,e):this[Ec](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[bc](t),!t.readdir)return}if(t.entry=this[zu](t),!t.entry){t.ignore=!0;return}t===this[pn]&&!t.piped&&this[Ws](t)}}}[rc](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[_t]+=1;try{return new this[Ks](t.path,this[rc](t)).on("end",()=>this[nc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[ic](){this[pn]&&this[pn].entry&&this[pn].entry.resume()}[Ws](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let s=t.path,c=s==="./"?"":s.replace(/\/*$/,"/");this[Hs](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={}){to(this,t,e,n)}},Fc=class extends ro{sync=!0;constructor(t){super(t),this[Ks]=Jw}pause(){}resume(){}[Ec](t){let e=this.follow?"statSync":"lstatSync";this[qs](t,Ys[e](t.absolute))}[bc](t){this[js](t,Ys.readdirSync(t.absolute))}[Ws](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let s=t.path,c=s==="./"?"":s.replace(/\/*$/,"/");this[Hs](c+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[hf](i)})}},r_=(t,e)=>{let n=new Fc(t),i=new Qu(t.file,{mode:t.mode||438});n.pipe(i),xf(n,e)},i_=(t,e)=>{let n=new ro(t),i=new Qs(t.file,{mode:t.mode||438});n.pipe(i);let s=new Promise((c,d)=>{i.on("error",d),i.on("close",c),n.on("error",d)});return pf(n,e).catch(c=>n.emit("error",c)),s},xf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?kr({file:ef.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},pf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await kr({file:ef.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},s_=(t,e)=>{let n=new Fc(t);return xf(n,e),n},o_=(t,e)=>{let n=new ro(t);return pf(n,e).catch(i=>n.emit("error",i)),n},LI=Pi(r_,i_,s_,o_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),c_=process.env.__FAKE_PLATFORM__||process.platform,_f=c_==="win32",{O_CREAT:yf,O_NOFOLLOW:Uu,O_TRUNC:Ef,O_WRONLY:bf}=wf.constants,vf=Number(process.env.__FAKE_FS_O_FILENAME__)||wf.constants.UV_FS_O_FILEMAP||0,d_=_f&&!!vf,l_=512*1024,u_=vf|Ef|yf|bf,Gu=!_f&&typeof Uu=="number"?Uu|Ef|yf|bf:null,Sf=Gu!==null?()=>Gu:d_?t=>t<l_?u_:"w":()=>"w",vc=(t,e,n)=>{try{return io.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},Zs=(t,e,n,i)=>{io.lchown(t,e,n,s=>{i(s&&s?.code!=="ENOENT"?s:null)})},f_=(t,e,n,i,s)=>{if(e.isDirectory())If(Si.resolve(t,e.name),n,i,c=>{if(c)return s(c);let d=Si.resolve(t,e.name);Zs(d,n,i,s)});else{let c=Si.resolve(t,e.name);Zs(c,n,i,s)}},If=(t,e,n,i)=>{io.readdir(t,{withFileTypes:!0},(s,c)=>{if(s){if(s.code==="ENOENT")return i();if(s.code!=="ENOTDIR"&&s.code!=="ENOTSUP")return i(s)}if(s||!c.length)return Zs(t,e,n,i);let d=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return Zs(t,e,n,i)}};for(let x of c)f_(t,x,e,n,h)})},h_=(t,e,n,i)=>{e.isDirectory()&&Af(Si.resolve(t,e.name),n,i),vc(Si.resolve(t,e.name),n,i)},Af=(t,e,n)=>{let i;try{i=io.readdirSync(t,{withFileTypes:!0})}catch(s){let c=s;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return vc(t,e,n);throw c}for(let s of i)h_(t,s,e,n);return vc(t,e,n)},kf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},so=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},p_=(t,e)=>{st.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new kf(t,n?.code||"ENOTDIR")),e(n)})},g_=(t,e,n)=>{t=Q(t);let i=e.umask??18,s=e.mode|448,c=(s&i)!==0,d=e.uid,u=e.gid,h=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,g=e.unlink,w=Q(e.cwd),S=(v,I)=>{v?n(v):I&&h?If(I,d,u,A=>S(A)):c?st.chmod(t,s,n):n()};if(t===w)return p_(t,S);if(x)return x_.mkdir(t,{mode:s,recursive:!0}).then(v=>S(null,v??void 0),S);let y=Q(Xs.relative(w,t)).split("/");Sc(w,y,s,g,w,void 0,S)},Sc=(t,e,n,i,s,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),h=Q(Xs.resolve(t+"/"+u));st.mkdir(h,n,Tf(h,e,n,i,s,c,d))},Tf=(t,e,n,i,s,c,d)=>u=>{u?st.lstat(t,(h,x)=>{if(h)h.path=h.path&&Q(h.path),d(h);else if(x.isDirectory())Sc(t,e,n,i,s,c,d);else if(i)st.unlink(t,g=>{if(g)return d(g);st.mkdir(t,n,Tf(t,e,n,i,s,c,d))});else{if(x.isSymbolicLink())return d(new so(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Sc(t,e,n,i,s,c,d))},m_=t=>{let e=!1,n;try{e=st.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new kf(t,n??"ENOTDIR")}},w_=(t,e)=>{t=Q(t);let n=e.umask??18,i=e.mode|448,s=(i&n)!==0,c=e.uid,d=e.gid,u=typeof c=="number"&&typeof d=="number"&&(c!==e.processUid||d!==e.processGid),h=e.preserve,x=e.unlink,g=Q(e.cwd),w=v=>{v&&u&&Af(v,c,d),s&&st.chmodSync(t,i)};if(t===g)return m_(g),w();if(h)return w(st.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(Xs.relative(g,t)).split("/"),y;for(let v=S.shift(),I=g;v&&(I+="/"+v);v=S.shift()){I=Q(Xs.resolve(I));try{st.mkdirSync(I,i),y=y||I}catch{let A=st.lstatSync(I);if(A.isDirectory())continue;if(x){st.unlinkSync(I),st.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new so(I,I+"/"+S.join("/"))}}return w(y)},sc=Object.create(null),qu=1e4,wr=new Set,__=t=>{wr.has(t)?wr.delete(t):sc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),wr.add(t);let e=sc[t],n=wr.size-qu;if(n>qu/10){for(let i of wr)if(wr.delete(i),delete sc[i],--n<=0)break}return e},y_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,E_=y_==="win32",b_=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Rf(i,n)),e.push(n||"/"),e},[]),v_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=E_?["win32 parallelization disabled"]:t.map(i=>vi(Rf(__(i))));let n=new Set(t.map(i=>b_(i)).reduce((i,s)=>i.concat(s)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let s=this.#e.get(i);s?s.push(e):this.#e.set(i,[e])}for(let i of n){let s=this.#e.get(i);if(!s)this.#e.set(i,[new Set([e])]);else{let c=s.at(-1);c instanceof Set?c.add(e):s.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:i}=e,s=new Set;for(let c of n){let d=this.#e.get(c);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(c);continue}if(d.shift(),typeof u=="function")s.add(u);else for(let h of u)s.add(h)}for(let c of i){let d=this.#e.get(c),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(c);continue}else if(u.size===1){d.shift();let h=d[0];typeof h=="function"&&s.add(h)}else u.delete(t)}return this.#r.delete(t),s.forEach(c=>this.#i(c)),!0}},S_=()=>process.umask(),Hu=Symbol("onEntry"),Ic=Symbol("checkFs"),ju=Symbol("checkFs2"),Ac=Symbol("isReusable"),ut=Symbol("makeFs"),kc=Symbol("file"),Tc=Symbol("directory"),$s=Symbol("link"),Wu=Symbol("symlink"),Ku=Symbol("hardlink"),Ei=Symbol("ensureNoSymlink"),$u=Symbol("unsupported"),Vu=Symbol("checkPath"),oc=Symbol("stripAbsolutePath"),yn=Symbol("mkdir"),Ge=Symbol("onError"),Ms=Symbol("pending"),Yu=Symbol("pend"),_r=Symbol("unpend"),ac=Symbol("ended"),cc=Symbol("maybeClose"),Rc=Symbol("skip"),Ii=Symbol("doChown"),Ai=Symbol("uid"),ki=Symbol("gid"),Ti=Symbol("checkedCwd"),I_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ri=I_==="win32",A_=1024,k_=(t,e)=>{if(!Ri)return ie.unlink(t,e);let n=t+".DELETE."+mf(16).toString("hex");ie.rename(t,n,i=>{if(i)return e(i);ie.unlink(n,e)})},T_=t=>{if(!Ri)return ie.unlinkSync(t);let e=t+".DELETE."+mf(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},Ju=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,zc=class extends Ci{[ac]=!1;[Ti]=!1;[Ms]=0;reservations=new v_;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[ac]=!0,this[cc]()},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:A_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ri,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:S_():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[Hu](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[cc](){this[ac]&&this[Ms]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[oc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[s,c]=Nc(n),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Ri&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=Me.posix.dirname(t.path),h=Me.posix.normalize(Me.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return s&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute ${e}`,{entry:t,[e]:n})),!0}[Vu](t){let e=Q(t.path),n=e.split("/");if(this.strip){if(n.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}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[oc](t,"path")||!this[oc](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+Cu(String(t.absolute).slice(i.length));let{root:s}=Me.win32.parse(t.path);t.path=s+Cu(t.path.slice(s.length))}return!0}[Hu](t){if(!this[Vu](t))return t.resume();switch(a_.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[Ic](t);default:return this[$u](t)}}[Ge](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[_r](),e.resume())}[yn](t,e,n){g_(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},n)}[Ii](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ai](t){return Ju(this.uid,t.uid,this.processUid)}[ki](t){return Ju(this.gid,t.gid,this.processGid)}[kc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new Qs(String(t.absolute),{flags:Sf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[Ge](u,t),e()});let s=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[Ge](u,t),e();return}--s===0&&i.fd!==void 0&&ie.close(i.fd,h=>{h?this[Ge](h,t):this[_r](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){s++;let x=t.atime||new Date,g=t.mtime;ie.futimes(h,x,g,w=>w?ie.utimes(u,x,g,S=>c(S&&w)):c())}if(typeof h=="number"&&this[Ii](t)){s++;let x=this[Ai](t),g=this[ki](t);typeof x=="number"&&typeof g=="number"&&ie.fchown(h,x,g,w=>w?ie.chown(u,x,g,S=>c(S&&w)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[Ge](u,t),e()}),t.pipe(d)),d.pipe(i)}[Tc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[yn](String(t.absolute),n,i=>{if(i){this[Ge](i,t),e();return}let s=1,c=()=>{--s===0&&(e(),this[_r](),t.resume())};t.mtime&&!this.noMtime&&(s++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ii](t)&&(s++,ie.chown(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)),c)),c()})}[$u](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Wu](t,e){let n=Q(Me.relative(this.cwd,Me.resolve(Me.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ei](t,this.cwd,n,()=>this[$s](t,String(t.linkpath),"symlink",e),i=>{this[Ge](i,t),e()})}[Ku](t,e){let n=Q(Me.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Ei](t,this.cwd,i,()=>this[$s](t,n,"link",e),s=>{this[Ge](s,t),e()})}[Ei](t,e,n,i,s){let c=n.shift();if(this.preservePaths||c===void 0)return i();let d=Me.resolve(e,c);ie.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return s(new so(d,Me.resolve(d,n.join("/"))));this[Ei](t,d,n,i,s)})}[Yu](){this[Ms]++}[_r](){this[Ms]--,this[cc]()}[Rc](t){this[_r](),t.resume()}[Ac](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ri}[Ic](t){this[Yu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[ju](t,n))}[ju](t,e){let n=d=>{e(d)},i=()=>{this[yn](this.cwd,this.dmode,d=>{if(d){this[Ge](d,t),n();return}this[Ti]=!0,s()})},s=()=>{if(t.absolute!==this.cwd){let d=Q(Me.dirname(String(t.absolute)));if(d!==this.cwd)return this[yn](d,this.dmode,u=>{if(u){this[Ge](u,t),n();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Rc](t),n();return}if(d||this[Ac](t,u))return this[ut](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[ut](g??null,t,n);return h?ie.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),h=>this[ut](h??null,t,n))}if(t.absolute===this.cwd)return this[ut](null,t,n);k_(String(t.absolute),h=>this[ut](h??null,t,n))})};this[Ti]?s():i()}[ut](t,e,n){if(t){this[Ge](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[kc](e,n);case"Link":return this[Ku](e,n);case"SymbolicLink":return this[Wu](e,n);case"Directory":case"GNUDumpDir":return this[Tc](e,n)}}[$s](t,e,n,i){ie[n](e,String(t.absolute),s=>{s?this[Ge](s,t):(this[_r](),t.resume()),i()})}},_i=t=>{try{return[null,t()]}catch(e){return[e,null]}},Cf=class extends zc{sync=!0;[ut](t,e){return super[ut](t,e,()=>{})}[Ic](t){if(!this[Ti]){let s=this[yn](this.cwd,this.dmode);if(s)return this[Ge](s,t);this[Ti]=!0}if(t.absolute!==this.cwd){let s=Q(Me.dirname(String(t.absolute)));if(s!==this.cwd){let c=this[yn](s,this.dmode);if(c)return this[Ge](c,t)}}let[e,n]=_i(()=>ie.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Rc](t);if(e||this[Ac](t,n))return this[ut](null,t);if(n.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=c?_i(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ut](d,t)}let[s]=_i(()=>ie.rmdirSync(String(t.absolute)));this[ut](s,t)}let[i]=t.absolute===this.cwd?[]:_i(()=>T_(String(t.absolute)));this[ut](i,t)}[kc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{ie.closeSync(s)}catch(h){u=h}(d||u)&&this[Ge](d||u,t),e()},s;try{s=ie.openSync(String(t.absolute),Sf(t.size),n)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[Ge](d,t)),t.pipe(c)),c.on("data",d=>{try{ie.writeSync(s,d,0,d.length)}catch(u){i(u)}}),c.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{ie.futimesSync(s,u,h)}catch(x){try{ie.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[Ii](t)){let u=this[Ai](t),h=this[ki](t);try{ie.fchownSync(s,Number(u),Number(h))}catch(x){try{ie.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[Tc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[yn](String(t.absolute),n);if(i){this[Ge](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ii](t))try{ie.chownSync(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)))}catch{}e(),t.resume()}[yn](t,e){try{return w_(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(n){return n}}[Ei](t,e,n,i,s){if(this.preservePaths||n.length===0)return i();let c=e;for(let d of n){c=Me.resolve(c,d);let[u,h]=_i(()=>ie.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return s(new so(c,Me.resolve(e,n.join("/"))))}i()}[$s](t,e,n,i){let s=`${n}Sync`;try{ie[s](e,String(t.absolute)),i(),t.resume()}catch(c){return this[Ge](c,t)}}},R_=t=>{let e=new Cf(t),n=t.file,i=gf.statSync(n),s=t.maxReadSize||16*1024*1024;new Vm(n,{readSize:s,size:i.size}).pipe(e)},C_=(t,e)=>{let n=new zc(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("close",c),gf.stat(s,(u,h)=>{if(u)d(u);else{let x=new Pc(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Pf=Pi(R_,C_,t=>new Cf(t),t=>new zc(t),(t,e)=>{e?.length&&df(t,e)}),P_=(t,e)=>{let n=new Fc(t),i=!0,s,c;try{try{s=it.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")s=it.openSync(t.file,"w+");else throw h}let d=it.fstatSync(s),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let g=0,w=0;g<512;g+=w){if(w=it.readSync(s,u,g,u.length-g,c+g),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let h=new Wn(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(c+x+512>d.size)break;c+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,D_(t,n,c,s,e)}finally{if(i)try{it.closeSync(s)}catch{}}},D_=(t,e,n,i,s)=>{let c=new Qu(t.file,{fd:i,start:n});e.pipe(c),L_(e,s)},O_=(t,e)=>{e=Array.from(e);let n=new ro(t),i=(s,c,d)=>{let u=(S,y)=>{S?it.close(s,v=>d(S)):d(null,y)},h=0;if(c===0)return u(null,0);let x=0,g=Buffer.alloc(512),w=(S,y)=>{if(S||y===void 0)return u(S);if(x+=y,x<512&&y)return it.read(s,g,x,g.length-x,h+x,w);if(h===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let v=new Wn(g);if(!v.cksumValid)return u(null,h);let I=512*Math.ceil((v.size??0)/512);if(h+I+512>c||(h+=I+512,h>=c))return u(null,h);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,it.read(s,g,0,512,h,w)};it.read(s,g,0,512,h,w)};return new Promise((s,c)=>{n.on("error",c);let d="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",it.open(t.file,d,u);if(h||!x)return c(h);it.fstat(x,(g,w)=>{if(g)return it.close(x,()=>c(g));i(x,w.size,(S,y)=>{if(S)return c(S);let v=new Qs(t.file,{fd:x,start:y});n.pipe(v),v.on("error",c),v.on("close",s),N_(n,e)})})};it.open(t.file,d,u)})},L_=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?kr({file:Df.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},N_=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await kr({file:Df.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},yi=Pi(P_,O_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!nw(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")}),YI=Pi(yi.syncFile,yi.asyncFile,yi.syncNoFile,yi.asyncNoFile,(t,e=[])=>{yi.validate?.(t,e),M_(t)}),M_=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))};dn();var ft={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function oo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Of(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ao(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Lf(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function Nf(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}Vt();je();ne();Le();je();function Tr(t,e){if(oo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Di(t){return t.startsWith("http://")||t.startsWith("https://")}function Rr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as UA}from"node:fs";import{dirname as qA,join as HA}from"node:path";import{fileURLToPath as WA}from"node:url";var Dt="0.2.2-beta.1";je();ne();var co="1008033",zf="1289";var Uf="pbbp2",Gf="https://www.coze.cn",qf="/api/coze_claw/resource/get_frontier_key",j_="https://www.coze.cn",W_="wss://frontier.coze.cn";function Cr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??j_}function Hf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??W_}function vn(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 Li(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Oi=H("handshake");async function Uc(t){let e=Cr(t.endpoint),n=t.timeoutMs??1e4,i=`${Rr(e)}${qf}?aid=${encodeURIComponent(co)}`,s={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...vn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),n);Oi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:s,signal:c.signal}),h=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let v=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${v.slice(0,200)}`)}let g=await u.json();if(g.code!==void 0&&g.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${g.code} msg=${g.msg??"-"} logid=${h}`);let w=g.data??{},S=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,y=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!S||!y){let v=JSON.stringify(g).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${v}`)}return Oi.info("handshake ok",{remoteDeviceId:y,logid:h,traceId:x}),{accessKey:S,deviceId:y}}catch(u){if(u instanceof k)throw Oi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Oi.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let h=u.cause;throw Oi.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(d)}}var qc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Ot="auto",Gc=15e4;function Wf(t){return{model:Hc(t.model)??Ot,...t.modelToken?{modelToken:t.modelToken}:{}}}function Kf(t){return!t||t===Ot}var K_=new Set(["auto","\u81EA\u52A8"]);function Hc(t){let e=t?.trim();if(e)return K_.has(e.toLowerCase())?Ot:e}function $f(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=qc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Ot;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=n,e.ANTHROPIC_DEFAULT_OPUS_MODEL=n,e.ANTHROPIC_DEFAULT_SONNET_MODEL=n,e.CLAUDE_CODE_SUBAGENT_MODEL=n,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else Kf(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Vf(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Ot}"`):Kf(t.model)||e.push("-c",`model="${t.model}"`),t.modelToken){e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${qc}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"');let n=t.modelInfo?.contextWindow??Gc;e.push("-c",`model_context_window=${n}`)}return e}function Yf(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function jc(t,e){let{ttEnv:n,usePpe:i}=Li(t),s={};return n&&(s["x-tt-env"]=n),i&&(s["x-use-ppe"]=i),e&&(s["x-mock-scenario"]=e),s}function Jf(t,e,n){if(!t.modelToken)return{};let i=jc(e,n);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
92
- `)}}function Wc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Kc(t){return t.model||Ot}function jf(t,e,n){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:8192,api:"openai-completions"}}function Zf(t,e,n,i){if(!t.modelToken)return null;let s=Kc(t),c=jc(e,n),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[jf(s,d,t.modelInfo?.contextWindow??Gc)],h=new Set([s]);for(let g of i??[])!g||h.has(g)||(h.add(g),u.push(jf(g,["text"],Gc)));let x={baseUrl:`${qc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(x.headers=c),x}function Xf(t,e,n){if(!t.modelToken)return[];let i=jc(e,n),s=[];for(let[c,d]of Object.entries(i))s.push("-c",`model_providers.coze.http_headers.${c}="${d}"`);return s}var he=H("agent-handlers"),Qf=5*1024*1024,Z_=1,X_=6,Q_=new Set(["node_modules",".git",".coze","dist","build",".next"]),ey=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,ty=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,ny=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function ry(t){let e=t?.trim();return e?ny.test(e)||ty.test(e)?e:(he.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function iy(t){return new Promise((e,n)=>{let i=nt("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),s=!1,c=d=>{s||(s=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",d=>c(d))})}var uo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let n=$n(e._meta),i=await this.loadAgentCfg(n),s=i?.workspace??$e(n).workspace,c=i?.skills??[],d=[],u=new Set;for(let h of c){let x=me(s,h.relPath,"SKILL.md");await n0(x).then(w=>w.isFile()).catch(()=>!1)&&(d.push(ly(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",x=await oy(n,s,h),g=await ay(n,h);for(let w of[...x,...g])u.has(w.relPath)||(u.add(w.relPath),d.push(w.skill))}return{skills:d}}async addSkills(e){e._meta;let n=$n(e._meta),i=await this.requireAgentCfg(n),s=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((h,x)=>[h.skillId,x])),u=[];for(let h of s){let x=await fo({agentId:n,workspace:i.workspace,framework:i.framework,skill:h});ho(c,d,x),u.push(h)}return await si(n,c),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=$n(e._meta),i=await this.requireAgentCfg(n),s=new Set(e.skillIds??[]),c=i.skills??[],d=[];for(let u of c){if(!s.has(u.skillId)){d.push(u);continue}let h=me(i.workspace,u.relPath);await Yc(h,{recursive:!0,force:!0}),he.info("skill removed",{agentId:n,skillId:u.skillId,relPath:u.relPath})}return await si(n,d),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");he.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),s=i?.workspace??$e(n).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=o0(e.skillName),h=await sy(s,c,u,d);if(!h){let D=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${D}: ${e.skillName} (${u})`)}let{absDir:x,relPath:g}=h,w=me(x,"SKILL.md"),S=new ed.default;S.addLocalFolder(x,u);let y=S.toBuffer();if(y.length>e0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${e0}`);let v=await lo(w,{encoding:"utf8"}).then(D=>d0(D).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):he.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",R=I.skillId??e.skillId??c0(n,g);if(i&&!d){let D=i.skills??[],E=D.find(C=>C.relPath===g);E?(E.version=A,E.skillId=R):D.push({skillId:R,skillName:e.skillName,relPath:g,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await si(n,D)}return he.info("skill published",{agentId:n,skillName:e.skillName,relPath:g,zipBytes:y.length,skillId:R,version:A}),{ok:!0,skillId:R,version:A}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[s,c]of i.sessions){if(!c.downstream)continue;let d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,he.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d});continue}let h=c.downstream;c.downstream=void 0,he.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d}),h.stop(n).catch(x=>he.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:s,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return he.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await Te(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return he.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await ur(i.workspace,i.framework,e.cozeIdentity)}catch(s){throw he.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(s)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(s)}`,{cause:s})}return i.cozeIdentity=e.cozeIdentity,await Be(i),he.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 Te(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=["-y"];e.registry&&Di(e.registry)&&s.push(`--registry=${e.registry}`);let c=ry(e.targetVersion);s.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&ey.test(d)&&s.push("--env",d);let u=await iy(s);return he.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 Te(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Be(i),he.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}):(he.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",`${ft.DELETE}: missing agentId`);let i=await Te(n),s=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??s??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let d=$e(n);return c==="cloud"?await Yc(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Be(i)),he.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Tr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=Hc(e.model)??Ot,i=await Te(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 Be(i),he.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return he.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=s.model;s.model=n,e.modelInfo&&s.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(s,c).catch(u=>he.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)}));let d=[];for(let[u,h]of s.allSessionQueues())d.push(h.enqueue(async()=>{let x=s.sessions.get(u);x?.downstream&&(await x.downstream.stop(`switchModel: ${n}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(d),he.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:d.length}),{ok:!0}}async resetAgent(e){if(Tr(e._meta,ft.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ft.RESET),await this.runDetailSync(e.agentId,ft.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),he.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(n);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let s=new Map;for(let[c,d]of i.sessions)s.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await ii(e,s)}async clearPersistedAcpSessionIds(e){let n=await Te(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let s of Object.values(n.sessions))s.acpSessionId&&(s.acpSessionId=void 0,i=!0);i&&await Be(n)}async repairAgent(e){if(Tr(e._meta,ft.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${ft.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){he.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ft.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){he.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){he.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(s)})}}async getFileTree(e){Tr(e._meta,"_agent/getFileTree");let n=e._meta,i=$n(n),s=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(s,c),u=await $c(d).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await ri(d,s))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=by(e.depth);return u.isDirectory()?{tree:await Ey(s,d,c,h)}:{tree:[{name:vy(c),path:h0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Tr(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 s=this.safeJoin(i,e.filePath),c=await $c(s).catch(()=>null);if(!c||!c.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await ri(s,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>Qf)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${Qf})`);let d=await lo(s);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:c.size}:{content:d.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let n=this.opts.agents.get(e);return n?n.workspace:(await Te(e).catch(()=>null))?.workspace??$e(e).workspace}safeJoin(e,n){let i=Zc(e,n||"."),s=Qc(e,i);if(s.startsWith("..")||s===".."||s.startsWith(`..${r0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return Te(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 o0(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 td(t){return t==="claude-code"?me(".claude","skills"):me(".agents","skills")}function a0(t){let e=V_();return t==="claude-code"?[me(e,".claude","skills")]:t==="codex"?[me(e,".agents","skills"),me(e,".codex","skills")]:[me(e,".agents","skills"),me(e,".openclaw","skills")]}async function sy(t,e,n,i){let s=async c=>n0(me(c,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let c=me(td(e),n),d=me(t,c);return await s(d)?{absDir:d,relPath:c}:null}for(let c of a0(e)){let d=me(c,n);if(await s(d))return{absDir:d,relPath:d}}return null}function c0(t,e){return($_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function d0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
- ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let s of n.split(`
94
- `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(s);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function l0(t,e,n,i){let s=await t0(e,{withFileTypes:!0}).catch(()=>null);if(!s)return[];let c=[];for(let d of s){if(!d.isDirectory())continue;let u=d.name,h=me(n,u),x=me(e,u,"SKILL.md"),g=await lo(x,{encoding:"utf8"}).catch(()=>null);if(g===null)continue;let w=d0(g);c.push({relPath:h,skill:{skillId:c0(t,h),skillName:w.name||u,...w.description?{description:w.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function oy(t,e,n){let i=td(n);return l0(t,me(e,i),i,!1)}async function ay(t,e){let n=[],i=new Set;for(let s of a0(e)){let c=await l0(t,s,s,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var cy=3e4,dy=50*1024*1024,e0=10*1024*1024,Pr=3e4;async function fo(t){let{agentId:e,workspace:n,framework:i,skill:s}=t;if(!s.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let c=typeof s.content=="string"&&s.content.length>0,d=typeof s.downloadUrl=="string"&&s.downloadUrl.length>0;if(!c&&!d)throw new k("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let u=o0(s.skillName),h=td(i),x=me(h,u),g=me(n,x);if(await Vc(g,{recursive:!0}),c){let S=Buffer.from(s.content,"utf8");Ni(S.length),await Jc(me(g,"SKILL.md"),S,"utf8")}else{let S=await fy(s.downloadUrl);xy(S)?await wy(S,g):py(S)?await gy(S,g):await Jc(me(g,"SKILL.md"),S.toString("utf8"),"utf8")}let w={skillId:s.skillId,skillName:s.skillName,relPath:x,installedAt:Date.now(),...s.description?{description:s.description}:{},...s.icon?{icon:s.icon}:{},...s.version?{version:s.version}:{},...s.downloadUrl?{downloadUrl:s.downloadUrl}:{},...s.config?{config:s.config}:{},...s.builtin?{builtin:s.builtin}:{}};return he.info("skill installed",{agentId:e,skillId:s.skillId,skillName:s.skillName,relPath:x,source:c?"content":"downloadUrl"}),w}function ho(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 ly(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 u0(t,e){let n=await Te(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Dt,s=n.skillsRefreshedForVersion;if(s===i)return{status:"noop",count:0};if(!s)return n.skillsRefreshedForVersion=i,await Be(n,e),{status:"seeded",count:0};let c=[...n.skills??[]],d=new Map(c.map((g,w)=>[g.skillId,w])),u=c.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Be(n,e),{status:"noop",count:0};let h=0,x=0;for(let g of u)try{await Yc(me(n.workspace,g.relPath),{recursive:!0,force:!0});let w=await fo({agentId:t,workspace:n.workspace,framework:n.framework,skill:uy(g)});ho(c,d,w),h+=1}catch(w){x+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(w)})}return n.skills=c,x===0&&(n.skillsRefreshedForVersion=i),await Be(n,e),he.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:s,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function fy(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ni(e);let n=hy(t);return Ni(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await lo(e);return Ni(n.length),n}if(Di(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),cy);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 s=await i.arrayBuffer();return Ni(s.byteLength),Buffer.from(s)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Ni(t){if(t>dy)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 xy(t){return t.length>=2&&t[0]===31&&t[1]===139}function py(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 Xc(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function gy(t,e){let n,i;try{n=new ed.default(t),i=n.getEntries()}catch(d){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||Xc(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=d.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 s=my(i),c=Zc(e);for(let d of i){if(Xc(d.entryName))continue;let u=d.entryName;if(s&&u.startsWith(s)&&(u=u.slice(s.length)),!u)continue;let h=Zc(e,u),x=Qc(c,h);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Vc(h,{recursive:!0});continue}await Vc(Y_(h),{recursive:!0});let g;try{g=d.getData()}catch(w){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await Jc(h,g)}}function my(t){let e;for(let n of t){let i=n.entryName;if(!i||Xc(i))continue;let s=i.indexOf("/");if(s<=0)return;let c=i.slice(0,s+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function wy(t,e){await _y(t);let n=Pf({cwd:e,strip:1}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`))},Pr);try{await s0(i0.from(t),n)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(s)}}async function _y(t){let e=[],n=kr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Pr}ms)`))},Pr);try{await s0(i0.from(t),n)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Pr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(s)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var yy=5e3;async function Ey(t,e,n,i){return f0(t,e,n,i,{count:0})}async function f0(t,e,n,i,s){if(i<=0)return[];let c;try{c=await t0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(Q_.has(u.name)||u.isSymbolicLink())continue;if(s.count>=yy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=me(e,u.name),x=J_(me(n,u.name)),g=null;try{g=await $c(h)}catch{continue}if(g.isSymbolicLink())continue;s.count++;let w={name:u.name,path:h0(Qc(t,h)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(w.children=await f0(t,h,x,i-1,s)),d.push(w)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function by(t){return!t||t<=0?Z_:Math.min(t,X_)}function vy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function h0(t){return t.split(r0).join("/")}ne();var Sn=H("agent-health-reporter"),Sy=1e4,Iy=3,Mi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Sy,this.livenessFailureThreshold=e.livenessFailureThreshold??Iy}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()}),Sn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Sn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Sn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Sn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let d of this.opts.core.agents.values()){let u=Ay(d);if(!u)continue;let h={agentId:d.agentId,status:u};d.patToken&&(h.patToken=d.patToken),d.accountId&&(h.accountId=d.accountId),n.push(h)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Dt,_meta:{cozeDeviceId:e}},s;try{s=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Sn.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=s?.authFailures;if(c&&c.length>0&&(Sn.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){Sn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Sn.warn("onTickEnd hook failed",{err:String(n)})}}};function Ay(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}dn();import{mkdir as ad,rm as mE,stat as wE}from"node:fs/promises";import{homedir as _E}from"node:os";import{join as q0}from"node:path";on();import{existsSync as zy}from"node:fs";import{release as Uy}from"node:os";import{basename as Gy,isAbsolute as qy}from"node:path";function Bi(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Dr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Or(t,e){return{jsonrpc:"2.0",id:t,result:e}}function In(t,e){return{jsonrpc:"2.0",id:t,error:e}}je();var xo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Z={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 x0(t){return"method"in t&&"id"in t&&t.id!==void 0}function p0(t){return"method"in t&&!("id"in t)}function po(t){return!("method"in t)&&"id"in t}var ky={AGENT_NOT_FOUND:Z.AGENT_NOT_FOUND,AGENT_BUSY:Z.AGENT_BUSY,AGENT_DISCONNECTED:Z.AGENT_DISCONNECTED,AGENT_TIMEOUT:Z.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Z.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Z.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Z.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Z.INTERNAL_ERROR,BRIDGE_INTERNAL:Z.INTERNAL_ERROR,IPC_AUTH_FAILED:Z.INTERNAL_ERROR,IPC_BAD_REQUEST:Z.INVALID_REQUEST,METHOD_NOT_FOUND:Z.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Z.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Z.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Z.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Z.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Z.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Z.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Z.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Z.FILE_TOO_LARGE,UNSUPPORTED_MIME:Z.UNSUPPORTED_MIME,UPLOAD_FAILED:Z.UPLOAD_FAILED,UPSTREAM_NOT_READY:Z.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Z.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Z.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Z.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Z.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Z.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Z.SKILL_ZIP_TOO_LARGE};function Ty(t){if(t!=null)return t instanceof Error?{name:t.name,message:Fi(t.message)}:typeof t=="string"?Fi(t):typeof t=="object"?Cy(t):t}var Ry=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Fi(t){let e=t;for(let[n,i]of Ry)e=e.replace(n,i);return e}function Cy(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Fi(i):e[n]=i;return e}function zi(t){if(t instanceof k){let e=Ty(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:ky[t.code]??Z.INTERNAL_ERROR,message:Fi(t.message),data:n}}return{code:Z.INTERNAL_ERROR,message:Fi(t instanceof Error?t.message:String(t))}}function g0(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,s=i?e?.message:t.message,c=t.data;if(i&&e){let{message:d,...u}=e;c=u}return new k(n,s,{retriable:e?.retriable??!1,cause:c})}function w0(t){return`${JSON.stringify(t)}
95
- `}var m0=10*1024*1024,go=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>m0){let s=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${s} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${m0} bytes`)}),[]}let n=this.buffer.split(`
96
- `);this.buffer=n.pop()??"";let i=[];for(let s of n){let c=s.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(d){this.onError?.({line:c,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(n){return this.onError?.({line:e,error:n}),[]}}};var y0={"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"},Ck=Object.fromEntries(Object.entries(y0).map(([t,e])=>[e,t])),Py={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Lr=class{seq=0;next(e,n){this.seq+=1;let i=y0[e]??Dy(e),s=Py[i]??[],c=[i,String(this.seq)];if(s.length>0){let d=s.map(h=>_0(n?.[h]??"")),u=Oy(d).join(":");u&&c.push(u)}else n&&Object.values(n).some(d=>d)&&c.push(Object.values(n).filter(Boolean).map(d=>_0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function Dy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function _0(t){return t.replace(/[:_\s]+/g,"-")}function Oy(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}cn();import{readFileSync as Ly}from"node:fs";var Ny=384;async function nd(t,e=process.env){let n={};for(let[i,s]of Object.entries(e))typeof s=="string"&&(n[i]=s);await lr(t.agentEnvFile,n,{mode:Ny})}function rd(t){try{let e=JSON.parse(Ly(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function E0(t,e,n={},i=s=>s){return{...i({...t,...rd(e)}),...n}}Vt();sr();je();ne();Le();import{execFileSync as My,spawnSync as By}from"node:child_process";function Ui(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Gi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),By("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var id=new Set;function b0(t){typeof t=="number"&&t>0&&id.add(t)}function v0(t){typeof t=="number"&&id.delete(t)}function S0(){for(let t of id)Gi(t,"SIGKILL")}var Nr="coze-bridge-daemon";function I0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let s=process.getuid?.()??0;return My("pgrep",["-U",String(s),"-f",Nr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
97
- `).map(s=>Number.parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0&&s!==i)}async function A0(t,e){if(t.length===0)return;let n=e?.killFn??Gi,i=e?.isAliveFn??Ui,s=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),c=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<c&&t.some(h=>i(h));u+=d)await s(Math.min(d,c-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var Fy=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find module[^\n]*node_modules[\\/]@(agentclientprotocol[\\/]claude-agent-acp|zed-industries[\\/]codex-acp)/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function k0(t,e){if(!e)return null;for(let n of Fy)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function T0(t,e){return k0(t,e)}function R0(t,e){return k0(t,e)}function Mr(t,e,n){return!e&&n.firstUpdateMs>0&&t<n.firstUpdateMs?Math.max(1,n.firstUpdateMs-t):t<n.phase2GateMs?Math.max(1,n.phase2GateMs-t):Math.max(1,n.livenessWindowMs)}function C0(t,e,n){let s=n-t.armedAt-t.expectedIntervalMs;if(s>e.suspendThresholdMs){let x=t.suspendedMs+s,g=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:s,rearmMs:Mr(g,t.firstFrameSeen,e)}}let c=n-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:Mr(c,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Mr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Mr(c,!1,e)}}var P0=Ke("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Hy=200,jy=40,Wy=Ke("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Ky=Ke("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),$y=Ke("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Vy=Ke("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Yy=Ke("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Jy=Ke("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),D0=500;function Zy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=D0?t:`${e.slice(0,D0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Xy(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 O0(t){try{return zy(t)}catch{return}}function Qy(t,e){return{platform:process.platform,osRelease:Uy(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:qy(e.command)?O0(e.command):void 0,cwd:e.cwd,cwdExists:O0(e.cwd),envKeys:e.envKeys}}function eE(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Gy(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Lt=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new go({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Lr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=E0(process.env,this.opts.agentEnvFile??ee().agentEnvFile,this.opts.env,s=>this.sanitizeEnv(s)),i=nt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,b0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",s=>{try{for(let c of this.decoder.push(s))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",s=>{let c=s.trimEnd();this.stderrRing.push(c),this.stderrRing.length>Hy&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",s=>{this.log.warn("child stdin error",{err:String(s)})}),i.stdout?.on("error",s=>{this.log.warn("child stdout error",{err:String(s)})}),i.stderr?.on("error",s=>{this.log.warn("child stderr error",{err:String(s)})}),i.on("exit",(s,c)=>{this.stopped=!0,v0(i.pid),(s!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:s,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(s,c));for(let u of this.exitHandlers)u(s,c)}),i.on("error",s=>{let c=s,d=Qy(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(s),diag:d}),this.failAllPending(new k("AGENT_SPAWN_FAILED",eE(c,d),{cause:d}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let n=this.child,i=new Promise(c=>n.once("exit",()=>c()));Gi(n.pid,"SIGTERM");let s=setTimeout(()=>{n.killed||Gi(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(s)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:Yy,phase2GateMs:Wy,livenessWindowMs:Ky,absoluteMaxMs:$y,approvalMaxMs:Jy,suspendThresholdMs:Vy,...n};return this.call("session/prompt",e,P0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Dr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Or(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(In(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=P0,s){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Bi(c,e,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 g={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(s){let w=this.now(),S={cfg:s,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:Mr(0,!1,s),sessionId:u};g.promptTimeout=S;let y=()=>{let v={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=C0(v,S.cfg,I),R=D=>{S.armedAt=I,S.expectedIntervalMs=D,g.timer=setTimeout(y,D)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),R(A.rearmMs);return}if(A.action==="continue"){R(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};g.timer=setTimeout(y,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(g.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,g);try{this.writeFrame(d)}catch(w){g.timer&&clearTimeout(g.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(w0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(po(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:Zy(e.result)}),n.resolve(e.result));return}if(p0(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let s=i.promptTimeout;s&&(s.firstFrameSeen=!0,s.lastActivityAt=this.now(),this.trackToolCall(s,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(s=>this.log.warn("update handler failed (async)",{err:String(s)}))}catch(s){this.log.warn("update handler threw sync, swallowed",{err:String(s)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(x0(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,s=i?.sessionUpdate;if(s!=="tool_call"&&s!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";s==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(In(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(In(e.id,zi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=g0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=R0(this.framework,Xy(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(jy).join(`
98
- `),s=T0(this.framework,i);return s?new k(s.bridgeCode,s.message,{cause:{reason:s.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 tE(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 mo=class extends Lt{framework="claude-code";constructor(e){let{command:n,args:i}=ni("claude-code",e.command,e.args??[]),s={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s)}sanitizeEnv(e){return tE(e)}};on();import{mkdtempSync as nE,rmSync as rE}from"node:fs";import{tmpdir as iE}from"node:os";import{join as sE}from"node:path";var wo=class extends Lt{framework="codex";authMethodId;codexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:s,args:c}=ni("codex",e.command,i),d=e.isolateCodexHome?nE(sE(iE(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,h={command:s,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(h),this.authMethodId=e.authMethodId,this.codexHomeDir=d}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async stop(e){if(await super.stop(e),this.codexHomeDir)try{rE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};je();var oE=3e4,Br=class extends Lt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let s={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},oE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var L0=["default","acceptEdits","plan","auto","bypassPermissions"],N0=["read-only","auto","full-access"];function An(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return L0.includes(e);case"codex":return N0.includes(e);case"openclaw":return!1}}function sd(t){switch(t){case"claude-code":return L0.join("/");case"codex":return N0.join("/");case"openclaw":return""}}cn();je();ne();Le();function od(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}on();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 _o=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)qi(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 qi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Yt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Vt();ne();import{constants as M0}from"node:fs";import{access as aE}from"node:fs/promises";import{delimiter as cE,join as dE}from"node:path";var bt=H("framework-detector"),B0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},lE=[".exe",".cmd",".bat",".ps1"],Vn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??nt,access:e.access??aE}}async detect(e){let n=B0[e],i=await this.which(n);if(!i)return bt.debug("framework binary not found",{framework:e,bin:n}),null;let s=e==="openclaw"?["--log-level","silent"]:[],[c,d]=await Promise.all([this.probeVersion(i,s),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(B0).map(async i=>[i,await this.detect(i)])),n={};for(let[i,s]of e)s&&(n[i]=s);return n}async which(e){let n=this.env.pathEnv.split(cE).filter(Boolean),i=this.env.platform==="win32"?["",...lE]:[""];for(let s of n)for(let c of i){let d=dE(s,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?M0.F_OK:M0.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return bt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return bt.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 bt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let s=JSON.parse(i[0]);if(!Array.isArray(s))return bt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=s.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(bt.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}:(bt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:s.length}),null)}catch(s){return bt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(s),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return bt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||bt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let s={reachable:i},c=n.stdout.match(/\{[\s\S]*\}/);if(c)try{let d=JSON.parse(c[0]);typeof d.gateway?.port=="number"&&(s.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(s.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(s.detail=d.rpc.error)}catch(d){bt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return s}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(fE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let s="",c=!1,d,u=h=>{c||(c=!0,d&&clearTimeout(d),i(h))};try{let h=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{s+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:s}))}catch{u(null)}})}},uE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function fE(t){return t.replace(uE,"")}import{homedir as hE}from"node:os";import{join as xE}from"node:path";cn();Vt();sr();je();ne();async function U0(){let t=xE(hE(),".openclaw/openclaw.json");return dr(t)}async function G0(){return(await U0())?.gateway?.auth?.token??""}var F0=H("openclaw.config"),pE=[0,5e3,5e3],gE=Ke("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),z0="models.providers.",yo="agents.defaults.models",Eo=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new kn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??pE,this.cliTimeoutMs=e.cliTimeoutMs??gE}async withRetry(e,n){let i;for(let s=0;s<this.retryDelaysMs.length;s++){let c=this.retryDelaysMs[s]??0;c>0&&await new Promise(d=>setTimeout(d,c));try{return await n()}catch(d){i=d,F0.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let s=nt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=x=>{d||(d=!0,clearTimeout(h),x())};s.stderr?.on("data",x=>{c+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.unref(),s.on("error",x=>u(()=>i(x))),s.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let s=String(i);if(n.some(c=>s.includes(c)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",n])))}catch(i){F0.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",`${z0}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${z0}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${yo}[${e}]`,()=>this.runCli(["config","set",yo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${yo}[${e}]`,`${yo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await U0())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let s=`${e}/`,c=[];for(let d of Object.keys(i))d.startsWith(s)&&c.push(d.slice(s.length));return c}ensureAgent(e,n,i){let s=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&s.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(s,["already exists","already registered"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var le=H("agent-manager"),dd="acceptEdits",W0="full-access",K0="read-only";function yE(t){switch(t){case"read-only":return["-c",'sandbox_mode="read-only"',"-c",'approval_policy="on-request"'];case"auto":return["-c",'sandbox_mode="workspace-write"',"-c",'approval_policy="on-failure"'];case"full-access":return["-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"']}}var EE=(t,e,n,i,s,c,d,u,h,x)=>{switch(t){case"claude-code":{let g={...s?{...$f(s),...Jf(s,d,u)}:{},...h??{},IS_SANDBOX:"1"};return new mo({cwd:n,env:g,agentId:i})}case"codex":{let g=s?[...Vf(s),...Xf(s,d,u)]:[],w=W0;x!==void 0&&(An("codex",x)?w=x:le.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let S=[...g,...yE(w)],y={...s?Yf(s):{},...h??{}},v=!!s;return new wo({cwd:n,agentId:i,...S.length>0?{extraArgs:S}:{},...Object.keys(y).length>0?{env:y}:{},...v?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Br({command:e,cwd:n,agentId:i,...c?{sessionName:od(c)}:{}})}};function cd(t){return t==="claude-code"||t==="codex"}function bE(t){let e=[],n=Object.keys(t).sort();for(let i of n){let s=t[i];s!==void 0&&(vE(s)||e.push(`${i}=${s}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return rI(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 Cp("schtasks",["/Create","/SC","ONLOGON","/TN",ga,"/TR",r,"/RU",t.userName,"/F"]),rd.info("task scheduler entry created",{task:ga,logFile:t.logFile})},async uninstall(t){await Cp("schtasks",["/Delete","/TN",ga,"/F"]).catch(e=>rd.warn("schtasks /Delete failed (ignored)",{err:String(e)})),rd.info("task scheduler entry removed",{task:ga})}}});var Pp={};Ra(Pp,{buildContext:()=>lI,getSupervisor:()=>oI,launchdSupervisor:()=>td,systemdSupervisor:()=>nd,taskSchedulerSupervisor:()=>id});import{homedir as iI,userInfo as sI}from"node:os";function oI(t=process.platform){switch(t){case"darwin":return td;case"linux":return nd;case"win32":return id;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function cI(){let t={};for(let e of aI){let r=process.env[e];r&&(t[e]=r)}return t}function lI(){let t=J();return{nodeBin:process.execPath,entry:Kl(t),logFile:t.logFile,homeDir:iI(),userName:sI().username,isRoot:process.getuid?.()===0,env:cI()}}var aI,Dp=et(()=>{"use strict";Ce();sa();Ap();kp();Rp();aI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();an();var Md=H("acp-installer-warmup"),sm=["claude-code","codex"];async function Bd(t={}){let e=t.ensure??ar,i=(await Promise.allSettled(sm.map(async o=>{let c=await e(o);Md.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Md.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))})}Ht();te();import{readdir as bm}from"node:fs/promises";import{mkdir as Hd,readFile as _m,writeFile as Gd}from"node:fs/promises";import{join as Ba}from"node:path";var ym={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function dr(t,e,r){await Hd(t,{recursive:!0});let i=ym[e],o=Ba(t,i);return await Gd(o,r??"","utf8"),o}async function Fa(t,e,r){let i=Ba(t,".claude");await Hd(i,{recursive:!0});let o=Ba(i,"settings.local.json"),c={};try{let u=await _m(o,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}catch{}let l=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")l.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");l.defaultMode===void 0&&(l.defaultMode=r)}return c.permissions=l,await Gd(o,JSON.stringify(c,null,2),"utf8"),o}var Ye=H("agent-detail-sync"),Em=6e4,vm=5*6e4,ys=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await bm(r)}catch(o){Ye.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Ye.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await Ee(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Ye.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(l){Ye.warn("detail sync failed for agent, skipping",{agentId:o,err:String(l)})}}})),Ye.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Ye.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Ye.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await Ee(e,this.opts.paths);if(!i){Ye.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){Ye.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,vm):Em;this.retryQueue.set(e,{dueAt:Date.now()+p,currentDelay:p});return}if(o.agentId&&o.agentId!==e){Ye.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,l=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,l=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Ye.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Ye.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Ye.debug("detail sync: no diff",{agentId:e});return}await Fe(i,this.opts.paths),Ye.info("detail sync: config updated",{agentId:e,identityChanged:l,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Ye.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await dr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var cl=zt(bu(),1);import{createHash as ly}from"node:crypto";import{lstat as tl,mkdir as nl,readFile as po,readdir as u0,rm as rl,stat as c0,writeFile as il}from"node:fs/promises";import{dirname as dy,join as $e,normalize as uy,relative as al,resolve as sl,sep as f0}from"node:path";import{Readable as h0}from"node:stream";import{pipeline as x0}from"node:stream/promises";import Wm from"events";import nt from"fs";import{EventEmitter as Bc}from"node:events";import nf from"node:stream";import{StringDecoder as Km}from"node:string_decoder";import of from"node:path";import Er from"node:fs";import{dirname as sw,parse as ow}from"path";import{EventEmitter as xw}from"events";import wc from"assert";import{Buffer as Hn}from"buffer";import*as Au from"zlib";import pw from"zlib";import{posix as pr}from"node:path";import{basename as Gw}from"node:path";import Xs from"fs";import Rt from"fs";import Ou from"path";import{win32 as e_}from"node:path";import Uu from"path";import bf from"node:fs";import m_ from"node:assert";import{randomBytes as Ef}from"node:crypto";import ie from"node:fs";import Ne from"node:path";import vf from"fs";import ao from"node:fs";import Ii from"node:path";import ot from"node:fs";import S_ from"node:fs/promises";import to from"node:path";import{join as Lf}from"node:path";import st from"node:fs";import Bf from"node:path";var qm=Object.defineProperty,jm=(t,e)=>{for(var r in e)qm(t,r,{get:e[r],enumerable:!0})},Eu=typeof process=="object"&&process?process:{stdout:null,stderr:null},$m=t=>!!t&&typeof t=="object"&&(t instanceof jn||t instanceof nf||Vm(t)||Jm(t)),Vm=t=>!!t&&typeof t=="object"&&t instanceof Bc&&typeof t.pipe=="function"&&t.pipe!==nf.Writable.prototype.pipe,Jm=t=>!!t&&typeof t=="object"&&t instanceof Bc&&typeof t.write=="function"&&typeof t.end=="function",Gt=Symbol("EOF"),qt=Symbol("maybeEmitEnd"),ln=Symbol("emittedEnd"),Is=Symbol("emittingEnd"),ci=Symbol("emittedError"),As=Symbol("closed"),vu=Symbol("read"),Ts=Symbol("flush"),Su=Symbol("flushChunk"),wt=Symbol("encoding"),xr=Symbol("decoder"),ze=Symbol("flowing"),li=Symbol("paused"),_r=Symbol("resume"),Ue=Symbol("buffer"),Xe=Symbol("pipes"),He=Symbol("bufferLength"),ja=Symbol("bufferPush"),ks=Symbol("bufferShift"),Ze=Symbol("objectMode"),Ie=Symbol("destroyed"),Wa=Symbol("error"),Ka=Symbol("emitData"),Iu=Symbol("emitEnd"),$a=Symbol("emitEnd2"),Tt=Symbol("async"),Va=Symbol("abort"),Cs=Symbol("aborted"),di=Symbol("signal"),Dn=Symbol("dataListeners"),it=Symbol("discarded"),ui=t=>Promise.resolve().then(t),Zm=t=>t(),Ym=t=>t==="end"||t==="finish"||t==="prefinish",Xm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Qm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),rf=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[_r](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},ew=class extends rf{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)}},tw=t=>!!t.objectMode,nw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",jn=class extends Bc{[ze]=!1;[li]=!1;[Xe]=[];[Ue]=[];[Ze];[wt];[Tt];[xr];[Gt]=!1;[ln]=!1;[Is]=!1;[As]=!1;[ci]=null;[He]=0;[Ie]=!1;[di];[Cs]=!1;[Dn]=0;[it]=!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");tw(e)?(this[Ze]=!0,this[wt]=null):nw(e)?(this[wt]=e.encoding,this[Ze]=!1):(this[Ze]=!1,this[wt]=null),this[Tt]=!!e.async,this[xr]=this[wt]?new Km(this[wt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ue]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Xe]});let{signal:r}=e;r&&(this[di]=r,r.aborted?this[Va]():r.addEventListener("abort",()=>this[Va]()))}get bufferLength(){return this[He]}get encoding(){return this[wt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ze]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Tt]}set async(t){this[Tt]=this[Tt]||!!t}[Va](){this[Cs]=!0,this.emit("abort",this[di]?.reason),this.destroy(this[di]?.reason)}get aborted(){return this[Cs]}set aborted(t){}write(t,e,r){if(this[Cs])return!1;if(this[Gt])throw new Error("write after end");if(this[Ie])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]?ui:Zm;if(!this[Ze]&&!Buffer.isBuffer(t)){if(Qm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Xm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ze]?(this[ze]&&this[He]!==0&&this[Ts](!0),this[ze]?this.emit("data",t):this[ja](t),this[He]!==0&&this.emit("readable"),r&&i(r),this[ze]):t.length?(typeof t=="string"&&!(e===this[wt]&&!this[xr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[wt]&&(t=this[xr].write(t)),this[ze]&&this[He]!==0&&this[Ts](!0),this[ze]?this.emit("data",t):this[ja](t),this[He]!==0&&this.emit("readable"),r&&i(r),this[ze]):(this[He]!==0&&this.emit("readable"),r&&i(r),this[ze])}read(t){if(this[Ie])return null;if(this[it]=!1,this[He]===0||t===0||t&&t>this[He])return this[qt](),null;this[Ze]&&(t=null),this[Ue].length>1&&!this[Ze]&&(this[Ue]=[this[wt]?this[Ue].join(""):Buffer.concat(this[Ue],this[He])]);let e=this[vu](t||null,this[Ue][0]);return this[qt](),e}[vu](t,e){if(this[Ze])this[ks]();else{let r=e;t===r.length||t===null?this[ks]():typeof r=="string"?(this[Ue][0]=r.slice(t),e=r.slice(0,t),this[He]-=t):(this[Ue][0]=r.subarray(t),e=r.subarray(0,t),this[He]-=t)}return this.emit("data",e),!this[Ue].length&&!this[Gt]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[Gt]=!0,this.writable=!1,(this[ze]||!this[li])&&this[qt](),this}[_r](){this[Ie]||(!this[Dn]&&!this[Xe].length&&(this[it]=!0),this[li]=!1,this[ze]=!0,this.emit("resume"),this[Ue].length?this[Ts]():this[Gt]?this[qt]():this.emit("drain"))}resume(){return this[_r]()}pause(){this[ze]=!1,this[li]=!0,this[it]=!1}get destroyed(){return this[Ie]}get flowing(){return this[ze]}get paused(){return this[li]}[ja](t){this[Ze]?this[He]+=1:this[He]+=t.length,this[Ue].push(t)}[ks](){return this[Ze]?this[He]-=1:this[He]-=this[Ue][0].length,this[Ue].shift()}[Ts](t=!1){do;while(this[Su](this[ks]())&&this[Ue].length);!t&&!this[Ue].length&&!this[Gt]&&this.emit("drain")}[Su](t){return this.emit("data",t),this[ze]}pipe(t,e){if(this[Ie])return t;this[it]=!1;let r=this[ln];return e=e||{},t===Eu.stdout||t===Eu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Xe].push(e.proxyErrors?new ew(this,t,e):new rf(this,t,e)),this[Tt]?ui(()=>this[_r]()):this[_r]()),t}unpipe(t){let e=this[Xe].find(r=>r.dest===t);e&&(this[Xe].length===1?(this[ze]&&this[Dn]===0&&(this[ze]=!1),this[Xe]=[]):this[Xe].splice(this[Xe].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[it]=!1,this[Dn]++,!this[Xe].length&&!this[ze]&&this[_r]();else if(t==="readable"&&this[He]!==0)super.emit("readable");else if(Ym(t)&&this[ln])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ci]){let i=e;this[Tt]?ui(()=>i.call(this,this[ci])):i.call(this,this[ci])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Dn]=this.listeners("data").length,this[Dn]===0&&!this[it]&&!this[Xe].length&&(this[ze]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Dn]=0,!this[it]&&!this[Xe].length&&(this[ze]=!1)),e}get emittedEnd(){return this[ln]}[qt](){!this[Is]&&!this[ln]&&!this[Ie]&&this[Ue].length===0&&this[Gt]&&(this[Is]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[As]&&this.emit("close"),this[Is]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Ie&&this[Ie])return!1;if(t==="data")return!this[Ze]&&!r?!1:this[Tt]?(ui(()=>this[Ka](r)),!0):this[Ka](r);if(t==="end")return this[Iu]();if(t==="close"){if(this[As]=!0,!this[ln]&&!this[Ie])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ci]=r,super.emit(Wa,r);let o=!this[di]||this.listeners("error").length?super.emit("error",r):!1;return this[qt](),o}else if(t==="resume"){let o=super.emit("resume");return this[qt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[qt](),i}[Ka](t){for(let r of this[Xe])r.dest.write(t)===!1&&this.pause();let e=this[it]?!1:super.emit("data",t);return this[qt](),e}[Iu](){return this[ln]?!1:(this[ln]=!0,this.readable=!1,this[Tt]?(ui(()=>this[$a]()),!0):this[$a]())}[$a](){if(this[xr]){let e=this[xr].end();if(e){for(let r of this[Xe])r.dest.write(e);this[it]||super.emit("data",e)}}for(let e of this[Xe])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ze]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Ze]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Ze])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[wt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Ie,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[it]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Gt])return e();let i,o,c=x=>{this.off("data",l),this.off("end",u),this.off(Ie,f),e(),o(x)},l=x=>{this.off("error",c),this.off("end",u),this.off(Ie,f),this.pause(),i({value:x,done:!!this[Gt]})},u=()=>{this.off("error",c),this.off("data",l),this.off(Ie,f),e(),i({done:!0,value:void 0})},f=()=>c(new Error("stream destroyed"));return new Promise((x,p)=>{o=p,i=x,this.once(Ie,f),this.once("error",c),this.once("end",u),this.once("data",l)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[it]=!1;let t=!1,e=()=>(this.pause(),this.off(Wa,e),this.off(Ie,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(Wa,e),this.once(Ie,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Ie])return t?this.emit("error",t):this.emit(Ie),this;this[Ie]=!0,this[it]=!0,this[Ue].length=0,this[He]=0;let e=this;return typeof e.close=="function"&&!this[As]&&e.close(),t?this.emit("error",t):this.emit(Ie),this}static get isStream(){return $m}},rw=nt.writev,_n=Symbol("_autoClose"),Et=Symbol("_close"),fi=Symbol("_ended"),le=Symbol("_fd"),Ja=Symbol("_finished"),$t=Symbol("_flags"),Za=Symbol("_flush"),gc=Symbol("_handleChunk"),mc=Symbol("_makeBuf"),vi=Symbol("_mode"),Rs=Symbol("_needDrain"),Sr=Symbol("_onerror"),Ir=Symbol("_onopen"),Ya=Symbol("_onread"),yr=Symbol("_onwrite"),yn=Symbol("_open"),bt=Symbol("_path"),xn=Symbol("_pos"),kt=Symbol("_queue"),br=Symbol("_read"),Xa=Symbol("_readSize"),Kt=Symbol("_reading"),hi=Symbol("_remain"),Qa=Symbol("_size"),Us=Symbol("_write"),On=Symbol("_writing"),Hs=Symbol("_defaultFlag"),Un=Symbol("_errored"),Fc=class extends jn{[Un]=!1;[le];[bt];[Xa];[Kt]=!1;[Qa];[hi];[_n];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[Un]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[bt]=t,this[Xa]=e.readSize||16*1024*1024,this[Kt]=!1,this[Qa]=typeof e.size=="number"?e.size:1/0,this[hi]=this[Qa],this[_n]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[br]():this[yn]()}get fd(){return this[le]}get path(){return this[bt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[yn](){nt.open(this[bt],"r",(t,e)=>this[Ir](t,e))}[Ir](t,e){t?this[Sr](t):(this[le]=e,this.emit("open",e),this[br]())}[mc](){return Buffer.allocUnsafe(Math.min(this[Xa],this[hi]))}[br](){if(!this[Kt]){this[Kt]=!0;let t=this[mc]();if(t.length===0)return process.nextTick(()=>this[Ya](null,0,t));nt.read(this[le],t,0,t.length,null,(e,r,i)=>this[Ya](e,r,i))}}[Ya](t,e,r){this[Kt]=!1,t?this[Sr](t):this[gc](e,r)&&this[br]()}[Et](){if(this[_n]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,nt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Sr](t){this[Kt]=!0,this[Et](),this.emit("error",t)}[gc](t,e){let r=!1;return this[hi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[hi]<=0)&&(r=!1,this[Et](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[br](),!1;case"error":return this[Un]?!1:(this[Un]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},iw=class extends Fc{[yn](){let t=!0;try{this[Ir](null,nt.openSync(this[bt],"r")),t=!1}finally{t&&this[Et]()}}[br](){let t=!0;try{if(!this[Kt]){this[Kt]=!0;do{let e=this[mc](),r=e.length===0?0:nt.readSync(this[le],e,0,e.length,null);if(!this[gc](r,e))break}while(!0);this[Kt]=!1}t=!1}finally{t&&this[Et]()}}[Et](){if(this[_n]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,nt.closeSync(t),this.emit("close")}}},no=class extends Wm{readable=!1;writable=!0;[Un]=!1;[On]=!1;[fi]=!1;[kt]=[];[Rs]=!1;[bt];[vi];[_n];[le];[Hs];[$t];[Ja]=!1;[xn];constructor(t,e){e=e||{},super(e),this[bt]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[vi]=e.mode===void 0?438:e.mode,this[xn]=typeof e.start=="number"?e.start:void 0,this[_n]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[xn]!==void 0?"r+":"w";this[Hs]=e.flags===void 0,this[$t]=e.flags===void 0?r:e.flags,this[le]===void 0&&this[yn]()}emit(t,...e){if(t==="error"){if(this[Un])return!1;this[Un]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[bt]}[Sr](t){this[Et](),this[On]=!0,this.emit("error",t)}[yn](){nt.open(this[bt],this[$t],this[vi],(t,e)=>this[Ir](t,e))}[Ir](t,e){this[Hs]&&this[$t]==="r+"&&t&&t.code==="ENOENT"?(this[$t]="w",this[yn]()):t?this[Sr](t):(this[le]=e,this.emit("open",e),this[On]||this[Za]())}end(t,e){return t&&this.write(t,e),this[fi]=!0,!this[On]&&!this[kt].length&&typeof this[le]=="number"&&this[yr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[fi]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[On]||this[kt].length?(this[kt].push(t),this[Rs]=!0,!1):(this[On]=!0,this[Us](t),!0)}[Us](t){nt.write(this[le],t,0,t.length,this[xn],(e,r)=>this[yr](e,r))}[yr](t,e){t?this[Sr](t):(this[xn]!==void 0&&typeof e=="number"&&(this[xn]+=e),this[kt].length?this[Za]():(this[On]=!1,this[fi]&&!this[Ja]?(this[Ja]=!0,this[Et](),this.emit("finish")):this[Rs]&&(this[Rs]=!1,this.emit("drain"))))}[Za](){if(this[kt].length===0)this[fi]&&this[yr](null,0);else if(this[kt].length===1)this[Us](this[kt].pop());else{let t=this[kt];this[kt]=[],rw(this[le],t,this[xn],(e,r)=>this[yr](e,r))}}[Et](){if(this[_n]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,nt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},sf=class extends no{[yn](){let t;if(this[Hs]&&this[$t]==="r+")try{t=nt.openSync(this[bt],this[$t],this[vi])}catch(e){if(e?.code==="ENOENT")return this[$t]="w",this[yn]();throw e}else t=nt.openSync(this[bt],this[$t],this[vi]);this[Ir](null,t)}[Et](){if(this[_n]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,nt.closeSync(t),this.emit("close")}}[Us](t){let e=!0;try{this[yr](null,nt.writeSync(this[le],t,0,t.length,this[xn])),e=!1}finally{if(e)try{this[Et]()}catch{}}}},aw=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"]]),cw=t=>!!t.sync&&!!t.file,lw=t=>!t.sync&&!!t.file,dw=t=>!!t.sync&&!t.file,uw=t=>!t.sync&&!t.file,fw=t=>!!t.file,hw=t=>aw.get(t)||t,zc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=hw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Di=(t,e,r,i,o)=>Object.assign((c=[],l,u)=>{Array.isArray(c)&&(l=c,c={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let f=zc(c);if(o?.(f,l),cw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,l)}else if(lw(f)){let x=e(f,l);return u?x.then(()=>u(),u):x}else if(dw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(f,l)}else if(uw(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,l)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),gw=pw.constants||{ZLIB_VERNUM:4736},Dt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},gw)),mw=Hn.concat,Tu=Object.getOwnPropertyDescriptor(Hn,"concat"),ww=t=>t,ec=Tu?.writable===!0||Tu?.set!==void 0?t=>{Hn.concat=t?ww:mw}:t=>{},Gn=Symbol("_superWrite"),Ps=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"}},tc=Symbol("flushFlag"),Uc=class extends jn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Au[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Au[e](t)}catch(r){throw new Ps(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 Ps(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return wc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Hn.alloc(0),{[tc]: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}[Gn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Hn.from(t,e)),this.#e)return;wc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},ec(!0);let l;try{let f=typeof t[tc]=="number"?t[tc]:this.#r;l=this.#t._processChunk(t,f),ec(!1)}catch(f){ec(!1),this.#o(new Ps(f,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",f=>this.#o(new Ps(f,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let f=l[0];u=this[Gn](Hn.from(f));for(let x=1;x<l.length;x++)u=this[Gn](l[x])}else u=this[Gn](Hn.from(l));return r&&r(),u}},af=class extends Uc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Dt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Dt.Z_FINISH,t.fullFlushFlag=Dt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Dt.Z_SYNC_FLUSH),wc(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)}}}},_w=class extends af{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Gn](t){return this.#e?(this.#e=!1,t[9]=255,super[Gn](t)):super[Gn](t)}},yw=class extends af{constructor(t){super(t,"Unzip")}},cf=class extends Uc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Dt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Dt.BROTLI_OPERATION_FLUSH,super(t,e)}},bw=class extends cf{constructor(t){super(t,"BrotliCompress")}},Ew=class extends cf{constructor(t){super(t,"BrotliDecompress")}},lf=class extends Uc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Dt.ZSTD_e_end,t.fullFlushFlag=Dt.ZSTD_e_flush,super(t,e)}},vw=class extends lf{constructor(t){super(t,"ZstdCompress")}},Sw=class extends lf{constructor(t){super(t,"ZstdDecompress")}},Iw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Tw(t,e):Aw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Aw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Tw=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),r?e[i-1]=df(o):o===0?e[i-1]=0:(r=!0,e[i-1]=uf(o))}},kw=t=>{let e=t[0],r=e===128?Rw(t.subarray(1,t.length)):e===255?Cw(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},Cw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),l;i?l=df(c):c===0?l=c:(i=!0,l=uf(c)),l!==0&&(r-=l*Math.pow(256,e-o-1))}return r},Rw=t=>{for(var e=t.length,r=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(r+=o*Math.pow(256,e-i-1))}return r},df=t=>(255^t)&255,uf=t=>(255^t)+1&255,Pw={};jm(Pw,{code:()=>Hc,isCode:()=>Gs,isName:()=>Dw,name:()=>ro,normalFsTypes:()=>ff});var Gs=t=>ro.has(t),Dw=t=>Hc.has(t),ff=new Set(["0","","1","2","3","4","5","6","7","D"]),ro=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Hc=new Map(Array.from(ro).map(t=>[t[1],t[0]])),qn=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=Ln(t,e+156,1),c=ff.has(o),l=c?r:void 0,u=c?i:void 0;if(this.path=l?.path??Ln(t,e,100),this.mode=l?.mode??u?.mode??pn(t,e+100,8),this.uid=l?.uid??u?.uid??pn(t,e+108,8),this.gid=l?.gid??u?.gid??pn(t,e+116,8),this.size=l?.size??u?.size??pn(t,e+124,12),this.mtime=l?.mtime??u?.mtime??nc(t,e+136,12),this.cksum=pn(t,e+148,12),u&&this.#n(u,!0),l&&this.#n(l),Gs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Ln(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=l?.uname??u?.uname??Ln(t,e+265,32),this.gname=l?.gname??u?.gname??Ln(t,e+297,32),this.devmaj=l?.devmaj??u?.devmaj??pn(t,e+329,8)??0,this.devmin=l?.devmin??u?.devmin??pn(t,e+337,8)??0,t[e+475]!==0){let x=Ln(t,e+345,155);this.path=x+"/"+this.path}else{let x=Ln(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=r?.atime??i?.atime??nc(t,e+476,12),this.ctime=r?.ctime??i?.ctime??nc(t,e+488,12)}let f=256;for(let x=e;x<e+148;x++)f+=t[x];for(let x=e+156;x<e+512;x++)f+=t[x];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,i=Ow(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Nn(t,e,100,o)||this.needPax,this.needPax=gn(t,e+100,8,this.mode)||this.needPax,this.needPax=gn(t,e+108,8,this.uid)||this.needPax,this.needPax=gn(t,e+116,8,this.gid)||this.needPax,this.needPax=gn(t,e+124,12,this.size)||this.needPax,this.needPax=rc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Nn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Nn(t,e+265,32,this.uname)||this.needPax,this.needPax=Nn(t,e+297,32,this.gname)||this.needPax,this.needPax=gn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=gn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Nn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Nn(t,e+345,155,c)||this.needPax:(this.needPax=Nn(t,e+345,130,c)||this.needPax,this.needPax=rc(t,e+476,12,this.atime)||this.needPax,this.needPax=rc(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,gn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:ro.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Hc.get(t));if(Gs(e)||e==="Unsupported")this.#e=e;else if(Gs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Ow=(t,e)=>{let r=t,i="",o,c=pr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=pr.dirname(r),r=pr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?o=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?o=[r.slice(0,99),i,!0]:(r=pr.join(pr.basename(i),r),i=pr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Ln=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),nc=(t,e,r)=>Lw(pn(t,e,r)),Lw=t=>t===void 0?void 0:new Date(t*1e3),pn=(t,e,r)=>Number(t[e])&128?kw(t.subarray(e,e+r)):Mw(t,e,r),Nw=t=>isNaN(t)?void 0:t,Mw=(t,e,r)=>Nw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Bw={12:8589934591,8:2097151},gn=(t,e,r,i)=>i===void 0?!1:i>Bw[r]||i<0?(Iw(i,t.subarray(e,e+r)),!0):(Fw(t,e,r,i),!1),Fw=(t,e,r,i)=>t.write(zw(i,r),e,r,"ascii"),zw=(t,e)=>Uw(Math.floor(t).toString(8),e),Uw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",rc=(t,e,r,i)=>i===void 0?!1:gn(t,e,r,i.getTime()/1e3),Hw=new Array(156).join("\0"),Nn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Hw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Ys=class hf{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 qn({path:("PaxHeader/"+Gw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(o),l=Math.floor(Math.log(c)/Math.log(10))+1;return c+l>=Math.pow(10,l)&&(l+=1),l+c+o}static parse(e,r,i=!1){return new hf(qw(jw(e),r),i)}},qw=(t,e)=>e?Object.assign({},e,t):t,jw=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(Ww,Object.create(null)),Ww=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),l=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(l)*1e3):/^[0-9]+$/.test(l)?+l:l,t},Kw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=Kw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),$w=class extends jn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},io=(t,e,r,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=r instanceof Error&&r.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),t.emit("warn",e,r,i)):r instanceof Error?t.emit("error",Object.assign(r,i)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),i))},Vw=1024*1024,_c=Buffer.from([31,139]),yc=Buffer.from([40,181,47,253]),Jw=Math.max(_c.length,yc.length),dt=Symbol("state"),Mn=Symbol("writeEntry"),jt=Symbol("readEntry"),ic=Symbol("nextEntry"),ku=Symbol("processEntry"),Ct=Symbol("extendedHeader"),xi=Symbol("globalExtendedHeader"),dn=Symbol("meta"),Cu=Symbol("emitMeta"),ge=Symbol("buffer"),Wt=Symbol("queue"),un=Symbol("ended"),sc=Symbol("emittedEnd"),Bn=Symbol("emit"),Re=Symbol("unzip"),Ds=Symbol("consumeChunk"),Os=Symbol("consumeChunkSub"),oc=Symbol("consumeBody"),Ru=Symbol("consumeMeta"),Pu=Symbol("consumeHeader"),pi=Symbol("consuming"),ac=Symbol("bufferConcat"),Ls=Symbol("maybeEnd"),gr=Symbol("writing"),fn=Symbol("aborted"),Ns=Symbol("onDone"),Fn=Symbol("sawValidEntry"),Ms=Symbol("sawNullBlock"),Bs=Symbol("sawEOF"),Du=Symbol("closeStream"),Zw=()=>!0,Pi=class extends xw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Wt]=[];[ge];[jt];[Mn];[dt]="begin";[dn]="";[Ct];[xi];[un]=!1;[Re];[fn]=!1;[Fn];[Ms]=!1;[Bs]=!1;[gr]=!1;[pi]=!1;[sc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ns,()=>{(this[dt]==="begin"||this[Fn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ns,t.ondone):this.on(Ns,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Vw,this.filter=typeof t.filter=="function"?t.filter:Zw;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[Du]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){io(this,t,e,r)}[Pu](t,e){this[Fn]===void 0&&(this[Fn]=!1);let r;try{r=new qn(t,e,this[Ct],this[xi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Ms]?(this[Bs]=!0,this[dt]==="begin"&&(this[dt]="header"),this[Bn]("eof")):(this[Ms]=!0,this[Bn]("nullBlock"));else if(this[Ms]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let i=r.type;if(/^(Symbolic)?Link$/.test(i)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let o=this[Mn]=new $w(r,this[Ct],this[xi]);if(!this[Fn])if(o.remain){let c=()=>{o.invalid||(this[Fn]=!0)};o.on("end",c)}else this[Fn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Bn]("ignoredEntry",o),this[dt]="ignore",o.resume()):o.size>0&&(this[dn]="",o.on("data",c=>this[dn]+=c),this[dt]="meta"):(this[Ct]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Bn]("ignoredEntry",o),this[dt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[dt]="body":(this[dt]="header",o.end()),this[jt]?this[Wt].push(o):(this[Wt].push(o),this[ic]())))}}}[Du](){queueMicrotask(()=>this.emit("close"))}[ku](t){let e=!0;if(!t)this[jt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[jt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ic]()),e=!1);return e}[ic](){do;while(this[ku](this[Wt].shift()));if(this[Wt].length===0){let t=this[jt];!t||t.flowing||t.size===t.remain?this[gr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[oc](t,e){let r=this[Mn];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[dt]="header",this[Mn]=void 0,r.end()),o.length}[Ru](t,e){let r=this[Mn],i=this[oc](t,e);return!this[Mn]&&r&&this[Cu](r),i}[Bn](t,e,r){this[Wt].length===0&&!this[jt]?this.emit(t,e,r):this[Wt].push([t,e,r])}[Cu](t){switch(this[Bn]("meta",this[dn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=Ys.parse(this[dn],this[Ct],!1);break;case"GlobalExtendedHeader":this[xi]=Ys.parse(this[dn],this[xi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[dn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[dn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[fn]=!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[fn])return r?.(),!1;if((this[Re]===void 0||this.brotli===void 0&&this[Re]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<Jw)return this[ge]=t,r?.(),!0;for(let l=0;this[Re]===void 0&&l<_c.length;l++)t[l]!==_c[l]&&(this[Re]=!1);let o=!1;if(this[Re]===!1&&this.zstd!==!1){o=!0;for(let l=0;l<yc.length;l++)if(t[l]!==yc[l]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Re]===!1&&c)if(t.length<512)if(this[un])this.brotli=!0;else return this[ge]=t,r?.(),!0;else try{new qn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Re]===void 0||this[Re]===!1&&(this.brotli||o)){let l=this[un];this[un]=!1,this[Re]=this[Re]===void 0?new yw({}):o?new Sw({}):new Ew({}),this[Re].on("data",f=>this[Ds](f)),this[Re].on("error",f=>this.abort(f)),this[Re].on("end",()=>{this[un]=!0,this[Ds]()}),this[gr]=!0;let u=!!this[Re][l?"end":"write"](t);return this[gr]=!1,r?.(),u}}this[gr]=!0,this[Re]?this[Re].write(t):this[Ds](t),this[gr]=!1;let i=this[Wt].length>0?!1:this[jt]?this[jt].flowing:!0;return!i&&this[Wt].length===0&&this[jt]?.once("drain",()=>this.emit("drain")),r?.(),i}[ac](t){t&&!this[fn]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[Ls](){if(this[un]&&!this[sc]&&!this[fn]&&!this[pi]){this[sc]=!0;let t=this[Mn];if(t&&t.blockRemain){let e=this[ge]?this[ge].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ge]&&t.write(this[ge]),t.end()}this[Bn](Ns)}}[Ds](t){if(this[pi]&&t)this[ac](t);else if(!t&&!this[ge])this[Ls]();else if(t){if(this[pi]=!0,this[ge]){this[ac](t);let e=this[ge];this[ge]=void 0,this[Os](e)}else this[Os](t);for(;this[ge]&&this[ge]?.length>=512&&!this[fn]&&!this[Bs];){let e=this[ge];this[ge]=void 0,this[Os](e)}this[pi]=!1}(!this[ge]||this[un])&&this[Ls]()}[Os](t){let e=0,r=t.length;for(;e+512<=r&&!this[fn]&&!this[Bs];)switch(this[dt]){case"begin":case"header":this[Pu](t,e),e+=512;break;case"ignore":case"body":e+=this[oc](t,e);break;case"meta":e+=this[Ru](t,e);break;default:throw new Error("invalid state: "+this[dt])}e<r&&(this[ge]=this[ge]?Buffer.concat([t.subarray(e),this[ge]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[fn]||(this[Re]?(t&&this[Re].write(t),this[Re].end()):(this[un]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ls]())),this}},Si=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)},Yw=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},xf=(t,e)=>{let r=new Map(e.map(c=>[Si(c),!0])),i=t.filter,o=(c,l="")=>{let u=l||ow(c).root||".",f;if(c===u)f=!1;else{let x=r.get(c);f=x!==void 0?x:o(sw(c),u)}return r.set(c,f),f};t.filter=i?(c,l)=>i(c,l)&&o(Si(c)):c=>o(Si(c))},Xw=t=>{let e=new Pi(t),r=t.file,i;try{i=Er.openSync(r,"r");let o=Er.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let l=Buffer.allocUnsafe(o.size),u=Er.readSync(i,l,0,o.size,0);e.end(u===l.byteLength?l:l.subarray(0,u))}else{let l=0,u=Buffer.allocUnsafe(c);for(;l<o.size;){let f=Er.readSync(i,u,0,c,l);if(f===0)break;l+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Er.closeSync(i)}catch{}}},Qw=(t,e)=>{let r=new Pi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("end",c),Er.stat(o,(u,f)=>{if(u)l(u);else{let x=new Fc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Ar=Di(Xw,Qw,t=>new Pi(t),t=>new Pi(t),(t,e)=>{e?.length&&xf(t,e),t.noResume||Yw(t)}),pf=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:t_,parse:Lu}=e_,Gc=t=>{let e="",r=Lu(t);for(;t_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Lu(t)}return[e,t]},so=["|","<",">","?",":"],qc=so.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),n_=new Map(so.map((t,e)=>[t,qc[e]])),r_=new Map(qc.map((t,e)=>[t,so[e]])),Nu=t=>so.reduce((e,r)=>e.split(r).join(n_.get(r)),t),i_=t=>qc.reduce((e,r)=>e.split(r).join(r_.get(r)),t),gf=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Si(e)+"/"+t):Q(t),s_=16*1024*1024,Mu=Symbol("process"),Bu=Symbol("file"),Fu=Symbol("directory"),bc=Symbol("symlink"),zu=Symbol("hardlink"),gi=Symbol("header"),qs=Symbol("read"),Ec=Symbol("lstat"),js=Symbol("onlstat"),vc=Symbol("onread"),Sc=Symbol("onreadlink"),Ic=Symbol("openfile"),Ac=Symbol("onopenfile"),mn=Symbol("close"),Qs=Symbol("mode"),Tc=Symbol("awaitDrain"),cc=Symbol("ondrain"),Pt=Symbol("prefix"),mf=class extends jn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=zc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||s_,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Q(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Q(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,l]=Gc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=i_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||Ou.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[js](o):this[Ec]()}warn(t,e,r={}){return io(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Ec](){Rt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[js](e)})}[js](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=c_(t),this.emit("stat",t),this[Mu]()}[Mu](){switch(this.type){case"File":return this[Bu]();case"Directory":return this[Fu]();case"SymbolicLink":return this[bc]();default:return this.end()}}[Qs](t){return pf(t,this.type==="Directory",this.portable)}[Pt](t){return gf(t,this.prefix)}[gi](){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 qn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this[Qs](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new Ys({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Fu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[gi](),this.end()}[bc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Sc](e)})}[Sc](t){this.linkpath=Q(t),this[gi](),this.end()}[zu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Ou.relative(this.cwd,t)),this.stat.size=0,this[gi](),this.end()}[Bu](){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[zu](e);this.linkCache.set(t,this.absolute)}if(this[gi](),this.stat.size===0)return this.end();this[Ic]()}[Ic](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ac](e)})}[Ac](t){if(this.fd=t,this.#e)return this[mn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[qs]()}[qs](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Rt.read(t,e,r,i,o,(c,l)=>{if(c)return this[mn](()=>this.emit("error",c));this[vc](l)})}[mn](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[vc](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[mn](()=>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[mn](()=>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[cc]():this[Tc](()=>this[cc]())}[Tc](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)}[cc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[mn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[qs]()}},o_=class extends mf{sync=!0;[Ec](){this[js](Rt.lstatSync(this.absolute))}[bc](){this[Sc](Rt.readlinkSync(this.absolute))}[Ic](){this[Ac](Rt.openSync(this.absolute,"r"))}[qs](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let l=Rt.readSync(e,r,i,o,c);this[vc](l),t=!1}finally{if(t)try{this[mn](()=>{})}catch{}}}[Tc](t){t()}[mn](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},a_=class extends jn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return io(this,t,e,r)}constructor(t,e={}){let r=zc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[Qs](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[l,u]=Gc(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 qn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new Ys({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Pt](t){return gf(t,this.prefix)}[Qs](t){return pf(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},c_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",l_=class vr{tail;head;length=0;static create(e=[]){return new vr(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)u_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)f_(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new vr;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new vr;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new vr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new vr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let l=0;o&&l<e;l++)o=o.next;let c=[];for(let l=0;o&&l<r;l++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let l of i)o=d_(this,o,l);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=r,this.tail=e,this}};function d_(t,e,r){let i=e,o=e?e.next:t.head,c=new jc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function u_(t,e){t.tail=new jc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function f_(t,e){t.head=new jc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var jc=class{list;next;prev;value;constructor(t,e,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}},Hu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Gu=Buffer.alloc(1024),Ws=Symbol("onStat"),mi=Symbol("ended"),_t=Symbol("queue"),wi=Symbol("pendingLinks"),hn=Symbol("current"),zn=Symbol("process"),_i=Symbol("processing"),Fs=Symbol("processJob"),yt=Symbol("jobs"),lc=Symbol("jobDone"),Ks=Symbol("addFSEntry"),qu=Symbol("addTarEntry"),kc=Symbol("stat"),Cc=Symbol("readdir"),$s=Symbol("onreaddir"),Vs=Symbol("pipe"),ju=Symbol("entry"),dc=Symbol("entryOpt"),Js=Symbol("writeEntryClass"),wf=Symbol("write"),uc=Symbol("ondrain"),oo=class extends jn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Js];onWriteEntry;[_t];[wi]=new Map;[yt]=0;[_i]=!1;[mi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[Js]=mf,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 _w(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new bw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new vw(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[uc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[uc]);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[_t]=new l_,this[yt]=0,this.jobs=Number(t.jobs)||4,this[_i]=!1,this[mi]=!1}[wf](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[mi]=!0,this[zn](),r&&r(),this}write(t){if(this[mi])throw new Error("write after end");return typeof t=="string"?this[Ks](t):this[qu](t),this.flowing}[qu](t){let e=Q(Uu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Hu(t.path,e);r.entry=new a_(t,this[dc](r)),r.entry.on("end",()=>this[lc](r)),this[yt]+=1,this[_t].push(r)}this[zn]()}[Ks](t){let e=Q(Uu.resolve(this.cwd,t));this[_t].push(new Hu(t,e)),this[zn]()}[kc](t){t.pending=!0,this[yt]+=1;let e=this.follow?"stat":"lstat";Xs[e](t.absolute,(r,i)=>{t.pending=!1,this[yt]-=1,r?this.emit("error",r):this[Ws](t,i)})}[Ws](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[hn])this[Fs](t);else{let r=`${e.dev}:${e.ino}`,i=this[wi].get(r);i?i.push(t):this[wi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[zn]()}[Cc](t){t.pending=!0,this[yt]+=1,Xs.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[yt]-=1,e)return this.emit("error",e);this[$s](t,r)})}[$s](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[zn]()}[zn](){if(!this[_i]){this[_i]=!0;for(let t=this[_t].head;t&&this[yt]<this.jobs;t=t.next)if(this[Fs](t.value),t.value.ignore){let e=t.next;this[_t].removeNode(t),t.next=e}this[_i]=!1,this[mi]&&this[_t].length===0&&this[yt]===0&&(this.zip?this.zip.end(Gu):(super.write(Gu),super.end()))}}get[hn](){return this[_t]&&this[_t].head&&this[_t].head.value}[lc](t){this[_t].shift(),this[yt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[wi].get(r);if(i){this[wi].delete(r);for(let o of i)o.pending=!1,this[Fs](o)}}this[zn]()}[Fs](t){if(t.pending&&t.pendingLink&&t===this[hn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[hn]&&!t.piped&&this[Vs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Ws](t,e):this[kc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[$s](t,e):this[Cc](t),!t.readdir)return}if(t.entry=this[ju](t),!t.entry){t.ignore=!0;return}t===this[hn]&&!t.piped&&this[Vs](t)}}}[dc](t){return{onwarn:(e,r,i)=>this.warn(e,r,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[ju](t){this[yt]+=1;try{return new this[Js](t.path,this[dc](t)).on("end",()=>this[lc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[uc](){this[hn]&&this[hn].entry&&this[hn].entry.resume()}[Vs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ks](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){io(this,t,e,r)}},Wc=class extends oo{sync=!0;constructor(t){super(t),this[Js]=o_}pause(){}resume(){}[kc](t){let e=this.follow?"statSync":"lstatSync";this[Ws](t,Xs[e](t.absolute))}[Cc](t){this[$s](t,Xs.readdirSync(t.absolute))}[Vs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ks](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[wf](i)})}},h_=(t,e)=>{let r=new Wc(t),i=new sf(t.file,{mode:t.mode||438});r.pipe(i),_f(r,e)},x_=(t,e)=>{let r=new oo(t),i=new no(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((c,l)=>{i.on("error",l),i.on("close",c),r.on("error",l)});return yf(r,e).catch(c=>r.emit("error",c)),o},_f=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Ar({file:of.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},yf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Ar({file:of.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},p_=(t,e)=>{let r=new Wc(t);return _f(r,e),r},g_=(t,e)=>{let r=new oo(t);return yf(r,e).catch(i=>r.emit("error",i)),r},W2=Di(h_,x_,p_,g_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),w_=process.env.__FAKE_PLATFORM__||process.platform,Sf=w_==="win32",{O_CREAT:If,O_NOFOLLOW:Wu,O_TRUNC:Af,O_WRONLY:Tf}=vf.constants,kf=Number(process.env.__FAKE_FS_O_FILENAME__)||vf.constants.UV_FS_O_FILEMAP||0,__=Sf&&!!kf,y_=512*1024,b_=kf|Af|If|Tf,Ku=!Sf&&typeof Wu=="number"?Wu|Af|If|Tf:null,Cf=Ku!==null?()=>Ku:__?t=>t<y_?b_:"w":()=>"w",Rc=(t,e,r)=>{try{return ao.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},eo=(t,e,r,i)=>{ao.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},E_=(t,e,r,i,o)=>{if(e.isDirectory())Rf(Ii.resolve(t,e.name),r,i,c=>{if(c)return o(c);let l=Ii.resolve(t,e.name);eo(l,r,i,o)});else{let c=Ii.resolve(t,e.name);eo(c,r,i,o)}},Rf=(t,e,r,i)=>{ao.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return eo(t,e,r,i);let l=c.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--l===0)return eo(t,e,r,i)}};for(let x of c)E_(t,x,e,r,f)})},v_=(t,e,r,i)=>{e.isDirectory()&&Pf(Ii.resolve(t,e.name),r,i),Rc(Ii.resolve(t,e.name),r,i)},Pf=(t,e,r)=>{let i;try{i=ao.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Rc(t,e,r);throw c}for(let o of i)v_(t,o,e,r);return Rc(t,e,r)},Df=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},co=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},I_=(t,e)=>{ot.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Df(t,r?.code||"ENOTDIR")),e(r)})},A_=(t,e,r)=>{t=Q(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,l=e.uid,u=e.gid,f=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),x=e.preserve,p=e.unlink,m=Q(e.cwd),v=(b,I)=>{b?r(b):I&&f?Rf(I,l,u,A=>v(A)):c?ot.chmod(t,o,r):r()};if(t===m)return I_(t,v);if(x)return S_.mkdir(t,{mode:o,recursive:!0}).then(b=>v(null,b??void 0),v);let _=Q(to.relative(m,t)).split("/");Pc(m,_,o,p,m,void 0,v)},Pc=(t,e,r,i,o,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),f=Q(to.resolve(t+"/"+u));ot.mkdir(f,r,Of(f,e,r,i,o,c,l))},Of=(t,e,r,i,o,c,l)=>u=>{u?ot.lstat(t,(f,x)=>{if(f)f.path=f.path&&Q(f.path),l(f);else if(x.isDirectory())Pc(t,e,r,i,o,c,l);else if(i)ot.unlink(t,p=>{if(p)return l(p);ot.mkdir(t,r,Of(t,e,r,i,o,c,l))});else{if(x.isSymbolicLink())return l(new co(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,Pc(t,e,r,i,o,c,l))},T_=t=>{let e=!1,r;try{e=ot.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Df(t,r??"ENOTDIR")}},k_=(t,e)=>{t=Q(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,l=e.gid,u=typeof c=="number"&&typeof l=="number"&&(c!==e.processUid||l!==e.processGid),f=e.preserve,x=e.unlink,p=Q(e.cwd),m=b=>{b&&u&&Pf(b,c,l),o&&ot.chmodSync(t,i)};if(t===p)return T_(p),m();if(f)return m(ot.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=Q(to.relative(p,t)).split("/"),_;for(let b=v.shift(),I=p;b&&(I+="/"+b);b=v.shift()){I=Q(to.resolve(I));try{ot.mkdirSync(I,i),_=_||I}catch{let A=ot.lstatSync(I);if(A.isDirectory())continue;if(x){ot.unlinkSync(I),ot.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new co(I,I+"/"+v.join("/"))}}return m(_)},fc=Object.create(null),$u=1e4,mr=new Set,C_=t=>{mr.has(t)?mr.delete(t):fc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),mr.add(t);let e=fc[t],r=mr.size-$u;if(r>$u/10){for(let i of mr)if(mr.delete(i),delete fc[i],--r<=0)break}return e},R_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,P_=R_==="win32",D_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Lf(i,r)),e.push(r||"/"),e},[]),O_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=P_?["win32 parallelization disabled"]:t.map(i=>Si(Lf(C_(i))));let r=new Set(t.map(i=>D_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let l=this.#e.get(c);if(!l||l?.[0]!==t)continue;let u=l[1];if(!u){this.#e.delete(c);continue}if(l.shift(),typeof u=="function")o.add(u);else for(let f of u)o.add(f)}for(let c of i){let l=this.#e.get(c),u=l?.[0];if(!(!l||!(u instanceof Set)))if(u.size===1&&l.length===1){this.#e.delete(c);continue}else if(u.size===1){l.shift();let f=l[0];typeof f=="function"&&o.add(f)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},L_=()=>process.umask(),Vu=Symbol("onEntry"),Dc=Symbol("checkFs"),Ju=Symbol("checkFs2"),Oc=Symbol("isReusable"),ut=Symbol("makeFs"),Lc=Symbol("file"),Nc=Symbol("directory"),Zs=Symbol("link"),Zu=Symbol("symlink"),Yu=Symbol("hardlink"),Ei=Symbol("ensureNoSymlink"),Xu=Symbol("unsupported"),Qu=Symbol("checkPath"),hc=Symbol("stripAbsolutePath"),wn=Symbol("mkdir"),Ge=Symbol("onError"),zs=Symbol("pending"),ef=Symbol("pend"),wr=Symbol("unpend"),xc=Symbol("ended"),pc=Symbol("maybeClose"),Mc=Symbol("skip"),Ai=Symbol("doChown"),Ti=Symbol("uid"),ki=Symbol("gid"),Ci=Symbol("checkedCwd"),N_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ri=N_==="win32",M_=1024,B_=(t,e)=>{if(!Ri)return ie.unlink(t,e);let r=t+".DELETE."+Ef(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},F_=t=>{if(!Ri)return ie.unlinkSync(t);let e=t+".DELETE."+Ef(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},tf=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Kc=class extends Pi{[xc]=!1;[Ci]=!1;[zs]=0;reservations=new O_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[xc]=!0,this[pc]()},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:M_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ri,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Ne.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:L_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Vu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[pc](){this[xc]&&this[zs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[hc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Gc(r),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Ri&&/^[a-z]:\.\.$/i.test(l[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Ne.posix.dirname(t.path),f=Ne.posix.normalize(Ne.posix.join(u,l.join("/")));if(f.startsWith("../")||f==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[Qu](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[hc](t,"path")||!this[hc](t,"linkpath"))return!1;if(t.absolute=Ne.isAbsolute(t.path)?Q(Ne.resolve(t.path)):Q(Ne.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Q(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Ne.win32.parse(String(t.absolute));t.absolute=i+Nu(String(t.absolute).slice(i.length));let{root:o}=Ne.win32.parse(t.path);t.path=o+Nu(t.path.slice(o.length))}return!0}[Vu](t){if(!this[Qu](t))return t.resume();switch(m_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Dc](t);default:return this[Xu](t)}}[Ge](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[wr](),e.resume())}[wn](t,e,r){A_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Ai](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ti](t){return tf(this.uid,t.uid,this.processUid)}[ki](t){return tf(this.gid,t.gid,this.processGid)}[Lc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new no(String(t.absolute),{flags:Cf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[Ge](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[Ge](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,f=>{f?this[Ge](f,t):this[wr](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,p=t.mtime;ie.futimes(f,x,p,m=>m?ie.utimes(u,x,p,v=>c(v&&m)):c())}if(typeof f=="number"&&this[Ai](t)){o++;let x=this[Ti](t),p=this[ki](t);typeof x=="number"&&typeof p=="number"&&ie.fchown(f,x,p,m=>m?ie.chown(u,x,p,v=>c(v&&m)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[Ge](u,t),e()}),t.pipe(l)),l.pipe(i)}[Nc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[wn](String(t.absolute),r,i=>{if(i){this[Ge](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[wr](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ai](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ti](t)),Number(this[ki](t)),c)),c()})}[Xu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Zu](t,e){let r=Q(Ne.relative(this.cwd,Ne.resolve(Ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ei](t,this.cwd,r,()=>this[Zs](t,String(t.linkpath),"symlink",e),i=>{this[Ge](i,t),e()})}[Yu](t,e){let r=Q(Ne.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Ei](t,this.cwd,i,()=>this[Zs](t,r,"link",e),o=>{this[Ge](o,t),e()})}[Ei](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let l=Ne.resolve(e,c);ie.lstat(l,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new co(l,Ne.resolve(l,r.join("/"))));this[Ei](t,l,r,i,o)})}[ef](){this[zs]++}[wr](){this[zs]--,this[pc]()}[Mc](t){this[wr](),t.resume()}[Oc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ri}[Dc](t){this[ef]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Ju](t,r))}[Ju](t,e){let r=l=>{e(l)},i=()=>{this[wn](this.cwd,this.dmode,l=>{if(l){this[Ge](l,t),r();return}this[Ci]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let l=Q(Ne.dirname(String(t.absolute)));if(l!==this.cwd)return this[wn](l,this.dmode,u=>{if(u){this[Ge](u,t),r();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Mc](t),r();return}if(l||this[Oc](t,u))return this[ut](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=p=>this[ut](p??null,t,r);return f?ie.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),f=>this[ut](f??null,t,r))}if(t.absolute===this.cwd)return this[ut](null,t,r);B_(String(t.absolute),f=>this[ut](f??null,t,r))})};this[Ci]?o():i()}[ut](t,e,r){if(t){this[Ge](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Lc](e,r);case"Link":return this[Yu](e,r);case"SymbolicLink":return this[Zu](e,r);case"Directory":case"GNUDumpDir":return this[Nc](e,r)}}[Zs](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[Ge](o,t):(this[wr](),t.resume()),i()})}},yi=t=>{try{return[null,t()]}catch(e){return[e,null]}},Nf=class extends Kc{sync=!0;[ut](t,e){return super[ut](t,e,()=>{})}[Dc](t){if(!this[Ci]){let o=this[wn](this.cwd,this.dmode);if(o)return this[Ge](o,t);this[Ci]=!0}if(t.absolute!==this.cwd){let o=Q(Ne.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[wn](o,this.dmode);if(c)return this[Ge](c,t)}}let[e,r]=yi(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Mc](t);if(e||this[Oc](t,r))return this[ut](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[l]=c?yi(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ut](l,t)}let[o]=yi(()=>ie.rmdirSync(String(t.absolute)));this[ut](o,t)}let[i]=t.absolute===this.cwd?[]:yi(()=>F_(String(t.absolute)));this[ut](i,t)}[Lc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{ie.closeSync(o)}catch(f){u=f}(l||u)&&this[Ge](l||u,t),e()},o;try{o=ie.openSync(String(t.absolute),Cf(t.size),r)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[Ge](l,t)),t.pipe(c)),c.on("data",l=>{try{ie.writeSync(o,l,0,l.length)}catch(u){i(u)}}),c.on("end",()=>{let l=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{ie.futimesSync(o,u,f)}catch(x){try{ie.utimesSync(String(t.absolute),u,f)}catch{l=x}}}if(this[Ai](t)){let u=this[Ti](t),f=this[ki](t);try{ie.fchownSync(o,Number(u),Number(f))}catch(x){try{ie.chownSync(String(t.absolute),Number(u),Number(f))}catch{l=l||x}}}i(l)})}[Nc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[wn](String(t.absolute),r);if(i){this[Ge](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ai](t))try{ie.chownSync(String(t.absolute),Number(this[Ti](t)),Number(this[ki](t)))}catch{}e(),t.resume()}[wn](t,e){try{return k_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[Ei](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let l of r){c=Ne.resolve(c,l);let[u,f]=yi(()=>ie.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new co(c,Ne.resolve(e,r.join("/"))))}i()}[Zs](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[Ge](c,t)}}},z_=t=>{let e=new Nf(t),r=t.file,i=bf.statSync(r),o=t.maxReadSize||16*1024*1024;new iw(r,{readSize:o,size:i.size}).pipe(e)},U_=(t,e)=>{let r=new Kc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("close",c),bf.stat(o,(u,f)=>{if(u)l(u);else{let x=new Fc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Mf=Di(z_,U_,t=>new Nf(t),t=>new Kc(t),(t,e)=>{e?.length&&xf(t,e)}),H_=(t,e)=>{let r=new Wc(t),i=!0,o,c;try{try{o=st.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=st.openSync(t.file,"w+");else throw f}let l=st.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<l.size;c+=512){for(let p=0,m=0;p<512;p+=m){if(m=st.readSync(o,u,p,u.length-p,c+p),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!m)break e}let f=new qn(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(c+x+512>l.size)break;c+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,G_(t,r,c,o,e)}finally{if(i)try{st.closeSync(o)}catch{}}},G_=(t,e,r,i,o)=>{let c=new sf(t.file,{fd:i,start:r});e.pipe(c),j_(e,o)},q_=(t,e)=>{e=Array.from(e);let r=new oo(t),i=(o,c,l)=>{let u=(v,_)=>{v?st.close(o,b=>l(v)):l(null,_)},f=0;if(c===0)return u(null,0);let x=0,p=Buffer.alloc(512),m=(v,_)=>{if(v||_===void 0)return u(v);if(x+=_,x<512&&_)return st.read(o,p,x,p.length-x,f+x,m);if(f===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let b=new qn(p);if(!b.cksumValid)return u(null,f);let I=512*Math.ceil((b.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&b.mtime&&t.mtimeCache.set(String(b.path),b.mtime),x=0,st.read(o,p,0,512,f,m)};st.read(o,p,0,512,f,m)};return new Promise((o,c)=>{r.on("error",c);let l="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&l==="r+")return l="w+",st.open(t.file,l,u);if(f||!x)return c(f);st.fstat(x,(p,m)=>{if(p)return st.close(x,()=>c(p));i(x,m.size,(v,_)=>{if(v)return c(v);let b=new no(t.file,{fd:x,start:_});r.pipe(b),b.on("error",c),b.on("close",o),W_(r,e)})})};st.open(t.file,l,u)})},j_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Ar({file:Bf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},W_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Ar({file:Bf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},bi=Di(H_,q_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!fw(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")}),oA=Di(bi.syncFile,bi.asyncFile,bi.syncNoFile,bi.asyncNoFile,(t,e=[])=>{bi.validate?.(t,e),K_(t)}),K_=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,i)=>e(r,i)&&!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0)):(r,i)=>!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0))};Ht();var ft={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function lo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Ff(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function uo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function zf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Uf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Wn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Vt();We();te();Ce();We();function Tr(t,e){if(lo(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Oi(t){return t.startsWith("http://")||t.startsWith("https://")}function kr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as YA}from"node:fs";import{dirname as QA,join as eT}from"node:path";import{fileURLToPath as nT}from"node:url";var Ot="0.2.3-alpha.1";import{mkdir as ay,rm as r0}from"node:fs/promises";import{join as zi}from"node:path";Ut();import{readFileSync as ey}from"node:fs";var ty=384;async function $c(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await lr(t.agentEnvFile,r,{mode:ty})}function Li(t){try{let e=JSON.parse(ey(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function jf(t,e,r={},i=o=>o){return{...i({...t,...Li(e)}),...r}}Ut();function Ni(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(ny(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
99
92
  `)}
100
- `}function vE(t){if(t.includes(`
101
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var SE={path:"",version:"cloud-deployed"},H0="openclaw_gateway_unavailable",IE="openclaw_default_agent_missing";function j0(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}}},kE=6e4,bo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??EE,this.createTimeoutMs=e.createTimeoutMs??kE,this.detectorFactory=e.detectorFactory??(()=>new Vn),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Eo({command:n})),this.openclawConfigDir=e.openclawConfigDir??q0(_E(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{le.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=q0(e,".env");if(await wE(n).then(c=>c.isFile()).catch(()=>!1)){le.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let s=bE({...process.env,...rd(this.paths.agentEnvFile)});await an(n,s,{mode:384}),le.info("openclaw .env bootstrapped",{envFile:n,bytes:s.length}),await this.getOpenclawConfig().restartGateway(),le.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 Te(e.agentId,this.paths).catch(()=>null),s=oo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")le.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(R=>le.warn("dispose stale agent failed (ignored)",{err:String(R)})),this.registry.unregister(e.agentId);else if(s&&c.deployType!=="cloud")le.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(R=>le.warn("dispose drifted agent failed (ignored)",{err:String(R)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){le.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let R=await Te(e.agentId,this.paths).catch(()=>null);R&&(R.patToken=e.patToken,await Be(R,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){le.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let R=await Te(e.agentId,this.paths).catch(()=>null);R&&(R.modelInfo=e.modelInfo,await Be(R,this.paths))}return le.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!s&&!this.config.frameworksCache?.[e.framework])throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=$e(e.agentId,this.paths),h=s?"cloud":"local",x=e.framework==="openclaw"&&h==="local",g;x&&!n?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??w??u.workspace,y=new AbortController,v=setTimeout(()=>y.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{s&&cd(e.framework)&&await cr(e.framework,y.signal);let R=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await ad(u.root,{recursive:!0}),await ad(S,{recursive:!0}),await ad(u.logs,{recursive:!0}),R(),x||await ur(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await Pa(S,"cloud"):await Pa(S,"local",dd)),R();let D=i,E=Wf({model:e.model??D?.model}),C=Of(e._meta)??D?.accountId,O=e.patToken??D?.patToken,F=h==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new _o({agentId:e.agentId,framework:e.framework,workspace:S,model:E.model??Ot,deployType:h,...C?{accountId:C}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",D?.sessions){let V=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,se]of Object.entries(D.sessions)){let oe={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?se.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",le.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:oe.permissionMode})):An(e.framework,se.permissionMode)?oe.permissionMode=se.permissionMode:le.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&le.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:h}),se.cozeGroupId&&(oe.cozeGroupId=se.cozeGroupId),I.sessions.set(X,oe)}let re=Object.keys(D.sessions).length;re>0&&le.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(I),A=!0;let B={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:E.model};h==="cloud"&&(B.deployType="cloud"),C&&(B.accountId=C),O&&(B.patToken=O),F&&(B.modelInfo=F),D?.skills&&(B.skills=D.skills),D?.agentName&&(B.agentName=D.agentName),D?.description&&(B.description=D.description),B.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Dt,e.framework==="openclaw"&&h==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):le.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let Y=e.initialSkills??[];if(Y.length>0){let V=[...B.skills??[]],re=new Map(V.map((oe,P)=>[oe.skillId,P])),X=await Promise.allSettled(Y.map(oe=>fo({agentId:e.agentId,workspace:S,framework:e.framework,skill:oe}))),se=0;for(let[oe,P]of X.entries()){let U=Y[oe];U&&(P.status==="fulfilled"?(ho(V,re,P.value),se++):le.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(P.reason)}))}se>0&&(B.skills=V,le.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:Y.length}))}return await Be(B,this.paths),le.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(R){throw le.error("agent create failed, rolling back",{agentId:e.agentId,err:String(R)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await mE(u.root,{recursive:!0,force:!0}).catch(D=>le.warn("rm agent dir failed (ignored)",{err:String(D)})),R instanceof k?R:new k("AGENT_SPAWN_FAILED",String(R),{cause:R})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,n,i,s,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&cd(e.framework))u=SE;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);cd(e.framework)&&!hs(e.framework)&&(le.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await cr(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:i,cozeEnv:s,mockScenario:c,command:u.path});else{let g=e.sessions.get(i),w=Yt(e)?g?.permissionMode??W0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,s,c,this.buildBinShimPathEnv(),w)}try{return await x.start(),await x.initialize(AE),x}catch(g){let w=x instanceof Lt?x.getStderrTail():[];throw w.length>0&&le.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof k?g.code:"unknown",recentStderr:w}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,g)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let s=await this.detectorFactory().probeOpenclawGateway(n);if(!s.reachable)return new k("AGENT_ENV_NOT_READY",j0(s),{cause:{reason:H0}})}catch(s){le.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(s)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};le.warn("openclaw default agent stale or missing, attempting lazy re-detect");let n=await this.detectorFactory().detect("openclaw");if(n?.defaultAgent?.id&&n.defaultAgent.workspace)return le.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:IE}})}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",j0(n),{cause:{reason:H0}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:s,cozeEnv:c,mockScenario:d,command:u}=e,h=od(s);if(n.deployType==="local"){let w=await this.ensureOpenclawDefaultAgent();return new Br({command:u,cwd:w.workspace,agentId:w.id,sessionName:h})}let x=await G0(),g;if(i?.modelToken){let w=Wc(s),S=Kc(i),y=`${w}/${S}`;if(!this.ensuredProviders.has(y)){let v=this.getOpenclawConfig(),I=await v.getAllowlistModelsForProvider(w),A=Zf(i,c,d,I);A&&(await v.ensureProvider(w,A),await v.addModelToAllowlist(y),this.ensuredProviders.add(y))}g=y}return new Br({command:u,cwd:n.workspace,agentId:n.agentId,sessionName:h,...x?{gatewayToken:x}:{},...g?{slashModelOnStart:g}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,s=n??e.model;for(let c of e.sessions.keys()){let d=Wc(c),u=`${d}/${s}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,le.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,le.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as Z0}from"node:crypto";import{promises as LE}from"node:fs";import{basename as X0}from"node:path";je();ne();import{promises as TE}from"node:fs";import{basename as RE}from"node:path";var $0=H("file-upload"),CE="/api/coze_claw/file/agent_upload",PE=6e4;async function V0(t,e={}){let i=`${Rr(Cr(e.handshakeBase))}${CE}`,s=e.timeoutMs??PE,c=await TE.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",...vn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),s);$0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let g=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),w=g.headers.get("x-tt-logid")??"";if(!g.ok){let v=await g.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${w}: ${v.slice(0,200)}`)}let S=await g.json();if(S.code!==void 0&&S.code!==0)throw new k("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${w}`);let y=S.data?.file?.file_url;if(!y)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(S).slice(0,200)}`);return $0.info("file upload ok",{uri:y,logid:w}),{uri:y}}catch(g){throw g instanceof k?g:g.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${s}ms) for ${RE(t.path)}`):new k("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}je();ne();import{extname as DE}from"node:path";var OE={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function Y0(t){let e=DE(t).toLowerCase();return OE[e]??"application/octet-stream"}Le();var vo=H("agent-send"),J0=50*1024*1024;function Q0(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 s=i.sessions.get(n);if(!s)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:s}}async function eh(t,e,n,i,s,c){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,n,i,s);return}catch(x){u=x,h<2&&(vo.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(g=>setTimeout(g,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function th(t,e){let{session:n,runtime:i}=Q0(e.core,t.agentId,t.sessionId);if(!await ri(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let s=await LE.stat(t.path).catch(()=>null);if(!s||!s.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(s.size>J0)throw new k("FILE_TOO_LARGE",`${s.size} bytes > limit ${J0}`);let c=await Y0(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??X0(t.path),u;try{u=await V0({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:s.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw vo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:s.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:Z0(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:d,sizeBytes:s.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await eh(e,n,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),vo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:s.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:s.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function nh(t,e){let{session:n,runtime:i}=Q0(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 s=t.name??X0(t.path),c={sessionUpdate:"group_file",messageId:Z0(),content:{uri:t.path,name:s,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await eh(e,n,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),vo.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:s,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function rh(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),s=Math.max(n.length,i.length);for(let c=0;c<s;c++){let d=n[c]??0,u=i[c]??0;if(d<u)return!0;if(d>u)return!1}return!1}on();Vt();ne();var Nt=H("coze-cli-installer"),ih="@coze/cli@latest",NE="coze",sh="0.1.8",ME=5e3,BE=5e3,FE=9e4,oh=1e4,Hi=null,So=!1;async function ud(t,e={}){if(So)return;if(Hi)return Hi;let n=e.exec??Ff;return Hi=(async()=>{try{let i=await zE(NE,n),s=!1;if(i){let d=await UE(n);if(d===void 0)Nt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(rh(d,sh))Nt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:sh}),s=!0;else{Nt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),So=!0;return}}let c=s?"upgrade-only":"full";Nt.info("coze-cli install start",{package:ih,mode:c});try{await n("npm",["i","-g","--prefer-online",ih],{timeout:FE,maxBuffer:10*1024*1024}),Nt.info("coze-cli install ok")}catch(d){Nt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(s){So=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:oh}),Nt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Nt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:oh}),Nt.info("coze auth login ok")}catch(d){Nt.warn("coze auth login failed",{err:String(d)});return}So=!0}finally{Hi=null}})(),Hi}async function zE(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:ME});return Ra(i)}catch{return}}async function UE(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:BE});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}cn();Le();var GE=10*6e4;function ah(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?GE:e}function Io(t){return dr(t??ee().configFile)}function ji(t,e){return lr(e??ee().configFile,t)}import{randomBytes as ab}from"node:crypto";sr();je();ne();import{createReadStream as qE}from"node:fs";import{mkdir as HE,readFile as jE,realpath as WE,stat as KE,writeFile as $E}from"node:fs/promises";import{basename as VE,dirname as fd,isAbsolute as YE,join as JE,relative as ZE,resolve as ch,sep as XE}from"node:path";import{createInterface as QE}from"node:readline";var lh=H("fs-rpc"),Wi=Ke("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function uh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>Wi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${Wi} bytes`);let i=await hh(t.path,e);return await HE(fd(i),{recursive:!0}),await $E(i,t.content,"utf8"),lh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function fh(t,e){let n=await hh(t.path,e),i=await KE(n),s=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Wi&&!s)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Wi} bytes`);let c;if(s&&i.size>Wi)c=await eb(n,t.line??1,t.limit);else{let d=await jE(n,"utf8");if(s){let u=d.split(`
102
- `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;c=u.slice(h,x).join(`
103
- `)}else c=d}return lh.info("fs/read_text_file ok",{path:n,size:c.length}),{content:c}}async function eb(t,e,n){let i=QE({input:qE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),s=Math.max(0,e-1),c=typeof n=="number"?s+n:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let h of i)if(u>=s&&u<c&&d.push(h),u++,u>=c)break}finally{i.close()}return d.join(`
104
- `)}async function hh(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([dh(ch(e)),dh(ch(t))]),s=ZE(n,i);if(tb(s,XE,YE(s)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function tb(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function dh(t){let e=[],n=t;for(;n!==fd(n);)try{let i=await WE(n);return e.length?JE(i,...e.reverse()):i}catch{e.push(VE(n)),n=fd(n)}return t}ne();var xh=H("prompt-multimodal"),ph=10*1024*1024,nb=15e3,rb=6;async function gh(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let c=n++,d=t[c];d!==void 0&&(e[c]=await ib(d))}}let s=Array.from({length:Math.min(rb,t.length)},()=>i());return await Promise.all(s),e}function mh(t){return t.some(e=>e.type==="image")}async function ib(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Di(e.uri))return t;try{let{buf:n,contentType:i}=await ob(e.uri),s=e.mimeType||sb(i)||"application/octet-stream";return xh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:s}),{type:"image",data:n.toString("base64"),mimeType:s}}catch(n){return xh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function sb(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function ob(t){let e=new AbortController,n=setTimeout(()=>e.abort(),nb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let s=await i.arrayBuffer();if(s.byteLength>ph)throw new Error(`image too large: ${s.byteLength} bytes (max ${ph})`);return{buf:Buffer.from(s),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}dn();je();ne();var $=H("core"),cb=3e4,db=/^(boe|ppe)_[A-Za-z0-9_-]+$/,lb="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",ub="\u5BA1\u6279\u5DF2\u8D85\u65F6",fb=3e4,Ao=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Lr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=ah(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(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.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),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(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,n,i){let s=i.downstream;s&&(s.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),s.onAgentRequest(c=>{this.handleAgentRequest(e,s,c)}),s.onExit((c,d)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:c,signal:d}),qi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(s,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[s,c]of this.pendingUpstream)c.downstream===e&&i.push(s);if(i.length!==0){$.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let s of i){let c=this.pendingUpstream.get(s);if(c){this.pendingUpstream.delete(s),this.upstream.send(In(s,{code:Z.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>$.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:Z.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){$.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Z.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(po(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&db.test(i)?this.currentCozeEnv=i:i&&$.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let s=this.extensions[e.method];if(!s){n!==null?await this.sendError(n,Z.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let c=await s(e,this);n!==null&&await this.upstream.send(Or(n,c));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Or(n,s));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Or(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,Z.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(s){$.error("handleFrame failed",{method:e.method,err:String(s)}),n!==null&&await this.upstream.send(In(n,zi(s)))}}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 s=this.agents.get(i);if(!s)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(s,e.method,n);if(e.method==="session/prompt"){let h=s.sessions.get(c);if(h?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,g=ao(n._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:s.agentId,cloudSessionId:c}),this.synthesizePromptReply(s,h,c,lb,x,g)}}let d=Date.now(),u=!1;try{let h=await s.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(s,e.method,n));return u=!0,h}finally{$.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:s}=Nf(i);switch(n){case"session/new":{let c=hb();return $.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=s;return $.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=s,d=c.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Yt(e)?Lf(i._meta):void 0;if(u!==void 0&&!An(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${sd(e.framework)}`);let h=await this.ensureRuntime(e,d);if(u!==void 0&&h.permissionMode===void 0&&(h.permissionMode=u,await this.persistSessionMapping(e)),h.replySeq=0,await this.ensureDownstream(e,d,h),!h.downstream||!h.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&h.permissionMode!==void 0&&h.permissionMode!==u){let S=h.permissionMode;h.permissionMode=u,await this.persistSessionMapping(e);try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(y){throw h.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),y}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(h.acpSessionId,x):e.activeTriggers.delete(h.acpSessionId);let g=ao(i._meta);if(g?e.activeGroupIds.set(h.acpSessionId,g):e.activeGroupIds.delete(h.acpSessionId),g&&h.cozeGroupId!==g&&(h.cozeGroupId=g,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&mh(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let w=await gh(c.prompt);try{let S=await h.downstream.sessionPrompt({...c,sessionId:h.acpSessionId,prompt:w});return h.lastActiveAt=Date.now(),S}catch(S){if(S instanceof k&&S.code==="AGENT_APPROVAL_TIMEOUT"){let y=h.pendingPermission;y&&(y.downstream.respondAgentRequest(y.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(y.upstreamId),h.pendingPermission=void 0);let v=h.acpSessionId,I=v?e.activeTriggers.get(v):void 0,A=v?e.activeGroupIds.get(v):void 0;return $.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,h,d,ub,I,A)}throw S}finally{if(e.activeTriggers.delete(h.acpSessionId),e.activeGroupIds.delete(h.acpSessionId),h.pendingPermission=void 0,h.reloadAfterTurn){h.reloadAfterTurn=!1;let S=h.downstream;S&&(h.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:h.acpSessionId}),S.stop("reload-after-turn").catch(y=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(y)})))}else h.downstream?.isAlive()&&this.armIdleTimer(e,d,h)}}case"session/cancel":{let d=s.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=s,d=c.sessionId,u=c.modeId,h=ao(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Yt(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(!An(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${sd(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let g=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(w){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),w}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let s=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&s.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(s.length===0)return $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};$.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:s.length});for(let d of s)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of s){let u=d.runtime.downstream,h=d.runtime.acpSessionId;u?.isAlive()&&h&&c.push({downstream:u,acpSessionId:h,oldMode:d.oldMode,runtime:d.runtime})}for(let d of c)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let h of s)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n){let i=e.sessions.get(n);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Yt(e)&&(c.permissionMode=e.framework==="claude-code"?dd:K0),e.sessions.set(n,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,n){let i={sessionId:n,_meta:{cozeAgentId:e}};try{let s=await this.sendRequest(ft.GEN_MODEL_TOKEN,i,fb);if(!s?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return s.modelToken}catch(s){throw s instanceof k&&s.code==="MODEL_TOKEN_GEN_FAILED"?s:new k("MODEL_TOKEN_GEN_FAILED",s instanceof Error?s.message:String(s),{cause:s})}}async ensureDownstream(e,n,i){if(qi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=3,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=s&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let h;try{h=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=s&&i.acpSessionId&&($.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}),$.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let g=await h.sessionNew({cwd:e.workspace});i.acpSessionId=g.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),Yt(e)&&i.acpSessionId&&i.permissionMode)try{await h.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){$.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(qi(i),this.isRuntimeBusy(e,i)){$.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)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}$.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let s=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),s&&s.stop("idle timeout").catch(c=>$.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let s of this.pendingUpstream.values())if(s.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,s){let c={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Dr("session/update",{sessionId:i,update:s,_meta:c}))}async synthesizePromptReply(e,n,i,s,c,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return c&&(u.cozeTriggerMsgId=c),d&&(u.cozeGroupId=d),await this.upstream.send(Dr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}},_meta:u})).catch(h=>$.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,s=this.reverseSessionId(e,i);if(!s){$.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(s);if(!c){$.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(gb(n)){$.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Yt(e)){let g=d.currentModeId;An(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(w=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof g=="string"&&!An(e.framework,g)&&$.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:g})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Dr("session/update",{...n,sessionId:s,_meta:u})).catch(g=>$.warn("forward update failed",{agentId:e.agentId,err:String(g)}))}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}$.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:Z.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let s=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await uh(c,s);n.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await fh(c,s);n.respondAgentRequest(i.id,d)}}catch(s){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(s)}),n.respondAgentRequestError(i.id,zi(s))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let s=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let g=u?e.activeGroupIds.get(u):void 0;g&&(x.cozeGroupId=g);let w=u?this.reverseSessionId(e,u):void 0,S=w?e.sessions.get(w):void 0;S&&(S.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:s});let y={...c,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(s,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:w}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:s,acpSessionId:u,cloudSessionId:w,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(Bi(s,"session/request_permission",y)).catch(v=>{this.pendingUpstream.delete(s),$.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),n.respondAgentRequestError(i.id,{code:Z.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let s=n.value;this.clearPendingPermissionFor(s),e.error?($.info("upstream \u2192 permission response (error)",{agentId:s.agentId,upstreamId:e.id,method:s.method,error:e.error}),s.downstream.respondAgentRequestError(s.agentRequestId,e.error)):(s.method==="session/request_permission"&&xb(e.result,s),$.info("upstream \u2192 permission response (result)",{agentId:s.agentId,upstreamId:e.id,method:s.method,result:e.result}),s.downstream.respondAgentRequest(s.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new xo(e.error)):i.value.resolve(e.result);return}$.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let s=e.get(n);if(s)return{value:s,key:n};if(typeof n=="number"){let c=String(n),d=e.get(c);if(d)return $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:c}),{value:d,key:c}}}sendRequest(e,n,i=cb){let s=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(s),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(s,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(Bi(s,e,n)).catch(h=>{let x=this.pendingBridge.get(s);x&&(clearTimeout(x.timer),this.pendingBridge.delete(s)),d(h)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,s]of e.sessions){let c={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(c.acpSessionId=s.acpSessionId),s.permissionMode&&Yt(e)&&(c.permissionMode=s.permissionMode),s.cozeGroupId&&(c.cozeGroupId=s.cozeGroupId),n.set(i,c)}await ii(e.agentId,n,this.paths)}catch(n){$.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,s]of e.sessions.entries())if(s.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(In(e,{code:n,message:i,data:{bridgeVersion:Dt}}))}};function hb(){return ab(16).toString("hex")}function xb(t,e){if(!t||typeof t!="object"){$.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){$.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"){$.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 pb=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function gb(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let{text:s}=i;return pb.some(c=>s.startsWith(c))}cn();ne();Le();import{randomBytes as mb}from"node:crypto";import{createServer as wb}from"node:http";var _b=1e6,wh=H("ipc"),ko=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??ee()}async start(){this.token=mb(32).toString("hex");let e=wb((i,s)=>{this.dispatch(i,s)});this.server=e,await new Promise((i,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),wh.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(s=>s?i(s):n())}),this.server=null)}async persistAuthFiles(){await an(this.paths.portFile,String(this.port)),await an(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){Ki(n,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(s);if(!c){Ki(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await yb(e)}catch(u){Ki(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Ki(n,200,u??{ok:!0})}catch(u){wh.error("IPC handler failed",{key:s,err:String(u)}),Ki(n,500,{error:u instanceof Error?u.message:String(u)})}}};function Ki(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function yb(t){let e=[],n=0;for await(let s of t){let c=s;if(n+=c.length,n>_b)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 G1=Gt(hx(),1),q1=Gt(Mo(),1),H1=Gt(Ur(),1),j1=Gt(vd(),1),W1=Gt(Ad(),1),K1=Gt(Dd(),1),vx=Gt(Uo(),1),$1=Gt(bx(),1);var Sx=vx.default;je();ne();var{FWS:dv}=Nx(),De=H("upstream.frontier"),Bx="application/json",Fx="none",lv=15e3;function uv(t){class e extends Sx{constructor(i){super(i,Uf,{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,s){this.guardTeardown(),super.close(i,s)}terminate(){this.guardTeardown(),super.terminate()}send(i,...s){if(Sl("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,...s)}}return e}var ts=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){De.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Gf,...vn(this.opts.ppeOverride)},n=uv(e),i=Hf(this.opts.urlOverride),s={url:i,ws:n,fpID:zf,aID:co,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Bx,force:!0},payloadEncoding:{encoding:Fx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new dv(s),d=!1,u=null,h,x,g=new Promise((y,v)=>{h=y,x=v}),w=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?x(y):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;De.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&w();for(let v of this.connectHandlers)Promise.resolve(v({initial:y})).catch(I=>De.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,De.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{De.warn("frontier error",{code:y.code,msg:y.message}),w(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},c.onmessage=y=>this.handleMessage(y),this.fws=c;let S=this.opts.openTimeoutMs??lv;u=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await g}catch(y){try{c.close(1e3,"open failed")}catch(v){De.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){De.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw De.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?(De.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 s=JSON.stringify(e),c=e;zx(c)||De.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:s.length});try{await n.send(s,{service:33555712,method:1,payloadType:Bx,payloadEncoding:Fx})}catch(u){throw De.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 s=n(i.cozeAgentId);s&&(i.cozePatToken=s)}handleMessage(e){let n=e.message?.service;if(n!==33555712){De.debug("drop non-adapter frontier frame",{service:n});return}let i=xv(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 s;try{s=JSON.parse(i)}catch(d){De.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=s;zx(c)||De.info("frontier frame in",{logid:hv(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:fv(i)}),Promise.resolve(this.handler(s)).catch(d=>De.warn("frontier frame handler threw",{err:String(d)}))}};function zx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Ux=2e3;function fv(t){return t.length<=Ux?t:`${t.slice(0,Ux)}...<truncated, total ${t.length} chars>`}function hv(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function xv(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}}je();ne();var Md=H("skill-publish"),pv="/api/marketplace/product/skill/publish_with_assets",gv=15e4;async function Gx(t,e={}){let i=`${Rr(Cr(e.handshakeBase))}${pv}`,s=e.timeoutMs??gv,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",...vn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),s);Md.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let y=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${y.slice(0,200)}`)}let w=await x.json();if(Md.info("skill publish response",{logid:g,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${g}`);let S={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(S.skillId=String(w.data.skill_id)),w.data?.version&&(S.version=w.data.version),Md.info("skill publish ok",{logid:g,skillId:S.skillId??"",version:S.version??""}),S}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${s}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}ne();var Bd=H("upstream.switchable"),Yo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;Bd.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let s of this.connectHandlers)e.onConnect(s);try{await e.start()}catch(s){throw Bd.error("swap target start failed, reverting",{err:String(s)}),this.inner=i,s}await i.stop(n??"swapped").catch(s=>Bd.warn("previous upstream stop threw (ignored)",{err:String(s)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var Fd=H("upstream"),Kr=class{handler=null;async start(){Fd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Fd.info("NoopUpstream stopped",{reason:e})}async send(e){Fd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};je();ne();cn();ne();Le();import{promises as mv}from"node:fs";var qx=H("pat-token-store");async function Jo(t=ee()){try{let n=(await mv.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(qx.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"&&qx.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ns(t,e=ee()){if(!t)throw new Error("writePatToken: empty patToken");await an(e.patTokenFile,t,{mode:384})}Le();Le();import{promises as Zo}from"node:fs";import{join as wv}from"node:path";function _v(t,e){return`#!/bin/sh
93
+ `}function ny(t){if(t.includes(`
94
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}te();Ce();We();te();var fo="1008033",Wf="1289";var Kf="pbbp2",$f="https://www.coze.cn",Vf="/api/coze_claw/resource/get_frontier_key",ry="https://www.coze.cn",iy="wss://frontier.coze.cn";function Cr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??ry}function Jf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??iy}function bn(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Bi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Mi=H("handshake");async function Vc(t){let e=Cr(t.endpoint),r=t.timeoutMs??1e4,i=`${kr(e)}${Vf}?aid=${encodeURIComponent(fo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...bn(t.ppeOverride)},c=new AbortController,l=setTimeout(()=>c.abort(),r);Mi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),f=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let b=await u.text().catch(()=>"");throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${b.slice(0,200)}`)}let p=await u.json();if(p.code!==void 0&&p.code!==0)throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${p.code} msg=${p.msg??"-"} logid=${f}`);let m=p.data??{},v=typeof m.access_key=="string"&&m.access_key||typeof m.accessKey=="string"&&m.accessKey||void 0,_=typeof m.device_id=="string"&&m.device_id||typeof m.deviceId=="string"&&m.deviceId||void 0;if(!v||!_){let b=JSON.stringify(p).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${b}`)}return Mi.info("handshake ok",{remoteDeviceId:_,logid:f,traceId:x}),{accessKey:v,deviceId:_}}catch(u){if(u instanceof T)throw Mi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Mi.warn("handshake timeout",{base:e,timeoutMs:r}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let f=u.cause;throw Mi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}var ho=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",vt="auto",Jc=15e4;function Zf(t){return{model:Zc(t.model)??vt,...t.modelToken?{modelToken:t.modelToken}:{}}}function sy(t){return!t||t===vt}var oy=new Set(["auto","\u81EA\u52A8"]);function Zc(t){let e=t?.trim();if(e)return oy.has(e.toLowerCase())?vt:e}function Yf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=ho,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||vt;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else sy(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Xf(t,e,r){return t.modelToken?{baseUrl:`${ho}/v1`,providerName:"coze",headers:{Authorization:`Bearer ${t.modelToken}`,...xo(e,r)}}:null}function Qf(t){if(!t.modelToken)return{};let e={model:t.model||vt,model_context_window:t.modelInfo?.contextWindow??Jc};return{CODEX_CONFIG:JSON.stringify(e)}}function xo(t,e){let{ttEnv:r,usePpe:i}=Bi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function e0(t,e,r){if(!t.modelToken)return{};let i=xo(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,l])=>`${c}:${l}`).join(`
95
+ `)}}function Yc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function t0(t,e,r){if(!t.modelToken)return null;let i=t.model||vt,o=xo(e,r),c=["text"];t.modelInfo?.capabilities?.image===!0&&c.push("image");let l={baseUrl:`${ho}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:i,name:i,reasoning:!1,input:c,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??Jc,maxTokens:8192,api:"openai-completions"}]};return Object.keys(o).length>0&&(l.headers=o),l}function n0(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function Xc(t,e,r){let i=xo(e,r),o=t.modelInfo?.contextWindow??Jc,c=["model:"," provider: openai",` base_url: ${ho}/v1`,` context_length: ${o}`];if(Object.keys(i).length>0){c.push(" default_headers:");for(let[l,u]of Object.entries(i))c.push(` ${l}: ${JSON.stringify(u)}`)}return`${c.join(`
96
+ `)}
97
+ `}var Fi=H("hermes-config"),i0="dont_ask",s0="default";function Kn(t,e){return zi(Be(t,e).root,"hermes-home")}async function cy(t){let e=Kn(t.agentId,t.paths);await ay(e,{recursive:!0,mode:448});let r=Ni({...process.env,...Li(t.paths.agentEnvFile),...n0(t.modelConfig)});await lt(zi(e,".env"),r,{mode:384});let i=Xc(t.modelConfig,t.cozeEnv,t.mockScenario);await lt(zi(e,"config.yaml"),i,{mode:384}),Fi.debug("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:r.length,yamlBytes:i.length})}async function o0(t){let e=Kn(t.agentId,t.paths),r=zi(e,"state.db"),i=zi(e,"config.yaml");await r0(r,{force:!0}).catch(c=>Fi.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(c)}));let o=Xc({modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await lt(i,o,{mode:384}).catch(c=>Fi.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(c)})),Fi.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function el(t,e){let r=Kn(t,e);await r0(r,{recursive:!0,force:!0}).catch(i=>Fi.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var Qc=new Map;function a0(t){let e=Qc.get(t.agentId);if(e)return e;let r=cy(t).finally(()=>Qc.delete(t.agentId));return Qc.set(t.agentId,r),r}var fe=H("agent-handlers"),l0=5*1024*1024,fy=1,hy=6,xy=new Set(["node_modules",".git",".coze","dist","build",".next"]),py=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,gy=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,my=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function wy(t){let e=t?.trim();return e?my.test(e)||gy.test(e)?e:(fe.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function _y(t){return new Promise((e,r)=>{let i=rt("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=l=>{o||(o=!0,l?r(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",l=>c(l))})}var go=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??J()}async listSkills(e){e._meta;let r=Wn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Be(r,this.paths).workspace,c=i?.framework??"claude-code",l=i?.skills??[],{base:u}=Rr(c,r,o,this.paths),f=[],x=new Set;for(let p of l){let m=$e(u,p.relPath,"SKILL.md");await c0(m).then(_=>_.isFile()).catch(()=>!1)&&(f.push(vy(p)),x.add(p.relPath))}if(e.scanLocal){let p=await yy(r,o,c,this.paths);for(let m of p)x.has(m.relPath)||(x.add(m.relPath),f.push(m.skill))}return{skills:f}}async addSkills(e){e._meta;let r=Wn(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],l=new Map(c.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await mo({agentId:r,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});wo(c,l,x),u.push(f)}return await oi(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Wn(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],l=[],{base:u}=Rr(i.framework,r,i.workspace,this.paths);for(let f of c){if(!o.has(f.skillId)){l.push(f);continue}let x=$e(u,f.relPath);await rl(x,{recursive:!0,force:!0}),fe.info("skill removed",{agentId:r,skillId:f.skillId,relPath:f.relPath})}return await oi(r,l),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Wn(e._meta);if(!e.skillName)throw new T("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");fe.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??Be(r,this.paths).workspace,c=i?.framework??"claude-code",l=p0(e.skillName),{base:u,subdir:f}=Rr(c,r,o,this.paths),x=$e(f,l),p=$e(u,x),m=$e(p,"SKILL.md");if(!await c0(m).then(y=>y.isFile()).catch(()=>!1))throw new T("SKILL_NOT_FOUND",`skill not found locally: ${e.skillName} (${x})`);let _=new cl.default;_.addLocalFolder(p,l);let b=_.toBuffer();if(b.length>d0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${b.length} bytes exceeds limit ${d0}`);let I=await po(m,{encoding:"utf8"}).then(y=>m0(y).description).catch(()=>{}),A={};this.opts.publishSkillToMarketplace?A=await this.opts.publishSkillToMarketplace({zip:b,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...I?{description:I}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):fe.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let k=A.version??"v1.0",P=A.skillId??e.skillId??g0(r,x);if(i){let y=i.skills??[],R=y.find(O=>O.relPath===x);R?(R.version=k,R.skillId=P):y.push({skillId:P,skillName:e.skillName,relPath:x,version:k,installedAt:Date.now(),...I?{description:I}:{}}),await oi(r,y)}return fe.info("skill published",{agentId:r,skillName:e.skillName,relPath:x,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 l=c.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,fe.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l});continue}let f=c.downstream;c.downstream=void 0,fe.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l}),f.stop(r).catch(x=>fe.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return fe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await Ee(r);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return fe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await dr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw fe.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Fe(i),fe.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 Ee(r))throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Oi(e.registry)&&o.push(`--registry=${e.registry}`);let c=wy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&py.test(l)&&o.push("--env",l);let u=await _y(o);return fe.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 Ee(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Fe(i),fe.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}):(fe.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new T("IPC_BAD_REQUEST",`${ft.DELETE}: missing agentId`);let i=await Ee(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let l=Be(r);return c==="cloud"?await rl(l.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Fe(i)),fe.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Tr(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Zc(e.model)??vt,i=await Ee(e.agentId);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Fe(i),fe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return fe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o).catch(l=>fe.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(l)}));let c=[];for(let[l,u]of o.allSessionQueues())c.push(u.enqueue(async()=>{let f=o.sessions.get(l);f?.downstream&&(await f.downstream.stop(`switchModel: ${r}`).catch(()=>{}),f.downstream=void 0)}));return await Promise.all(c),fe.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:c.length}),{ok:!0}}async resetAgent(e){if(Tr(e._meta,ft.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ft.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ft.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(r=>fe.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(r)})),await this.runDetailSync(e.agentId,ft.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),fe.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,l]of i.sessions)o.set(c,{modelToken:l.modelToken,tokenGeneratedAt:l.tokenGeneratedAt});await si(e,o)}async clearPersistedAcpSessionIds(e){let r=await Ee(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await Fe(r)}async repairAgent(e){if(Tr(e._meta,ft.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ft.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${ft.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){fe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ft.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){fe.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){fe.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Tr(e._meta,"_agent/getFileTree");let r=e._meta,i=Wn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(o,c),u=await tl(l).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 ii(l,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=Ny(e.depth);return u.isDirectory()?{tree:await Ly(o,l,c,f)}:{tree:[{name:My(c),path:y0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Tr(e._meta,"_agent/getFileContent");let r=Wn(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 tl(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 ii(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>l0)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${l0})`);let l=await po(o);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:c.size}:{content:l.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await Ee(e).catch(()=>null))?.workspace??Be(e).workspace}safeJoin(e,r){let i=sl(e,r||"."),o=al(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${f0}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Ee(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 p0(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 Rr(t,e,r,i){switch(t){case"claude-code":return{base:r,subdir:$e(".claude","skills")};case"codex":case"openclaw":return{base:r,subdir:$e(".agents","skills")};case"hermes":return{base:Kn(e,i??J()),subdir:"skills"}}}function g0(t,e){return(ly("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function m0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
98
+ ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
99
+ `)){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 yy(t,e,r,i){let{base:o,subdir:c}=Rr(r,t,e,i),l=$e(o,c),u=await u0(l,{withFileTypes:!0}).catch(()=>null);if(!u)return[];let f=[];for(let x of u){if(!x.isDirectory())continue;let p=x.name,m=$e(c,p),v=$e(l,p,"SKILL.md"),_=await po(v,{encoding:"utf8"}).catch(()=>null);if(_===null)continue;let b=m0(_);f.push({relPath:m,skill:{skillId:g0(t,m),skillName:b.name||p,...b.description?{description:b.description}:{}}})}return f}var by=3e4,Ey=50*1024*1024,d0=10*1024*1024,Pr=3e4;async function mo(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 l=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!l&&!u)throw new T("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let f=p0(o.skillName),{base:x,subdir:p}=Rr(i,e,r,c),m=$e(p,f),v=$e(x,m);if(await nl(v,{recursive:!0}),l){let b=Buffer.from(o.content,"utf8");Ui(b.length),await il($e(v,"SKILL.md"),b,"utf8")}else{let b=await Iy(o.downloadUrl);Ty(b)?await Py(b,v):ky(b)?await Cy(b,v):await il($e(v,"SKILL.md"),b.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:m,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 fe.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:m,source:l?"content":"downloadUrl"}),_}function wo(t,e,r){let i=e.get(r.skillId);if(i!==void 0){t[i]=r;return}e.set(r.skillId,t.length),t.push(r)}function vy(t){return{skillId:t.skillId,skillName:t.skillName,...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}function Sy(t){return{skillId:t.skillId,skillName:t.skillName,...t.downloadUrl?{downloadUrl:t.downloadUrl}:{},...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function w0(t,e){let r=await Ee(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Ot,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await Fe(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],l=new Map(c.map((m,v)=>[m.skillId,v])),u=c.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Fe(r,e),{status:"noop",count:0};let f=0,x=0,{base:p}=Rr(r.framework,t,r.workspace,e);for(let m of u)try{await rl($e(p,m.relPath),{recursive:!0,force:!0});let v=await mo({agentId:t,workspace:r.workspace,framework:r.framework,skill:Sy(m),...e?{paths:e}:{}});wo(c,l,v),f+=1}catch(v){x+=1,fe.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(v)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await Fe(r,e),fe.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function Iy(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ui(e);let r=Ay(t);return Ui(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await po(e);return Ui(r.length),r}if(Oi(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),by);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 Ui(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 Ui(t){if(t>Ey)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Ay(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new T("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function Ty(t){return t.length>=2&&t[0]===31&&t[1]===139}function ky(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 ol(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Cy(t,e){let r,i;try{r=new cl.default(t),i=r.getEntries()}catch(l){throw new T("IPC_BAD_REQUEST",`zip parse failed: ${l.message}`,{cause:l})}for(let l of i){let u=l.entryName;if(!u||ol(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new T("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=l.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=Ry(i),c=sl(e);for(let l of i){if(ol(l.entryName))continue;let u=l.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=sl(e,u),x=al(c,f);if(x.startsWith("..")||x==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await nl(f,{recursive:!0});continue}await nl(dy(f),{recursive:!0});let p;try{p=l.getData()}catch(m){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${m.message}`,{cause:m})}await il(f,p)}}function Ry(t){let e;for(let r of t){let i=r.entryName;if(!i||ol(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 Py(t,e){await Dy(t);let r=Mf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`))},Pr);try{await x0(h0.from(t),r)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Dy(t){let e=[],r=Ar({onReadEntry:c=>{let l=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${l.slice(0,100)}`);return}if(l.startsWith("/")||l.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(l)){e.push(`tar entry absolute path: ${l}`);return}l.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${l}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Pr}ms)`))},Pr);try{await x0(h0.from(t),r)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Pr}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Oy=5e3;async function Ly(t,e,r,i){return _0(t,e,r,i,{count:0})}async function _0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await u0(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if(xy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Oy){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=$e(e,u.name),x=uy($e(r,u.name)),p=null;try{p=await tl(f)}catch{continue}if(p.isSymbolicLink())continue;o.count++;let m={name:u.name,path:y0(al(t,f)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(m.children=await _0(t,f,x,i-1,o)),l.push(m)}return l.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),l}function Ny(t){return!t||t<=0?fy:Math.min(t,hy)}function My(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function y0(t){return t.split(f0).join("/")}te();var En=H("agent-health-reporter"),By=1e4,Fy=3,Hi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??By,this.livenessFailureThreshold=e.livenessFailureThreshold??Fy}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()}),En.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),En.info("heartbeat stopped"))}async tick(){if(this.inFlight){En.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,En.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let l of this.opts.core.agents.values()){let u=zy(l);if(!u)continue;let f={agentId:l.agentId,status:u};l.patToken&&(f.patToken=l.patToken),l.accountId&&(f.accountId=l.accountId),r.push(f)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Ot,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(l){this.consecutiveFailures+=1,En.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let c=o?.authFailures;if(c&&c.length>0&&(En.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){En.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){En.warn("onTickEnd hook failed",{err:String(r)})}}};function zy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Ht();import{mkdir as fl,rm as Db,stat as Ob}from"node:fs/promises";import{homedir as Lb}from"node:os";import{join as xl}from"node:path";an();import{existsSync as Zy}from"node:fs";import{release as Yy}from"node:os";import{basename as Xy,isAbsolute as Qy}from"node:path";function Gi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Dr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Or(t,e){return{jsonrpc:"2.0",id:t,result:e}}function vn(t,e){return{jsonrpc:"2.0",id:t,error:e}}We();var _o=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Z={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 b0(t){return"method"in t&&"id"in t&&t.id!==void 0}function E0(t){return"method"in t&&!("id"in t)}function yo(t){return!("method"in t)&&"id"in t}var Uy={AGENT_NOT_FOUND:Z.AGENT_NOT_FOUND,AGENT_BUSY:Z.AGENT_BUSY,AGENT_DISCONNECTED:Z.AGENT_DISCONNECTED,AGENT_TIMEOUT:Z.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Z.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Z.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Z.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Z.INTERNAL_ERROR,BRIDGE_INTERNAL:Z.INTERNAL_ERROR,IPC_AUTH_FAILED:Z.INTERNAL_ERROR,IPC_BAD_REQUEST:Z.INVALID_REQUEST,METHOD_NOT_FOUND:Z.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Z.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Z.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Z.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Z.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Z.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Z.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Z.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Z.FILE_TOO_LARGE,UNSUPPORTED_MIME:Z.UNSUPPORTED_MIME,UPLOAD_FAILED:Z.UPLOAD_FAILED,UPSTREAM_NOT_READY:Z.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Z.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Z.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Z.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Z.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Z.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Z.SKILL_ZIP_TOO_LARGE};function Hy(t){if(t!=null)return t instanceof Error?{name:t.name,message:qi(t.message)}:typeof t=="string"?qi(t):typeof t=="object"?qy(t):t}var Gy=[[/\/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 qi(t){let e=t;for(let[r,i]of Gy)e=e.replace(r,i);return e}function qy(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=qi(i):e[r]=i;return e}function ji(t){if(t instanceof T){let e=Hy(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:Uy[t.code]??Z.INTERNAL_ERROR,message:qi(t.message),data:r}}return{code:Z.INTERNAL_ERROR,message:qi(t instanceof Error?t.message:String(t))}}function v0(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:l,...u}=e;c=u}return new T(r,o,{retriable:e?.retriable??!1,cause:c})}function I0(t){return`${JSON.stringify(t)}
100
+ `}var S0=10*1024*1024,bo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>S0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${S0} bytes`)}),[]}let r=this.buffer.split(`
101
+ `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(l){this.onError?.({line:c,error:l})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var T0={"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"},ek=Object.fromEntries(Object.entries(T0).map(([t,e])=>[e,t])),jy={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Lr=class{seq=0;next(e,r){this.seq+=1;let i=T0[e]??Wy(e),o=jy[i]??[],c=[i,String(this.seq)];if(o.length>0){let l=o.map(f=>A0(r?.[f]??"")),u=Ky(l).join(":");u&&c.push(u)}else r&&Object.values(r).some(l=>l)&&c.push(Object.values(r).filter(Boolean).map(l=>A0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function Wy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function A0(t){return t.replace(/[:_\s]+/g,"-")}function Ky(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Vt();ir();We();te();Ce();import{execFileSync as $y,spawnSync as Vy}from"node:child_process";function Wi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Ki(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Vy("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ll=new Set;function k0(t){typeof t=="number"&&t>0&&ll.add(t)}function C0(t){typeof t=="number"&&ll.delete(t)}function R0(){for(let t of ll)Ki(t,"SIGKILL")}var Nr="coze-bridge-daemon";function P0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return $y("pgrep",["-U",String(o),"-f",Nr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
102
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function D0(t,e){if(t.length===0)return;let r=e?.killFn??Ki,i=e?.isAliveFn??Wi,o=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),c=e?.graceMs??3e3,l=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(f=>i(f));u+=l)await o(Math.min(l,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var Jy=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @(zed-industries|agentclientprotocol)\/codex-acp|optional dependency was not installed|\.resolve is not a function/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find module[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|zed-industries[\\/]codex-acp)/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"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 O0(t,e){if(!e)return null;for(let r of Jy)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function L0(t,e){return O0(t,e)}function N0(t,e){return O0(t,e)}function Mr(t,e,r){return!e&&r.firstUpdateMs>0&&t<r.firstUpdateMs?Math.max(1,r.firstUpdateMs-t):t<r.phase2GateMs?Math.max(1,r.phase2GateMs-t):Math.max(1,r.livenessWindowMs)}function M0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,p=r-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Mr(p,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,l=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=l?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:Mr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Mr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Mr(c,!1,e)}}var B0=Je("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),eb=200,tb=40,nb=Je("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),rb=Je("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),ib=Je("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),sb=Je("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),ob=Je("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),ab=Je("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),F0=500;function cb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=F0?t:`${e.slice(0,F0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function lb(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 z0(t){try{return Zy(t)}catch{return}}function db(t,e){return{platform:process.platform,osRelease:Yy(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Qy(e.command)?z0(e.command):void 0,cwd:e.cwd,cwdExists:z0(e.cwd),envKeys:e.envKeys}}function ub(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Xy(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var ht=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new bo({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Lr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;spawnEnv={};sanitizeEnv(e){return e}async start(){if(this.child)throw new T("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=jf(process.env,this.opts.agentEnvFile??J().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o));this.spawnEnv=r;let i=rt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,k0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>eb&&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,C0(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=db(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:l}),this.failAllPending(new T("AGENT_SPAWN_FAILED",ub(c,l),{cause:l}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));Ki(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||Ki(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r){let i={firstUpdateMs:ob,phase2GateMs:nb,livenessWindowMs:rb,absoluteMaxMs:ib,approvalMaxMs:ab,suspendThresholdMs:sb,...r};return this.call("session/prompt",e,B0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Dr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Or(e,r))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(vn(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=B0,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=Gi(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let f=r.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,x)=>{let p={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let m=this.now(),v={cfg:o,startedAt:m,lastActivityAt:m,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:m,expectedIntervalMs:Mr(0,!1,o),sessionId:u};p.promptTimeout=v;let _=()=>{let b={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},I=this.now(),A=M0(b,v.cfg,I),k=P=>{v.armedAt=I,v.expectedIntervalMs=P,p.timer=setTimeout(_,P)};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}:{}}),k(A.rearmMs);return}if(A.action==="continue"){k(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),x(A.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(_,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(p.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,p);try{this.writeFrame(l)}catch(m){p.timer&&clearTimeout(p.timer),this.pending.delete(c),x(m)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(I0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(yo(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new T("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:cb(e.result)}),r.resolve(e.result));return}if(E0(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(b0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let l=typeof i.status=="string"?i.status:void 0,u=l==="completed"||l==="failed"||l==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(vn(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(vn(e.id,ji(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=v0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=N0(this.framework,lb(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(tb).join(`
103
+ `),o=L0(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 fb(t){let e={};for(let[r,i]of Object.entries(t))i!==void 0&&(r.startsWith("CLAUDE")||r==="AI_AGENT"||r==="BAGGAGE"||(e[r]=i));return e}var Eo=class extends ht{framework="claude-code";constructor(e){let{command:r,args:i}=ri("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 fb(e)}};an();import{mkdtempSync as gb,rmSync as mb}from"node:fs";import{tmpdir as wb}from"node:os";import{join as _b}from"node:path";import{readFileSync as H0}from"node:fs";import{homedir as hb}from"node:os";import{join as U0}from"node:path";function G0(t){let e=t.CODEX_HOME?.trim()||U0(t.HOME?.trim()||hb(),".codex");return U0(e,"config.toml")}function xb(t){let e=null;for(let r=0;r<t.length;r++){let i=t[r];if(e)i===e&&(e=null);else if(i==='"'||i==="'")e=i;else if(i==="#")return t.slice(0,r)}return t}function pb(t){let e=t.trim();if(e.length>=2){let r=e[0];if((r==='"'||r==="'")&&e[e.length-1]===r)return e.slice(1,-1)}return e}function q0(t){let e={},r={},i=e;for(let o of t.split(/\r?\n/)){let c=xb(o).trim();if(!c)continue;let l=/^\[([^\]]+)\]$/.exec(c);if(l){let x=(l[1]??"").trim(),p=r[x]??{};r[x]=p,i=p;continue}let u=c.indexOf("=");if(u<=0)continue;let f=c.slice(0,u).trim();f&&(i[f]=pb(c.slice(u+1)))}return{root:e,tables:r}}function j0(t){let e=t.root.model_provider;if(!e||e==="openai")return null;let r=t.tables[`model_providers.${e}`];return r?{providerId:e,baseUrl:r.base_url,envKey:r.env_key,bearerToken:r.experimental_bearer_token}:null}function W0(t){let e;try{e=H0(G0(t),"utf8")}catch{return null}return j0(q0(e))?.providerId??null}function K0(t){let e;try{e=H0(G0(t),"utf8")}catch{return null}let r=j0(q0(e));if(!r?.baseUrl)return null;let i=r.bearerToken||(r.envKey?t[r.envKey]?.trim():void 0);return i?{baseUrl:r.baseUrl,providerName:r.providerId,headers:{Authorization:`Bearer ${i}`}}:null}var vo=class t extends ht{framework="codex";authRequest;resolveLocalGatewayAuth;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ri("codex",e.command,i),l=e.isolateCodexHome?gb(_b(wb(),"coze-bridge-codex-home-")):void 0,u=l?{...e.env??{},CODEX_HOME:l}:e.env,f={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(f),this.authRequest=e.authRequest,this.resolveLocalGatewayAuth=e.resolveLocalGatewayAuth??!1,this.codexHomeDir=l}async initialize(e){let r=await super.initialize(e),i=this.authRequest??this.localGatewayAuthRequest();return i&&await this.call("authenticate",i),r}localGatewayAuthRequest(){if(!this.resolveLocalGatewayAuth)return null;let e=K0(this.spawnEnv);return e?(this.log.info("codex local: \u7528 config.toml custom provider \u8D70 gateway \u8BA4\u8BC1",{providerName:e.providerName,baseUrl:e.baseUrl}),{methodId:"gateway",_meta:{gateway:e}}):null}static MODE_ID_MAP={"read-only":"read-only",auto:"agent","full-access":"agent-full-access"};setSessionMode(e){let r=t.MODE_ID_MAP[e.modeId]??e.modeId;return super.setSessionMode({...e,modeId:r})}async stop(e){if(await super.stop(e),this.codexHomeDir)try{mb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var So=class extends ht{framework="hermes";constructor(e){let r={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(r)}};We();var yb=3e4,Br=class extends ht{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}`}]},yb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var $0=["default","acceptEdits","plan","auto","bypassPermissions"],V0=["read-only","auto","full-access"],J0=["default","accept_edits","dont_ask"];function Sn(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return $0.includes(e);case"codex":return V0.includes(e);case"hermes":return J0.includes(e);case"openclaw":return!1}}function dl(t){switch(t){case"claude-code":return $0.join("/");case"codex":return V0.join("/");case"hermes":return J0.join("/");case"openclaw":return""}}Ut();We();te();Ce();function ul(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}an();var In=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 Io=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 In,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)$i(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 $i(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Jt(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Vt();te();import{constants as Z0}from"node:fs";import{access as bb,readFile as Eb}from"node:fs/promises";import{delimiter as vb,dirname as Sb,join as Y0}from"node:path";var Qe=H("framework-detector"),X0={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},Ib=[".exe",".cmd",".bat",".ps1"],$n=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??rt,access:e.access??bb,readFile:e.readFile??Eb}}async detect(e){let r=X0[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,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(X0).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(vb).filter(Boolean),i=this.env.platform==="win32"?["",...Ib]:[""];for(let o of r)for(let c of i){let l=Y0(o,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?Z0.F_OK:Z0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async 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(l){return Qe.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(l)}),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=Y0(Sb(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(l=>l?.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 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){Qe.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(l)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(Tb(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,l,u=f=>{c||(c=!0,l&&clearTimeout(l),i(f))};try{let f=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});l=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{o+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},Ab=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Tb(t){return t.replace(Ab,"")}import{homedir as kb}from"node:os";import{join as Cb}from"node:path";Ut();Vt();ir();We();te();async function th(){let t=Cb(kb(),".openclaw/openclaw.json");return(await cr(t))?.gateway?.auth?.token??""}var Q0=H("openclaw.config"),Rb=[0,5e3,5e3],Pb=Je("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),eh="models.providers.",Ao="agents.defaults.models",To=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new In;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Rb,this.cliTimeoutMs=e.cliTimeoutMs??Pb}async withRetry(e,r){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(l=>setTimeout(l,c));try{return await r()}catch(l){i=l,Q0.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(l)})}}throw new T("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=rt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",l=!1,u=x=>{l||(l=!0,clearTimeout(f),x())};o.stderr?.on("data",x=>{c+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?r():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",r])))}catch(i){Q0.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",`${eh}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${eh}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Ao}[${e}]`,()=>this.runCli(["config","set",Ao,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Ao}[${e}]`,`${Ao}.${e}`)}ensureAgent(e,r,i){let o=["agents","add",e,"--workspace",r,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var de=H("agent-manager"),pl="acceptEdits",ih="full-access",sh="read-only";function Nb(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}var Mb=(t,e,r,i,o,c,l,u,f,x)=>{switch(t){case"claude-code":{let p={...o?{...Yf(o),...e0(o,l,u)}:{},...f??{},IS_SANDBOX:"1"};return new Eo({cwd:r,env:p,agentId:i})}case"codex":{let p=ih;x!==void 0&&(Sn("codex",x)?p=x:de.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let m=o?null:W0(process.env),v={...o?Qf(o):{},INITIAL_AGENT_MODE:Nb(p),...process.env.COZE_BRIDGE_CODEX_APP_SERVER_LOGS==="1"?{APP_SERVER_LOGS:xl(r,"..","logs","codex-app-server")}:{},...m?{MODEL_PROVIDER:m}:{},...f??{}},_=o?Xf(o,l,u):null,b=_?{methodId:"gateway",_meta:{gateway:_}}:void 0,I=!!o,A=!I&&process.env.COZE_BRIDGE_CODEX_LOCAL_GATEWAY_AUTH==="1";return new vo({cwd:r,agentId:i,...Object.keys(v).length>0?{env:v}:{},...b?{authRequest:b}:{},...I?{isolateCodexHome:!0}:{},...A?{resolveLocalGatewayAuth:!0}:{}})}case"openclaw":return new Br({command:e,cwd:r,agentId:i,...c?{sessionName:ul(c)}:{}});case"hermes":return new So({command:e,cwd:r,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{}})}};function hl(t){return t==="claude-code"||t==="codex"}var Bb={path:"",version:"cloud-deployed"},nh="openclaw_gateway_unavailable",Fb="openclaw_default_agent_missing";function rh(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 zb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Ub=6e4,ko=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Mb,this.createTimeoutMs=e.createTimeoutMs??Ub,this.detectorFactory=e.detectorFactory??(()=>new $n),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new To({command:r})),this.openclawConfigDir=e.openclawConfigDir??xl(Lb(),".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=>{de.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=xl(e,".env");if(await Ob(r).then(c=>c.isFile()).catch(()=>!1)){de.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=Ni({...process.env,...Li(this.paths.agentEnvFile)});await lt(r,o,{mode:384}),de.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),de.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 Ee(e.agentId,this.paths).catch(()=>null),o=lo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new T("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")de.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(k=>de.warn("dispose stale agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")de.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(k=>de.warn("dispose drifted agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){de.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let k=await Ee(e.agentId,this.paths).catch(()=>null);k&&(k.patToken=e.patToken,await Fe(k,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){de.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let k=await Ee(e.agentId,this.paths).catch(()=>null);k&&(k.modelInfo=e.modelInfo,await Fe(k,this.paths))}return de.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 P=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${P}`)}let u=Be(e.agentId,this.paths),f=o?"cloud":"local",x=e.framework==="openclaw"&&f==="local",p;x&&!r?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let m=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??m??u.workspace,_=new AbortController,b=setTimeout(()=>_.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&hl(e.framework)&&await ar(e.framework,_.signal);let k=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await fl(u.root,{recursive:!0}),await fl(v,{recursive:!0}),await fl(u.logs,{recursive:!0}),k(),x||await dr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Fa(v,"cloud"):await Fa(v,"local",pl)),k();let P=i,y=Zf({model:e.model??P?.model}),R=Ff(e._meta)??P?.accountId,O=e.patToken??P?.patToken,F=f==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new Io({agentId:e.agentId,framework:e.framework,workspace:v,model:y.model??vt,deployType:f,...R?{accountId:R}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",P?.sessions){let $=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Y,se]of Object.entries(P.sessions)){let oe={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};$?se.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",de.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Y,framework:e.framework,fallback:oe.permissionMode})):Sn(e.framework,se.permissionMode)?oe.permissionMode=se.permissionMode:de.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Y,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&de.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Y,framework:e.framework,deployType:f}),se.cozeGroupId&&(oe.cozeGroupId=se.cozeGroupId),I.sessions.set(Y,oe)}let ne=Object.keys(P.sessions).length;ne>0&&de.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ne})}this.registry.register(I),A=!0;let M={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:y.model};f==="cloud"&&(M.deployType="cloud"),R&&(M.accountId=R),O&&(M.patToken=O),F&&(M.modelInfo=F),P?.skills&&(M.skills=P.skills),P?.agentName&&(M.agentName=P.agentName),P?.description&&(M.description=P.description),M.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Ot,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):de.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let V=e.initialSkills??[];if(V.length>0){let $=[...M.skills??[]],ne=new Map($.map((oe,C)=>[oe.skillId,C])),Y=await Promise.allSettled(V.map(oe=>mo({agentId:e.agentId,workspace:v,framework:e.framework,skill:oe,paths:this.paths}))),se=0;for(let[oe,C]of Y.entries()){let U=V[oe];U&&(C.status==="fulfilled"?(wo($,ne,C.value),se++):de.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(C.reason)}))}se>0&&(M.skills=$,de.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:V.length}))}return await Fe(M,this.paths),de.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(k){throw de.error("agent create failed, rolling back",{agentId:e.agentId,err:String(k)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Db(u.root,{recursive:!0,force:!0}).catch(P=>de.warn("rm agent dir failed (ignored)",{err:String(P)})),k instanceof T?k:new T("AGENT_SPAWN_FAILED",String(k),{cause:k})}finally{clearTimeout(b)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&hl(e.framework))u=Bb;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`);hl(e.framework)&&!gs(e.framework)&&(de.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await ar(e.framework));let f=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:f,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else if(e.framework==="hermes"){let p={...this.buildBinShimPathEnv()};f&&(await a0({paths:this.paths,agentId:e.agentId,modelConfig:f,cozeEnv:o,mockScenario:c}),p.HERMES_HOME=Kn(e.agentId,this.paths)),x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,p)}else{let p=e.sessions.get(i),m=Jt(e)?p?.permissionMode??ih:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,this.buildBinShimPathEnv(),m)}try{return await x.start(),await x.initialize(zb),x}catch(p){let m=x instanceof ht?x.getStderrTail():[];throw m.length>0&&de.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:p instanceof T?p.code:"unknown",recentStderr:m}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,p)}}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",rh(o),{cause:{reason:nh}})}catch(o){de.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};de.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 de.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:Fb}})}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",rh(r),{cause:{reason:nh}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:l,command:u}=e,f=ul(o);if(r.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new Br({command:u,cwd:v.workspace,agentId:v.id,sessionName:f})}let x=await th(),p=i?t0(i,c,l):null,m;if(p){let v=Yc(o),b=p.models[0]?.id??vt,I=`${v}/${b}`;if(!this.ensuredProviders.has(I)){let A=this.getOpenclawConfig();await A.ensureProvider(v,p),await A.addModelToAllowlist(I),this.ensuredProviders.add(I)}m=I}return new Br({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:f,...x?{gatewayToken:x}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let r=this.openclawConfigCache;for(let i of e.sessions.keys()){let o=Yc(i),c=`${o}/${e.model}`,l=!0;try{await r.removeProvider(o)}catch(u){l=!1,de.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:o,err:String(u)})}try{await r.removeModelFromAllowlist(c)}catch(u){l=!1,de.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:c,err:String(u)})}l&&this.ensuredProviders.delete(c)}}};import{randomUUID as dh}from"node:crypto";import{promises as $b}from"node:fs";import{basename as uh}from"node:path";We();te();import{promises as Hb}from"node:fs";import{basename as Gb}from"node:path";var oh=H("file-upload"),qb="/api/coze_claw/file/agent_upload",jb=6e4;async function ah(t,e={}){let i=`${kr(Cr(e.handshakeBase))}${qb}`,o=e.timeoutMs??jb,c=await Hb.readFile(t.path),l=new FormData;l.append("agent_id",t.agentId),l.append("session_id",t.sessionId),l.append("file_name",t.name),l.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...bn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);oh.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let p=await fetch(i,{method:"POST",headers:u,body:l,signal:f.signal}),m=p.headers.get("x-tt-logid")??"";if(!p.ok){let b=await p.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${m}: ${b.slice(0,200)}`)}let v=await p.json();if(v.code!==void 0&&v.code!==0)throw new T("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${m}`);let _=v.data?.file?.file_url;if(!_)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${m}: ${JSON.stringify(v).slice(0,200)}`);return oh.info("file upload ok",{uri:_,logid:m}),{uri:_}}catch(p){throw p instanceof T?p:p.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Gb(t.path)}`):new T("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}We();te();import{extname as Wb}from"node:path";var Kb={".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 ch(t){let e=Wb(t).toLowerCase();return Kb[e]??"application/octet-stream"}Ce();var Co=H("agent-send"),lh=50*1024*1024;function fh(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 hh(t,e,r,i,o,c){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(x){u=x,f<2&&(Co.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function xh(t,e){let{session:r,runtime:i}=fh(e.core,t.agentId,t.sessionId);if(!await ii(t.path,r.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await $b.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>lh)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${lh}`);let c=await ch(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 l=t.name??uh(t.path),u;try{u=await ah({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:l,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Co.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:x instanceof T?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let f={sessionUpdate:"agent_file",messageId:dh(),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 hh(e,r,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Co.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 ph(t,e){let{session:r,runtime:i}=fh(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??uh(t.path),c={sessionUpdate:"group_file",messageId:dh(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await hh(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Co.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 gh(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(r.length,i.length);for(let c=0;c<o;c++){let l=r[c]??0,u=i[c]??0;if(l<u)return!0;if(l>u)return!1}return!1}an();Vt();te();var Lt=H("coze-cli-installer"),mh="@coze/cli@latest",Vb="coze",wh="0.1.8",Jb=5e3,Zb=5e3,Yb=9e4,_h=1e4,Vi=null,Ro=!1;async function ml(t,e={}){if(Ro)return;if(Vi)return Vi;let r=e.exec??qf;return Vi=(async()=>{try{let i=await Xb(Vb,r),o=!1;if(i){let l=await Qb(r);if(l===void 0)Lt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(gh(l,wh))Lt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:wh}),o=!0;else{Lt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),Ro=!0;return}}let c=o?"upgrade-only":"full";Lt.info("coze-cli install start",{package:mh,mode:c});try{await r("npm",["i","-g","--prefer-online",mh],{timeout:Yb,maxBuffer:10*1024*1024}),Lt.info("coze-cli install ok")}catch(l){Lt.warn("coze-cli install failed (skip subsequent steps)",{err:String(l)});return}if(o){Ro=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:_h}),Lt.info("coze config set xTTEnv ok",{env:t.env})}catch(l){Lt.warn("coze config set failed (continue to auth login)",{err:String(l)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:_h}),Lt.info("coze auth login ok")}catch(l){Lt.warn("coze auth login failed",{err:String(l)});return}Ro=!0}finally{Vi=null}})(),Vi}async function Xb(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:Jb});return Ma(i)}catch{return}}async function Qb(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:Zb});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Ht();Ut();Ce();var eE=10*6e4;function yh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?eE:e}function Po(t){return cr(t??J().configFile)}function Ji(t,e){return lr(e??J().configFile,t)}import{randomBytes as yE}from"node:crypto";ir();We();te();import{createReadStream as tE}from"node:fs";import{mkdir as nE,readFile as rE,realpath as iE,stat as sE,writeFile as oE}from"node:fs/promises";import{basename as aE,dirname as wl,isAbsolute as cE,join as lE,relative as dE,resolve as bh,sep as uE}from"node:path";import{createInterface as fE}from"node:readline";var vh=H("fs-rpc"),Zi=Je("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Sh(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Zi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Zi} bytes`);let i=await Ah(t.path,e);return await nE(wl(i),{recursive:!0}),await oE(i,t.content,"utf8"),vh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Ih(t,e){let r=await Ah(t.path,e),i=await sE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Zi&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Zi} bytes`);let c;if(o&&i.size>Zi)c=await hE(r,t.line??1,t.limit);else{let l=await rE(r,"utf8");if(o){let u=l.split(`
104
+ `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;c=u.slice(f,x).join(`
105
+ `)}else c=l}return vh.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function hE(t,e,r){let i=fE({input:tE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,l=[],u=0;try{for await(let f of i)if(u>=o&&u<c&&l.push(f),u++,u>=c)break}finally{i.close()}return l.join(`
106
+ `)}async function Ah(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([Eh(bh(e)),Eh(bh(t))]),o=dE(r,i);if(xE(o,uE,cE(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function xE(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function Eh(t){let e=[],r=t;for(;r!==wl(r);)try{let i=await iE(r);return e.length?lE(i,...e.reverse()):i}catch{e.push(aE(r)),r=wl(r)}return t}te();var Th=H("prompt-multimodal"),kh=10*1024*1024,pE=15e3,gE=6;async function Ch(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,l=t[c];l!==void 0&&(e[c]=await mE(l))}}let o=Array.from({length:Math.min(gE,t.length)},()=>i());return await Promise.all(o),e}function Rh(t){return t.some(e=>e.type==="image")}async function mE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Oi(e.uri))return t;try{let{buf:r,contentType:i}=await _E(e.uri),o=e.mimeType||wE(i)||"application/octet-stream";return Th.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 Th.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function wE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function _E(t){let e=new AbortController,r=setTimeout(()=>e.abort(),pE);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>kh)throw new Error(`image too large: ${o.byteLength} bytes (max ${kh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}Ht();We();te();var K=H("core"),bE=3e4,EE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,vE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",SE="\u5BA1\u6279\u5DF2\u8D85\u65F6",IE=3e4,Do=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Lr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=yh(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),K.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){K.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),K.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){K.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&K.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,l)=>{K.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:l}),$i(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){K.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(vn(o,{code:Z.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(l=>K.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:Z.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){K.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Z.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(yo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&EE.test(i)?this.currentCozeEnv=i:i&&K.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,Z.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):K.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Or(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Or(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Or(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,Z.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):K.warn("drop unknown notification",{method:e.method})}catch(o){K.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(vn(r,ji(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 f=o.sessions.get(c);if(f?.pendingPermission){let x=r._meta?.cozeTriggerMsgId,p=uo(r._meta);return K.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,vE,x,p)}}let l=Date.now(),u=!1;try{let f=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,f}finally{K.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-l,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Uf(i);switch(r){case"session/new":{let c=AE();return K.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return K.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,l=c.sessionId;if(!l)throw new T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Jt(e)?zf(i._meta):void 0;if(u!==void 0&&!Sn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${dl(e.framework)}`);let f=await this.ensureRuntime(e,l);if(u!==void 0&&f.permissionMode===void 0&&(f.permissionMode=u,await this.persistSessionMapping(e)),f.replySeq=0,await this.ensureDownstream(e,l,f),!f.downstream||!f.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&f.permissionMode!==void 0&&f.permissionMode!==u){let v=f.permissionMode;f.permissionMode=u,await this.persistSessionMapping(e);try{await f.downstream.setSessionMode({sessionId:f.acpSessionId,modeId:u})}catch(_){throw f.permissionMode=v,await this.persistSessionMapping(e).catch(()=>{}),_}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(f.acpSessionId,x):e.activeTriggers.delete(f.acpSessionId);let p=uo(i._meta);if(p?e.activeGroupIds.set(f.acpSessionId,p):e.activeGroupIds.delete(f.acpSessionId),p&&f.cozeGroupId!==p&&(f.cozeGroupId=p,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Rh(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let m=await Ch(c.prompt);try{let v=await f.downstream.sessionPrompt({...c,sessionId:f.acpSessionId,prompt:m});return f.lastActiveAt=Date.now(),v}catch(v){if(v instanceof T&&v.code==="AGENT_APPROVAL_TIMEOUT"){let _=f.pendingPermission;_&&(_.downstream.respondAgentRequest(_.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(_.upstreamId),f.pendingPermission=void 0);let b=f.acpSessionId,I=b?e.activeTriggers.get(b):void 0,A=b?e.activeGroupIds.get(b):void 0;return K.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:l}),await this.synthesizePromptReply(e,f,l,SE,I,A)}throw v}finally{if(e.activeTriggers.delete(f.acpSessionId),e.activeGroupIds.delete(f.acpSessionId),f.pendingPermission=void 0,f.reloadAfterTurn){f.reloadAfterTurn=!1;let v=f.downstream;v&&(f.downstream=void 0,K.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:f.acpSessionId}),v.stop("reload-after-turn").catch(_=>K.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(_)})))}else f.downstream?.isAlive()&&this.armIdleTimer(e,l,f)}}case"session/cancel":{let l=o.sessionId;if(!l)throw new T("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(l);if(e.hasSessionQueue(l)){let f=e.getSessionQueue(l);f.size>0&&(K.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:f.size}),f.dispose(new T("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${l}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,l=c.sessionId,u=c.modeId,f=uo(i._meta);if(!l)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Jt(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(!Sn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${dl(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(l)??await this.ensureRuntime(e,l);if(x.permissionMode===u)return{};let p=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(m){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),m}else K.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:l,modeId:u});return{}}default:throw new T("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[l,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:l,runtime:u,oldMode:u.permissionMode});if(o.length===0)return K.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};K.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let l of o)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let l of o){let u=l.runtime.downstream,f=l.runtime.acpSessionId;u?.isAlive()&&f&&c.push({downstream:u,acpSessionId:f,oldMode:l.oldMode,runtime:l.runtime})}for(let l of c)try{await l.downstream.setSessionMode({sessionId:l.acpSessionId,modeId:i})}catch(u){for(let f of o)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r){let i=e.sessions.get(r);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Jt(e)&&(e.framework==="hermes"?c.permissionMode=e.deployType==="cloud"?i0:s0:c.permissionMode=e.framework==="claude-code"?pl:sh),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(ft.GEN_MODEL_TOKEN,i,IE);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($i(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,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=o&&Date.now()-u<c)throw new T("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${l} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let f;try{f=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=l+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(K.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),K.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){K.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw K.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),Jt(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){K.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,r,i){if($i(i),this.isRuntimeBusy(e,i)){K.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){K.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}K.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>K.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let l=e.activeTriggers.get(r.acpSessionId);l&&(c.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Dr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,l){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),l&&(u.cozeGroupId=l),await this.upstream.send(Dr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>K.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){K.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){K.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(CE(r)){K.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=r.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&Jt(e)){let p=l.currentModeId;Sn(e.framework,p)&&c.permissionMode!==p?(c.permissionMode=p,this.persistSessionMapping(e).catch(m=>K.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(m)}))):typeof p=="string"&&!Sn(e.framework,p)&&K.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:p})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Dr("session/update",{...r,sessionId:o,_meta:u})).catch(p=>K.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}handleAgentRequest(e,r,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,r,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,i);return}K.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:Z.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},l=await Sh(c,o);r.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await Ih(c,o);r.respondAgentRequest(i.id,l)}}catch(o){K.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,ji(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let p=u?e.activeGroupIds.get(u):void 0;p&&(x.cozeGroupId=p);let m=u?this.reverseSessionId(e,u):void 0,v=m?e.sessions.get(m):void 0;v&&(v.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let _={...c,...m?{sessionId:m}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:m}),K.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:m,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(b=>({optionId:b.optionId,kind:b.kind,name:b.name}))}),this.upstream.send(Gi(o,"session/request_permission",_)).catch(b=>{this.pendingUpstream.delete(o),K.error("forward permission request failed",{agentId:e.agentId,err:String(b)}),r.respondAgentRequestError(i.id,{code:Z.INTERNAL_ERROR,message:`upstream send failed: ${String(b)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(K.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&TE(e.result,o),K.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new _o(e.error)):i.value.resolve(e.result);return}K.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),l=e.get(c);if(l)return K.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:l,key:c}}}sendRequest(e,r,i=bE){let o=this.upstreamIds.next(e);return new Promise((c,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),l(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:l,timer:u}),this.upstream.send(Gi(o,e,r)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),l(f)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Jt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await si(e.agentId,r,this.paths)}catch(r){K.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(vn(e,{code:r,message:i,data:{bridgeVersion:Ot}}))}};function AE(){return yE(16).toString("hex")}function TE(t,e){if(!t||typeof t!="object"){K.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){K.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){K.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&K.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var kE=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function CE(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let i=r;if(i.type!=="text"||typeof i.text!="string")return!1;let{text:o}=i;return kE.some(c=>o.startsWith(c))}Ut();te();Ce();import{randomBytes as RE}from"node:crypto";import{createServer as PE}from"node:http";var DE=1e6,Ph=H("ipc"),Oo=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=RE(32).toString("hex");let e=PE((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(),Ph.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 lt(this.paths.portFile,String(this.port)),await lt(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Yi(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Yi(r,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await OE(e)}catch(u){Yi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);Yi(r,200,u??{ok:!0})}catch(u){Ph.error("IPC handler failed",{key:o,err:String(u)}),Yi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Yi(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function OE(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>DE)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 eS=zt(Tx(),1),tS=zt(Go(),1),nS=zt(Ur(),1),rS=zt(Cl(),1),iS=zt(Dl(),1),sS=zt(Fl(),1),Mx=zt(Ko(),1),oS=zt(Nx(),1);var Bx=Mx.default;We();te();var{FWS:ES}=Vx(),De=H("upstream.frontier"),Zx="application/json",Yx="none",vS=15e3;function SS(t){class e extends Bx{constructor(i){super(i,Kf,{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(Cd("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");De.debug("WS raw frame out",{bytes:c.byteLength,headHex:l})}catch(c){De.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var os=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:$f,...bn(this.opts.ppeOverride)},r=SS(e),i=Jf(this.opts.urlOverride),o={url:i,ws:r,fpID:Wf,aID:fo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Zx,force:!0},payloadEncoding:{encoding:Yx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new ES(o),l=!1,u=null,f,x,p=new Promise((_,b)=>{f=_,x=b}),m=_=>{l||(l=!0,u&&(clearTimeout(u),u=null),_?x(_):f())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;De.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&m();for(let b of this.connectHandlers)Promise.resolve(b({initial:_})).catch(I=>De.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=_=>{this.opened=!1,De.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{De.warn("frontier error",{code:_.code,msg:_.message}),m(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let v=this.opts.openTimeoutMs??vS;u=setTimeout(()=>{m(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await c.connect();try{await p}catch(_){try{c.close(1e3,"open failed")}catch(b){De.warn("fws close during start failure threw (ignored)",{err:String(b)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){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;Xx(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:Zx,payloadEncoding:Yx})}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=TS(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(l){De.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let c=o;Xx(c)||De.info("frontier frame in",{logid:AS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:IS(i)}),Promise.resolve(this.handler(o)).catch(l=>De.warn("frontier frame handler threw",{err:String(l)}))}};function Xx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Qx=2e3;function IS(t){return t.length<=Qx?t:`${t.slice(0,Qx)}...<truncated, total ${t.length} chars>`}function AS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function TS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}We();te();var Gl=H("skill-publish"),kS="/api/marketplace/product/skill/publish_with_assets",CS=15e4;async function ep(t,e={}){let i=`${kr(Cr(e.handshakeBase))}${kS}`,o=e.timeoutMs??CS,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let l={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...bn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);Gl.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}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${_.slice(0,200)}`)}let m=await x.json();if(Gl.info("skill publish response",{logid:p,httpStatus:x.status,code:m.code,msg:m.msg,dataSkillId:m.data?.skill_id??"",dataVersion:m.data?.version??""}),m.code!==void 0&&m.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${m.code} msg=${m.msg??"-"} logid=${p}`);let v={};return m.data?.skill_id!==void 0&&m.data.skill_id!==""&&(v.skillId=String(m.data.skill_id)),m.data?.version&&(v.version=m.data.version),Gl.info("skill publish ok",{logid:p,skillId:v.skillId??"",version:v.version??""}),v}catch(x){throw x instanceof T?x:x.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(f)}}te();var ql=H("upstream.switchable"),ta=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;ql.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 ql.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>ql.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 jl=H("upstream"),Kr=class{handler=null;async start(){jl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){jl.info("NoopUpstream stopped",{reason:e})}async send(e){jl.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};We();te();Ut();te();Ce();import{promises as RS}from"node:fs";var tp=H("pat-token-store");async function na(t=J()){try{let r=(await RS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(tp.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"&&tp.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function as(t,e=J()){if(!t)throw new Error("writePatToken: empty patToken");await lt(e.patTokenFile,t,{mode:384})}Ce();Ce();import{promises as ra}from"node:fs";import{join as PS}from"node:path";function DS(t,e){return`#!/bin/sh
105
107
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
106
- `}function yv(t,e){return`@echo off\r
108
+ `}function OS(t,e){return`@echo off\r
107
109
  "${e}" "${t}" %*\r
108
- `}async function Hx(t,e=ee()){let n=e.binDir;await Zo.mkdir(n,{recursive:!0});let i=wv(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),s=process.execPath,c=process.platform==="win32"?yv(t,s):_v(t,s);return await Zo.readFile(i,"utf8").catch(()=>null)===c||(await Zo.writeFile(i,c,"utf8"),process.platform!=="win32"&&await Zo.chmod(i,493)),n}ne();Le();import{execSync as jx}from"node:child_process";import{readFileSync as Wx,unlinkSync as Ev}from"node:fs";import{mkdir as bv,open as vv,readFile as Kx,unlink as zd,writeFile as Sv}from"node:fs/promises";import{dirname as Iv}from"node:path";var Av=H("single-instance"),kv=t=>new Promise(e=>setTimeout(e,t)),Xo=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??ee().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Ui(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&&Av.warn("removing stale pid file",{stalePid:i}),await Sv(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 Kx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await zd(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let n=await Kx(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 bv(Iv(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let s;try{s=await vv(n,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let d=await this.readPidFrom(n);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await kv(this.claimLockIntervalMs);continue}await zd(n).catch(()=>{});continue}try{return await s.writeFile(String(this.selfPid)),await e()}finally{await s.close().catch(()=>{}),await zd(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=Wx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Nr)||n.includes("lib/index.js"))}catch{}try{let n=jx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Nr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=jx(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let s=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return s.includes("node")||s.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Wx(this.pidFile,"utf8").trim()===String(this.selfPid)&&Ev(this.pidFile)}catch{}})}};Qo();ne();var er=H("daemon.upstream-watchdog"),Nv=12e4,Mv=9e5,Bv=3e4;function Gd(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ea=class{constructor(e){this.opts=e;this.softMs=e.softMs??Gd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",Nv),this.hardMs=e.hardMs??Gd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",Mv),this.intervalMs=e.intervalMs??Gd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",Bv),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),er.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&er.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&er.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,er.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){er.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,er.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>er.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var W=H("daemon");async function Yx(){let t=ee();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){bl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>$e(P,t).logs,listAgentIds:()=>xs(t)});try{let{writeFileSync:P}=await import("node:fs");P(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
110
+ `}async function np(t,e=J()){let r=e.binDir;await ra.mkdir(r,{recursive:!0});let i=PS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?OS(t,o):DS(t,o);return await ra.readFile(i,"utf8").catch(()=>null)===c||(await ra.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ra.chmod(i,493)),r}te();Ce();import{execSync as rp}from"node:child_process";import{readFileSync as ip,unlinkSync as LS}from"node:fs";import{mkdir as NS,open as MS,readFile as sp,unlink as Wl,writeFile as BS}from"node:fs/promises";import{dirname as FS}from"node:path";var zS=H("single-instance"),US=t=>new Promise(e=>setTimeout(e,t)),ia=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??J().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Wi(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&zS.warn("removing stale pid file",{stalePid:i}),await BS(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 sp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Wl(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 sp(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 NS(FS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await MS(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=await this.readPidFrom(r);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await US(this.claimLockIntervalMs);continue}await Wl(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Wl(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=ip(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Nr)||r.includes("lib/index.js"))}catch{}try{let r=rp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Nr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=rp(`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{ip(this.pidFile,"utf8").trim()===String(this.selfPid)&&LS(this.pidFile)}catch{}})}};sa();te();var Qn=H("daemon.upstream-watchdog"),VS=12e4,JS=9e5,ZS=3e4;function $l(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var oa=class{constructor(e){this.opts=e;this.softMs=e.softMs??$l("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",VS),this.hardMs=e.hardMs??$l("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",JS),this.intervalMs=e.intervalMs??$l("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",ZS),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),Qn.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&Qn.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&Qn.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,Qn.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){Qn.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:r,hardMs:this.hardMs}),this.opts.onFatal(r);return}r>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,Qn.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>Qn.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var q=H("daemon");async function cp(){let t=J();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Td({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>Be(C,t).logs,listAgentIds:()=>ms(t)});try{let{writeFileSync:C}=await import("node:fs");C(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
109
111
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
110
112
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
111
- `)}catch{}}let e=new Xo({processTitle:Nr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Io(),s=i??{};us({pid:process.pid}),W.info(i?"loaded bridge config":"initialized bridge config");let c=new Yo(new Kr),d=null,u=new Ao({upstream:c,paths:t,bridgeConfig:s,sessionSpawner:async(P,U,K,te)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,U,K,te)}}),h=new bo({paths:t,config:s,registry:u});d=h;let x,g,w=null,S={},y,v=null,I=null,A=null,R=new kn;function D(P,U){return R.enqueue(()=>C(P,U))}function E(){I||(I=new ea({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:P=>{if(process.env[rs]==="1"){W.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}W.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),I.start()}async function C(P,U){let K=P,te=K?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Ze=Li(K.env),xe=K.handshake_url,pe=K.frontier_url,St=Vx(K.env,xe,pe);if(A=K,!U?.force&&x===te&&g===St){let _e=await Fv(t);return u.agents.size===0&&_e?(W.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),na(t,h).catch(Ae=>W.warn("connect-noop auto-revive error (ignored)",{err:String(Ae)}))):W.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let pt=!!x&&x!==te,tn=g!==void 0&&g!==St,Ut=pt||tn,nn=await Uc({privatecode:te,...xe?{endpoint:xe}:{},ppeOverride:Ze});if(Ut){W.warn("connect config switched, resetting agents",{pcChanged:pt,envChanged:tn,previousPc:x?ta(x):"",nextPc:ta(te)});for(let _e of[...u.agents.values()])await _e.dispose("connect config switch").catch(()=>{}),u.agents.delete(_e.agentId);u.disconnectedAgents.size>0&&(W.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"connect switch").catch(()=>{})}w=nn.deviceId,us({deviceId:w,pid:process.pid}),ud({patToken:te,env:K.env}).catch(_e=>W.warn("coze-cli setup error (ignored)",{err:String(_e)}));let Zr=new ts({handshake:nn,privatecode:te,...pe?{urlOverride:pe}:{},ppeOverride:Ze,getPatTokenForAgent:_e=>u.agents.get(_e)?.patToken});return await c.swap(Zr,"connect"),x=te,g=St,S=Ze,y=xe,K.mock_scenario!==void 0&&(u.setMockScenario(K.mock_scenario),W.info("mock scenario set",{scenario:K.mock_scenario})),v||(v=new Mi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(_e=>W.warn("detailSync.retryPending failed (ignored)",{err:String(_e)})),onAuthFailures:Y})),v.start(),E(),Ut&&na(t,h).catch(_e=>W.warn("post-connect-switch auto-revive error (ignored)",{err:String(_e)})),ns(te,t).catch(_e=>W.warn("writePatToken after /connect failed (ignored)",{err:String(_e)})),W.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 O={},F=new uo({agents:u.agents,publishSkillToMarketplace:async P=>{let U=u.agents.get(P.agentId)?.patToken??x;if(!U)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Gx({patToken:U,zip:P.zip,...P.skillId?{skillId:P.skillId}:{},skillName:P.skillName,...P.description?{description:P.description}:{},agentId:P.agentId,...P.accountId?{accountId:P.accountId}:{}},{handshakeBase:y,ppeOverride:S})},disposeAndMarkDisconnected:async(P,U)=>{let K=u.agents.get(P);if(K){await h.cleanupOpenclawSessionProviders(K).catch(Ze=>W.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(Ze)}));let te=!0;try{await K.dispose(`disconnect: ${U}`)}catch(Ze){te=!1,W.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(Ze)}),K.status="error"}te&&(K.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,U)=>{let K=u.agents.get(P);K&&(await h.cleanupOpenclawSessionProviders(K).catch(te=>W.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(te)})),await K.dispose(`delete: ${U}`).catch(te=>W.warn("dispose during delete failed (ignored)",{agentId:P,err:String(te)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(P)},cleanupOpenclawProviders:async(P,U)=>{await h.cleanupOpenclawSessionProviders(P,U)},openclawRepair:async(P,U)=>{await h.openclawRepair(P,U)},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>F.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>F.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>F.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>F.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>F.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>F.getFileContent(P.params)),u.registerExtension("_agent/update",P=>F.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>F.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>F.switchModel(P.params)),u.registerExtension("_agent/reset",P=>F.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>F.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>F.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>F.upgradeBridge(P.params));let B=new ms({paths:t,handlers:F,agentManager:h,sendDetail:P=>u.sendRequest("_agent/detail",P)});O.ref=B;let Y=async P=>{await Promise.allSettled(P.map(async U=>{try{await F.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),W.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(K){W.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(K)})}}))};c.onConnect(({initial:P})=>{W.info("frontier upstream connected, triggering detail sync",{initial:P}),B.syncAll(P?"initial-connect":"reconnect").catch(U=>W.warn("detail sync top-level error (ignored)",{err:String(U)}))});let V=new ko({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let P=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[rs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:s.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let U=P,K=U?.privatecode,te=U?.pairing_code;if(!K||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ze=Li(U.env),xe=U.handshake_url,pe=U.frontier_url,St=Vx(U.env,xe,pe),pt=!!x&&x!==K,tn=g!==void 0&&g!==St,Ut=pt||tn,nn=await Uc({privatecode:K,...xe?{endpoint:xe}:{},ppeOverride:Ze});if(Ut){W.warn("pair config switched, resetting agents",{pcChanged:pt,envChanged:tn,previousPc:x?ta(x):"",nextPc:ta(K),previousEnvKey:g??"",nextEnvKey:St});for(let Ae of[...u.agents.values()])await Ae.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ae.agentId);u.disconnectedAgents.size>0&&(W.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"pair switch").catch(()=>{})}w=nn.deviceId,us({deviceId:w,pid:process.pid}),ud({patToken:K,env:U.env}).catch(Ae=>W.warn("coze-cli setup error (ignored)",{err:String(Ae)}));let Zr=new ts({handshake:nn,privatecode:K,...pe?{urlOverride:pe}:{},ppeOverride:Ze,getPatTokenForAgent:Ae=>u.agents.get(Ae)?.patToken});await c.swap(Zr,"pair");try{let Ae=new Vn;s.frameworksCache=await Ae.detectAll(),await ji(s),W.info("frameworks_cache refreshed before pair",{detected:Object.keys(s.frameworksCache)})}catch(Ae){W.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ae)})}let _e=Object.keys(s.frameworksCache??{});try{let Ae=await u.sendRequest("_agent/pair",{pairCode:te,patToken:K,frameworks:_e,_meta:{cozeDeviceId:w}});W.info("_agent/pair ok",{pairResult:Ae}),x=K,g=St,S=Ze,y=xe,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),W.info("mock scenario set",{scenario:U.mock_scenario})),ns(K,t).catch(Oe=>W.warn("writePatToken after /pair failed (ignored)",{err:String(Oe)})),v||(v=new Mi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(Oe=>W.warn("detailSync.retryPending failed (ignored)",{err:String(Oe)})),onAuthFailures:Y})),v.start(),E(),Ut&&na(t,h).catch(Oe=>W.warn("post-pair-switch auto-revive error (ignored)",{err:String(Oe)}));let tr;return U.agent_id&&(tr=await Uv(U.agent_id,t,h,Oe=>u.sendRequest("_agent/detail",Oe),K).catch(Oe=>(W.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Oe)}),{ok:!1,agentId:U.agent_id??"",note:String(Oe)}))),{ok:!0,note:"paired with cloud",...tr?{agent:tr}:{}}}catch(Ae){return W.error("_agent/pair failed",{err:String(Ae)}),{ok:!1,note:`pair failed: ${String(Ae)}`}}}},{method:"POST",path:"/connect",handler:P=>D(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let U=P;return{ok:!0,result:await h.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async P=>{let U=P;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let K=U;return await(K.groupFile?nh:th)(K,{core:u,patToken:x,handshakeBase:y,ppeOverride:S})}catch(K){if(K instanceof k)return{ok:!1,code:K.code,message:K.message};throw K}}},{method:"POST",path:"/reload",handler:async P=>{let U=P?.agent_id,K=await u.reloadAgents(U);return W.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:K}),{ok:!0,recycled:K}}},{method:"POST",path:"/shutdown",handler:async()=>(W.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:X}=await V.start();try{await Hx(t.libEntry,t)}catch(P){W.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),Gv({paths:t,core:u,agentManager:h,detectAll:async()=>(s.frameworksCache=await new Vn().detectAll(),await ji(s),s.frameworksCache)}).catch(P=>W.warn("startup warmup error (ignored)",{err:String(P)})),Dl().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(on(),Cl));for(let U of["claude-code","codex"]){let K=await P(U);K&&W.info("acp wrapper version",{framework:U,version:K})}}).catch(P=>W.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let se=null,oe={port:re,token:X,core:u,ipc:V,shutdown(P){return se||(W.info("daemon shutdown",{reason:P}),se=(async()=>{v?.stop(),I?.stop(),await u.stop(P),await V.stop(),await e.release()})(),se)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{oe.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>S0()),process.on("unhandledRejection",P=>{W.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{W.error("uncaughtException (will exit, supervisor will restart)",{message:P.message,stack:P.stack,name:P.name});try{process.stderr.write(`FATAL uncaughtException: ${P.stack??P.message}
112
- `)}catch{}process.exit(1)}),W.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(s.frameworksCache??{}),libVersion:s.libVersion??"dev"}),Hv({cliSpawned:process.env[rs]==="1",readPatToken:()=>Jo(t),connect:D}).catch(P=>W.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),oe}async function Fv(t){return xs(t).length>0}function ta(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Vx(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function zv(t,e){let n=xs(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(dn(),gs));for(let c of n){await s(c,t).catch(d=>W.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),W.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),W.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){W.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function Uv(t,e,n,i,s){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(dn(),gs)),d=await c(t,e);if(d){if(d.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);W.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let g=Jx(d),w={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...s?{patToken:s}:{},...g?{_meta:g}:{}};return await n.createAgent(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}W.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}:{},...s?{patToken:s}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await n.createAgent(h);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function Gv(t){let e=t.logger??W;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 zv(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await na(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await qv(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function na(t,e){let{readdir:n}=await import("node:fs/promises"),i;try{i=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(dn(),gs));W.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let h;try{h=await s(u,t)}catch(x){W.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){W.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){W.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{W.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=Jx(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){W.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),d+=1}}return W.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function qv(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let s of n)try{(await u0(s,t)).status==="refreshed"&&(i+=1)}catch(c){W.warn("refresh builtin skills failed (skipping agent)",{agentId:s,err:String(c)})}return i>0&&W.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function Hv(t){let e=t.logger??W;if(t.cliSpawned)return"skipped-cli";let n=await t.readPatToken();return n?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:n}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function Jx(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Qo();Le();import{readFile as Zx}from"node:fs/promises";var en=class{paths;constructor(e){this.paths=e??ee()}async probe(e=1e3){let n=await ra(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:Wv(i)}}}async request(e){let n=await ra(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let i=n.body!==void 0,s={Authorization:`Bearer ${e.token}`};i&&(s["content-type"]="application/json");let c=new AbortController,d=setTimeout(()=>c.abort(),n.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:s,body:i?JSON.stringify(n.body):void 0,signal:c.signal}),h=await u.text();return{status:u.status,body:jv(h)}}finally{clearTimeout(d)}}};async function ra(t){try{let[e,n]=await Promise.all([Zx(t.portFile,"utf8"),Zx(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),s=n.trim();return!Number.isFinite(i)||i<=0||!s?null:{port:i,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}function jv(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Wv(t){return t instanceof Error?t.message:String(t)}Vt();ne();sr();import{spawn as Kv}from"node:child_process";import{userInfo as Qx}from"node:os";var qd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",$v=new Set(["bash","zsh","sh","dash","ksh"]),Xx=Ke("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),Vv=2e3;function Yv(t,e=qd){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let s=t.slice(n+e.length,i),c={};for(let d of s.split(`
113
- `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function Jv(){let t=(process.env.SHELL??"").trim()||(Qx().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return $v.has(e)?t:null}function Zv(t){return new Promise(e=>{let n=`printf '%s' '${qd}'; env; printf '%s' '${qd}'`,i;try{i=Kv(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Qx().homedir}})}catch{e(null);return}let s="",c=!1,d=g=>{try{i.pid&&process.kill(-i.pid,g)}catch{}},u=g=>{c||(c=!0,clearTimeout(h),clearTimeout(x),e(g))};i.stdout?.on("data",g=>{s+=g.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(s.length>0?s:null));let h=setTimeout(()=>d("SIGTERM"),Xx),x=setTimeout(()=>{d("SIGKILL"),u(s.length>0?s:null)},Xx+Vv)})}async function Hd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=Jv();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??Zv)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let s=Yv(i);return s==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:s}}Le();function Cn(t,...e){let n=[],i;for(let s=0;s<t.length;s++){let c=t[s],d=!1;for(let u of e){if(c===u){i=t[s+1],s+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||n.push(c)}return{value:i,rest:n}}on();import{chmod as Xv,copyFile as ep,mkdir as np,readFile as ss,rename as tp,rm as Kd,stat as $d,writeFile as Qv}from"node:fs/promises";import{homedir as oD}from"node:os";import{dirname as eS,join as zt,resolve as Vd,sep as is}from"node:path";import{fileURLToPath as tS}from"node:url";Vt();ne();Le();var $r=H("dist-install");function rp(){return{darwin:{arm64:"@zed-industries/codex-acp-darwin-arm64",x64:"@zed-industries/codex-acp-darwin-x64"},linux:{arm64:"@zed-industries/codex-acp-linux-arm64",x64:"@zed-industries/codex-acp-linux-x64"},win32:{arm64:"@zed-industries/codex-acp-win32-arm64",x64:"@zed-industries/codex-acp-win32-x64"}}[process.platform]?.[process.arch]}function nS(){return process.platform==="win32"?"codex-acp.exe":"codex-acp"}function rS(t){let e=tS(t),n=eS(e),i=`${is}src${is}`;if(n.includes(i)||n.endsWith(`${is}src${is}cli`))return null;let s=Vd(n,"index.js"),c=Vd(n,"..","package.json");return{dist:s,pkgJson:c}}async function Yd(t={}){let e=t.paths??ee(),n=rS(import.meta.url),i=t.sourceDist??n?.dist,s=t.sourcePackageJson??n?.pkgJson;if(!i||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,d;try{let v=JSON.parse(await ss(s,"utf8"));c=v.version??"unknown",d=v.dependencies??{}}catch(v){return $r.warn("cannot read source package.json,skip dist install",{err:String(v)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(v)}`}}let u=fs.map(v=>({name:v,spec:d[v]??"latest"})),h=u.map(({name:v,spec:I})=>`${v}@${I}`),x=await Io(e.configFile)??{},g=x.libVersion,w=await ss(e.libEntry).then(()=>!0).catch(()=>!1),S=g===c,y=await ip(e,u);if(S&&w&&y)return{kind:"already-current",libVersion:c};if(!S||!w){await np(e.libDir,{recursive:!0}),await ep(i,e.libEntry),await ep(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=Vd(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
114
- `;await ss(v,"utf8").catch(()=>null)!==I&&await Qv(v,I)}return y||(t.installWrappers?await t.installWrappers(e,h):await sS(e,h,u)),x.libVersion=c,await ji(x,e.configFile),$r.info("dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:c}),S&&w?{kind:"already-current",libVersion:c}:g?{kind:"version-changed",fromVersion:g,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function ip(t,e){for(let n of e){let i=zt(t.libDir,"node_modules",...n.name.split("/"),"package.json"),s;try{s=JSON.parse(await ss(i,"utf8"))}catch(d){return $r.warn("wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(d)}),!1}let c=s.version;if(!c)return $r.warn("wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!iS(c,n.spec))return $r.warn("wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:c,expected:n.spec}),!1}return!!await sp(zt(t.libDir,"node_modules"))}function iS(t,e){let n=jd(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=jd(i.slice(1));if(!c)return!0;if(Wd(n,c)<0)return!1;let d=c[0]>0?[c[0]+1,0,0]:c[1]>0?[0,c[1]+1,0]:[0,0,c[2]+1];return Wd(n,d)<0}let s=jd(i);return s?Wd(n,s)===0:!0}function jd(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Wd(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 sS(t,e,n){await cS(t.installLock,async()=>{if(await ip(t,n))return;let i=Math.random().toString(36).slice(2,10),s=`${t.libDir}${is}.staging-${process.pid}-${i}`,c=zt(s,"node_modules"),d=zt(t.libDir,"node_modules");try{await np(s,{recursive:!0}),await oS(e,s),await aS(c);let u=`${d}.trash-${i}`;await tp(d,u).catch(()=>{}),await tp(c,d),await Kd(u,{recursive:!0,force:!0}).catch(()=>{}),$r.info("wrapper closure installed",{liveNm:d,specs:e})}finally{await Kd(s,{recursive:!0,force:!0}).catch(()=>{})}})}function oS(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,s)=>{let c=nt("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";c.stderr?.on("data",h=>{d.length<8192&&(d+=h.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",h=>{clearTimeout(u),s(new Error(`spawn npm failed: ${String(h)}`))}),c.once("close",h=>{clearTimeout(u),h===0?i():s(new Error(`npm install \u9000\u51FA\u7801 ${h}: ${d.trim().slice(0,2e3)}`))})})}async function aS(t){for(let e of fs){let n=zt(t,...e.split("/")),i=JSON.parse(await ss(zt(n,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let s=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!s)throw new Error(`${e}: package.json \u7F3A bin`);let c=zt(t,".bin",s),d=await $d(c);process.platform!=="win32"&&!(d.mode&73)&&await Xv(c,d.mode|73).catch(()=>{})}if(!await sp(t)){let e=rp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex-acp binary \u7F3A\u5931`)}}async function sp(t){let e=rp();if(!e)return!0;let n=zt(t,...e.split("/")),i=zt(n,"package.json"),s=zt(n,"bin",nS()),[c,d]=await Promise.all([$d(i).then(u=>u.isFile()).catch(()=>!1),$d(s).then(u=>u.isFile()).catch(()=>!1)]);return c&&d}async function cS(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let s=0;s<60&&!i;s++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await Kd(t,{force:!0}).catch(()=>{})}}Ia();ne();Le();import{closeSync as ap,fstatSync as cp,openSync as dp,readFileSync as dS,readSync as lS,readdirSync as uS,statSync as fS}from"node:fs";import{join as ia}from"node:path";var hS=new Set(["debug","info","warn","error"]);function lp(t){let e=t,n=Cn(e,"--agent-id");e=n.rest;let i=Cn(e,"--date");e=i.rest;let s=Cn(e,"-n","--lines");e=s.rest;let c=Cn(e,"--level");e=c.rest;let d=Cn(e,"--grep");e=d.rest;let u=s.value===void 0?200:Number(s.value),h=Number.isInteger(u)&&u>=0?u:200,x=c.value&&hS.has(c.value)?c.value:void 0,g={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(g.agentId=n.value),i.value&&(g.date=i.value),x&&(g.level=x),d.value&&(g.grep=d.value),g}function xS(t,e){return t.agentId?ia($e(t.agentId,e).logs,or("agent",t.date)):ia(e.bridgeLogsDir,or("bridge",t.date))}function pS(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function gS(t,e){let n;try{n=uS(t)}catch{return[]}let i=[];for(let s of n){let c=Sa(s,e);if(!c)continue;let d=0;try{d=fS(ia(t,s)).size}catch{}i.push({file:ia(t,s),date:c,size:d})}return i.sort((s,c)=>c.date.localeCompare(s.date)),i}function up(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"&&!Il(n,e.level))return!1}return!0}var op={debug:"90",info:"36",warn:"33",error:"31"},mS=new Set(["ts","level","module","msg"]);function wS(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function fp(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=wS(n.ts),s=typeof n.level=="string"?n.level:"",c=s.toUpperCase().padEnd(5);e.color&&op[s]&&(c=`\x1B[${op[s]}m${c}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",h=Object.entries(n).filter(([x])=>!mS.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${d} ${u}${h}`}function _S(t,e,n){let c=dS(t,"utf8").split(`
115
- `).filter(d=>d.length>0).filter(d=>up(d,{level:e.level,grep:e.grep}));for(let d of pS(c,e.lines))process.stdout.write(`${fp(d,{raw:e.raw,color:n})}
116
- `)}async function hp(t,e){let n=e.paths??ee(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?$e(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=gS(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
117
- `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
118
- `);return 0}let s=t.date??Dn(new Date),c=xS({agentId:t.agentId,date:s},n);try{_S(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
113
+ `)}catch{}}let e=new ia({processTitle:Nr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Po(),o=i??{};ps({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let c=new ta(new Kr),l=null,u=new Do({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(C,U,G,ee)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(C,U,G,ee)}}),f=new ko({paths:t,config:o,registry:u});l=f;let x,p,m=null,v={},_,b=null,I=null,A=null,k=new In;function P(C,U){return k.enqueue(()=>R(C,U))}function y(){I||(I=new oa({isConnected:()=>c.isConnected()&&!(b?.isLivenessLost()??!1),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:C=>{if(process.env[cs]==="1"){q.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}q.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),I.start()}async function R(C,U){let G=C,ee=G?.privatecode;if(!ee)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let Ve=Bi(G.env),xe=G.handshake_url,pe=G.frontier_url,It=ap(G.env,xe,pe);if(A=G,!U?.force&&x===ee&&p===It){let we=await YS(t);return u.agents.size===0&&we?(q.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ca(t,f).catch(Ae=>q.warn("connect-noop auto-revive error (ignored)",{err:String(Ae)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let gt=!!x&&x!==ee,tn=p!==void 0&&p!==It,Ft=gt||tn,nn=await Vc({privatecode:ee,...xe?{endpoint:xe}:{},ppeOverride:Ve});if(Ft){q.warn("connect config switched, resetting agents",{pcChanged:gt,envChanged:tn,previousPc:x?aa(x):"",nextPc:aa(ee)});for(let we of[...u.agents.values()])await we.dispose("connect config switch").catch(()=>{}),u.agents.delete(we.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"connect switch").catch(()=>{})}m=nn.deviceId,ps({deviceId:m,pid:process.pid}),ml({patToken:ee,env:G.env}).catch(we=>q.warn("coze-cli setup error (ignored)",{err:String(we)}));let Yr=new os({handshake:nn,privatecode:ee,...pe?{urlOverride:pe}:{},ppeOverride:Ve,getPatTokenForAgent:we=>u.agents.get(we)?.patToken});return await c.swap(Yr,"connect"),x=ee,p=It,v=Ve,_=xe,G.mock_scenario!==void 0&&(u.setMockScenario(G.mock_scenario),q.info("mock scenario set",{scenario:G.mock_scenario})),b||(b=new Hi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>M.retryPending().catch(we=>q.warn("detailSync.retryPending failed (ignored)",{err:String(we)})),onAuthFailures:V})),b.start(),y(),Ft&&ca(t,f).catch(we=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(we)})),as(ee,t).catch(we=>q.warn("writePatToken after /connect failed (ignored)",{err:String(we)})),q.info("/connect: WS established",{deviceId:m}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async C=>f.createAgent(C.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},F=new go({agents:u.agents,paths:t,publishSkillToMarketplace:async C=>{let U=u.agents.get(C.agentId)?.patToken??x;if(!U)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return ep({patToken:U,zip:C.zip,...C.skillId?{skillId:C.skillId}:{},skillName:C.skillName,...C.description?{description:C.description}:{},agentId:C.agentId,...C.accountId?{accountId:C.accountId}:{}},{handshakeBase:_,ppeOverride:v})},disposeAndMarkDisconnected:async(C,U)=>{let G=u.agents.get(C);if(G){await f.cleanupOpenclawSessionProviders(G).catch(Ve=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(Ve)})),G.framework==="hermes"&&G.deployType==="cloud"&&await el(C,t).catch(Ve=>q.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(Ve)}));let ee=!0;try{await G.dispose(`disconnect: ${U}`)}catch(Ve){ee=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(Ve)}),G.status="error"}ee&&(G.status="disconnected",u.unregister(C),u.disconnectedAgents.add(C))}else u.disconnectedAgents.add(C)},disposeForDelete:async(C,U)=>{let G=u.agents.get(C);G&&(await f.cleanupOpenclawSessionProviders(G).catch(ee=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(ee)})),G.framework==="hermes"&&G.deployType==="cloud"&&await el(C,t).catch(ee=>q.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(ee)})),await G.dispose(`delete: ${U}`).catch(ee=>q.warn("dispose during delete failed (ignored)",{agentId:C,err:String(ee)})),u.unregister(C)),u.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(C)},cleanupOpenclawProviders:async C=>{await f.cleanupOpenclawSessionProviders(C)},openclawRepair:async(C,U)=>{await f.openclawRepair(C,U)},hermesReset:async(C,U)=>{let G=await Ee(C).catch(()=>null);!G||G.framework!=="hermes"||G.deployType!=="cloud"||await o0({paths:t,agentId:C,modelInfo:G.modelInfo,cozeEnv:U,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:C=>u.hasPendingPermissionFor(C)});u.registerExtension("_agent/listSkills",C=>F.listSkills(C.params)),u.registerExtension("_agent/addSkills",C=>F.addSkills(C.params)),u.registerExtension("_agent/removeSkills",C=>F.removeSkills(C.params)),u.registerExtension("_agent/publishSkill",C=>F.publishSkill(C.params)),u.registerExtension("_agent/getFileTree",C=>F.getFileTree(C.params)),u.registerExtension("_agent/getFileContent",C=>F.getFileContent(C.params)),u.registerExtension("_agent/update",C=>F.updateAgent(C.params)),u.registerExtension("_agent/disconnect",C=>F.disconnectAgent(C.params)),u.registerExtension("_agent/switchModel",C=>F.switchModel(C.params)),u.registerExtension("_agent/reset",C=>F.resetAgent(C.params)),u.registerExtension("_agent/repair",C=>F.repairAgent(C.params)),u.registerExtension("_agent/delete",C=>F.deleteAgent(C.params)),u.registerExtension("_agent/upgrade",C=>F.upgradeBridge(C.params));let M=new ys({paths:t,handlers:F,agentManager:f,sendDetail:C=>u.sendRequest("_agent/detail",C)});O.ref=M;let V=async C=>{await Promise.allSettled(C.map(async U=>{try{await F.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),q.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(G){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(G)})}}))};c.onConnect(({initial:C})=>{q.info("frontier upstream connected, triggering detail sync",{initial:C}),M.syncAll(C?"initial-connect":"reconnect").catch(U=>q.warn("detail sync top-level error (ignored)",{err:String(U)}))});let $=new Oo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=u.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[cs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:m??"",frameworksCache:o.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let U=C,G=U?.privatecode,ee=U?.pairing_code;if(!G||!ee)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ve=Bi(U.env),xe=U.handshake_url,pe=U.frontier_url,It=ap(U.env,xe,pe),gt=!!x&&x!==G,tn=p!==void 0&&p!==It,Ft=gt||tn,nn=await Vc({privatecode:G,...xe?{endpoint:xe}:{},ppeOverride:Ve});if(Ft){q.warn("pair config switched, resetting agents",{pcChanged:gt,envChanged:tn,previousPc:x?aa(x):"",nextPc:aa(G),previousEnvKey:p??"",nextEnvKey:It});for(let Ae of[...u.agents.values()])await Ae.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ae.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"pair switch").catch(()=>{})}m=nn.deviceId,ps({deviceId:m,pid:process.pid}),ml({patToken:G,env:U.env}).catch(Ae=>q.warn("coze-cli setup error (ignored)",{err:String(Ae)}));let Yr=new os({handshake:nn,privatecode:G,...pe?{urlOverride:pe}:{},ppeOverride:Ve,getPatTokenForAgent:Ae=>u.agents.get(Ae)?.patToken});await c.swap(Yr,"pair");try{let Ae=new $n;o.frameworksCache=await Ae.detectAll(),await Ji(o),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ae){q.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ae)})}let we=Object.keys(o.frameworksCache??{});try{let Ae=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:G,frameworks:we,_meta:{cozeDeviceId:m}});q.info("_agent/pair ok",{pairResult:Ae}),x=G,p=It,v=Ve,_=xe,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),q.info("mock scenario set",{scenario:U.mock_scenario})),as(G,t).catch(Oe=>q.warn("writePatToken after /pair failed (ignored)",{err:String(Oe)})),b||(b=new Hi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>M.retryPending().catch(Oe=>q.warn("detailSync.retryPending failed (ignored)",{err:String(Oe)})),onAuthFailures:V})),b.start(),y(),Ft&&ca(t,f).catch(Oe=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(Oe)}));let er;return U.agent_id&&(er=await QS(U.agent_id,t,f,Oe=>u.sendRequest("_agent/detail",Oe),G).catch(Oe=>(q.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Oe)}),{ok:!1,agentId:U.agent_id??"",note:String(Oe)}))),{ok:!0,note:"paired with cloud",...er?{agent:er}:{}}}catch(Ae){return q.error("_agent/pair failed",{err:String(Ae)}),{ok:!1,note:`pair failed: ${String(Ae)}`}}}},{method:"POST",path:"/connect",handler:C=>P(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let U=C;return{ok:!0,result:await f.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async C=>{let U=C;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new T("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let G=U;return await(G.groupFile?ph:xh)(G,{core:u,patToken:x,handshakeBase:_,ppeOverride:v})}catch(G){if(G instanceof T)return{ok:!1,code:G.code,message:G.message};throw G}}},{method:"POST",path:"/reload",handler:async C=>{let U=C?.agent_id,G=await u.reloadAgents(U);return q.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:G}),{ok:!0,recycled:G}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ne,token:Y}=await $.start();try{await np(t.libEntry,t)}catch(C){q.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await u.start(),e1({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new $n().detectAll(),await Ji(o),o.frameworksCache)}).catch(C=>q.warn("startup warmup error (ignored)",{err:String(C)})),Bd().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(an(),Nd));for(let U of["claude-code","codex"]){let G=await C(U);G&&q.info("acp wrapper version",{framework:U,version:G})}}).catch(C=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let se=null,oe={port:ne,token:Y,core:u,ipc:$,shutdown(C){return se||(q.info("daemon shutdown",{reason:C}),se=(async()=>{b?.stop(),I?.stop(),await u.stop(C),await $.stop(),await e.release()})(),se)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{oe.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>R0()),process.on("unhandledRejection",C=>{q.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{q.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
114
+ `)}catch{}process.exit(1)}),q.info("daemon ready",{port:ne,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),n1({cliSpawned:process.env[cs]==="1",readPatToken:()=>na(t),connect:P}).catch(C=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),oe}async function YS(t){return ms(t).length>0}function aa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function ap(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function XS(t,e){let r=ms(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(Ht(),_s));for(let c of r){await o(c,t).catch(l=>q.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.deletedAt?(e.disconnectedAgents.add(c),q.info("agent marked deleted on startup",{agentId:c,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(c),q.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){q.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function QS(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Ht(),_s)),l=await c(t,e);if(l){if(l.deletedAt)throw new T("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${l.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let p=lp(l),m={agentId:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...o?{patToken:o}:{},...p?{_meta:p}:{}};return await r.createAgent(m),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}q.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new T("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(f);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function e1(t){let e=t.logger??q;try{let r=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(r??{})})}catch(r){e.warn("framework detection failed (using cached)",{err:String(r)})}await XS(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await ca(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await t1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function ca(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(()=>(Ht(),_s));q.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,l=0;for(let u of i){let f;try{f=await o(u,t)}catch(x){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),l+=1;continue}if(!f){l+=1;continue}if(f.deletedAt){q.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),l+=1;continue}if(f.disconnectedAt){q.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),l+=1;continue}try{q.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=lp(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),l+=1}}return q.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,total:i.length}}async function t1(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 w0(o,t)).status==="refreshed"&&(i+=1)}catch(c){q.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&q.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function n1(t){let e=t.logger??q;if(t.cliSpawned)return"skipped-cli";let r=await t.readPatToken();return r?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:r}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function lp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}sa();Ce();import{readFile as dp}from"node:fs/promises";var en=class{paths;constructor(e){this.paths=e??J()}async probe(e=1e3){let r=await la(this.paths);if(!r)return{kind:"not-running"};try{let i=await this.fetch(r,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...r}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:i1(i)}}}async request(e){let r=await la(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let i=r.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,l=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),f=await u.text();return{status:u.status,body:r1(f)}}finally{clearTimeout(l)}}};async function la(t){try{let[e,r]=await Promise.all([dp(t.portFile,"utf8"),dp(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 r1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function i1(t){return t instanceof Error?t.message:String(t)}Vt();te();ir();import{spawn as s1}from"node:child_process";import{userInfo as fp}from"node:os";var Vl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",o1=new Set(["bash","zsh","sh","dash","ksh"]),up=Je("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),a1=2e3;function c1(t,e=Vl){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let l of o.split(`
115
+ `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.slice(u+1))}return c}function l1(){let t=(process.env.SHELL??"").trim()||(fp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return o1.has(e)?t:null}function d1(t){return new Promise(e=>{let r=`printf '%s' '${Vl}'; env; printf '%s' '${Vl}'`,i;try{i=s1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??fp().homedir}})}catch{e(null);return}let o="",c=!1,l=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},u=p=>{c||(c=!0,clearTimeout(f),clearTimeout(x),e(p))};i.stdout?.on("data",p=>{o+=p.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>l("SIGTERM"),up),x=setTimeout(()=>{l("SIGKILL"),u(o.length>0?o:null)},up+a1)})}async function Jl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=l1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??d1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=c1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Ce();function kn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],l=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,l=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),l=!0;break}}l||r.push(c)}return{value:i,rest:r}}an();import{chmod as u1,copyFile as hp,mkdir as pp,readFile as da,rename as xp,rm as Zl,stat as gp,writeFile as f1}from"node:fs/promises";import{homedir as GD}from"node:os";import{dirname as h1,join as $r,resolve as Yl,sep as ls}from"node:path";import{fileURLToPath as x1}from"node:url";Vt();te();Ce();var Xl=H("dist-install");function p1(t){let e=x1(t),r=h1(e),i=`${ls}src${ls}`;if(r.includes(i)||r.endsWith(`${ls}src${ls}cli`))return null;let o=Yl(r,"index.js"),c=Yl(r,"..","package.json");return{dist:o,pkgJson:c}}async function ed(t={}){let e=t.paths??J(),r=p1(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,l;try{let v=JSON.parse(await da(o,"utf8"));c=v.version??"unknown",l=v.dependencies??{}}catch(v){return Xl.warn("cannot read source package.json,skip dist install",{err:String(v)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(v)}`}}let u=ni.map(v=>`${v}@${l[v]??"latest"}`),f=await Po(e.configFile)??{},x=f.libVersion,p=await da(e.libEntry).then(()=>!0).catch(()=>!1),m=x===c;if(m&&p&&await Ql(e))return{kind:"already-current",libVersion:c};if(!m||!p){await pp(e.libDir,{recursive:!0}),await hp(i,e.libEntry),await hp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=Yl(e.libDir,"package.json"),_=`${JSON.stringify({type:"module"},null,2)}
116
+ `;await da(v,"utf8").catch(()=>null)!==_&&await f1(v,_)}return(!m||!await Ql(e))&&await(t.installWrappers??g1)(e,u),f.libVersion=c,await Ji(f,e.configFile),Xl.info("dist installed",{libEntry:e.libEntry,fromVersion:x,toVersion:c}),m&&p?{kind:"already-current",libVersion:c}:x?{kind:"version-changed",fromVersion:x,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Ql(t){for(let e of ni){let r=$r(t.libDir,"node_modules",...e.split("/"),"package.json");if(!await gp(r).then(o=>o.isFile()).catch(()=>!1))return!1}return!0}async function g1(t,e){await _1(t.installLock,async()=>{if(await Ql(t))return;let r=Math.random().toString(36).slice(2,10),i=`${t.libDir}${ls}.staging-${process.pid}-${r}`,o=$r(i,"node_modules"),c=$r(t.libDir,"node_modules");try{await pp(i,{recursive:!0}),await m1(e,i),await w1(o);let l=`${c}.trash-${r}`;await xp(c,l).catch(()=>{}),await xp(o,c),await Zl(l,{recursive:!0,force:!0}).catch(()=>{}),Xl.info("wrapper closure installed",{liveNm:c,specs:e})}finally{await Zl(i,{recursive:!0,force:!0}).catch(()=>{})}})}function m1(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=rt("npm",r,{stdio:["ignore","pipe","pipe"]}),l="";c.stderr?.on("data",f=>{l.length<8192&&(l+=f.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",f=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(f)}`))}),c.once("close",f=>{clearTimeout(u),f===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${l.trim().slice(0,2e3)}`))})})}async function w1(t){for(let e of ni){let r=$r(t,...e.split("/")),i=JSON.parse(await da($r(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=$r(t,".bin",o),l=await gp(c);process.platform!=="win32"&&!(l.mode&73)&&await u1(c,l.mode|73).catch(()=>{})}}async function _1(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 Zl(t,{force:!0}).catch(()=>{})}}Da();te();Ce();import{closeSync as wp,fstatSync as _p,openSync as yp,readFileSync as y1,readSync as b1,readdirSync as E1,statSync as v1}from"node:fs";import{join as ua}from"node:path";var S1=new Set(["debug","info","warn","error"]);function bp(t){let e=t,r=kn(e,"--agent-id");e=r.rest;let i=kn(e,"--date");e=i.rest;let o=kn(e,"-n","--lines");e=o.rest;let c=kn(e,"--level");e=c.rest;let l=kn(e,"--grep");e=l.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,x=c.value&&S1.has(c.value)?c.value:void 0,p={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(p.agentId=r.value),i.value&&(p.date=i.value),x&&(p.level=x),l.value&&(p.grep=l.value),p}function I1(t,e){return t.agentId?ua(Be(t.agentId,e).logs,sr("agent",t.date)):ua(e.bridgeLogsDir,sr("bridge",t.date))}function A1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function T1(t,e){let r;try{r=E1(t)}catch{return[]}let i=[];for(let o of r){let c=Pa(o,e);if(!c)continue;let l=0;try{l=v1(ua(t,o)).size}catch{}i.push({file:ua(t,o),date:c,size:l})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Ep(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"&&!Rd(r,e.level))return!1}return!0}var mp={debug:"90",info:"36",warn:"33",error:"31"},k1=new Set(["ts","level","module","msg"]);function C1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function vp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=C1(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&mp[o]&&(c=`\x1B[${mp[o]}m${c}\x1B[0m`);let l=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",f=Object.entries(r).filter(([x])=>!k1.has(x)).map(([x,p])=>` ${x}=${typeof p=="string"?p:JSON.stringify(p)}`).join("");return`${i} ${c} ${l} ${u}${f}`}function R1(t,e,r){let c=y1(t,"utf8").split(`
117
+ `).filter(l=>l.length>0).filter(l=>Ep(l,{level:e.level,grep:e.grep}));for(let l of A1(c,e.lines))process.stdout.write(`${vp(l,{raw:e.raw,color:r})}
118
+ `)}async function Sp(t,e){let r=e.paths??J(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?Be(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=T1(l,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
119
+ `),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
120
+ `);return 0}let o=t.date??Rn(new Date),c=I1({agentId:t.agentId,date:o},r);try{R1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
119
121
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
120
- (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
121
- `),1}return t.follow&&await bS(c,t,i),0}var yS=500;function ES(t){try{let e=dp(t,"r");try{return cp(e).size}finally{ap(e)}}catch{return 0}}async function bS(t,e,n){let i=ES(t),s="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let h=dp(t,"r");try{let x=cp(h).size;if(x>i){let g=Buffer.allocUnsafe(x-i),w=lS(h,g,0,g.length,i);u=g.subarray(0,w).toString("utf8"),i+=w}}finally{ap(h)}}catch{}if(u){let h=(s+u).split(`
122
- `);s=h.pop()??"";for(let x of h)x.length>0&&up(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${fp(x,{raw:e.raw,color:n})}
123
- `)}await new Promise(h=>setTimeout(h,yS))}}finally{process.off("SIGINT",d)}}import{basename as vS,resolve as SS}from"node:path";Le();var IS=9e4,AS={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 kS(t){return AS[t]??1}async function xp(t,e={}){let n=e.paths??ee();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
122
+ (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
123
+ `),1}return t.follow&&await O1(c,t,i),0}var P1=500;function D1(t){try{let e=yp(t,"r");try{return _p(e).size}finally{wp(e)}}catch{return 0}}async function O1(t,e,r){let i=D1(t),o="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let f=yp(t,"r");try{let x=_p(f).size;if(x>i){let p=Buffer.allocUnsafe(x-i),m=b1(f,p,0,p.length,i);u=p.subarray(0,m).toString("utf8"),i+=m}}finally{wp(f)}}catch{}if(u){let f=(o+u).split(`
124
+ `);o=f.pop()??"";for(let x of f)x.length>0&&Ep(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${vp(x,{raw:e.raw,color:r})}
125
+ `)}await new Promise(f=>setTimeout(f,P1))}}finally{process.off("SIGINT",l)}}import{basename as L1,resolve as N1}from"node:path";Ce();var M1=9e4,B1={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 F1(t){return B1[t]??1}async function Ip(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>
124
126
  `),4;if(t.groupFile&&!t.mimeType)return process.stderr.write(`Error: --group-file requires --mime <mimeType> (e.g. application/pdf, image/png). No local file is read in group-file mode, mime cannot be auto-detected.
125
- `),3;let i=await ra(n).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${n.portFile} / ${n.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
126
- `),4;let s={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:SS(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 TS(i,"/agent/send",s,IS)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
127
+ `),3;let i=await la(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.
128
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:N1(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 z1(i,"/agent/send",o,M1)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
127
129
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
128
- `),kS(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
129
- `);else{let d=t.name??vS(s.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
130
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${RS(c.bytes)})
131
- `)}return 0}async function TS(t,e,n,i){let s=new AbortController,c=setTimeout(()=>s.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:s.signal}),u=await d.text(),h=u?JSON.parse(u):null;return h&&typeof h=="object"&&"ok"in h?h:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function RS(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Sp=H("cli");function He(t,e){let{value:n,rest:i}=Cn(t,e);return{value:n,rest:i}}function la(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
132
- `)}function QS(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:D}=He(e.slice(1),"--agent-id");return D?{mode:"reload",agentId:D}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return e2(e.slice(1));if(e[0]==="log")return{mode:"log",...lp(e.slice(1))};if(e[0]==="connect")return t2(e.slice(1));if(e.includes("--status"))return la("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return la("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return la("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return la("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:i,rest:s}=He(n,"--pat-token");n=s;let{value:c,rest:d}=He(n,"--pair-code");n=d;let{value:u,rest:h}=He(n,"--env");n=h;let{value:x,rest:g}=He(n,"--handshake-url");n=g;let{value:w,rest:S}=He(n,"--frontier-url");n=S;let{value:y,rest:v}=He(n,"--mock-scenario");n=v;let{value:I}=He(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let R={mode:"pair",privatecode:i,pairingCode:c};return u&&(R.env=u),x&&(R.handshakeUrl=x),w&&(R.frontierUrl=w),y&&(R.mockScenario=y),I&&(R.agentId=I),A&&(R.skipRebuildEnv=!0),R}function e2(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:s,rest:c}=He(i,"--caption");i=c;let{value:d,rest:u}=He(i,"--name");i=u;let{value:h,rest:x}=He(i,"--agent-id");i=x;let{value:g,rest:w}=He(i,"--session-id");i=w;let{value:S,rest:y}=He(i,"--mime");i=y;let v=i.includes("--group-file");i=i.filter(R=>R!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return s&&(A.caption=s),d&&(A.name=d),h&&(A.agentId=h),g&&(A.sessionId=g),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function t2(t){let e=t,{value:n,rest:i}=He(e,"--pat-token");e=i;let{value:s,rest:c}=He(e,"--env");e=c;let{value:d,rest:u}=He(e,"--handshake-url");e=u;let{value:h,rest:x}=He(e,"--frontier-url");e=x;let{value:g,rest:w}=He(e,"--mock-scenario");e=w;let S=e.includes("--skip-rebuild-env"),y={mode:"connect"};return n&&(y.privatecode=n),s&&(y.env=s),d&&(y.handshakeUrl=d),h&&(y.frontierUrl=h),g&&(y.mockScenario=g),S&&(y.skipRebuildEnv=!0),y}var n2=`
130
+ `),F1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
131
+ `);else{let l=t.name??L1(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})
132
+ `)}else process.stdout.write(`Sent ${t.kind} ${l} (${U1(c.bytes)})
133
+ `)}return 0}async function z1(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let l=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await l.text(),f=u?JSON.parse(u):null;return f&&typeof f=="object"&&"ok"in f?f:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${l.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function U1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Lp=H("cli");function je(t,e){let{value:r,rest:i}=kn(t,e);return{value:r,rest:i}}function ma(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
134
+ `)}function dI(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:P}=je(e.slice(1),"--agent-id");return P?{mode:"reload",agentId:P}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return uI(e.slice(1));if(e[0]==="log")return{mode:"log",...bp(e.slice(1))};if(e[0]==="connect")return fI(e.slice(1));if(e.includes("--status"))return ma("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ma("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ma("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ma("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:o}=je(r,"--pat-token");r=o;let{value:c,rest:l}=je(r,"--pair-code");r=l;let{value:u,rest:f}=je(r,"--env");r=f;let{value:x,rest:p}=je(r,"--handshake-url");r=p;let{value:m,rest:v}=je(r,"--frontier-url");r=v;let{value:_,rest:b}=je(r,"--mock-scenario");r=b;let{value:I}=je(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let k={mode:"pair",privatecode:i,pairingCode:c};return u&&(k.env=u),x&&(k.handshakeUrl=x),m&&(k.frontierUrl=m),_&&(k.mockScenario=_),I&&(k.agentId=I),A&&(k.skipRebuildEnv=!0),k}function uI(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=je(i,"--caption");i=c;let{value:l,rest:u}=je(i,"--name");i=u;let{value:f,rest:x}=je(i,"--agent-id");i=x;let{value:p,rest:m}=je(i,"--session-id");i=m;let{value:v,rest:_}=je(i,"--mime");i=_;let b=i.includes("--group-file");i=i.filter(k=>k!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return o&&(A.caption=o),l&&(A.name=l),f&&(A.agentId=f),p&&(A.sessionId=p),b&&(A.groupFile=!0),v&&(A.mimeType=v),A}function fI(t){let e=t,{value:r,rest:i}=je(e,"--pat-token");e=i;let{value:o,rest:c}=je(e,"--env");e=c;let{value:l,rest:u}=je(e,"--handshake-url");e=u;let{value:f,rest:x}=je(e,"--frontier-url");e=x;let{value:p,rest:m}=je(e,"--mock-scenario");e=m;let v=e.includes("--skip-rebuild-env"),_={mode:"connect"};return r&&(_.privatecode=r),o&&(_.env=o),l&&(_.handshakeUrl=l),f&&(_.frontierUrl=f),p&&(_.mockScenario=p),v&&(_.skipRebuildEnv=!0),_}var hI=`
133
135
  coze-bridge - local bridge daemon for cloud Agent Service
134
136
 
135
137
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -210,57 +212,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
210
212
 
211
213
  Internal:
212
214
  <node> <entry> --daemon daemon mode (OS supervisor only)
213
- `.trimStart();async function Ip(t=process.argv,e={}){let n=QS(t);switch(n.mode){case"help":return process.stdout.write(n2),0;case"version":return process.stdout.write(`${Dt}
214
- `),0;case"daemon":{try{await Yx()}catch(i){return Sp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return r2(e);case"stop":return kp(e);case"reload":return o2(n.agentId,e);case"log":return hp(n,e);case"update":return i2(e);case"purge":return c2(e);case"service-install":return d2(e);case"service-uninstall":return l2(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),u2(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),f2(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return xp({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 Ap(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 r2(t){let e=t.paths??ee(),n=new en(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
215
- `),1;if(i.kind==="stale")return await Ap(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
216
- `),1;let s=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
217
- ${JSON.stringify(s.body,null,2)}
218
- `),0}async function kp(t){let e=t.paths??ee(),n=new en(e),i=t.daemonSweep??(async()=>{let h=I0();return await A0(h),h}),s=async()=>{t.skipProcessKill||await i(e)},c=await as(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
219
- `)}let u=await n.probe();if(u.kind==="not-running")return await s(),process.stdout.write(d?`coze-bridge: stopped
215
+ `.trimStart();async function Np(t=process.argv,e={}){let r=dI(t);switch(r.mode){case"help":return process.stdout.write(hI),0;case"version":return process.stdout.write(`${Ot}
216
+ `),0;case"daemon":{try{await cp()}catch(i){return Lp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return xI(e);case"stop":return Bp(e);case"reload":return mI(r.agentId,e);case"log":return Sp(r,e);case"update":return pI(e);case"purge":return wI(e);case"service-install":return _I(e);case"service-uninstall":return yI(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),bI(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),EI(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Ip({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 Mp(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 xI(t){let e=t.paths??J(),r=new en(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
217
+ `),1;if(i.kind==="stale")return await Mp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
218
+ `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
219
+ ${JSON.stringify(o.body,null,2)}
220
+ `),0}async function Bp(t){let e=t.paths??J(),r=new en(e),i=t.daemonSweep??(async()=>{let f=P0();return await D0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await us(t),l=!1;if(c)try{await c.uninstall(),l=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
221
+ `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(l?`coze-bridge: stopped
220
222
  `:`coze-bridge: not running
221
- `),0;if(u.kind==="stale")return await Ap(e),await s(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
222
- `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await s(),process.stdout.write(`coze-bridge: stopped
223
- `),0}catch(h){return(await n.probe()).kind!=="connected"?(await s(),process.stdout.write(`coze-bridge: stopped
224
- `),0):(await s(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
225
- `),1)}}async function i2(t){return await kp(t),(t.spawnNpx??s2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function s2(t){return new Promise(e=>{let n=nt("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
226
- `),e(1)})})}async function o2(t,e){let n=new en(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
227
- `),1;try{let s=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(s.status===200&&s.body?.ok){let c=s.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
223
+ `),0;if(u.kind==="stale")return await Mp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
224
+ `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
225
+ `),0}catch(f){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
226
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
227
+ `),1)}}async function pI(t){return await Bp(t),(t.spawnNpx??gI)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function gI(t){return new Promise(e=>{let r=rt("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)}
228
+ `),e(1)})})}async function mI(t,e){let r=new en(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
229
+ `),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)
228
230
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
229
- `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(s.body)}
230
- `),1}catch(s){return process.stderr.write(`coze-bridge: reload failed: ${String(s)}
231
- `),1}}async function as(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(Ep(),yp)),i=e(),s=n();return{platform:i.platform,install:c=>i.install(s,c),uninstall:()=>i.uninstall(s)}}async function Tp(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,s=t.sleep??h2,c=t.paths??ee();if(n.kind==="connected"){if(!a2(n.body))return n;dt(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=>dt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await vp(c.pidFile,s)}let d=t.spawnDaemon??$x,u=await as(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await bp(e,i,s);if(h.kind==="connected")return h;dt(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){dt(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}dt(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 vp(c.pidFile,s)}else u&&await u.install({activate:!1}).catch(h=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(h)}
231
+ `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
232
+ `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
233
+ `),1}}async function us(t){if(t.supervisor){let c=t.supervisor,l={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(l,u),uninstall:()=>c.uninstall(l)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Dp(),Pp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Fp(t,e){let r=await e.probe();if(r.kind==="connected")return r;let i=t.spawnDaemon??op,o=t.waitTimeoutMs??15e3,c=t.sleep??SI,l=t.paths??J(),u=await us(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await Op(e,o,c);if(f.kind==="connected")return f;At(l.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:o})}catch(f){At(l.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}At(l.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await vI(l.pidFile,c)}else u&&await u.install({activate:!1}).catch(f=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(f)}
232
234
  `));return process.stdout.write(`coze-bridge: starting daemon...
233
- `),await d({paths:t.paths}),bp(e,i,s)}function a2(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 c2(t){let e=new en(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
234
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
235
- `)}await new Promise(d=>setTimeout(d,500))}let i=await as(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
236
- `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
237
- `)}let s=t.paths??ee(),{rm:c}=await import("node:fs/promises");try{await c(s.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${s.bridgeRoot}
238
- `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
235
+ `),await i({paths:t.paths}),Op(e,o,c)}async function wI(t){let e=new en(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
236
+ `);try{await e.request({method:"POST",path:"/shutdown"})}catch(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
237
+ `)}await new Promise(l=>setTimeout(l,500))}let i=await us(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
238
+ `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
239
+ `)}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}
240
+ `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
239
241
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
240
- `),0}async function d2(t){let e=await as(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
242
+ `),0}async function _I(t){let e=await us(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
241
243
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
242
- `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
243
- `),1}}async function l2(t){let e=await as(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
244
- `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
245
- `),1}}async function Rp(t,e,n){if(e)return dt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(dt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(dt(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
246
- `),dt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function u2(t,e,n,i={},s,c){let d=new en(n.paths),u=n.paths??ee(),h=await Rp(u,c,n.reconstructEnv??Hd);if(await nd(u,h).catch(w=>dt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!n.skipDistInstall){let w=await Yd({paths:n.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
247
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
248
- `)}let x=await Tp(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
249
- `),1;let g={privatecode:t,pairing_code:e};i.env&&(g.env=i.env),i.handshakeUrl&&(g.handshake_url=i.handshakeUrl),i.frontierUrl&&(g.frontier_url=i.frontierUrl),i.mockScenario&&(g.mock_scenario=i.mockScenario),s&&(g.agent_id=s);try{let w=await d.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let S=w.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
244
+ `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
245
+ `),1}}async function yI(t){let e=await us(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
246
+ `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
247
+ `),1}}async function zp(t,e,r){if(e)return At(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(At(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(At(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)
248
+ `),At(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function bI(t,e,r,i={},o,c){let l=new en(r.paths),u=r.paths??J(),f=await zp(u,c,r.reconstructEnv??Jl);if(await $c(u,f).catch(m=>At(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!r.skipDistInstall){let m=await ed({paths:r.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
249
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
250
+ `)}let x=await Fp(r,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
251
+ `),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),o&&(p.agent_id=o);try{let m=await l.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});if(m.status===200&&m.body?.ok){let v=m.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
250
252
  `),1):(process.stdout.write(`\u5DF2\u914D\u5BF9\u8FDE\u63A5\u5B8C\u6210\uFF0C\u8BF7\u8FD4\u56DE\u5230 coze \u5E73\u53F0\u4E0A\u70B9\u51FB "\u6211\u5DF2\u6267\u884C"
251
- `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
252
- `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
253
- `),1}}async function f2(t,e,n={},i){let s=e.paths??ee(),c=t??await Jo(s);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new en(e.paths),u=await Rp(s,i,e.reconstructEnv??Hd);if(await nd(s,u).catch(g=>dt(s.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await Yd({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
254
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
255
- `)}let h=await Tp(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
256
- `),1;let x={privatecode:c};n.env&&(x.env=n.env),n.handshakeUrl&&(x.handshake_url=n.handshakeUrl),n.frontierUrl&&(x.frontier_url=n.frontierUrl),n.mockScenario&&(x.mock_scenario=n.mockScenario);try{let g=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return g.status===200&&g.body?.ok?(process.stdout.write(`coze-bridge: connected (${g.body.note??"ok"})
257
- `),t!==void 0&&await ns(c,s).catch(w=>Sp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
258
- `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
259
- `),1}}async function bp(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let s=await t.probe(500);if(s.kind==="connected")return s;await n(200)}return t.probe(500)}async function vp(t,e,n=60,i=200){let{readFile:s}=await import("node:fs/promises");for(let c=0;c<n;c++){let d;try{d=await s(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Ui(u))return;await e(i)}}function h2(t){return new Promise(e=>setTimeout(e,t))}ne();function x2(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let n=Number(e[1]),i=Number(e[2]??0);return n<18||n===18&&i<4?"fatal":n<20?"warn":"ok"}function Cp(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){let i=x2(t);if(i==="ok")return;let s=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${s} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
260
- `),n(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${s},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
253
+ `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(m.body)}
254
+ `),1}catch(m){return process.stderr.write(`coze-bridge: pair failed: ${String(m)}
255
+ `),1}}async function EI(t,e,r={},i){let o=e.paths??J(),c=t??await na(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let l=new en(e.paths),u=await zp(o,i,e.reconstructEnv??Jl);if(await $c(o,u).catch(p=>At(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(p)})),!e.skipDistInstall){let p=await ed({paths:e.paths});p.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${p.fromVersion} \u2192 ${p.toVersion}
256
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):p.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${p.libVersion}
257
+ `)}let f=await Fp(e,l);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
258
+ `),1;let x={privatecode:c};r.env&&(x.env=r.env),r.handshakeUrl&&(x.handshake_url=r.handshakeUrl),r.frontierUrl&&(x.frontier_url=r.frontierUrl),r.mockScenario&&(x.mock_scenario=r.mockScenario);try{let p=await l.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return p.status===200&&p.body?.ok?(process.stdout.write(`coze-bridge: connected (${p.body.note??"ok"})
259
+ `),t!==void 0&&await as(c,o).catch(m=>Lp.warn("writePatToken after connect failed (ignored)",{err:String(m)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(p.body)}
260
+ `),1)}catch(p){return process.stderr.write(`coze-bridge: connect failed: ${String(p)}
261
+ `),1}}async function Op(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 vI(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let l;try{l=await o(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!Wi(u))return;await e(i)}}function SI(t){return new Promise(e=>setTimeout(e,t))}te();function II(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 Up(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=II(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
262
+ `),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
261
263
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
262
264
  npx -y coze-bridge@latest stop
263
265
  npx -y coze-bridge@latest connect
264
266
 
265
- `)}Cp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&vl("warn");Ip(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
267
+ `)}Up();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&kd("warn");Np(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
266
268
  `),process.exit(1)});