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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +95 -94
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,25 +5,25 @@ 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 yg=Object.create;var Ia=Object.defineProperty;var bg=Object.getOwnPropertyDescriptor;var Eg=Object.getOwnPropertyNames;var vg=Object.getPrototypeOf,Sg=Object.prototype.hasOwnProperty;var he=(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 rt=(t,e)=>()=>(t&&(e=t(t=0)),e);var de=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Aa=(t,e)=>{for(var n in e)Ia(t,n,{get:e[n],enumerable:!0})},Ig=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Eg(e))!Sg.call(t,s)&&s!==n&&Ia(t,s,{get:()=>e[s],enumerable:!(i=bg(e,s))||i.enumerable});return t};var Ht=(t,e,n)=>(n=t!=null?yg(vg(t)):{},Ig(e||!t||!t.__esModule?Ia(n,"default",{value:t,enumerable:!0}):n,t));function Ze(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ar=rt(()=>{"use strict"});import{createWriteStream as Ag,mkdirSync as Tg,readdirSync as kg,unlinkSync as Cg}from"node:fs";import{join as bl}from"node:path";function Ln(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function cr(t,e){return`${t}-${e}.log`}function Ta(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Dg(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 us(t,e,n,i){let s;try{s=kg(t)}catch{return}for(let c of s){let d=Ta(c,e);if(d&&Dg(d,n,i))try{Cg(bl(t,c))}catch{}}}var ri,ka=rt(()=>{"use strict";ri=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Ln(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{Tg(this.dir,{recursive:!0});let n=Ag(bl(this.dir,cr(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
- `)),this.stream=n}catch(n){process.stderr.write(`[log-sink] rotate failed: ${String(n)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&us(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Rg,mkdirSync as Pg}from"node:fs";import{join as Og}from"node:path";function vl(t){let e=t.retentionDays??Mg,n=t.clock??(()=>Ln(new Date));hs={bridgeSink:new ri(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:s=>new ri(t.agentLogsDir(s),"agent",{retentionDays:e,clock:n})};let i=n();us(t.bridgeLogsDir,"bridge",i,e);for(let s of t.listAgentIds?.()??[])us(t.agentLogsDir(s),"agent",i,e)}function Bg(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Sl(t){Ca=t}function Il(t){return dr[Ca]<=dr[t]}function Al(t,e){let n=dr[t];return n===void 0?!0:n>=dr[e]}function xs(t){El={...t}}function Tl(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`${Ln(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function ut(t,e,n,i,s){try{let c=`${JSON.stringify({ts:Tl(new Date),level:e,module:n,msg:i,...s})}
11
- `;Pg(t,{recursive:!0}),Rg(Og(t,cr("bridge",Ln(new Date))),c)}catch{}}function Fg(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function fs(t,e,n,i,s){if(dr[t]<dr[Ca])return;let c=`${JSON.stringify({ts:Tl(new Date),level:t,module:e,msg:n,...El,...i})}
12
- `;if(hs){let d=Fg(s,i),u=d?Bg(hs,d):hs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Ng.write(c):Lg.write(c)}function q(t,e){return{debug:(n,i)=>fs("debug",t,n,i,e),info:(n,i)=>fs("info",t,n,i,e),warn:(n,i)=>fs("warn",t,n,i,e),error:(n,i)=>fs("error",t,n,i,e),child:n=>q(`${t}.${n}`,e),forAgent:n=>q(t,n)}}var dr,Ca,Lg,Ng,El,Mg,hs,ee=rt(()=>{"use strict";ar();ka();dr={debug:10,info:20,warn:30,error:40},Ca=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Lg=process.stdout,Ng=process.stderr,El={},Mg=Ze("COZE_BRIDGE_LOG_RETENTION_DAYS",30),hs=null});var T,$e=rt(()=>{"use strict";T=class extends Error{code;retriable;cause;constructor(e,n,i){super(n),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Rl={};Aa(Rl,{ACP_WRAPPER_NPM_PACKAGES:()=>ps,_resetAcpInstallerForTests:()=>jg,_setBinaryPathCacheForTests:()=>Wg,buildAcpSpawn:()=>si,ensureAcpInstalled:()=>lr,getAcpBinaryPath:()=>gs,pickWhichLine:()=>Pa,probeAcpVersion:()=>Hg,resolveAcpCommand:()=>Dl});import{readFileSync as kl}from"node:fs";import{createRequire as zg}from"node:module";import{dirname as Ug,resolve as Gg}from"node:path";function Pa(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=i=>e.find(s=>s.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function qg(t){let e=Cl.resolve(`${t.npmPackage}/package.json`),n=Ug(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 Gg(n,s)}async function lr(t,e){let n=Ra[t];if(!n)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ii.get(t);if(i)return i;try{let s=qg(n);return ii.set(t,s),Da.info("acp wrapper resolved",{framework:t,binary:n.binary,path:s}),s}catch(s){throw Da.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(s)}),new T("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${n.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
- `),{cause:s})}}async function Hg(t){let e=Ra[t];if(e)try{let n=Cl.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){Da.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function gs(t){return ii.get(t)}function Dl(t,e){if(e)return e;let n=gs(t);if(!n)throw new T("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return n}function si(t,e,n){if(e)return{command:e,args:[...n]};let i=Dl(t);return{command:process.execPath,args:[i,...n]}}function jg(){ii.clear()}function Wg(t,e){ii.set(t,e)}var Da,Ra,ps,Cl,ii,cn=rt(()=>{"use strict";$e();ee();Da=q("agents.acp-installer"),Ra={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},ps=Object.values(Ra).filter(t=>t!==void 0).map(t=>t.npmPackage),Cl=zg(import.meta.url),ii=new Map});import{chmod as $g,mkdir as Vg,readFile as Jg,rename as Zg,rm as Yg,writeFile as Xg}from"node:fs/promises";import{dirname as Qg}from"node:path";async function ur(t){try{let e=await Jg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function dn(t,e,n){await Vg(Qg(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Xg(i,e,{encoding:"utf8",mode:n?.mode}),await Zg(i,t),n?.mode!==void 0&&await $g(t,n.mode)}catch(s){throw await Yg(i,{force:!0}).catch(()=>{}),s}}async function fr(t,e,n){await dn(t,`${JSON.stringify(e,null,2)}
14
- `,n)}var ln=rt(()=>{"use strict"});import{promises as Ll,readdirSync as em}from"node:fs";import{homedir as tm}from"node:os";import{sep as nm,join as De,resolve as Nl}from"node:path";function X(t){let e=t??tm(),n=De(e,".coze"),i=De(n,"bridge"),s=De(i,"lib"),c=De(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:s,libEntry:De(s,"index.js"),binDir:De(i,"bin"),pidFile:De(i,"bridge.pid"),portFile:De(i,"bridge.port"),tokenFile:De(i,"bridge.token"),patTokenFile:De(i,"pat-token"),agentEnvFile:De(i,"agent-env.json"),logFile:De(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:De(c,"daemon-stdio.log"),installLock:De(i,"install.lock"),configFile:De(i,"config.json"),agentsRoot:De(n,"agents")}}function Ye(t,e=X()){let n=De(e.agentsRoot,t);return{root:n,config:De(n,"config.json"),workspace:De(n,"workspace"),logs:De(n,"logs")}}function ms(t=X()){try{return em(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function oi(t,e){let n=await Ll.realpath(Nl(t)).catch(()=>null);if(!n)return!1;let i=await Ll.realpath(Nl(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+nm)}var Be=rt(()=>{"use strict"});var _s={};Aa(_s,{AGENT_CONFIG_FILE_MODE:()=>ws,enforceAgentConfigMode:()=>sm,loadAgentConfig:()=>Re,persistAgentSessions:()=>ai,persistAgentSkills:()=>ci,saveAgentConfig:()=>Ue});import{chmod as rm,stat as im}from"node:fs/promises";function Re(t,e){return ur(Ye(t,e).config)}function Ue(t,e){return fr(Ye(t.agentId,e).config,t,{mode:ws})}async function sm(t,e){if(process.platform==="win32")return;let n=Ye(t,e).config;try{let i=await im(n);if(!i.isFile())return;let s=i.mode&511;s!==ws&&(await rm(n,ws),Ml.warn("agent config mode auto-corrected to 0600",{path:n,from:s.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Ml.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function ai(t,e,n){let i=await Re(t,n);i&&(i.sessions=Object.fromEntries(e),await Ue(i,n))}async function ci(t,e,n){let i=await Re(t,n);i&&(i.skills=e,await Ue(i,n))}var Ml,ws,un=rt(()=>{"use strict";ln();ee();Be();Ml=q("agent-config"),ws=384});var Na=de(($2,zl)=>{zl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var bs=de(Gl=>{var Ul={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function um(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(Ul))Gl[t]=um(Ul[t])});var Kl=de((J2,Wl)=>{var fm=he("fs"),Fe=he("path"),ql=Na(),hm=bs(),xm=typeof process=="object"&&process.platform==="win32",Hl=t=>typeof t=="object"&&t!==null,jl=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 Ae(t){this.sep=Fe.sep,this.fs=fm,Hl(t)&&Hl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Wl.exports=Ae;Ae.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 hm.FILE_IN_THE_WAY(`"${s}"`)}})}n(t)};Ae.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=Fe.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};Ae.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=Fe.dirname(t);c.fs.exists(x,function(m){m||c.makeDir(x),c.fs.open(t,"w",438,function(_,S){_?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,v){c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){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)})})})})})};Ae.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=Fe.join(i,u),x=e.fs.statSync(h);(!s||s.test(h))&&d.push(Fe.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(n(h,s,c)))}),d}return n(t,void 0,!0)};Ae.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=Fe.join(t,u),n.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Fe.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(m,_){if(m)return e(m);i=i.concat(_),--d||e(null,i)}):--d||e(null,i))})})})};Ae.prototype.getAttributes=function(){};Ae.prototype.setAttributes=function(){};Ae.crc32update=function(t,e){return jl[(t^e)&255]^t>>>8};Ae.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Ae.crc32update(n,t[i++]);return~n>>>0};Ae.methodToString=function(t){switch(t){case ql.STORED:return"STORED ("+t+")";case ql.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ae.canonical=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.join(".",e)};Ae.zipnamefix=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.posix.join(".",e)};Ae.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let i=n-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ae.sanitize=function(t,e){t=Fe.resolve(Fe.normalize(t));for(var n=e.split("/"),i=0,s=n.length;i<s;i++){var c=Fe.normalize(Fe.join(t,n.slice(i,s).join(Fe.sep)));if(c.indexOf(t)===0)return c}return Fe.normalize(Fe.join(t,Fe.basename(e)))};Ae.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Ae.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Ae.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ae.fromDate2DOS=function(t){let e=0,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};Ae.isWin=xm;Ae.crcTable=jl});var Vl=de((Z2,$l)=>{var pm=he("path");$l.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=pm.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 Zl=de((Y2,Jl)=>{Jl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=de((X2,xr)=>{xr.exports=Kl();xr.exports.Constants=Na();xr.exports.Errors=bs();xr.exports.FileAttr=Vl();xr.exports.decoder=Zl()});var Xl=de((Q2,Yl)=>{var fn=pr(),z=fn.Constants;Yl.exports=function(){var t=20,e=10,n=0,i=0,s=0,c=0,d=0,u=0,h=0,x=0,m=0,_=0,S=0,y=0,v=0;t|=fn.isWin?2560:768,n|=z.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,k=b=>Math.max(0,b)&65535,P=b=>Math.max(0,b)&255;return s=fn.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return n},set flags(b){n=b},get flags_efs(){return(n&z.FLG_EFS)>0},set flags_efs(b){b?n|=z.FLG_EFS:n&=~z.FLG_EFS},get flags_desc(){return(n&z.FLG_DESC)>0},set flags_desc(b){b?n|=z.FLG_DESC:n&=~z.FLG_DESC},get method(){return i},set method(b){switch(b){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=b},get time(){return fn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=fn.fromDate2DOS(b)},get timeval(){return s},set timeval(b){s=A(b)},get timeHighByte(){return P(s>>>8)},get crc(){return c},set crc(b){c=A(b)},get compressedSize(){return d},set compressedSize(b){d=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return h},set fileNameLength(b){h=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return m},set commentLength(b){m=b},get diskNumStart(){return _},set diskNumStart(b){_=A(b)},get inAttr(){return S},set inAttr(b){S=A(b)},get attr(){return y},set attr(b){y=A(b)},get fileAttr(){return(y||0)>>16&4095},get offset(){return v},set offset(b){v=A(b)},get encrypted(){return(n&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+x+m},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var D=b.slice(v,v+z.LOCHDR);if(D.readUInt32LE(0)!==z.LOCSIG)throw fn.Errors.INVALID_LOC();I.version=D.readUInt16LE(z.LOCVER),I.flags=D.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=D.readUInt16LE(z.LOCHOW),I.time=D.readUInt32LE(z.LOCTIM),I.crc=D.readUInt32LE(z.LOCCRC),I.compressedSize=D.readUInt32LE(z.LOCSIZ),I.size=D.readUInt32LE(z.LOCLEN),I.fnameLen=D.readUInt16LE(z.LOCNAM),I.extraLen=D.readUInt16LE(z.LOCEXT);let O=v+z.LOCHDR+I.fnameLen,F=O+I.extraLen;return b.slice(O,F)},loadFromBinary:function(b){if(b.length!==z.CENHDR||b.readUInt32LE(0)!==z.CENSIG)throw fn.Errors.INVALID_CEN();t=b.readUInt16LE(z.CENVEM),e=b.readUInt16LE(z.CENVER),n=b.readUInt16LE(z.CENFLG),i=b.readUInt16LE(z.CENHOW),s=b.readUInt32LE(z.CENTIM),c=b.readUInt32LE(z.CENCRC),d=b.readUInt32LE(z.CENSIZ),u=b.readUInt32LE(z.CENLEN),h=b.readUInt16LE(z.CENNAM),x=b.readUInt16LE(z.CENEXT),m=b.readUInt16LE(z.CENCOM),_=b.readUInt16LE(z.CENDSK),S=b.readUInt16LE(z.CENATT),y=b.readUInt32LE(z.CENATX),v=b.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(z.LOCHDR);return b.writeUInt32LE(z.LOCSIG,0),b.writeUInt16LE(e,z.LOCVER),b.writeUInt16LE(n,z.LOCFLG),b.writeUInt16LE(i,z.LOCHOW),b.writeUInt32LE(s,z.LOCTIM),b.writeUInt32LE(c,z.LOCCRC),b.writeUInt32LE(d,z.LOCSIZ),b.writeUInt32LE(u,z.LOCLEN),b.writeUInt16LE(h,z.LOCNAM),b.writeUInt16LE(I.extraLen,z.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(z.CENHDR+h+x+m);return b.writeUInt32LE(z.CENSIG,0),b.writeUInt16LE(t,z.CENVEM),b.writeUInt16LE(e,z.CENVER),b.writeUInt16LE(n,z.CENFLG),b.writeUInt16LE(i,z.CENHOW),b.writeUInt32LE(s,z.CENTIM),b.writeUInt32LE(c,z.CENCRC),b.writeUInt32LE(d,z.CENSIZ),b.writeUInt32LE(u,z.CENLEN),b.writeUInt16LE(h,z.CENNAM),b.writeUInt16LE(x,z.CENEXT),b.writeUInt16LE(m,z.CENCOM),b.writeUInt16LE(_,z.CENDSK),b.writeUInt16LE(S,z.CENATT),b.writeUInt32LE(y,z.CENATX),b.writeUInt32LE(v,z.CENOFF),b},toJSON:function(){let b=function(D){return D+" bytes"};return{made:t,version:e,flags:n,method:fn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(m),diskNumStart:_,inAttr:S,attr:y,offset:v,centralHeaderSize:b(z.CENHDR+h+x+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var eu=de((eI,Ql)=>{var gr=pr(),ve=gr.Constants;Ql.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 ve.ENDHDR+s},loadFromBinary:function(c){if((c.length!==ve.ENDHDR||c.readUInt32LE(0)!==ve.ENDSIG)&&(c.length<ve.ZIP64HDR||c.readUInt32LE(0)!==ve.ZIP64SIG))throw gr.Errors.INVALID_END();c.readUInt32LE(0)===ve.ENDSIG?(t=c.readUInt16LE(ve.ENDSUB),e=c.readUInt16LE(ve.ENDTOT),n=c.readUInt32LE(ve.ENDSIZ),i=c.readUInt32LE(ve.ENDOFF),s=c.readUInt16LE(ve.ENDCOM)):(t=gr.readBigUInt64LE(c,ve.ZIP64SUB),e=gr.readBigUInt64LE(c,ve.ZIP64TOT),n=gr.readBigUInt64LE(c,ve.ZIP64SIZE),i=gr.readBigUInt64LE(c,ve.ZIP64OFF),s=0)},toBinary:function(){var c=Buffer.alloc(ve.ENDHDR+s);return c.writeUInt32LE(ve.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,ve.ENDSUB),c.writeUInt16LE(e,ve.ENDTOT),c.writeUInt32LE(n,ve.ENDSIZ),c.writeUInt32LE(i,ve.ENDOFF),c.writeUInt16LE(s,ve.ENDCOM),c.fill(" ",ve.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 Ba=de(Ma=>{Ma.EntryHeader=Xl();Ma.MainHeader=eu()});var nu=de((nI,tu)=>{tu.exports=function(t){var e=he("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 m=c[x];m.copy(u,h),h+=m.length}i&&i(u)}),s.end(t)}}}});var iu=de((rI,ru)=>{var gm=+(process.versions?process.versions.node:"").split(".")[0]||0;ru.exports=function(t,e){var n=he("zlib");let i=gm>=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 m=0;m<d.length;m++){var _=d[m];_.copy(h,x),x+=_.length}s&&s(h)}),c.end(t)}}}});var du=de((iI,cu)=>{"use strict";var{randomFillSync:su}=he("crypto"),mm=bs(),wm=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}),au=(t,e)=>Math.imul(t,e)>>>0,ou=(t,e)=>wm[(t^e)&255]^t>>>8,di=()=>typeof su=="function"?su(Buffer.alloc(12)):di.node();di.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 Es={genSalt:di};function vs(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])}vs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=ou(e[0],t),e[1]+=e[0]&255,e[1]=au(e[1],134775813)+1,e[2]=ou(e[2],e[1]>>>24),t};vs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return au(t,t^1)>>8&255};function _m(t){let e=new vs(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 ym(t){let e=new vs(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 bm(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=_m(n),s=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==c)throw mm.WRONG_PASSWORD();return i(t.slice(12))}function Em(t){Buffer.isBuffer(t)&&t.length>=12?Es.genSalt=function(){return t.slice(0,12)}:t==="node"?Es.genSalt=di.node:Es.genSalt=di}function vm(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=ym(n),c=Es.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)}cu.exports={decrypt:bm,encrypt:vm,_salter:Em}});var lu=de(Ss=>{Ss.Deflater=nu();Ss.Inflater=iu();Ss.ZipCrypto=du()});var za=de((oI,uu)=>{var le=pr(),Sm=Ba(),Te=le.Constants,Fa=lu();uu.exports=function(t,e){var n=new Sm.EntryHeader,i=Buffer.alloc(0),s=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let m=t,_=typeof m.decoder=="object"?m.decoder:le.decoder;x=_.hasOwnProperty("efs")?_.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(b){if(!n.flags_desc&&!n.localHeader.flags_desc){if(le.crc32(b)!==n.localHeader.crc)return!1}else{let D={},O=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(O)==Te.LOCSIG||e.readUInt32LE(O)==Te.CENSIG)throw le.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Te.EXTSIG)D.crc=e.readUInt32LE(O+Te.EXTCRC),D.compressedSize=e.readUInt32LE(O+Te.EXTSIZ),D.size=e.readUInt32LE(O+Te.EXTLEN);else if(e.readUInt16LE(O+12)===19280)D.crc=e.readUInt32LE(O+Te.EXTCRC-4),D.compressedSize=e.readUInt32LE(O+Te.EXTSIZ-4),D.size=e.readUInt32LE(O+Te.EXTLEN-4);else throw le.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==n.compressedSize||D.size!==n.size||D.crc!==n.crc)throw le.Errors.DESCRIPTOR_FAULTY();if(le.crc32(b)!==D.crc)return!1}return!0}function v(b,D,O){if(typeof D>"u"&&typeof b=="string"&&(O=b,b=void 0),c)return b&&D&&D(Buffer.alloc(0),le.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return b&&D&&D(F),F;if(n.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw le.Errors.INVALID_PASS_PARAM();F=Fa.ZipCrypto.decrypt(F,n,O)}var B=Buffer.alloc(n.size);switch(n.method){case le.Constants.STORED:if(F.copy(B),y(B))return b&&D&&D(B),B;throw b&&D&&D(B,le.Errors.BAD_CRC()),le.Errors.BAD_CRC();case le.Constants.DEFLATED:var V=new Fa.Inflater(F,n.size);if(b)V.inflateAsync(function(K){K.copy(K,0),D&&(y(K)?D(K):D(K,le.Errors.BAD_CRC()))});else{if(V.inflate(B).copy(B,0),!y(B))throw le.Errors.BAD_CRC(`"${_.decode(i)}"`);return B}break;default:throw b&&D&&D(Buffer.alloc(0),le.Errors.UNKNOWN_METHOD()),le.Errors.UNKNOWN_METHOD()}}function I(b,D){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&D&&D(S()),S();if(d.length&&!c){var O;switch(n.method){case le.Constants.STORED:return n.compressedSize=n.size,O=Buffer.alloc(d.length),d.copy(O),b&&D&&D(O),O;default:case le.Constants.DEFLATED:var F=new Fa.Deflater(d);if(b)F.deflateAsync(function(V){O=Buffer.alloc(V.length),n.compressedSize=V.length,V.copy(O),D&&D(O)});else{var B=F.deflate();return n.compressedSize=B.length,B}F=null;break}}else if(b&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,D){return le.readBigUInt64LE(b,D)}function k(b){try{for(var D=0,O,F,B;D+4<b.length;)O=b.readUInt16LE(D),D+=2,F=b.readUInt16LE(D),D+=2,B=b.slice(D,D+F),D+=F,Te.ID_ZIP64===O&&P(B)}catch{throw le.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(b){var D,O,F,B;b.length>=Te.EF_ZIP64_SCOMP&&(D=A(b,Te.EF_ZIP64_SUNCOMP),n.size===Te.EF_ZIP64_OR_32&&(n.size=D)),b.length>=Te.EF_ZIP64_RHO&&(O=A(b,Te.EF_ZIP64_SCOMP),n.compressedSize===Te.EF_ZIP64_OR_32&&(n.compressedSize=O)),b.length>=Te.EF_ZIP64_DSN&&(F=A(b,Te.EF_ZIP64_RHO),n.offset===Te.EF_ZIP64_OR_32&&(n.offset=F)),b.length>=Te.EF_ZIP64_DSN+4&&(B=b.readUInt32LE(Te.EF_ZIP64_DSN),n.diskNumStart===Te.EF_ZIP64_OR_16&&(n.diskNumStart=B))}return{get entryName(){return _.decode(i)},get rawEntryName(){return i},set entryName(b){i=le.toBuffer(b,_.encode);var D=i[i.length-1];c=D===47||D===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,n.extraLength=b.length,k(b)},get comment(){return _.decode(s)},set comment(b){if(s=le.toBuffer(b,_.encode),n.commentLength=s.length,s.length>65535)throw le.Errors.COMMENT_TOO_LONG()},get name(){var b=_.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){d=le.toBuffer(b,le.decoder.encode),!c&&d.length?(n.size=d.length,n.method=le.Constants.DEFLATED,n.crc=le.crc32(b),n.changed=!0):n.method=le.Constants.STORED},getData:function(b){return n.changed?d:v(!1,null,b)},getDataAsync:function(b,D){n.changed?b(d):v(!0,b,D)},set attr(b){n.attr=b},get attr(){return n.attr},set header(b){n.loadFromBinary(b)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var b=n.centralHeaderToBinary(),D=le.Constants.CENHDR;return i.copy(b,D),D+=i.length,u.copy(b,D),D+=n.extraLength,s.copy(b,D),b},packLocalHeader:function(){let b=0;n.flags_efs=this.efs,n.extraLocalLength=h.length;let D=n.localHeaderToBinary(),O=Buffer.alloc(D.length+i.length+n.extraLocalLength);return D.copy(O,b),b+=D.length,i.copy(O,b),b+=i.length,h.copy(O,b),b+=h.length,O},toJSON:function(){let b=function(D){return"<"+(D&&D.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:b(e),data:b(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var xu=de((aI,hu)=>{var fu=za(),Im=Ba(),Ve=pr();hu.exports=function(t,e){var n=[],i={},s=Buffer.alloc(0),c=new Im.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:m,decoder:_}=x;t?v(x.readEntries):d=!0;function S(){let A=new Set;for(let k of Object.keys(i)){let P=k.split("/");if(P.pop(),!!P.length)for(let b=0;b<P.length;b++){let D=P.slice(0,b+1).join("/")+"/";A.add(D)}}for(let k of A)if(!(k in i)){let P=new fu(x);P.entryName=k,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,h.add(P)}}function y(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/Ve.Constants.CENHDR)throw Ve.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(c.diskEntries);for(var A=c.offset,k=0;k<n.length;k++){var P=A,b=new fu(x,t);b.header=t.slice(P,P+=Ve.Constants.CENHDR),b.entryName=t.slice(P,P+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(P,P+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(P,P+b.header.commentLength)),A+=b.header.centralHeaderSize,n[k]=b,i[b.entryName]=b}h.clear(),S()}function v(A){var k=t.length-Ve.Constants.ENDHDR,P=Math.max(0,k-65535),b=P,D=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),k;k>=b;k--)if(t[k]===80){if(t.readUInt32LE(k)===Ve.Constants.ENDSIG){O=k,F=k,D=k+Ve.Constants.ENDHDR,b=k-Ve.Constants.END64HDR;continue}if(t.readUInt32LE(k)===Ve.Constants.END64SIG){b=P;continue}if(t.readUInt32LE(k)===Ve.Constants.ZIP64SIG){O=k,D=k+Ve.readBigUInt64LE(t,k+Ve.Constants.ZIP64SIZE)+Ve.Constants.ZIP64LEAD;break}}if(O==-1)throw Ve.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,D)),c.commentLength&&(s=t.slice(F+Ve.Constants.ENDHDR)),A&&y()}function I(){n.length>1&&!m&&n.sort((A,k)=>A.entryName.toLowerCase().localeCompare(k.entryName.toLowerCase()))}return{get entries(){return d||y(),n.filter(A=>!h.has(A))},get comment(){return _.decode(s)},set comment(A){s=Ve.toBuffer(A,_.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,k=!0){d||y();let P=i[A];this.getEntryChildren(P,k).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let k=i[A],P=n.indexOf(k);P>=0&&(n.splice(P,1),delete i[A],c.totalEntries=n.length)},getEntryChildren:function(A,k=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&k){let P=[],b=A.entryName;for(let D of n)D.entryName.startsWith(b)&&P.push(D);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(){d||y(),I();let A=[],k=[],P=0,b=0;c.size=0,c.offset=0;let D=0;for(let B of this.entries){let V=B.getCompressedData();B.header.offset=b;let K=B.packLocalHeader(),te=K.length+V.length;b+=te,A.push(K),A.push(V);let Z=B.packCentralHeader();k.push(Z),c.size+=Z.length,P+=te+Z.length,D++}P+=c.mainHeaderSize,c.offset=b,c.totalEntries=D,b=0;let O=Buffer.alloc(P);for(let B of A)B.copy(O,b),b+=B.length;for(let B of k)B.copy(O,b),b+=B.length;let F=c.toBinary();return s&&s.copy(F,Ve.Constants.ENDHDR),F.copy(O,b),t=O,d=!1,O},toAsyncBuffer:function(A,k,P,b){try{d||y(),I();let D=[],O=[],F=0,B=0,V=0;c.size=0,c.offset=0;let K=function(te){if(te.length>0){let Z=te.shift(),ae=Z.entryName+Z.extra.toString();P&&P(ae),Z.getCompressedDataAsync(function(ce){b&&b(ae),Z.header.offset=B;let R=Z.packLocalHeader(),U=R.length+ce.length;B+=U,D.push(R),D.push(ce);let j=Z.packCentralHeader();O.push(j),c.size+=j.length,F+=U+j.length,V++,K(te)})}else{F+=c.mainHeaderSize,c.offset=B,c.totalEntries=V,B=0;let Z=Buffer.alloc(F);D.forEach(function(ce){ce.copy(Z,B),B+=ce.length}),O.forEach(function(ce){ce.copy(Z,B),B+=ce.length});let ae=c.toBinary();s&&s.copy(ae,Ve.Constants.ENDHDR),ae.copy(Z,B),t=Z,d=!1,A(Z)}};K(Array.from(this.entries))}catch(D){k(D)}}}}});var mu=de((cI,gu)=>{var Ie=pr(),Se=he("path"),Am=za(),Tm=xu(),Nn=(...t)=>Ie.findLast(t,e=>typeof e=="boolean"),pu=(...t)=>Ie.findLast(t,e=>typeof e=="string"),km=(...t)=>Ie.findLast(t,e=>typeof e=="function"),Cm={noSort:!1,readEntries:!1,method:Ie.Constants.NONE,fs:null};gu.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),Cm);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=Ie.Constants.BUFFER,t=void 0)),Object.assign(i,e);let s=new Ie(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ie.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))i.method=Ie.Constants.FILE,i.filename=t,n=s.fs.readFileSync(t);else throw Ie.Errors.INVALID_FILENAME();let c=new Tm(n,i),{canonical:d,sanitize:u,zipnamefix:h}=Ie;function x(y){if(y&&c){var v;if(typeof y=="string"&&(v=c.getEntry(Se.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(v=c.getEntry(y.entryName)),v)return v}return null}function m(y){let{join:v,normalize:I,sep:A}=Se.posix;return v(Se.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function _(y){return y instanceof RegExp?(function(v){return function(I){return v.test(I)}})(y):typeof y!="function"?()=>!0:y}let S=(y,v)=>{let I=v.slice(-1);return I=I===s.sep?s.sep:"",Se.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(k,P){if(P){v(k,P);return}k&&k.length?v(k.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?m(v):"";let k=Se.win32.basename(Se.win32.normalize(y));v+=I||k;let P=s.fs.statSync(y),b=P.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);P.isDirectory()&&(v+=s.sep),this.addFile(v,b,A,P)}else throw Ie.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,v){y=typeof y=="object"?y:{localPath:y};let I=Se.resolve(y.localPath),{comment:A}=y,{zipPath:k,zipName:P}=y,b=this;s.fs.stat(I,function(D,O){if(D)return v(D,!1);k=k?m(k):"";let F=Se.win32.basename(Se.win32.normalize(I));if(k+=P||F,O.isFile())s.fs.readFile(I,function(B,V){return B?v(B,!1):(b.addFile(k,V,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return k+=s.sep,b.addFile(k,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(y,v,I){if(I=_(I),v=v?m(v):"",y=Se.normalize(y),s.fs.existsSync(y)){let A=s.findFiles(y),k=this;if(A.length)for(let P of A){let b=Se.join(v,S(y,P));I(b)&&k.addLocalFile(P,Se.dirname(b))}}else throw Ie.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,v,I,A){A=_(A),I=I?m(I):"",y=Se.normalize(y);var k=this;s.fs.open(y,"r",function(P){if(P&&P.code==="ENOENT")v(void 0,Ie.Errors.FILE_NOT_FOUND(y));else if(P)v(void 0,P);else{var b=s.findFiles(y),D=-1,O=function(){if(D+=1,D<b.length){var F=b[D],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(V,K){V&&v(void 0,V),K.isFile()?s.fs.readFile(F,function(te,Z){te?v(void 0,te):(k.addFile(I+B,Z,"",K),O())}):(k.addFile(I+B+"/",Buffer.alloc(0),"",K),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=Se.resolve(m(y.localPath));let{zipPath:A,filter:k,namefix:P}=y;k instanceof RegExp?k=(function(O){return function(F){return O.test(F)}})(k):typeof k!="function"&&(k=function(){return!0}),A=A?m(A):"",P=="latin1"&&(P=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=O=>O);let b=O=>Se.join(A,P(S(localPath,O))),D=O=>Se.win32.basename(Se.win32.normalize(P(O)));s.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?v(void 0,Ie.Errors.FILE_NOT_FOUND(localPath)):O?v(void 0,O):s.findFilesAsync(localPath,function(F,B){if(F)return v(F);B=B.filter(V=>k(b(V))),B.length||v(void 0,!1),setImmediate(B.reverse().reduce(function(V,K){return function(te,Z){if(te||Z===!1)return setImmediate(V,te,!1);I.addLocalFileAsync({localPath:K,zipPath:Se.dirname(b(K)),zipName:D(K)},V)}},v))})})},addLocalFolderPromise:function(y,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},v),(k,P)=>{k&&A(k),P&&I(this)})})},addFile:function(y,v,I,A){y=h(y);let k=x(y),P=k!=null;P||(k=new Am(i),k.entryName=y),k.comment=I||"";let b=typeof A=="object"&&A instanceof s.fs.Stats;b&&(k.header.time=A.mtime);var D=k.isDirectory?16:0;let O=k.isDirectory?16384:32768;return b?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=k.isDirectory?493:420,D=(D|O<<16)>>>0,k.attr=D,k.setData(v),P||c.setEntry(k),k},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,k,P){A=Nn(!1,A),k=Nn(!1,k),I=Nn(!0,I),P=pu(k,P);var b=x(y);if(!b)throw Ie.Errors.NO_ENTRY();var D=d(b.entryName),O=u(v,P&&!b.isDirectory?P:I?D:Se.basename(D));if(b.isDirectory){var F=c.getEntryChildren(b);return F.forEach(function(K){if(K.isDirectory)return;var te=K.getData();if(!te)throw Ie.Errors.CANT_EXTRACT_FILE();var Z=d(K.entryName),ae=u(v,I?Z:Se.basename(Z));let ce=k?K.header.fileAttr:void 0;s.writeFileTo(ae,te,A,ce)}),!0}var B=b.getData(c.password);if(!B)throw Ie.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(O)&&!A)throw Ie.Errors.CANT_OVERRIDE();let V=k?y.header.fileAttr:void 0;return s.writeFileTo(O,B,A,V),!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=Nn(!1,I),A=pu(I,A),v=Nn(!1,v),!c)throw Ie.Errors.NO_ZIP();c.entries.forEach(function(k){var P=u(y,d(k.entryName));if(k.isDirectory){s.makeDir(P);return}var b=k.getData(A);if(!b)throw Ie.Errors.CANT_EXTRACT_FILE();let D=I?k.header.fileAttr:void 0;s.writeFileTo(P,b,v,D);try{s.fs.utimesSync(P,k.header.time,k.header.time)}catch{throw Ie.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,v,I,A){if(A=km(v,I,A),I=Nn(!1,I),v=Nn(!1,v),!A)return new Promise((O,F)=>{this.extractAllToAsync(y,v,I,function(B){B?F(B):O(this)})});if(!c){A(Ie.Errors.NO_ZIP());return}y=Se.resolve(y);let k=O=>u(y,Se.normalize(d(O.entryName))),P=(O,F)=>new Error(O+': "'+F+'"'),b=[],D=[];c.entries.forEach(O=>{O.isDirectory?b.push(O):D.push(O)});for(let O of b){let F=k(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(P("Unable to create folder",F))}}D.reverse().reduce(function(O,F){return function(B){if(B)O(B);else{let V=Se.normalize(d(F.entryName)),K=u(y,V);F.getDataAsync(function(te,Z){if(Z)O(Z);else if(!te)O(Ie.Errors.CANT_EXTRACT_FILE());else{let ae=I?F.header.fileAttr:void 0;s.writeFileToAsync(K,te,v,ae,function(ce){ce||O(P("Unable to write file",K)),s.fs.utimes(K,F.header.time,F.header.time,function(R){R?O(P("Unable to set times",K)):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((k,P)=>{!y&&i.filename&&(y=i.filename),y||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let D=O=>O?k(O):P("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(y,b,I,A,D)},P)})},toBufferPromise:function(){return new Promise((y,v)=>{c.toAsyncBuffer(y,v)})},toBuffer:function(y,v,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,v,I,A),null):c.compressToBuffer()}}}});import{execFile as N_,spawn as M_,spawnSync as AA}from"node:child_process";import{promisify as B_}from"node:util";function z_(t){if(process.platform!=="win32")return!1;if(Bf.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(Bf,"").toLowerCase();return F_.has(n)}function Ff(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return z_(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function st(t,e=[],n={}){return M_(t,e,Ff(t,n))}function zf(t,e=[],n={}){return U_(t,e,Ff(t,n))}var F_,Bf,U_,Zt=rt(()=>{"use strict";F_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Bf=/\.(cmd|bat|ps1)$/i;U_=B_(N_)});var Xt=de((aD,yh)=>{"use strict";var wh=["nodebuffer","arraybuffer","fragments"],_h=typeof Blob<"u";_h&&wh.push("blob");yh.exports={BINARY_TYPES:wh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:_h,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Zi=de((cD,Ro)=>{"use strict";var{EMPTY_BUFFER:pE}=Xt(),gd=Buffer[Symbol.species];function gE(t,e){if(t.length===0)return pE;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 gd(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 Eh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function mE(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function md(t){if(md.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new gd(t):ArrayBuffer.isView(t)?e=new gd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),md.readOnly=!1),e}Ro.exports={concat:gE,mask:bh,toArrayBuffer:mE,toBuffer:md,unmask:Eh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=he("bufferutil");Ro.exports.mask=function(e,n,i,s,c){c<48?bh(e,n,i,s,c):t.mask(e,n,i,s,c)},Ro.exports.unmask=function(e,n){e.length<32?Eh(e,n):t.unmask(e,n)}}catch{}});var Ih=de((dD,Sh)=>{"use strict";var vh=Symbol("kDone"),wd=Symbol("kRun"),_d=class{constructor(e){this[vh]=()=>{this.pending--,this[wd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[wd]()}[wd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[vh])}}};Sh.exports=_d});var qr=de((lD,Ch)=>{"use strict";var Yi=he("zlib"),Ah=Zi(),wE=Ih(),{kStatusCode:Th}=Xt(),_E=Buffer[Symbol.species],yE=Buffer.from([0,0,255,255]),Oo=Symbol("permessage-deflate"),Qt=Symbol("total-length"),Ur=Symbol("callback"),Dn=Symbol("buffers"),Gr=Symbol("error"),Po,yd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Po){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Po=new wE(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[Ur];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){Po.add(s=>{this._decompress(e,n,(c,d)=>{s(),i(c,d)})})}compress(e,n,i){Po.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"?Yi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Yi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Oo]=this,this._inflate[Qt]=0,this._inflate[Dn]=[],this._inflate.on("error",EE),this._inflate.on("data",kh)}this._inflate[Ur]=i,this._inflate.write(e),n&&this._inflate.write(yE),this._inflate.flush(()=>{let c=this._inflate[Gr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Ah.concat(this._inflate[Dn],this._inflate[Qt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Qt]=0,this._inflate[Dn]=[],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"?Yi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Yi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Qt]=0,this._deflate[Dn]=[],this._deflate.on("data",bE)}this._deflate[Ur]=i,this._deflate.write(e),this._deflate.flush(Yi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Ah.concat(this._deflate[Dn],this._deflate[Qt]);n&&(c=new _E(c.buffer,c.byteOffset,c.length-4)),this._deflate[Ur]=null,this._deflate[Qt]=0,this._deflate[Dn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Ch.exports=yd;function bE(t){this[Dn].push(t),this[Qt]+=t.length}function kh(t){if(this[Qt]+=t.length,this[Oo]._maxPayload<1||this[Qt]<=this[Oo]._maxPayload){this[Dn].push(t);return}this[Gr]=new RangeError("Max payload size exceeded"),this[Gr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Gr][Th]=1009,this.removeListener("data",kh),this.reset()}function EE(t){if(this[Oo]._inflate=null,this[Gr]){this[Ur](this[Gr]);return}t[Th]=1007,this[Ur](t)}});var Hr=de((uD,Lo)=>{"use strict";var{isUtf8:Dh}=he("buffer"),{hasBlob:vE}=Xt(),SE=[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 IE(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function bd(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 AE(t){return vE&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Lo.exports={isBlob:AE,isValidStatusCode:IE,isValidUTF8:bd,tokenChars:SE};if(Dh)Lo.exports.isValidUTF8=function(t){return t.length<24?bd(t):Dh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=he("utf-8-validate");Lo.exports.isValidUTF8=function(e){return e.length<32?bd(e):t(e)}}catch{}});var Ad=de((fD,Bh)=>{"use strict";var{Writable:TE}=he("stream"),Rh=qr(),{BINARY_TYPES:kE,EMPTY_BUFFER:Ph,kStatusCode:CE,kWebSocket:DE}=Xt(),{concat:Ed,toArrayBuffer:RE,unmask:PE}=Zi(),{isValidStatusCode:OE,isValidUTF8:Oh}=Hr(),No=Buffer[Symbol.species],pt=0,Lh=1,Nh=2,Mh=3,vd=4,Sd=5,Mo=6,Id=class extends TE{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||kE[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[DE]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=pt}_write(e,n,i){if(this._opcode===8&&this._state==pt)return i();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 No(i.buffer,i.byteOffset+e,i.length-e),new No(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 No(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case pt:this.getInfo(e);break;case Lh:this.getPayloadLength16(e);break;case Nh:this.getPayloadLength64(e);break;case Mh:this.getMask();break;case vd:this.getData(e);break;case Sd:case Mo: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[Rh.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=Lh:this._payloadLength===127?this._state=Nh: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=Mh:this._state=vd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vd}getData(e){let n=Ph;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&&PE(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Sd,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[Rh.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===pt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=pt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ed(i,n):this._binaryType==="arraybuffer"?s=RE(Ed(i,n)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=pt):(this._state=Mo,setImmediate(()=>{this.emit("message",s,!0),this._state=pt,this.startLoop(e)}))}else{let s=Ed(i,n);if(!this._skipUTF8Validation&&!Oh(s)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Sd||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=pt):(this._state=Mo,setImmediate(()=>{this.emit("message",s,!1),this._state=pt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ph),this.end();else{let i=e.readUInt16BE(0);if(!OE(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(c);return}let s=new No(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Oh(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=pt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=pt):(this._state=Mo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=pt,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[CE]=s,d}};Bh.exports=Id});var Cd=de((xD,Uh)=>{"use strict";var{Duplex:hD}=he("stream"),{randomFillSync:LE}=he("crypto"),{types:{isUint8Array:NE}}=he("util"),Fh=qr(),{EMPTY_BUFFER:ME,kWebSocket:BE,NOOP:FE}=Xt(),{isBlob:jr,isValidStatusCode:zE}=Hr(),{mask:zh,toBuffer:Yn}=Zi(),gt=Symbol("kByteLength"),UE=Buffer.alloc(4),Bo=8*1024,Xn,Wr=Bo,It=0,GE=1,qE=2,Td=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=It,this.onerror=FE,this[BE]=void 0}static frame(e,n){let i,s=!1,c=2,d=!1;n.mask&&(i=n.maskBuffer||UE,n.generateMask?n.generateMask(i):(Wr===Bo&&(Xn===void 0&&(Xn=Buffer.alloc(Bo)),LE(Xn,0,Bo),Wr=0),i[0]=Xn[Wr++],i[1]=Xn[Wr++],i[2]=Xn[Wr++],i[3]=Xn[Wr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!n.mask||d)&&n[gt]!==void 0?u=n[gt]:(e=Buffer.from(e),u=e.length):(u=e.length,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?(zh(e,i,x,c,u),[x]):(zh(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,s){let c;if(e===void 0)c=ME;else{if(typeof e!="number"||!zE(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(NE(n))c.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[gt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==It?this.enqueue([this.dispatch,c,!1,d,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):jr(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={[gt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};jr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let s,c;if(typeof e=="string"?(s=Buffer.byteLength(e),c=!1):jr(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={[gt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};jr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let s=this._extensions[Fh.extensionName],c=n.binary?2:1,d=n.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):jr(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={[gt]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:d};jr(e)?this._state!==It?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==It?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,s){this._bufferedBytes+=i[gt],this._state=qE,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(kd,this,u,s);return}this._bufferedBytes-=i[gt];let d=Yn(c);n?this.dispatch(d,n,i,s):(this._state=It,this.sendFrame(t.frame(d,i),s),this.dequeue())}).catch(c=>{process.nextTick(HE,this,c,s)})}dispatch(e,n,i,s){if(!n){this.sendFrame(t.frame(e,i),s);return}let c=this._extensions[Fh.extensionName];this._bufferedBytes+=i[gt],this._state=GE,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");kd(this,h,s);return}this._bufferedBytes-=i[gt],this._state=It,i.readOnly=!1,this.sendFrame(t.frame(u,i),s),this.dequeue()})}dequeue(){for(;this._state===It&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][gt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][gt],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Uh.exports=Td;function kd(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 HE(t,e,n){kd(t,e,n),t.onerror(e)}});var Jh=de((pD,Vh)=>{"use strict";var{kForOnEventAttribute:Xi,kListener:Dd}=Xt(),Gh=Symbol("kCode"),qh=Symbol("kData"),Hh=Symbol("kError"),jh=Symbol("kMessage"),Wh=Symbol("kReason"),Kr=Symbol("kTarget"),Kh=Symbol("kType"),$h=Symbol("kWasClean"),en=class{constructor(e){this[Kr]=null,this[Kh]=e}get target(){return this[Kr]}get type(){return this[Kh]}};Object.defineProperty(en.prototype,"target",{enumerable:!0});Object.defineProperty(en.prototype,"type",{enumerable:!0});var Qn=class extends en{constructor(e,n={}){super(e),this[Gh]=n.code===void 0?0:n.code,this[Wh]=n.reason===void 0?"":n.reason,this[$h]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Gh]}get reason(){return this[Wh]}get wasClean(){return this[$h]}};Object.defineProperty(Qn.prototype,"code",{enumerable:!0});Object.defineProperty(Qn.prototype,"reason",{enumerable:!0});Object.defineProperty(Qn.prototype,"wasClean",{enumerable:!0});var $r=class extends en{constructor(e,n={}){super(e),this[Hh]=n.error===void 0?null:n.error,this[jh]=n.message===void 0?"":n.message}get error(){return this[Hh]}get message(){return this[jh]}};Object.defineProperty($r.prototype,"error",{enumerable:!0});Object.defineProperty($r.prototype,"message",{enumerable:!0});var Qi=class extends en{constructor(e,n={}){super(e),this[qh]=n.data===void 0?null:n.data}get data(){return this[qh]}};Object.defineProperty(Qi.prototype,"data",{enumerable:!0});var jE={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Xi]&&s[Dd]===e&&!s[Xi])return;let i;if(t==="message")i=function(c,d){let u=new Qi("message",{data:d?c:c.toString()});u[Kr]=this,Fo(e,this,u)};else if(t==="close")i=function(c,d){let u=new Qn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Kr]=this,Fo(e,this,u)};else if(t==="error")i=function(c){let d=new $r("error",{error:c,message:c.message});d[Kr]=this,Fo(e,this,d)};else if(t==="open")i=function(){let c=new en("open");c[Kr]=this,Fo(e,this,c)};else return;i[Xi]=!!n[Xi],i[Dd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Dd]===e&&!n[Xi]){this.removeListener(t,n);break}}};Vh.exports={CloseEvent:Qn,ErrorEvent:$r,Event:en,EventTarget:jE,MessageEvent:Qi};function Fo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var zo=de((gD,Zh)=>{"use strict";var{tokenChars:es}=Hr();function Bt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function WE(t){let e=Object.create(null),n=Object.create(null),i=!1,s=!1,c=!1,d,u,h=-1,x=-1,m=-1,_=0;for(;_<t.length;_++)if(x=t.charCodeAt(_),d===void 0)if(m===-1&&es[x]===1)h===-1&&(h=_);else if(_!==0&&(x===32||x===9))m===-1&&h!==-1&&(m=_);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_);let y=t.slice(h,m);x===44?(Bt(e,y,n),n=Object.create(null)):d=y,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(u===void 0)if(m===-1&&es[x]===1)h===-1&&(h=_);else if(x===32||x===9)m===-1&&h!==-1&&(m=_);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_),Bt(n,t.slice(h,m),!0),x===44&&(Bt(e,d,n),n=Object.create(null),d=void 0),h=m=-1}else if(x===61&&h!==-1&&m===-1)u=t.slice(h,_),h=m=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(s){if(es[x]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);h===-1?h=_:i||(i=!0),s=!1}else if(c)if(es[x]===1)h===-1&&(h=_);else if(x===34&&h!==-1)c=!1,m=_;else if(x===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(x===34&&t.charCodeAt(_-1)===61)c=!0;else if(m===-1&&es[x]===1)h===-1&&(h=_);else if(h!==-1&&(x===32||x===9))m===-1&&(m=_);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_);let y=t.slice(h,m);i&&(y=y.replace(/\\/g,""),i=!1),Bt(n,u,y),x===44&&(Bt(e,d,n),n=Object.create(null),d=void 0),u=void 0,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=_);let S=t.slice(h,m);return d===void 0?Bt(e,S,n):(u===void 0?Bt(n,S,!0):i?Bt(n,u,S.replace(/\\/g,"")):Bt(n,u,S),Bt(e,d,n)),e}function KE(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:KE,parse:WE}});var Ho=de((_D,cx)=>{"use strict";var $E=he("events"),VE=he("https"),JE=he("http"),Qh=he("net"),ZE=he("tls"),{randomBytes:YE,createHash:XE}=he("crypto"),{Duplex:mD,Readable:wD}=he("stream"),{URL:Rd}=he("url"),Rn=qr(),QE=Ad(),ev=Cd(),{isBlob:tv}=Hr(),{BINARY_TYPES:Yh,CLOSE_TIMEOUT:nv,EMPTY_BUFFER:Uo,GUID:rv,kForOnEventAttribute:Pd,kListener:iv,kStatusCode:sv,kWebSocket:We,NOOP:ex}=Xt(),{EventTarget:{addEventListener:ov,removeEventListener:av}}=Jh(),{format:cv,parse:dv}=zo(),{toBuffer:lv}=Zi(),tx=Symbol("kAborted"),Od=[8,13],tn=["CONNECTING","OPEN","CLOSING","CLOSED"],uv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,be=class t extends $E{constructor(e,n,i){super(),this._binaryType=Yh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Uo,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]),nx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yh.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let s=new QE({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 ev(e,this._extensions,i.generateMask);this._receiver=s,this._sender=c,this._socket=e,s[We]=this,c[We]=this,e[We]=this,s.on("conclude",xv),s.on("drain",pv),s.on("error",gv),s.on("message",mv),s.on("ping",wv),s.on("pong",_v),c.onerror=yv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",sx),e.on("data",qo),e.on("end",ox),e.on("error",ax),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){dt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ix(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){Ld(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Uo,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){Ld(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Uo,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){Ld(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||Uo,s,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(be,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(be.prototype,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(be,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(be.prototype,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(be,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(be.prototype,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(be,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});Object.defineProperty(be.prototype,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(be.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(be.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Pd])return e[iv];return null},set(e){for(let n of this.listeners(t))if(n[Pd]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Pd]:!0})}})});be.prototype.addEventListener=ov;be.prototype.removeEventListener=av;cx.exports=be;function nx(t,e,n,i){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:nv,protocolVersion:Od[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Od.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Od.join(", ")})`);let c;if(e instanceof Rd)c=e;else try{c=new Rd(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;Go(t,I);return}let x=d?443:80,m=YE(16).toString("base64"),_=d?VE.request:JE.request,S=new Set,y;if(s.createConnection=s.createConnection||(d?hv:fv),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":m,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"]=cv({[Rn.extensionName]:y.offer()})),n.length){for(let I of n){if(typeof I!="string"||!uv.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,k]of Object.entries(I))i.headers[A.toLowerCase()]=k}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=_(s),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=_(s);s.timeout&&v.on("timeout",()=>{dt(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[tx]||(v=t._req=null,Go(t,I))}),v.on("response",I=>{let A=I.headers.location,k=I.statusCode;if(A&&s.followRedirects&&k>=300&&k<400){if(++t._redirects>s.maxRedirects){dt(t,v,"Maximum redirects exceeded");return}v.abort();let P;try{P=new Rd(A,e)}catch{let D=new SyntaxError(`Invalid URL: ${A}`);Go(t,D);return}nx(t,P,n,i)}else t.emit("unexpected-response",v,I)||dt(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,k)=>{if(t.emit("upgrade",I),t.readyState!==be.CONNECTING)return;v=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){dt(t,A,"Invalid Upgrade header");return}let b=XE("sha1").update(m+rv).digest("base64");if(I.headers["sec-websocket-accept"]!==b){dt(t,A,"Invalid Sec-WebSocket-Accept header");return}let D=I.headers["sec-websocket-protocol"],O;if(D!==void 0?S.size?S.has(D)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":S.size&&(O="Server sent no subprotocol"),O){dt(t,A,O);return}D&&(t._protocol=D);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!y){dt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=dv(F)}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(B);if(V.length!==1||V[0]!==Rn.extensionName){dt(t,A,"Server indicated an extension that was not requested");return}try{y.accept(B[Rn.extensionName])}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Rn.extensionName]=y}t.setSocket(A,k,{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 Go(t,e){t._readyState=be.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function fv(t){return t.path=t.socketPath,Qh.connect(t)}function hv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Qh.isIP(t.host)?"":t.host),ZE.connect(t)}function dt(t,e,n){t._readyState=be.CLOSING;let i=new Error(n);Error.captureStackTrace(i,dt),e.setHeader?(e[tx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Go,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ld(t,e,n){if(e){let i=tv(e)?e.size:lv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${tn[t.readyState]})`);process.nextTick(n,i)}}function xv(t,e){let n=this[We];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[We]!==void 0&&(n._socket.removeListener("data",qo),process.nextTick(rx,n._socket),t===1005?n.close():n.close(t,e))}function pv(){let t=this[We];t.isPaused||t._socket.resume()}function gv(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",qo),process.nextTick(rx,e._socket),e.close(t[sv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Xh(){this[We].emitClose()}function mv(t,e){this[We].emit("message",t,e)}function wv(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,ex),e.emit("ping",t)}function _v(t){this[We].emit("pong",t)}function rx(t){t.resume()}function yv(t){let e=this[We];e.readyState!==be.CLOSED&&(e.readyState===be.OPEN&&(e._readyState=be.CLOSING,ix(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ix(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function sx(){let t=this[We];if(this.removeListener("close",sx),this.removeListener("data",qo),this.removeListener("end",ox),t._readyState=be.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Xh),t._receiver.on("finish",Xh))}function qo(t){this[We]._receiver.write(t)||this.pause()}function ox(){let t=this[We];t._readyState=be.CLOSING,t._receiver.end(),this.end()}function ax(){let t=this[We];this.removeListener("error",ax),this.on("error",ex),t&&(t._readyState=be.CLOSING,this.destroy())}});var fx=de((bD,ux)=>{"use strict";var yD=Ho(),{Duplex:bv}=he("stream");function dx(t){t.emit("close")}function Ev(){!this.destroyed&&this._writableState.finished&&this.destroy()}function lx(t){this.removeListener("error",lx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function vv(t,e){let n=!0,i=new bv({...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(dx,i);return}let d=!1;t.once("error",function(h){d=!0,c(h)}),t.once("close",function(){d||c(s),process.nextTick(dx,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",Ev),i.on("error",lx),i}ux.exports=vv});var Nd=de((ED,hx)=>{"use strict";var{tokenChars:Sv}=Hr();function Iv(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&&Sv[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}hx.exports={parse:Iv}});var bx=de((SD,yx)=>{"use strict";var Av=he("events"),jo=he("http"),{Duplex:vD}=he("stream"),{createHash:Tv}=he("crypto"),xx=zo(),er=qr(),kv=Nd(),Cv=Ho(),{CLOSE_TIMEOUT:Dv,GUID:Rv,kWebSocket:Pv}=Xt(),Ov=/^[+/0-9A-Za-z]{22}==$/,px=0,gx=1,_x=2,Md=class extends Av{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:Dv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Cv,...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=jo.createServer((i,s)=>{let c=jo.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=Lv(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=px}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===_x){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ts,this);return}if(e&&this.once("close",e),this._state!==gx)if(this._state=gx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ts,this):process.nextTick(ts,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ts(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",mx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){tr(this,e,n,400,"Invalid Upgrade header");return}if(c===void 0||!Ov.test(c)){tr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){tr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ns(n,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=kv.parse(h)}catch{tr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&m!==void 0){let S=new er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=xx.parse(m);y[er.extensionName]&&(S.accept(y[er.extensionName]),_[er.extensionName]=S)}catch{tr(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 ns(n,v||401,I,A);this.completeUpgrade(_,c,x,e,n,i,s)});return}if(!this.options.verifyClient(S))return ns(n,401)}this.completeUpgrade(_,c,x,e,n,i,s)}completeUpgrade(e,n,i,s,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[Pv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>px)return ns(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Tv("sha1").update(n+Rv).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let _=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;_&&(x.push(`Sec-WebSocket-Protocol: ${_}`),m._protocol=_)}if(e[er.extensionName]){let _=e[er.extensionName].params,S=xx.format({[er.extensionName]:[_]});x.push(`Sec-WebSocket-Extensions: ${S}`),m._extensions=e}this.emit("headers",x,s),c.write(x.concat(`\r
8
+ var bg=Object.create;var Ta=Object.defineProperty;var vg=Object.getOwnPropertyDescriptor;var Sg=Object.getOwnPropertyNames;var Ig=Object.getPrototypeOf,Ag=Object.prototype.hasOwnProperty;var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var nt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ca=(t,e)=>{for(var r in e)Ta(t,r,{get:e[r],enumerable:!0})},kg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Sg(e))!Ag.call(t,o)&&o!==r&&Ta(t,o,{get:()=>e[o],enumerable:!(i=vg(e,o))||i.enumerable});return t};var Ht=(t,e,r)=>(r=t!=null?bg(Ig(t)):{},kg(e||!t||!t.__esModule?Ta(r,"default",{value:t,enumerable:!0}):r,t));function Je(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var cr=nt(()=>{"use strict"});import{createWriteStream as Tg,mkdirSync as Cg,readdirSync as Rg,unlinkSync as Dg}from"node:fs";import{join as vl}from"node:path";function Ln(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function dr(t,e){return`${t}-${e}.log`}function Ra(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function Pg(t,e,r){let i=c=>{let[l,u,f]=c.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>r}function us(t,e,r,i){let o;try{o=Rg(t)}catch{return}for(let c of o){let l=Ra(c,e);if(l&&Pg(l,r,i))try{Dg(vl(t,c))}catch{}}}var ni,Da=nt(()=>{"use strict";ni=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Ln(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let r=this.clock();r!==this.currentDate&&this.rotate(r),this.stream?.write(e)}rotate(e){this.stream?.end();try{Cg(this.dir,{recursive:!0});let r=Tg(vl(this.dir,dr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
+ `)),this.stream=r}catch(r){process.stderr.write(`[log-sink] rotate failed: ${String(r)}
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&us(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Og,mkdirSync as Lg}from"node:fs";import{join as Ng}from"node:path";function Il(t){let e=t.retentionDays??Fg,r=t.clock??(()=>Ln(new Date));hs={bridgeSink:new ni(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ni(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();us(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])us(t.agentLogsDir(o),"agent",i,e)}function zg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Al(t){Pa=t}function kl(t){return lr[Pa]<=lr[t]}function Tl(t,e){let r=lr[t];return r===void 0?!0:r>=lr[e]}function xs(t){Sl={...t}}function Cl(t){let e=(u,f=2)=>String(u).padStart(f,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),l=e(o%60);return`${Ln(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${l}`}function kt(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Cl(new Date),level:e,module:r,msg:i,...o})}
11
+ `;Lg(t,{recursive:!0}),Og(Ng(t,dr("bridge",Ln(new Date))),c)}catch{}}function Ug(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function fs(t,e,r,i,o){if(lr[t]<lr[Pa])return;let c=`${JSON.stringify({ts:Cl(new Date),level:t,module:e,msg:r,...Sl,...i})}
12
+ `;if(hs){let l=Ug(o,i),u=l?zg(hs,l):hs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Bg.write(c):Mg.write(c)}function H(t,e){return{debug:(r,i)=>fs("debug",t,r,i,e),info:(r,i)=>fs("info",t,r,i,e),warn:(r,i)=>fs("warn",t,r,i,e),error:(r,i)=>fs("error",t,r,i,e),child:r=>H(`${t}.${r}`,e),forAgent:r=>H(t,r)}}var lr,Pa,Mg,Bg,Sl,Fg,hs,ne=nt(()=>{"use strict";cr();Da();lr={debug:10,info:20,warn:30,error:40},Pa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Mg=process.stdout,Bg=process.stderr,Sl={},Fg=Je("COZE_BRIDGE_LOG_RETENTION_DAYS",30),hs=null});var k,We=nt(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Ol={};Ca(Ol,{ACP_WRAPPER_NPM_PACKAGES:()=>ri,_resetAcpInstallerForTests:()=>Wg,_setBinaryPathCacheForTests:()=>$g,buildAcpSpawn:()=>ii,ensureAcpInstalled:()=>fr,getAcpBinaryPath:()=>gs,pickWhichLine:()=>Na,probeAcpVersion:()=>Kg,resolveAcpCommand:()=>Pl});import{readFileSync as Rl}from"node:fs";import{createRequire as Hg}from"node:module";import{dirname as Gg,resolve as qg}from"node:path";function La(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Na(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function jg(t){let e=Dl.resolve(`${t.npmPackage}/package.json`),r=Gg(e),i=JSON.parse(Rl(e,"utf8")),o=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!o)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return qg(r,o)}async function fr(t,e){let r=Oa[t];if(!r)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ur.get(t);if(i)return i;let o=La(t);if(o)return ur.set(t,o),ps.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let c=jg(r);return ur.set(t,c),ps.info("acp wrapper resolved",{framework:t,binary:r.binary,path:c}),c}catch(c){throw ps.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(c)}),new k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
+ `),{cause:c})}}async function Kg(t){let e=Oa[t];if(e)try{let r=Dl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Rl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){ps.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function gs(t){return ur.get(t)}function Pl(t,e){if(e)return e;let r=La(t);if(r)return r;let i=gs(t);if(!i)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function ii(t,e,r){if(e)return{command:e,args:[...r]};let i=La(t);if(i)return{command:i,args:[...r]};let o=Pl(t);return{command:process.execPath,args:[o,...r]}}function Wg(){ur.clear()}function $g(t,e){ur.set(t,e)}var ps,Oa,ri,Dl,ur,on=nt(()=>{"use strict";We();ne();ps=H("agents.acp-installer"),Oa={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},ri=Object.values(Oa).filter(t=>t!==void 0).map(t=>t.npmPackage),Dl=Hg(import.meta.url),ur=new Map});import{chmod as Jg,mkdir as Zg,readFile as Yg,rename as Xg,rm as Qg,writeFile as em}from"node:fs/promises";import{dirname as tm}from"node:path";async function an(t){try{let e=await Yg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function cn(t,e,r){await Zg(tm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await em(i,e,{encoding:"utf8",mode:r?.mode}),await Xg(i,t),r?.mode!==void 0&&await Jg(t,r.mode)}catch(o){throw await Qg(i,{force:!0}).catch(()=>{}),o}}async function dn(t,e,r){await cn(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var ln=nt(()=>{"use strict"});import{promises as Ml,readdirSync as nm}from"node:fs";import{homedir as rm}from"node:os";import{sep as im,join as Ce,resolve as Bl}from"node:path";function Y(t){let e=t??rm(),r=Ce(e,".coze"),i=Ce(r,"bridge"),o=Ce(i,"lib"),c=Ce(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Ce(o,"index.js"),binDir:Ce(i,"bin"),pidFile:Ce(i,"bridge.pid"),portFile:Ce(i,"bridge.port"),tokenFile:Ce(i,"bridge.token"),patTokenFile:Ce(i,"pat-token"),agentEnvFile:Ce(i,"agent-env.json"),logFile:Ce(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Ce(c,"daemon-stdio.log"),installLock:Ce(i,"install.lock"),configFile:Ce(i,"config.json"),agentsRoot:Ce(r,"agents")}}function Ze(t,e=Y()){let r=Ce(e.agentsRoot,t);return{root:r,config:Ce(r,"config.json"),workspace:Ce(r,"workspace"),logs:Ce(r,"logs")}}function ms(t=Y()){try{return nm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function si(t,e){let r=await Ml.realpath(Bl(t)).catch(()=>null);if(!r)return!1;let i=await Ml.realpath(Bl(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?r.toLowerCase():r,c=process.platform==="win32"?i.toLowerCase():i;return o===c||o.startsWith(c+im)}var Re=nt(()=>{"use strict"});var _s={};Ca(_s,{AGENT_CONFIG_FILE_MODE:()=>ws,enforceAgentConfigMode:()=>am,loadAgentConfig:()=>De,persistAgentSessions:()=>oi,persistAgentSkills:()=>ai,saveAgentConfig:()=>ze});import{chmod as sm,stat as om}from"node:fs/promises";function De(t,e){return an(Ze(t,e).config)}function ze(t,e){return dn(Ze(t.agentId,e).config,t,{mode:ws})}async function am(t,e){if(process.platform==="win32")return;let r=Ze(t,e).config;try{let i=await om(r);if(!i.isFile())return;let o=i.mode&511;o!==ws&&(await sm(r,ws),Fl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Fl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function oi(t,e,r){let i=await De(t,r);i&&(i.sessions=Object.fromEntries(e),await ze(i,r))}async function ai(t,e,r){let i=await De(t,r);i&&(i.skills=e,await ze(i,r))}var Fl,ws,un=nt(()=>{"use strict";ln();ne();Re();Fl=H("agent-config"),ws=384});var Fa=ce((c2,Hl)=>{Hl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Es=ce(ql=>{var Gl={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function hm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Gl))ql[t]=hm(Gl[t])});var Vl=ce((l2,$l)=>{var xm=xe("fs"),Me=xe("path"),jl=Fa(),pm=Es(),gm=typeof process=="object"&&process.platform==="win32",Kl=t=>typeof t=="object"&&t!==null,Wl=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Ie(t){this.sep=Me.sep,this.fs=xm,Kl(t)&&Kl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}$l.exports=Ie;Ie.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var l;try{l=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(l&&l.isFile())throw pm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Ie.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var l=Me.dirname(t);o.fs.existsSync(l)||o.makeDir(l);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ie.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(l){if(l&&!r)return o(!1);c.fs.stat(t,function(u,f){if(l&&f.isDirectory())return o(!1);var x=Me.dirname(t);c.fs.exists(x,function(g){g||c.makeDir(x),c.fs.open(t,"w",438,function(y,S){y?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,v){c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ie.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let l=[];return e.fs.readdirSync(i).forEach(function(u){let f=Me.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&l.push(Me.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(l=l.concat(r(f,o,c)))}),l}return r(t,void 0,!0)};Ie.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let l=c.length;if(!l)return e(null,i);c.forEach(function(u){u=Me.join(t,u),r.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Me.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(g,y){if(g)return e(g);i=i.concat(y),--l||e(null,i)}):--l||e(null,i))})})})};Ie.prototype.getAttributes=function(){};Ie.prototype.setAttributes=function(){};Ie.crc32update=function(t,e){return Wl[(t^e)&255]^t>>>8};Ie.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Ie.crc32update(r,t[i++]);return~r>>>0};Ie.methodToString=function(t){switch(t){case jl.STORED:return"STORED ("+t+")";case jl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ie.canonical=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.join(".",e)};Ie.zipnamefix=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.posix.join(".",e)};Ie.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ie.sanitize=function(t,e){t=Me.resolve(Me.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Me.normalize(Me.join(t,r.slice(i,o).join(Me.sep)));if(c.indexOf(t)===0)return c}return Me.normalize(Me.join(t,Me.basename(e)))};Ie.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Ie.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Ie.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ie.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};Ie.isWin=gm;Ie.crcTable=Wl});var Zl=ce((u2,Jl)=>{var mm=xe("path");Jl.exports=function(t,{fs:e}){var r=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(o=e.statSync(r),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=mm.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:r,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Xl=ce((f2,Yl)=>{Yl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=ce((h2,xr)=>{xr.exports=Vl();xr.exports.Constants=Fa();xr.exports.Errors=Es();xr.exports.FileAttr=Zl();xr.exports.decoder=Xl()});var eu=ce((x2,Ql)=>{var fn=pr(),z=fn.Constants;Ql.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,l=0,u=0,f=0,x=0,g=0,y=0,S=0,_=0,v=0;t|=fn.isWin?2560:768,r|=z.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,D=E=>Math.max(0,E)&255;return o=fn.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return r},set flags(E){r=E},get flags_efs(){return(r&z.FLG_EFS)>0},set flags_efs(E){E?r|=z.FLG_EFS:r&=~z.FLG_EFS},get flags_desc(){return(r&z.FLG_DESC)>0},set flags_desc(E){E?r|=z.FLG_DESC:r&=~z.FLG_DESC},get method(){return i},set method(E){switch(E){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=E},get time(){return fn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=fn.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=A(E)},get timeHighByte(){return D(o>>>8)},get crc(){return c},set crc(E){c=A(E)},get compressedSize(){return l},set compressedSize(E){l=A(E)},get size(){return u},set size(E){u=A(E)},get fileNameLength(){return f},set fileNameLength(E){f=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return g},set commentLength(E){g=E},get diskNumStart(){return y},set diskNumStart(E){y=A(E)},get inAttr(){return S},set inAttr(E){S=A(E)},get attr(){return _},set attr(E){_=A(E)},get fileAttr(){return(_||0)>>16&4095},get offset(){return v},set offset(E){v=A(E)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+f+x+g},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var C=E.slice(v,v+z.LOCHDR);if(C.readUInt32LE(0)!==z.LOCSIG)throw fn.Errors.INVALID_LOC();I.version=C.readUInt16LE(z.LOCVER),I.flags=C.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=C.readUInt16LE(z.LOCHOW),I.time=C.readUInt32LE(z.LOCTIM),I.crc=C.readUInt32LE(z.LOCCRC),I.compressedSize=C.readUInt32LE(z.LOCSIZ),I.size=C.readUInt32LE(z.LOCLEN),I.fnameLen=C.readUInt16LE(z.LOCNAM),I.extraLen=C.readUInt16LE(z.LOCEXT);let O=v+z.LOCHDR+I.fnameLen,F=O+I.extraLen;return E.slice(O,F)},loadFromBinary:function(E){if(E.length!==z.CENHDR||E.readUInt32LE(0)!==z.CENSIG)throw fn.Errors.INVALID_CEN();t=E.readUInt16LE(z.CENVEM),e=E.readUInt16LE(z.CENVER),r=E.readUInt16LE(z.CENFLG),i=E.readUInt16LE(z.CENHOW),o=E.readUInt32LE(z.CENTIM),c=E.readUInt32LE(z.CENCRC),l=E.readUInt32LE(z.CENSIZ),u=E.readUInt32LE(z.CENLEN),f=E.readUInt16LE(z.CENNAM),x=E.readUInt16LE(z.CENEXT),g=E.readUInt16LE(z.CENCOM),y=E.readUInt16LE(z.CENDSK),S=E.readUInt16LE(z.CENATT),_=E.readUInt32LE(z.CENATX),v=E.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(z.LOCHDR);return E.writeUInt32LE(z.LOCSIG,0),E.writeUInt16LE(e,z.LOCVER),E.writeUInt16LE(r,z.LOCFLG),E.writeUInt16LE(i,z.LOCHOW),E.writeUInt32LE(o,z.LOCTIM),E.writeUInt32LE(c,z.LOCCRC),E.writeUInt32LE(l,z.LOCSIZ),E.writeUInt32LE(u,z.LOCLEN),E.writeUInt16LE(f,z.LOCNAM),E.writeUInt16LE(I.extraLen,z.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(z.CENHDR+f+x+g);return E.writeUInt32LE(z.CENSIG,0),E.writeUInt16LE(t,z.CENVEM),E.writeUInt16LE(e,z.CENVER),E.writeUInt16LE(r,z.CENFLG),E.writeUInt16LE(i,z.CENHOW),E.writeUInt32LE(o,z.CENTIM),E.writeUInt32LE(c,z.CENCRC),E.writeUInt32LE(l,z.CENSIZ),E.writeUInt32LE(u,z.CENLEN),E.writeUInt16LE(f,z.CENNAM),E.writeUInt16LE(x,z.CENEXT),E.writeUInt16LE(g,z.CENCOM),E.writeUInt16LE(y,z.CENDSK),E.writeUInt16LE(S,z.CENATT),E.writeUInt32LE(_,z.CENATX),E.writeUInt32LE(v,z.CENOFF),E},toJSON:function(){let E=function(C){return C+" bytes"};return{made:t,version:e,flags:r,method:fn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:E(l),size:E(u),fileNameLength:E(f),extraLength:E(x),commentLength:E(g),diskNumStart:y,inAttr:S,attr:_,offset:v,centralHeaderSize:E(z.CENHDR+f+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var nu=ce((p2,tu)=>{var gr=pr(),be=gr.Constants;tu.exports=function(){var t=0,e=0,r=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return r},set size(c){r=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return be.ENDHDR+o},loadFromBinary:function(c){if((c.length!==be.ENDHDR||c.readUInt32LE(0)!==be.ENDSIG)&&(c.length<be.ZIP64HDR||c.readUInt32LE(0)!==be.ZIP64SIG))throw gr.Errors.INVALID_END();c.readUInt32LE(0)===be.ENDSIG?(t=c.readUInt16LE(be.ENDSUB),e=c.readUInt16LE(be.ENDTOT),r=c.readUInt32LE(be.ENDSIZ),i=c.readUInt32LE(be.ENDOFF),o=c.readUInt16LE(be.ENDCOM)):(t=gr.readBigUInt64LE(c,be.ZIP64SUB),e=gr.readBigUInt64LE(c,be.ZIP64TOT),r=gr.readBigUInt64LE(c,be.ZIP64SIZE),i=gr.readBigUInt64LE(c,be.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(be.ENDHDR+o);return c.writeUInt32LE(be.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,be.ENDSUB),c.writeUInt16LE(e,be.ENDTOT),c.writeUInt32LE(r,be.ENDSIZ),c.writeUInt32LE(i,be.ENDOFF),c.writeUInt16LE(o,be.ENDCOM),c.fill(" ",be.ENDHDR),c},toJSON:function(){let c=function(l,u){let f=l.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ua=ce(za=>{za.EntryHeader=eu();za.MainHeader=nu()});var iu=ce((m2,ru)=>{ru.exports=function(t){var e=xe("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],l=0;o.on("data",function(u){c.push(u),l+=u.length}),o.on("end",function(){var u=Buffer.alloc(l),f=0;u.fill(0);for(var x=0;x<c.length;x++){var g=c[x];g.copy(u,f),f+=g.length}i&&i(u)}),o.end(t)}}}});var ou=ce((w2,su)=>{var wm=+(process.versions?process.versions.node:"").split(".")[0]||0;su.exports=function(t,e){var r=xe("zlib");let i=wm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),l=[],u=0;c.on("data",function(f){l.push(f),u+=f.length}),c.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var g=0;g<l.length;g++){var y=l[g];y.copy(f,x),x+=y.length}o&&o(f)}),c.end(t)}}}});var uu=ce((_2,lu)=>{"use strict";var{randomFillSync:au}=xe("crypto"),_m=Es(),ym=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),du=(t,e)=>Math.imul(t,e)>>>0,cu=(t,e)=>ym[(t^e)&255]^t>>>8,ci=()=>typeof au=="function"?au(Buffer.alloc(12)):ci.node();ci.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var bs={genSalt:ci};function vs(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}vs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=cu(e[0],t),e[1]+=e[0]&255,e[1]=du(e[1],134775813)+1,e[2]=cu(e[2],e[1]>>>24),t};vs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return du(t,t^1)>>8&255};function Em(t){let e=new vs(t);return function(r){let i=Buffer.alloc(r.length),o=0;for(let c of r)i[o++]=e.updateKeys(c^e.next());return i}}function bm(t){let e=new vs(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let l=e.next();i[o++]=c^l,e.updateKeys(c)}return i}}function vm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Em(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw _m.WRONG_PASSWORD();return i(t.slice(12))}function Sm(t){Buffer.isBuffer(t)&&t.length>=12?bs.genSalt=function(){return t.slice(0,12)}:t==="node"?bs.genSalt=ci.node:bs.genSalt=ci}function Im(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=bm(r),c=bs.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let l=Buffer.alloc(t.length+12);return o(c,l),o(t,l,12)}lu.exports={decrypt:vm,encrypt:Im,_salter:Sm}});var fu=ce(Ss=>{Ss.Deflater=iu();Ss.Inflater=ou();Ss.ZipCrypto=uu()});var Ga=ce((E2,hu)=>{var de=pr(),Am=Ua(),Ae=de.Constants,Ha=fu();hu.exports=function(t,e){var r=new Am.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,l=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let g=t,y=typeof g.decoder=="object"?g.decoder:de.decoder;x=y.hasOwnProperty("efs")?y.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function _(E){if(!r.flags_desc&&!r.localHeader.flags_desc){if(de.crc32(E)!==r.localHeader.crc)return!1}else{let C={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==Ae.LOCSIG||e.readUInt32LE(O)==Ae.CENSIG)throw de.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Ae.EXTSIG)C.crc=e.readUInt32LE(O+Ae.EXTCRC),C.compressedSize=e.readUInt32LE(O+Ae.EXTSIZ),C.size=e.readUInt32LE(O+Ae.EXTLEN);else if(e.readUInt16LE(O+12)===19280)C.crc=e.readUInt32LE(O+Ae.EXTCRC-4),C.compressedSize=e.readUInt32LE(O+Ae.EXTSIZ-4),C.size=e.readUInt32LE(O+Ae.EXTLEN-4);else throw de.Errors.DESCRIPTOR_UNKNOWN();if(C.compressedSize!==r.compressedSize||C.size!==r.size||C.crc!==r.crc)throw de.Errors.DESCRIPTOR_FAULTY();if(de.crc32(E)!==C.crc)return!1}return!0}function v(E,C,O){if(typeof C>"u"&&typeof E=="string"&&(O=E,E=void 0),c)return E&&C&&C(Buffer.alloc(0),de.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return E&&C&&C(F),F;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw de.Errors.INVALID_PASS_PARAM();F=Ha.ZipCrypto.decrypt(F,r,O)}var B=Buffer.alloc(r.size);switch(r.method){case de.Constants.STORED:if(F.copy(B),_(B))return E&&C&&C(B),B;throw E&&C&&C(B,de.Errors.BAD_CRC()),de.Errors.BAD_CRC();case de.Constants.DEFLATED:var V=new Ha.Inflater(F,r.size);if(E)V.inflateAsync(function($){$.copy($,0),C&&(_($)?C($):C($,de.Errors.BAD_CRC()))});else{if(V.inflate(B).copy(B,0),!_(B))throw de.Errors.BAD_CRC(`"${y.decode(i)}"`);return B}break;default:throw E&&C&&C(Buffer.alloc(0),de.Errors.UNKNOWN_METHOD()),de.Errors.UNKNOWN_METHOD()}}function I(E,C){if((!l||!l.length)&&Buffer.isBuffer(e))return E&&C&&C(S()),S();if(l.length&&!c){var O;switch(r.method){case de.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(l.length),l.copy(O),E&&C&&C(O),O;default:case de.Constants.DEFLATED:var F=new Ha.Deflater(l);if(E)F.deflateAsync(function(V){O=Buffer.alloc(V.length),r.compressedSize=V.length,V.copy(O),C&&C(O)});else{var B=F.deflate();return r.compressedSize=B.length,B}F=null;break}}else if(E&&C)C(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,C){return de.readBigUInt64LE(E,C)}function T(E){try{for(var C=0,O,F,B;C+4<E.length;)O=E.readUInt16LE(C),C+=2,F=E.readUInt16LE(C),C+=2,B=E.slice(C,C+F),C+=F,Ae.ID_ZIP64===O&&D(B)}catch{throw de.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(E){var C,O,F,B;E.length>=Ae.EF_ZIP64_SCOMP&&(C=A(E,Ae.EF_ZIP64_SUNCOMP),r.size===Ae.EF_ZIP64_OR_32&&(r.size=C)),E.length>=Ae.EF_ZIP64_RHO&&(O=A(E,Ae.EF_ZIP64_SCOMP),r.compressedSize===Ae.EF_ZIP64_OR_32&&(r.compressedSize=O)),E.length>=Ae.EF_ZIP64_DSN&&(F=A(E,Ae.EF_ZIP64_RHO),r.offset===Ae.EF_ZIP64_OR_32&&(r.offset=F)),E.length>=Ae.EF_ZIP64_DSN+4&&(B=E.readUInt32LE(Ae.EF_ZIP64_DSN),r.diskNumStart===Ae.EF_ZIP64_OR_16&&(r.diskNumStart=B))}return{get entryName(){return y.decode(i)},get rawEntryName(){return i},set entryName(E){i=de.toBuffer(E,y.encode);var C=i[i.length-1];c=C===47||C===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,r.extraLength=E.length,T(E)},get comment(){return y.decode(o)},set comment(E){if(o=de.toBuffer(E,y.encode),r.commentLength=o.length,o.length>65535)throw de.Errors.COMMENT_TOO_LONG()},get name(){var E=y.decode(i);return c?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){l=de.toBuffer(E,de.decoder.encode),!c&&l.length?(r.size=l.length,r.method=de.Constants.DEFLATED,r.crc=de.crc32(E),r.changed=!0):r.method=de.Constants.STORED},getData:function(E){return r.changed?l:v(!1,null,E)},getDataAsync:function(E,C){r.changed?E(l):v(!0,E,C)},set attr(E){r.attr=E},get attr(){return r.attr},set header(E){r.loadFromBinary(E)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var E=r.centralHeaderToBinary(),C=de.Constants.CENHDR;return i.copy(E,C),C+=i.length,u.copy(E,C),C+=r.extraLength,o.copy(E,C),E},packLocalHeader:function(){let E=0;r.flags_efs=this.efs,r.extraLocalLength=f.length;let C=r.localHeaderToBinary(),O=Buffer.alloc(C.length+i.length+r.extraLocalLength);return C.copy(O,E),E+=C.length,i.copy(O,E),E+=i.length,f.copy(O,E),E+=f.length,O},toJSON:function(){let E=function(C){return"<"+(C&&C.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:E(e),data:E(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var gu=ce((b2,pu)=>{var xu=Ga(),km=Ua(),$e=pr();pu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new km.MainHeader,l=!1,u=null;let f=new Set,x=e,{noSort:g,decoder:y}=x;t?v(x.readEntries):l=!0;function S(){let A=new Set;for(let T of Object.keys(i)){let D=T.split("/");if(D.pop(),!!D.length)for(let E=0;E<D.length;E++){let C=D.slice(0,E+1).join("/")+"/";A.add(C)}}for(let T of A)if(!(T in i)){let D=new xu(x);D.entryName=T,D.attr=16,D.temporary=!0,r.push(D),i[D.entryName]=D,f.add(D)}}function _(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/$e.Constants.CENHDR)throw $e.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,T=0;T<r.length;T++){var D=A,E=new xu(x,t);E.header=t.slice(D,D+=$e.Constants.CENHDR),E.entryName=t.slice(D,D+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(D,D+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(D,D+E.header.commentLength)),A+=E.header.centralHeaderSize,r[T]=E,i[E.entryName]=E}f.clear(),S()}function v(A){var T=t.length-$e.Constants.ENDHDR,D=Math.max(0,T-65535),E=D,C=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(D=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===$e.Constants.ENDSIG){O=T,F=T,C=T+$e.Constants.ENDHDR,E=T-$e.Constants.END64HDR;continue}if(t.readUInt32LE(T)===$e.Constants.END64SIG){E=D;continue}if(t.readUInt32LE(T)===$e.Constants.ZIP64SIG){O=T,C=T+$e.readBigUInt64LE(t,T+$e.Constants.ZIP64SIZE)+$e.Constants.ZIP64LEAD;break}}if(O==-1)throw $e.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,C)),c.commentLength&&(o=t.slice(F+$e.Constants.ENDHDR)),A&&_()}function I(){r.length>1&&!g&&r.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return l||_(),r.filter(A=>!f.has(A))},get comment(){return y.decode(o)},set comment(A){o=$e.toBuffer(A,y.encode),c.commentLength=o.length},getEntryCount:function(){return l?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return l||_(),i[A]||null},setEntry:function(A){l||_(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,T=!0){l||_();let D=i[A];this.getEntryChildren(D,T).map(C=>C.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||_();let T=i[A],D=r.indexOf(T);D>=0&&(r.splice(D,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,T=!0){if(l||_(),typeof A=="object")if(A.isDirectory&&T){let D=[],E=A.entryName;for(let C of r)C.entryName.startsWith(E)&&D.push(C);return D}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){l||_(),I();let A=[],T=[],D=0,E=0;c.size=0,c.offset=0;let C=0;for(let B of this.entries){let V=B.getCompressedData();B.header.offset=E;let $=B.packLocalHeader(),re=$.length+V.length;E+=re,A.push($),A.push(V);let Q=B.packCentralHeader();T.push(Q),c.size+=Q.length,D+=re+Q.length,C++}D+=c.mainHeaderSize,c.offset=E,c.totalEntries=C,E=0;let O=Buffer.alloc(D);for(let B of A)B.copy(O,E),E+=B.length;for(let B of T)B.copy(O,E),E+=B.length;let F=c.toBinary();return o&&o.copy(F,$e.Constants.ENDHDR),F.copy(O,E),t=O,l=!1,O},toAsyncBuffer:function(A,T,D,E){try{l||_(),I();let C=[],O=[],F=0,B=0,V=0;c.size=0,c.offset=0;let $=function(re){if(re.length>0){let Q=re.shift(),se=Q.entryName+Q.extra.toString();D&&D(se),Q.getCompressedDataAsync(function(oe){E&&E(se),Q.header.offset=B;let R=Q.packLocalHeader(),U=R.length+oe.length;B+=U,C.push(R),C.push(oe);let K=Q.packCentralHeader();O.push(K),c.size+=K.length,F+=U+K.length,V++,$(re)})}else{F+=c.mainHeaderSize,c.offset=B,c.totalEntries=V,B=0;let Q=Buffer.alloc(F);C.forEach(function(oe){oe.copy(Q,B),B+=oe.length}),O.forEach(function(oe){oe.copy(Q,B),B+=oe.length});let se=c.toBinary();o&&o.copy(se,$e.Constants.ENDHDR),se.copy(Q,B),t=Q,l=!1,A(Q)}};$(Array.from(this.entries))}catch(C){T(C)}}}}});var _u=ce((v2,wu)=>{var Se=pr(),ve=xe("path"),Tm=Ga(),Cm=gu(),Nn=(...t)=>Se.findLast(t,e=>typeof e=="boolean"),mu=(...t)=>Se.findLast(t,e=>typeof e=="string"),Rm=(...t)=>Se.findLast(t,e=>typeof e=="function"),Dm={noSort:!1,readEntries:!1,method:Se.Constants.NONE,fs:null};wu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Dm);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=Se.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Se(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Se.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Se.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw Se.Errors.INVALID_FILENAME();let c=new Cm(r,i),{canonical:l,sanitize:u,zipnamefix:f}=Se;function x(_){if(_&&c){var v;if(typeof _=="string"&&(v=c.getEntry(ve.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(v=c.getEntry(_.entryName)),v)return v}return null}function g(_){let{join:v,normalize:I,sep:A}=ve.posix;return v(ve.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function y(_){return _ instanceof RegExp?(function(v){return function(I){return v.test(I)}})(_):typeof _!="function"?()=>!0:_}let S=(_,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",ve.relative(_,v)+I};return{readFile:function(_,v){var I=x(_);return I&&I.getData(v)||null},childCount:function(_){let v=x(_);if(v)return c.getChildCount(v)},readFileAsync:function(_,v){var I=x(_);I?I.getDataAsync(v):v(null,"getEntry failed for:"+_)},readAsText:function(_,v){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(_,v,I){var A=x(_);A?A.getDataAsync(function(T,D){if(D){v(T,D);return}T&&T.length?v(T.toString(I||"utf8")):v("")}):v("")},deleteFile:function(_,v=!0){var I=x(_);I&&c.deleteFile(I.entryName,v)},deleteEntry:function(_){var v=x(_);v&&c.deleteEntry(v.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,v){var I=x(_);I&&(I.comment=v)},getZipEntryComment:function(_){var v=x(_);return v&&v.comment||""},updateFile:function(_,v){var I=x(_);I&&I.setData(v)},addLocalFile:function(_,v,I,A){if(o.fs.existsSync(_)){v=v?g(v):"";let T=ve.win32.basename(ve.win32.normalize(_));v+=I||T;let D=o.fs.statSync(_),E=D.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);D.isDirectory()&&(v+=o.sep),this.addFile(v,E,A,D)}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,v){_=typeof _=="object"?_:{localPath:_};let I=ve.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:D}=_,E=this;o.fs.stat(I,function(C,O){if(C)return v(C,!1);T=T?g(T):"";let F=ve.win32.basename(ve.win32.normalize(I));if(T+=D||F,O.isFile())o.fs.readFile(I,function(B,V){return B?v(B,!1):(E.addFile(T,V,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(_,v,I){if(I=y(I),v=v?g(v):"",_=ve.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),T=this;if(A.length)for(let D of A){let E=ve.join(v,S(_,D));I(E)&&T.addLocalFile(D,ve.dirname(E))}}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,v,I,A){A=y(A),I=I?g(I):"",_=ve.normalize(_);var T=this;o.fs.open(_,"r",function(D){if(D&&D.code==="ENOENT")v(void 0,Se.Errors.FILE_NOT_FOUND(_));else if(D)v(void 0,D);else{var E=o.findFiles(_),C=-1,O=function(){if(C+=1,C<E.length){var F=E[C],B=S(_,F).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(B)?o.fs.stat(F,function(V,$){V&&v(void 0,V),$.isFile()?o.fs.readFile(F,function(re,Q){re?v(void 0,re):(T.addFile(I+B,Q,"",$),O())}):(T.addFile(I+B+"/",Buffer.alloc(0),"",$),O())}):process.nextTick(()=>{O()})}else v(!0,void 0)};O()}})},addLocalFolderAsync2:function(_,v){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=ve.resolve(g(_.localPath));let{zipPath:A,filter:T,namefix:D}=_;T instanceof RegExp?T=(function(O){return function(F){return O.test(F)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?g(A):"",D=="latin1"&&(D=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=O=>O);let E=O=>ve.join(A,D(S(localPath,O))),C=O=>ve.win32.basename(ve.win32.normalize(D(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?v(void 0,Se.Errors.FILE_NOT_FOUND(localPath)):O?v(void 0,O):o.findFilesAsync(localPath,function(F,B){if(F)return v(F);B=B.filter(V=>T(E(V))),B.length||v(void 0,!1),setImmediate(B.reverse().reduce(function(V,$){return function(re,Q){if(re||Q===!1)return setImmediate(V,re,!1);I.addLocalFileAsync({localPath:$,zipPath:ve.dirname(E($)),zipName:C($)},V)}},v))})})},addLocalFolderPromise:function(_,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},v),(T,D)=>{T&&A(T),D&&I(this)})})},addFile:function(_,v,I,A){_=f(_);let T=x(_),D=T!=null;D||(T=new Tm(i),T.entryName=_),T.comment=I||"";let E=typeof A=="object"&&A instanceof o.fs.Stats;E&&(T.header.time=A.mtime);var C=T.isDirectory?16:0;let O=T.isDirectory?16384:32768;return E?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=T.isDirectory?493:420,C=(C|O<<16)>>>0,T.attr=C,T.setData(v),D||c.setEntry(T),T},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,v,I,A,T,D){A=Nn(!1,A),T=Nn(!1,T),I=Nn(!0,I),D=mu(T,D);var E=x(_);if(!E)throw Se.Errors.NO_ENTRY();var C=l(E.entryName),O=u(v,D&&!E.isDirectory?D:I?C:ve.basename(C));if(E.isDirectory){var F=c.getEntryChildren(E);return F.forEach(function($){if($.isDirectory)return;var re=$.getData();if(!re)throw Se.Errors.CANT_EXTRACT_FILE();var Q=l($.entryName),se=u(v,I?Q:ve.basename(Q));let oe=T?$.header.fileAttr:void 0;o.writeFileTo(se,re,A,oe)}),!0}var B=E.getData(c.password);if(!B)throw Se.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw Se.Errors.CANT_OVERRIDE();let V=T?_.header.fileAttr:void 0;return o.writeFileTo(O,B,A,V),!0},test:function(_){if(!c)return!1;for(var v in c.entries)try{if(v.isDirectory)continue;var I=c.entries[v].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,v,I,A){if(I=Nn(!1,I),A=mu(I,A),v=Nn(!1,v),!c)throw Se.Errors.NO_ZIP();c.entries.forEach(function(T){var D=u(_,l(T.entryName));if(T.isDirectory){o.makeDir(D);return}var E=T.getData(A);if(!E)throw Se.Errors.CANT_EXTRACT_FILE();let C=I?T.header.fileAttr:void 0;o.writeFileTo(D,E,v,C);try{o.fs.utimesSync(D,T.header.time,T.header.time)}catch{throw Se.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,v,I,A){if(A=Rm(v,I,A),I=Nn(!1,I),v=Nn(!1,v),!A)return new Promise((O,F)=>{this.extractAllToAsync(_,v,I,function(B){B?F(B):O(this)})});if(!c){A(Se.Errors.NO_ZIP());return}_=ve.resolve(_);let T=O=>u(_,ve.normalize(l(O.entryName))),D=(O,F)=>new Error(O+': "'+F+'"'),E=[],C=[];c.entries.forEach(O=>{O.isDirectory?E.push(O):C.push(O)});for(let O of E){let F=T(O),B=I?O.header.fileAttr:void 0;try{o.makeDir(F),B&&o.fs.chmodSync(F,B),o.fs.utimesSync(F,O.header.time,O.header.time)}catch{A(D("Unable to create folder",F))}}C.reverse().reduce(function(O,F){return function(B){if(B)O(B);else{let V=ve.normalize(l(F.entryName)),$=u(_,V);F.getDataAsync(function(re,Q){if(Q)O(Q);else if(!re)O(Se.Errors.CANT_EXTRACT_FILE());else{let se=I?F.header.fileAttr:void 0;o.writeFileToAsync($,re,v,se,function(oe){oe||O(D("Unable to write file",$)),o.fs.utimes($,F.header.time,F.header.time,function(R){R?O(D("Unable to set times",$)):O()})})}})}}},A)()},writeZip:function(_,v){if(arguments.length===1&&typeof _=="function"&&(v=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((T,D)=>{!_&&i.filename&&(_=i.filename),_||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let C=O=>O?T(O):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,E,I,A,C)},D)})},toBufferPromise:function(){return new Promise((_,v)=>{c.toAsyncBuffer(_,v)})},toBuffer:function(_,v,I,A){return typeof _=="function"?(c.toAsyncBuffer(_,v,I,A),null):c.compressToBuffer()}}}});import{execFile as M_,spawn as B_,spawnSync as HA}from"node:child_process";import{promisify as F_}from"node:util";function U_(t){if(process.platform!=="win32")return!1;if(zf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(zf,"").toLowerCase();return z_.has(r)}function Uf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return U_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function it(t,e=[],r={}){return B_(t,e,Uf(t,r))}function Hf(t,e=[],r={}){return H_(t,e,Uf(t,r))}var z_,zf,H_,Vt=nt(()=>{"use strict";z_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),zf=/\.(cmd|bat|ps1)$/i;H_=F_(M_)});var Zt=ce((IR,vh)=>{"use strict";var Eh=["nodebuffer","arraybuffer","fragments"],bh=typeof Blob<"u";bh&&Eh.push("blob");vh.exports={BINARY_TYPES:Eh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Yi=ce((AR,Oo)=>{"use strict";var{EMPTY_BUFFER:Ob}=Zt(),_d=Buffer[Symbol.species];function Lb(t,e){if(t.length===0)return Ob;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let c=t[o];r.set(c,i),i+=c.length}return i<e?new _d(r.buffer,r.byteOffset,i):r}function Sh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Ih(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Nb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function yd(t){if(yd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new _d(t):ArrayBuffer.isView(t)?e=new _d(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),yd.readOnly=!1),e}Oo.exports={concat:Lb,mask:Sh,toArrayBuffer:Nb,toBuffer:yd,unmask:Ih};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");Oo.exports.mask=function(e,r,i,o,c){c<48?Sh(e,r,i,o,c):t.mask(e,r,i,o,c)},Oo.exports.unmask=function(e,r){e.length<32?Ih(e,r):t.unmask(e,r)}}catch{}});var Th=ce((kR,kh)=>{"use strict";var Ah=Symbol("kDone"),Ed=Symbol("kRun"),bd=class{constructor(e){this[Ah]=()=>{this.pending--,this[Ed]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ed]()}[Ed](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ah])}}};kh.exports=bd});var Gr=ce((TR,Ph)=>{"use strict";var Xi=xe("zlib"),Ch=Yi(),Mb=Th(),{kStatusCode:Rh}=Zt(),Bb=Buffer[Symbol.species],Fb=Buffer.from([0,0,255,255]),No=Symbol("permessage-deflate"),Yt=Symbol("total-length"),Ur=Symbol("callback"),Rn=Symbol("buffers"),Hr=Symbol("error"),Lo,vd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Lo){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Lo=new Mb(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Ur];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let o=r[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){Lo.add(o=>{this._decompress(e,r,(c,l)=>{o(),i(c,l)})})}compress(e,r,i){Lo.add(o=>{this._compress(e,r,(c,l)=>{o(),i(c,l)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?Xi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Xi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[No]=this,this._inflate[Yt]=0,this._inflate[Rn]=[],this._inflate.on("error",Ub),this._inflate.on("data",Dh)}this._inflate[Ur]=i,this._inflate.write(e),r&&this._inflate.write(Fb),this._inflate.flush(()=>{let c=this._inflate[Hr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=Ch.concat(this._inflate[Rn],this._inflate[Yt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Yt]=0,this._inflate[Rn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,l)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?Xi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Xi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[Yt]=0,this._deflate[Rn]=[],this._deflate.on("data",zb)}this._deflate[Ur]=i,this._deflate.write(e),this._deflate.flush(Xi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Ch.concat(this._deflate[Rn],this._deflate[Yt]);r&&(c=new Bb(c.buffer,c.byteOffset,c.length-4)),this._deflate[Ur]=null,this._deflate[Yt]=0,this._deflate[Rn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Ph.exports=vd;function zb(t){this[Rn].push(t),this[Yt]+=t.length}function Dh(t){if(this[Yt]+=t.length,this[No]._maxPayload<1||this[Yt]<=this[No]._maxPayload){this[Rn].push(t);return}this[Hr]=new RangeError("Max payload size exceeded"),this[Hr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Hr][Rh]=1009,this.removeListener("data",Dh),this.reset()}function Ub(t){if(this[No]._inflate=null,this[Hr]){this[Ur](this[Hr]);return}t[Rh]=1007,this[Ur](t)}});var qr=ce((CR,Mo)=>{"use strict";var{isUtf8:Oh}=xe("buffer"),{hasBlob:Hb}=Zt(),Gb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function qb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Sd(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function jb(t){return Hb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Mo.exports={isBlob:jb,isValidStatusCode:qb,isValidUTF8:Sd,tokenChars:Gb};if(Oh)Mo.exports.isValidUTF8=function(t){return t.length<24?Sd(t):Oh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");Mo.exports.isValidUTF8=function(e){return e.length<32?Sd(e):t(e)}}catch{}});var Cd=ce((RR,Uh)=>{"use strict";var{Writable:Kb}=xe("stream"),Lh=Gr(),{BINARY_TYPES:Wb,EMPTY_BUFFER:Nh,kStatusCode:$b,kWebSocket:Vb}=Zt(),{concat:Id,toArrayBuffer:Jb,unmask:Zb}=Yi(),{isValidStatusCode:Yb,isValidUTF8:Mh}=qr(),Bo=Buffer[Symbol.species],ht=0,Bh=1,Fh=2,zh=3,Ad=4,kd=5,Fo=6,Td=class extends Kb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Wb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Vb]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ht}_write(e,r,i){if(this._opcode===8&&this._state==ht)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Bo(i.buffer,i.byteOffset+e,i.length-e),new Bo(i.buffer,i.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=r.length-e;e>=i.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new Bo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case ht:this.getInfo(e);break;case Bh:this.getPayloadLength16(e);break;case Fh:this.getPayloadLength64(e);break;case zh:this.getMask();break;case Ad:this.getData(e);break;case kd:case Fo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(r[0]&64)===64;if(i&&!this._extensions[Lh.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=Bh:this._payloadLength===127?this._state=Fh:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),i=r.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=zh:this._state=Ad}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ad}getData(e){let r=Nh;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Zb(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=kd,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Lh.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return r(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(l);return}this._fragments.push(c)}this.dataMessage(r),this._state===ht&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=ht;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Id(i,r):this._binaryType==="arraybuffer"?o=Jb(Id(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=ht):(this._state=Fo,setImmediate(()=>{this.emit("message",o,!0),this._state=ht,this.startLoop(e)}))}else{let o=Id(i,r);if(!this._skipUTF8Validation&&!Mh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===kd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=ht):(this._state=Fo,setImmediate(()=>{this.emit("message",o,!1),this._state=ht,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Nh),this.end();else{let i=e.readUInt16BE(0);if(!Yb(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Bo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Mh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=ht;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ht):(this._state=Fo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ht,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let l=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(l,this.createError),l.code=c,l[$b]=o,l}};Uh.exports=Td});var Pd=ce((PR,qh)=>{"use strict";var{Duplex:DR}=xe("stream"),{randomFillSync:Xb}=xe("crypto"),Hh=Gr(),{EMPTY_BUFFER:Qb,kWebSocket:ev,NOOP:tv}=Zt(),{isBlob:jr,isValidStatusCode:nv}=qr(),{mask:Gh,toBuffer:Xn}=Yi(),xt=Symbol("kByteLength"),rv=Buffer.alloc(4),zo=8*1024,Qn,Kr=zo,St=0,iv=1,sv=2,Rd=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=St,this.onerror=tv,this[ev]=void 0}static frame(e,r){let i,o=!1,c=2,l=!1;r.mask&&(i=r.maskBuffer||rv,r.generateMask?r.generateMask(i):(Kr===zo&&(Qn===void 0&&(Qn=Buffer.alloc(zo)),Xb(Qn,0,zo),Kr=0),i[0]=Qn[Kr++],i[1]=Qn[Kr++],i[2]=Qn[Kr++],i[3]=Qn[Kr++]),l=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||l)&&r[xt]!==void 0?u=r[xt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!l);let f=u;u>=65536?(c+=8,f=127):u>125&&(c+=2,f=126);let x=Buffer.allocUnsafe(o?u+c:c);return x[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(x[0]|=64),x[1]=f,f===126?x.writeUInt16BE(u,2):f===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),r.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],l?[x,e]:o?(Gh(e,i,x,c,u),[x]):(Gh(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=Qb;else{if(typeof e!="number"||!nv(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(r);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof r=="string"?c.write(r,2):c.set(r,2)}}let l={[xt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==St?this.enqueue([this.dispatch,c,!1,l,o]):this.sendFrame(t.frame(c,l),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):jr(e)?(o=e.size,c=!1):(e=Xn(e),o=e.length,c=Xn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[xt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};jr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==St?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):jr(e)?(o=e.size,c=!1):(e=Xn(e),o=e.length,c=Xn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[xt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};jr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==St?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,r,i){let o=this._extensions[Hh.extensionName],c=r.binary?2:1,l=r.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):jr(e)?(u=e.size,f=!1):(e=Xn(e),u=e.length,f=Xn.readOnly),this._firstFragment?(this._firstFragment=!1,l&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=u>=o._threshold),this._compress=l):(l=!1,c=0),r.fin&&(this._firstFragment=!0);let x={[xt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:f,rsv1:l};jr(e)?this._state!==St?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==St?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[xt],this._state=sv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Dd,this,u,o);return}this._bufferedBytes-=i[xt];let l=Xn(c);r?this.dispatch(l,r,i,o):(this._state=St,this.sendFrame(t.frame(l,i),o),this.dequeue())}).catch(c=>{process.nextTick(ov,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[Hh.extensionName];this._bufferedBytes+=i[xt],this._state=iv,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Dd(this,f,o);return}this._bufferedBytes-=i[xt],this._state=St,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===St&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][xt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][xt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};qh.exports=Rd;function Dd(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],c=o[o.length-1];typeof c=="function"&&c(e)}}function ov(t,e,r){Dd(t,e,r),t.onerror(e)}});var Xh=ce((OR,Yh)=>{"use strict";var{kForOnEventAttribute:Qi,kListener:Od}=Zt(),jh=Symbol("kCode"),Kh=Symbol("kData"),Wh=Symbol("kError"),$h=Symbol("kMessage"),Vh=Symbol("kReason"),Wr=Symbol("kTarget"),Jh=Symbol("kType"),Zh=Symbol("kWasClean"),Xt=class{constructor(e){this[Wr]=null,this[Jh]=e}get target(){return this[Wr]}get type(){return this[Jh]}};Object.defineProperty(Xt.prototype,"target",{enumerable:!0});Object.defineProperty(Xt.prototype,"type",{enumerable:!0});var er=class extends Xt{constructor(e,r={}){super(e),this[jh]=r.code===void 0?0:r.code,this[Vh]=r.reason===void 0?"":r.reason,this[Zh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[jh]}get reason(){return this[Vh]}get wasClean(){return this[Zh]}};Object.defineProperty(er.prototype,"code",{enumerable:!0});Object.defineProperty(er.prototype,"reason",{enumerable:!0});Object.defineProperty(er.prototype,"wasClean",{enumerable:!0});var $r=class extends Xt{constructor(e,r={}){super(e),this[Wh]=r.error===void 0?null:r.error,this[$h]=r.message===void 0?"":r.message}get error(){return this[Wh]}get message(){return this[$h]}};Object.defineProperty($r.prototype,"error",{enumerable:!0});Object.defineProperty($r.prototype,"message",{enumerable:!0});var es=class extends Xt{constructor(e,r={}){super(e),this[Kh]=r.data===void 0?null:r.data}get data(){return this[Kh]}};Object.defineProperty(es.prototype,"data",{enumerable:!0});var av={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Qi]&&o[Od]===e&&!o[Qi])return;let i;if(t==="message")i=function(c,l){let u=new es("message",{data:l?c:c.toString()});u[Wr]=this,Uo(e,this,u)};else if(t==="close")i=function(c,l){let u=new er("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Wr]=this,Uo(e,this,u)};else if(t==="error")i=function(c){let l=new $r("error",{error:c,message:c.message});l[Wr]=this,Uo(e,this,l)};else if(t==="open")i=function(){let c=new Xt("open");c[Wr]=this,Uo(e,this,c)};else return;i[Qi]=!!r[Qi],i[Od]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Od]===e&&!r[Qi]){this.removeListener(t,r);break}}};Yh.exports={CloseEvent:er,ErrorEvent:$r,Event:Xt,EventTarget:av,MessageEvent:es};function Uo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Ho=ce((LR,Qh)=>{"use strict";var{tokenChars:ts}=qr();function Bt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function cv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,l,u,f=-1,x=-1,g=-1,y=0;for(;y<t.length;y++)if(x=t.charCodeAt(y),l===void 0)if(g===-1&&ts[x]===1)f===-1&&(f=y);else if(y!==0&&(x===32||x===9))g===-1&&f!==-1&&(g=y);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${y}`);g===-1&&(g=y);let _=t.slice(f,g);x===44?(Bt(e,_,r),r=Object.create(null)):l=_,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${y}`);else if(u===void 0)if(g===-1&&ts[x]===1)f===-1&&(f=y);else if(x===32||x===9)g===-1&&f!==-1&&(g=y);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${y}`);g===-1&&(g=y),Bt(r,t.slice(f,g),!0),x===44&&(Bt(e,l,r),r=Object.create(null),l=void 0),f=g=-1}else if(x===61&&f!==-1&&g===-1)u=t.slice(f,y),f=g=-1;else throw new SyntaxError(`Unexpected character at index ${y}`);else if(o){if(ts[x]!==1)throw new SyntaxError(`Unexpected character at index ${y}`);f===-1?f=y:i||(i=!0),o=!1}else if(c)if(ts[x]===1)f===-1&&(f=y);else if(x===34&&f!==-1)c=!1,g=y;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${y}`);else if(x===34&&t.charCodeAt(y-1)===61)c=!0;else if(g===-1&&ts[x]===1)f===-1&&(f=y);else if(f!==-1&&(x===32||x===9))g===-1&&(g=y);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${y}`);g===-1&&(g=y);let _=t.slice(f,g);i&&(_=_.replace(/\\/g,""),i=!1),Bt(r,u,_),x===44&&(Bt(e,l,r),r=Object.create(null),l=void 0),u=void 0,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${y}`);if(f===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=y);let S=t.slice(f,g);return l===void 0?Bt(e,S,r):(u===void 0?Bt(r,S,!0):i?Bt(r,u,S.replace(/\\/g,"")):Bt(r,u,S),Bt(e,l,r)),e}function dv(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(l=>l===!0?o:`${o}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Qh.exports={format:dv,parse:cv}});var Ko=ce((BR,ux)=>{"use strict";var lv=xe("events"),uv=xe("https"),fv=xe("http"),nx=xe("net"),hv=xe("tls"),{randomBytes:xv,createHash:pv}=xe("crypto"),{Duplex:NR,Readable:MR}=xe("stream"),{URL:Ld}=xe("url"),Dn=Gr(),gv=Cd(),mv=Pd(),{isBlob:wv}=qr(),{BINARY_TYPES:ex,CLOSE_TIMEOUT:_v,EMPTY_BUFFER:Go,GUID:yv,kForOnEventAttribute:Nd,kListener:Ev,kStatusCode:bv,kWebSocket:je,NOOP:rx}=Zt(),{EventTarget:{addEventListener:vv,removeEventListener:Sv}}=Xh(),{format:Iv,parse:Av}=Ho(),{toBuffer:kv}=Yi(),ix=Symbol("kAborted"),Md=[8,13],Qt=["CONNECTING","OPEN","CLOSING","CLOSED"],Tv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ye=class t extends lv{constructor(e,r,i){super(),this._binaryType=ex[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Go,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(i=r,r=[]):r=[r]),sx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ex.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,i){let o=new gv({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new mv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[je]=this,c[je]=this,e[je]=this,o.on("conclude",Dv),o.on("drain",Pv),o.on("error",Ov),o.on("message",Lv),o.on("ping",Nv),o.on("pong",Mv),c.onerror=Bv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",cx),e.on("data",jo),e.on("end",dx),e.on("error",lx),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Dn.extensionName]&&this._extensions[Dn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ct(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ax(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Go,r,i)}pong(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Go,r,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(i=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Dn.extensionName]||(o.compress=!1),this._sender.send(e||Go,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ct(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ye,"CONNECTING",{enumerable:!0,value:Qt.indexOf("CONNECTING")});Object.defineProperty(ye.prototype,"CONNECTING",{enumerable:!0,value:Qt.indexOf("CONNECTING")});Object.defineProperty(ye,"OPEN",{enumerable:!0,value:Qt.indexOf("OPEN")});Object.defineProperty(ye.prototype,"OPEN",{enumerable:!0,value:Qt.indexOf("OPEN")});Object.defineProperty(ye,"CLOSING",{enumerable:!0,value:Qt.indexOf("CLOSING")});Object.defineProperty(ye.prototype,"CLOSING",{enumerable:!0,value:Qt.indexOf("CLOSING")});Object.defineProperty(ye,"CLOSED",{enumerable:!0,value:Qt.indexOf("CLOSED")});Object.defineProperty(ye.prototype,"CLOSED",{enumerable:!0,value:Qt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ye.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ye.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Nd])return e[Ev];return null},set(e){for(let r of this.listeners(t))if(r[Nd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Nd]:!0})}})});ye.prototype.addEventListener=vv;ye.prototype.removeEventListener=Sv;ux.exports=ye;function sx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_v,protocolVersion:Md[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Md.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Md.join(", ")})`);let c;if(e instanceof Ld)c=e;else try{c=new Ld(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let l=c.protocol==="wss:",u=c.protocol==="ws+unix:",f;if(c.protocol!=="ws:"&&!l&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?f="The URL's pathname is empty":c.hash&&(f="The URL contains a fragment identifier"),f){let I=new SyntaxError(f);if(t._redirects===0)throw I;qo(t,I);return}let x=l?443:80,g=xv(16).toString("base64"),y=l?uv.request:fv.request,S=new Set,_;if(o.createConnection=o.createConnection||(l?Rv:Cv),o.defaultPort=o.defaultPort||x,o.port=c.port||x,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Dn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Iv({[Dn.extensionName]:_.offer()})),r.length){for(let I of r){if(typeof I!="string"||!Tv.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=l,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,T]of Object.entries(I))i.headers[A.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!l)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),v=t._req=y(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=y(o);o.timeout&&v.on("timeout",()=>{ct(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[ix]||(v=t._req=null,qo(t,I))}),v.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){ct(t,v,"Maximum redirects exceeded");return}v.abort();let D;try{D=new Ld(A,e)}catch{let C=new SyntaxError(`Invalid URL: ${A}`);qo(t,C);return}sx(t,D,r,i)}else t.emit("unexpected-response",v,I)||ct(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==ye.CONNECTING)return;v=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){ct(t,A,"Invalid Upgrade header");return}let E=pv("sha1").update(g+yv).digest("base64");if(I.headers["sec-websocket-accept"]!==E){ct(t,A,"Invalid Sec-WebSocket-Accept header");return}let C=I.headers["sec-websocket-protocol"],O;if(C!==void 0?S.size?S.has(C)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":S.size&&(O="Server sent no subprotocol"),O){ct(t,A,O);return}C&&(t._protocol=C);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!_){ct(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=Av(F)}catch{ct(t,A,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(B);if(V.length!==1||V[0]!==Dn.extensionName){ct(t,A,"Server indicated an extension that was not requested");return}try{_.accept(B[Dn.extensionName])}catch{ct(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Dn.extensionName]=_}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(v,t):v.end()}function qo(t,e){t._readyState=ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Cv(t){return t.path=t.socketPath,nx.connect(t)}function Rv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=nx.isIP(t.host)?"":t.host),hv.connect(t)}function ct(t,e,r){t._readyState=ye.CLOSING;let i=new Error(r);Error.captureStackTrace(i,ct),e.setHeader?(e[ix]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(qo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Bd(t,e,r){if(e){let i=wv(e)?e.size:kv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Qt[t.readyState]})`);process.nextTick(r,i)}}function Dv(t,e){let r=this[je];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[je]!==void 0&&(r._socket.removeListener("data",jo),process.nextTick(ox,r._socket),t===1005?r.close():r.close(t,e))}function Pv(){let t=this[je];t.isPaused||t._socket.resume()}function Ov(t){let e=this[je];e._socket[je]!==void 0&&(e._socket.removeListener("data",jo),process.nextTick(ox,e._socket),e.close(t[bv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function tx(){this[je].emitClose()}function Lv(t,e){this[je].emit("message",t,e)}function Nv(t){let e=this[je];e._autoPong&&e.pong(t,!this._isServer,rx),e.emit("ping",t)}function Mv(t){this[je].emit("pong",t)}function ox(t){t.resume()}function Bv(t){let e=this[je];e.readyState!==ye.CLOSED&&(e.readyState===ye.OPEN&&(e._readyState=ye.CLOSING,ax(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ax(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function cx(){let t=this[je];if(this.removeListener("close",cx),this.removeListener("data",jo),this.removeListener("end",dx),t._readyState=ye.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",tx),t._receiver.on("finish",tx))}function jo(t){this[je]._receiver.write(t)||this.pause()}function dx(){let t=this[je];t._readyState=ye.CLOSING,t._receiver.end(),this.end()}function lx(){let t=this[je];this.removeListener("error",lx),this.on("error",rx),t&&(t._readyState=ye.CLOSING,this.destroy())}});var px=ce((zR,xx)=>{"use strict";var FR=Ko(),{Duplex:Fv}=xe("stream");function fx(t){t.emit("close")}function zv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function hx(t){this.removeListener("error",hx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Uv(t,e){let r=!0,i=new Fv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,l){let u=!l&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(fx,i);return}let l=!1;t.once("error",function(f){l=!0,c(f)}),t.once("close",function(){l||c(o),process.nextTick(fx,i)}),r&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,l){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,l)});return}t.send(o,l)},i.on("end",zv),i.on("error",hx),i}xx.exports=Uv});var Fd=ce((UR,gx)=>{"use strict";var{tokenChars:Hv}=qr();function Gv(t){let e=new Set,r=-1,i=-1,o=0;for(o;o<t.length;o++){let l=t.charCodeAt(o);if(i===-1&&Hv[l]===1)r===-1&&(r=o);else if(o!==0&&(l===32||l===9))i===-1&&r!==-1&&(i=o);else if(l===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(r,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(r,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}gx.exports={parse:Gv}});var Sx=ce((GR,vx)=>{"use strict";var qv=xe("events"),Wo=xe("http"),{Duplex:HR}=xe("stream"),{createHash:jv}=xe("crypto"),mx=Ho(),tr=Gr(),Kv=Fd(),Wv=Ko(),{CLOSE_TIMEOUT:$v,GUID:Vv,kWebSocket:Jv}=Zt(),Zv=/^[+/0-9A-Za-z]{22}==$/,_x=0,yx=1,bx=2,zd=class extends qv{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:$v,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wv,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Wo.createServer((i,o)=>{let c=Wo.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=Yv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,l)=>{this.handleUpgrade(o,c,l,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=_x}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===bx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ns,this);return}if(e&&this.once("close",e),this._state!==yx)if(this._state=yx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ns,this):process.nextTick(ns,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{ns(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,o){r.on("error",Ex);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){nr(this,e,r,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){nr(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!Zv.test(c)){nr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){nr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){rs(r,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=Kv.parse(f)}catch{nr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],y={};if(this.options.perMessageDeflate&&g!==void 0){let S=new tr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=mx.parse(g);_[tr.extensionName]&&(S.accept(_[tr.extensionName]),y[tr.extensionName]=S)}catch{nr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(S,(_,v,I,A)=>{if(!_)return rs(r,v||401,I,A);this.completeUpgrade(y,c,x,e,r,i,o)});return}if(!this.options.verifyClient(S))return rs(r,401)}this.completeUpgrade(y,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,l,u){if(!c.readable||!c.writable)return c.destroy();if(c[Jv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>_x)return rs(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${jv("sha1").update(r+Vv).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let y=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;y&&(x.push(`Sec-WebSocket-Protocol: ${y}`),g._protocol=y)}if(e[tr.extensionName]){let y=e[tr.extensionName].params,S=mx.format({[tr.extensionName]:[y]});x.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",mx),m.setSocket(c,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ts,this)})),u(m,s)}};yx.exports=Md;function Lv(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 ts(t){t._state=_x,t.emit("close")}function mx(){this.destroy()}function ns(t,e,n,i){n=n||jo.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} ${jo.STATUS_CODES[e]}\r
17
- `+Object.keys(i).map(s=>`${s}: ${i[s]}`).join(`\r
16
+ `)),c.removeListener("error",Ex),g.setSocket(c,l,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(g),g.on("close",()=>{this.clients.delete(g),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ns,this)})),u(g,o)}};vx.exports=zd;function Yv(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function ns(t){t._state=bx,t.emit("close")}function Ex(){this.destroy()}function rs(t,e,r,i){r=r||Wo.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Wo.STATUS_CODES[e]}\r
17
+ `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+n)}function tr(t,e,n,i,s,c){if(t.listenerCount("wsClientError")){let d=new Error(s);Error.captureStackTrace(d,tr),t.emit("wsClientError",d,n,e)}else ns(n,i,s,c)}});var Lx=de(oe=>{"use strict";var M=G;(function(t,e){let n=G,i=t();for(;;)try{if(-parseInt(n(1768))/1*(parseInt(n(410))/2)+parseInt(n(1405))/3*(parseInt(n(1126))/4)+-parseInt(n(1433))/5+-parseInt(n(1280))/6*(-parseInt(n(1124))/7)+-parseInt(n(692))/8*(parseInt(n(1422))/9)+parseInt(n(1784))/10+parseInt(n(801))/11===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Vo,102953);var qv=Object[M(1641)+"operty"],Hv=Object[M(1125)+M(1323)+M(864)],Cx=(t,e)=>function(){return t&&(e=(0,t[{qUvMl:function(c,d){return c(d)}}[M(1102)](Hv,t)[0]])(t=0)),e},jv=(t,e)=>{for(var n in e)qv(t,n,{get:e[n],enumerable:!0})};function Wv(){return Sx||(Sx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Kv(){let t=M;return Ix||(Ix=[IDBCursor[t(1042)+"e"][t(813)],IDBCursor[t(1042)+"e"].continue,IDBCursor.prototype.continuePrimaryKey])}function $v(t){let e=M,n={TZbfT:e(1653),eUAdM:e(730),oLELu:function(s,c){return s(c)},mQNar:"success",HuKwb:e(1055),PZaLZ:function(s,c){return s(c)},WhBpJ:function(s){return s()},MENdL:function(s,c){return s!==c},XARMl:e(1259),rQras:"ZALnQ",hWPxl:function(s,c){return s instanceof c}},i=new Promise((s,c)=>{let d=e,u={LHMom:n.mQNar,CyHnS:n.HuKwb,ylnLn:function(_,S){return n.PZaLZ(_,S)},dTjhV:function(_){return n.WhBpJ(_)}},h=()=>{let _=G;t[_(1363)+_(1016)+"ner"](u[_(784)],x),t["removeEventListe"+_(1552)](u[_(1005)],m)},x=()=>{s(u[G(591)](zt,t.result)),u.dTjhV(h)},m=()=>{let _=G;if(n[_(1553)]===n[_(1174)])return this._qosDB[_(780)];n.oLELu(c,t.error),h()};t[d(1195)+d(1617)](n[d(1711)],x),t[d(1195)+d(1617)](n[d(1625)],m)});return i[e(859)](s=>{let c=e;if(n[c(467)](n[c(833)],n[c(422)]))n[c(1251)](s,IDBCursor)&&Fd[c(1087)](s,t);else return this._socket.protocol}).catch(()=>{}),Zo[e(1087)](i,t),i}function Vo(){let t=["Dgnntg4","DxjS","CgLUz0XVC3m","zvPgCeK","vLLpB0W","u2TmC1i","vvP1q0u","qwjVCNrfCNi","yNLL","tw9AD1G","AvfNDwG","ruD6uvC","vffLBhm","AvfYAe8","C0DnDeS","BhLywMO","tMf0zfy","tMrNBhq","CeTXyMW","BKXPBMu","q3LfvvK","yufVB0u","BwPHA2G","BMvJDa","vNzSz2K","Aw9U","Bhm6ia","C0LPqLG","rNH6B3u","CNnVCKzPBgu","BMnLq2XVC2u","vxbKyxrLq28","tu1Nzeq","rNjVBNrPzxi","CM92AwrLigi","uvDNtNu","yLPyq0O","DxDPBhO","ywnRpwzYB24","igzPzwXKoIa","CMvJzxzPzwq","rgrcyw4","t293wxm","DMvY","AgLNAa","zxf1ywXZ","zvH1swG","tMnSC1m","tgLZDgvUzxi","C0jmC2y","D1fqy20","CxfSrfi","z2v0qwXS","z1HxugS","thj4u3u","y0LrD2m","shvlD2i","re5Qt3O","Ae1LC3nHz2u","uenJEhG","q3rKz0q","vvHxv1u","C1f4D1m","zwH5BLq","x2LZtwLUAvq","y2Ter1y","y0P3Bge","DuvsuKm","z0jtu08","CM9YrxzLBNq","Ahr0Ca","yw5ZzM9YBvq","zgvMAw5Luhi","zxrxB3jRq2G","v0r3Dwu","qxPpDNO","AuncB24","txnjDve","y2nLAuu","sK9ZwuO","qwXWr3G","wLj3vwG","z2vtEw5J","se1gz0G","vvL4uMu","uvjWCxu","vhnswve","u3z4rM8","AwHoEK4","C0Xdr1a","CLLMBfO","vLbpCwe","yw1LoIa","CgvYC2LZDgu","Cwfby0q","DgvZDa","Aw5L","zhbhrfy","mdaWma","wKn2thO","uezREwu","wKXJwfG","q0Xpu0ve","Dgv4DfbHEwW","AhjHCuO","whPpAuW","BhP5qxK","wMvIB0q","y3jeDei","AKvXy3K","vgrMrLy","zvr0Ce4","z3rnt0G","swfsAwi","wMDcsem","BM5Ly3q","rLjptLrjrvi","r1DNyvy","vxHeBwu","yMXVy2TLza","BxnPBwS","u0fjruq","Dg9hzw5LCMe","CMfTzq","qKniuMW","x3DZ","tLjkvNu","yxrHlcbKyxq","B3bLBIa","yxvvBuG","uuHLBee","y3PeBve","yxGGCMv0CMK","C05JC1i","uM1yA24","quXm","q3rhrMu","z1brueW","C29Tzq","uNDkEfu","z1vjqLy","D1nYwfK","Bvfoyxi","nxWWFdj8nhW","Efrurw52","wwHuAei","rM5bCNy","u2jss0W","swLJvhC","B3jLtMfTzxm","AxnmB25N","ug1dy04","yNL0zuXLBMC","D0X3AKO","ywWGy3vYC28","txr1Eg4","BwPVD2q","x2HHBMrSzu8","ChHnyMm","Cgf5Bg9Hzeu","zwTbtLu","DvntDNC","B25tDgfYDfi","vKrPsem","rgvKAwnHDgu","B2nRzxq","C3vIC3rYAw4","DvnwwgG","y3fquNK","uNzqtfy","tgHuDem","x25HDMLNyxq","qNv2Egu","CMDvANu","mhWZFdj8nhW","BMDuAw1LCG","AxnAzxjV","y29UBMvJDca","v1zwrem","tfDesMi","B3v0sw50zxi","yw5Hz2vY","BgvY","r0TvEwq","u2vYDMLJzvC","tLnJEwW","rwTbtxO","yMfSrxzLBNq","ufHbChC","zNbTC3i","CMvWBgfJzq","CgfNzwHPzgu","BuX4Dui","zcbLCNjVCI4","twfyBe4","BufTwNO","wNnsBey","BwfW","AwXLtMfTzq","mZfoEgHzr0S","D1rzzwC","Dw5ZAwDUzwq","EK1Lvfq","tMf3sKS","uxbKwfi","u0jcEMW","z2vrDwv1zuW","z3joA2S","suXJCem","r3rXuuC","werLD3C","CgLUz19VBMm","y01HsgS","quziyK8","C3vIyxjYyxK","ote1mZaWtvrHt1P2","yMLUza","zvbLDvu","A0vSvvO","wwHnChO","D3D4zvq","s1HPrue","u3nNA0q","oxW3FdeXFdu","EhPMENa","zgDlvLe","tejhEwK","x3DHAxq","Chv0","C2v0q3vYC28","CNnVCL92ywW","CvLqt2W","rM1Mv1a","C2vYDMvYvgK","DgXfre4","ChL6tNm","thj5t3e","DLDVB1e","y3jLyxrLt2i","qKfICxy","vffgyLi","wNHLsNG","tg9JAW","qvbrr2O","ALncv2K","qNnYuM0","z3LAzu8","C2v0y3vYC28","AMrZALm","zxmGCMvHy2G","rxzZwgq","Bwf4tg9ZC0m","CLHfBgq","D2DgBhe","vKTmsKC","AwTwtvG","EeLzDgy","zgvSzxrLrge","vgv6wvy","sKjlC3a","l3DZl3yY","B2nRzxrtDwm","D3Pzr1G","rNb4tuu","ihrYEsbYzwm","Cgu6ia","Cu5osem","zxH0ugf5Bg8","vwrwu00","vfvuvxO","uMvHzcbWyxm","EuzPDw4","DvHKtMy","ueXdse0","zgvSzxrL","yvLSDuO","EMPYruy","wfLfz0e","zvj4vhC","CgXLyxnLiha","weLZDhG","wu9ODva","tfjpCKS","qxrWzeq","vKTKvgC","qLf4uxa","wgLgEuK","yMLUyxj5","ywDLrxzLBNq","CNzHBfzHBhu","DwPHtuW","zg9Uzq","qMvdDvu","B3jL","ruT4ru8","CKjtv24","z2v0qwXSs2u","C3nHz2vfDMu","q09ZC2y","EsbJBg9Zzwq","zw5HyMXLvhi","uMXkEgW","wgnQy28","C2nYAxb0","DK55qMK","x29UugfNzu4","vwnrBvu","uxvLDwu","CwvpvMi","x29Uq2XVC2u","ANfSrMS","wLPsBNm","C2DPza","zgv2AwnLx2K","veHfs2C","BM1mufu","qxnXqKW","y3jLD0i","AgPdrhm","CM9qCMK","CMfUzg9T","yw51Ce1LC3m","DeHqzNm","B25LCNjVCG","t1bftL9fuLi","CMvHzfvjBNq","vKfZyuC","tej4D2e","id4G","C2HPzNq","s0XyufC","Bg93","EgD2zNi","swzYDwi","Chj1wu4","CgLUz1rPBwu","BgLTAxq","x2n1CNnVCK4","mNW1Fdb8m3W","CMLLC0nVDw4","vgfN","sKr4C1K","uMLstee","Ahr0Chm6","AgfUz2u","yxbWBgLJyxq","nde0nMvYqxrMEq","su5tvefova","BM93","DgHHBIbSB2m","x194x21Zz18","CMfNzvn5BMm","DNPgBgW","uKPiC3a","DxbKyxrLq3u","rgPnuwq","ywnOzwq","v2vIu29JA2u","CLfYyxm","q0LOuw0","sLL1DMe","qu13zKO","x21LC3nHz2u","rxzLBNq","yMXNA2i","vxror0u","x2TLEvbHDgG","ANbntgC","x2rLC3rYB3K","ENfiChO","shjxvgq","ywrK","Dev2zw50","y29Uy2f0","zNjHBwvuExa","y3vYC29Yx24","x3nVy2TLDa","BervEg4","sfjUzvi","tuXoq2q","ywrvAwe","DLjUswK","DffmDei","Cvjdswy","zw5NDgG","DKXrENu","y2HnyxHdB3u","y29UBMvJDfm","D05hANq","t2nwswy","EurUrvm","x3bPBMDmB3m","DgrkBMy","qKvQvKy","t1bftG","zNvUy3rPB24","AwDHDg9Yt24","yxbWBhK","tw9KDwXL","z25Ks3m","ihn1y2nLC3m","x3bYzwzPEa","C29YDa","tuvozeW","vuLlB1K","v2vPEgLUsLm","BxnNsuq","D3H5B3y","AxnrB1nnzxm","wwf0uNG","Dxrjza","ExPjB1G","z1f6wuW","sLLjq0y","zw1PDa","CMvJzwL2zwq","rhvttLG","zvPby0i","CgnnEMW","BhrPCgXLihq","BgLUzq","DgLUzYbZzxi","A1n0yxr1C0m","x2nSzwfYugK","zw5XDwv1zq","y3vYC29Yx2y","Ae1fDMm","BNrLCG","qwnZq0y","z0n2sgW","B3nLza","swfdvNO","mhW1Fdj8nW","v1HvBge","teHQuvy","DgPlz0O","s094qve","yMfJA3vWigu","tMD4zee","zff2zwm","zgvdBM8","x3bPBMDqB24","yMfSu2nVCgu","DuDNtwi","CM92AwrLige","C0Xf","ChzuDxG","uhDkrMW","vNfqBwS","ywnRx2LK","v0rezgu","s25MAeS","C3rVCMu","ALLcu3K","wMLUB3i","zMzMzG","EgrMvuO","svzWA2e","Ae9XtM0","DhjPzxm","yw1L","Aw1LCYbPBIa","y0XkB1q","BLz3y0u","zwnVBM5Ly3q","sxLAwKO","BMrWB2LUDca","ELjetKC","s0zwC00","DKPZzM4","vMvkAw0","sfHnswO","AhDStgu","BMvLzf9Hy2S","CgfNzxnOB3C","yM9KEq","BxLNvxK","zKvYCg4","AK9LwMC","BNbbsNu","z2vY","D2vI","mhWXFdy","CMTLCKDSB2i","y3jLyxrLq2W","CMvZzxrdB3u","mxWZFdr8nNW","r3fqtKS","AevYCM9Yrxy","AwXnuvi","y2HHCKnVzgu","BNDqteu","x19LC01Vzhu","tufyx1jfvfi","zMzmAw5L","BgvUz3rO","DfDHu04","A2v5","qvrHv1m","zw5KCg9PBNq","qvD4BKG","tMT4te4","CMvZB2X2zq","BNvTyMvY","C3vJy2vZCW","BfrPBwvVDxq","C3bSAwnL","revpEwG","Ef9MCM9UDgK","x2nYzwf0zvm","EhLhs2K","EKH5BxC","zgvS","D1H4Afm","CYbPBNn0yw4","zNPSvwK","uK9KzwC","rMTlCum","t2H6zgu","seTJqwO","rMfKsxC","nhWWFdn8mxW","DNPovMS","sNzXvKW","C3rYAw5NAwy","tvvZz2C","sendqMq","EwXUtg4","yMfgswC","twvZC2fNzuu","ExvfuuK","r25tyuy","B1j6Cu8","yxnZAwDU","Dgf3CK0","u2jpu0O","tLfttw0","rwPmq0i","x2LUAxq","Dhr3Awq","wu9Uuee","C2fNzq","yLLzuwq","x2n1CNnVCKy","Dg9oDw1Izxi","zw50zwqGDhK","tKrny28","AvfjD04","s2nhuuG","veHJtNO","x3bHDgHlzxK","ALH1sK0","sfrMq3u","mhW5Fdv8m3W","Eej5A2q","CMvJB25Uzwm","B3jRig9MzMW","swjrDK4","DwXPtNu","rw9pDMK","zLDfEMK","y29UBMvJDeu","we1PBvG","wfL3wvy","ru9XtM4","D21or1K","DgLLCKPtt04","vKrqthC","icSG","DhDVCMTdAge","CgLUz09Uy2u","u1b3wg8","s1DluLC","BfHkvLC","x3DZsw5ZDge","Aw50zwDLCIa","AwvtrLa","yMvNBw4","y2XVC2veqG","Dg9mB3DLCKm","CMvUDevUzha","qvrbuMi","x2rYB3bhBg8","x29UtwvZC2e","A2v5CW","rLDt","rNfVrNa","BwLZzq","tvzKAxe","DxbNCMfKzw4","x2nVBM5Ly3q","x2n1CNnVCK0","DejJy2G","Cxz2yNa","DMjrzwq","Bg9Nsurhzw4","tu5kzwu","nhWX","uMvJB25Uzwm","x3bYB3rVy28","D2rWBva","z2u6ia","BvLct00","vw1ZrvO","wLrly2O","DxrVuMvJB24","x2rPC3bHDgm","ugHZEfy","y096y3i","q0PequC","BMrLEa","AhLSwg8","C3rHCNq","Dg9Y","zM9Yy2u","EuzmsfK","u09wuxe","tg9Nsuq","x3jLy29UBMu","zwL1tee","rxf0BKy","x2DLBMvYyxq","x29WDgLVBNm","r0LLCNK","CYbHBhjLywq","qujOzLC","x2nSzwfYvgK","rKLmrv9ot1q","mtq2mJr4veDdv1u","y3vYC29Y","vNPqzg4","zcWGDw5RBM8","ignVzgu6ia","u09iuwK","AxHHEhi","BKXnuMq","zg9sAwK","vhfZs2S","Dw5KzwzPBMu","wMjNrKu","uu9srLu","y21Rz0W","uenizNy","DMfSDwvZ","whr4z2e","DhjHBNnHy3q","BhHiwu4","mdaWmdaWmda","A3rkruy","vK5iz04","yxnJCMLWDa","DgjktMG","zfbysM8","D2HrtwC","zgrjrcWGzgu","u2vXsuq","DfLJAve","DwLMy08","B25VCgvU","uwTer24","A0nOAfG","vwDwu1m","Aw5N","y3jLyxrLt3a","uLzhDgK","ywnR","ELDJteS","q09otKvdveK","uu5evhO","tg9NsurozxC","vfLWEeq","Cgf5Bg9Hzfq","yNvMzMvYzwq","sKPVDuG","tujHBgy","DfzhBxK","Ag9kB3G","BezSDxnO","Aw9Ul2PZB24","BNrfBMrWB2K","qvnkr2W","uLbfEMS","x29UrxjYB3i","C3rYAw5N","y2HLy2Tszwe","shDlq0e","ELDNz2u","x2HHBMrSzva","Dunkq00","EvjLy29UBMu","rKTMy24","Dg9cExrLCW","q0fltK8","Ae9Wzw5fDMu","Aw5JBhvKzxm","y2XVC2uSihC","zgvJB2rLzey","CMfTugfYyw0","uuvcqKe","BMfTzq","v2LUzg93","wK5wA1G","DMr6sfK","ENjMCK4","mxWZFdb8mNW","vgPWwgG","BwvZC2fNzq","yxnL","rgDqtfe","qLH4veK","wK1kteu","Cg9PBNrbBMq","u3v5DeO","wwXiEgS","zLzdEwq","A3jeqNy","AxnszwfKEq","we5Ry0y","vLLnr1q","ENf2zK8","teHnB20","AvLesu4","t3HmDfy","BKDWq1q","r2rkB2u","C2vUzf9Hy2S","x3jLywr5q2W","q0Hstfy","DMfS","DNHLteu","BeHHBMrSzxi","rgroDvy","ihrPBwvVDxq","yNL0zu9MzNm","x2LZtwLUAvC","y3vYCMvUDeu","EgvbvMC","nZa3nZqWuw5PD2jA","wM5gELK","BMv4DcGPigm","zgjlq2S","yxKSig5LDhC","wxfPEhO","z2v0","B25nzxnZywC","q2vsrxC","rvHYDg0","qMrzC3e","ugPQCNa","ywr2yw5Jzq","r2vOzuq","uxndsxe","mNW1Fdn8nhW","C1HhtNC","Dvfnz3G","Dw5RBM93BIa","zKXyqxi","D3m6lY8","t3bLBKv2zw4","zw5wv0q","B2zMC2v0","y2XLyxi","AgrLteW","D2LSBfjLy28","Bwf4twvZC2e","y2f0y2G","CMP5twW","zK92ChK","Egf3vwm","wefstwW","AwDRugu","DhjPzxmGCMu","CNrztfe","sKr2s0e","wM14sMC","shrcwuG","Bhr6seq","BMDLza","ChzMELe","AfPIq00","Bxb4tgW","uMnrELO","mxW0Fdn8mhW","C0nVDw50zxi","x2XPC3rLBMu","EMzOuwS","C2vYDMLJzq","Bg1QDNu","x2rItMfTzq","z2v0s2v5","ze9js3K","BMv3vMvYC2K","AgvHzgvYCW","EvzKB2u","ugDiEwC","DgHLBG","EvrXt3m","zNjVBu51Bwi","vw9ty1G","DcbVzIbYyw4","BwvZ","uhnhtLO","u2LJvNG","wufRAfO","DgvmB2Djre4","BM9Vs2e","BMvpAwC","tevjv2m","tNjtC0m","CLDAs0S","Cg9KrNu","Ec11C2uT","Ewjht0u","zNjVBunOyxi","r2HYBw4","vxLLswu","zw50","Dgrhrxe","AeT5B0K","AenSB3nLrxy","x0rctMfTzq","vLHewvq","ugDAsha","BNDtt0S","zhbSuNu","B25JBg9Zzq","BNHTtee","DfzpwxO","BwLUzW","vxDPBMq","Cg9PBNrdB24","ywXty29Wzq","zcWG","DgLTzw91Da","CLbrAMS","qMPbzvO","ue53rxa","tNfVB2u","Aw5PDcbrB1m","BxnN","x3nLBMrby2S","B3Hvqwu","EwT3vxm","x3vYBa","rvztz0u","DgHQzey","yvv4Axq","CwLgrfG","Aw5Lza","B1jZEha","DLb4tMy","tw1VzKe","zfjzqLu","rNrXqKm","yxv0BW","B2fK","uxz1yuK","yuffyvi","zMLN","zwvKzwq","B2LLtu0","D0nHsfa","DuPbAeC","yM9L","ANPiDNa","ywnOzwqSihC","zeXRD1O","zw5HyMXLqxu","yMLUyxj5vhK","x2vUzhbVAw4","wxbtB1u","yw5Nzq","rwrLww4","rwPfrxC","zxD3v1i","s0jMC2K","BMCGDxjSoIa","D2fZq2XLyw4","rvPhu1m","sw1JrMe","z2v0q3vYC28","tfDOAvm","ChvZAa","x2LUAxrqCM8","CvDHuMO","jMPZy2fSBgi","B3bLCNr5","AM9PBG","D3DethG","De1HBMfNzxi","r3zhD00","BfHsA1K","CMvHzg9UBhK","BujOB1q","CMvZzxrfBMq","B3PzrvC","yNrcCwq","ALPkBwy","BK1eDMS","B3bLBG","r0vjwMy","DhjPBq","yNvMzMvY","wuTKu08","u1zNzKi","z2v0sxrLBq","DxnLCKLW","EKfbuw0","nhW3Fdf8mta","zgTSq20","DhvcrKO","EgzHrLC","Cw9Zx18","ywDLsgLKzq","z2virKW","zxj2AwnL","rhfTA3a","zM9YrwfJAa","CgLUz0LUDgu","x21PBMLoyxy","BM9Uzv9UB24","CMv0CNLdB3u","zwn0","s1rKug8","v3DoD2C","DxrMofDYAxq","uM5lweK","DufkEfu","DMfSDwu","AwXLx25HBwu","zKP6CKW","uuPxwhq","y2vZC0HHBMq","qujVAeS","CMzPA1G","C2v0sxrLBq","Aw5KzxG","zxjYtM8","Cgf5Bg9Hza","zenWB3y","Ew5ptui","q3LiBLm","u2ryEfq","y3vZDg9Tshq","vKLhq2q","AKXls3q","vw5Ws20","EgXfDMm","yxbWzw5Kq2G","t3nIqxK","zgf0yq","wKnjq2q","zw50tgLZDgu","Egf1CuG","ywnRx2nVzgu","q3vZDg9Tq2W","C3fJru8","zgvIDwC","yvj4rgi","o2nOyxjZzxq","zeTkBhm","vfPHDxC","zxjFAxnFywm","y0HtAvu","C3rLBMvYCW","B3vUDa","rwXYCNy","C2vYDMLJzs0","zMXVB3i","s0Hyu1u","CMvHC29U","AffHBLG","qw1VDw50","ig1LC3nHz2u","shbjtfq","CgfYC2u","AMrTshy","Dg9VigXHCMC","ChjVDg90Exa","zKz1BLO","BMr0yLa","x1fVu01HBMe","Cg9W","DwvVt2W","CxrUENy","wxPYt3C","ruHjCeG","rwzUB3G","B25fCNjVCG","sLnptLa","Aw9UvgLTzw8","zxjYB3i","CMvZzxruCMK","ChvKAfO","u0rVAfa","DhLWzq","x2fKzfDZtgK","AgfZ","B25pCgvU","B2nRzxrgywK","AxmGDw5Kzwy","x2LUDgvYDMe","z1jjBui","C2XPy2u","EvL5uge","C0XPC3rLBMu","Bwf4uMv0CMK","zvfjqNq","uNzov0u","D1bfEwm","BMfxtKS","qNjPzgDL","te1ArMu","rwjgrKC","B1Piwu8","yw1KChG","Cur0ueG","t25Zr2i","serHz2K","Aw47y2HHCNm","rvzcB3C","DLvzwLu","AffitNm","C2v0","zNjVBujPDhm","ue9gB1C","AxrAC0S","q3PxELG","veLmywi","rKfUC1K","A0jzqKC","q0rAzLm","EvDwv2C","tuvtu0fhrv8","BIWGAg9ZDg4","AMLMveW","CePRrgu","C2TIvwW","Cvv2twW","zMLSDgvY","Bxzmq3a","C2jzrxy","AwXK","AeDhtLK","ugXzDLa","tLDszuu","rLjzwLu","z3DOqw8","pxv0zI04","BLLUCKW","ywnRtxnNswq","vMzIvw8","lcbTyxGGCMu","B25Uzwn0Aw4","seL6Bgy","B25SAw5L","rfntBLG","q3vZDg9Trxi","s3HesMS","yKrnCMW","mZy2mtD3sunmu3y","z2v0t3DUuhi","ngvsEw1XvW","B3jpBMXPBMu","DcbSAw1PDa","DuTpzue","z3rwsxi","CuTbCK8","zxLZqKi","zwH0wxC","tvrJAg4","B2zMBgLUzq","q1b6shu","Dfr3C2i","BwfUDwfSihi","B25TzxnZywC","vg5dsLu","zfv1sgG","mxWZ","y29Kzq","DeLK","zufVsxq","DLrQu1m","zwXYtgq","wMn1ueC","vMv3DK0","BNrbBMrvCgq","AgfZt3DUuhi","q0Xpu0LorW","DMvUDa","zxjHDg9Y","u3DdCvC","BwviAKy","BNbIwMC","y29SBM8","AxnFywnR","DgrUzuG","Bg9NsurozxC","x2zVCM1HDeu","ihrVihjLDhi","zxjFDhrS","ywjVCNq","z1rPBwvVDxq","v0fnEeG","B25szwnLAxy","q29Kzq","v2L0sNy","yLHzrM8","CNzOzxy","Aw5KzxHpzG","zvvbze0","rNrYEgu","tfrwww0","EvjAveq","vuvgsfq","DLzNtLy","rxjYB3jdB2q","B2nKwu8","ywDL","BMrWB2LUDfq","wKXHvKi","sevOyw0","wvHzquO","AuTys3y","x2jPBMfYEvq","ihzHBgLKihm","Dw50","wvfHEei","B3bLBKrc","qMXZtu0","vevyrhi","ywrKrxzLBNq","weTVD1e","zgTJwLa","Fdz8ohWY","y3jLyxrLtwu","x3bPBMC","zfvqz1e","sNHLDeS","rKPdvee","lcbxzwjtB2m","ENPjr0i","z0Tnsxe","tMzTCe0","zwTPA0K","u1fuyuG","C2rIwwW","tK1hC0q","x3jLBw92zvC","x29UvgLTzw8","B3nLrxzLBNq","uLjpuG","whjgufK","zNjVBuj5Dgu","ALbUueO","EfvZzuvUDG","BwvKAwf0zwW","rfDXwg4","Dgv4Dc9WBge","Dfnqwuq","B25tDg9Wsw0","uMzsB0S","zNH2t0O","ChjVDg9JB2W","aaaaaaaaaaa","Dg9tDhjPBMC","se5zEKm","igXHCMDLCIa","CKTqz3u","tKfusvzfx0u","CNDPtfq","x2LZqNjVD3m","AwTnruK","qxblzK4","BMnVzgLUzW","CMvWBgfJzui","AxnrB1nby2S","Au9yzwq","BuDdAw0","zK92zM4","u2fTueO","zLDjz1G","A09oAha","rezYwwS","C3DtDuy","zMLUza","Bwv0Ag9K","AfDqEgW","zw5fDMvUDa","y2fSBa","ALHZzg4","CMvXDwLYzwq","Awfgq2m","AwjUvgW","CNzHBa","t1PvvwG","zgLZCgf0y2G","BNzAyLe","B21cDuq","AMfjBwy","BKfMBvm","r2rtBKu","BwLUAvbYB2C","B05Iuey","tLb2Dfm","z29PBMCGyxC","ihrPBwvZ","ueTUwgi","sxfbtvm","C0jf","BKPkA3G","shbgwgS","t2TpsLe","x2LZv29YA2u","Axnby2TdBgu","ugD1BfC","mtaYt3HyA1vz","rw16r0C","z2v0u3rVCMe","z1bbyKC","D1DYzMy","rwndDMK","ywDLu2HVDW","zMvY","AxnbCNjHEq","wuP2Aei","B2zM","D0TOshO","DvjWAvy","AuT2yMm","yxblzxa","u29nu1O","sffjtvK","AK9mDe0","zffHEKi","D1b2BLO","C3jJ","t2jQzwn0","twLZC2LUzYa","rMv6EwC","lcbOB3n0BMe","yLzdzuu","tMfTzq","v2zACNK","zxH0zw5ZAw8","BwvY","r3jOANO","ywzL","yuXqsva","Ee9hqNa","BMCGzMfPBgu","y3vYCMvUDeK","whv6C1y","wwDMrKy","B21mBfG","tLf6uNC","ywrKq291BNq","DeLUDgvYy2u","vxz4y08","B3bLCNr5tMe","qNHLsfq","yxv0B21HDgK","zw1LBNq","vfPbuxm","suvtx0vsuK8","BKXgu2O","uNDIAe8","zxjYtxnN","ExPry2C","y2PVv0S","CLzHBhvLCW","ywXPzcb1CMW","vKzPwNK","q0PAt2W","qLz5yuy","CMzWs20","t2n2qMm","Dg9cExrLC0i","ExbL","x2rPC2nVBM4","zv90Aw1LB3u","y3vYC29YlNm","DgLTzw91DcW","A2v0ignVBNm","EM1fDKq","yvrpDKe","zu5rD3q","z2v0q3vYCMu","rNP2tfa","uwfbuNq","CfH4Ee0","zNbZD2G","BK9lveK","x2HHBMrSzvi","q2fvC1G","mtf8n3WYFdK","uevRqwi","qLD6yxe","zw5JB2rLrNi","CMvTB3zLrxy","ywrKt25L","x2rLyNvN","AgvKtwf4uMu","q0rYuKy","uw1uEwW","sKTmu2C","zvvYBa","DgfIyxnL","Euz5v2G","y3jLyxrLrwW","D3jPDgvvAw4","qvrhANa","vwnwB1G","EwLZzfO","nNWXFdn8mG","DMLJzuLeig8","qNr0Cgu","CMvZDwX0","Cxf3wfa","igzHAwWSig0","z3bbCNK","Dgv4Dc9Qyxy","y09Wzw4","sMftvxm","y3jLyxrLrxi","CLDWt1q","u1nYy0G","vKXID2S","twTcAgK","CMvTB3zLq2G","Bfzjrxe","rKrKBgK","ywvjrgW","zhnTDu0","su5hvva","yMrFzgLK","zw5JB2rPBMC","Dhfbtfa","ywX3yxLZ","C2vUza","C2zOrwK","ntCYotKXvhHnshvI","vw5Oyw5KBgu","y2HLy2TdDxi","BuzRvKO","tffmwhy","B2fUA0q","x3nLCuLK","x2LZsw5PDa","B25mAw5L","BeD5zw8","wNjdvgi","y29UDgv4Da","zNjVBuHHC2G","x3fVC0rc","EeXOq0S","z2vjBMzVu3K","y29UC3rYDwm","ntq5u2Dtz2nu","vuHluu8","t2P6ELq","y2uGBM90igK","ufLdALC","zMX1C2HfEha","zwzAqvK","rvjst1i","zMrzrwO","vw1QrLK","sgXpD1C","nZG1mZuWCgzpwKLJ","Bu9srgO","qwHXAuC","y1PdC0S","r0HODKq","CLPjCem","A0LjEg4","rfvUChm","t0vVwgi","CNjVCK1LC3m","sNLJz1u","y3jLyxrLuMu","D3v4r3u","Ec1TC2CTy3u","vLnnuvy","A0PUC0u","y3r4","B1Hey20","y29TCgXLDgu","AfnPEeq","uMXKrvq","EKX4v3q","u3rYyxrLz3K","zM9zEMS","CvniBLm","y2XVC2u","C3vvtfi","CMv1tNe","zMzLCG","tKPXEu8","vMvcwuu","q0jPA1u","B2LUDfjLywm","D3jPDgu","BNruCMLLC0m","ruPdy2u","igfYCMf5yNu","ywXS","zMLSzw5HBwu","nhW3Fdv8mhW","CMvHzhLtDge","DfL5DeK","zgnPvMC","CNHluK4","werXu0y","svj6uKy","BLzIEMC","Aw55DgW","CNb3sK0","ywXSq3vYC28","zu9kAfe","AfrdAMG","Ew5MwfC","AuDVthq","t29lELu","suPQCfq","q291BNq","zuH2y1C","CwTtsee","wvnZuhO","mxW2Fdv8m3W","D1rwC1m","u3jfrKq","ChrVCG","BwvZC2fNzv8","u2HHCMvKv28","EKzLAeG","BuvrCw4","y29UBMvJDgK","ExPprNC","Awf3Dvy","vgLTzw91Da","wNfUzxy","qMr3yvC","B2jQzwn0u3q","CgrUBe8","AeLzwLq","yKPSvMO","y3ruAw1LB3u","C3bSAxq","vMD1z0e","D2XZELe","AK5ACeS","qLjwvKy","B25ozxr3B3i","Eg11Bxm","yNL0zxm","s1Pvue4","DxfOshO","AwXSihvZzsa","svzpB3O","tMTNteG","Ec1TC2CTCw8","zNjVBNrPzxi","DNjzBu0","AunZD0u","s25ewKO","Bw9Awgu","C2v0u3rVCMe","r0PSEva","EvvYsLi","AfDoA3i","AxjLza","vwTfq2C","Ee1SCgm","yxrLq291BNq","B3jRzxjhBg8","wfbdq0m","tuTfAwq","BxnjsKC","veHosMS","AhvNv24","t1joB24","sKvUzLi","DgfYz2v0","zw5HyMXLuw8","BgLUzw5V","y2Xxu2y","zxHWB3j0CW","BMvY","vfPIzLq","zufJAW","yw1Lu3bHy2u","ChbL","D24GCMvHC28","y1nwrNe","y291BNq","EgTYtK4","DMvYC2LVBG","u01hvMq","Bg9N","ywnRDxbfBMq","AefJA01LC3m","AgvHzgvY","uLLqExq","y2HnyxHuCMK"];return Vo=function(){return t},Vo()}function Vv(t){let e=M,n={omLlX:e(1576)+"or",tlEDN:e(1451),HpILT:e(1055),bDMrl:e(1165),EGzQW:function(s){return s()}};if(Jo[e(1061)](t))return;let i=new Promise((s,c)=>{let d=e,u={MoZwX:n[d(1803)],XqPVu:n[d(1038)],wwDLx:n[d(1123)],wOHSi:function(_){return n[d(1580)](_)}},h=()=>{let _=d;t[_(1363)+_(1016)+_(1552)](u[_(1578)],x),t["removeEv"+_(1016)+_(1552)](u.XqPVu,m),t["removeEv"+_(1016)+_(1552)](u[_(952)],m)},x=()=>{s(),u.wOHSi(h)},m=()=>{let _=d;c(t.error||new DOMException(n[_(1318)],n[_(1318)])),h()};t[d(1195)+d(1617)](d(1451),x),t[d(1195)+d(1617)](n[d(1038)],m),t[d(1195)+"Listener"](n.bDMrl,m)});Jo[e(1087)](t,i)}function Jv(t){Yo={NclsS:function(i,s){return i(s)}}[M(1616)](t,Yo)}function Zv(t){let e=M,n={SbRKL:function(i,s){return i(s)},ueoOl:function(i,s){return i(s)},tdneH:function(i,s){return i(s)},jzHvp:function(i,s){return i in s},YhThB:e(1507)+e(1718),THNJk:function(i){return i()},hSixD:function(i,s){return i===s},ZmxJg:e(1426)};return t===IDBDatabase.prototype[e(709)+e(1594)]&&!n[e(928)](n[e(1714)],IDBTransaction[e(1042)+"e"])?function(i,...s){let c=e,d=t[c(1253)](n.SbRKL(rs,this),i,...s);return Bd.set(d,i[c(466)]?i[c(466)]():[i]),n[c(1716)](zt,d)}:n[e(1543)](Kv).includes(t)?n[e(1452)](n[e(838)],n.ZmxJg)?function(...i){let s=e;return t[s(461)](n[s(1047)](rs,this),i),zt(Fd[s(807)](this))}:this["currentEndpointT"+e(403)+"t"]:function(...i){let s=e;return n[s(1160)](zt,t.apply(n[s(1160)](rs,this),i))}}function Yv(t){let e=M,n={VSMQV:function(i,s){return i===s},GqPNK:"function",hZbCM:function(i,s){return i(s)},BEjVF:function(i,s){return i instanceof s},ZCvLz:function(i){return i()}};return n[e(1447)](typeof t,n[e(551)])?n[e(843)](Zv,t):(n[e(457)](t,IDBTransaction)&&n[e(843)](Vv,t),Dx(t,n[e(1668)](Wv))?new Proxy(t,Yo):t)}function zt(t){let e=M,n={ZZRns:e(778),hdeLL:"kQtTN"};if(t instanceof IDBRequest)return $v(t);if(Ko.has(t))return Ko[e(807)](t);let i=Yv(t);return i!==t&&(n[e(375)]===n[e(826)]?(this[e(1820)+"ount"]=_0x25d5d2,this[e(1559)]=0):(Ko[e(1087)](t,i),Zo[e(1087)](i,t))),i}var Dx,Sx,Ix,Fd,Jo,Bd,Ko,Zo,Yo,rs,Ax=Cx({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={CyEUY:function(n,i){return n instanceof i},Dqmkp:function(n,i){return n===i},ZLcXX:t(355),ZNVkX:t(1507)+"oreNames",RldET:"store",qWaRj:function(n,i){return n(i)},skbUl:function(n,i){return n!==i},rWpOT:"jynyw",fDlAu:t(657),fdYEj:function(n,i){return n in i}};Dx=(n,i)=>i[t(1707)](s=>n instanceof s),Fd=new WeakMap,Jo=new WeakMap,Bd=new WeakMap,Ko=new WeakMap,Zo=new WeakMap,Yo={get(n,i,s){let c=t;if(e[c(1589)](n,IDBTransaction)){if(e[c(980)](i,e[c(1670)]))return Jo[c(807)](n);if(i===e[c(765)])return n[c(1507)+c(1718)]||Bd[c(807)](n);if(e.Dqmkp(i,e[c(1453)]))return s.objectStoreNames[1]?void 0:s[c(1507)+c(357)](s[c(1507)+c(1718)][0])}return e[c(948)](zt,n[i])},set(n,i,s){return n[i]=s,!0},has(n,i){let s=t;return n instanceof IDBTransaction&&(e[s(980)](i,e.ZLcXX)||e[s(980)](i,s(516)))?e[s(1101)](e[s(1389)],e.fDlAu)?!0:new _0x53a8e5(c=>{let d=s;_0xc9307(c,this["_getInte"+d(353)+"e"](_0x42dcd1))}):e[s(1430)](i,n)}},rs=n=>Zo[t(807)](n)}}),Rx={};jv(Rx,{deleteDB:()=>Qv,openDB:()=>Xv,unwrap:()=>rs,wrap:()=>zt});function Xv(t,e,{blocked:n,upgrade:i,blocking:s,terminated:c}={}){let d=M,u={KcGQH:d(846)+"2",wlszQ:function(m,_){return m!==_},gwhAo:function(m,_){return m===_},kBYBG:function(m,_,S,y,v){return m(_,S,y,v)},dCpov:function(m,_){return m(_)},JDxsY:function(m,_){return m(_)},CBikU:"close",KBfsi:"versionc"+d(408),mygUy:function(m,_){return m(_)},dCJIj:d(653)+d(923),VeBYE:"blocked"},h=indexedDB[d(963)](t,e),x=u[d(540)](zt,h);return i&&h[d(1195)+d(1617)](u.dCJIj,m=>{let _=d,S={mBhoT:u[_(612)],qqwXP:function(I,A){return u[_(1514)](I,A)}};if(u[_(1111)](_(1118),_(1657))){let I=S[_(957)].split("|"),A=0;for(;;){switch(I[A++]){case"0":_0x16ddc7[_0x383c28](v,v.exports,_0x3005c7);continue;case"1":var y=_0x575231[_0x392fd8];continue;case"2":return v[_(1551)];case"3":var v=_0x30bb28[_0x5e2681]={exports:{}};continue;case"4":if(S[_(1382)](void 0,y))return y[_(1551)];continue}break}}else u[_(1094)](i,u[_(1003)](zt,h[_(1381)]),m.oldVersion,m[_(855)+"on"],u[_(405)](zt,h[_(709)+_(1594)]))}),n&&h[d(1195)+d(1617)](u[d(1463)],()=>n()),x[d(859)](m=>{let _=d;c&&m[_(1195)+_(1617)](u[_(1464)],()=>c()),s&&m[_(1195)+_(1617)](u[_(939)],()=>s())})[d(829)](()=>{}),x}function Qv(t,{blocked:e}={}){let n=M,i={oXDcm:n(1688),jOLtM:function(c,d){return c(d)}},s=indexedDB[n(1826)+n(1371)](t);return e&&s["addEvent"+n(1617)](i[n(1450)],()=>e()),i[n(1297)](zt,s)[n(859)](()=>{})}function Tx(t,e){let n=M,i={hwlLe:function(h,x,m){return h(x,m)},MaXlN:function(h,x,m){return h(x,m)},euJrG:function(h,x){return h!==x},VKdTg:function(h,x){return h===x},iQrhO:n(667),RoOtX:"readwrite",RYPyt:n(956),YKdSO:function(h,x){return h instanceof x},jaImf:function(h,x){return h in x},SSrcH:function(h,x){return h===x},tYytI:n(747),SQTaH:function(h,x){return h!==x},roPri:n(840)};if(!(i[n(967)](t,IDBDatabase)&&!i[n(1263)](e,t)&&i[n(1390)](typeof e,i[n(1474)])))return;if($o[n(807)](e))return $o[n(807)](e);let s=e.replace(/FromIndex$/,""),c=i[n(1209)](e,s),d=Ox[n(758)](s);if(!i[n(1263)](s,(c?IDBIndex:IDBObjectStore).prototype)||!(d||Px[n(758)](s))){if(i[n(1209)](i[n(383)],"eaDqh"))return;i[n(536)](_0xcb5f76,_0x5afa7f,10),i[n(1763)](_0x407563,_0x435581,_0x176029)}let u=async function(h,...x){let m=n,_={LBxwa:function(S,y){return i.euJrG(S,y)},LHjQV:function(S,y){return S>>>y},DLCLQ:function(S,y){return S===y},TZauw:function(S,y){return i[G(348)](S,y)}};if(m(667)!==i[m(1582)])return _0x527276[m(1719)](_0x2c1f27)||(_0x5dc676=_0x5e6bbb[m(861)+"er"](_0x2c8ba7)),_[m(391)](this[m(1770)],_0x4f8ebd[m(1770)])&&_[m(498)](this.high,31)===1&&_.DLCLQ(_.LHjQV(_0x51aff0[m(1613)],31),1)?!1:this[m(1613)]===_0x163e5b[m(1613)]&&_[m(1025)](this[m(395)],_0x1f96ca[m(395)]);{let S=this[m(709)+m(1594)](h,d?i.RoOtX:i[m(1567)]),y=S.store;return c&&(y=y[m(1e3)](x[m(393)]())),(await Promise[m(1470)]([y[s](...x),d&&S[m(355)]]))[0]}};return $o[n(1087)](e,u),u}function G(t,e){t=t-342;let n=Vo(),i=n[t];if(G.tqauks===void 0){var s=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",_="";for(let S=0,y,v,I=0;v=h.charAt(I++);~v&&(y=S%4?y*64+v:v,S++%4)?m+=String.fromCharCode(255&y>>(-2*S&6)):0)v=x.indexOf(v);for(let S=0,y=m.length;S<y;S++)_+="%"+("00"+m.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(_)};G.MBNNdD=s,G.SYUbri={},G.tqauks=!0}let c=n[0],d=t+c,u=G.SYUbri[d];return u?i=u:(i=G.MBNNdD(i),G.SYUbri[d]=i),i}var Px,Ox,$o,eS=Cx({"node_modules/idb/build/index.js"(){let t=M,e={IVOoz:t(402)+t(661),naWNK:t(807),BWUqf:t(360)+"ys",IyZZJ:"count",LEIWc:function(s,c){return s(c)},cIQwc:function(s){return s()},Bttpe:t(1797),Rgexm:t(435),kXtel:t(1843),SMGVd:"clear"},n=e[t(1523)][t(1512)]("|"),i=0;for(;;){switch(n[i++]){case"0":Px=[e[t(1074)],t(853),"getAll",e.BWUqf,e[t(529)]];continue;case"1":e[t(871)](Jv,s=>({...s,get:(c,d,u)=>Tx(c,d)||s.get(c,d,u),has:(c,d)=>!!Tx(c,d)||s[t(1061)](c,d)}));continue;case"2":e.cIQwc(Ax);continue;case"3":Ox=[e[t(1380)],e.Rgexm,e.kXtel,e[t(1562)]];continue;case"4":$o=new Map;continue;case"5":e[t(1624)](Ax);continue}break}}}),tS={idb:function(t){let e=M;t[e(1551)]=Promise.resolve()[e(859)](()=>(eS(),Rx))[e(859)](function(n){return n})}},kx={};function Ft(t){let e=M,n={ZsRlF:e(768)+"4",QmTyl:function(u,h){return u!==h}},i=n[e(1765)][e(1512)]("|"),s=0;for(;;){switch(i[s++]){case"0":var c=kx[t]={exports:{}};continue;case"1":var d=kx[t];continue;case"2":tS[t](c,c.exports,Ft);continue;case"3":if(n[e(1368)](void 0,d))return d.exports;continue;case"4":return c.exports}break}}Ft.d=(t,e)=>{let n=G;for(var i in e)Ft.o(e,i)&&!Ft.o(t,i)&&Object[n(1641)+"operty"](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Ft.o=(e,n)=>Object[t(1042)+"e"][t(1151)+t(950)][t(1253)](e,n)})(),(()=>{let t=M,e={xmums:t(1222)+t(1083)+"et=utf-8",PwJFl:t(409)+t(742),vdzHY:t(984)+"e",DbQsB:function(n,i,s,c){return n(i,s,c)},gnCvi:function(n,i){return n!==i},dbKCk:t(342),ZgBHC:function(n,i){return n!=i},WjhbL:t(702)+"d",UmkNE:t(556)+"le"};Ft.r=n=>{let i=t;if(e.gnCvi(e[i(804)],e[i(804)])){let s=oe[i(686)].payloadEncoding instanceof _0xe94ab?{force:!!oe[i(686)][i(1728)+"ncoding"][i(678)],encoding:oe[i(686)][i(1728)+i(1238)][i(1400)]?oe._options["payloadE"+i(1238)][i(1400)][i(1759)](/\s/g,"")[i(643)+i(771)]():""}:{force:!1,encoding:oe[i(686)][i(1728)+"ncoding"]?oe[i(686)][i(1728)+i(1238)][i(1759)](/\s/g,"")[i(643)+i(771)]():""},c=_0x2992b3[i(1728)+i(1238)]?_0x5e5513[i(1728)+i(1238)].replace(/\s/g,"")[i(643)+i(771)]():"",d=oe[i(686)]["payloadT"+i(1342)]instanceof _0x1d18d1?{force:!!oe[i(686)]["payloadT"+i(1342)][i(678)],type:oe[i(686)][i(735)+"ype"][i(1059)]?oe._options[i(735)+i(1342)][i(1059)].replace(/\s/g,"")[i(643)+i(771)]():""}:{force:!1,type:oe[i(686)].payloadType?oe[i(686)][i(735)+i(1342)].replace(/\s/g,"").toLowerCase():""},u=_0xec11eb[i(735)+i(1342)]?_0x1b3b87[i(735)+i(1342)][i(1759)](/\s/g,"")[i(643)+"ase"]():"",h=d[i(678)]?d[i(1059)]:u||d[i(1059)],x=s[i(678)]?s.encoding:c||s[i(1400)],m=[e[i(1518)],e[i(511)],i(409)+i(742)+i(1023)+"=utf-8","string"],_=[e[i(766)],i(351)];oe._options[i(364)+i(1640)+i(1836)+"ad"]&&m[i(758)](h)&&(!x||_.includes(x))?_0x1de762.textPayload=e.DbQsB(_0xf973f6,_0x307ea1[i(1002)],0,_0x59e15e[i(1002)].byteLength):_0x54333a[i(1672)+i(919)]=""}else e[i(1683)](e.WjhbL,typeof Symbol)&&Symbol[i(1229)+"Tag"]&&Object[i(1641)+i(950)](n,Symbol[i(1229)+i(404)],{value:i(462)}),Object[i(1641)+i(950)](n,e.UmkNE,{value:!0})}})();var Oe={};(()=>{let t=M,e={ROdeg:function(a,r){return a(r)},XzOiL:function(a,r){return a+r},EvsXd:function(a,r){return a+r},SBBzl:function(a,r){return a*r},cMaHk:function(a,r,o){return a(r,o)},inytl:function(a,r){return a(r)},PeLHB:function(a,r){return a(r)},yFyWh:function(a,r){return a+r},gKMIq:t(1667),whQMg:t(519),XDqSF:t(711)+t(711)+"00000000"+t(711),qGaZx:"0|4|1|2|3",xkrNN:function(a,r){return a>r},Zqnev:function(a,r){return a<r},dQvec:function(a,r){return a!==r},oRzqO:function(a,r){return a-r},gQzYL:function(a,r){return a<r},EZGSS:function(a,r){return a===r},gRImB:t(988),LQLXv:"uWIMd",qSHnS:t(767),UdVSM:t(680),SVgfB:function(a,r,o){return a(r,o)},dklCm:function(a,r,o){return a(r,o)},nxmLA:function(a,r){return a>>>r},lXJVW:function(a,r){return a&r},lyXZj:function(a,r){return a|r},TqsKk:function(a,r){return a|r},HCCBd:function(a,r){return a<<r},iQguh:function(a,r){return a&r},qeOVb:function(a,r){return a|r},msimk:function(a,r){return a<<r},rBSWn:function(a,r){return a<<r},tYciQ:function(a,r){return a&r},MkBhi:function(a,r){return a<r},vJsfn:function(a,r){return a<<r},GEIZf:function(a,r,o,l){return a(r,o,l)},sqcEO:function(a,r){return a(r)},oODMH:t(1109),Ghrmn:t(1757),nVbzg:function(a,r){return a(r)},ndtbP:function(a,r){return a>>>r},VAsaG:function(a,r,o){return a(r,o)},nGpCT:function(a,r){return a(r)},QvuaI:function(a,r,o){return a(r,o)},RuvHe:t(1302)+t(1255)+t(1608)+"key",NJqyO:function(a,r){return a===r},bVCeE:t(1302)+t(1255)+t(1608)+t(992),VYMGT:function(a){return a()},omBuD:function(a,r,o){return a(r,o)},HEham:"xGUZw",vNyBi:function(a,r){return a!==r},rPQjk:function(a,r,o){return a(r,o)},DEOyh:function(a,r,o){return a(r,o)},dOIKy:function(a,r,o){return a(r,o)},IbQvN:function(a,r){return a!==r},HNYzC:function(a,r,o){return a(r,o)},BdYsq:function(a,r){return a(r)},TngGS:function(a,r){return a!==r},qDtPH:function(a,r){return a(r)},HKcAj:function(a,r){return a!==r},YJvhB:function(a,r,o){return a(r,o)},BxeHT:function(a,r,o){return a(r,o)},CHRLV:function(a,r,o){return a(r,o)},zMeTT:function(a,r,o){return a(r,o)},XMimX:function(a,r){return a!==r},YgfFF:function(a,r,o){return a(r,o)},wXxhS:function(a,r,o){return a(r,o)},MVdiq:function(a,r){return a!==r},DWqXn:function(a,r,o){return a(r,o)},gPAbG:function(a,r){return a!==r},foYzk:function(a,r){return a(r)},zLxWt:function(a,r){return a===r},WfZry:function(a,r){return a(r)},tHPfs:function(a,r){return a>>>r},Ohzde:function(a,r){return a(r)},ImcFa:function(a,r){return a(r)},jdmHv:function(a,r){return a(r)},cSVFq:function(a,r,o){return a(r,o)},CJDAG:function(a,r,o){return a(r,o)},LTVYm:t(1302)+t(1255)+t(1608)+t(719),YSsPz:function(a,r){return a===r},kChhX:t(1302)+"required"+t(1608)+t(681),pJkDe:t(1302)+t(1255)+t(1608)+t(850),Vvlgi:t(1302)+t(1255)+" field: method",jPnPJ:function(a,r){return a+r},qNNHC:function(a,r){return a(r)},OowYs:function(a,r,o){return a(r,o)},NkgLH:function(a,r){return a(r)},UQzFv:function(a,r,o){return a(r,o)},AWxnH:"Unimplem"+t(609)+t(1834),iawuV:function(a,r){return a>=r},ZLaVB:function(a,r,o){return a(r,o)},EJCce:function(a,r){return a&r},gPQPL:function(a,r){return a!==r},ePeuU:"JYICF",mpxLl:function(a,r){return a>>r},LMZFe:"Skip pas"+t(1128),sfhEi:function(a,r,o){return a(r,o)},HtBYH:t(1443),kONhp:function(a,r){return a*r},Ndglt:function(a,r){return a>r},NMGsD:function(a,r){return a>r},zzIGB:function(a,r){return a+r},ZRwUh:t(1839)+t(1128),HpFXk:function(a,r){return a+r},WXUla:"4|2|1|3|"+t(1792)+"|0|10|6|8",kIIxn:function(a,r){return a|r},vbQed:function(a,r){return a<r},DFrYk:function(a,r){return a<r},quAcU:function(a,r){return a>r},OjzzT:function(a,r){return a|r},BdwaW:t(518),fpswh:function(a,r,o){return a(r,o)},rfikX:function(a,r){return a<r},JaSUs:function(a,r){return a+r},zFehH:function(a,r){return a&r},DBEOL:function(a,r){return a===r},XiFyI:function(a,r){return a+r},wgFlq:function(a,r){return a+r},ekANU:function(a,r){return a&r},ikVMX:function(a,r){return a&r},pyzNs:function(a,r){return a+r},UHKQO:function(a,r){return a&r},zjrEF:function(a,r){return a&r},HDagi:function(a,r){return a<<r},sNcsR:function(a,r){return a<r},TEXDr:function(a,r){return a<=r},elrLd:t(732),VKLJG:t(987),VNHgN:function(a,r){return a==r},gBSSO:function(a,r){return a&r},Uwind:function(a,r){return a>=r},YatRx:function(a,r){return a+r},CeREw:function(a,r){return a+r},nVwcE:function(a,r){return a+r},podFu:function(a,r){return a!==r},oieMM:function(a,r){return a|r},yuEQI:function(a,r){return a<<r},RvPLV:function(a,r){return a<<r},FKfcn:function(a,r){return a|r},AzOvz:function(a,r){return a|r},thjdF:function(a,r){return a|r},NgxdA:function(a,r){return a<<r},WAMxH:function(a,r){return a&r},fJzrL:function(a,r,o){return a(r,o)},aYluJ:function(a,r){return a+r},iCswE:function(a,r){return a+r},HQIMY:function(a,r){return a<r},ZcuPG:function(a,r){return a<r},WPbcT:function(a,r,o){return a(r,o)},BjAeZ:function(a,r){return a<r},mEQqn:function(a,r){return a-r},ZCICd:function(a,r){return a<r},iYDIN:function(a,r){return a&r},uCJCM:function(a,r){return a|r},uwilz:function(a,r){return a>>r},qkSHA:function(a,r){return a&r},jSBWi:function(a,r){return a>>r},NPvtS:function(a,r){return a|r},PXDxZ:function(a,r,o){return a(r,o)},RwJxU:t(356),eZFpI:t(1809),McAuP:function(a,r,o){return a(r,o)},tdJnf:function(a,r){return a===r},JDvKA:"AoBDk",FtqBC:function(a,r,o){return a(r,o)},RmXkn:function(a,r){return a&r},VPOqa:function(a,r){return a<<r},MsmXi:function(a,r){return a<<r},tQLtB:function(a,r){return a(r)},eQIBt:function(a,r){return a&r},PCHfv:function(a,r){return a(r)},bJlVj:function(a,r){return a(r)},PsGNZ:function(a,r){return a<<r},gtVIr:function(a,r){return a&r},gtMOH:function(a,r){return a<<r},hMEvc:function(a,r){return a&r},dciVg:function(a,r){return a&r},uRvZW:function(a,r){return a>>>r},OoKzU:function(a,r){return a===r},bYYQd:function(a,r){return a===r},CtdgD:function(a,r,o){return a(r,o)},eoJqx:function(a,r){return a>>>r},dUPgQ:function(a,r){return a+r},EcCvi:function(a,r){return a&r},pcMzl:function(a,r){return a|r},vWooQ:function(a,r){return a>>>r},GHhvD:function(a,r){return a!==r},cceiE:function(a,r){return a|r},neOig:function(a,r){return a>>>r},YXYAJ:function(a,r){return a&r},AsqBL:function(a,r){return a>>>r},CJZOl:function(a,r){return a+r},Buvxe:function(a,r){return a>>>r},eHvcW:function(a,r){return a!==r},tVOYz:function(a,r){return a|r},TezYV:function(a,r){return a+r},oRsxp:function(a,r){return a!==r},aTOvA:function(a,r){return a|r},OEoXb:function(a,r){return a&r},XANMz:function(a,r){return a>>>r},ZxeJx:function(a,r){return a>>>r},lmjvu:function(a,r){return a!==r},efZAY:function(a,r){return a&r},tVGmy:function(a,r){return a(r)},fOvpy:function(a,r){return a(r)},UxDme:function(a,r){return a|r},gndKs:function(a,r){return a|r},sKsgg:t(960),qmHoS:"service",npbZg:t(1031)+t(763),CgoAl:t(763),xMlpc:"curvalue",NDMco:"MzLFA",xzfzp:t(1226),AcsCF:function(a,r){return a(r)},WJdte:t(885),xlEvc:function(a,r){return a<<r},crDtB:function(a,r){return a<<r},PLCHM:function(a,r){return a>r},PEkAb:t(1358),FaWNP:t(1715),qiFDX:function(a,r){return a|r},DTLsb:function(a,r){return a<<r},CnDsm:function(a,r){return a<<r},YnlBr:function(a,r){return a|r},PFkye:function(a,r){return a>>>r},IicTw:function(a,r){return a|r},oxUAe:function(a,r){return a<<r},pXxxM:function(a,r){return a<<r},GtqQG:function(a,r){return a&r},nGogU:function(a,r){return a&r},nRson:function(a,r){return a&r},amdpx:function(a,r){return a>>>r},FgDwN:function(a,r){return a>>>r},ktJEF:function(a,r){return a>=r},vLQzu:function(a,r){return a+r},jZJmf:function(a,r){return a|r},GzLCr:function(a,r){return a%r},JJouH:function(a,r){return a/r},uXdNf:function(a,r){return a+r},yVdoe:function(a,r){return a*r},UIKoY:function(a,r){return a>>>r},meHjF:function(a,r){return a+r},USgET:function(a,r){return a*r},DdBan:function(a,r){return a>>>r},WHpMC:function(a,r,o){return a(r,o)},yzQcg:function(a,r,o){return a(r,o)},XIstx:function(a,r){return a!==r},yTqOs:"bMJeq",qTsxy:function(a,r){return a===r},fpmsr:t(672),xIYtf:function(a,r){return a&r},WDwue:function(a,r){return a>>>r},xOGBp:function(a,r){return a&r},ikMEI:function(a,r){return a>>>r},JOsYJ:function(a,r){return a&r},adUia:function(a,r){return a+r},sLCGP:function(a,r){return a+r},AlpGx:function(a,r){return a|r},QJWXt:function(a,r){return a<<r},HrWTd:function(a,r){return a===r},dgKVQ:function(a,r){return a===r},vPxNf:function(a,r){return a===r},PhsxV:function(a,r){return a+r},JxetK:function(a,r){return a>>>r},wSrXY:function(a,r){return a>>>r},UXWWU:function(a,r){return a>>>r},mYBOM:function(a,r){return a&r},dKJls:function(a,r){return a&r},pvTux:function(a,r){return a>>>r},aLPIP:function(a,r){return a>>>r},VkLtT:function(a,r){return a&r},SOHQi:t(1233)+"RROR",HXMIj:t(731)+"NG_ERROR",jdsjS:t(557)+t(1328)+"R",YpSoU:t(1097)+t(1429),QORFU:t(388)+"OR",iCBon:t(1291),NkxLN:"KsAXY",enVWD:function(a,r){return a>r},AhqiG:function(a,r){return a+r},nwPLE:t(945),nooKa:t(1458),mVlLI:function(a,r){return a===r},eIVJo:t(522),Xcjco:function(a,r){return a||r},eNQwt:function(a,r){return a===r},HlOwW:t(507),UEFHT:function(a,r){return a===r},nOKTI:function(a,r){return a-r},zRDNG:function(a,r){return a===r},SsgkD:t(1055),hylXo:function(a,r){return a instanceof r},LhTtC:t(1406)+t(1762),KOxAQ:function(a,r){return a+r},UcVoX:function(a,r){return a+r},rpwJM:function(a,r){return a===r},EHIpH:function(a,r){return a<r},SbOSJ:t(759)+t(578)+t(1425)+"nitialized",GdSnE:function(a,r){return a!==r},BlsMM:"FsQVZ",WYwtk:t(1544),qRCIf:function(a,r){return a>r},SkLsR:t(963),DSSnX:function(a,r){return a&r},KldAs:function(a,r){return a>>>r},GJlyP:function(a,r){return a&r},xgvfr:t(770),xawUc:t(441),xfaFW:t(710),zfhQk:function(a,r,o){return a(r,o)},EkAMz:function(a,r){return a<r},qgsZf:function(a,r){return a&r},OcvBc:function(a,r,o){return a(r,o)},yFLHY:"reconnect",wzYGX:"stop immediately reconnect",rwiLT:t(381),apKep:function(a,r){return a||r},nvZbQ:t(702)+"d",DNjOz:"1|2|0|3|4",APQGj:function(a,r){return a||r},awpDm:function(a,r){return a!=r},pruYN:function(a,r){return a>r},iOXed:t(639)+t(1041)+"e",nIFbz:t(803)+"alled mu"+t(483)+t(525)+"process",UkPZP:function(a,r){return a===r},RJHsp:function(a,r){return a+r},hoJox:"rtYLQ",suULR:function(a,r){return a<r},sdbYl:function(a,r){return a===r},BAbqv:function(a,r){return a&r},ozYEW:function(a,r){return a===r},vzFll:function(a,r){return a&r},Iqaxl:function(a,r){return a<r},EbFFG:function(a,r){return a<=r},VzPdn:function(a,r){return a|r},MMgdD:function(a,r){return a&r},gCvHl:function(a,r){return a&r},tWaSN:function(a,r){return a>=r},KLXPW:function(a,r){return a|r},nJJkx:function(a,r){return a&r},yzIoX:function(a,r){return a&r},rxKRN:function(a,r){return a<<r},vTjSS:function(a,r){return a&r},OSRkD:function(a,r){return a>>r},FRYZU:function(a,r){return a<r},LrxSu:function(a,r){return a&r},nnySG:function(a,r){return a===r},MsIuQ:function(a,r){return a&r},GVsCo:function(a,r){return a|r},wPvnZ:function(a,r){return a&r},Fxzou:function(a,r){return a+r},FmfWP:function(a,r){return a|r},UkECg:function(a,r){return a>>r},MPXAA:function(a,r){return a&r},YOhuP:function(a,r){return a-r},dVHxb:function(a,r){return a(r)},uifcO:function(a,r,o,l){return a(r,o,l)},FJCTA:function(a,r){return a+r},MhuTb:t(1081),mGumF:t(990),fLXAr:"PiUWz",mAmZz:t(1181),HwKCA:t(747),vRnIi:function(a,r){return a instanceof r},KxDJk:function(a,r){return a!=r},gXWPk:"applicat"+t(742),THEKg:function(a,r){return a==r},hQHNs:t(1222)+t(1083)+"et=utf-8",bXYFo:t(1556),jNZpK:function(a,r){return a>=r},VewvM:function(a,r,o){return a(r,o)},IPlID:function(a,r,o){return a(r,o)},XDeww:t(601),mvLCp:function(a,r){return a===r},BQkze:t(991),fErpn:function(a,r){return a(r)},eXuIh:t(367),MKdNt:t(1385)+t(714),mFkVJ:function(a,r){return a+r},MLNCd:t(819)+t(1034),UoScX:"idb",VLbwk:t(1208),GKUyd:function(a){return a()},gpAry:function(a,r,o,l){return a(r,o,l)},EjEEw:function(a,r){return a>=r},ybGOE:"zfrFH",DUnps:"gBFdr",yWVWg:function(a,r){return a>=r},KBzQs:t(684),sIiBX:function(a,r){return a(r)},FAnsY:function(a,r){return a&r},iKXKv:function(a,r){return a+r},xBykd:function(a,r){return a||r},afjLp:function(a,r){return a>>>r},cLJoT:function(a,r){return a===r},BVyaF:t(1545),hGGNY:t(499),eAoIt:function(a,r){return a||r},XYwYV:function(a,r){return a||r},KZUPN:function(a,r){return a||r},ArZmM:function(a,r){return a||r},wTYeg:t(1136),xeAVg:function(a,r){return a(r)},bBBiq:function(a,r){return a===r},npAJu:t(1573),BXxTI:function(a,r){return a||r},BCHRl:function(a,r){return a!=r},fZwwP:t(902)+"DB failed",BQxQp:function(a,r,o){return a(r,o)},sXGNw:"qos",rWZKK:"message_id",FtDVJ:"x_frontier_qos",rXEld:function(a,r,o,l){return a(r,o,l)},GeheD:t(572)+"er_ack_m"+t(376),dUuHh:function(a,r,o,l){return a(r,o,l)},uSVXh:t(537),zmEvD:function(a,r){return a&&r},RcQzZ:t(1159),NRJVu:t(513),jXsdn:function(a,r){return a||r},SAIED:t(1018),EVSgE:function(a,r){return a(r)},sbYEv:function(a,r){return a(r)},ZbgFE:function(a,r){return a instanceof r},UZuCE:t(409)+t(742)+t(1023)+t(1112),oNbPF:t(984)+"e",blgkb:t(351),uJAhG:function(a,r){return a>r},WVVDC:function(a,r){return a(r)},UvxcO:function(a,r){return a+r},qaAcD:function(a,r){return a>>>r},raOsG:t(1550),SvxFo:t(1245),PgHyg:function(a,r){return a(r)},jEqcy:function(a,r){return a+r},CDZfS:function(a,r){return a+r},JwLwS:t(632),mGCim:t(392),UqYvW:function(a,r){return a+r},GWgaV:function(a,r){return a+r},JBKsp:function(a,r,o){return a(r,o)},nLFSj:function(a,r){return a>>>r},JeCPA:"2|3|4|1|0",MTchn:function(a,r){return a+r},wmNGY:function(a,r,o,l){return a(r,o,l)},kCEoZ:function(a,r){return a+r},vxeLE:function(a,r){return a|r},VDPLw:function(a,r){return a+r},ABhfW:function(a,r){return a<<r},TQels:function(a,r){return a+r},AMwfJ:function(a,r){return a<<r},wuxGu:function(a,r){return a+r},Ifrub:function(a,r){return a|r},WitJv:function(a,r){return a<<r},jYBSy:function(a,r){return a+r},AjMcr:function(a,r){return a+r},MKEid:function(a,r){return a>>>r},igkPe:function(a,r){return a&r},LROrK:function(a,r){return a&r},OxbOe:function(a,r){return a+r},tawrM:function(a,r){return a>>>r},PCcxx:function(a,r){return a&r},HHFiy:function(a,r){return a>>>r},yDnES:function(a,r){return a+r},KnDZJ:function(a,r){return a&r},MqRDo:function(a,r){return a&r},NrSsC:t(1493)+t(1359)+"|10|4|0|8",SPwXo:function(a,r,o,l){return a(r,o,l)},sGMtK:function(a,r){return a&r},ZMJLE:function(a,r){return a<r},lVIEq:function(a,r){return a|r},hIYZT:function(a,r){return a<r},iKvbc:function(a,r){return a<r},RvNWE:function(a,r){return a|r},ehynT:function(a,r){return a<r},oankD:function(a,r){return a-r},ZeboD:function(a,r){return a<r},TrvOT:t(616),krDBv:function(a,r){return a(r)},QaARt:function(a,r){return a+r},LQVqa:t(617)+t(972)+t(1198),PGRrF:t(1345)+"ervice",BsrRm:function(a,r,o,l){return a(r,o,l)},SoMSZ:"cursor_f"+t(993),qtnzv:function(a,r){return a<r},OcVIf:function(a,r,o,l){return a(r,o,l)},ewwWR:t(691)+"_EXIST",tTwsb:t(1685)+">",AlymX:function(a,r){return a===r},NQSMm:t(1225),oVOvV:"cursor_n"+t(524),XrFPY:t(1482)+t(1334),pxMbc:t(1704),fsFWd:"CONTINUE",CYTiD:function(a,r,o,l){return a(r,o,l)},lzyAy:function(a){return a()},hQanX:"setdb",nLMRd:function(a,r){return a instanceof r},wNGjt:t(355),XKowQ:function(a,r){return a===r},YQaxB:"store",puzUg:function(a,r){return a in r},Ehqfx:function(a,r){return a===r},ibnTl:"ZlPSv",QsCIq:t(1816)+"r",YOnPA:function(a,r){return a(r)},zqvfO:function(a,r){return a===r},COssf:t(1730),ATGjp:function(a,r){return a||r},bZXCJ:t(1303),IVpka:t(1207),MBalf:function(a,r,o,l){return a(r,o,l)},zqHpz:"code",OxLtV:function(a,r){return a(r)},wGNyo:function(a,r,o){return a(r,o)},grNkk:t(572)+t(1164),LPAlw:t(1525)+"s",EOqNn:function(a,r,o){return a(r,o)},doRii:"x-msg-cursor_name",jifTL:function(a,r){return a(r)},fbEKd:function(a,r,o){return a(r,o)},DvWGq:t(1446)+t(1799)+"ue",JvqVL:t(866),PgulW:function(a){return a()},FqoFp:function(a){return a()},aAEaR:function(a,r){return a===r},tqALP:function(a){return a()},yyNYE:function(a,r){return a!==r},xauqH:function(a,r){return a===r},nAfmS:t(1635),GIery:function(a,r,o){return a(r,o)},rZIpC:function(a){return a()},LkrJb:function(a){return a()},xgPcZ:"mLxuB",VqPmk:function(a,r){return a===r},tbJNh:t(1402),PmCcN:function(a,r){return a===r},nMDvk:t(918),FpxME:t(1780)+"e_success",uRpiV:t(568),dPXJo:function(a,r,o){return a(r,o)},Xtxga:function(a,r,o){return a(r,o)},vUYZU:function(a,r){return a+r},gUIBV:function(a,r){return a&r},wLwjJ:function(a,r){return a>>r},swSuF:"pbbp2",yRZTD:t(343)+"rovide v"+t(1335),BWzaq:function(a,r){return a(r)},RlJxl:t(343)+"rovide ws params"+t(1204)+t(1347)+"tructor "+t(1064)+t(912),xLhCK:function(a,r){return a+r},MUsgg:function(a,r){return a+r},JKLSg:function(a,r){return a<<r},ZcizB:function(a,r){return a>r},VtIib:function(a,r){return a!==r},Yqixz:t(750),YhMpz:function(a,r,o){return a(r,o)},mORDj:"online",NScyl:t(1760),pKqbl:t(538),fFunZ:"offline",YAkhZ:function(a,r){return a&r},NawJK:function(a,r){return a>>r},EmzGG:function(a,r){return a|r},yYyPa:function(a,r){return a&r},jOeZg:function(a,r){return a===r},eOJhQ:t(480),eZAcB:function(a,r){return a==r},GSMTv:t(407),FkKqC:t(821),TdfFV:t(1399),iQIwN:t(377)+"d",eTtpN:t(343)+t(1603)+t(718)+t(1379)+"r ttwID",GdJoe:t(459),sBLsf:t(545),LBGyi:"fws_1.0.0",Elrrv:t(925),CtGFe:function(a,r,o){return a(r,o)},jqlFk:function(a,r,o){return a(r,o)},moZXe:t(676),EdeYn:function(a,r){return a-r},RwbhO:function(a,r,o){return a(r,o)},rKPgu:function(a,r){return a===r},ILcpC:t(429),Efnox:function(a,r){return a(r)},DjMQd:function(a,r){return a(r)},VsUmi:function(a,r){return a*r},PMgjQ:function(a,r){return a-r},aRxDb:function(a,r){return a>r},TUTUz:function(a,r){return a!==r},aAooE:t(897),KnfhK:function(a,r,o){return a(r,o)},POFoW:function(a,r){return a(r)},FmKUh:function(a,r){return a===r},CzWzX:t(789),zbSEx:"ViSIi",cmkgL:"VqCwH",ZwVuG:t(1743)+"1",AtpdD:function(a,r){return a+r},dLkwZ:function(a,r){return a<<r},gwmcC:"HuRVH",hkptd:t(1398),rjyMl:t(1577),ATaWS:t(1269)+t(805)+t(620)+t(1665),fFwVb:t(729),QEBBA:t(698),qYPOl:t(1472)+t(1378),zHymw:t(759)+"s alread"+t(363),UgVSS:function(a,r){return a==r},qqlDR:t(343)+t(508)+" valid d"+t(1696)+"a must be a string or an"+t(1469)+t(1461),AFHbO:t(567),ykwUs:function(a,r){return a instanceof r},baFIg:function(a,r){return a instanceof r},uQMgx:function(a,r){return a(r)},msIJG:"please p"+t(508)+t(1189)+t(979),qKArO:function(a,r){return a instanceof r},DivVG:function(a,r){return a<r},YzrOw:t(488),rYflZ:function(a,r){return a==r},iaFCc:t(1138)+"econnect"+t(726),uaajb:t(1780)+t(1344)+"t",RSiXB:function(a,r){return a<r},pPgoZ:function(a,r){return a===r},rgUju:function(a,r){return a(r)},nYnrL:t(1228),DgPLQ:function(a,r){return a*r},JYuva:function(a,r){return a*r},lXRkY:function(a,r){return a!=r},UmjFY:t(764),ujaML:function(a,r){return a!=r},eqxIp:function(a,r){return a===r},iGoLt:function(a,r){return a!=r},QRpqu:t(1301),ryvwr:t(1733)+"dWorkerGlobalScope",tclOt:function(a,r){return a!=r},IQcHu:function(a,r){return a==r},pudhZ:function(a,r){return a!=r},GnSaF:function(a,r){return a===r},MmofA:t(1498)+t(547)+t(895),otdqw:function(a,r){return a!=r},deCno:function(a,r){return a!=r},kElUZ:t(414)+t(976)};Ft.r(Oe),Ft.d(Oe,{FWS:()=>wg,CustomErrorEvent:()=>sl,createCloseEvent:()=>wt,ReconnectEvent:()=>il,createErrorEvent:()=>lt,decodedFrame:()=>rn,createOpenEvent:()=>ul,CustomCloseEvent:()=>ol,createReconnectEvent:()=>xa,FrontierMessageEvent:()=>cl,encodeFrame:()=>Gt,createMessageEvent:()=>ll,OpenEvent:()=>dl,ErrorCode:()=>on,Event:()=>ir,MessageEvent:()=>al});let n="";function i(a=""){let r=t,o="02",l=""+Date.now(),f=n||(n=e[r(580)](h,a)),p=Math.random()[r(1229)](16)[r(1067)](-6);return e[r(1674)](e.EvsXd(e[r(1819)](o,l),f),p)}function s(){let a=t;return e.XzOiL(1e4*Date[a(412)](),Math[a(1032)](e[a(1774)](1e4,Math[a(384)]())))}function c(a){let r=t;return e[r(1674)](Array(8)[r(951)]("0"),parseInt(a,10).toString(2))[r(1067)](-8)}function d(a){let r=t;return e[r(1819)](e[r(580)](Array,4)[r(951)]("0"),e.cMaHk(parseInt,a,2)[r(1229)](16)).slice(-4)}function u(a){let r=t,o=a.split(/\./)[r(1766)](p=>c(p)),l=[];return l[0]=e[r(1480)](d,e[r(1674)](o[0],o[1])),l[1]=e.PeLHB(d,e[r(1372)](o[2],o[3])),[e[r(1206)],e[r(1206)],e[r(1206)],e[r(1206)],e[r(1206)],e[r(717)],l[0],l[1]][r(951)]("")}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}/[r(1664)](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]))/.test(a);return o?u(a):l?e[r(580)](x,a):e[r(1477)]}function x(a){let r=t,o="",l=[],f=0,p=0,w=!0,E=e[r(1206)];if(a[r(1173)]("::")>-1){let g=a.split("::");for(let L=0;L<g[r(559)];L++){let N=g[L];if(e[r(1560)](N.indexOf(":"),0)){let $=N.split(":");w&&(f=$[r(559)]),p+=$.length;for(let se=0;e[r(1505)](se,$[r(559)]);se++)if(e[r(503)](4,$[se][r(559)])){let re=E.substring(0,e.oRzqO(4,$[se].length)),ie=re[r(437)]($[se]);l[r(946)](ie)}else l[r(946)]($[se]);w=!1}else{if(N[r(559)]!==4){let $=E[r(1735)+"g"](0,4-N.length),se=$.concat(N);l[r(946)](se)}else l[r(946)](N);w&&(f+=1),p+=1,w=!1}}let C="";for(let L=0;e[r(1505)](L,e[r(596)](8,p));L++)C=C[r(437)](E);for(let L=0;e.gQzYL(L,l[r(559)]);L++)e[r(942)](L,f)&&(o=o[r(437)](C)),o=o[r(437)](l[L]);return o}if(e[r(1066)]!==e[r(1409)]){let g=a[r(1512)](":");for(let C=0;e[r(1505)](C,g[r(559)]);C++){let L=g[C];if(e[r(503)](4,g[C][r(559)]))if(e[r(942)](e[r(1457)],e[r(1837)]))this["currentE"+r(1183)+r(403)+"t"]=0;else{let N=E[r(1735)+"g"](0,e[r(596)](4,g[C][r(559)])),$=N[r(437)](L);o=o[r(437)]($)}else o=o[r(437)](L)}return o}else if(!this[r(654)+r(1811)]){let g=e.qGaZx[r(1512)]("|"),C=0;for(;;){switch(g[C++]){case"0":this[r(933)+r(953)]?.[r(958)+"pointConfig"]();continue;case"1":this[r(790)+r(494)]=!1;continue;case"2":this[r(1412)]=!0;continue;case"3":this[r(654)]();continue;case"4":this._pingLossCounter?.["resetCou"+r(491)]();continue}break}}}function m(a,r){let o=t,l=a[o(561)];e.dQvec(void 0,l)&&(e[o(968)](we,r,10),e[o(968)](U,r,l));let f=a[o(992)];e[o(503)](void 0,f)&&(e[o(973)](we,r,18),e.dklCm(U,r,f))}function _(a){let r=t,o={};e:for(;!e[r(1020)](K,a);)if(e[r(503)](e.oODMH,e[r(878)])){let l=e[r(1479)](me,a);switch(e[r(1044)](l,3)){case 0:break e;case 1:o.key=e.VAsaG(R,a,e[r(787)](me,a));break;case 2:o[r(992)]=e.cMaHk(R,a,me(a));break;default:e[r(920)](k,a,7&l)}}else{if(_0x5a3a4d=e.nxmLA(e.lXJVW(127,_0xbfff9e[_0xa3f7b]),0),e[r(476)](_0x18ae07[_0x53c5b8++],128))return{value:_0x243136?_0x214521:e.lyXZj(0,_0x45b615),offset:_0x2fad3b};if(_0x511567=e[r(890)](e[r(701)](_0x3610f4,e.HCCBd(e[r(1579)](127,_0x4d42b6[_0x4e8d75]),7)),0),e.Zqnev(_0x53f52a[_0x3b973b++],128))return{value:_0x1b8bb7?_0x1c1651:e.qeOVb(0,_0x133fad),offset:_0x1d0a9};if(_0x5138b6=e[r(890)](e.qeOVb(_0x2c3b65,e.msimk(127&_0x115b91[_0x341cbe],14)),0),e[r(1505)](_0x4f572b[_0x37cfe7++],128))return{value:_0x5a96c5?_0x2a7014:e[r(701)](0,_0x5153cd),offset:_0x25377c};if(_0x22a7d3=e[r(890)](_0x5c1b28|e[r(359)](e.tYciQ(127,_0x50e530[_0x4d0749]),21),0),e[r(1392)](_0x2b9844[_0x153d82++],128))return{value:_0x555579?_0x285348:e.qeOVb(0,_0x586995),offset:_0x9dc4f5};if(_0x524000=e[r(890)](_0x1afe29|e.vJsfn(15&_0x5c9614[_0x3d589d],28),0),e.Zqnev(_0xb66408[_0x2848fe++],128))return{value:_0x564129?_0x3d15f6:0|_0x355f73,offset:_0x2094b6};if(e[r(1560)](_0xba96a7+=5,_0x202872.length))throw _0x59cfc9=_0x54c503[r(559)],e.GEIZf(_0x4a47c7,_0x12b1b5,10,_0xf7e199[r(559)]);return{value:_0x2d2d4b?_0x199391:0|_0x12684e,offset:_0x2ff4f9}}if(e[r(942)](void 0,o[r(561)]))throw new Error(e.RuvHe);if(e.NJqyO(void 0,o.value))throw new Error(e[r(1305)]);return o}function S(a){let r=t,o=e[r(782)](D);return e[r(920)](y,a,o),B(o)}function y(a,r){let o=t,l={jXuJM:function(f,p,w){return e[G(1262)](f,p,w)},vVgNV:"close"};if(e.NJqyO(e[o(1185)],e.HEham)){let f=a.SeqID;e[o(368)](void 0,f)&&(e[o(898)](we,r,8),e[o(571)](mt,r,f));let p=a[o(681)];p!==void 0&&(we(r,16),e[o(854)](mt,r,p));let w=a[o(850)];e[o(503)](void 0,w)&&(we(r,24),e[o(973)](mt,r,e[o(1479)](P,w)));let E=a[o(1250)];e[o(621)](void 0,E)&&(e[o(1262)](we,r,32),e[o(1230)](mt,r,e[o(811)](P,E)));let g=a[o(856)];if(e.TngGS(void 0,g))for(let Me of g){e.dOIKy(we,r,42);let pe=D();e[o(854)](m,Me,pe),we(r,pe[o(400)]),e[o(968)](j,r,pe),e[o(1080)](O,pe)}let C=a[o(1728)+o(1238)];e[o(583)](void 0,C)&&(e[o(1289)](we,r,50),e[o(1324)](U,r,C));let L=a.payloadType;L!==void 0&&(e[o(920)](we,r,58),e.rPQjk(U,r,L));let N=a[o(1002)];e[o(368)](void 0,N)&&(e[o(571)](we,r,66),e[o(791)](we,r,N[o(559)]),e[o(1771)](ce,r,N));let $=a[o(733)];e[o(626)](void 0,$)&&(e[o(1317)](we,r,74),e[o(577)](U,r,$));let se=a[o(1802)+"ming"];se!==void 0&&(e[o(577)](we,r,82),e[o(1771)](U,r,se));let re=a[o(470)];e.MVdiq(void 0,re)&&(we(r,90),e[o(1221)](U,r,re));let ie=a[o(438)+"e"];e.gPAbG(void 0,ie)&&(e.cMaHk(we,r,96),e[o(1221)](mt,r,e[o(1456)](P,ie)))}else{let f=this[o(933)+o(953)]?.[o(1351)+"ntEndpoint"]();this[o(670)+"hCloseEv"+o(880)](l[o(615)](_0x5b53ae,l[o(1179)],{code:1006,reason:"connect "+f+(o(796)+o(1116)+o(835)+"ached"),wasClean:!0}))}}function v(a){return e[t(787)](I,F(a))}function I(a){let r=t,o={hraqJ:function(l,f){return l(f)}};if(e[r(1454)](r(1604),r(1789)))return _0x4c69a7(_0x1ca128[r(461)](XtnNVc[r(1673)](_0x24d1c4,this),_0x17e13c));{let l={};e:for(;!K(a);){let f=e.WfZry(me,a);switch(e.tHPfs(f,3)){case 0:break e;case 1:l[r(719)]=e[r(390)](At,a,!0);break;case 2:l[r(681)]=e[r(854)](At,a,!0);break;case 3:l[r(850)]=e.inytl(me,a);break;case 4:l[r(1250)]=e[r(1307)](me,a);break;case 5:{let p=e[r(582)](A,a);(l[r(856)]||(l[r(856)]=[]))[r(946)](e[r(943)](_,a)),a[r(400)]=p;break}case 6:l[r(1728)+"ncoding"]=e[r(1781)](R,a,e[r(943)](me,a));break;case 7:l["payloadT"+r(1342)]=e.DEOyh(R,a,e.sqcEO(me,a));break;case 8:l[r(1002)]=e[r(1324)](ae,a,e[r(1040)](me,a));break;case 9:l[r(733)]=e[r(1558)](R,a,e[r(1307)](me,a));break;case 10:l[r(1802)+r(892)]=e.CJDAG(R,a,e.sqcEO(me,a));break;case 11:l.msgID=e[r(898)](R,a,e.nVbzg(me,a));break;case 12:l.frameType=me(a);break;default:e.DWqXn(k,a,e[r(637)](7,f))}}if(e[r(1454)](void 0,l[r(719)]))throw new Error(e[r(1176)]);if(e.YSsPz(void 0,l.LogID))throw new Error(e[r(724)]);if(e[r(1454)](void 0,l[r(850)]))throw new Error(e[r(1100)]);if(e.zLxWt(void 0,l[r(1250)]))throw new Error(e[r(1593)]);return l}}function A(a){let r=t,o=me(a),l=a.limit;return a[r(400)]=e[r(1218)](a[r(824)],o),l}function k(a,r){let o=t;switch(r){case 0:for(;128&e[o(1835)](Q,a););break;case 2:e.OowYs(V,a,e[o(1524)](me,a));break;case 5:V(a,4);break;case 1:e.UQzFv(V,a,8);break;default:throw new Error(e[o(1218)](e[o(564)],r))}}function P(a){let r=t;if(e.gPQPL(e[r(1786)],r(477))){for(_0x538465>>>=0;e.iawuV(_0x1ff3e4,128);)e[r(1184)](_0x5d9cd6,_0x41b5cb,e[r(701)](e[r(1468)](127,_0x4d522c),128)),_0x57f100>>>=7;e[r(1324)](_0x4559be,_0xe78171,_0x3a057f)}else return a|=0,{low:a,high:e[r(844)](a,31),unsigned:a>=0}}let b=[];function D(){let a=t,r=b[a(1046)]();return r?(r[a(824)]=r.limit=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){b[t(946)](a)}function F(a){return{bytes:a,offset:0,limit:a.length}}function B(a){let r=t,o=a[r(1519)],l=a[r(400)];return o[r(559)]===l?o:o[r(1783)](0,l)}function V(a,r){let o=t;if(e[o(1560)](e[o(1819)](a[o(824)],r),a[o(400)]))throw new Error(e[o(1076)]);a.offset+=r}function K(a){let r=t;return e[r(1503)](a[r(824)],a.limit)}function te(a,r){let o=t,l=a[o(1519)],f=a.offset,p=a.limit,w=e.EvsXd(f,r);if(e[o(1560)](w,l[o(559)]))if(e.TngGS(o(1396),e[o(839)])){let E=new Uint8Array(e[o(1246)](2,w));E[o(1087)](l),a[o(1519)]=E}else e[o(791)](_0x26fa4d,_0x1ff5dc,18),e[o(1404)](_0x4159d2,_0xd3a124,_0x55d86a);return a.offset=w,e[o(1586)](w,p)&&(a[o(400)]=w),f}function Z(a,r){let o=t,l=a.offset;if(e[o(1211)](e[o(1205)](l,r),a.limit))throw new Error(e.ZRwUh);return a[o(824)]+=r,l}function ae(a,r){let o=t,l=e[o(898)](Z,a,r);return a[o(1519)][o(1783)](l,e[o(1275)](l,r))}function ce(a,r){let o=t,l=e[o(1221)](te,a,r[o(559)]);a.bytes[o(1087)](r,l)}function R(a,r){let o=t,l={xlAGQ:e[o(497)],PlYvP:function(f,p){return e[o(386)](f,p)},SDohP:function(f,p){return e[o(1439)](f,p)},IRzRF:function(f,p){return e[o(1044)](f,p)},vrYmM:function(f,p){return e[o(720)](f,p)},tcMLn:function(f,p){return e.vbQed(f,p)},wdpmP:function(f,p){return e[o(372)](f,p)},uliNu:function(f,p){return e.ndtbP(f,p)},hTCjh:function(f,p){return e[o(1247)](f,p)},XNkcF:function(f,p){return e[o(1439)](f,p)},XuzsV:function(f,p){return e.quAcU(f,p)},HMFgH:function(f,p,w,E){return e[o(964)](f,p,w,E)},jpMLg:function(f,p){return e[o(1424)](f,p)},NatdV:function(f,p){return e[o(590)](f,p)},dsmuM:function(f,p){return e.lXJVW(f,p)},btFwu:function(f,p){return e[o(1247)](f,p)},ZrCTb:function(f,p){return f|p},ZnFzY:function(f,p){return f|p}};if(e.YSsPz(e[o(1506)],"miJoI")){if(this._options["disableA"+o(669)+o(1592)]||this[o(790)+"osed"])return;this["_handleR"+o(528)]()}else{let f=e[o(1355)](Z,a,r),p=String[o(877)+o(1169)],w=a[o(1519)],E="\uFFFD",g="";for(let C=0;e[o(998)](C,r);C++){let L=w[e.JaSUs(C,f)],N,$,se,re;if(e[o(1499)](128,L)===0)g+=e[o(1480)](p,L);else if(e.DBEOL(224&L,192))e[o(1503)](e[o(350)](C,1),r)?g+=E:(N=w[e.wgFlq(e.XzOiL(C,f),1)],(192&N)!==128?g+=E:(re=e[o(701)](e[o(1689)](e[o(1729)](31,L),6),63&N),e[o(1392)](re,128)?g+=E:(g+=p(re),C++)));else if(e[o(1824)](240,L)==224)if(e[o(1804)](C,2)>=r)g+=E;else if(N=w[e[o(1205)](e.pyzNs(C,f),1)],$=w[e[o(1822)](C+f,2)],e[o(1423)](e[o(372)](N,$<<8),49344)!==32896)g+=E;else if(re=e[o(1439)](e[o(372)](e[o(1845)](15,L)<<12,e[o(1082)](e[o(1824)](63,N),6)),63&$),e[o(1702)](re,2048)||e.iawuV(re,55296)&&e.TEXDr(re,57343))g+=E;else if(e[o(1462)](e[o(1147)],e[o(1823)])){let ie=4294967295;return function(Me,pe,qt=!0){let _e=o,Ea=l.xlAGQ[_e(1512)]("|"),ni=0;for(;;){switch(Ea[ni++]){case"0":ie=l[_e(1108)](l[_e(1058)](ie,(15&Me[pe])<<28),0);continue;case"1":ie=l[_e(1478)](l.SDohP(ie,l.vrYmM(127,Me[pe])<<7),0);continue;case"2":if(l[_e(1569)](Me[pe++],128))return{value:qt?ie:l[_e(664)](0,ie),offset:pe};continue;case"3":if(l[_e(1569)](Me[pe++],128))return{value:qt?ie:0|ie,offset:pe};continue;case"4":ie=l[_e(622)](l[_e(1527)](127,Me[pe]),0);continue;case"5":if(l[_e(1484)](Me[pe++],128))return{value:qt?ie:l.XNkcF(0,ie),offset:pe};continue;case"6":if(l[_e(1316)](pe+=5,Me[_e(559)]))throw pe=Me[_e(559)],l[_e(1652)](_0x190b17,pe,10,Me[_e(559)]);continue;case"7":if(Me[pe++]<128)return{value:qt?ie:l[_e(781)](0,ie),offset:pe};continue;case"8":return{value:qt?ie:l[_e(431)](0,ie),offset:pe};case"9":ie=l[_e(1478)](l[_e(431)](ie,l[_e(1585)](l[_e(1397)](127,Me[pe]),14)),0);continue;case"10":if(l.btFwu(Me[pe++],128))return{value:qt?ie:l[_e(1415)](0,ie),offset:pe};continue;case"11":ie=l[_e(802)](ie,l.vrYmM(127,Me[pe])<<21)>>>0;continue}break}}}else g+=e.BdYsq(p,re),C+=2;else e[o(713)](e.gBSSO(248,L),240)?e[o(893)](e[o(473)](C,3),r)?g+=E:(N=w[e[o(809)](C,f)+1],$=w[e[o(1387)](e[o(527)](C,f),2)],se=w[e[o(809)](C,f)+3],e[o(874)]((e.oieMM(N,e[o(594)]($,8))|e[o(1738)](se,16))&12632256,8421504)?g+=E:(re=e[o(754)](e[o(1644)](e[o(909)]((7&L)<<18,e[o(502)](e.WAMxH(63,N),12)),e[o(502)](e.iQguh(63,$),6)),63&se),e[o(1702)](re,65536)||re>1114111?g+=E:(re-=65536,g+=e[o(994)](p,e[o(1844)](e.mpxLl(re,10),55296),e[o(1528)](e.gBSSO(1023,re),56320)),C+=3))):g+=E}return g}}function U(a,r){let o=t,l=r.length,f=0;for(let E=0;e[o(998)](E,l);E++){let g=r.charCodeAt(E);e[o(893)](g,55296)&&g<=56319&&e[o(1296)](e[o(1218)](E,1),l)&&(g=e[o(1528)](e.vJsfn(g,10),r[o(554)+"At"](++E))-56613888),f+=e[o(658)](g,128)?1:e[o(1148)](g,2048)?2:e[o(1296)](g,65536)?3:4}e.WPbcT(we,a,f);let p=e[o(1289)](te,a,f),w=a[o(1519)];for(let E=0;e[o(476)](E,l);E++){let g=r[o(554)+"At"](E);g>=55296&&e.TEXDr(g,56319)&&e[o(899)](e.HpFXk(E,1),l)&&(g=e[o(1500)](e.pyzNs(g<<10,r[o(554)+"At"](++E)),56613888)),e[o(1015)](g,128)?w[p++]=g:(e[o(658)](g,2048)?w[p++]=e.OjzzT(e[o(785)](e[o(844)](g,6),31),192):(e[o(1702)](g,65536)?w[p++]=e[o(752)](e.iQguh(e.uwilz(g,12),15),224):(w[p++]=e[o(1439)](e[o(1729)](e[o(844)](g,18),7),240),w[p++]=e.OjzzT(e[o(1491)](g>>12,63),128)),w[p++]=e[o(909)](e[o(1499)](e[o(1813)](g,6),63),128)),w[p++]=e[o(1268)](63&g,128))}}function j(a,r){let o=t,l=e.PXDxZ(te,a,r.limit),f=a[o(1519)],p=r.bytes;for(let w=0,E=r[o(400)];e[o(1148)](w,E);w++)f[e[o(1674)](w,l)]=p[w]}function Q(a){let r=t,o={ABohK:function(l,f){return e[G(1040)](l,f)},xyGKi:function(l,f){return e[G(1674)](l,f)}};if(e[r(1706)](e[r(1708)],e[r(1572)]))return a[r(1519)][e.McAuP(Z,a,1)];{let f=""+_0x4c3ed2[r(412)](),p=_0x43470c||(_0x28f212=gfdOhS[r(997)](_0x3a3754,_0x532976)),w=_0x27999d[r(384)]()[r(1229)](16)[r(1067)](-6);return gfdOhS[r(574)](gfdOhS[r(574)]("02",f)+p,w)}}function nt(a,r){let o=t,l={dpGDV:function(f,p,w){return e[G(1611)](f,p,w)},XYEgA:o(439)+"ame"};if(e[o(456)](e[o(837)],e[o(837)])){let f=e[o(917)](te,a,1);a[o(1519)][f]=r}else this[o(401)+o(1555)]=_0x52c0d8,this[o(607)+o(1767)]=_0x51b88c,this[o(426)+o(1455)]=_0x13186c,this[o(1418)]=l[o(1666)](_0x1b2650,this[o(401)+"ameSpace"],l[o(1846)])}function me(a){let r=t,o=0,l=0,f;do f=Q(a),e.DFrYk(o,32)&&(l|=e.vJsfn(e.RmXkn(127,f),o)),o+=7;while(e[r(1637)](128,f));return l}function we(a,r){let o=t;for(r>>>=0;e.iawuV(r,128);)e[o(917)](nt,a,e[o(924)](e[o(1729)](127,r),128)),r>>>=7;e[o(994)](nt,a,r)}function At(a,r){let o=t,l=0,f=0,p=0,w;return w=Q(a),l=e[o(1703)](127,w),e.ekANU(128,w)&&(w=e[o(1480)](Q,a),l|=e[o(1660)](127&w,7),128&w&&(w=e[o(1479)](Q,a),l|=e.MsmXi(127&w,14),e.lXJVW(128,w)&&(w=e[o(446)](Q,a),l|=e[o(1071)](127,w)<<21,128&w&&(w=e[o(706)](Q,a),f=e[o(1637)](127,w),e[o(1468)](128,w)&&(w=e[o(1835)](Q,a),f|=e[o(1738)](127&w,7),e[o(1703)](128,w)&&(w=e.bJlVj(Q,a),f|=e.PsGNZ(e[o(1167)](127,w),14),e[o(1130)](128,w)&&(w=e.WfZry(Q,a),f|=e[o(1681)](e[o(490)](127,w),21),e[o(1475)](128,w)&&(w=e[o(1510)](Q,a),p=e.gBSSO(127,w),128&w&&(w=Q(a),p|=e[o(1738)](e.hMEvc(127,w),7)))))))))),{low:e.FKfcn(l,f<<28),high:e[o(924)](f>>>4,p<<24),unsigned:r}}function mt(a,r){let o=t,l=e.nxmLA(r[o(395)],0),f=e[o(1644)](e.ndtbP(r[o(395)],28),r[o(1613)]<<4)>>>0,p=e.uRvZW(r[o(1613)],24),w=e[o(1487)](0,p)?e[o(606)](0,f)?l<16384?e[o(1296)](l,128)?1:2:e.vbQed(l,2097152)?3:4:f<16384?e.ZCICd(f,128)?5:6:f<2097152?7:8:e.ZCICd(p,128)?9:10,E=e[o(1629)](te,a,w),g=a[o(1519)];switch(w){case 10:g[e.XiFyI(E,9)]=e[o(1130)](e.eoJqx(p,7),1);case 9:g[e[o(1201)](E,8)]=e.TngGS(9,w)?e[o(1424)](128,p):e[o(1285)](127,p);case 8:g[e.iCswE(E,7)]=e[o(368)](8,w)?e[o(482)](e[o(1806)](f,21),128):f>>>21&127;case 7:g[E+6]=e[o(1437)](7,w)?e[o(1647)](e[o(870)](f,14),128):e[o(1186)](e.AsqBL(f,14),127);case 6:g[e.CJZOl(E,5)]=w!==6?e.thjdF(e[o(386)](f,7),128):e[o(1741)](f,7)&127;case 5:g[E+4]=e[o(1490)](5,w)?e.tVOYz(128,f):e.EJCce(127,f);case 4:g[e[o(527)](E,3)]=e[o(626)](4,w)?e[o(1424)](e[o(1044)](l,21),128):e[o(637)](e[o(380)](l,21),127);case 3:g[e[o(1827)](E,2)]=e[o(913)](3,w)?e[o(1349)](l>>>14,128):e[o(1441)](e.XANMz(l,14),127);case 2:g[e[o(527)](E,1)]=e[o(368)](2,w)?e[o(1810)](l,7)|128:l>>>7&127;case 1:g[E]=e[o(851)](1,w)?128|l:e.efZAY(127,l)}}function rn(a){return e[t(739)](v,a)}function Gt(a){return e[t(831)](S,a)}let sn=65536,Qr=e[t(1113)],Ee=e[t(772)](sn,sn),Ce=e[t(424)](Ee,Ee),rr=Ce/2,Ne=String[t(1042)+"e"][t(554)+"At"];class xe{constructor(r,o,l){let f=t;this[f(1719)]=!0,this[f(395)]=e[f(1687)](0,r),this[f(1613)]=e.gndKs(0,o),this.unsigned=!!l}static[t(1719)](r){let o=t;return r&&e[o(1492)](!0,r[o(1719)])}static[t(1088)](r,o,l){let f=t;if(e[f(1283)](e.sKsgg,f(1276)))return new xe(r,o,l);{let p=_0x39a558.substring(0,e.mEQqn(4,_0x1d1f07[_0x546af9].length)),w=p[f(437)](_0x184664);_0x151263=_0x182e7e.concat(w)}}static fromBytes(r,o,l){let f=t,p={SDBPw:f(1345)+f(979),TnCJU:function(w,E,g,C){return w(E,g,C)},JEHRF:function(w,E,g,C){return w(E,g,C)},pvfzQ:e.qmHoS,fOvfn:function(w,E,g,C){return e[f(964)](w,E,g,C)},eMqpn:e[f(1157)],tBcch:e.CgoAl,yisdZ:e[f(1537)],JEnfR:function(w,E){return e[f(1479)](w,E)}};if(e.tdJnf(e[f(610)],e[f(1793)])){let[w,E]=p[f(1546)](_0xf85039,_0x352c24),g=_0x5c6050(w),C=0;return _0x4303c9[f(981)](L=>{let N=f;_0x3b0daf[N(1563)](p.SDBPw,L,L.service),C=p[N(1140)](_0x518f10,0,g,C),_0x5e0f52[N(1563)](N(1566),C),C=p.JEHRF(_0x48b1c8,g,C,L[N(850)]||0),_0x34c61b[N(1563)](p[N(842)],C),C=p[N(1243)](_0x3a939d,E[L[N(439)+"ame"]],g,C),_0x5e0db9[N(1563)](p.eMqpn,C),C=_0xe8612d(L[N(439)+"ame"],g,C),_0x2563de[N(1563)](p[N(656)],C),C=p[N(1140)](_0x2f3dc6,_0x11c1d2[N(861)+"er"](L.cursor||_0x3d5deb),g,C),_0x9498bd[N(1563)](p[N(1377)],C)}),{frameType:_0x1d9e1a,headers:[{key:f(489)+f(993),value:_0x27549e}],payload:g}}else return l?xe[f(1217)+f(509)](r,o):xe["fromByte"+f(1273)](r,o)}static fromBytesLE(r,o){let l=t;if(e[l(1492)](e.WJdte,"VXDYT"))return new xe(e[l(1647)](e.thjdF(r[0]|r[1]<<8,e.VPOqa(r[2],16)),e[l(1011)](r[3],24)),e.thjdF(r[4]|e[l(1677)](r[5],8)|e[l(1681)](r[6],16),e[l(1677)](r[7],24)),o);e[l(492)](_0xb75c51,this[l(1065)+l(569)+"Id"]),this["_interva"+l(569)+"Id"]=e[l(1355)](_0x5b0b8a,()=>{this[l(1427)+"ired"]()},this._interval)}static[t(1217)+t(1273)](r,o){let l=t;if(e.lmjvu(e[l(1360)],e.FaWNP))return new xe(e.tVOYz(e.qiFDX(e[l(1424)](r[4]<<24,e.DTLsb(r[5],16)),r[6]<<8),r[7]),e[l(924)](e[l(752)](e[l(865)](r[0],24)|e.xlEvc(r[1],16),e.CnDsm(r[2],8)),r[3]),o);if(e[l(1842)](_0x11d4b3[l(824)]+_0x1945c5,_0x29a012[l(400)]))throw new _0x206702(e.LMZFe);_0xf7a442[l(824)]+=_0x2ee697}static[t(1417)](r){let o=t;return e[o(456)](r,Qr)?rl:new xe(e[o(386)](e.YnlBr(Ne[o(1253)](r,0),e[o(1082)](Ne.call(r,1),8))|Ne[o(1253)](r,2)<<16|e.MsmXi(Ne.call(r,3),24),0),e[o(1669)](e[o(1717)](e[o(924)](Ne.call(r,4),e.oxUAe(Ne[o(1253)](r,5),8)),e[o(1354)](Ne[o(1253)](r,6),16))|Ne[o(1253)](r,7)<<24,0),!0)}toHash(){let r=t;return String.fromCharCode(e[r(1130)](255,this[r(395)]),e[r(1778)](e[r(1669)](this[r(395)],8),255),e.nGogU(this[r(395)]>>>16,255),e[r(1810)](this[r(395)],24),e.nRson(255,this.high),e.GtqQG(this[r(1613)]>>>8,255),e[r(1285)](e.amdpx(this[r(1613)],16),255),e.FgDwN(this[r(1613)],24))}static fromNumber(r,o=!0){let l=t;if(e[l(787)](isNaN,r))return o?Dp:rl;if(o){if(r>=Ce)return Pp}else{if(e[l(1194)](r,-rr))return Op;if(e[l(712)](e[l(449)](r,1),rr))return Rp}return xe[l(1088)](e[l(961)](e.GzLCr(r,Ee),0),e[l(482)](e[l(737)](r,Ee),0),o)}toNumber(){let r=t;return this[r(1770)]?e[r(1841)](e[r(857)](e.neOig(this.high,0),Ee),e[r(468)](this[r(395)],0)):e[r(1156)](e.USgET(this[r(1613)],Ee),e.DdBan(this[r(395)],0))}[t(1745)](){let r=t;if(e[r(344)](e[r(860)],r(645)))return e.qTsxy(0,this.high)&&e[r(1492)](0,this.low);e.WHpMC(_0x55c317,_0x5b8d1c,24),e[r(1332)](_0x826c7a,_0x52ed3e,e.PeLHB(_0x5818be,_0x5aea13))}[t(435)](r){let o=t;if(e[o(851)](e[o(1758)],e[o(1758)]))this[o(848)+"rs"]={};else{xe.isLong(r)||(r=xe[o(861)+"er"](r));let l=e.uRvZW(this.high,16),f=e[o(1825)](65535,this.high),p=e[o(1643)](this.low,16),w=e[o(1313)](65535,this.low),E=e[o(1669)](r[o(1613)],16),g=65535&r[o(1613)],C=e[o(1236)](r.low,16),L=e[o(1648)](65535,r[o(395)]),N=0,$=0,se=0,re=0;return re+=e[o(444)](w,L),se+=e[o(1610)](re,16),re&=65535,se+=e[o(1658)](p,C),$+=e.neOig(se,16),se&=65535,$+=f+g,N+=$>>>16,$&=65535,N+=e[o(1844)](l,E),N&=65535,xe.fromBits(e[o(1649)](se<<16,re),e[o(1584)](e.QJWXt(N,16),$),this[o(1770)])}}[t(1614)](r){let o=t;return xe.isLong(r)||(r=xe.fromNumber(r)),this[o(1770)]!==r[o(1770)]&&e[o(1462)](this.high>>>31,1)&&e[o(1462)](r.high>>>31,1)?!1:e[o(942)](this[o(1613)],r[o(1613)])&&e.HrWTd(this[o(395)],r[o(395)])}[t(1364)](){let r=t;return e[r(1794)](-1,this[r(395)])&&e[r(914)](-1,this[r(1613)])?xe[r(1088)](0,0,this.unsigned):this[r(395)]===-1?xe[r(1088)](0,this[r(1613)]+1,this.unsigned):xe[r(1088)](e[r(671)](this[r(395)],1),this[r(1613)],this[r(1770)])}[t(755)](r){return r?this.toBytesLE():this[t(1341)+"E"]()}toBytesLE(){let r=t,o=this[r(1613)],l=this[r(395)];return[e[r(1579)](255,l),e[r(1579)](e[r(1202)](l,8),255),e[r(1845)](e[r(1710)](l,16),255),e.JxetK(l,24),255&o,e.eQIBt(e[r(890)](o,8),255),o>>>16&255,o>>>24]}[t(1341)+"E"](){let r=t,o=this.high,l=this[r(395)];return[e[r(1741)](o,24),e[r(1491)](o>>>16,255),e[r(1630)](o,8)&255,e[r(666)](255,o),l>>>24,e[r(1024)](e[r(510)](l,16),255),e[r(1312)](l,8)&255,e.VkLtT(255,l)]}}let rl=new xe(0,0,!1),Dp=new xe(0,0,!0),Rp=xe[t(1088)](-1,2147483647,!1),Pp=xe[t(1088)](-1,-1,!0),Op=xe.fromBits(0,-2147483648,!1);var on=(function(a){let r=t;return a[a[e[r(697)]]=5001]=e.SOHQi,a[a[e[r(535)]]=5002]=e[r(535)],a[a[e[r(1817)]]=5003]=e[r(1817)],a[a[e[r(934)]]=5004]=r(1097)+r(1429),a[a[e[r(704)]]=5005]=e.QORFU,a})({});class ir{constructor(r){let o=t;if(e[o(583)](e[o(1645)],e[o(565)]))this[o(1059)]=r,this[o(1547)]=null;else return 0}}class il extends ir{constructor(r,o){let l=t;super(r),this[l(770)]=o&&o[l(770)]||null}}class sl extends ir{constructor(r,o){let l=t,f=(l(816)+l(546))[l(1512)]("|"),p=0;for(;;){switch(f[p++]){case"0":this.lineno=o&&o[l(1549)]||0;continue;case"1":this.message=o&&o.message||"";continue;case"2":super(r);continue;case"3":this[l(1158)]=o&&o[l(1158)]||0;continue;case"4":this[l(1471)]=o&&o.filename||"";continue;case"5":this[l(1055)]=o&&o[l(1055)]||null;continue;case"6":this.code=o&&o[l(1143)]||5001;continue}break}}}class ol extends ir{constructor(r,o){let l=t,f=(l(585)+"2")[l(1512)]("|"),p=0;for(;;){switch(f[p++]){case"0":this[l(1143)]=o&&o[l(1143)]||0;continue;case"1":this[l(941)]=o&&o[l(941)]||!1;continue;case"2":this[l(827)+l(1684)]=o&&o[l(827)+l(1684)]||!1;continue;case"3":this.reason=o&&o[l(1034)]||"";continue;case"4":super(r);continue}break}}}class al extends ir{constructor(r,o){let l=t;super(r),this.data=o&&o[l(1014)]||null}}class cl extends al{constructor(r,o){let l=t;if(e[l(1492)](e[l(555)],e[l(555)]))super(r),this.data=o&&o[l(1014)]||null,this[l(770)]=o&&o[l(770)]||null;else{let f=_0x3ca88f[l(824)];if(e[l(823)](e[l(1435)](f,_0x25394f),_0x203124[l(400)]))throw new _0x2e873c(e[l(1650)]);return _0x1e3527[l(824)]+=_0x46e86d,f}}}class dl extends ir{constructor(r,o){let l=t;super(r),this[l(1014)]=o&&o[l(1014)]||null}}function lt(a,{message:r,code:o,error:l}){return new sl(a,{message:r,code:o,error:l})}function wt(a,{code:r,reason:o,wasClean:l,willReconnect:f}){return new ol(a,{code:r,reason:o,wasClean:l,willReconnect:f})}function ll(a,{data:r,message:o}){return new cl(a,{data:r,message:o})}function ul(a,{data:r}){return new dl(a,{data:r})}function xa(a,{message:r}){let o=t,l={VFcag:function(f,p,w){return e[G(791)](f,p,w)},QkDGn:"error",czDmQ:function(f,p,w){return e[G(1355)](f,p,w)},HRneR:e.nooKa};if(e.mVlLI(e.eIVJo,o(1725))){let f=l.VFcag(_0x555a21,l[o(723)],{message:this["_formatE"+o(1442)+o(1182)](_0x163c98)});this[o(478)](o(1055),f);let p=l[o(1700)](_0x571013,l.HRneR,{reason:this[o(1162)+o(1442)+o(1182)](_0x455363)});this[o(478)](l[o(442)],p)}else return new il(a,{message:r})}class fl{constructor(r,o){let l=t;this.endpoints=r,this.maxRetries=o,this[l(1315)+"ndex"]=0,this[l(799)+l(1183)+l(403)+"t"]=0}[t(958)+t(894)+t(922)](){let r=t;this[r(1315)+r(674)]=0,this[r(799)+"ndpointTriesCount"]=0}[t(1056)+"es"](){let r=t;this[r(799)+r(1183)+"riesCount"]=0}[t(1351)+t(743)+"nt"](){let r=t;if(e[r(1350)](e[r(1432)],e[r(1432)]))return this[r(563)+"s"][this[r(1315)+r(674)]];{let o=this._qosDB[r(1282)+r(1651)](this._prefix),l=_0x46ffcf[r(1039)](e[r(366)](o,"{}"));return l[_0x4ad3bc]=void 0,this[r(1418)][r(1531)+r(1651)](this._prefix,_0x70dde2.stringify(l))}}[t(1351)+t(743)+"ntTriesC"+t(1029)](){let r=t;return this[r(799)+r(1183)+"riesCount"]}[t(748)+"chMaxTries"](){let r=t;return!!(this[r(1315)+r(674)]>=this.endpoints[r(559)]||e[r(1178)](this[r(1315)+"ndex"],e[r(1356)](this[r(563)+"s"][r(559)],1))&&e[r(531)](this[r(799)+r(1183)+r(403)+"t"],this.maxRetries))}[t(1407)+t(644)+t(1465)+t(1366)+"tries"](){let r=t;return e.VNHgN(this.currentIndex,this[r(563)+"s"][r(559)])?!0:e[r(1842)](this[r(799)+"ndpointTriesCount"],this[r(1070)+"es"])}[t(1239)+t(1564)+t(775)+t(1600)+t(1190)](){let r=t;return this[r(799)+r(1183)+r(403)+"t"]=1,this["currentI"+r(674)]++,this.endpoints[this[r(1315)+r(674)]]}[t(1351)+t(743)+t(1150)+t(1538)](){let r=t;return this[r(799)+"ndpointT"+r(403)+"t"]++,this.getCurrentEndpoint()}}let sr=(e[t(955)](e.nvZbQ,typeof globalThis)&&e[t(526)](e[t(1431)],globalThis[t(1421)+t(677)][t(763)])||e[t(354)](e.nvZbQ,typeof window)&&e.eqxIp(e[t(1431)],window[t(1421)+t(677)][t(763)]))&&e[t(1486)](e[t(1261)],typeof document),On=t(702)+"d"!=typeof globalThis&&(e.QRpqu===globalThis[t(1421)+"tor"][t(763)]||e[t(1454)](e.ryvwr,globalThis[t(1421)+t(677)][t(763)]))&&e[t(1261)]!=typeof tt,ei=(e.tclOt(e.nvZbQ,typeof globalThis)&&e.UkPZP(t(1301),globalThis[t(1421)+t(677)][t(763)])||e.IQcHu(t(702)+"d",typeof globalThis)||e[t(1057)](e[t(1261)],typeof globalThis)&&!!globalThis[t(469)+t(1075)])&&e[t(1693)](t(702)+"d",typeof wx),ti=e[t(955)](t(702)+"d",typeof globalThis)&&(e[t(595)](e.ryvwr,globalThis[t(1421)+t(677)].name)||e[t(915)]===globalThis[t(1421)+"tor"][t(763)]||e.nnySG(t(1753)+t(1539)+t(506),globalThis[t(1421)+t(677)][t(763)]))&&e.otdqw(t(702)+"d",typeof self),Lp=e.KxDJk(t(702)+"d",typeof globalThis)&&e[t(1654)]===globalThis[t(1421)+t(677)].name&&e[t(504)](e[t(1261)],typeof global)&&e.eNQwt(t(1301),global[t(1421)+t(677)][t(763)])&&e[t(1122)](e[t(1261)],typeof process)&&!!process[t(1561)];class pa{constructor(){let r=t;this[r(848)+"rs"]={}}[t(478)](r,...o){let l=t,f=this._listeners[r];if(f)f[l(1067)]().forEach(p=>p.fn[l(461)](p[l(1449)],o));else if(e[l(1492)](e[l(1791)],r)&&!this[l(387)]){let p=o[l(559)]&&o[0];if(e.hylXo(p,Error))throw p;let w=new Error(e[l(1739)]+(p?e[l(500)](e[l(1376)](" (",p.message),")"):""));throw w[l(1416)]=p,p}return this}[t(1290)](r,o){let l=t;if(r===void 0)this[l(848)+"rs"]={};else if(e[l(1481)](void 0,o))this[l(848)+"rs"][r]=null;else{let f=this[l(848)+"rs"][r];if(f)for(let p=0;e[l(1050)](p,f[l(559)]);)e[l(1492)](f[p].fn,o)?f[l(570)](p,1):++p}return this}on(r,o,l){let f=t;if(e[f(1265)](e[f(1193)],e.WYwtk))return(this[f(848)+"rs"][r]||(this[f(848)+"rs"][r]=[]))[f(946)]({fn:o,ctx:l||this}),this;{let p=(f(550)+f(496))[f(1512)]("|"),w=0;for(;;){switch(p[w++]){case"0":this[f(1045)+f(544)]?.[f(642)]();continue;case"1":this[f(790)+f(494)]=!0;continue;case"2":if(e[f(456)](this._ws[f(1473)+"te"],this[f(1671)])||e.OoKzU(this[f(1694)][f(1473)+"te"],this[f(1152)]))return void this[f(1365)](f(759)+f(688)+f(363));continue;case"3":this["_clearTi"+f(1309)]();continue;case"4":this._clearPingTimer();continue;case"5":if(!this[f(1694)])return void this[f(1365)](e[f(599)]);continue;case"6":this["_dropGlo"+f(1756)+"Listener"]();continue;case"7":this[f(432)+f(421)+"t"](_0xc39fe9,_0x4c694a);continue}break}}}}class Np extends pa{[t(1162)+"rrorMess"+t(1182)](r){let o=t;return r.errMsg||r.errNo?("message: "+(r[o(1331)]||"")+o(696)+(r[o(1001)]||""))[o(965)]():JSON.stringify(r)}constructor(r,o,l){let f=t;super(),this[f(440)]=null,ei&&wx[f(451)+f(1734)]&&(this[f(440)]=wx[f(451)+f(1734)]({url:r,protocols:o,header:l,fail:this["_createS"+f(1063)+f(794)][f(1785)](this),success:this["_createSocketSuc"+f(996)+"ler"][f(1785)](this)})),On&&tt[f(451)+f(1734)]&&(this[f(440)]=tt[f(451)+f(1734)]({url:r,protocols:o,header:l,fail:this[f(573)+f(1063)+f(794)][f(1785)](this),success:this[f(573)+f(1830)+f(996)+f(1751)][f(1785)](this)}))}[t(573)+t(1830)+t(996)+t(1751)](){let r=t;Promise[r(566)]()[r(859)](()=>{this[r(1060)+"steners"]()})}[t(573)+"ocketFai"+t(794)](r){let o=t;Promise[o(566)]()[o(859)](()=>{let l=o,f=lt(e[l(1791)],{message:this[l(1162)+l(1442)+l(1182)](r)});this.emit(e[l(1791)],f);let p=e.DEOyh(wt,e[l(869)],{reason:this[l(1162)+l(1442)+l(1182)](r)});this[l(478)](e[l(869)],p)})}["_addWsLi"+t(1028)](){let r=t,o={pSpgb:function(l,f){return e[G(671)](l,f)},cZCsK:function(l,f){return e[G(1560)](l,f)},CDrRF:function(l,f){return e[G(1774)](l,f)},yzOFw:function(l,f){return e[G(447)](l,f)},lGyeo:e[r(1574)],tSPYD:function(l,f,p){return e.QvuaI(l,f,p)},dplRu:function(l,f,p){return l(f,p)},EXrtm:function(l,f){return e[r(1079)](l,f)},FzvLP:function(l,f){return l>>>f},Mtuxn:function(l,f){return e[r(1120)](l,f)},hKyoI:function(l,f){return l&f},FDdli:function(l,f){return e.KldAs(l,f)},BUpvu:function(l,f){return e[r(1532)](l,f)},VDiHC:function(l,f){return e[r(1454)](l,f)},TsRYQ:r(745),KWKRW:e[r(396)],KHXSU:e.SsgkD,aUxit:function(l,f,p){return l(f,p)}};if(e[r(832)]===e[r(975)]){let l=_0x46f498[r(1519)],f=_0x4a11a0[r(824)],p=_0x41211d[r(400)],w=BaFYyT.pSpgb(f,_0x54c56e);if(BaFYyT[r(1436)](w,l[r(559)])){let E=new _0x5d20da(BaFYyT[r(1367)](2,w));E[r(1087)](l),_0x392509.bytes=E}return _0x47dd5f[r(824)]=w,BaFYyT[r(1502)](w,p)&&(_0x3e583a[r(400)]=w),f}else this[r(440)][r(1062)](l=>{let f=r;this[f(478)](o[f(1414)],o[f(1223)](ul,f(963),{...l,data:l[f(1331)]||""}))}),this[r(440)].onClose(l=>{let f=r;this.emit(f(1458),o[f(888)](wt,f(1458),{...l}))}),this[r(440)][r(808)+"e"](l=>{let f=r;if(o[f(1732)](o.TsRYQ,o[f(1655)]))this[f(478)](o.KWKRW,o.tSPYD(ll,o[f(636)],{...l}));else{let p=this[f(1613)],w=this.low;return[BaFYyT.EXrtm(p,24),BaFYyT[f(1352)](p,16)&255,BaFYyT[f(1724)](p>>>8,255),255&p,BaFYyT[f(810)](w,24),BaFYyT[f(882)](w>>>16,255),BaFYyT[f(882)](BaFYyT[f(1395)](w,8),255),BaFYyT.BUpvu(255,w)]}}),this[r(440)][r(1052)](l=>{let f=r;this[f(478)](o[f(1033)],o[f(910)](lt,o[f(1033)],{...l,message:l[f(1331)]||""}))})}send(r){let o=t,l={mjakh:"culVg",gyZeO:e.SsgkD,XDmUe:function(f,p,w){return e[G(849)](f,p,w)},kDEeQ:function(f,p){return e[G(1755)](f,p)},Nqooe:function(f,p){return e[G(658)](f,p)},CIhQm:function(f,p){return e.qgsZf(f,p)},ApKfN:function(f,p){return e[G(1156)](f,p)},SyDaj:function(f,p){return f!==p},EVBow:o(495),RVGti:function(f,p,w){return e[o(1340)](f,p,w)}};if(e[o(675)](r,Uint8Array)){let f=r.buffer[o(1067)](r[o(797)+"et"],e[o(527)](r[o(1721)+"th"],r.byteOffset));this[o(440)]&&this[o(440)][o(1403)]({data:f,fail:p=>{let w=o;if(l[w(1591)]!==w(1495))this.emit(l.gyZeO,l.XDmUe(lt,w(1055),{message:this[w(1162)+w(1442)+w(1182)](p)}));else return this[w(1694)]?this[w(1694)][w(1473)+"te"]:this[w(686)].automaticOpen?this.CONNECTING:this[w(1671)]}})}else this[o(440)]&&this[o(440)][o(1403)]({data:r,fail:f=>{let p=o,w={YXHUx:function(E,g){return l.kDEeQ(E,g)},UnpKm:function(E,g){return l.kDEeQ(E,g)},wTVsS:function(E,g){return l[G(901)](E,g)},pdnlO:function(E,g){return E===g},Pjjrp:function(E,g){return l[G(423)](E,g)},aVWKw:function(E,g){return l[G(423)](E,g)},eysBB:function(E,g){return l[G(1237)](E,g)}};if(l.SyDaj(l[p(1084)],l[p(1084)])){let E=0,g=0;for(let C=0;w.YXHUx(C,_0xadbfaa[p(559)]);++C)g=_0x5c24e4[p(554)+"At"](C),w[p(1010)](g,128)?E+=1:w[p(1494)](g,2048)?E+=2:w[p(1508)](w[p(812)](64512,g),55296)&&w[p(1508)](w.aVWKw(64512,_0x25230e[p(554)+"At"](w[p(1132)](C,1))),56320)?(++C,E+=4):E+=3;return E}else this[p(478)](p(1055),l[p(728)](lt,l[p(1815)],{message:this[p(1162)+p(1442)+p(1182)](f)}))}})}close(r,o){let l=t;this[l(440)]&&this[l(440)][l(1458)]({code:r,reason:o})}[t(1195)+t(1617)](r,o){this.on(r,o)}[t(1363)+t(1016)+t(1552)](r,o){let l=t,f={PKnXb:function(p,w,E){return e.rPQjk(p,w,E)},PNwEp:e[l(679)],gJCNH:e[l(1831)]};if(e[l(1234)]!==e.rwiLT){this[l(432)+l(421)+"t"]();let p=f[l(1271)](_0x4ee25b,f[l(900)],{message:f.gJCNH});this[l(1224)+l(1220)+l(753)+"ct"]&&this[l(1224)+l(1220)+l(753)+"ct"](p)}else this[l(1290)](r,o)}get[t(1473)+"te"](){let r=t;return this[r(440)][r(1473)+"te"]}get binaryType(){return this[t(440)].binaryType}set[t(932)+"pe"](r){}get[t(1570)](){return this[t(440)].url}get[t(1227)](){let r=t;return this[r(440)][r(1227)]}get[t(1308)+"ns"](){let r=t;return this[r(440)][r(1308)+"ns"]}get["buffered"+t(1036)](){return 0}}function Mp(a,r){let o=t;if(r)return new r(a[o(1570)],a[o(1227)]);if(ei||On)return new Np(a[o(1570)],a[o(1227)],a[o(856)]);if(e[o(1294)](sr,ti)&&e[o(1261)]!=typeof WebSocket&&WebSocket)return new WebSocket(a[o(1570)],a[o(1227)+"s"])}function Bp(a){let r=t,o=e[r(1626)].split("|"),l=0;for(;;){switch(o[l++]){case"0":if(On&&tt[r(451)+r(1734)])return!0;continue;case"1":if(a)return!0;continue;case"2":if(ei&&wx[r(451)+r(1734)])return!0;continue;case"3":if(e[r(1812)](sr,ti)&&e.awpDm(e[r(1261)],typeof WebSocket)&&WebSocket)return!0;continue;case"4":return!1}break}}function hl(a,r,o){let l=t,f={BRVVF:e.nIFbz,kJnsE:function(p,w){return e.UkPZP(p,w)},begmn:function(p,w){return e.RJHsp(p,w)}};if(e[l(740)]===l(836)){let p=-1;async function w(E){let g=l;return E<=p?Promise.reject(new Error(f[g(1516)])):(p=E,f[g(1448)](E,o[g(559)])?Promise[g(566)]():o[E][g(1785)](a)(r,w[g(1785)](null,f[g(641)](E,1))))}w(0)}else{if(e[l(398)](_0x2a35f9,_0xb3a68b))throw new _0x102f41(e.iOXed);let p=3;for(;p>=0;){let w=255&_0x5d49fc;_0x3d22b5(w,_0x2ad45d,e[l(1372)](_0x49418b,p)),_0x41ab99>>>=8,p--}return _0x437cda+4}}function xl(a){let r=t,o=0,l=0;for(let f=0;e[r(1459)](f,a.length);++f)l=a[r(554)+"At"](f),e[r(1702)](l,128)?o+=1:l<2048?o+=2:e[r(1210)](e[r(1808)](64512,l),55296)&&e[r(959)](e[r(416)](64512,a[r(554)+"At"](e.aYluJ(f,1))),56320)?(++f,o+=4):o+=3;return o}function pl(a,r,o){let l=t;if(e[l(1500)](o,r)<1)return"";let f="";for(let p=r;e.Iqaxl(p,o);){let w=a[p++];if(e[l(1077)](w,127))f+=String["fromChar"+l(1169)](w);else if(e[l(712)](w,192)&&e[l(1505)](w,224))f+=String[l(877)+l(1169)](e[l(694)](e[l(995)](e[l(1601)](31,w),6),e[l(493)](63,a[p++])));else if(w>=224&&e[l(1296)](w,240))f+=String[l(877)+"Code"](e[l(372)](e[l(594)](15&w,12)|e[l(1689)](e.gtVIr(63,a[p++]),6),e[l(1428)](63,a[p++])));else if(e[l(560)](w,240)){let E=e[l(1356)](e[l(394)](e[l(1274)](7,w)<<18|e[l(475)](63,a[p++])<<12,e[l(1476)](e[l(1146)](63,a[p++]),6))|63&a[p++],65536);f+=String[l(877)+l(1169)](55296+e.OSRkD(E,10)),f+=String["fromChar"+l(1169)](e[l(1674)](56320,e.GtqQG(1023,E)))}}return f}function ga(a,r,o){let l=t,f=o,p,w;for(let E=0;e[l(1247)](E,a[l(559)]);++E)if(p=a[l(554)+"At"](E),e[l(1110)](p,128))r[o++]=p;else if(e[l(899)](p,2048))r[o++]=e[l(1606)](p,6)|192,r[o++]=63&p|128;else if(e[l(1623)](64512,p)===55296&&e.nnySG(64512&(w=a.charCodeAt(E+1)),56320)){let g=(l(1712)+l(1142)).split("|"),C=0;for(;;){switch(g[C++]){case"0":++E;continue;case"1":r[o++]=e[l(961)](e[l(1646)](p>>6,63),128);continue;case"2":r[o++]=e.GVsCo(p>>18,240);continue;case"3":r[o++]=e.aTOvA(e[l(1299)](63,p),128);continue;case"4":r[o++]=e[l(372)](e[l(1606)](p,12)&63,128);continue;case"5":p=e[l(1597)](e[l(417)](65536,(1023&p)<<10),e[l(1499)](1023,w));continue}break}}else r[o++]=e[l(1801)](e[l(844)](p,12),224),r[o++]=e[l(463)](e[l(1536)](p,6)&63,128),r[o++]=e.MPXAA(63,p)|128;return e[l(345)](o,f)}async function gl(a){let r=t;if(e[r(713)]("string",typeof a)){let o=new Uint8Array(e.dVHxb(xl,a));return e[r(721)](ga,a,o,0),o}return a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a[r(966)],a[r(797)+"et"],a[r(1721)+"th"])}function Fp(a){let r=t;if(e[r(434)](e.MhuTb,e.mGumF)){let o=e[r(673)](_0x234891,_0x4ea3e9,1);_0x518459[r(1519)][o]=_0x56421e}else try{return e[r(820)]===e[r(1764)]?e[r(1203)](e[r(1774)](1e4,_0x228b94[r(412)]()),_0x50832a[r(1032)](e[r(857)](1e4,_0x277cd2.random()))):e.awpDm(e[r(749)],typeof a)&&(a instanceof ArrayBuffer||a[r(966)]&&e[r(445)](a.buffer,ArrayBuffer))||e[r(1122)](r(747),typeof a)?"":(JSON[r(1039)](a),e[r(1622)])}catch{return e[r(378)](e[r(749)],typeof a)?e[r(1086)]:""}}let zp=(a,r)=>{let o=t;switch(a){case o(927):case e[o(1171)]:return{[o(875)+a]:1,"x-tt-env":r};default:return{}}};class Up{constructor(r){let o=t;this[o(1820)+o(1029)]=r,this[o(1559)]=0}[t(1320)](){this.count++}[t(748)+"chMaxCount"](){let r=t;return e.jNZpK(this[r(1559)],this[r(1820)+r(1029)])}[t(549)+t(491)](r=0){let o=t,l={aOTqr:function(f,p,w){return e[G(1149)](f,p,w)},reuNq:function(f,p,w){return e.IPlID(f,p,w)},BSGXU:function(f,p,w){return e[G(1771)](f,p,w)}};e[o(1265)](e[o(1779)],e[o(1779)])?(vmmzCM.aOTqr(_0x1fb57d,_0x2f7321,66),vmmzCM[o(1460)](_0x4026a3,_0x14e519,_0x66ce4c.length),vmmzCM.BSGXU(_0x4450f8,_0x4d74c5,_0x57b803)):(this["maxLossC"+o(1029)]=r,this[o(1559)]=0)}}async function Gp(a){return new Promise(r=>{let o=G,l={KXiEA:function(f,p,w){return e[G(920)](f,p,w)},ynfXW:e[o(869)]};if(e[o(1104)](e.BQkze,"pylpX")){let f={QHelA:o(1055),oZHYO:function(p,w,E){let g=o;return qgXOrJ[g(1790)](p,w,E)},xdfUJ:qgXOrJ[o(1485)]};_0x23feeb[o(566)]()[o(859)](()=>{let p=o,w=_0x32da92(f[p(1699)],{message:this[p(1162)+p(1442)+p(1182)](_0x4d945e)});this[p(478)](f[p(1699)],w);let E=f[p(1078)](_0xd952c7,f[p(520)],{reason:this[p(1162)+p(1442)+p(1182)](_0x363abb)});this[p(478)](f[p(520)],E)})}else{if(!sr)return e[o(541)](r,o(819)+o(1034));try{let f=document[o(1373)+o(1326)](e[o(1615)]);window[o(1526)+o(1053)]=p=>{let w=o;document[w(539)].removeChild(f),window[w(1526)+w(1053)]=void 0,r(p&&p[w(903)]||w(819)+"reason")},f[o(1059)]=e.MKdNt,f[o(1300)]=e[o(1408)](a[o(1759)](/^ws/,o(1639)),o(949)+o(1607)+o(630)+"P");try{document.body[o(1012)+o(1106)](f)}catch{document[o(539)][o(1393)+o(1106)](f)}}catch{window["frontier"+o(1053)]=void 0,e.fOvpy(r,e.MLNCd)}}})}function an(a,r,o){let l=t;return!!a?.[l(1249)](f=>f[l(561)]===r&&f[l(992)]===o)}function or(a,r){let o=t;return a?.find(l=>l[o(561)]===r)?.value}let ma=null;async function qp(){let a=t;return ma||(ma=Promise[a(566)]().then(Ft[a(1785)](Ft,e[a(862)]))),ma}class Hp extends pa{constructor(r,o){let l=t;super(),this[l(852)]=r,this[l(430)]=o,this._qosDB=void 0,this[l(947)+"mise"]=null}async[t(1192)](){await this[t(602)]()}async[t(602)](){let r=t,o={vzNVk:function(l,f){return l===f},nmLPU:e[r(1391)],auUmH:function(l){return e[r(1752)](l)},iEcGW:function(l,f,p,w){return e[r(1384)](l,f,p,w)}};if(!this._qosDB){if(this._initPromise)return this[r(947)+"mise"];try{let l=this[r(852)],f=this._keyPath;this[r(947)+r(651)]=(async()=>{let p=r,{openDB:w}=await o[p(1698)](qp);this[p(1418)]=await o.iEcGW(w,p(1526)+"_"+l,1,{upgrade(E){let g=p;o[g(586)](o[g(379)],g(471))?this[g(1694)]&&this._ws[g(1458)](_0x6b22c0,_0x1e6a1a):E[g(1807)+"jectStore"](l,{keyPath:f})}})})(),await this[r(947)+"mise"]}catch(l){console[r(1563)](l)}finally{this[r(947)+r(651)]=null}}}async[t(807)](r){let o=t;try{return await this[o(602)](),this[o(1418)]?.get(this[o(852)],r)}catch(l){console.log(l)}}async set(r,o){let l=t,f={uqhHz:function(p,w){return e[G(937)](p,w)}};return l(1197)!==l(1272)?(await this[l(602)](),this[l(1418)]?.[l(1797)](this[l(852)],r)):(_0x2fb934|=0,{low:_0x21f19d,high:_0x1a7df7>>31,unsigned:lqwzxg[l(1521)](_0x1b13e1,0)})}async[t(576)](r){let o=t;try{return await this[o(602)](),this[o(1418)]?.delete(this._dbName,r)}catch(l){console[o(1563)](l)}}async clear(){let r=t,o={nwSOK:function(l,f){return e[G(1104)](l,f)}};if(e[r(626)](r(1540),e[r(876)]))try{if(e.MVdiq(e[r(1440)],e.DUnps)){let l=_0x1c5243[r(1519)],f=_0x3a3eb6.limit;return ugXySk[r(887)](l[r(559)],f)?l:l[r(1783)](0,f)}else return await this[r(602)](),this._qosDB?.[r(825)](this[r(852)])}catch(l){console[r(1563)](l)}else{let l=this[r(1418)][r(969)](this._prefix),f=_0x39ea8a.parse(e[r(366)](l,"{}"));return f[_0x63fe1d]=void 0,this[r(1418)][r(999)](this._prefix,_0x578515[r(588)+"y"](f))}}async[t(648)](){let r=t;return await this[r(602)](),this._qosDB?.[r(360)+"ys"](this._dbName)}async getAll(){let r=t;return await this[r(602)](),this[r(1418)]?.[r(1621)](this[r(852)])}async[t(642)](){let r=t;try{this._qosDB?.[r(1458)](),this[r(1418)]=void 0}catch(o){console[r(1563)](o)}}get isReady(){let r=t;try{return e.KBzQs!==r(1004)?!!this[r(1418)]:!!(e[r(1096)](this["currentI"+r(674)],this[r(563)+"s"].length)||e.nnySG(this["currentI"+r(674)],this.endpoints[r(559)]-1)&&this[r(799)+"ndpointT"+r(403)+"t"]===this[r(1070)+"es"])}catch(o){return console[r(1563)](o),!1}}}class jp{constructor(r,o){let l=t;this[l(884)]=r,this[l(614)]=o,this[l(1418)]=localStorage}async openDB(){}get _prefix(){let r=t;return r(1526)+"_"+this[r(884)]}async get(r){let o=t;if(e[o(526)](e[o(1338)],e[o(1107)])){let l={dRYBU:function(g,C){return e[o(1148)](g,C)},jLKKt:function(g,C){return g>C},DdNuV:function(g,C){return e[o(1596)](g,C)},TZAQs:function(g,C){return e[o(1842)](g,C)},RiRLA:function(g,C){return e[o(1480)](g,C)},ubXsB:function(g,C){return e[o(1093)](g,C)},hjCDs:function(g,C){return e[o(1187)](g,C)},geHFL:function(g,C){return g|C}},f=e[o(618)](_0x21295d,8192),p=e.afjLp(f,1),w=null,E=f;return function(g){let C=o;if(l[C(916)](g,1)||l[C(1009)](g,p))return l[C(795)](_0x5b84dd,g);l[C(1327)](E+g,f)&&(w=l[C(406)](_0x38a5fb,f),E=0);let L=_0x671af0[C(1253)](w,E,E+=g);return l.ubXsB(7,E)&&(E=l[C(382)](l[C(978)](7,E),1)),L}}else{let l=this[o(1418)][o(969)](this[o(465)]);return JSON[o(1039)](e[o(366)](l,"{}"))[r]}}async[t(1087)](r,o){let l=t,f=this[l(1418)][l(969)](this[l(465)]),p=JSON.parse(f||"{}");return p[o||r[this[l(614)]]]=r,this[l(1418)][l(999)](this[l(465)],JSON[l(588)+"y"](p)),o||r[this[l(614)]]}async[t(576)](r){let o=t,l=this._qosDB[o(969)](this[o(465)]),f=JSON[o(1039)](e[o(1294)](l,"{}"));return f[r]=void 0,this[o(1418)][o(999)](this[o(465)],JSON[o(588)+"y"](f))}async[t(825)](){let r=t;return this._qosDB[r(825)]()}async[t(648)](){let r=t,o=this[r(1418)][r(969)](this[r(465)]),l=JSON.parse(e[r(1145)](o,"{}"));return Object[r(648)](l)}async[t(1621)](){let r=t,o=this._qosDB[r(969)](this[r(465)]),l=JSON[r(1039)](o||"{}");return Object[r(707)](l)}closeDB(){return Promise[t(566)]()}get[t(780)](){return!!this[t(1418)]}}class Wp{constructor(r,o){let l=t;this[l(884)]=r,this[l(614)]=o,this._qosDB=On?tt:ei?wx:null}async[t(1192)](){}get[t(465)](){return t(1526)+"_"+this._DBName}async[t(807)](r){let o=t,l=this[o(1418)][o(1282)+o(1651)](this[o(465)]);return JSON[o(1039)](e[o(627)](l,"{}"))[r]}async[t(1087)](r,o){let l=t,f=this[l(1418)][l(1282)+l(1651)](this[l(465)]),p=JSON.parse(e[l(1145)](f,"{}"));return p[o||r[this._pathKey]]=r,this._qosDB[l(1531)+l(1651)](this._prefix,JSON[l(588)+"y"](p)),o||r[this[l(614)]]}async[t(576)](r){let o=t,l=this._qosDB[o(1282)+o(1651)](this[o(465)]),f=JSON[o(1039)](e[o(1294)](l,"{}"));return f[r]=void 0,this[o(1418)][o(1531)+o(1651)](this[o(465)],JSON[o(588)+"y"](f))}async clear(){let r=t;return this[r(1418)]["clearSto"+r(415)]()}async[t(648)](){let r=t,o=this._qosDB[r(1282)+r(1420)+"nc"](this[r(465)]),l=JSON.parse(e[r(1520)](o,"{}"));return Object[r(648)](l)}async getAll(){let r=t,o=this[r(1418)][r(1282)+r(1420)+"nc"](this[r(465)]),l=JSON[r(1039)](e.ArZmM(o,"{}"));return Object[r(707)](l)}closeDB(){return Promise[t(566)]()}get[t(780)](){let r=t,o={wPEyc:function(l,f,p){return l(f,p)},QpdXR:function(l,f){return l+f}};if(r(1136)!==e[r(1769)]){let l=wvAFqi[r(1073)](_0x3d872d,_0x349452,_0x1ee6b7[r(400)]),f=_0x3e0efa.bytes,p=_0x561b37[r(1519)];for(let w=0,E=_0x3e2df9[r(400)];w<E;w++)f[wvAFqi[r(1773)](w,l)]=p[w]}else return!!this[r(1418)]}}function ml(a,r){let o=t;if(e.bBBiq(e[o(543)],e[o(543)])){if(e[o(773)](On,On))return new Wp(a,r);if(e.xBykd(sr,ti)&&e[o(1693)](e[o(1261)],typeof indexedDB))return new Hp(a,r);if((sr||ti)&&e[o(1261)]!=typeof localStorage)return new jp(a,r);throw new Error(e.fZwwP)}else _0x38401f+=e[o(800)](_0xbedc34,_0x187594),_0x11fcc8+=2}class Kp{constructor(){let r=t;this[r(1065)+r(569)+"Id"]=null,this._interval=36e5,this[r(1418)]=e[r(349)](ml,e[r(817)],e[r(873)])}async[t(1065)+t(741)](){let r=t;e[r(1596)](clearInterval,this[r(1065)+r(569)+"Id"]),this._intervalTimeoutId=setInterval(()=>{this.flushExpired()},this[r(1065)+"l"])}async[t(1192)](){let r=t;await this[r(1418)][r(1192)]()[r(859)](()=>{let o=r;this[o(1065)+o(741)]()})}async[t(1427)+t(1535)](){let r=t;(await this._qosDB?.[r(1621)]()||[])[r(1103)](({timestamp:f})=>f<Date[r(412)]())[r(981)](f=>{let p=r;this._qosDB?.[p(576)](f[p(1497)+"id"])})}async del(r){return this._qosDB?.del(r)}async[t(1087)](r,o){let l=t;return this[l(1418)]?.[l(1087)]({message_id:r,timestamp:o})}async get(r){let o=t;return this[o(1418)]?.[o(807)](r)}async[t(642)](){let r=t;clearInterval(this[r(1065)+"lTimeoutId"]),await this[r(1418)]?.closeDB()}get[t(780)](){let r=t;return this._qosDB?.[r(780)]}}function wa(a){let r=t,o=!!this[r(686)][r(1548)+"S"];if(!o)return{enabled:o,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(1384)](an,a[r(770)][r(856)],e.FtDVJ,"2"),f=l&&e[r(1821)](an,a[r(770)][r(856)],"x_frontier_qos_ack","1"),p=l&&e.gpAry(an,a[r(770)][r(856)],r(572)+r(1026)+"k","1"),w=p?e[r(1324)](or,a[r(770)][r(856)],e[r(814)])?.split(",")[r(1103)](Boolean)||[]:[];return{enabled:o,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:p,ackMsgIds:w}}async function wl(){let a=t;return this[a(1045)+"ger"]||(this[a(1045)+a(544)]=new Kp),this[a(1045)+a(544)][a(780)]||await this._QoSManager.openDB(),this["_QoSMana"+a(544)]}async function $p(a,r){let o=t,{enableAutoAck:l}=this[o(686)],f=e[o(1141)](an,a[o(770)][o(856)],e[o(1736)],"1"),p=e.dUuHh(an,a[o(770)][o(856)],"is_ack","1"),w=wa[o(1253)](this,a);if(e[o(1348)](l,f)){let{SeqID:E,LogID:g,service:C,LogIDNew:L,method:N}=a[o(770)];this[o(904)]({SeqID:E,LogID:g,LogIDNew:L,service:C,method:N,headers:[{key:e[o(845)],value:"1"},{key:e[o(1695)],value:e[o(1254)](L,"")},{key:e[o(1690)],value:"0"}]})}p&&!w[o(1240)]&&this[o(670)+o(1565)+"ageEvent"](a),e[o(1752)](r)}async function Vp(a,r){let o=t;this[o(1365)](o(479),a[o(770)]),e.GKUyd(r)}async function Jp(a,r){let o=t,l=e[o(908)](rn,await e[o(1105)](gl,a[o(1014)]));try{if(e[o(445)](l[o(1002)],Uint8Array)){let f=e[o(703)](this[o(686)]["payloadE"+o(1238)],Object)?{force:!!this[o(686)][o(1728)+"ncoding"][o(678)],encoding:this[o(686)][o(1728)+o(1238)][o(1400)]?this[o(686)]["payloadE"+o(1238)][o(1400)][o(1759)](/\s/g,"")[o(643)+"ase"]():""}:{force:!1,encoding:this[o(686)]["payloadE"+o(1238)]?this[o(686)].payloadEncoding[o(1759)](/\s/g,"")["toLowerC"+o(771)]():""},p=l[o(1728)+o(1238)]?l["payloadE"+o(1238)][o(1759)](/\s/g,"")[o(643)+o(771)]():"",w=e[o(703)](this[o(686)].payloadType,Object)?{force:!!this[o(686)].payloadType.force,type:this[o(686)]["payloadT"+o(1342)][o(1059)]?this[o(686)][o(735)+o(1342)][o(1059)][o(1759)](/\s/g,"")[o(643)+o(771)]():""}:{force:!1,type:this._options[o(735)+o(1342)]?this[o(686)][o(735)+o(1342)][o(1759)](/\s/g,"")[o(643)+o(771)]():""},E=l[o(735)+o(1342)]?l[o(735)+o(1342)].replace(/\s/g,"")[o(643)+"ase"]():"",g=w.force?w[o(1059)]:E||w.type,C=f.force?f.encoding:p||f[o(1400)],L=[e[o(1086)],e[o(1622)],e[o(1575)],e[o(749)]],N=[e[o(1267)],e[o(428)]];this._options[o(364)+o(1640)+"extPayload"]&&L[o(758)](g)&&(!C||N[o(758)](C))?l[o(1672)+"oad"]=e[o(1384)](pl,l[o(1002)],0,l[o(1002)][o(1721)+"th"]):l[o(1672)+"oad"]=""}else l[o(1672)+o(919)]=""}catch(f){l["textPayl"+o(919)]="",console[o(1563)](f)}a.message=l,r()}function Zp(a,r,o){let l=t,f=e[l(1145)](o,8192),p=e[l(1663)](f,1),w=null,E=f;return function(g){let C=l;if(g<1||e[C(926)](g,p))return a(g);e[C(527)](E,g)>f&&(w=e[C(1747)](a,f),E=0);let L=r[C(1253)](w,E,E+=g);return 7&E&&(E=e[C(1322)](e[C(891)](7,E),1)),L}}let Yp=4294967295;function Xp(a,r,o){let l=t;return e[l(531)](e.raOsG,e[l(1656)])?_0x34bc85[l(1507)+l(1718)][1]?void 0:_0x50e39d[l(1507)+l(357)](_0x46c6c1["objectSt"+l(1718)][0]):e[l(858)](RangeError,e[l(1678)](e[l(1095)](e[l(1205)]("index ou"+l(863)+l(665),a),e.JwLwS)+e.BXxTI(r,1),e[l(1242)])+o)}function Qp(a,r,o){let l=t;if(e[l(1586)](o,Yp))throw new Error(e[l(1241)]);let f=3;for(;e[l(1515)](f,0);){let p=e.VkLtT(255,o);e[l(1384)](ya,p,a,e.UqYvW(r,f)),o>>>=8,f--}return e[l(1686)](r,4)}function eg(a,r){let o=t,l=0,f=r,p=e[o(1156)](r,4);for(;f<p;){let{value:w,offset:E}=e[o(1828)](_a,a,f);f=E,l=e[o(1329)](e[o(1354)](l,8),0),l+=w}return{value:l,offset:p}}function tg(a,r,o){let l=t,f=e.JeCPA[l(1512)]("|"),p=0;for(;;){switch(f[p++]){case"0":return e[l(449)](ga(a,r,o),o);case"1":if(r[l(1466)])return e[l(809)](r[l(1466)](a,o),o);continue;case"2":if(!a)return o;continue;case"3":if(e[l(899)](a.length,40))return e[l(1134)](e[l(629)](ga,a,r,o),o);continue;case"4":if(r[l(989)+"e"])return e.kCEoZ(r.utf8Write(a,o),o);continue}break}}function ng(a,r){let o=t,l=new xe(e[o(911)](e[o(463)](e[o(793)](e.yuEQI(a[e[o(631)](r,4)],24),e[o(689)](a[e[o(1581)](r,5)],16)),e[o(425)](a[e.wuxGu(r,6)],8)),a[e[o(1408)](r,7)]),e[o(909)](e[o(397)](e[o(502)](a[r+0],24)|e[o(905)](a[e.TezYV(r,1)],16),e[o(1170)](a[e[o(517)](r,2)],8)),a[e[o(1658)](r,3)]),!0);return r+=8,{value:l,offset:e.AjMcr(r,8)}}function rg(a,r,o){let l=t,f=a[l(395)],p=a[l(1613)];return r[o]=p>>>24,r[o+1]=e[l(1541)](p,16)&255,r[o+2]=e[l(834)](e[l(1202)](p,8),255),r[e[l(1201)](o,3)]=e[l(346)](255,p),r[e.OxbOe(o,4)]=e[l(598)](f,24),r[e[l(1156)](o,5)]=e[l(1628)](f>>>16,255),r[e[l(1337)](o,6)]=e[l(1299)](e.HHFiy(f,8),255),r[e[l(1445)](o,7)]=255&f,o+=8,o}function _a(a,r){let o=t;return a[o(389)+"8"]?{value:a.readUInt8(r),offset:e[o(454)](r,1)}:{value:e[o(1529)](255,a[r]),offset:e[o(1822)](r,1)}}function ya(a,r,o){let l=t;return r.writeUint8?r[l(1374)+"t8"](a,o):r[o]=e.MqRDo(255,a),o+1}let ig=function(a){return new Uint8Array(a)},sg=e[t(1261)]!=typeof Buffer?Buffer["allocUns"+t(1311)]:e[t(917)](Zp,ig,Uint8Array[t(1042)+"e"][t(1783)]);(()=>{let a=t,r={SwCqW:e[a(872)],IaRib:function(l,f){return l>f},VgugA:function(l,f,p,w){return e[a(635)](l,f,p,w)},THcNz:function(l,f){return l>>>f},yFiun:function(l,f){return e[a(1583)](l,f)},puZLQ:function(l,f){return e[a(774)](l,f)},TYpxD:function(l,f){return e[a(1394)](l,f)},fzlUi:function(l,f){return l<<f},yUrJR:function(l,f){return e[a(1509)](l,f)},GvGwM:function(l,f){return l|f},IbLTr:function(l,f){return e[a(1293)](l,f)},RrBSb:function(l,f){return e[a(1072)](l,f)},TILab:function(l,f){return e[a(1632)](l,f)},AYBAR:function(l,f){return e[a(533)](l,f)}},o=4294967295;return function(l,f,p=!0){let w=a,E=r[w(1155)][w(1512)]("|"),g=0;for(;;){switch(E[g++]){case"0":if(r[w(1682)](f+=5,l.length))throw f=l.length,r[w(1513)](Xp,f,10,l[w(559)]);continue;case"1":o=r[w(613)](r[w(1840)](127,l[f]),0);continue;case"2":o=(o|r[w(1840)](127,l[f])<<21)>>>0;continue;case"3":if(r.puZLQ(l[f++],128))return{value:p?o:0|o,offset:f};continue;case"4":if(l[f++]<128)return{value:p?o:r[w(734)](0,o),offset:f};continue;case"5":o=(o|r[w(579)](r[w(1840)](127,l[f]),7))>>>0;continue;case"6":if(r[w(1533)](l[f++],128))return{value:p?o:r[w(954)](0,o),offset:f};continue;case"7":if(r.IbLTr(l[f++],128))return{value:p?o:0|o,offset:f};continue;case"8":return{value:p?o:r.RrBSb(0,o),offset:f};case"9":if(r[w(1092)](l[f++],128))return{value:p?o:r.GvGwM(0,o),offset:f};continue;case"10":o=(o|r.AYBAR(15&l[f],28))>>>0;continue;case"11":o=r[w(613)](r.TYpxD(o,r[w(579)](127&l[f],14)),0);continue}break}}})();let og=16,ba=32;function ag(a){let r=t,o={VfbUo:function(p,w){return p<w},MFtQx:function(p,w){return e[G(1283)](p,w)},Ftrxe:function(p,w){return e[G(1410)](p,w)}},l=0,f={};for(let p=0;e[r(1676)](p,a[r(559)]);p++)if(e[r(1265)]("euYcN",e.TrvOT))f[a[p][r(439)+r(524)]]=e[r(779)](xl,a[p]["cursor_n"+r(524)]),l+=e[r(1353)](14,f[a[p]["cursor_n"+r(524)]]);else{let w=_0x210703[r(1512)](":");_0x61917a&&(_0x361190=w[r(559)]),_0x2d8f4f+=w[r(559)];for(let E=0;DpCzhy[r(1115)](E,w[r(559)]);E++)if(DpCzhy.MFtQx(4,w[E][r(559)])){let g=_0x43732e.substring(0,DpCzhy[r(1175)](4,w[E][r(559)])),C=g[r(437)](w[E]);_0x409263[r(946)](C)}else _0x52bf05[r(946)](w[E]);_0x1d1f64=!1}return[l,f]}function _l(a,r,o){let l=t,[f,p]=e.WVVDC(ag,a),w=sg(f),E=0;return a[l(981)](g=>{let C=l,L=e.LQVqa[C(1512)]("|"),N=0;for(;;){switch(L[N++]){case"0":console[C(1563)](e.PGRrF,g,g.service);continue;case"1":console[C(1563)](e.npbZg,E);continue;case"2":console[C(1563)](e.xMlpc,E);continue;case"3":E=e[C(1814)](Qp,w,E,g[C(850)]||0);continue;case"4":console.log(e.qmHoS,E);continue;case"5":console[C(1563)](C(1566),E);continue;case"6":console.log(C(763),E);continue;case"7":E=ya(p[g[C(439)+C(524)]],w,E);continue;case"8":E=e[C(1384)](rg,xe[C(861)+"er"](g[C(693)]||r),w,E);continue;case"9":E=ya(0,w,E);continue;case"10":E=tg(g[C(439)+C(524)],w,E);continue}break}}),{frameType:ba,headers:[{key:e.SoMSZ,value:o}],payload:w}}function cg(a){let r=t,o=0,l=[];for(;e[r(1048)](o,a.byteLength);){let{offset:f}=e[r(1317)](_a,a,o);o=f;let p={cursor_name:"",cursor:0,service:0},{value:w,offset:E}=e.zMeTT(eg,a,o);p[r(850)]=w,o=E;let{value:g,offset:C}=e.HNYzC(_a,a,o);o=C,p[r(439)+r(524)]=e[r(453)](pl,a,o,o+g),o+=g;let{value:L,offset:N}=ng(a,o);p[r(693)]=L[r(608)](),o=N,l[r(946)](p)}return l}function dg(){let a=t;return{frameType:ba,headers:[{key:e.SoMSZ,value:e[a(938)]}],payload:void 0}}class lg{constructor(r,o,l){let f=t;e.AlymX(e[f(600)],e[f(600)])?(this[f(401)+"ameSpace"]=r,this[f(607)+f(1767)]=o,this[f(426)+f(1455)]=l,this[f(1418)]=ml(this[f(401)+"ameSpace"],e.oVOvV)):this[f(686)][f(1021)]&&_0x481c62[f(1563)][f(461)](_0x4b7bc1,[e.tTwsb,..._0x498ac2])}async[t(1192)](){let r=t;await this[r(1418)][r(1192)]()}async[t(944)+"rs"](){let r=t;if(!this[r(1418)][r(780)])return;let o=this[r(426)+r(1455)],l=await this[r(1418)][r(1621)]();switch(console[r(1563)](e[r(1216)],l),o){case e[r(1727)]:return l&&l.length?e.BsrRm(_l,l,0,this[r(607)+"ileName"]):void 0;case r(411):return;case e.fsFWd:return l&&l[r(559)]?e.CYTiD(_l,l,0,this[r(607)+r(1767)]):e[r(1675)](dg)}}async set(r,o,l){let f=t;return console[f(1563)](e[f(1035)],r,o,l),this._qosDB[f(1087)]({cursor_name:r,cursor:o,service:l})}async[t(1798)+"rs"](r){let o=t;if(e.Ehqfx("CaQDW",e[o(1257)]))return KCTZtp[o(699)](_0x523a57,_0x1a0bb2)&&(_0x2a8314===KCTZtp[o(452)]||KCTZtp[o(1196)](_0x38b003,KCTZtp[o(1191)]))?!0:KCTZtp.puzUg(_0x4ea7e0,_0x63f1c7);{let l=e.Ohzde(cg,r);for(let f of l)console[o(1563)](e[o(815)],l),await this._qosDB[o(1087)](f)}}async[t(807)](r){let o=t;return(await this[o(1418)].get(r))?.[o(693)]}async[t(642)](){let r=t;e[r(783)](e[r(362)],e.COssf)?await this[r(1418)].closeDB():(_0x24cc8f[r(539)].removeChild(_0x1c8ee7),_0x3c4f59["frontier"+r(1053)]=void 0,e[r(604)](_0x3de2c4,_0x243f97&&_0x2fc4f7[r(903)]||e[r(443)]))}[t(418)+"rsorFile"+t(1306)](r){let o=t;this[o(607)+o(1767)]=r}get[t(780)](){return this._qosDB.isReady}}let ug=e[t(1787)];async function yl(a){let r=t,o={WDDde:function(E,g){return e.ROdeg(E,g)}};if(!this[r(686)].enableQoS)return null;let{aID:l,fpID:f,messageStrategy:p}=this[r(686)],w=e[r(1375)](a,ug);try{if(this[r(655)+"anager"]){if(e[r(914)](e[r(1605)],e[r(521)]))return xcsSmh[r(514)](_0x44b80a,_0x5d6760);a&&this[r(655)+r(1750)][r(418)+r(1598)+"Name"](a)}else this[r(655)+r(1750)]=new lg(f+"_"+l+"_"+w,w,p);return this["_cursorM"+r(1750)][r(780)]||await this[r(655)+"anager"].openDB(),this._cursorManager}catch{return null}}async function fg(a,r){let o=t,l=e[o(738)](an,a[o(770)][o(856)],e[o(433)],"-1"),f=an(a[o(770)][o(856)],e[o(845)],"1"),p=or(a.message[o(856)],o(572)+"er_msgid"),w=e[o(786)](Number,e.wGNyo(or,a[o(770)][o(856)],e[o(1776)]))||0,E=wa[o(1253)](this,a),g=e[o(629)](an,a.message[o(856)],e.LPAlw,"2"),C=e[o(628)](or,a.message.headers,e[o(700)]),L=e[o(1099)](Number,e.fbEKd(or,a.message[o(856)],e.DvWGq));if(E.isQoSAck)return e[o(1675)](r);let N=E["isQoSMes"+o(605)]?await wl[o(1253)](this):null;if(e[o(398)](a[o(770)][o(850)],0)&&f&&!l||e[o(1842)](a[o(770)][o(850)],0)){if(p&&E[o(472)+o(605)]&&N)if(e.tdJnf(e[o(587)],o(584)))try{return!!this[o(1418)]}catch($){return _0x284c88.log($),!1}else return!!!await N[o(807)](p)&&(this["_dispatc"+o(1627)+o(427)](a),await N[o(1087)](p,e[o(500)](Date[o(412)](),w))),e[o(1279)](r);if(g){let $=await yl[o(1253)](this);if(!$)return this[o(670)+o(1627)+o(427)](a),e[o(1752)](r);let se=await $[o(807)](C)??-1;if(se<L)this[o(670)+o(1627)+"Event"](a),$[o(1087)](C,L,a[o(770)][o(850)]);else throw new Error(o(1609)+o(1037)+" cursor "+L+(o(1231)+o(413)+o(1723)+"r ")+se);return e[o(1752)](r)}return this[o(670)+"hMessage"+o(427)](a),e[o(650)](r)}}async function hg(a,r){let o=t,l=wa[o(1253)](this,a);if(!l[o(472)+o(605)])return r();let f=await wl.call(this);if(l[o(1278)+o(385)+"age"]&&l.ackMsgIds[o(559)])for(let p of l[o(1114)+"s"])await f[o(576)](p);e[o(1752)](r)}async function xg(a,r){let o=t,l=e[o(921)](a[o(770)][o(438)+"e"],og),f=e.Ehqfx(a[o(770)][o(438)+"e"],ba);if(!l&&!f)return e[o(1401)](r);let p=e.dOIKy(or,a.message.headers,e[o(1295)]);if(!p)return e[o(1279)](r);let w=await yl[o(1253)](this,p);if(!w)return e[o(1675)](r);if(l){let E=await w[o(944)+"rs"](),g={frameType:E?.[o(438)+"e"],SeqID:xe.fromNumber(this[o(1411)]++),LogID:xe[o(861)+"er"](this[o(686)][o(659)+"erator"]()),service:9e3,method:5,headers:E?.[o(856)],payload:E?.[o(1002)]},C=S(g);this[o(1694)]&&this[o(1694)].readyState&&this[o(1694)].send(C)}if(f){let E=a.message[o(1002)];E&&w[o(1798)+"rs"](E)}}let pg=async function(a,r){let o=t;this[o(1412)]=!1,e[o(580)](clearTimeout,this["_connect"+o(1054)+o(474)]),e[o(782)](r)},gg=async function(a,r){let o=t;if(!this[o(1694)]||e.yyNYE(this[o(1694)][o(1473)+"te"],this[o(458)]))return e.FqoFp(r);let{pingInterval:l}=this._options;this["_endpoin"+o(953)]?.[o(958)+o(894)+o(922)]();for(let p=0;p<this[o(426)+o(371)].length;p++){let w=this[o(426)+o(371)][p];if(e[o(1017)](this[o(1694)][o(1473)+"te"],this[o(458)])&&w!==null)if(e[o(1264)]!=="xpFjv")this[o(1694)]&&this[o(1694)].send(w),this[o(426)+o(371)][p]=null;else return _0x3c5d4f;else break}this[o(426)+o(371)]=this[o(426)+o(371)].filter(p=>!!p),this[o(505)+o(1166)+"Id"]=e[o(687)](setTimeout,()=>this[o(1200)](),l),this[o(670)+o(757)+"nt"](a),this._isBrowser&&this[o(1694)]&&(this[o(1694)][o(932)+"pe"]=this[o(1188)+o(1342)]);let f=this[o(933)+o(953)]?.[o(1351)+o(743)+"nt"]();this[o(1365)](o(1697)+f+o(464)),e[o(1438)](r)},mg=async function(a,r){let o=t,l=this["_endpoin"+o(953)]?.[o(1351)+o(743)+"nt"]();this[o(1365)](o(1697)+l),e.LkrJb(r)};class wg extends pa{constructor(r){let o=t,l={hWNkr:function(E,g){return e[G(1085)](E,g)},PgZHp:function(E,g){return e[G(1819)](E,g)},eiuLA:function(E,g){return e[G(689)](E,g)},wQPcm:function(E,g){return e[G(1709)](E,g)},cHSiU:function(E,g){return e[G(1722)](E,g)},MNJee:function(E,g){return e[G(1801)](E,g)},qWAtI:function(E,g){return e[G(1583)](E,g)}};super(),this[o(983)+"igatorOnline"]=!0,this[o(1235)+"er"]=sr,this._isNode=Lp,this._isMiniTT=On,this[o(798)+"X"]=ei,this[o(1277)+"r"]=ti,this[o(426)+"Queue"]=[],this._endpointManager=null,this[o(790)+o(494)]=!1,this[o(1188)+"ype"]="arraybuf"+o(1287),this[o(654)+o(1811)]=!1,this[o(654)+o(1054)+o(474)]=null,this[o(682)+o(1511)+o(1144)]=null,this["_pingPon"+o(1166)+"Id"]=null,this[o(1411)]=0,this[o(1412)]=!1,this[o(907)]="",this[o(1045)+o(544)]=null,this[o(655)+o(1750)]=null,this[o(455)+o(847)]=null,this._protocols=e[o(1248)],this[o(1671)]=3,this[o(731)+"NG"]=0,this.OPEN=1,this[o(1152)]=2,this._onOpen=E=>{let g=o;try{e[g(1104)](g(1761),e.xgPcZ)?e[g(453)](hl,this,E,[pg,gg,mg]):(_0x7a6609=lOIovn[g(1534)](lOIovn[g(886)](65536,lOIovn[g(683)](1023&_0x16b437,10)),lOIovn[g(1619)](1023,_0x4924f0)),++_0x3333c3,_0x521ce8[_0x295c81++]=lOIovn.cHSiU(_0xfdc87f,18)|240,_0x433ec0[_0x5b545a++]=lOIovn[g(660)](lOIovn[g(1619)](lOIovn[g(1027)](_0x31ec80,12),63),128),_0x517544[_0x3eb998++]=lOIovn[g(660)](lOIovn.qWAtI(_0x5db143>>6,63),128),_0x465596[_0x210b3d++]=63&_0x42d696|128)}catch(C){let L=e[g(1149)](lt,e.SsgkD,{message:C[g(770)],code:on[g(388)+"OR"],error:C});this[g(670)+g(552)+g(880)](L)}},this[o(647)+"ge"]=async E=>{let g=o,{pingInterval:C,pingFrequency:L}=this[g(686)];if((e[g(783)]("hi",E[g(1014)])&&e[g(512)](e[g(715)],L)||e[g(1720)](e[g(962)],L))&&(this[g(487)+g(1744)](),this[g(478)](e[g(1832)],e.uRpiV),this[g(505)+g(1166)+"Id"]=setTimeout(this[g(1200)][g(1785)](this),C)),!e[g(1481)]("hi",E.data))try{e[g(453)](hl,this,E,[Jp,$p,hg,xg,fg,Vp])}catch(N){let $=lt(e[g(1791)],{message:N.message,code:on[g(1097)+"ERROR"],error:N});this[g(670)+g(552)+g(880)]($)}},this._onError=E=>{let g=o,C=this[g(933)+"tManager"]?.[g(748)+g(1568)+"es"](),L=this[g(933)+g(953)]?.[g(1351)+"ntEndpoint"]();if(C&&!E[g(770)]){let N=g(1746)+L+(g(1383)+g(1701)+g(1818)+"ed");this[g(670)+g(552)+g(880)](e.CtdgD(lt,g(1055),{message:N,code:on[g(557)+"IES_ERROR"],error:E}));return}this._ws&&e.rpwJM(this._ws.readyState,this[g(458)])&&this[g(1343)+g(986)](),this["_dispatc"+g(552)+g(880)](e[g(716)](lt,e.SsgkD,{message:E[g(770)],code:on[g(1233)+g(1215)],error:E}))},this[o(373)]=async E=>{let g=o;this[g(690)+g(1309)](),this["_clearPi"+g(1744)](),this[g(1212)+"sListeners"](),this[g(1694)]=null,this[g(654)+g(1811)]=!1;let C=this["_endpoin"+g(953)]?.["checkRea"+g(1568)+"es"]();if(!C&&this[g(1740)+g(1127)]()&&!this["_readyCl"+g(494)]){let L=this[g(933)+g(953)]?.[g(1351)+"ntEndpoint"](),N=this[g(686)][g(619)+g(1321)+g(1496)](E[g(1143)],E[g(1034)]);this["_dispatchCloseEv"+g(880)](wt(e.nooKa,{code:1006,reason:E[g(1034)]||"connecti"+g(1314)+"d, unkno"+g(1557)+g(1098)+g(1661)+L,willReconnect:N})),N&&this[g(654)]();return}if(e[g(874)](1e3,E[g(1143)])&&this[g(790)+"osed"]){this[g(670)+g(883)+g(880)](e.SVgfB(wt,e[g(869)],{code:1e3,reason:g(1577)})),this["_endpoin"+g(953)]?.[g(958)+"pointConfig"](),this["_pingLos"+g(847)]?.[g(549)+g(491)]();return}if(E.code!==1e3&&C){let L=this[g(933)+"tManager"]?.[g(1351)+g(743)+"nt"](),N=E[g(1034)];N||(N=await Gp(this[g(907)])),N=g(1501)+g(1314)+g(896)+N+(g(1304)+"me: ")+L+(g(1116)+"tries re"+g(420)),this["_dispatc"+g(883)+"ent"](wt(g(1458),{code:E[g(1143)],reason:N}));let $=g(1746)+L+(" fail, m"+g(1701)+g(1818)+"ed");this[g(670)+g(552)+"ent"](e[g(1221)](lt,e.SsgkD,{message:$,code:on["MAX_RETR"+g(1328)+"R"]})),this[g(933)+"tManager"]?.["resetEndpointCon"+g(922)](),this[g(455)+g(847)]?.[g(549)+g(491)]();return}if(e[g(652)](1e3,E.code)&&!E[g(1034)]){let L=this[g(933)+g(953)]?.[g(1351)+g(743)+"nt"]();this[g(670)+g(883)+g(880)](e[g(708)](wt,"close",{code:E[g(1143)],reason:g(1501)+"ng faile"+g(695)+"wn reaso"+g(1098)+g(1661)+L})),this[g(933)+g(953)]?.[g(958)+g(894)+g(922)](),this["_pingLos"+g(847)]?.[g(549)+"nter"]();return}this["_dispatc"+g(883)+"ent"](E),this["_endpoin"+g(953)]?.["resetEnd"+g(894)+g(922)](),this[g(455)+g(847)]?.[g(549)+g(491)]()},this.onclose=null,this[o(387)]=null,this[o(1139)+"e"]=null,this[o(722)]=null,this[o(1731)+o(528)]=null,this[o(1168)+o(1554)]=null,this[o(1224)+o(1220)+o(753)+"ct"]=null,this["_handleO"+o(1588)]=this[o(1726)+o(1588)][o(1785)](this),this[o(1726)+o(558)]=this[o(1726)+o(558)].bind(this),this[o(751)+"ageHide"]=this[o(751)+o(977)][o(1785)](this),this["_handleP"+o(1286)]=this[o(751)+"ageShow"].bind(this),this[o(686)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[o(737)](1,0),service:0,logIDGenerator:s,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[o(962)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e.fsFWd,env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:p}=r,w=Array.isArray(f)?f:e.THEKg(e[o(749)],typeof f)?[f]:[];if(!w||e.bYYQd(0,w[o(559)]))throw new Error(e[o(1177)]);if(!e[o(1361)](Bp,p))throw new Error(e[o(365)]);Object[o(597)](this._options,r),this[o(933)+o(953)]=new fl(w,this[o(686)].maxRetries),this[o(455)+"sCounter"]=new Up(this[o(686)][o(1571)+o(1489)]),this[o(686)][o(1325)+o(1386)]&&(this[o(1412)]=!0,this[o(654)]()),this[o(686)]["listenNe"+o(633)+"nged"]&&(this[o(1633)+"T"]||this[o(798)+"X"]?this[o(369)+"etWorkCh"+o(935)]():this[o(1235)+"er"]&&this["_initGlo"+o(1756)+o(1617)]())}[t(1726)+t(1588)](){let r=t;this[r(686)]["disableAutoRecon"+r(1592)]||this[r(790)+"osed"]||this["_handleR"+r(528)]()}[t(1726)+t(558)](){let r=t,o={UyeIe:function(l,f){return e[G(1419)](l,f)},tuBFJ:function(l,f){return e[G(589)](l,f)},IJjpT:function(l,f){return e[G(490)](l,f)},cqPRy:function(l,f){return l|f},rvhev:function(l,f){return l<<f},ckDGV:function(l,f){return e[G(1369)](l,f)},KFVsM:function(l,f){return l|f},LryOq:function(l,f){return l&f},YlHxk:function(l,f){return e[G(1824)](l,f)},CAKNO:function(l,f){return e[G(1681)](l,f)},itZsK:function(l,f){return e.MsIuQ(l,f)},frUVH:function(l,f){return e.hIYZT(l,f)},cjoWK:function(l,f){return e.ZcizB(l,f)},wWrff:function(l,f,p){return l(f,p)},OsbAy:function(l,f){return e[G(844)](l,f)},SuytJ:function(l,f){return l+f},fvlOI:function(l,f){return e[G(1130)](l,f)}};if(e.VtIib(e[r(806)],e[r(806)]))_0x3f4064=_0xe279a1[LstyDK[r(879)](LstyDK[r(879)](_0x1f6fed,_0x2d7dcd),1)],_0x5ae056=_0x52499e[LstyDK[r(879)](LstyDK.UyeIe(_0x1bc3fe,_0x489957),2)],_0xe02bf9=_0x1328d3[LstyDK[r(974)](_0x5973f8+_0x350e09,3)],LstyDK[r(1488)](LstyDK[r(1737)](_0x396867,LstyDK[r(1172)](_0x5bc533,8))|LstyDK.ckDGV(_0x3a0382,16),12632256)!==8421504?_0x39c1a9+=_0x51a90e:(_0x2b263d=LstyDK.cqPRy(LstyDK[r(532)](LstyDK[r(1634)](LstyDK[r(1805)](7,_0x2e19dd),18),LstyDK[r(1634)](LstyDK[r(777)](63,_0x1cf76e),12)),LstyDK[r(756)](LstyDK[r(1488)](63,_0x15d5cb),6))|LstyDK[r(1090)](63,_0x2d2d75),LstyDK.frUVH(_0x1febd1,65536)||LstyDK[r(1333)](_0x32aa59,1114111)?_0x53dc1e+=_0x2dedd6:(_0x5d22e1-=65536,_0x586226+=LstyDK[r(1284)](_0x5312f6,LstyDK[r(974)](LstyDK[r(1013)](_0x2385dc,10),55296),LstyDK[r(776)](LstyDK.fvlOI(1023,_0x4a3e56),56320)),_0x29263c+=3));else{this[r(432)+"WebSocket"]();let l=e[r(1788)](xa,e[r(679)],{message:e[r(1831)]});this["onStopIm"+r(1220)+r(753)+"ct"]&&this["onStopIm"+r(1220)+r(753)+"ct"](l)}}["_initGlobalEvent"+t(1617)](){let r=t;this[r(1235)+"er"]&&window["addEvent"+r(1617)](e[r(1434)],this[r(1726)+"nLine"]),this._isBrowser&&window[r(1195)+"Listener"](r(1135),this["_handleO"+r(558)]),this[r(1235)+"er"]&&window["addEvent"+r(1617)](e.NScyl,this[r(751)+"ageHide"]),this[r(1235)+"er"]&&window[r(1195)+r(1617)](e[r(1587)],this["_handleP"+r(1286)])}[t(646)+"balEventListener"](){let r=t;this._isBrowser&&window[r(1363)+r(1016)+r(1552)](e[r(1434)],this[r(1726)+r(1588)]),this._isBrowser&&window[r(1363)+"entListe"+r(1552)](e[r(1043)],this[r(1726)+r(558)]),this[r(1235)+"er"]&&window[r(1363)+"entListe"+r(1552)](e[r(1754)],this["_handleP"+r(977)]),this[r(1235)+"er"]&&window[r(1363)+r(1016)+r(1552)](e.pKqbl,this["_handleP"+r(1286)])}[t(751)+"ageHide"](r){let o=t;r[o(1662)+"d"]||(e[o(542)](o(1336),"VFiZy")?(this[o(1235)+"er"]&&window[o(1363)+o(1016)+o(1552)](e[o(1754)],this[o(751)+o(977)]),this[o(1235)+"er"]&&window[o(1363)+o(1016)+"ner"](e[o(1587)],this["_handleP"+o(1286)]),this[o(1458)]()):(e.EkAMz(_0x3cb39f,65536)?_0x651e66[_0x33bae5++]=e[o(1120)](e[o(1722)](_0x4f637f,12),15)|224:(_0x23d92c[_0x167423++]=e[o(867)](e[o(1813)](_0x4b5df9,18),7)|240,_0xed68ce[_0x14f3be++]=e[o(1801)](e.hMEvc(e[o(1772)](_0x57af67,12),63),128)),_0x2de361[_0x3287b8++]=e[o(1281)](e[o(1068)](_0x351cc1>>6,63),128))),this[o(1235)+"er"]&&window["removeEv"+o(1016)+"ner"](e[o(1434)],this["_handleO"+o(1588)]),this._isBrowser&&window["removeEv"+o(1016)+"ner"](o(1135),this[o(1726)+"ffLine"])}[t(751)+t(1286)](r){let o=t;if(e[o(1483)]!=="ZVWNW")r[o(1662)+"d"]&&(this[o(1740)+o(1127)]()&&(!this[o(1694)]||e[o(621)](this[o(1694)][o(1473)+"te"],this[o(458)])||e.MVdiq(this[o(1694)][o(1473)+"te"],this.CONNECTING))&&this["_handleO"+o(1588)](),this[o(1235)+"er"]&&window[o(1195)+o(1617)](o(1119),this[o(1726)+o(1588)]),this._isBrowser&&window[o(1195)+o(1617)](e[o(1043)],this["_handleO"+o(558)]));else return _0x1942e1&&(_0x36a95d=(0,_0x18a4e1[_0x5c281c(_0x56de5d)[0]])(_0x30d469=0)),_0x26028b}async[t(685)+"eUrl"](r){let o=t,{fpID:l,deviceID:f,bddID:p,ttwID:w,accessKey:E,aID:g,customParams:C={},enableAutoAck:L,enableQoS:N,QoSLevel:$,env:se}=this._options,re,ie,Me;this[o(1235)+"er"]||this._isMiniWX||this[o(1633)+"T"]?(re=location&&e[o(481)](e.GSMTv,location.protocol)?"wss://":e[o(581)],ie=r.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),Me=/^wss(.*:\/\/)/[o(1664)](r)?r:""+re+ie):(re="wss://",ie=r.replace(/(^http)((?:[s]*:\/\/))/,""),Me=/(^ws)((?:[s]*:\/\/))/[o(1664)](ie)?ie:""+re+ie);let pe=p?e[o(1679)]:w?o(603):e[o(611)],qt=p||w||f;if(!qt||!pe)throw new Error(e[o(1680)]);let _e=e[o(713)](e[o(788)],typeof C)?await C():C,Ea=se?e[o(673)](zp,se[o(1219)],se[o(1713)]):{},ni=Object[o(597)]({device_platform:e[o(1618)],version_code:e[o(1795)],access_key:E,fpid:l,aid:g,[pe]:qt,xsack:L?1:0,xaack:L?1:0,xsqos:N?1:0,qos_level:N?$:void 0,qos_sdk_version:2,...Ea},_e),_g=Object[o(648)](ni).reduce((va,Sa)=>ni[Sa]!==void 0?""+va+(va?"&":"?")+Sa+"="+ni[Sa]:va,"");return Me+o(1829)+_g}async[t(654)](){let r=t;if(!(this._connectLock||this[r(790)+"osed"])){this[r(654)+r(1811)]=!0;try{let o=this[r(933)+"tManager"]?.[r(1407)+r(644)+r(1465)+r(1366)+r(523)](),{timeoutInterval:l}=this[r(686)];if(o)if(e[r(942)](r(925),e[r(1030)])){let p=this[r(933)+r(953)]?.[r(1351)+r(743)+"nt"](),w=this[r(933)+r(953)]?.[r(1239)+r(1564)+"pointAnd"+r(1600)+r(1190)](),E=this[r(933)+"tManager"]?.[r(1351)+"ntEndpointTriesC"+r(1029)]();if(w){let g=r(1746)+p+(r(796)+", max retries re"+r(929)+r(1522)+r(501)+r(530))+w+(r(1163)+"y"),C=e[r(1705)](lt,e[r(1791)],{message:g,code:on[r(557)+r(1328)+"R"]});this._debug(g),this[r(670)+r(552)+r(880)](C),this[r(907)]=await this[r(685)+r(1370)](w),this._debug(r(1746)+w+" "+E+r(1270)),this[r(1212)+r(1069)+"rs"]()}else{let g="connect "+p+(r(796)+r(1116)+"tries reached");this[r(1365)](g),this[r(670)+r(552)+r(880)](lt(e[r(1791)],{message:g,code:on["MAX_RETR"+r(1328)+"R"]}));return}}else _0x3456ae=_0x49d6fd.concat(_0x5a2a1b),_0x47d8fb=_0x13e4c3.concat(_0x3de9d7[_0x4d7d3c]);else{let p=this[r(933)+r(953)]?.[r(1351)+r(743)+r(1150)+r(1538)](),w=this[r(933)+r(953)]?.[r(1351)+"ntEndpoi"+r(1467)+r(1029)]();this._url=await this[r(685)+r(1370)](e[r(1294)](p,"")),this[r(1365)](r(1746)+p+" "+w+r(1270)),this[r(1212)+r(1069)+"rs"]()}if(this._isInit)this._isInit=!1;else{let p=e[r(374)](xa,"reconnect",{message:e[r(1530)]});this["onStartR"+r(528)]&&this["onStartR"+r(528)](p)}let f=this[r(933)+r(953)]?.[r(1351)+r(743)+r(1467)+r(1029)]()||0;f>1&&await this[r(1796)](e[r(936)](f,1)),this[r(1365)](r(1501)+r(940)+this[r(907)]+(" protoco"+r(1595))+this[r(663)+"ls"]),this[r(1694)]=e[r(1705)](Mp,{url:this[r(907)],protocols:[this[r(663)+"ls"]],headers:this._options[r(1266)+r(761)+"s"][r(1007)+"tpHeader"]},this._options.ws),(this[r(1235)+"er"]||this[r(1277)+"r"])&&this._ws&&(this._ws[r(932)+"pe"]=this[r(1188)+r(1342)]),this[r(1060)+"steners"](),this[r(654)+r(1054)+"utId"]=e[r(1330)](setTimeout,this._onTimeout[r(1785)](this),l)}catch(o){throw this[r(654)+r(1811)]=!1,o}}}_clearTimer(){let r=t;e[r(1232)](e[r(1777)],e[r(1777)])?(e[r(1051)](clearTimeout,this["_connect"+r(1054)+r(474)]),this[r(654)+r(1054)+r(474)]=null):this[r(1290)](_0x3c2c58,_0x4f7343)}[t(487)+t(1744)](){let r=t;e[r(1099)](clearTimeout,this[r(505)+"gTimeoutId"]),e[r(419)](clearTimeout,this[r(682)+r(1511)+r(1144)]),this[r(505)+r(1166)+"Id"]=null,this[r(682)+r(1511)+"tId"]=null}[t(1365)](...r){let o=t;this._options.debug&&console.log[o(461)](console,[e[o(1137)],...r])}["_getInte"+t(353)+"e"](r){let o=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:p}=this[o(686)],w=e.VsUmi(l,Math.pow(p,e.PMgjQ(r,1)));return e[o(1022)](w,f)?f:w}[t(1200)](){let r=t;if(this[r(1694)]&&e[r(1210)](this._ws[r(1473)+"te"],this[r(731)+"NG"])){this["_clearPi"+r(1744)](),this[r(505)+r(1166)+"Id"]=setTimeout(this._ping[r(1785)](this),this[r(686)][r(982)+r(1258)]);return}if(!this._ws||e[r(1838)](this[r(1694)][r(1473)+"te"],this[r(458)]))return void this[r(1357)+r(528)]();this[r(1694)]&&this[r(1694)][r(1403)]("hi"),this["_reconne"+r(1511)+r(1144)]=setTimeout(this[r(1357)+r(528)+r(1504)].bind(this),this._options[r(399)+r(1749)+r(792)])}["_handleR"+t(528)+t(1504)](){let r=t;this[r(455)+"sCounter"]?.[r(1320)](),this[r(478)]("ping_onc"+r(1344)+"t",e[r(1590)]),this[r(455)+r(847)]?.[r(748)+r(450)+"nt"]()?this[r(1357)+r(528)]():this[r(1200)]()}[t(1740)+t(1127)](){let r=t;return this[r(1633)+"T"]||this._isMiniWX?this[r(983)+"igatorOn"+r(484)]:(this._isBrowser||this[r(1277)+"r"])&&this[r(686)]["listenNe"+r(633)+r(841)]?navigator[r(1413)]:!0}[t(1357)+t(528)](){let r=t;!this["_navigat"+r(1127)]()||this[r(790)+r(494)]||(this["_endpoin"+r(953)]?.[r(958)+r(894)+r(922)](),this["_pingLos"+r(847)]?.resetCounter(),this[r(1694)]?this[r(1343)+"ect"](1001,"going away, try "+r(619)+r(485)+r(1612),!0):this._connect())}[t(369)+t(1642)+t(935)](){let r=t;this[r(1633)+"T"]?tt[r(1517)+r(486)+"hange"](({isConnected:o})=>{let l=r;this[l(983)+"igatorOn"+l(484)]=o,o?this[l(1726)+"nLine"]():this[l(1726)+l(558)]()}):this[r(798)+"X"]&&wx[r(1517)+r(486)+r(408)](({isConnected:o})=>{let l=r;this[l(983)+l(460)+l(484)]=o,o?this["_handleO"+l(1588)]():this[l(1726)+"ffLine"]()})}[t(1796)](r){let o={AcxIr:function(l,f,p){return e[G(515)](l,f,p)}};return new Promise(l=>{let f=G;o.AcxIr(setTimeout,l,this["_getInte"+f(353)+"e"](r))})}[t(1343)+t(986)](r=1e3,o="",l=!1){let f=t;this[f(1694)]&&this[f(432)+f(421)+"t"](r,o,l)}[t(1213)+"ut"](){let r=t,o=this[r(933)+r(953)]?.["getCurre"+r(743)+"nt"]();this[r(1365)](r(1746)+o+r(796)),this["_disconn"+r(986)](1001,r(1346)+r(1833)+r(1117)+"g",!0)}[t(904)](r){let o=t,l=e[o(1089)](Gt,r);this[o(1694)]&&e.FmKUh(this._ws[o(1473)+"te"],this[o(458)])&&(this[o(1694)]&&this._ws[o(1403)](l),this._debug(e[o(1091)],r))}[t(1212)+t(1069)+"rs"](){let r=t;if(e.zbSEx===e[r(705)])this[r(1418)]?.close(),this[r(1418)]=void 0;else{let o=e.ZwVuG[r(1512)]("|"),l=0;for(;;){switch(o[l++]){case"0":if(!this._ws)return;continue;case"1":this[r(1694)]["removeEv"+r(1016)+r(1552)](e[r(1791)],this[r(746)]);continue;case"2":this[r(1694)][r(1363)+"entListe"+r(1552)](e[r(869)],this._onClose);continue;case"3":this._ws[r(1363)+r(1016)+r(1552)](e.SkLsR,this._onOpen);continue;case"4":this._ws[r(1363)+r(1016)+r(1552)]("message",this[r(647)+"ge"]);continue}break}}}[t(1060)+t(1028)](){let r=t;this[r(1694)]&&(this[r(1694)]["addEvent"+r(1617)](e[r(1574)],this._onOpen),this[r(1694)][r(1195)+r(1617)](e.nooKa,this[r(373)]),this[r(1694)][r(1195)+r(1617)](e[r(396)],this._onMessage),this._ws[r(1195)+r(1617)](e[r(1791)],this[r(746)]))}["_wsInsta"+t(1599)](r=1e3,o=""){let l=t;try{this[l(1694)]&&this._ws[l(1458)](r,o)}catch{}}["_destroy"+t(421)+"t"](r=1e3,o="",l=!1){let f=t,p={ZTKcj:function(w,E){return e.EbFFG(w,E)},zAAQm:function(w,E){return e.Zqnev(w,E)},ApGQm:function(w,E){return e[G(347)](w,E)},jbXMT:function(w,E){return e[G(1410)](w,E)},VDXyX:function(w,E){return e[G(930)](w,E)}};if(e.gwmcC===e.hkptd){let w=_0x6d9420.charCodeAt(_0x6ecc5f);w>=55296&&dFlMhG[f(668)](w,56319)&&dFlMhG.zAAQm(dFlMhG.ApGQm(_0x57958c,1),_0x1ec12a)&&(w=dFlMhG.jbXMT(dFlMhG.VDXyX(w,10)+_0x52c634[f(554)+"At"](++_0x1b9552),56613888)),_0xc0be71+=w<128?1:dFlMhG[f(971)](w,2048)?2:dFlMhG[f(971)](w,65536)?3:4}else{if(this[f(487)+f(1744)](),this[f(690)+"mer"](),this["_removeW"+f(1069)+"rs"](),this[f(638)+f(1599)](1e3,o),this[f(654)+"Lock"]=!1,l&&this[f(1740)+f(1127)]()&&!this["_readyCl"+f(494)]){if(this["_endpoin"+f(953)]?.["checkRea"+f(1568)+"es"]()){let E=this["_endpoin"+f(953)]?.[f(1351)+f(743)+"nt"]();this[f(670)+f(883)+"ent"](wt(f(1458),{code:1006,reason:f(1746)+E+(f(796)+f(1116)+"tries re"+f(420)),wasClean:!0}))}else{let E=this[f(686)][f(619)+f(1321)+f(1496)](r,o);this[f(670)+f(883)+f(880)](e[f(1558)](wt,e[f(869)],{code:r,reason:o,wasClean:!0,willReconnect:E})),E&&this[f(654)]()}return}this[f(1740)+f(1127)]()||this["_readyCl"+f(494)]?this["_dispatchCloseEv"+f(880)](wt(f(1458),{code:r,reason:e[f(830)]})):this[f(670)+f(883)+f(880)](e.SVgfB(wt,e.nooKa,{code:1006,reason:e[f(562)]})),this[f(1694)]=null,this["_endpoin"+f(953)]?.[f(958)+f(894)+f(922)](),this[f(455)+f(847)]?.[f(549)+f(491)]()}}[t(670)+"hOpenEvent"](r){let o=t;this[o(478)](e[o(1574)],r),this[o(722)]&&this[o(722)](r)}[t(670)+t(1627)+t(427)](r){let o=t;this.emit(e[o(396)],r),this[o(1139)+"e"]&&this[o(1139)+"e"](r)}[t(670)+t(1565)+t(352)](r){let o=t;this[o(478)](e.fFwVb,r),this[o(1168)+"eAck"]&&this[o(1168)+o(1554)](r)}[t(670)+t(552)+t(880)](r){let o=t;this[o(478)](e[o(1791)],r),this.onerror&&this.onerror(r)}[t(670)+"hCloseEvent"](r){let o=t;this[o(478)](e[o(869)],r),this[o(889)]&&this[o(889)](r)}get[t(932)+"pe"](){let r=t;return this[r(1694)]?this[r(1694)][r(932)+"pe"]:this[r(1188)+"ype"]}set[t(932)+"pe"](r){let o=t;this["_binaryT"+o(1342)]=r,this[o(1694)]&&(this[o(1694)].binaryType=r)}get[t(985)+"nt"](){let r=t;return this[r(933)+r(953)]?.[r(1351)+r(743)+r(1467)+r(1029)]()||0}get["buffered"+t(1036)](){let r=t;return this._messageQueue.reduce((l,f)=>(l+=f&&f[G(1721)+"th"]||0,l),0)+(this[r(1694)]?this[r(1694)][r(736)+r(1036)]:0)}get[t(1308)+"ns"](){let r=t;return this[r(1694)]?this[r(1694)][r(1308)+"ns"]:""}get protocol(){let r=t;return this[r(1694)]?this[r(1694)][r(1227)]:""}get[t(1473)+"te"](){let r=t;return this._ws?this._ws.readyState:this[r(686)]["automati"+r(1386)]?this[r(731)+"NG"]:this[r(1671)]}get[t(1570)](){let r=t;return this[r(1694)]?this[r(1694)][r(1570)]:this._url}close(r=1e3,o){let l=t,f={ehtYw:function(p,w){return e.vxeLE(p,w)},uODSC:function(p,w){return p&w},KEJnG:function(p,w){return e[G(1110)](p,w)},dQazB:function(p,w){return p>=w},NQzRw:function(p,w){return e[G(1077)](p,w)},Grhjz:function(p,w){return p(w)}};if(l(698)===e[l(762)]){let p=e[l(1800)][l(1512)]("|"),w=0;for(;;){switch(p[w++]){case"0":this[l(646)+l(1756)+l(1617)]();continue;case"1":if(!this[l(1694)])return void this[l(1365)](e[l(599)]);continue;case"2":this[l(432)+l(421)+"t"](r,o);continue;case"3":if(e[l(1487)](this._ws[l(1473)+"te"],this.CLOSED)||this[l(1694)][l(1473)+"te"]===this[l(1152)])return void this[l(1365)](e[l(575)]);continue;case"4":this["_readyCl"+l(494)]=!0;continue;case"5":this._clearPingTimer();continue;case"6":this[l(1045)+l(544)]?.[l(642)]();continue;case"7":this["_clearTi"+l(1309)]();continue}break}}else _0xb42d3f=CfFbbb[l(1133)](CfFbbb[l(1133)]((15&_0x511a60)<<12,CfFbbb.uODSC(63,_0x48d3a8)<<6),CfFbbb.uODSC(63,_0x5cfad2)),CfFbbb.KEJnG(_0x924095,2048)||CfFbbb[l(1298)](_0x166bd2,55296)&&CfFbbb[l(1319)](_0x45fe93,57343)?_0x4995b0+=_0x312afe:(_0x5e74ff+=CfFbbb[l(1310)](_0x2f3119,_0x81bd46),_0x178158+=2)}async[t(1403)](r,o){let l=t;if(e[l(725)](null,r))throw new Error(e[l(1620)]);e[l(378)](e[l(1782)],typeof r)&&(r=JSON[l(588)+"y"](r)),e[l(749)]!=typeof r&&!e[l(906)](r,ArrayBuffer)&&!(r[l(966)]&&e[l(592)](r[l(966)],ArrayBuffer))&&(r=JSON[l(588)+"y"](r));let f=await e.jifTL(gl,r),p=e[l(818)](Fp,r),{method:w=0,service:E=this[l(686)][l(850)],logID:g=this[l(686)][l(659)+l(1154)](),headers:C=this._options[l(856)],payloadEncoding:L=this._options[l(1728)+l(1238)],payloadType:N=this[l(686)][l(735)+"ype"],logIDNew:$=this[l(686)].logIDNewConfig[l(931)+l(1691)+l(868)+"ew"]?e[l(800)](i,this[l(686)][l(1161)+"Config"][l(970)]):""}=e[l(773)](o,{});if(!E)throw new Error(e[l(1542)]);let se={SeqID:xe[l(861)+"er"](this[l(1411)]++),LogID:xe.fromNumber(g),service:E,method:w,headers:C,payloadEncoding:e[l(592)](L,Object)?L.encoding?L.encoding:"":L,payloadType:e[l(1131)](N,Object)?N[l(1059)]?N[l(1059)]:p:N||p,payload:f,LogIDNew:$},re=Gt(se);return this[l(1694)]&&e[l(1492)](this[l(1694)][l(1473)+"te"],this[l(458)])?(this[l(1694)]&&this[l(1694)][l(1403)](re),this._debug("sent",se)):e.DivVG(this[l(426)+l(371)][l(559)],this[l(686)][l(828)+l(1775)+l(448)])?(this[l(426)+l(371)].push(re),this[l(1365)](e[l(1049)],se)):(this[l(426)+l(371)][l(393)](),this[l(426)+l(371)][l(946)](re)),{seqID:this[l(1411)],logID:g,logIDNew:$}}async reconnect(r){let o=t,{url:l}=e[o(627)](r,{}),f=Array[o(1288)](l)?l:e[o(1659)](e.HwKCA,typeof l)?[l]:[];r&&Object.assign(this._options,r),f&&f[o(559)]?this[o(933)+o(953)]=new fl(f,this._options[o(1070)+"es"]):this[o(933)+o(953)]?.[o(958)+o(894)+o(922)](),this[o(455)+"sCounter"]?.[o(549)+o(491)](this[o(686)][o(1571)+"Count"]),this[o(790)+o(494)]=!1,this[o(1694)]&&this._ws[o(1473)+"te"]!==this.CLOSED?this[o(1343)+"ect"](1e3,e[o(1256)],!0):(this[o(1412)]=!0,this._connect())}async connect(){let r=t;!this[r(654)+r(1811)]&&(this[r(933)+r(953)]?.[r(958)+"pointCon"+r(922)](),this[r(455)+r(847)]?.resetCounter(),this[r(790)+"osed"]=!1,this._isInit=!0,this[r(654)]())}[t(1195)+t(1617)](r,o){this.on(r,o)}[t(1260)+t(427)](r){let o=t,{type:l}=r;this[o(478)](l,r)}["removeEventListe"+t(1552)](r,o){this[t(1290)](r,o)}[t(634)](){let r=t,o={rfpKm:function(l,f){return e.RSiXB(l,f)},ilMQR:function(l,f){return e.yYyPa(l,f)},fWEzi:function(l,f){return e[G(752)](l,f)},uERRC:function(l,f){return e.pPgoZ(l,f)},VIGCd:r(1748),UcQmU:function(l,f){return e[r(1742)](l,f)},ieSFP:e[r(1292)],tdGEq:e[r(1832)],ASJGl:r(1780)+r(1344)+"t",uKOeA:e[r(1590)]};return new Promise((l,f)=>{let p=r;this[p(487)+p(1744)](),this["_pingPon"+p(1166)+"Id"]=e.YhMpz(setTimeout,this[p(1200)][p(1785)](this),this[p(686)][p(982)+p(1258)]);let w=()=>{let g=p,C={VeJim:function(L,N){return o[G(1339)](L,N)},TjpXh:function(L,N){return L|N},SamPJ:function(L,N){return o.ilMQR(L,N)},EKxEO:function(L,N){return L<N},SdXxT:function(L,N){return o[G(624)](L,N)},sQxwS:function(L,N){return L>>N},zSCur:function(L,N){return L&N},EoOvi:function(L,N){return o[G(553)](L,N)}};o[g(1636)](o[g(1008)],o[g(1008)])?(o[g(370)](l,o[g(640)]),this[g(1290)](o[g(881)],w),this[g(1290)](o[g(744)],E)):(oCFSPw[g(534)](_0x56c388,2048)?_0x447c54[_0x186426++]=oCFSPw[g(769)](oCFSPw[g(1244)](_0x3bd6e1>>6,31),192):(oCFSPw[g(358)](_0x28cadc,65536)?_0x5c3a34[_0xe049a7++]=oCFSPw[g(1006)](oCFSPw[g(1244)](oCFSPw[g(1631)](_0x44cca9,12),15),224):(_0x5a52e8[_0x4c8bbe++]=oCFSPw[g(1006)](oCFSPw[g(1244)](oCFSPw.sQxwS(_0x1f1625,18),7),240),_0x34e9d6[_0x23ab28++]=oCFSPw.SamPJ(_0x5b928>>12,63)|128),_0x284676[_0x234d77++]=oCFSPw.SdXxT(oCFSPw.zSCur(_0x1bf7cb>>6,63),128)),_0x527adc[_0xda113b++]=oCFSPw[g(1006)](oCFSPw[g(623)](63,_0x2939ed),128))},E=()=>{let g=p;f(o[g(1129)]),this.off(o[g(881)],w),this[g(1290)](o.ASJGl,E)};this.on(e[p(1832)],w),this.on(e.uaajb,E),this[p(1200)]()})}}})(),oe[M(1019)+M(1214)]=Oe[M(1019)+M(1214)],oe[M(1121)+M(1638)]=Oe[M(1121)+M(1638)],oe.ErrorCode=Oe[M(1180)+"e"],oe[M(427)]=Oe.Event,oe[M(649)]=Oe[M(649)],oe[M(1602)+M(593)+M(1153)]=Oe[M(1602)+M(593)+M(1153)],oe[M(593)+"vent"]=Oe[M(593)+"vent"],oe.OpenEvent=Oe[M(822)+"t"],oe[M(662)+"tEvent"]=Oe[M(662)+M(436)],oe[M(548)+M(1214)]=Oe[M(548)+M(1214)],oe[M(1388)+M(1638)]=Oe.createErrorEvent,oe[M(1199)+M(361)+"nt"]=Oe[M(1199)+M(361)+"nt"],oe[M(727)+M(1252)]=Oe[M(727)+"enEvent"],oe[M(1444)+M(625)+M(1153)]=Oe["createRe"+M(625)+"vent"],oe[M(760)+M(1692)]=Oe[M(760)+M(1692)],oe[M(1362)+M(524)]=Oe[M(1362)+M(524)];for(Wo in Oe)[M(1019)+M(1214),M(1121)+"rorEvent","ErrorCode","Event",M(649),"Frontier"+M(593)+M(1153),M(593)+M(1153),"OpenEvent",M(662)+M(436),"createCl"+M(1214),M(1388)+M(1638),M(1199)+M(361)+"nt",M(727)+"enEvent","createReconnectE"+M(1153),M(760)+M(1692),M(1362)+M(524)][M(1173)](Wo)===-1&&(oe[Wo]=Oe[Wo]);var Wo;Object["definePr"+M(950)](oe,"__esModule",{value:!0})});import{existsSync as ES,openSync as vS}from"node:fs";import{mkdir as SS}from"node:fs/promises";import{dirname as IS}from"node:path";import{fileURLToPath as AS}from"node:url";function kS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Hd(t=X()){return ES(t.libEntry)?t.libEntry:AS(new URL("../index.ts",import.meta.url))}async function Kx(t={}){let e=t.paths??X(),n=t.entryOverride??Hd(e),i=kS(e,process.env.COZE_BRIDGE_LOG_MODE);await SS(IS(i),{recursive:!0});let s=vS(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=st(process.execPath,d,{detached:!0,stdio:["ignore",s,s],env:{...process.env,[os]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return TS.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var TS,os,na=rt(()=>{"use strict";Zt();ee();Be();TS=q("spawn-daemon"),os="COZE_BRIDGE_DAEMON"});import{spawn as S1}from"node:child_process";import{mkdir as I1,unlink as A1,writeFile as T1}from"node:fs/promises";import{dirname as k1,join as C1}from"node:path";function Yr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function D1(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${Yr(n)}</key>
20
+ `+r)}function nr(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let l=new Error(o);Error.captureStackTrace(l,nr),t.emit("wsClientError",l,r,e)}else rs(r,i,o,c)}});var Bx=ce(Fe=>{"use strict";var N=q;function q(t,e){t=t-314;let r=Zo(),i=r[t];if(q.LYvFVQ===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",y="";for(let S=0,_,v,I=0;v=f.charAt(I++);~v&&(_=S%4?_*64+v:v,S++%4)?g+=String.fromCharCode(255&_>>(-2*S&6)):0)v=x.indexOf(v);for(let S=0,_=g.length;S<_;S++)y+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(y)};q.qndrmt=o,q.bOqRaD={},q.LYvFVQ=!0}let c=r[0],l=t+c,u=q.bOqRaD[l];return u?i=u:(i=q.qndrmt(i),q.bOqRaD[l]=i),i}(function(t,e){let r=q,i=t();for(;;)try{if(-parseInt(r(1883))/1*(-parseInt(r(679))/2)+-parseInt(r(951))/3+-parseInt(r(777))/4+parseInt(r(380))/5+parseInt(r(1081))/6+-parseInt(r(1269))/7+-parseInt(r(761))/8===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Zo,987965);var sS=Object[N(600)+N(877)],oS=Object[N(1151)+"opertyNames"],Px=(t,e)=>function(){return t&&(e=(0,t[{gxzVq:function(c,l){return c(l)}}[N(1377)](oS,t)[0]])(t=0)),e},aS=(t,e)=>{let r=N,i={fOJTK:function(c,l,u,f){return c(l,u,f)}};for(var o in e)i[r(489)](sS,t,o,{get:e[o],enumerable:!0})};function cS(){return kx||(kx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function dS(){let t=N;return Tx||(Tx=[IDBCursor.prototype.advance,IDBCursor[t(337)+"e"][t(653)],IDBCursor[t(337)+"e"][t(653)+t(1241)+"ey"]])}function lS(t){let e=N,r={GMIyO:e(1483),dSPno:"error",CCiCa:function(o,c,l){return o(c,l)},jTQAz:function(o,c,l){return o(c,l)},XGsEP:e(1769),pGdrK:function(o,c){return o===c},RGjHN:e(705),HaLCx:function(o,c){return o(c)},pTjyW:function(o){return o()},ykhXo:function(o,c){return o===c},TpIak:e(1866),UjMtE:e(1576),EpZkC:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let l=e,u={miTDq:function(f,x){return r[q(886)](f,x)},ufTvD:function(f,x){return f(x)},JGJbC:function(f){return f()}};if(r[l(1037)](r[l(797)],r.UjMtE))return 0;{let f=()=>{let y=l;t[y(1193)+y(864)+y(1499)](r[y(1760)],x),t[y(1193)+y(864)+y(1499)](r[y(634)],g)},x=()=>{let y=l;u[y(1050)](o,u[y(1457)](zt,t.result)),u[y(1300)](f)},g=()=>{let y=l,S={MKYpr:function(_,v,I){return r[q(1112)](_,v,I)},ijIde:y(1069),HEhNn:function(_,v,I){return r[y(808)](_,v,I)},bnzjg:r[y(322)]};r.pGdrK(y(1534),r[y(1454)])?_0x3be0b4[y(474)]()[y(862)](()=>{let _=y,v=S[_(1087)](_0x3df022,S.ijIde,{message:this[_(594)+_(872)+_(1815)](_0x363b0f)});this[_(985)](_(1069),v);let I=S[_(944)](_0x42b005,S[_(778)],{reason:this["_formatE"+_(872)+_(1815)](_0x4b5826)});this[_(985)](_(1769),I)}):(r.HaLCx(c,t.error),r[y(1352)](f))};t[l(1509)+l(1559)](r.GMIyO,x),t[l(1509)+l(1559)](r[l(634)],g)}});return i.then(o=>{let c=e;r[c(1674)](o,IDBCursor)&&Hd[c(1680)](o,t)}).catch(()=>{}),Xo[e(1680)](i,t),i}function uS(t){let e=N,r={CdzKo:e(401),kKyOQ:e(1069),OcRUJ:e(1668),BdUnt:function(o,c){return o(c)},eoWcp:"AbortError",wLGkT:function(o){return o()}};if(Yo[e(451)](t))return;let i=new Promise((o,c)=>{let l=e,u={OamZM:r[l(1717)],UEJmT:r[l(408)],wjWRR:r[l(1353)],oedtW:function(y,S){return r[l(758)](y,S)},wEbfx:r.eoWcp,XJfEa:function(y){return r[l(900)](y)}},f=()=>{let y=l;t["removeEventListe"+y(1499)](u[y(1328)],x),t["removeEv"+y(864)+y(1499)](u.UEJmT,g),t[y(1193)+y(864)+y(1499)](u[y(1880)],g)},x=()=>{o(),f()},g=()=>{let y=l;u[y(1488)](c,t[y(1069)]||new DOMException(u[y(1237)],u[y(1237)])),u[y(738)](f)};t[l(1509)+l(1559)](r[l(1717)],x),t[l(1509)+l(1559)](r[l(408)],g),t[l(1509)+l(1559)](r[l(1353)],g)});Yo.set(t,i)}function Zo(){let t=["qKnPuKy","wNH5u0G","zxH0ugf5Bg8","yMjtzMe","r2DuseW","y2HHCKnVzgu","B21mCLK","C3vIyxjYyxK","zfvkz2K","yvjesfO","CMfmwuS","ufvwreK","qu1HrKG","qNjvrMi","igfYCMf5yNu","DgfNCvC","zcbLCNjVCI4","v0PTCw4","u1f1vNG","BKfvvuO","x2rPC3bHDgm","BNrbBMrvCgq","CMvHC29U","v2LUzg93","wuTUCMS","Dg9cExrLC0W","twLZC2LUzYa","CMr5su4","Cgu6ia","x2nSzwfYvgK","CMvXDwLYzwq","AxnrB1nnzxm","ysbTDxn0igi","D0TquuC","x2LZtM9Kzq","sKHzCgy","swLXqLO","wvbxrKy","mdaWmdaWmda","vhvUvgG","vgLTzw91Da","sLvKAg8","uwzzrKq","zw5JB2rLrNi","BuvyD2y","qxbeswO","vePrrvm","y3vYC29Y","rNPYre4","sxvVsxa","C3jJ","ChvSqMO","yNL0zu9MzNm","sxLtA1m","vMDtt3O","D3PoDLG","reXlzxe","sfbwBha","zcWG","sw9fzMO","wwzvzxC","twLktLe","x29UugfNzu4","t2vOs3i","zwfKzwu","r2XwEu0","AvbYzhe","uw5uA3m","u0rSEvm","De1HBMfNzxi","zeL1Exe","DKTtBuy","r1HJwgG","u3PNzKO","BxvHAMS","ufrIAMC","wvLTt2u","Dw5ZAwDUzwq","sKPuwK4","wuzut3C","qNHfCLm","zNjHBwvuExa","Bg9IywXty28","ALfTu08","ywjVCNq","ALv6Ae8","CMvZzxrfBMq","DgXmz20","qNLYwxO","zeDyuha","rxbAA0m","AxnszwfKEq","DgvZDa","uxvqzvu","zuTvrgK","C0PhwuG","C2v0","yLLRDMW","ChbL","BgLUzq","ihrYEsbYzwm","q0Xpu0ve","D3vPA1a","CMvKDwnL","Egfpww0","C2DPza","v1fnB2W","ugzty2W","BeHHBMrSzxi","vfH5tee","zMHcCxy","ALjtwvK","ChrVCG","B3bLBKrc","ALzitxi","CKXXAve","Cgf5Bg9Hzfq","B25VCgvU","Afrvugi","v3PZvvi","B25ozxr3B3i","z1vXtMm","DfLNq2S","ufrvyvO","x3bYzwzPEa","A2v5CW","A0jVvgu","s3niqMG","x2nYzwf0zvm","wxjWvhq","C3rHCNq","Dg9tDhjPBMC","vufQrui","q2r6s28","zgrjrcWGzgu","ywzgvw4","x2HHBMrSzvi","q0vUu20","Buv6zNC","u1LzB3q","ve1MAwu","BxnN","uxbjALe","v0LQzuu","wNP5CKC","svLYA2S","D09QwM0","B3L6EMe","CYbWyxjHBxm","zuvuzxq","qKLoDei","EMfQDLi","B3jRig9MzMW","AgfZt3DUuhi","EMDfALO","D1zfz1K","Cg1Jr3a","rujrtxG","AvzIt2G","DfjRAwG","yLz1BgK","DezLsgW","yw1LoIa","CMfUzg9T","Dgv4Dc9WBge","Cxzwv0q","qxbJqxG","z2v2y3O","Dgznqwm","uw5wtfa","B3bLBIa","D3m6lY8","DLrlvvG","BejVBfy","CffsB2K","Ae1Jshe","r01jEu8","DwT3zxK","ANDZsge","CgLUz09Uy2u","y3vYCMvUDeu","Dwjlzxa","B3fVy3K","x2XPC3rLBMu","DuP3ufK","y2XVC2u","yMfSrxzLBNq","Aw5L","yNL0zxm","BgDZEMm","sMrrz0m","mhW2FdeWFdK","AgvHzgvYCW","BvnTBxm","C2veC2u","z2v0qwXSs2u","y3j0Cuy","A1fowhe","vLPQEvG","zMLSDgvY","s01iv3G","y29UBMvJDgK","vNrLuha","zxHWB3j0CW","vLPRy0e","sgvsv2C","C2XPy2u","vM5TCLO","sKLKuuy","vgHcENe","sNH1wKu","rfzuA3q","zufQB1O","B2fuq3G","u1bdrhO","u1rIA2e","ruvyEgi","qu9vzKC","tNzlEMS","sxjJsNG","x3bPBMDmB3m","z2zXwg0","EfvZzuvUDG","rMrwreK","tgjTzuG","tufyx1jfvfi","A2v0ignVBNm","D2rArMm","uuvuDvC","s2nouei","CfjgAwS","ywDL","C3bSAwnL","B3nLrxzLBNq","uujVCM8","CwPRywK","wujoB24","rKLyAwq","AMnbs28","x2n1CNnVCKy","sKfyANa","uKPJrKu","ve5zqNO","vhbLtKi","yMfSu2nVCgu","BMDuAw1LCG","ENbPEhG","r1PVrwC","tKfusvzfx0u","rhzOvK4","yLfyB2K","s1r1tg4","wufQv2G","v3LqwNu","DxnLCKLW","zgj3svG","BMzqtfO","B2LUDfjLywm","rLDWsMW","ru9qyvy","uwzWzKO","uefeC1u","zw1LBNq","sNvWEg8","DxbKyxrLq3u","z2v0u3rVCMe","zfrXyM8","AxnAzxjV","qLrVExO","rfHOChG","BLbhyxm","yufvCfO","x2rItMfTzq","C29Tzq","zM9YrwfJAa","EffNAhm","Au9UDKm","ywDLu2HVDW","ywnRDxbfBMq","vfH4zxi","DuveAMm","B3jRzxjhBg8","AKHjD0m","zw5JB2rPBMC","AwTlC0u","CMzNDK8","B25TzxnZywC","sePeBgS","yM9L","C0XUvvO","C1zkve8","zNDZxZeUmc4","u3D0tMS","q0jYuwK","weLhENy","qMHyr3C","D2PxuLi","EvzewLy","DhvKwwu","mZq0mtrVtLveCuS","BMCGzMfPBgu","nhWYFdb8mxW","tg5bu1i","ign1CNnVCIa","yM9KEq","DgfYz2v0","mNW3FdeWFdu","u25lEwS","q291BNq","B2zMC2v0","Aw5JBhvKzxm","wvzSsuW","ExvcvLa","Du1cENi","id4G","weDZrva","sLvkC0e","Cgjry0e","DvnOA1K","Cgf5Bg9Hza","DhLWzq","DgLTzw91Da","DhjPBq","wLfcCgK","tw5wDfm","y2Hcre8","z2v0q3vYC28","sunewuG","EhrhDxy","t0DtBNy","ChjVDg90Exa","BNDfq3O","z09dA0q","wKLfyNy","yvnVBxG","DxrMofDYAxq","B2LXEey","uKP2AfC","AvnQv1a","z2v0q3vYCMu","sNnhBwu","B25fCNjVCG","rgvKAwnHDgu","wK51z3y","EhvSthO","sxjgt2K","B1PntuW","B25SAw5L","DLHAwLu","tfbqB0u","vuHVAfa","rgrzAeu","CgfNzxnOB3C","thPyshO","zMzMzG","vKf3rK0","EunVy3i","zM9Yy2u","quPbA3G","BgvrDNi","C0Xf","yKjNENi","BgvY","zwnVBM5Ly3q","Dxnly0W","DMvUDa","DxDRAvy","C0zArwu","r25Ovge","Dw5RBM93BIa","zgzUseS","wfjADem","u0rdAxa","otG2mJi4mhrdzhbuvW","C2v0q3vYC28","AxmGDw5Kzwy","CgfYC2u","sujiCe0","CKPmBvG","rKDAr0S","DLLqEvy","uhzIq2i","uuLLrLC","BwLUAvbYB2C","vvDiv3u","ueDzD0S","tMT1D0O","x2TLEvbHDgG","BKXPBMu","vMrrtue","uhvXz2u","tvzrEKi","CMvJB25Uzwm","Dgfzswq","y29TCgXLDgu","vxLWBhK","EKrxC24","tNbXC3i","wxLRwLu","AgfUz2u","DunwtLu","A0T5t1e","t1njswC","AhfYzNq","yNvMzMvYzwq","BwvZC2fNzv8","uLritvi","CMvQzwn0","AwrI","CfDnthK","u2HHCMvKv28","vw5Oyw5KBgu","AhLpyMK","u3LIt0W","C3nHz2vfDMu","BwLUzW","x2rLC3rYB3K","teLywuO","A1n0yxr1C0m","rwHQCfO","Bg9NsurozxC","t1zTqMm","zKLkuLa","B25LCNjVCG","v0HfzKm","yw5Nzq","ugL0zha","D0LMAu0","u0LKwMm","B1ftqLC","Dfv2ueO","Aw9UvgLTzw8","B25tDgfYDfi","u1fzzve","qLvXs2W","y3jLyxrLt2i","Aw5Lza","y2HnyxHdB3u","BMfTzq","FdL8mhWZFdq","rwv6whC","wNnVu3O","qu1YueG","yw5Hz2vY","AgfZ","Dxvly28","CMvHzhDYAxq","tfzRvgi","x29Uq2XVC2u","Ae1LC3nHz2u","zfDVCMTLCKC","wKXRqNC","AuLftNi","zKLZthO","DfDKq0m","C0nWz0C","BgLZDgvUtMu","rufJqKi","ChPIte4","y3vYC29Yx24","AuXeyKy","rLfOANC","CMPzuem","yMjyvM8","Aw5PDcbrB1m","Dhzmqui","x3vYBa","CMvZB2X2zq","A3bIB3m","zeLYy3q","CgXLyxnLiha","r3rkDNa","AwHntMq","zxfKD28","yMLUCw0","x2HHBMrSzu8","B25XtwS","EvzJsxC","ywXPzcb1CMW","t1fvrfe","q25bAgm","s2vQu0K","zK9kveS","ue9JANa","uhvrree","x0vysvnu","DgfIyxnL","sfnusfm","vvflzwK","x3bPBMDqB24","x3DHAxq","uxvLDwu","BwLetgy","veLwD20","qwHlB2u","v2Xhwfy","wMzgt1i","ywTAwLi","Fdr8mNWZFdu","Dhj1y3rVCIa","sgLQsum","yxLYrfu","AfjKt0i","qMvUqwO","x2HHBMrSzva","tvDnswO","B3bUrgm","CM9YrxzLBNq","DLn5z2e","ywnRx2LK","tfzwr2W","A1v0u1O","Ec1TC2CTy3u","uuTiDNO","EvjyzeC","zgvS","A1HMtuC","rw9Ot1a","Ec1TC2CTCw8","y2LryNe","vMLvDwe","CMvJzwL2zwq","Cg9W","zxH0zw5ZAw8","yw1Lu3bHy2u","Cgf5Bg9Hzeu","BMCGB3iGyw4","wKDbrxa","uLfyCgu","B2zMBgLUzq","rNbYC3O","C3rVCMu","vwvsDxG","uwHptue","C211yMy","CNzHBfzHBhu","D3jPDgvvAw4","EwnrywG","tfDeAfi","BuT2Dxe","yMLUza","twHiDg8","BuLuDKm","D0HKC3y","ALDZA0W","Dgv4DfbHEwW","rKLtDvy","CgHRzNC","A3PewvK","zvvqvgS","C3bSAxq","DxbhrwC","x3fVC0rc","DKDPs04","BMXkv1e","wwjqCLO","u3HwuwS","mNWWFdr8m3W","qNHZzMC","yNvMzMvY","zeTdsva","BMDLza","AvP3Bwy","zxrxB3jRq2G","qLveDhy","Bujpte0","zhzXwha","ENnUC0G","C2vUzf9Hy2S","C2vYDMLJzs0","Aw5KzxG","DMvY","vM1yseC","uhnUvwK","vvbrwey","B3zAExe","x2jPBMfYEvq","vu1OvxG","CMDUEfe","su5tvefova","B3nLza","EMjsAu4","l3DZl3yY","zwDhCu0","ELLqwgW","zw5HyMXLuw8","q3vZDg9Tq2W","x2zVCM1HDeu","uvbAugu","C2vUza","y0DXsKS","Dxrjza","DKvKC2i","zgvMAw5Luhi","z2u6ia","qvvNsMm","CeT2rKm","r1rcvKS","ywnRtxnNswq","sNzszeq","A0T5u2C","wurNA24","rNfnsxG","u3Lyyum","zw50zwqGDhK","qxjvy2u","qKrdrfm","zgrdEeK","t21wugy","CvbJCva","zxjYtxnN","zKftBey","u1P5tvG","C0nVDw50zxi","t1DUufG","BxjpuKe","AwDHDg9Yt24","yxbWBgLJyxq","y0zADLm","zxjFywnRx20","zMvY","z29PBMCGyxC","x1fVu01HBMe","rfzVBue","y09Wzw4","quXm","wMzfCge","zfnqBM8","yuHLCwe","DxriteC","CgLsC2m","B25mAw5L","r1jUBeG","uurhwfq","wK5gt0W","C1vvvwG","EhrrDwC","B2nRzxq","AvnYqK0","BeTdq1m","Ehf5y2m","BKTtCwm","CM92AwrLige","ywnOzwq","B3vUDa","A3rysNC","y29UDgLUDwu","BMrWB2LUDca","y29UBMvJDa","u0DVqNa","DhjPzxm","DgLUzYbZzxi","AxDAvMO","zNLgCue","Dw5KzwzPBMu","Aw5KzxHpzG","uwveCwe","vgfN","z2v0qwXS","tKDFrvjst1i","uMvHzcbWyxm","zxjHDg9Y","EvjLy29UBMu","x3nLCuLK","qxjVCNe","zM9pEM0","y2nSuuq","svrHv24","A2nqBwO","Aw1LCYbPBIa","CNLmyNm","tLPKzKK","ndbsz3vIEei","tM9Tvu0","vNnsAg8","zhDSz2i","x2LUAxrqCM8","svf4sKm","uKHJB3u","BgfPD3q","CNfMAKe","u2Pbq0W","Eu5YuLy","vvDsBMS","y1bLzwG","qwXpvgi","t2HOrNC","ELzgCfe","EsbJBg9Zzwq","x3nVy2TLDa","zNvUy3rPB24","r1jcCLK","B25dBg9Zzq","x2LUDgvYDMe","yujQvM8","v0nhqMG","yuvPC1y","rKLmrv9ot1q","rKfly3q","zxbSD2m","x2DLDeLUDgu","Cfzzwum","DMLJzuLeig8","zNrduLm","C29YDa","ALbyywe","CMvHzhLtDge","ELDKBhq","svHkDfq","qxDjrw4","lcbxzwjtB2m","BMrLEa","y29UBMvJDfm","zxq9DxrMltG","qLLzuM0","ALfTEhO","r3rHCeW","B2zM","BwDUu1m","DKjMqNq","DhDVCMTdAge","m3W1Fdr8mNW","rMzNvwC","ENn1uei","y3jLyxrLrxi","y3vYDMfSDwu","y2XVC2uSihC","Bgrdv3q","Bg93","BwvZC2fNzq","ihzHBgLKihm","wePMrwe","CMfTugfYyw0","DKXIEfG","wxLiwgq","x3bYB3rVy28","x2DLBMvYyxq","x2nVBM5Ly3q","EwzdzNe","wwPwA04","Cg9PBNrdB24","thnAA1e","s1DXrem","s29LrMy","tMDHEKC","zufJAW","ALLgq1i","te94CeW","q29Kzq","D05uBvi","AxnrB1nby2S","qMrvBNq","zNjVBunOyxi","EePIBwi","odeXndCXmKjutwTJsG","CNnVCL9Uyw0","BwvKAwf0zwW","BgLTAxq","Dgv4Dc9Qyxy","CfzQsKK","reTxBMO","DwPWCNC","Efrks3u","zNrYr2q","u093yLi","vMXfAue","rNzozNu","vfbRu2W","s1rQuhK","s3PLv3i","mJy0ntK1nMnrzK5dCG","yM56AMC","vejUug8","x3bPBMC","x2fKzfDZtgK","wuzqt28","Aw9U","tKfTwK4","sefvveu","DxbNCMfKzw4","sfbnquu","DNLiBMm","y3vYCMvUDeK","lcbOB3n0BMe","vg9OA2u","zgHqzgq","rhPUs2G","C2PpAfa","wMr6uLK","yxrLq291BNq","vhbjywS","EwHjr04","tw1fCva","y2vZC0HHBMq","B3HRzMy","Dhztyvi","vg5wr3q","x3jLywr5q2W","C2jtruG","zxreu3e","vxjyvwK","ALrrqxO","ywDLrxzLBNq","tLbAvLa","qM1jDLO","Dg9oDw1Izxi","yMXVy2TLza","CwjjvK0","zgf0yq","sw5tzeS","BenHDfO","y1LPvLK","ywXSzwqGBxu","EeHeCeG","zwn0","zLDbCgG","DMfSDwu","DufNBwy","AfzdA3y","tfvnu3y","CMvWBgfJzq","Cvr6A1u","rLDt","s1HSAgm","BM5Ly3q","B3bLBG","vw5PBxbSzw0","zgvSzxrLrge","qvH6wxO","Cg9PBNrbBMq","DeLK","DKHJreK","vxbKyxrLq28","BNDcAum","x2vUzhbVAw4","x2LZv29YA2u","yufMBeu","rNziruq","rKPZz3e","x3DZsw5ZDge","AMzfDMq","zvvYBa","DffSt3i","reiGzMfPBgu","vfPdCNC","Aw9Ul2PZB24","AM16DLC","C0PxuuK","Dg9Y","q0nMvvK","DwzVEK0","BMrWB2LUDfq","CfjeBge","yxnYu2K","lcbTyxGGCMu","DgHLBG","CevyEwW","zw50tgLZDgu","AxvKvLO","igzPzwXKoIa","yMLUyxj5vhK","v2vMu2e","q3vZDg9Trxi","twfJvu4","wuz4zhG","CNjVCK1LC3m","BvbgBNq","C1vtDK8","x2n1CNnVCK0","B2nRzxrtDwm","B3bLCNr5","rNjVBNrPzxi","rxzLBNq","yw51Ce1LC3m","zejTy1y","BIWGAg9ZDg4","tg5tzNe","zLfZzxq","AxHjtxe","sgfmq3G","Dg9hzw5LCMe","ExbL","qK13q20","y3jLyxrLuMu","z0vgtvK","uxnMBw0","Ahnlsu8","DwriB0K","BuDgu2q","zxjFCw9Z","Bwu6ia","DxrVuMvJB24","C2vYDMvYvgK","D0XhA1q","BxnNsuq","zMLSzw5HBwu","y2fSBa","yxnZAwDU","r2Tpr1G","BLzwrgK","A2Lwyw0","zgHgqxq","Dw1Qrwm","D3nZoI8V","AwfTzMm","AxnbCNjHEq","EwHuD0y","C21Krfm","BwLZzq","DeLUDgvYy2u","v2vIu29JA2u","sNj1C1C","sLflsuO","vgnnseO","CunbA3y","zNjVBuHHC2G","q1fUrfa","C2fNzq","ywzgyxm","EvDoD0m","B3jL","x3jLy29UBMu","qMvns3e","yKfuqwu","yuHOu2u","ChvZAa","zvjfuK4","zgriwMS","ChnIq2m","zxf1ywXZ","CvLSu3i","zg9Uzq","CgXQCfe","CgLYy1C","AhHVD3a","CLL0y2G","shnSDuu","sevOtM4","ywnRpwzYB24","wgHfthq","BKrTqNO","uKrMCwm","FdH8mxW3","BLrJrxq","mtiWmdmZoxLjsMDpAG","CgLUz0LUDgu","s2zqvMK","te94AK8","wgrVzxm","DfvUuNG","rvPVAgu","AvjUs0i","rNvrBgS","sMnbCxa","BfrPBwvVDxq","y2HLy2TdDxi","zw50","ywrKq291BNq","wwvruwu","wezHDvq","zv9ZDwnJzxm","qvnwswS","C1bXyvi","EfrfC0e","uvnbqvi","ue5UvNC","u0jpvxi","C2vYDMLJzq","B25pCgvU","uw9JCxi","ALnUELu","z1zhtuq","yuzvzxq","tuHdEwW","A2vAuhC","AwXLtMfTzq","ihrPBwvVDxq","ignVzgu6ia","zw1PDa","DMvYC2LVBG","y3vYC29YlNm","CMvUDevUzha","CNzHBa","tLHlweW","zxjFBxnNAwq","y2HnyxHuCMK","r2rTr28","uNrRuvu","CvHQtw4","rhnZD0S","yLHLuLm","v3LIC2K","zxjFCw9Zx2e","B3rRCeO","tM5Nwg4","twvZC2fNzuu","ywDlsfC","D3zouM8","y29UDgv4Da","wvrQqNu","EhnWEfq","Bhm6ia","BNruCMLLC0m","D3r5vfO","B3jLtMfTzxm","CMv0CNLdB3u","CMjlqK0","DwXJvgu","sKLHsva","AxnFywnR","rxjYB3jdB2q","AxbYChK","rNvuzNq","CM92AwrLigi","wfniENK","t2jQzwn0","BMfowwG","y2HLy2Tszwe","r3rsCLy","uLjpuG","tKPTq1G","reXvu1a","t2jMBNG","igzHAwWSig0","yuPeswy","CeviEu8","yxKSihrYEsa","C3rYAw5N","zw9UBwi","zKXyAMy","EwTOwg8","u29MwMy","u1bSB1e","rLjptLrjrvi","z296DLa","qvzOqNe","qw9qz0W","uwrLvuy","rg5qqvq","tg9NsurozxC","B3v0sw50zxi","wg9hA2e","y29UBMvJDeu","BwLurhe","Bgjszwq","zvPWEKe","EwTftNy","ywrKt25L","AevYCM9Yrxy","zw5KCg9PBNq","ywDLsgLKzq","r3bLz3a","v21xzee","CxLuBNu","uKjzv2C","z2v0sxrLBq","C3jfBge","uuDXAKW","BK5MuwO","uu56r0C","CgLUz0XVC3m","rwfzwuW","zxjYB3i","Cu5cAKm","uu54Evy","yxv0B21HDgK","y2juy0K","tg9Nsuq","zwrPyxrLBhK","Au5sEKu","ExbPA0C","y3vZDg9Tshq","qKjuAvm","u0niAw4","mteZmJeWnJrRzxnkA3m","rgXRtgW","A2f3EwO","t1nqvLa","y3ruAw1LB3u","AM9PBG","tuTzChi","uhHLuw0","y29UBMvJDca","A0PXu2O","x2n1CNnVCK4","tfnPC3C","weTQuKm","CgvSD0C","uwXgEgm","B0fsCee","BMv4DcGPigm","BgndzKi","ihrVihjLDhi","B2fK","A3rkt1O","Cw9RDLC","z3PQqvC","EeHIv2y","y29Kzq","zwvKzwq","vNvUtKC","BK9LBNK","wfDMwhC","v1fXs1y","x2rYB3bhBg8","q0nPq2e","qw1VDw50","BezSDxnO","AxnmB25N","uxrUwMi","q0Xpu0LorW","C2v0y3vYC28","D05rtwq","CKLiv2W","m3W1","DhbizwfKzxi","EgTPCNm","DwTeDee","wNrkyLe","zNjVBNrPzxi","BhDvyMm","BwvZC2fNztO","s3LOvxK","CMvTB3zLq2G","C05ezLa","ywXSB2nvBNm","vwzzqMG","x2LZqNjVD3m","C0DvB0y","zgvIDwC","rLnlA0e","DK5yuKC","suTyAMC","BwLcAxq","ihrPBwvZ","mNW1","wufRzKW","u294uK8","u2vYDMLJzvC","y2uGBM90igK","icSG","A2v5","Ae9Wzw5fDMu","qNvTqKe","z2v0t3DUuhi","AefJA01LC3m","zw5NDgG","uMvJB25Uzwm","C0XPC3rLBMu","AgP1CM0","BMvJDa","yxjYyxLIDwy","x29UrxjYB3i","zvHfAKW","twneANa","y1PyuLy","EgHnzMS","ywr1zva","B25nzxnZywC","Dwvuwwe","zw9TB0m","yLLYwgy","B25szwnLAxy","C2v0sxrLBq","D2LSBfjLy28","ALnIBMu","y2XLyxi","ru1ytg4","ywPjB1q","qurwwxq","uvPWyLe","veHQyKG","vMjtB0m","uxvmzgy","z3ryz2W","ywnRx2nVzgu","y2XesK0","u1bJshG","x2LUAxrhBg8","C2nYAxb0","CKDMtwW","tg9JAW","ywXty29Wzq","ENfitwW","ihjLy29UBMu","tMfTzq","CMvTB3zLrxy","CNnVCKzPBgu","vgHjwwO","shrhrKS","s0DTsNG","x2rLyNvN","AKfMBLa","DNv4zwm","ywzL","C3rYAw5NAwy","uhfYr0m","zNjVBu51Bwi","qvDYtxK","wgnjB3i","C0jf","zMzmAw5L","C2HPzNq","zgLZCgf0y2G","Cw53Dhm","Bg9N","Dev2zw50","tePLENi","uNDytfG","t0rrCgO","BNvTyMvY","tuPWuMi","vNjLtMW","thz3qNu","B09KAxC","CMvHzfvjBNq","CMvRzxC","x29WDgLVBNm","zxjYtM8","CfrPrfy","ru9ZCMi","yvb4C3K","AwLPzeG","x194x21Zz18","ExL6Ceq","yNL0zuXLBMC","tw9KDwXL","BKn3AeW","zfPICNi","DcbSAw1PDa","D0vIzNG","Cw9Z","txvrwuS","zxj2AwnL","uhjPBwfYEuS","v0L6wui","x0rctMfTzq","zNjVBuj5Dgu","qvPlBwq","CgLUz19VBMm","tgz2D0u","DMzeBxi","q2fnBxO","CuPZDgS","DKHsCwy","Au1TquW","B2jQzwn0u3q","x2LZtwLUAvq","EuLzDw8","qKnOruS","zhPxuK4","yK1gt3i","ihzHBgLKigq","vNntC2i","CKXICMK","DMvYC2LVBMm","uhLiu1O","ug16seW","q2zMvuG","su9fuKC","yxnL","CKnSCMK","mtaZodu3mtHMDMDUy0K","BwvY","B3r6sMG","BNf5wMS","DhjPzxmGCMu","A2Lvzve","zfzqAK8","z1rPBwvVDxq","x19LC01Vzhu","EuvTrLy","yMrFzgLK","vNL2A2e","yNf5AxO","ELnLAKq","wK9jsKi","x29UtwvZC2e","u0rOywC","u2zLwKi","FdH8mxW2","rvjst1i","CMLLC0nVDw4","D2fZq2XLyw4","y3jLyxrLq2W","t1bgq1q","BMnVzgLUzW","zxmGCMvHy2G","Ef9MCM9UDgK","BffbBgO","AMfbvMK","v2DmAxa","qvblCxe","sKDkyKm","s2DZz2K","y3jLyxrLtwu","wMDnquW","ue1HAwq","zvrpCLy","zwf2tg8","x3nLBMrby2S","Dw50","A3z0r3C","mdaWma","DxjS","B3jNEMO","A1bzAKi","CMvZzxrdB3u","ENfftKy","rgDhy08","u2Lyrhm","qvDVwKi","zw5fDMvUDa","CKfcr0W","y291BNq","mhWZFdf8nhW","q09otKvdveK","thfeDNy","yNLL","EvDsAMS","AML5rgW","t2fTwK0","z2vY","y3r4","Ee90z0K","AxzrzMm","zK1IEK4","Bwv0Ag9K","x3jLBw92zvC","BwfW","B25tDg9Wsw0","Avv3rva","q1PlB1q","y2XkDeO","y3jLyxrLt3a","yuP1rKK","Dg9VigXHCMC","t1bftG","D2fUsxm","yMLUyxj5","AgTJzvq","tuvtu0fhrv8","tvHiq2K","x25HDMLNyxq","CxH5wNu","CfrQEvC","t2nsvuO","ig1LC3nHz2u","v2vPEgLUsLm","y3jLyxrLrwW","z2v0s2v5","shPNEeW","t01Lsxe","Ee5hyxa","CM92AwrLihC","DgLTzw91DcW","y2XVC2veqG","zNjVBujPDhm","x2LZsw5PDa","teHXChO","yw1htfC","rM1OEw8","tvHOvhy","EM1oBLO","t1Lfwwq","AgLNAa","ufHWCMm","swnbD24","vvrPAKK","AMTXC1q","z3H6vNe","yxbWzw5Kq2G","wKTdqwC","CMvHzg9UBhK","Ec11C2uT","DhHkDu8","BMnLq2XVC2u","CfrXBLy","ALvjvu0","wu5KDgO","yKvoEfy","yw5ZzM9YBvq","Dg9cExrLC0i","x2nSzwfYugK","EhrLzNC","AwXK","EgrhvKG","zK1ss2K","CgfNzwHPzgu","Ahr0Chm6","CMTLCKDSB2i","BgzPrg0","CgvYC2LZDgu","Afz0wMq","sNnOvwW","B25Uzwn0Aw4","zMLUza","ywX3yxLZ","AxjLza","Ew5Kru8","BgvUz3rO","rMPbre4","CeHlCg8","rgDiwNm","C3zHuwu","EgrVCxy","rw94AeO","zfrxrKS","yMfJA3vWigu","y2f0y2G","uxz4y3e","B3jpBMXPBMu","y1r2we4","sLnptLa","z2vjBMzVu3K","sefuAeu","sK9usee","Aw50zwDLCIa","nNWYFdD8oxW","tvviBwm","zgvJB2rLzey","thDbu3u","sgLgB3G","wfrfr0S","D24GCMvHC28","suvtx0vsuK8","C3rLBMvYCW","x29Ut3bLBG","wKXjDwy","B2XKvMvYC2K","r2XZD0W","ChjVDg9JB2W","BLfwru4","zeTNzKK","CuHVBK0","tuLSwKi","ExvICLi","wezjuuu","Cvvtsgu","u1vvBeO","EKzRuLq","BeTjsKG","z2vtEw5J","vMD3wvi","AhPiwue","AMfIz20","rw11re0","uKDQse4","u2vXsuq","B1njBfq","DwzuDKq","EuXKq0S","zMLN","y29SBM8","Dg9mB3DLCKm","A2LZrNO","zw5XDwv1zq","ywXS","Bwf4tg9ZC0m","uxjeyKC","AwfyC0y","y2Pluhi","uhjuCue","ENzcrwG","tvLRreC","Dg9iyxnO","BgLUzw5V","v0zNy2O","AvP3D0i","wuHAzxm","r1bXBxq","zunHAgW","q09oveLovuu","DhjHBNnHy3q","ufzTq1q","x2LUAxq","C3vJy2vZCW","zg5KvMi","zgLZywjSzue","s213yMm","EeXWuxm","B2vKDfC","BNrLCG","x2LZtwLUAvC","wMXyvhu","CgjICdi","yxbWBhK","ruzlwMS","t3bLBKv2zw4","wNDSwwK","BM9mDuG","AgvKtwf4uMu","BMvY","AenSB3nLrxy","vuHVBNq","AwPJBfO","zfPLtw8","A2Tqr1O","s3v5Dxq","yxrHlcbKyxq","DM5pr2q","tuvxBhm","ywrKrxzLBNq","swrRvxq","q29UzMLN","y2HwD1q","ihn1y2nLC3m","q21uwKi","z2Lzzvi","zMX1C2HfEha","C3vIC3rYAw4","BgPWC3y","y29UC3rYDwm","zw5HyMXLqxu","wgv6C2e","vK9PvxK","zKnxEMG","DMfS","zwvttey","zMn5BuC","yNLxEMO","y29Uy2f0","wwTczwS","D1Lorum","sxbjDhy","DgHHBIbSB2m","Bwf4uMv0CMK","sKTiCMq","EMv5B3m","B3HPuuO","CMfTzq","B1PpELq","CKjzB0C","u2TPCcbWyxm","Chv0","yuvrq0O","shjRuxa","sgLyv0O","zK1OBNK","z2v0","tLzwvLC","BNrfBMrWB2K","B3D1vgm","AhbHq0W","x3DZ","BM93","veD4D2e","u3rYyxrLz3K","rvrkquC","D2LOt3O","quLUB1q","wu13CvK","tgLZDgvUzxi","B25JBg9Zzq","BunMCvy","zgvSzxrL","ywnR","wwfKzfu","uwrysKC","svvfCgO","r2z4AMG","s1jLq0W","DNHrDva","zv90Aw1LB3u","x21LC3nHz2u","x2rPC2nVBM4","yw1L","zvnNs2K","AgvHzgvY","t0veqMC","x21PBMLoyxy","AKXRq3e","x3bHDgHlzxK","DerLyNC","yxnJCMLWDa","Ahn1Dgq","rhLLAfG"];return Zo=function(){return t},Zo()}function fS(t){Qo={yLdCK:function(i,o){return i(o)}}[N(1458)](t,Qo)}function hS(t){let e=N,r={vBfBt:function(i,o){return i(o)},FvNfu:"AbortError",nAUUJ:function(i){return i()},xQghs:e(1069),DlkLl:e(1668),RJcFE:function(i,o){return i==o},CQnDP:"wss://",PsnUi:e(1755),BChEK:function(i,o){return i===o},mSmms:e(1549),tQlOr:function(i,o){return i(o)},GdmGo:function(i,o){return i===o},Uyply:function(i,o){return i in o},OehKr:e(1253)+e(1011),VhSnV:"kkPGZ"};if(r[e(993)](t,IDBDatabase[e(337)+"e"]["transact"+e(783)])&&!r[e(402)](r[e(1647)],IDBTransaction[e(337)+"e"])){if(r.BChEK(e(1504),r.VhSnV))return function(i,...o){let c=e;if(c(314)!=="pYlHQ"){let l=t[c(903)](r[c(726)](is,this),i,...o);return Ud[c(1680)](l,i[c(711)]?i.sort():[i]),r[c(726)](zt,l)}else return this[c(1764)+c(858)+c(1289)+"t"]=1,this[c(789)+"ndex"]++,this.endpoints[this[c(789)+"ndex"]]};{let i={wdZFc:eFUDDu[e(1859)]},o=()=>{let u=e;_0x61df75["removeEventListe"+u(1499)](u(401),c),_0x1847b2[u(1193)+"entListe"+u(1499)](i[u(1811)],l),_0x48548d["removeEventListe"+u(1499)](u(1668),l)},c=()=>{_0x31a7f0(),o()},l=()=>{let u=e;_0x3bb215(_0x41ddb1[u(1069)]||new _0x529150(eFUDDu[u(773)],eFUDDu[u(773)])),eFUDDu.nAUUJ(o)};_0x25fd00[e(1509)+e(1559)](e(401),c),_0x5bc8db[e(1509)+e(1559)](eFUDDu.xQghs,l),_0xa3cb72[e(1509)+e(1559)](eFUDDu[e(1082)],l)}}return r[e(1603)](dS)[e(317)](t)?function(...i){let o=e,c={eAjoZ:function(l,u){return r[q(1825)](l,u)},vGiKN:r[o(923)],eonmb:r[o(580)]};if(r[o(1256)](r[o(1777)],o(1549)))return t.apply(is(this),i),r.vBfBt(zt,Hd.get(this));_0x5b4388=_0x4d999a&&c[o(1796)](o(1396),_0xc23613.protocol)?c[o(560)]:c[o(1035)],_0x14cf04=_0xea719c[o(827)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),_0x6d0134=/^wss(.*:\/\/)/[o(1676)](_0xf7a76)?_0x5b5661:""+_0x553f55+_0x2dce02}:function(...i){let o=e;return r[o(849)](zt,t[o(1493)](is(this),i))}}function xS(t){let e=N,r={SPcHx:function(i,o){return i===o},EOsrb:e(697),GZSeg:function(i,o){return i(o)},iIENr:function(i,o,c){return i(o,c)},ovZyq:function(i){return i()}};return r[e(1184)](typeof t,r[e(1227)])?hS(t):(t instanceof IDBTransaction&&r.GZSeg(uS,t),r[e(459)](Ox,t,r[e(582)](cS))?new Proxy(t,Qo):t)}function zt(t){let e=N,r={pHixE:function(o,c){return o instanceof c},eaCCM:function(o,c){return o(c)},jwsHa:function(o,c){return o!==c},KejSI:e(1881)};if(r.pHixE(t,IDBRequest))return lS(t);if(Vo[e(451)](t))return Vo[e(1546)](t);let i=r.eaCCM(xS,t);return r[e(1762)](i,t)&&(r[e(488)]!==r[e(488)]?_0x497dac.d=(o,c)=>{let l=e;for(var u in c)_0x3180cd.o(c,u)&&!_0x47a9a2.o(o,u)&&_0x5bed12[l(600)+"operty"](o,u,{enumerable:!0,get:c[u]})}:(Vo[e(1680)](t,i),Xo[e(1680)](i,t))),i}var Ox,kx,Tx,Hd,Yo,Ud,Vo,Xo,Qo,is,Cx=Px({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={cclQD:function(r,i){return r<i},wRHQB:function(r,i,o){return r(i,o)},ajIoT:function(r,i,o,c){return r(i,o,c)},gtXgl:function(r,i){return r+i},Obfnx:function(r,i){return r instanceof i},CuAtg:function(r,i){return r!==i},QETuW:t(1298),vEdsb:function(r,i){return r===i},vuxec:function(r,i){return r===i},xhMfk:function(r,i){return r(i)},iLDbF:"done",WyPZu:function(r,i){return r===i},chBDO:t(538),qCAkv:function(r,i){return r in i}};Ox=(r,i)=>i[t(1857)](o=>r instanceof o),Hd=new WeakMap,Yo=new WeakMap,Ud=new WeakMap,Vo=new WeakMap,Xo=new WeakMap,Qo={get(r,i,o){let c=t,l={qbIVM:function(u,f){return e[q(673)](u,f)},KTuLn:function(u,f,x){return e.wRHQB(u,f,x)},EokFw:function(u,f,x){return e.wRHQB(u,f,x)},QZpbQ:function(u,f,x,g){return e[q(1175)](u,f,x,g)},Bygse:function(u,f){return e[q(1181)](u,f)},IQxJC:function(u,f,x){return u(f,x)}};if(e[c(1029)](r,IDBTransaction))if(e.CuAtg("YXeMW",e[c(1812)])){if(e[c(599)](i,c(938)))return Yo[c(1546)](r);if(e[c(599)](i,c(1253)+c(1011)))return r[c(1253)+c(1011)]||Ud.get(r);if(e[c(1200)](i,c(538)))return o[c(1253)+"oreNames"][1]?void 0:o["objectSt"+c(927)](o[c(1253)+"oreNames"][0])}else{let u=0,f=[];for(;l[c(814)](u,_0x5be5fc[c(1232)+"th"]);){let{offset:x}=l[c(1835)](_0x165359,_0x1a0363,u);u=x;let g={cursor_name:"",cursor:0,service:0},{value:y,offset:S}=l.KTuLn(_0xc4cb90,_0xe3fcd3,u);g.service=y,u=S;let{value:_,offset:v}=l.EokFw(_0x53bc8d,_0x427b4f,u);u=v,g[c(466)+"ame"]=l[c(1177)](_0x2cfb8f,_0x9bba1c,u,l.Bygse(u,_)),u+=_;let{value:I,offset:A}=l[c(684)](_0x5bd47a,_0x27cde2,u);g[c(1631)]=I[c(812)](),u=A,f[c(932)](g)}return f}return e[c(1163)](zt,r[i])},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return e[o(1029)](r,IDBTransaction)&&(i===e[o(467)]||e[o(1837)](i,e[o(332)]))?!0:e[o(921)](i,r)}},is=r=>Xo[t(1546)](r)}}),Lx={};aS(Lx,{deleteDB:()=>gS,openDB:()=>pS,unwrap:()=>is,wrap:()=>zt});function pS(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let l=N,u={hTUPb:function(g,y){return g(y)},jWskL:l(1769),MVQzB:l(1262)+"hange",MIlZB:l(786)+l(1106),TCkrj:"blocked"},f=indexedDB[l(832)](t,e),x=u[l(1702)](zt,f);return i&&f[l(1509)+l(1559)](u[l(1442)],g=>{let y=l;i(u.hTUPb(zt,f.result),g[y(1436)+"on"],g.newVersion,u.hTUPb(zt,f[y(1480)+y(783)]))}),r&&f[l(1509)+l(1559)](u.TCkrj,()=>r()),x[l(862)](g=>{let y=l;c&&g.addEventListener(u[y(551)],()=>c()),o&&g.addEventListener(u[y(398)],()=>o())})[l(1416)](()=>{}),x}function gS(t,{blocked:e}={}){let r=N,i={sLnUZ:r(813),KTjPy:function(c,l){return c(l)}},o=indexedDB[r(834)+r(493)](t);return e&&o[r(1509)+r(1559)](i[r(1873)],()=>e()),i[r(775)](zt,o)[r(862)](()=>{})}function Rx(t,e){let r=N,i={wpooA:r(453)+"e",YrpTt:r(1380),zmNnZ:function(f,x){return f instanceof x},iSrBM:function(f,x){return f in x},JcAqp:function(f,x){return f===x},yWNwC:function(f,x){return f!==x}};if(!(i[r(1370)](t,IDBDatabase)&&!i[r(645)](e,t)&&i[r(960)](typeof e,r(1034))))return;if(Jo[r(1546)](e))return Jo[r(1546)](e);let o=e[r(827)](/FromIndex$/,""),c=i[r(926)](e,o),l=Mx.includes(o);if(!i[r(645)](o,(c?IDBIndex:IDBObjectStore)[r(337)+"e"])||!(l||Nx[r(317)](o)))return;let u=async function(f,...x){let g=r,y=this[g(1480)+g(783)](f,l?i.wpooA:i[g(1713)]),S=y[g(538)];return c&&(S=S[g(577)](x[g(1209)]())),(await Promise[g(1464)]([S[o](...x),l&&y[g(938)]]))[0]};return Jo.set(e,u),u}var Nx,Mx,Jo,mS=Px({"node_modules/idb/build/index.js"(){let t=N,e={mPFnt:"4|1|3|0|"+t(1142),NVVVW:t(1541),BenAj:t(1562),iwZVj:t(1173),oyzza:function(o){return o()},QPZPe:"get",QnTks:t(1357),jQmSO:t(665),XFIQE:t(1779)+"ys",QIeFW:function(o){return o()},fASlF:function(o,c){return o(c)}},r=e[t(873)][t(557)]("|"),i=0;for(;;){switch(r[i++]){case"0":Mx=[e[t(1547)],"add",e[t(510)],e[t(659)]];continue;case"1":e[t(1731)](Cx);continue;case"2":Jo=new Map;continue;case"3":Nx=[e[t(595)],e[t(1651)],e[t(1667)],e[t(1444)],t(1321)];continue;case"4":e[t(389)](Cx);continue;case"5":e[t(618)](fS,o=>({...o,get:(c,l,u)=>Rx(c,l)||o[t(1546)](c,l,u),has:(c,l)=>!!Rx(c,l)||o[t(451)](c,l)}));continue}break}}}),wS={idb:function(t){let e=N;t.exports=Promise[e(474)]()[e(862)](()=>(mS(),Lx))[e(862)](function(r){return r})}},Dx={};function Ft(t){let e=N;var r=Dx[t];if(r!==void 0)return r[e(1787)];var i=Dx[t]={exports:{}};return wS[t](i,i[e(1787)],Ft),i[e(1787)]}Ft.d=(t,e)=>{let r=q;for(var i in e)Ft.o(e,i)&&!Ft.o(t,i)&&Object["definePr"+r(877)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;Ft.o=(e,r)=>Object[t(337)+"e"][t(1737)+t(877)][t(903)](e,r)})(),(()=>{let t=N,e={zqENF:function(r,i){return r!=i},qNBjC:t(661)+"d",yJiSe:t(1233),CnAhc:t(1277)+"le"};Ft.r=r=>{let i=t;e[i(1315)](e[i(1070)],typeof Symbol)&&Symbol[i(1715)+"Tag"]&&Object[i(600)+"operty"](r,Symbol[i(1715)+i(664)],{value:e.yJiSe}),Object.defineProperty(r,e[i(487)],{value:!0})}})();var Oe={};(()=>{let t=N,e={dZeMo:t(909),zSejD:function(a,n){return a+n},aHeqa:function(a,n){return a+n},kJqSj:function(a,n){return a+n},zYPXl:function(a,n){return a*n},FvHED:function(a,n){return a*n},LSisw:function(a,n){return a+n},RJvhW:function(a,n){return a(n)},DKWnj:function(a,n){return a+n},aAUpZ:function(a,n,s){return a(n,s)},tfMAc:function(a,n){return a(n)},EhjpZ:t(1310),iRnKB:t(361),VgwYR:function(a,n){return a(n)},bZEcR:t(399)+"t",hMcHq:"stop imm"+t(1075)+t(1191)+"ct",BxErS:function(a,n){return a>n},QfYFD:function(a,n){return a===n},rABGL:t(1071),mEXwf:function(a,n){return a<n},OPFCT:function(a,n){return a!==n},LVkTb:function(a,n){return a-n},AUgJc:function(a,n){return a-n},NJmCX:function(a,n){return a-n},pEXyl:function(a,n){return a===n},NgazG:t(885),VmXHG:function(a,n){return a<n},muajk:t(973),UWHWu:function(a,n){return a(n)},yCocr:function(a,n){return a!==n},RBYWg:function(a,n){return a!==n},IBHpM:t(953),jtwLi:t(1735),IXJtT:function(a,n,s){return a(n,s)},IySkS:function(a,n,s,d){return a(n,s,d)},lKCCS:t(732),wKPQG:t(445),MnVtS:"service",PyHSZ:t(1575),DdYhE:t(1255),Pitdp:function(a,n){return a>>>n},rdyIN:function(a,n){return a(n)},eTOrV:function(a,n,s){return a(n,s)},uCVNU:function(a,n){return a&n},aSomx:function(a,n){return a===n},HSTHS:"Missing "+t(1614)+t(866)+"key",qYlSr:function(a,n){return a===n},BINtB:function(a){return a()},wanIs:function(a,n){return a>>>n},smdDS:function(a,n){return a>>>n},BumBA:function(a,n){return a&n},tagqW:function(a,n){return a>>>n},PTbjg:function(a,n){return a&n},Gfxjh:function(a,n){return a!==n},cTvXN:function(a,n,s){return a(n,s)},IuoIp:function(a,n){return a!==n},QpIjQ:function(a,n){return a!==n},MUHmc:function(a,n){return a(n)},yEmFV:function(a,n){return a!==n},IOERG:function(a,n,s){return a(n,s)},jRSYY:function(a,n){return a!==n},LWDhR:function(a,n,s){return a(n,s)},SIdZc:function(a,n,s){return a(n,s)},oSIlT:function(a,n){return a===n},wYNEC:t(478),mITvC:function(a,n,s){return a(n,s)},nQVEN:function(a,n){return a!==n},rqfjA:function(a,n,s){return a(n,s)},gVGMD:function(a,n,s){return a(n,s)},TFrdm:function(a,n,s){return a(n,s)},HtGFK:function(a,n,s){return a(n,s)},kpbos:function(a,n){return a(n)},HAUTE:function(a,n){return a(n)},iamfc:function(a,n){return a(n)},qJstk:function(a,n){return a(n)},IfKlO:function(a,n,s){return a(n,s)},kzDYY:function(a,n,s){return a(n,s)},AMaFH:function(a,n){return a(n)},rLbri:function(a,n){return a(n)},ktJOZ:function(a,n){return a(n)},GTBVK:function(a,n,s){return a(n,s)},sUSvO:function(a,n,s){return a(n,s)},rbKBM:"Missing "+t(1614)+t(866)+t(1455),BDCDS:t(1610)+t(1614)+t(866)+t(1074),xulLz:"Missing "+t(1614)+t(866)+t(974),nHBgv:t(1610)+"required field: "+t(1334),qSduL:t(575),MXHCi:function(a,n){return a(n)},Fmhyo:function(a,n,s){return a(n,s)},qPcqP:function(a,n){return a>>n},edmmt:function(a,n){return a>=n},bPRRt:function(a,n){return a===n},yWRjk:function(a,n){return a(n)},EoxhJ:t(1220),mgnSS:function(a,n){return a>n},hVtZd:function(a,n){return a+n},TDdhS:t(1540)+t(1236),VZkcA:function(a,n){return a>n},IKXjg:function(a,n,s){return a(n,s)},ddCxI:function(a,n,s){return a(n,s)},etDSq:t(628)+t(1033)+t(399)+t(658)+t(578),QdeUF:t(1668),cPeeh:function(a,n){return a<n},NZdfI:function(a,n){return a+n},dfnHK:function(a,n){return a===n},BEjdP:function(a,n){return a>=n},hHloP:function(a,n){return a+n},VlEiA:function(a,n){return a+n},byWzj:function(a,n){return a===n},BeMKq:t(1366),hRdOB:function(a,n){return a|n},uShkY:function(a,n){return a<<n},UPQXF:function(a,n){return a&n},BToyz:function(a,n){return a<n},MhHto:t(795),yhTwF:t(625),nlJWQ:function(a,n){return a==n},kisFz:function(a,n){return a>=n},dKgfI:function(a,n){return a+n},nOeny:function(a,n){return a&n},hpaCL:function(a,n){return a|n},wNQMd:function(a,n){return a<<n},OGSnv:function(a,n){return a&n},ByrYz:function(a,n){return a<n},Xdoes:function(a,n){return a>=n},zvBEh:function(a,n){return a+n},LnSfq:function(a,n){return a+n},JJTZN:function(a,n){return a|n},sGUoF:function(a,n){return a|n},XIGzv:function(a,n){return a<<n},xmYJJ:function(a,n){return a|n},upGEg:function(a,n){return a<<n},WFgcj:function(a,n){return a<<n},eCahl:function(a,n){return a<n},HPMAE:function(a,n,s){return a(n,s)},pVYYC:function(a,n){return a<n},JdQgC:function(a,n){return a>=n},PUVDI:function(a,n){return a<=n},LwASu:function(a,n){return a<<n},rClri:function(a,n){return a<n},aRDHZ:function(a,n,s){return a(n,s)},NPZVP:function(a,n){return a<n},SDCip:t(1819),QeDqa:t(1729),phkfw:function(a,n){return a>=n},psbCc:function(a,n){return a<=n},BCiRF:function(a,n){return a-n},ftCRS:function(a,n){return a<<n},LnASR:function(a,n){return a<n},EmuDM:function(a,n){return a&n},AInoT:function(a,n){return a|n},PMaid:function(a,n){return a>>n},ZGAEp:function(a,n){return a>>n},ihMNd:function(a,n){return a|n},EezXw:function(a,n){return a&n},QPMJq:function(a,n){return a&n},fMRKi:function(a,n){return a|n},SOwbR:function(a,n){return a<n},bXeRS:function(a,n,s){return a(n,s)},rekew:t(1782),aBjVo:function(a,n){return a(n)},giYeR:function(a,n){return a<n},OMeIq:function(a,n){return a>=n},qHonM:function(a,n,s){return a(n,s)},nwECz:function(a,n,s){return a(n,s)},SPCDz:function(a,n){return a>=n},mrORA:function(a,n,s){return a(n,s)},HiXWJ:function(a,n){return a>>>n},oARpA:function(a,n,s){return a(n,s)},nKSqc:function(a,n,s){return a(n,s)},iaXsF:function(a,n,s){return a(n,s)},ViUua:t(1452),qnwts:function(a,n){return a&n},BhXGw:function(a,n){return a&n},ZNFOL:function(a,n){return a&n},bQXoi:function(a,n){return a&n},AhKoe:function(a,n){return a&n},vfDmr:function(a,n){return a(n)},mvuDE:function(a,n){return a<<n},yNrRV:function(a,n){return a(n)},SYYot:function(a,n){return a&n},UMhUx:function(a,n){return a&n},noSXP:t(1077),rjYPC:function(a,n){return a(n)},pHKpo:function(a,n){return a&n},AlOTb:function(a,n){return a!==n},wHdsv:"GnhTa",VdQMA:function(a,n){return a<<n},uwkiV:function(a,n){return a&n},ryLbs:function(a,n){return a(n)},nVgXW:function(a,n){return a&n},iSjWP:function(a,n){return a<<n},IivgU:function(a,n){return a<<n},TpeNB:function(a,n){return a<<n},dTWFK:function(a,n){return a|n},qvVWD:function(a,n){return a>>>n},RTHMR:function(a,n){return a<<n},Vyvka:function(a,n){return a>>>n},JQKIJ:function(a,n){return a===n},IdkUt:function(a,n){return a===n},mGFSd:function(a,n){return a<n},PdsUB:function(a,n){return a<n},ZAIYM:function(a,n,s){return a(n,s)},sNDfP:function(a,n){return a>>>n},xBPzp:function(a,n){return a+n},jAfnP:function(a,n){return a!==n},gEFMY:function(a,n){return a|n},jcAKo:function(a,n){return a+n},EEXxb:function(a,n){return a&n},adueP:function(a,n){return a!==n},VAwFM:function(a,n){return a>>>n},ODQpj:function(a,n){return a>>>n},dKCIP:function(a,n){return a+n},ASVIk:function(a,n){return a|n},KXlhc:function(a,n){return a&n},QfpfJ:function(a,n){return a+n},QnVLP:function(a,n){return a!==n},VOiUy:function(a,n){return a&n},zDWsn:function(a,n){return a+n},nqyZk:function(a,n){return a!==n},sPqaR:function(a,n){return a|n},pTqnV:function(a,n){return a>>>n},otzJh:function(a,n){return a>>>n},nPGas:function(a,n){return a&n},QhOMA:function(a,n){return a(n)},pRFik:function(a,n){return a|n},ZLIuf:function(a,n){return a===n},PfScl:function(a,n){return a<<n},eavLo:function(a,n){return a|n},LbmeH:function(a,n){return a<<n},SQuVx:function(a,n){return a<<n},QrDbG:function(a,n){return a|n},QDGXT:function(a,n){return a|n},McDjp:function(a,n){return a<<n},Wvmwf:function(a,n){return a|n},nCwhL:function(a,n){return a|n},fLXjf:function(a,n){return a<<n},taYId:function(a,n){return a|n},wuikP:function(a,n){return a|n},dvqXp:function(a,n){return a<<n},YAjWh:function(a,n){return a&n},jiyDl:function(a,n){return a>>>n},dBmcV:function(a,n){return a&n},LRthl:function(a,n){return a>>>n},QbyQZ:t(774),GlpFk:t(1824),zsnsH:function(a,n){return a(n)},JIaIP:"YAkfL",yhIGN:function(a,n){return a>=n},xTEsA:t(597),PxrRT:function(a,n){return a<=n},tflof:function(a,n){return a+n},bYkvl:function(a,n){return a/n},iudVZ:function(a,n){return a(n)},JvRdD:t(690),CCfUY:function(a,n){return a*n},pbQcA:function(a,n){return a>>>n},VsSsb:function(a,n){return a>>>n},zaKiK:function(a,n){return a+n},egGqM:function(a,n){return a*n},lcCfB:function(a,n){return a>>>n},lQAlj:function(a,n){return a&n},UXdvy:t(746),lfBYz:function(a,n){return a>>>n},MQmpX:function(a,n){return a&n},ukwey:function(a,n){return a>>>n},uMBzr:function(a,n){return a&n},wvNRo:function(a,n){return a&n},BBTiS:function(a,n){return a+n},Kgsgi:function(a,n){return a>>>n},vTKUX:function(a,n){return a+n},crtqF:function(a,n){return a+n},APKqq:function(a,n){return a+n},IiqBZ:function(a,n){return a|n},pVjJI:function(a,n){return a<<n},OVmBc:function(a,n){return a>>>n},PqrGC:function(a,n){return a===n},qokvW:function(a,n){return a===n},tRkih:function(a,n){return a===n},naNYh:t(1845),LfvwE:function(a,n){return a&n},WlGXV:function(a,n){return a&n},wVEgY:function(a,n){return a>>>n},sgBXe:function(a,n){return a>>>n},BUDtv:function(a,n){return a>>>n},zsnWR:function(a,n){return a&n},Xezsa:function(a,n){return a&n},YKnrk:function(a,n){return a>>>n},Tohke:function(a,n){return a&n},oRpRX:function(a,n){return a&n},ftrGd:function(a,n){return a>>>n},lQOVg:t(1832)+t(1026),GkOGX:"CONNECTI"+t(666),SZyMX:"MAX_RETR"+t(1432)+"R",SjACL:"OPEN_ERROR",rgnxQ:function(a,n){return a|n},rBYoG:t(1580),mKvuq:t(1818),ddHZk:function(a,n){return a!==n},xNGap:t(536),rfgvO:t(524),ivQfc:t(621),PmzHL:t(1309),gzjAW:t(811),kQNXq:t(409),HeRWg:function(a,n){return a===n},pPJvu:function(a,n){return a-n},pzbLN:t(1069),rLqiQ:"hNXRy",xTJKu:t(353),yRXdG:function(a,n){return a==n},tudYe:function(a,n){return a>n},oqocy:function(a,n){return a===n},piRsc:t(624)+t(852),SCHin:t(624)+t(852)+";charset=utf-8",kBoTe:t(1034),pKvFC:"none_none",FjADN:t(1346),SyXaC:"bSkwB",gOCkD:function(a,n){return a===n},GtapL:function(a,n){return a instanceof n},Cxhuz:t(418)+t(1600),hsutd:function(a,n){return a+n},iPrdq:function(a,n){return a===n},EZohe:t(359),NomUM:t(1084),aEQCJ:t(1872),XKjRC:function(a,n){return a===n},aFUet:"sfAbW",bVuli:function(a,n,s){return a(n,s)},fIsLz:t(1769),srEla:t(832),KGmJx:function(a,n,s){return a(n,s)},DVomA:t(1021),fcymG:t(736),SDlyS:function(a,n,s){return a(n,s)},OmVPf:function(a,n){return a instanceof n},ubKep:function(a,n){return a+n},xspxT:function(a,n){return a!==n},iszPR:"naPOi",ycdPw:t(1690),JIdQF:function(a,n){return a|n},gfqXm:function(a,n){return a<<n},yVcIw:t(805),LIXYJ:"ZLaYN",KyhUy:function(a,n){return a||n},amGLW:function(a,n){return a!=n},POcjp:t(661)+"d",YFTOw:"3|1|2|4|0",hxowp:function(a,n){return a||n},YBNon:function(a,n){return a!=n},MXhTv:function(a,n){return a<=n},EFKZk:function(a,n){return a===n},IrcJx:function(a,n){return a<n},KMHWx:function(a,n){return a&n},eXEjL:function(a,n){return a+n},jmzvW:t(1429),arKCO:function(a,n){return a<=n},UfYBh:function(a,n){return a>=n},usKcL:function(a,n){return a<n},mEzfw:function(a,n){return a|n},sjOhP:function(a,n){return a<<n},hkceT:function(a,n){return a&n},BLqXK:function(a,n){return a>=n},Nkpcr:function(a,n){return a<n},PuJDw:function(a,n){return a|n},SoxRO:function(a,n){return a|n},ZIEbv:function(a,n){return a&n},vLbxX:function(a,n){return a&n},MacUN:function(a,n){return a<<n},ZLkBw:function(a,n){return a&n},qxyZu:function(a,n){return a&n},YfUew:function(a,n){return a+n},IUEpj:function(a,n){return a+n},oxMVV:function(a,n,s){return a(n,s)},utHLG:function(a,n,s){return a(n,s)},aJuFI:function(a,n){return a(n)},DXhpx:t(513),miDLf:function(a,n){return a<n},LLzOa:function(a,n){return a|n},hjurm:function(a,n){return a===n},pircW:function(a,n){return a&n},YFxdx:t(1297),UpgEP:t(1885)+t(1121),wVulW:function(a,n){return a|n},XrfuR:function(a,n){return a>>n},LOxpL:function(a,n){return a|n},miBit:function(a,n){return a&n},yuHHa:function(a,n){return a<<n},HPVlp:function(a,n){return a&n},RtkQU:function(a,n){return a>>n},LVVGl:function(a,n){return a|n},nwBiC:function(a,n){return a>>n},UTijI:function(a,n){return a-n},TvsEH:function(a,n){return a instanceof n},QKHvz:function(a,n){return a instanceof n},tvSaR:function(a,n){return a==n},fMbzN:t(1748)+"in;chars"+t(720),cbTcI:"OnYyg",YYmOe:t(1682),akZZR:function(a,n){return a>=n},fyFqA:function(a,n){return a>>>n},CIAgs:function(a,n){return a<<n},QlFxc:function(a,n){return a<n},DvhVN:function(a,n){return a<n},xtGuv:function(a,n){return a<n},HzgxL:function(a,n){return a&n},tFeHl:function(a,n){return a|n},wzNvX:function(a,n){return a+n},gevcz:function(a,n){return a|n},VgSOz:function(a,n){return a&n},ukDtA:function(a,n){return a+n},gUqNc:function(a,n){return a&n},hqrft:function(a,n){return a!==n},OYEYd:function(a,n){return a>>>n},dhPdd:function(a,n){return a+n},AXzYz:function(a,n){return a+n},seDse:function(a,n){return a|n},fWAph:function(a,n){return a>>>n},WCGBh:function(a,n){return a&n},kiVam:function(a,n){return a>>>n},vxQuP:function(a,n){return a+n},zTZOQ:function(a,n){return a!==n},JsGme:function(a,n){return a>>>n},kUtSZ:function(a,n){return a&n},qBacL:function(a,n){return a|n},bqyiz:function(a,n){return a(n)},ThBzq:t(376)+"reason",PTUaZ:function(a,n){return a(n)},sJGYH:t(1186),clJtJ:t(765)+t(1581),hIfCg:"http",PuQDA:"oJtwg",binqm:t(1578),ZOIJB:"PvZZs",eFcUC:t(416),bbSfa:function(a,n,s,d){return a(n,s,d)},QHSwN:function(a,n){return a>>n},Arorq:t(946),nNfQj:t(1673),EaYYL:t(1830),DgHZs:t(734),yfCfq:t(1215),DyehX:"GtRrV",BYYRm:function(a,n){return a===n},nfPLZ:"HWLdZ",rYtch:t(889),TIVwm:t(528),KmbpQ:t(319),CBrQi:"HDPFP",CEnSm:function(a,n){return a||n},PEtri:t(1238),JUJsA:t(412)+"id",afFas:function(a,n,s){return a(n,s)},foOzm:function(a,n){return a!==n},GPqmt:t(405),bENxV:function(a,n){return a>=n},MiJNQ:function(a,n){return a&n},lgszc:function(a,n){return a&n},KoeFf:function(a,n){return a<<n},MYkDG:function(a,n){return a-n},Bxsfg:function(a,n){return a&n},EAcBB:t(1417),ZwlYi:t(1028),sFZEe:t(1295)+t(896),ljpsv:t(1295)+t(999)+"ck",ISqez:function(a,n,s,d){return a(n,s,d)},ZNugv:t(1295)+"er_is_ack",YHZes:function(a,n,s){return a(n,s)},cjKPr:t(1040)+">",iTPAl:function(a,n){return a!==n},iVbOh:t(1556),YMwqY:"Module",nTcEt:t(1277)+"le",WmWdA:t(1561),YaddU:"need_ack",nAwoN:"is_ack",GqgWf:function(a,n){return a&&n},wNTmR:t(516),zqHMl:function(a){return a()},InSdK:function(a,n){return a>>>n},ZJClV:function(a,n){return a>>>n},cYiVY:function(a,n){return a&n},nwnRk:function(a,n){return a>>>n},afFUn:function(a,n){return a&n},FQhjw:function(a,n){return a&n},Qsfmm:function(a,n){return a+n},WHEfC:function(a,n){return a+n},YPWFF:function(a,n){return a>>>n},ayrDU:function(a,n){return a+n},RZuJK:function(a,n){return a<<n},GlswL:function(a,n){return a(n)},NkuwJ:function(a,n){return a(n)},Wybsi:function(a,n){return a===n},yubrR:"yrqVa",MJpRb:function(a,n){return a instanceof n},BUqKl:function(a,n){return a instanceof n},nvGsO:function(a){return a()},mqhdB:function(a,n){return a||n},dZbrr:function(a,n){return a||n},QNzGG:function(a,n){return a<n},NngXn:function(a,n){return a>n},tUvPJ:function(a,n){return a+n},IHDJO:function(a,n){return a===n},YbPrZ:t(703),oiqxF:function(a,n){return a(n)},DVTkt:function(a,n){return a||n},pSScq:function(a,n){return a>>>n},noLuH:function(a,n){return a!==n},ETJAG:t(472),WQqKV:function(a,n){return a+n},KReCL:function(a,n){return a+n},aJDIf:function(a,n){return a+n},FGZGK:"index out of ran"+t(601),QGqjL:t(1147),LAkPw:t(321),GgTHL:function(a,n){return a>n},jVHMr:t(1424)+t(1343)+"e",kiUeQ:function(a,n){return a+n},ApcAx:function(a,n){return a<<n},eKUDi:function(a,n){return a<n},VtePp:function(a,n,s,d){return a(n,s,d)},ycQah:function(a,n){return a+n},LzXHz:function(a,n){return a|n},lfiDm:function(a,n){return a|n},nDmBz:function(a,n){return a+n},oOdiw:function(a,n){return a+n},eQeaD:function(a,n){return a<<n},VnmrZ:function(a,n){return a<<n},ktXJw:function(a,n){return a+n},GlVyM:function(a,n){return a+n},AJAkx:function(a,n){return a+n},RQXpe:function(a,n){return a&n},awacv:function(a,n){return a+n},ijclZ:function(a,n){return a&n},zsuPB:function(a,n){return a+n},iZwmf:function(a,n){return a&n},hzHYA:function(a,n){return a+n},bBgzr:t(1425)+"3|5|4|1|11|0|8|10",iOnvC:function(a,n){return a<n},KKucg:function(a,n){return a>>>n},vSyga:function(a,n){return a|n},DgGcO:function(a,n){return a<n},XFauT:function(a,n){return a<n},PNnVw:function(a,n){return a(n)},DLKeq:function(a,n,s){return a(n,s)},zbRiN:function(a,n){return a&n},CffUH:t(1775)+t(505)+t(949),DnPAT:t(987)+t(1240),Puqge:t(576)+"name",PxeQm:function(a,n){return a===n},sCpgG:t(1475),lBolV:"cursor_file_name",NXKXL:function(a,n){return a<n},TunTh:function(a,n,s,d){return a(n,s,d)},wIfiM:t(704)+t(492),uizKF:function(a,n,s){return a(n,s)},lexsB:"cursor_n"+t(1573),bYrXf:"allCursorValues",qXjMn:t(632),NvKzk:t(586),yyzpD:t(1479),chVwT:function(a,n,s,d){return a(n,s,d)},jUzhO:t(1448),IpItv:"NtpRy",sVJTO:"setdb",kKySg:function(a,n){return a(n)},gKvuA:t(1118)+"r",fMhny:function(a,n){return a(n)},vHcDI:t(357),yndEO:function(a,n,s,d){return a(n,s,d)},tlLgm:t(1105),PmNRE:function(a,n,s,d){return a(n,s,d)},zVFpQ:t(1295)+t(991),VbSoC:t(1295)+"er_ttl",STbka:t(519)+t(762)+"e",GeesE:function(a,n){return a(n)},FISuV:t(519)+"rsor_value",asrSi:function(a,n){return a>n},orgzj:function(a){return a()},jSnzU:function(a,n){return a<n},WIzYB:function(a){return a()},pTiDV:function(a,n,s){return a(n,s)},THjbH:function(a){return a()},pOfnA:function(a){return a()},fCWzh:function(a,n){return a(n)},lbRed:function(a,n){return a!==n},bATAe:function(a,n){return a<n},dIrct:function(a,n){return a===n},WIjeE:function(a,n){return a!==n},raLYK:t(1127),SxVQk:function(a,n,s){return a(n,s)},AMrPH:function(a,n){return a!==n},IpWTz:t(1039),ZlXTu:t(1543),wHMwJ:function(a,n){return a!==n},IrFOi:t(1648),xtQug:function(a,n){return a<<n},kPYjB:function(a,n){return a!==n},JHYpf:"sYKNP",nVVDi:function(a,n){return a===n},YNdtj:t(1404),TXyLA:"auto",fhBqv:t(1246)+t(967)+"s",dbwIX:"success",HEIRM:function(a,n,s){return a(n,s)},ZHCgD:function(a,n){return a===n},TZCrw:t(1158)+t(627),EBQMx:function(a,n){return a==n},PXprc:function(a,n){return a===n},xJbmb:"please provide v"+t(485),pQRoi:function(a,n){return a(n)},VreNl:function(a,n){return a===n},RHcou:t(429),FdVDI:t(1395),ujprw:"online",sYMBO:function(a,n){return a!==n},kcPmj:t(910),QXobR:t(1755),JrusW:"ttwid",vXZZU:"device_id",QuLdf:function(a,n){return a||n},dhFAt:function(a,n){return a==n},xHDpH:function(a){return a()},smubf:"web",ZfFOR:t(1875)+"0",YDgkn:function(a,n){return a&n},qyTnu:t(1120),iiidH:function(a,n,s){return a(n,s)},vyHnc:function(a,n){return a(n)},iMmAL:t(1541),vpYQX:t(1173),KcNPB:t(1546),sJWQI:t(1357),tUnRx:t(665),TnVGt:t(1779)+"ys",XTEGK:t(1321),ITaWn:"NXDXj",LJezr:t(1048),XrpIY:function(a,n){return a>n},XcIor:function(a,n){return a===n},fQset:t(1246)+t(1570)+"t",KWqDC:t(328),ADVYt:function(a,n){return a>=n},CaMmz:function(a,n){return a<=n},AwIEn:function(a,n){return a+n},DsswK:function(a,n){return a-n},dVPjO:function(a,n){return a<n},SnKJf:function(a,n){return a<n},xgclC:function(a,n){return a!==n},UAjEB:t(799),UHont:function(a,n){return a===n},lCatZ:t(564)+"1",LOxjO:t(1322)+"2",oaTCx:function(a,n){return a===n},vHRqf:t(1536),pelwG:function(a,n,s){return a(n,s)},QrfAi:t(628)+"ay, netw"+t(1736)+t(1771),agKHW:t(1563),ONkfM:function(a,n){return a+n},njuur:function(a,n){return a!==n},LsZkQ:"vluvs",otkpJ:function(a,n){return a+n},FfgUg:t(733)+"s instan"+t(1146)+"nitialized",AZKmd:function(a,n){return a===n},jYFCR:function(a,n){return a===n},AVhBq:t(477)+"rovide a"+t(1259)+t(1506)+t(1616)+"e a stri"+t(533)+t(1598)+"ffer",lwWfJ:t(1217),IcAwn:function(a,n){return a instanceof n},SiXDs:function(a,n){return a(n)},yevXL:function(a,n){return a(n)},NNYzI:function(a,n){return a||n},ArUce:t(477)+t(649)+t(737)+"ervice",bbwkK:function(a,n){return a instanceof n},SwtNk:function(a,n){return a===n},pEHyO:"sent",pmcGp:function(a,n){return a<n},EOPaV:t(461),Jupxo:t(470),eeSLF:t(1463),GHKTo:function(a,n){return a||n},qYfxJ:function(a,n){return a!==n},WiMYy:"manual r"+t(370)+"ing",SybOL:function(a,n){return a===n},lgUUN:t(1422),zgEjZ:t(1331),GZoEg:function(a,n){return a*n},clDJM:function(a,n){return a*n},AWrMy:function(a,n){return a===n},MSjel:"Window",WJmqn:function(a,n){return a!=n},UrXUi:"Object",xaOYm:t(349)+t(457)+t(1666)+"pe",ufozM:function(a,n){return a!=n},YkBek:function(a,n){return a!=n},uJwPY:function(a,n){return a===n},BrUFb:function(a,n){return a===n},jUIUM:t(1145)+t(1865)+t(1828),mBOLM:function(a,n){return a!=n},hVCkv:function(a,n){return a!=n},Gpegp:function(a,n,s){return a(n,s)}};Ft.r(Oe),Ft.d(Oe,{FWS:()=>wg,CustomErrorEvent:()=>al,createCloseEvent:()=>gt,ReconnectEvent:()=>ol,createErrorEvent:()=>dt,decodedFrame:()=>tn,createOpenEvent:()=>hl,CustomCloseEvent:()=>cl,createReconnectEvent:()=>ma,FrontierMessageEvent:()=>ll,encodeFrame:()=>Ut,createMessageEvent:()=>fl,OpenEvent:()=>ul,ErrorCode:()=>rn,Event:()=>sr,MessageEvent:()=>dl});let r="";function i(a=""){let n=t;if(e[n(1503)]!==e.dZeMo)_0x46d3c3[n(1126)+n(1420)]=void 0,_0x4dc985(n(376)+n(1606));else{let d=""+Date[n(1552)](),h=r||(r=f(a)),w=Math[n(1747)]()[n(1715)](16)[n(1790)](-6);return e[n(1282)](e[n(635)](e.kJqSj("02",d),h),w)}}function o(){let a=t;return e[a(591)](1e4,Date[a(1552)]())+Math.floor(e[a(844)](1e4,Math[a(1747)]()))}function c(a){let n=t;return e.LSisw(e[n(344)](Array,8)[n(1086)]("0"),parseInt(a,10)[n(1715)](2)).slice(-8)}function l(a){let n=t;return e[n(767)](e[n(344)](Array,4)[n(1086)]("0"),e[n(1855)](parseInt,a,2)[n(1715)](16)).slice(-4)}function u(a){let n=t,s=a[n(557)](/\./)[n(1336)](w=>c(w)),d=[];return d[0]=e[n(1752)](l,s[0]+s[1]),d[1]=e[n(344)](l,s[2]+s[3]),[e[n(426)],"0000",e[n(426)],e[n(426)],n(1310),e[n(958)],d[0],d[1]].join("")}function f(a){let n=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(1676)](a),d=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[n(1676)](a);return s?e[n(344)](u,a):d?e.VgwYR(x,a):n(1622)+n(1622)+n(1622)+n(1622)}function x(a){let n=t,s="",d=[],h=0,w=0,m=!0,b=e[n(426)];if(e[n(1664)](a[n(662)]("::"),-1))if(e[n(1626)](n(1071),e[n(1320)])){let p=a.split("::");for(let L=0;e[n(1628)](L,p[n(1407)]);L++){let M=p[L];if(e[n(1664)](M[n(662)](":"),0)){let G=M[n(557)](":");m&&(h=G[n(1407)]),w+=G[n(1407)];for(let J=0;J<G[n(1407)];J++)if(e[n(1292)](4,G[J][n(1407)])){let Z=b[n(1517)+"g"](0,e[n(454)](4,G[J][n(1407)])),we=Z.concat(G[J]);d[n(932)](we)}else d[n(932)](G[J]);m=!1}else{if(e[n(1292)](4,M.length)){let G=b.substring(0,e[n(602)](4,M[n(1407)])),J=G[n(1528)](M);d[n(932)](J)}else d[n(932)](M);m&&(h+=1),w+=1,m=!1}}let P="";for(let L=0;L<e[n(1027)](8,w);L++)P=P[n(1528)](b);for(let L=0;e[n(1628)](L,d[n(1407)]);L++)e[n(1626)](L,h)&&(s=s[n(1528)](P)),s=s[n(1528)](d[L]);return s}else{this["_destroy"+n(917)+"t"]();let p=_0x29c6b8(e.bZEcR,{message:e[n(1759)]});this[n(1337)+"mediatel"+n(669)+"ct"]&&this[n(1337)+n(763)+"yReconnect"](p)}{if(e[n(863)]("pBjuR",e[n(751)]))return;{let p=a[n(557)](":");for(let P=0;e[n(579)](P,p[n(1407)]);P++){let L=p[P];if(e[n(1292)](4,p[P].length)){if(e[n(1658)]!==e.muajk)return this._socket[n(530)+"ns"];{let M=b[n(1517)+"g"](0,e[n(454)](4,p[P][n(1407)])),G=M[n(1528)](L);s=s[n(1528)](G)}}else s=s[n(1528)](L)}return s}}}function g(a,n){let s=t,d={leQvr:function(m,b,p){return m(b,p)},SSIsh:function(m,b){return e[q(391)](m,b)}},h=a.key;e.yCocr(void 0,h)&&(e[s(1855)](me,n,10),e[s(1855)](U,n,h));let w=a[s(823)];w!==void 0&&(e[s(1061)](e[s(384)],e.jtwLi)?(e[s(715)](me,n,18),e.IXJtT(U,n,w)):(d[s(366)](_0x35c53a,_0x580d4e,32),d[s(366)](_0x124fdd,_0x3f061b,d.SSIsh(_0x5847d5,_0x1efc92))))}function y(a){let n=t,s={laiwt:function(h,w,m,b){return h(w,m,b)},YFPOo:n(576)+n(445),FJsgq:function(h,w,m,b){return e[n(1637)](h,w,m,b)},uEDjc:function(h,w,m,b){return e[n(1637)](h,w,m,b)},txJuO:e[n(646)],UscAa:e[n(1617)],XnDiG:e[n(331)],PVmCT:e[n(1263)]},d={};e:for(;!$(a);)if(e[n(363)]("RyGvF",e[n(358)])){let h=ge(a);switch(e[n(433)](h,3)){case 0:break e;case 1:d.key=R(a,e[n(1611)](ge,a));break;case 2:d[n(823)]=e[n(1855)](R,a,e[n(1752)](ge,a));break;default:e[n(1305)](T,a,e.uCVNU(7,h))}}else{let h=(n(1890)+n(446)+n(1287))[n(557)]("|"),w=0;for(;;){switch(h[w++]){case"0":_0x3570a9=s[n(686)](_0x28b0cf,_0x1f1e3d[_0x38bbf1[n(466)+n(1573)]],_0x1a2453,_0x20a514);continue;case"1":_0x3937d0=s.laiwt(_0x3d7e2c,_0x28be08.fromNumber(_0x56772d.cursor||_0x5df364),_0x32e2c9,_0x3a6677);continue;case"2":_0x24aa71[n(1212)](n(987)+n(1240),_0x44208a,_0x12e3f3[n(974)]);continue;case"3":_0xf97571[n(1212)](s[n(782)],_0x34031f);continue;case"4":_0x1c3033=s[n(845)](_0x144992,_0x15f551[n(466)+"ame"],_0xef7581,_0x3cf896);continue;case"5":_0x1a1d97=s[n(1864)](_0x1452b9,_0x4c103a,_0x13bcdd,_0x1ec235[n(974)]||0);continue;case"6":_0x296054[n(1212)](s[n(1382)],_0x5582f0);continue;case"7":_0x539f2d=s.FJsgq(_0x29d1eb,0,_0x1b9ab7,_0xfdd01e);continue;case"8":_0x2b6309.log(s.UscAa,_0x531743);continue;case"9":_0x26a381[n(1212)](s.XnDiG,_0x3167c5);continue;case"10":_0x5492be[n(1212)](s[n(1481)],_0x281f78);continue}break}}if(e[n(341)](void 0,d.key))throw new Error(e[n(494)]);if(e[n(937)](void 0,d[n(823)]))throw new Error(n(1610)+n(1614)+n(866)+n(823));return d}function S(a){let n=t,s=e[n(1734)](C);return _(a,s),B(s)}function _(a,n){let s=t,d={svaQe:function(fe,ae){return e[q(1345)](fe,ae)},ThIYj:function(fe,ae){return e[q(914)](fe,ae)},wkSCp:function(fe,ae){return e[q(1150)](fe,ae)},MuQYK:function(fe,ae){return e[q(433)](fe,ae)},ZxySH:function(fe,ae){return e[q(1150)](fe,ae)},rYwaL:function(fe,ae){return fe&ae},TBnPo:function(fe,ae){return e.tagqW(fe,ae)},fhWYa:function(fe,ae){return e[q(1659)](fe,ae)}},h=a[s(1455)];e[s(1567)](void 0,h)&&(e[s(1419)](me,n,8),e.cTvXN(pt,n,h));let w=a[s(1074)];e[s(1633)](void 0,w)&&(e[s(1305)](me,n,16),e.aAUpZ(pt,n,w));let m=a[s(974)];e[s(1726)](void 0,m)&&(me(n,24),e.eTOrV(pt,n,e.MUHmc(D,m)));let b=a[s(1334)];e[s(1278)](void 0,b)&&(e[s(1855)](me,n,32),e[s(1266)](pt,n,D(b)));let p=a[s(1776)];if(e[s(1695)](void 0,p))for(let fe of p){e[s(545)](me,n,42);let ae=e[s(1734)](C);e.SIdZc(g,fe,ae),e[s(1419)](me,n,ae[s(764)]),K(n,ae),O(ae)}let P=a[s(532)+"ncoding"];if(e.Gfxjh(void 0,P))if(e[s(1456)](e[s(1530)],e.wYNEC))me(n,50),e[s(549)](U,n,P);else{let fe=this[s(1372)],ae=this.low;return[d[s(1411)](fe,24),d[s(1195)](fe,16)&255,d.wkSCp(d[s(1239)](fe,8),255),d[s(1585)](255,fe),d.MuQYK(ae,24),d.rYwaL(d[s(779)](ae,16),255),d.ZxySH(ae>>>8,255),d.fhWYa(255,ae)]}let L=a[s(1700)+s(888)];e[s(1439)](void 0,L)&&(me(n,58),e[s(687)](U,n,L));let M=a[s(326)];e[s(1695)](void 0,M)&&(me(n,66),e[s(435)](me,n,M[s(1407)]),e[s(435)](oe,n,M));let G=a[s(1046)];e[s(1292)](void 0,G)&&(me(n,74),e.eTOrV(U,n,G));let J=a["serverTi"+s(422)];e.RBYWg(void 0,J)&&(e.gVGMD(me,n,82),e.TFrdm(U,n,J));let Z=a[s(901)];e[s(1633)](void 0,Z)&&(e[s(1196)](me,n,90),e.TFrdm(U,n,Z));let we=a[s(1665)+"e"];we!==void 0&&(me(n,96),e[s(1419)](pt,n,e.VgwYR(D,we)))}function v(a){return e[t(475)](I,F(a))}function I(a){let n=t,s={};e:for(;!e[n(785)]($,a);){let d=e[n(911)](ge,a);switch(e.Pitdp(d,3)){case 0:break e;case 1:s[n(1455)]=It(a,!0);break;case 2:s[n(1074)]=It(a,!0);break;case 3:s[n(974)]=ge(a);break;case 4:s[n(1334)]=e[n(1250)](ge,a);break;case 5:{let h=e.RJvhW(A,a);(s[n(1776)]||(s[n(1776)]=[])).push(e[n(1752)](y,a)),a[n(764)]=h;break}case 6:s[n(532)+"ncoding"]=R(a,e[n(911)](ge,a));break;case 7:s[n(1700)+n(888)]=e.IfKlO(R,a,e[n(1450)](ge,a));break;case 8:s[n(326)]=e[n(555)](se,a,e.AMaFH(ge,a));break;case 9:s[n(1046)]=e.LWDhR(R,a,e.rLbri(ge,a));break;case 10:s[n(899)+"ming"]=e[n(549)](R,a,e[n(1101)](ge,a));break;case 11:s.msgID=e[n(604)](R,a,ge(a));break;case 12:s[n(1665)+"e"]=ge(a);break;default:e[n(874)](T,a,e[n(407)](7,d))}}if(e[n(341)](void 0,s[n(1455)]))throw new Error(e[n(1013)]);if(s[n(1074)]===void 0)throw new Error(e[n(613)]);if(e[n(1626)](void 0,s[n(974)]))throw new Error(e[n(351)]);if(s[n(1334)]===void 0)throw new Error(e.nHBgv);return s}function A(a){let n=t,s=e[n(1250)](ge,a),d=a[n(764)];return a[n(764)]=a[n(316)]+s,d}function T(a,n){let s=t;if(s(847)===s(847))switch(n){case 0:for(;e[s(407)](128,e[s(475)](te,a)););break;case 2:V(a,e[s(1349)](ge,a));break;case 5:e[s(1368)](V,a,4);break;case 1:e[s(1855)](V,a,8);break;default:throw new Error(s(833)+s(611)+s(1612)+n)}else this._ws&&this[s(1551)][s(596)](_0xab6e5d),this[s(1198)](e.qSduL,_0x3ea542)}function D(a){let n=t;return a|=0,{low:a,high:e[n(616)](a,31),unsigned:e.edmmt(a,0)}}let E=[];function C(){let a=t,n=E[a(529)]();return n?(n[a(316)]=n[a(764)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){let n=t;n(965)!==n(793)?E[n(932)](a):this[n(724)](_0x46baab,_0x487f5a)}function F(a){return{bytes:a,offset:0,limit:a.length}}function B(a){let n=t,s=a[n(1772)],d=a.limit;return e.bPRRt(s[n(1407)],d)?s:s[n(1591)](0,d)}function V(a,n){let s=t,d={SUUlJ:function(h,w){return e[q(1326)](h,w)},KzeWr:function(h,w){return h===w},uDtfb:s(575)};if(e[s(363)](e[s(1413)],s(1574))){if(e[s(725)](e.hVtZd(a[s(316)],n),a[s(764)]))throw new Error(e.TDdhS);a[s(316)]+=n}else{let h=d[s(1446)](_0x15dbcd,_0x41bc01);this._ws&&d[s(776)](this[s(1551)][s(713)+"te"],this[s(1344)])&&(this[s(1551)]&&this[s(1551)].send(h),this[s(1198)](d.uDtfb,_0x34e00a))}}function $(a){let n=t;return a[n(316)]>=a[n(764)]}function re(a,n){let s=t,d=a[s(1772)],h=a[s(316)],w=a[s(764)],m=e[s(767)](h,n);if(e[s(725)](m,d.length)){let b=new Uint8Array(e[s(844)](2,m));b[s(1680)](d),a[s(1772)]=b}return a[s(316)]=m,m>w&&(a[s(764)]=m),h}function Q(a,n){let s=t,d=a[s(316)];if(e[s(1788)](e.kJqSj(d,n),a[s(764)]))throw new Error(s(667)+s(1236));return a.offset+=n,d}function se(a,n){let s=t,d=e[s(1139)](Q,a,n);return a[s(1772)][s(1591)](d,e[s(1090)](d,n))}function oe(a,n){let s=t,d=e[s(614)](re,a,n[s(1407)]);a[s(1772)].set(n,d)}function R(a,n){let s=t,d={vYPyV:"error",jQmxz:e[s(1044)]},h=e[s(1419)](Q,a,n),w=String[s(759)+s(755)],m=a.bytes,b="\uFFFD",p="";for(let P=0;e[s(691)](P,n);P++){let L=m[e[s(678)](P,h)],M,G,J,Z;if(e.dfnHK(e[s(407)](128,L),0))p+=e[s(1426)](w,L);else if(e[s(377)](224&L,192))if(e.BEjdP(P+1,n))p+=b;else if(M=m[e.hHloP(e.VlEiA(P,h),1)],e[s(407)](192,M)!==128)p+=b;else if(e[s(1527)](e[s(929)],s(1366)))if(Z=e[s(509)](e[s(325)](31&L,6),e[s(581)](63,M)),e[s(1852)](Z,128))p+=b;else if(e[s(863)](e[s(548)],e[s(913)])){if(!this[s(1350)+s(1418)]()||this[s(804)+"osed"])return;this[s(841)+s(1653)]?.[s(1670)+s(747)+"fig"](),this["_pingLos"+s(620)]?.[s(1314)+s(1489)](),this[s(1551)]?this[s(1572)+s(821)](1001,e[s(806)],!0):this[s(744)]()}else p+=w(Z),P++;else _0x2f2906["removeEv"+s(864)+s(1499)](s(401),_0x465fc0),_0x4b0a9b[s(1193)+s(864)+s(1499)](cmSBIq[s(387)],_0x4455ff),_0x100667[s(1193)+s(864)+s(1499)](cmSBIq[s(722)],_0x36c404);else e.nlJWQ(e[s(1150)](240,L),224)?e[s(1462)](P+2,n)?p+=b:(M=m[e[s(1440)](P+h,1)],G=m[e[s(678)](P+h,2)],e[s(1108)](e[s(1550)](M,G<<8),49344)!==32896?p+=b:(Z=e[s(509)](e.wNQMd(e[s(407)](15,L),12)|e[s(1119)](e[s(1150)](63,M),6),e[s(336)](63,G)),e[s(1672)](Z,2048)||e.edmmt(Z,55296)&&Z<=57343?p+=b:(p+=e[s(911)](w,Z),P+=2))):e[s(561)](248&L,240)?e[s(955)](e[s(1092)](P,3),n)?p+=b:(M=m[e.zvBEh(P+h,1)],G=m[e[s(1092)](P+h,2)],J=m[e[s(1400)](e[s(883)](P,h),3)],e.OGSnv(e[s(1662)](e.sGUoF(M,e[s(1878)](G,8)),e.uShkY(J,16)),12632256)!==8421504?p+=b:(Z=e.xmYJJ(e[s(558)](e[s(407)](7,L),18),e[s(1474)](e[s(336)](63,M),12))|e[s(336)](63,G)<<6|e[s(1659)](63,J),e[s(1478)](Z,65536)||Z>1114111?p+=b:(Z-=65536,p+=e[s(787)](w,e[s(616)](Z,10)+55296,e[s(1400)](1023&Z,56320)),P+=3))):p+=b}return p}function U(a,n){let s=t,d=n.length,h=0;for(let b=0;e[s(708)](b,d);b++){let p=n[s(1589)+"At"](b);e[s(1774)](p,55296)&&e[s(1595)](p,56319)&&e[s(772)](b,1)<d&&(p=e[s(1027)](e.LSisw(e.LwASu(p,10),n[s(1589)+"At"](++b)),56613888)),h+=e[s(1268)](p,128)?1:e[s(1478)](p,2048)?2:e[s(1628)](p,65536)?3:4}e[s(1593)](me,a,h);let w=e.aRDHZ(re,a,h),m=a[s(1772)];for(let b=0;e[s(810)](b,d);b++)if(e[s(379)]!==e[s(663)]){let p=n[s(1589)+"At"](b);e.phkfw(p,55296)&&e[s(935)](p,56319)&&e[s(678)](b,1)<d&&(p=e[s(1584)](e.LnSfq(e[s(710)](p,10),n[s(1589)+"At"](++b)),56613888)),e[s(1886)](p,128)?m[w++]=p:(e[s(1672)](p,2048)?m[w++]=e[s(1550)](e[s(1453)](p>>6,31),192):(e[s(1672)](p,65536)?m[w++]=e[s(1557)](e[s(1659)](e[s(1304)](p,12),15),224):(m[w++]=e[s(509)](e[s(581)](e[s(534)](p,18),7),240),m[w++]=e[s(479)](e[s(447)](e[s(616)](p,12),63),128)),m[w++]=e.xmYJJ(e.QPMJq(p>>6,63),128)),m[w++]=e[s(1394)](e[s(336)](63,p),128))}else _0x262322[s(1212)](_0x41c4ab)}function K(a,n){let s=t,d=re(a,n[s(764)]),h=a.bytes,w=n.bytes;for(let m=0,b=n[s(764)];e[s(771)](m,b);m++)h[m+d]=w[m]}function te(a){let n=t;return a.bytes[e[n(997)](Q,a,1)]}function et(a,n){let s=t,d=e.HPMAE(re,a,1);a[s(1772)][d]=n}function ge(a){let n=t;if(e[n(1223)]===n(1630))return new _0x465774(_0x3ccdcf,{data:_0x25aef2});{let s=0,d=0,h;do h=e[n(701)](te,a),e.giYeR(s,32)&&(d|=(127&h)<<s),s+=7;while(128&h);return d}}function me(a,n){let s=t;for(n>>>=0;e[s(1359)](n,128);)e.qHonM(et,a,e[s(1557)](e.uCVNU(127,n),128)),n>>>=7;e[s(338)](et,a,n)}function It(a,n){let s=t;if(e[s(527)]!==s(1401)){let d=0,h=0,w=0,m;if(m=te(a),d=e[s(1211)](127,m),e[s(1879)](128,m)&&(m=e.RJvhW(te,a),d|=e[s(641)](127,m)<<7,e[s(1834)](128,m)&&(m=te(a),d|=e.upGEg(e[s(447)](127,m),14),e[s(501)](128,m)&&(m=e[s(1248)](te,a),d|=e.mvuDE(e.ZNFOL(127,m),21),e[s(1150)](128,m)&&(m=e[s(689)](te,a),h=e[s(1108)](127,m),e[s(1723)](128,m)&&(m=te(a),h|=e.EmuDM(127,m)<<7,e[s(584)](128,m)))))))if(e[s(1527)](e.noSXP,"ypikG")){if(m=e[s(469)](te,a),h|=e[s(1878)](e[s(1409)](127,m),14),e[s(407)](128,m)){if(e[s(692)](e[s(550)],s(375)))return e[s(1798)](this.count,this[s(1465)+s(651)]);m=e.AMaFH(te,a),h|=e[s(396)](e[s(373)](127,m),21),128&m&&(m=e[s(677)](te,a),w=e.nVgXW(127,m),e[s(1834)](128,m)&&(m=e[s(1261)](te,a),w|=e[s(345)](e.nOeny(127,m),7)))}}else{let{value:b,offset:p}=e[s(622)](_0x4520c8,_0x411e65,_0x5e0bc6);_0x39ae8b=p,_0x538ce3=e[s(1544)](e.uShkY(_0x1d71e5,8),0),_0x7184a6+=b}return{low:d|e.IivgU(h,28),high:h>>>4|e[s(1827)](w,24),unsigned:n}}else{e[s(1096)](_0xe29b5e,_0x17eb7f,42);let d=_0x4bbb6c();e[s(648)](_0x3f93d6,_0x544c94,d),e[s(1467)](_0x1a4383,_0x6af406,d[s(764)]),e[s(435)](_0x426956,_0x4488e2,d),e.rLbri(_0x55866e,d)}}function pt(a,n){let s=t,d=e.smdDS(n[s(735)],0),h=e[s(1414)](e[s(1749)](n[s(735)],28),e[s(413)](n[s(1372)],4))>>>0,w=e.Vyvka(n[s(1372)],24),m=e[s(919)](0,w)?e[s(1510)](0,h)?d<16384?d<128?1:2:e[s(895)](d,2097152)?3:4:e[s(1886)](h,16384)?h<128?5:6:e.PdsUB(h,2097152)?7:8:e[s(1852)](w,128)?9:10,b=e.ZAIYM(re,a,m),p=a[s(1772)];switch(m){case 10:p[b+9]=e[s(1131)](w,7)&1;case 9:p[e.xBPzp(b,8)]=e[s(1199)](9,m)?e.gEFMY(128,w):e[s(1453)](127,w);case 8:p[e[s(1822)](b,7)]=m!==8?e[s(1557)](h>>>21,128):e[s(1800)](e.qvVWD(h,21),127);case 7:p[e.xBPzp(b,6)]=e[s(1164)](7,m)?e[s(362)](h,14)|128:e.pHKpo(e[s(1345)](h,14),127);case 6:p[b+5]=e[s(1278)](6,m)?e[s(1216)](h,7)|128:e[s(1723)](e[s(1599)](h,7),127);case 5:p[e[s(567)](b,4)]=e.IuoIp(5,m)?e[s(968)](128,h):e[s(830)](127,h);case 4:p[e[s(1844)](b,3)]=e[s(1753)](4,m)?d>>>21|128:e[s(1522)](d>>>21,127);case 3:p[e[s(403)](b,2)]=m!==3?e[s(968)](e.sNDfP(d,14),128):e.EmuDM(d>>>14,127);case 2:p[b+1]=e[s(1272)](2,m)?e.sPqaR(e[s(1384)](d,7),128):e[s(1271)](d,7)&127;case 1:p[b]=m!==1?e.xmYJJ(128,d):e[s(1854)](127,d)}}function tn(a){return e[t(540)](v,a)}function Ut(a){return S(a)}let nn=65536,Qr="\0\0\0\0\0\0\0\0",Ee=e[t(1831)](nn,nn),Te=e[t(1183)](Ee,Ee),ir=Te/2,Ne=String[t(337)+"e"].charCodeAt;class he{constructor(n,s,d){let h=t;this[h(1115)]=!0,this[h(735)]=e[h(1814)](0,n),this[h(1372)]=0|s,this[h(1661)]=!!d}static[t(1115)](n){return n&&e[t(1435)](!0,n.isLong)}static[t(1364)](n,s,d){return new he(n,s,d)}static[t(1244)+"s"](n,s,d){let h=t;return d?he[h(1244)+h(367)](n,s):he[h(1244)+"sBE"](n,s)}static[t(1244)+t(367)](n,s){let d=t;return new he(e[d(1414)](e[d(969)](e.dTWFK(n[0],n[1]<<8),e[d(558)](n[2],16)),e[d(1691)](n[3],24)),e[d(968)](e[d(1306)](n[4]|e[d(1878)](n[5],8),e[d(1808)](n[6],16)),e[d(1602)](n[7],24)),s)}static[t(1244)+t(1207)](n,s){let d=t;return new he(e[d(1466)](e[d(640)](e[d(1119)](n[4],24),n[5]<<16)|e[d(1161)](n[6],8),n[7]),e[d(1814)](e[d(1306)](n[0]<<24,e[d(345)](n[1],16)),n[2]<<8)|n[3],s)}static[t(922)](n){let s=t;return n===Qr?sl:new he(e[s(1271)](e.Wvmwf(e[s(1234)](e[s(1135)](Ne[s(903)](n,0),e[s(1827)](Ne.call(n,1),8)),e.fLXjf(Ne[s(903)](n,2),16)),Ne[s(903)](n,3)<<24),0),e[s(1384)](e[s(1135)](e[s(400)](e.wuikP(Ne.call(n,4),e[s(1036)](Ne.call(n,5),8)),e[s(1808)](Ne[s(903)](n,6),16)),e[s(573)](Ne[s(903)](n,7),24)),0),!0)}[t(1472)](){let n=t;return String[n(759)+n(755)](e[n(1879)](255,this[n(735)]),e[n(1836)](e[n(1327)](this.low,8),255),e.ZNFOL(e[n(433)](this.low,16),255),e[n(1544)](this[n(735)],24),255&this[n(1372)],e[n(881)](e.LRthl(this[n(1372)],8),255),e[n(830)](this.high>>>16,255),this[n(1372)]>>>24)}static[t(1204)+"er"](n,s=!0){let d=t;if(e.QbyQZ!==e.GlpFk){if(e.zsnsH(isNaN,n))return s?Rp:sl;if(s){if(d(1143)!==e[d(1015)])return this[d(1551)]?this[d(1551)][d(713)+"te"]:this._options[d(1072)+d(631)]?this[d(1323)+"NG"]:this[d(1685)];if(e[d(798)](n,Te))return Pp}else if(e[d(970)]!=="vGpKT"){if(e.PxrRT(n,-ir))return Op;if(e.SPCDz(e.tflof(n,1),ir))return Dp}else throw this[d(744)+d(1188)]=!1,_0xb14caa;return he[d(1364)](e[d(1686)](n%Ee,0),e[d(400)](e.bYkvl(n,Ee),0),s)}else return{bytes:_0x598c31,offset:0,limit:_0x5050f7[d(1407)]}}[t(812)](){let n=t,s={eomoC:function(d,h){return e[q(865)](d,h)}};return e.JQKIJ(e[n(606)],n(698))?(_0x131ced[n(1493)](CLQjpG[n(1167)](_0x5ccaa0,this),_0xa88557),CLQjpG[n(1167)](_0x41cc92,_0x1ccb65[n(1546)](this))):this[n(1661)]?e[n(856)](e[n(324)](this[n(1372)],0),Ee)+e[n(1260)](this[n(735)],0):e.zaKiK(e[n(590)](this[n(1372)],Ee),e[n(1098)](this[n(735)],0))}[t(1851)](){let n=t;return e[n(1456)](0,this.high)&&e[n(937)](0,this.low)}add(n){let s=t,d={UeRux:function(h,w){return h<<w},ZgMAL:function(h,w){return h&w},PvbCb:function(h,w){return e[q(1296)](h,w)},FuQlk:function(h,w){return h<w},oMRbj:function(h,w){return e[q(1596)](h,w)}};if(e.UXdvy!==e.UXdvy)_0x2964ab=AjmxIA[s(539)](AjmxIA[s(1303)](31,_0x181304),6)|AjmxIA[s(388)](63,_0x249526),AjmxIA[s(959)](_0x535d6c,128)?_0x592aee+=_0x3cec4f:(_0xc6cdfc+=AjmxIA.oMRbj(_0x4446d2,_0x3d21b5),_0x2c5831++);else{he[s(1115)](n)||(n=he[s(1204)+"er"](n));let h=e.lfBYz(this.high,16),w=e[s(1453)](65535,this[s(1372)]),m=this.low>>>16,b=e.MQmpX(65535,this[s(735)]),p=e[s(1761)](n[s(1372)],16),P=e[s(320)](65535,n[s(1372)]),L=e[s(1260)](n[s(735)],16),M=e[s(1004)](65535,n.low),G=0,J=0,Z=0,we=0;return we+=e[s(1079)](b,M),Z+=e[s(1301)](we,16),we&=65535,Z+=e[s(1756)](m,L),J+=Z>>>16,Z&=65535,J+=e[s(1780)](w,P),G+=e[s(1098)](J,16),J&=65535,G+=e.APKqq(h,p),G&=65535,he[s(1364)](e[s(1620)](e.IivgU(Z,16),we),e[s(1135)](e[s(766)](G,16),J),this.unsigned)}}[t(936)](n){let s=t;return he.isLong(n)||(n=he[s(1204)+"er"](n)),this[s(1661)]!==n[s(1661)]&&e[s(1510)](this[s(1372)]>>>31,1)&&e[s(1527)](e[s(428)](n[s(1372)],31),1)?!1:e.PqrGC(this[s(1372)],n.high)&&this[s(735)]===n.low}[t(1054)](){let n=t;return e[n(1102)](-1,this[n(735)])&&this[n(1372)]===-1?he[n(1364)](0,0,this[n(1661)]):e[n(1435)](-1,this[n(735)])?he.fromBits(0,e[n(1282)](this.high,1),this[n(1661)]):he[n(1364)](e[n(1092)](this.low,1),this[n(1372)],this.unsigned)}toBytes(n){let s=t;if(e[s(1743)](e[s(1023)],e.naNYh))return n?this[s(1609)+"E"]():this.toBytesBE();this[s(1823)+"ileName"]=_0x536ac9}[t(1609)+"E"](){let n=t,s=this[n(1372)],d=this[n(735)];return[e[n(1247)](255,d),e[n(502)](e[n(1739)](d,8),255),e[n(1098)](d,16)&255,e.sgBXe(d,24),e.dBmcV(255,s),e[n(324)](s,8)&255,e[n(407)](e.BUDtv(s,16),255),e[n(1280)](s,24)]}[t(1389)+"E"](){let n=t,s=this.high,d=this[n(735)];return[s>>>24,e.UPQXF(s>>>16,255),e.zsnWR(e.BUDtv(s,8),255),e[n(1521)](255,s),e[n(1608)](d,24),e[n(791)](e[n(571)](d,16),255),e.oRpRX(e[n(770)](d,8),255),255&d]}}let sl=new he(0,0,!1),Rp=new he(0,0,!0),Dp=he.fromBits(-1,2147483647,!1),Pp=he[t(1364)](-1,-1,!0),Op=he.fromBits(0,-2147483648,!1);var rn=(function(a){let n=t;return a[a[e.lQOVg]=5001]="NATIVE_E"+n(1026),a[a[e[n(905)]]=5002]=e[n(905)],a[a[e[n(619)]]=5003]=e[n(619)],a[a[n(1348)+n(1288)]=5004]=n(1348)+"ERROR",a[a[e[n(688)]]=5005]=e[n(688)],a})({});class sr{constructor(n){let s=t,d={AoPgL:function(h,w){return e[q(585)](h,w)},dndVb:function(h,w){return e[q(1004)](h,w)}};e[s(1539)]===e[s(546)]?(_0x370899[_0x2cd457++]=mYFJzN[s(1043)](mYFJzN[s(1484)](_0x346259>>18,7),240),_0x13f02e[_0x165089++]=mYFJzN[s(1484)](_0x188b8f>>12,63)|128):(this[s(327)]=n,this[s(1889)]=null)}}class ol extends sr{constructor(n,s){let d=t;super(n),this[d(736)]=s&&s[d(736)]||null}}class al extends sr{constructor(n,s){let d=t;super(n),this[d(1069)]=s&&s.error||null,this[d(1460)]=s&&s[d(1460)]||0,this[d(902)]=s&&s[d(902)]||"",this[d(1473)]=s&&s[d(1473)]||0,this[d(736)]=s&&s.message||"",this[d(1105)]=s&&s[d(1105)]||5001}}class cl extends sr{constructor(n,s){let d=t;super(n),this[d(1105)]=s&&s[d(1105)]||0,this[d(1606)]=s&&s[d(1606)]||"",this[d(1290)]=s&&s[d(1290)]||!1,this[d(1171)+d(831)]=s&&s[d(1171)+d(831)]||!1}}class dl extends sr{constructor(n,s){let d=t;super(n),this[d(815)]=s&&s[d(815)]||null}}class ll extends dl{constructor(n,s){let d=t;super(n),this[d(815)]=s&&s[d(815)]||null,this[d(736)]=s&&s[d(736)]||null}}class ul extends sr{constructor(n,s){let d=t;e[d(1203)](e[d(1869)],e[d(1869)])?(super(n),this[d(815)]=s&&s.data||null):_0x5df468[d(1399)+"d"]&&(this["_navigat"+d(1418)]()&&(!this[d(1551)]||e[d(1292)](this._ws[d(713)+"te"],this.OPEN)||e.ddHZk(this[d(1551)][d(713)+"te"],this[d(1323)+"NG"]))&&this[d(482)+d(395)](),this[d(1134)+"er"]&&_0x7820d5[d(1509)+"Listener"]("online",this[d(482)+d(395)]),this[d(1134)+"er"]&&_0x2db010[d(1509)+d(1559)](e.xNGap,this[d(482)+d(1208)]))}}function dt(a,{message:n,code:s,error:d}){return new al(a,{message:n,code:s,error:d})}function gt(a,{code:n,reason:s,wasClean:d,willReconnect:h}){return new cl(a,{code:n,reason:s,wasClean:d,willReconnect:h})}function fl(a,{data:n,message:s}){let d=t;return e[d(1567)](e[d(1332)],e[d(1264)])?new ll(a,{data:n,message:s}):new _0x5fca2b(_0x597c57,_0x1ae17b,_0x489c1c)}function hl(a,{data:n}){return new ul(a,{data:n})}function ma(a,{message:n}){return new ol(a,{message:n})}class xl{constructor(n,s){let d=t;this.endpoints=n,this.maxRetries=s,this[d(789)+d(718)]=0,this["currentE"+d(858)+d(1289)+"t"]=0}[t(1670)+t(747)+"fig"](){let n=t;this[n(789)+n(718)]=0,this[n(1764)+n(858)+n(1289)+"t"]=0}resetTries(){let n=t;if(e.yCocr(e.gzjAW,e[n(1103)])){let s={SQYeQ:function(d,h){return PBuhzc.RJvhW(d,h)}};return function(...d){let h=n;return _0x571ea0.apply(_0x4b2724(this),d),s[h(440)](_0x513a69,_0x500cbd.get(this))}}else this[n(1764)+n(858)+n(1289)+"t"]=0}[t(346)+t(1548)+"nt"](){let n=t,s={ZQBpi:function(d,h,w){return e[q(1305)](d,h,w)},JUdho:function(d,h){return d<h},iprpy:function(d,h){return d+h}};if(e.kQNXq!==e[n(1781)]){let d=PCpaUI[n(330)](_0x593af9,_0xd74e74,_0x404a55[n(764)]),h=_0x2a888a[n(1772)],w=_0x3ab20f.bytes;for(let m=0,b=_0x462883.limit;PCpaUI[n(1625)](m,b);m++)h[PCpaUI[n(1018)](m,d)]=w[m]}else return this.endpoints[this[n(789)+"ndex"]]}["getCurre"+t(1548)+"ntTriesCount"](){let n=t;return this[n(1764)+n(858)+n(1289)+"t"]}[t(1024)+t(992)+"es"](){let n=t;return!!(e[n(554)](this[n(789)+n(718)],this[n(1056)+"s"][n(1407)])||e.HeRWg(this[n(789)+"ndex"],e.pPJvu(this[n(1056)+"s"][n(1407)],1))&&e.oSIlT(this[n(1764)+n(858)+n(1289)+"t"],this.maxRetries))}[t(962)+t(988)+t(1841)+t(1498)+t(657)](){let n=t,s={zWdlt:function(d,h,w){return e[q(715)](d,h,w)},kXfMG:e[n(465)],jkqsT:function(d,h,w){return e[n(1096)](d,h,w)}};if(e[n(1699)]===e[n(769)]){let d=s[n(714)](_0x36edce,s[n(523)],{message:this[n(594)+n(872)+n(1815)](_0x1a108d)});this[n(985)](s[n(523)],d);let h=s[n(1376)](_0xb1e39c,n(1769),{reason:this[n(594)+"rrorMess"+n(1815)](_0x40e966)});this[n(985)]("close",h)}else return e[n(521)](this[n(789)+n(718)],this[n(1056)+"s"][n(1407)])?!0:e[n(1882)](this[n(1764)+n(858)+n(1289)+"t"],this.maxRetries)}["replaceBackupEnd"+t(836)+t(839)+t(1308)](){let n=t;return this["currentE"+n(858)+n(1289)+"t"]=1,this[n(789)+"ndex"]++,this[n(1056)+"s"][this["currentI"+n(718)]]}[t(346)+t(1548)+"ntAndUpdateCount"](){let n=t,s={bdQBx:function(d,h,w){return d(h,w)}};if(e[n(1766)](n(868),n(868)))return this[n(1764)+n(858)+n(1289)+"t"]++,this[n(346)+n(1548)+"nt"]();{let d=JQBAaH.bdQBx(_0x361e60,_0x5b0270,_0x25f6c0);return _0xe18978.bytes[n(1591)](d,d+_0x484dcb)}}}let or=(e.POcjp!=typeof globalThis&&e[t(1206)](t(1607),globalThis[t(1519)+t(855)][t(445)])||e[t(1820)]("undefined",typeof window)&&e[t(1205)](e.MSjel,window[t(1519)+t(855)][t(445)]))&&e[t(1601)]("undefined",typeof document),On=e.amGLW(e[t(490)],typeof globalThis)&&(e[t(341)](e[t(807)],globalThis[t(1519)+t(855)][t(445)])||e[t(906)](e[t(1688)],globalThis[t(1519)+t(855)][t(445)]))&&e[t(857)](e[t(490)],typeof tt),ei=(e[t(1367)](e.POcjp,typeof globalThis)&&e[t(341)](t(1022),globalThis[t(1519)+t(855)][t(445)])||e.yRXdG(t(661)+"d",typeof globalThis)||e[t(1367)](e[t(490)],typeof globalThis)&&!!globalThis[t(1355)+"Bridge"])&&e[t(857)](t(661)+"d",typeof wx),ti=e[t(1529)](e[t(490)],typeof globalThis)&&(e[t(1768)](e[t(1688)],globalThis[t(1519)+"tor"][t(445)])||e[t(1219)](t(417)+t(1397)+t(1189),globalThis[t(1519)+t(855)][t(445)])||e[t(1597)](e[t(1385)],globalThis["construc"+t(855)][t(445)]))&&e[t(572)](e.POcjp,typeof self),Lp=e.YkBek(e.POcjp,typeof globalThis)&&e[t(1435)](e[t(807)],globalThis.constructor[t(445)])&&e[t(490)]!=typeof global&&e[t(1597)](e[t(807)],global[t(1519)+t(855)].name)&&e[t(825)](e[t(490)],typeof process)&&!!process[t(986)];class wa{constructor(){let n=t;this[n(1767)+"rs"]={}}[t(985)](n,...s){let d=t,h={xhxGT:function(w,m){return w instanceof m},MEWls:d(1748)+"in;chars"+d(720),CmTZB:e[d(637)],wVlyM:e[d(1080)],LUMSv:e.kBoTe,DwFWG:e[d(603)],SDhag:e.FjADN,ikKsE:function(w,m,b,p){return e[d(1637)](w,m,b,p)}};if(e[d(610)]===e[d(610)]){let w=this[d(1767)+"rs"][n];if(w)w[d(1790)]()[d(1858)](m=>m.fn[d(1493)](m[d(1330)],s));else if(e[d(339)](e[d(465)],n)&&!this.onerror){let m=s[d(1407)]&&s[0];if(e.GtapL(m,Error))throw m;let b=new Error(e[d(1299)](e.Cxhuz,m?e[d(1582)](e[d(403)](" (",m[d(736)]),")"):""));throw b[d(1005)]=m,m}return this}else{let w=h.xhxGT(this._options["payloadE"+d(1293)],_0x5b4432)?{force:!!this._options["payloadE"+d(1293)][d(364)],encoding:this[d(1224)][d(532)+"ncoding"][d(1867)]?this[d(1224)][d(532)+d(1293)][d(1867)][d(827)](/\s/g,"")["toLowerC"+d(1267)]():""}:{force:!1,encoding:this[d(1224)][d(532)+d(1293)]?this[d(1224)]["payloadE"+d(1293)][d(827)](/\s/g,"").toLowerCase():""},m=_0x100acd[d(532)+"ncoding"]?_0xfe85c9[d(532)+d(1293)].replace(/\s/g,"")["toLowerC"+d(1267)]():"",b=this[d(1224)][d(1700)+d(888)]instanceof _0x4ef2b8?{force:!!this._options[d(1700)+d(888)][d(364)],type:this._options[d(1700)+d(888)][d(327)]?this._options["payloadT"+d(888)][d(327)].replace(/\s/g,"")[d(1461)+d(1267)]():""}:{force:!1,type:this[d(1224)][d(1700)+d(888)]?this[d(1224)][d(1700)+d(888)][d(827)](/\s/g,"")[d(1461)+"ase"]():""},p=_0x25f5b5["payloadT"+d(888)]?_0x2c2cb8[d(1700)+d(888)][d(827)](/\s/g,"")[d(1461)+d(1267)]():"",P=b.force?b[d(327)]:p||b[d(327)],L=w[d(364)]?w[d(1867)]:m||w.encoding,M=[h[d(1508)],h[d(1514)],h.wVlyM,h[d(826)]],G=[h.DwFWG,h[d(1285)]];this[d(1224)]["enableTr"+d(1388)+"extPayload"]&&M[d(317)](P)&&(!L||G[d(317)](L))?_0x57fe27[d(552)+"oad"]=h[d(1868)](_0x3386ee,_0x51349a[d(326)],0,_0xe7ef5a.payload[d(1232)+"th"]):_0x18cebc[d(552)+d(1100)]=""}}[t(724)](n,s){let d=t;if(n===void 0)this._listeners={};else if(e[d(1789)](void 0,s))this[d(1767)+"rs"][n]=null;else{let h=this[d(1767)+"rs"][n];if(h)for(let w=0;e[d(1515)](w,h[d(1407)]);)e[d(1650)](h[w].fn,s)?h[d(1816)](w,1):++w}return this}on(n,s,d){let h=t;return(this._listeners[n]||(this[h(1767)+"rs"][n]=[])).push({fn:s,ctx:d||this}),this}}class Np extends wa{[t(594)+t(872)+t(1815)](n){let s=t;return n[s(617)]||n[s(1225)]?(s(1128)+" "+(n[s(617)]||"")+s(984)+(n[s(1225)]||""))[s(329)]():JSON.stringify(n)}constructor(n,s,d){let h=t;super(),this[h(696)]=null,ei&&wx[h(719)+h(644)]&&(this[h(696)]=wx[h(719)+h(644)]({url:n,protocols:s,header:d,fail:this[h(1712)+"ocketFai"+h(1692)][h(547)](this),success:this[h(1712)+"ocketSuc"+h(800)+h(369)][h(547)](this)})),On&&tt[h(719)+"ocket"]&&(this[h(696)]=tt[h(719)+h(644)]({url:n,protocols:s,header:d,fail:this[h(1712)+"ocketFai"+h(1692)][h(547)](this),success:this[h(1712)+h(876)+h(800)+h(369)].bind(this)}))}[t(1712)+t(876)+t(800)+t(369)](){let n=t;Promise[n(474)]()[n(862)](()=>{let s=n,d={aAflE:s(354),MWMIj:s(1395),bMFOr:e[s(957)]};e[s(680)]!==s(1084)?(this[s(1134)+"er"]&&_0x465a45[s(1509)+"Listener"](d[s(843)],this[s(482)+"nLine"]),this[s(1134)+"er"]&&_0x3bd12a[s(1509)+s(1559)](s(536),this["_handleO"+s(1208)]),this[s(1134)+"er"]&&_0x55ddb6[s(1509)+s(1559)](d[s(512)],this[s(511)+"ageHide"]),this._isBrowser&&_0x10fc8[s(1509)+"Listener"](d[s(1258)],this[s(511)+s(1861)])):this[s(781)+s(1433)]()})}[t(1712)+"ocketFailHandler"](n){let s=t,d={ENatX:e[s(1542)],dzWRN:function(h,w){return e[s(1093)](h,w)},cEsQq:e[s(979)],REFky:function(h,w,m){return e[s(1744)](h,w,m)},kawyj:e[s(465)],xkynl:function(h,w,m){return h(w,m)},LqDvv:e[s(460)]};Promise[s(474)]()[s(862)](()=>{let h=s,w={FIXid:d.ENatX};if(d[h(1257)](h(1125),d.cEsQq))switch(_0x137b3c){case w[h(1821)]:case h(1682):return{[h(1381)+_0x580ebe]:1,"x-tt-env":_0x456d8e};default:return{}}else{let m=d.REFky(dt,"error",{message:this[h(594)+h(872)+"age"](n)});this[h(985)](d[h(1083)],m);let b=d.xkynl(gt,d[h(1324)],{reason:this[h(594)+"rrorMess"+h(1815)](n)});this[h(985)](d[h(1324)],b)}})}[t(781)+t(1433)](){let n=t,s={YyHXd:e[n(460)],xLpQs:function(d,h){return e[n(339)](d,h)},oMygt:e[n(630)],Kuyut:function(d,h,w){return d(h,w)},cQvJL:e[n(1526)]};this[n(696)][n(975)](d=>{let h=n;this[h(985)](e[h(1063)],hl(e.srEla,{...d,data:d[h(617)]||""}))}),this[n(696)][n(699)](d=>{let h=n;this[h(985)](s[h(741)],gt(s[h(741)],{...d}))}),this[n(696)][n(1165)+"e"](d=>{let h=n;if(s[h(1487)](s.oMygt,"MRfOd"))try{this._qosDB?.[h(1769)](),this[h(559)]=void 0}catch(w){_0xb8d322.log(w)}else this[h(985)]("message",s[h(1505)](fl,s.cQvJL,{...d}))}),this._socket[n(348)](d=>{let h=n;this[h(985)](h(1069),e[h(1197)](dt,e[h(465)],{...d,message:d[h(617)]||""}))})}[t(596)](n){let s=t,d={VunNG:e.pzbLN,vnOGd:function(h,w,m){return e[q(1652)](h,w,m)},eZpzA:function(h,w,m){return h(w,m)}};if(e.OmVPf(n,Uint8Array)){let h=n[s(566)][s(1790)](n[s(1636)+"et"],e[s(1765)](n[s(1232)+"th"],n[s(1636)+"et"]));this[s(696)]&&this._socket.send({data:h,fail:w=>{let m=s;this[m(985)](d[m(1107)],d[m(1507)](dt,d[m(1107)],{message:this["_formatE"+m(872)+m(1815)](w)}))}})}else this[s(696)]&&this._socket[s(596)]({data:n,fail:h=>{let w=s;this[w(985)](w(1069),d[w(1052)](dt,d[w(1107)],{message:this["_formatE"+w(872)+w(1815)](h)}))}})}[t(1769)](n,s){let d=t;if(e[d(1007)](e.iszPR,e.ycdPw))this[d(696)]&&this[d(696)][d(1769)]({code:n,reason:s});else return _0x3c5b54[d(474)]()}[t(1509)+"Listener"](n,s){this.on(n,s)}["removeEv"+t(864)+"ner"](n,s){this.off(n,s)}get[t(713)+"te"](){return this[t(696)].readyState}get[t(867)+"pe"](){let n=t;return this[n(696)][n(867)+"pe"]}set[t(867)+"pe"](n){}get[t(1311)](){let n=t;return this[n(696)][n(1311)]}get[t(1438)](){let n=t;return this._socket[n(1438)]}get[t(530)+"ns"](){let n=t;return this[n(696)][n(530)+"ns"]}get[t(411)+t(1113)](){return 0}}function Mp(a,n){let s=t;if(e.iPrdq(e[s(484)],e[s(424)]))_0x9aa666=_0x54e956[e[s(1079)](_0x19b81b,_0x2ebdfe)+1],e[s(1292)](192&_0x302cc6,128)?_0x2661fa+=_0x1c572d:(_0x59f2c9=e[s(1792)](e[s(1805)](e[s(881)](31,_0x43aa6a),6),e[s(1854)](63,_0x46e552)),_0x11935d<128?_0x3a7580+=_0x4f87c9:(_0x1ede10+=e.rdyIN(_0x34f3cb,_0xd978b5),_0x1f0e8f++));else{if(n)return new n(a[s(1311)],a[s(1438)]);if(e[s(1129)](ei,On))return new Np(a[s(1311)],a.protocol,a[s(1776)]);if(e.KyhUy(or,ti)&&e[s(1367)](e.POcjp,typeof WebSocket)&&WebSocket)return new WebSocket(a[s(1311)],a[s(1438)+"s"])}}function Bp(a){let n=t,s=e[n(1663)][n(557)]("|"),d=0;for(;;){switch(s[d++]){case"0":return!1;case"1":if(ei&&wx[n(719)+n(644)])return!0;continue;case"2":if(On&&tt[n(719)+"ocket"])return!0;continue;case"3":if(a)return!0;continue;case"4":if(e[n(941)](or,ti)&&e[n(1820)](e.POcjp,typeof WebSocket)&&WebSocket)return!0;continue}break}}function pl(a,n,s){let d=-1;async function h(w){let m=q;return e[m(1369)](w,d)?Promise[m(414)](new Error(m(1097)+m(819)+"ltiple t"+m(676)+"process")):(d=w,e[m(1494)](w,s[m(1407)])?Promise[m(474)]():s[w][m(547)](a)(n,h[m(547)](null,e[m(1582)](w,1))))}h(0)}function gl(a){let n=t,s=0,d=0;for(let h=0;e[n(1803)](h,a[n(1407)]);++h)d=a[n(1589)+"At"](h),e[n(1886)](d,128)?s+=1:d<2048?s+=2:e[n(1784)](64512,d)===55296&&(64512&a[n(1589)+"At"](e[n(1160)](h,1)))===56320?(++h,s+=4):s+=3;return s}function ml(a,n,s){let d=t;if(e.XKjRC(e[d(853)],d(378)))this[d(985)](e[d(1063)],_0x19e324),this[d(1701)]&&this[d(1701)](_0x477fab);else{if(e[d(1852)](s-n,1))return"";let h="";for(let w=n;w<s;){let m=a[w++];if(e.arKCO(m,127))h+=String[d(759)+d(755)](m);else if(e[d(1133)](m,192)&&e[d(371)](m,224))h+=String[d(759)+d(755)](e[d(1722)](e[d(794)](31&m,6),e[d(1347)](63,a[w++])));else if(e.BLqXK(m,224)&&e.Nkpcr(m,240))h+=String[d(759)+d(755)](e.PuJDw(e[d(1144)](e[d(340)](15,m)<<12,e.SQuVx(e[d(336)](63,a[w++]),6)),63&a[w++]));else if(e[d(1774)](m,240)){let b=e[d(968)](e.QDGXT(e[d(1144)](e[d(573)](e[d(740)](7,m),18),e[d(870)](e[d(458)](63,a[w++]),12)),e[d(1351)](63,a[w++])<<6),e[d(336)](63,a[w++]))-65536;h+=String[d(759)+d(755)](e[d(1644)](55296,b>>10)),h+=String[d(759)+d(755)](e[d(1566)](56320,1023&b))}}return h}}function _a(a,n,s){let d=t,h={IZoZE:function(w,m){return e[q(1342)](w,m)}};if(e.yCocr("opnDc",e[d(1853)]))e.oxMVV(_0x31264a,_0x8c9b03,8),e[d(636)](_0x215e7f,_0x171c33,_0x2ab38e);else{let w=s,m,b;for(let p=0;e[d(708)](p,a[d(1407)]);++p)if(m=a[d(1589)+"At"](p),e[d(499)](m,128))n[s++]=m;else if(e[d(1803)](m,2048))n[s++]=e[d(1550)](e.qPcqP(m,6),192),n[s++]=e.LLzOa(63&m,128);else if(e[d(1156)](e.pircW(64512,m),55296)&&e.byWzj(64512&(b=a[d(1589)+"At"](e[d(1282)](p,1))),56320))if(d(1538)===e[d(871)])this[d(1764)+d(858)+d(1289)+"t"]=0;else{let P=e.UpgEP.split("|"),L=0;for(;;){switch(P[L++]){case"0":n[s++]=e.wVulW(e.XrfuR(m,18),240);continue;case"1":n[s++]=e[d(1814)](e[d(1659)](e[d(1304)](m,12),63),128);continue;case"2":++p;continue;case"3":n[s++]=e[d(754)](e[d(1140)](e[d(616)](m,6),63),128);continue;case"4":m=e.LnSfq(65536,e.yuHHa(e[d(1800)](1023,m),10))+e[d(791)](1023,b);continue;case"5":n[s++]=e[d(754)](e.HPVlp(63,m),128);continue}break}}else if(e[d(1789)](d(1019),d(1019)))n[s++]=e[d(1722)](e.RtkQU(m,12),224),n[s++]=e[d(517)](e[d(840)](m,6)&63,128),n[s++]=e.lQAlj(63,m)|128;else return _0x4a9b15&&(_0x51ffc7=(0,_0xde8270[cOLAVK.IZoZE(_0xf95851,_0x11e498)[0]])(_0x1b86f8=0)),_0x307813;return e[d(1375)](s,w)}}async function wl(a){let n=t;if(e[n(521)](e[n(1710)],typeof a)){let s=new Uint8Array(gl(a));return e[n(1637)](_a,a,s,0),s}return a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a.buffer,a.byteOffset,a[n(1232)+"th"])}function Fp(a){let n=t;try{return e[n(1710)]!=typeof a&&(e.TvsEH(a,ArrayBuffer)||a[n(566)]&&e[n(520)](a[n(566)],ArrayBuffer))||e[n(1820)](e[n(1710)],typeof a)?"":(JSON[n(383)](a),"applicat"+n(852))}catch{return e[n(802)](e[n(1710)],typeof a)?e.fMbzN:""}}let zp=(a,n)=>{let s=t;if(e[s(1073)]===e[s(1073)])switch(a){case e[s(1542)]:case e[s(1660)]:return{[s(1381)+a]:1,"x-tt-env":n};default:return{}}else{let d=new _0x500acf(e[s(844)](2,_0x41988a));d.set(_0x445296),_0x497c31[s(1772)]=d}};class Up{constructor(n){let s=t;this.maxLossCount=n,this[s(1321)]=0}[t(964)](){let n=t;this[n(1321)]++}["checkRea"+t(444)+"nt"](){let n=t;return e[n(504)](this[n(1321)],this[n(1465)+"ount"])}[t(1314)+t(1489)](n=0){let s=t;this["maxLossC"+s(651)]=n,this[s(1321)]=0}}async function Hp(a){let n=t,s={vKSmF:function(d,h){return e[q(1281)](d,h)},AWoZB:e[n(1793)],eqdwo:function(d,h){return d+h},zeyos:function(d,h){return d+h},HjiFn:"aTSym",rGfMl:function(d,h){return e[n(1707)](d,h)},pOhFl:e[n(1679)],YIeRW:e[n(1340)],VsRho:e.hIfCg,ZFEpA:function(d,h){return d===h},uAgmf:e[n(491)],bwDxO:e[n(481)]};if(n(1592)!==e[n(1283)])return new Promise(d=>{let h=n,w={ZfEpa:function(m,b){return s[q(480)](m,b)},QuPeU:function(m,b){return s[q(1535)](m,b)}};if(s.HjiFn!==s.HjiFn)_0xf22331[h(1888)][h(1378)+h(1392)](_0x2dee62);else{if(!or)return s[h(1187)](d,h(376)+h(1606));try{let m=document[h(1356)+h(1846)](s.pOhFl);window["frontier"+h(1420)]=b=>{let p=h;document[p(1888)][p(1130)+p(1392)](m),window[p(1126)+p(1420)]=void 0,s[p(1655)](d,b&&b[p(1725)]||s[p(1318)])},m[h(327)]=s.YIeRW,m[h(1634)]=a[h(827)](/^ws/,s[h(681)])+("&jscallb"+h(945)+"tierJSONP");try{if(s.ZFEpA(s[h(824)],s.bwDxO)){let p=""+_0xa33bad[h(1552)](),P=_0x2ba1a0||(_0x3b040a=_0x153590(_0x1f9805)),L=_0x2ad5c4[h(1747)]()[h(1715)](16).slice(-6);return DyHgLb[h(633)](DyHgLb.QuPeU(DyHgLb[h(1677)]("02",p),P),L)}else document.body[h(1378)+h(1392)](m)}catch{document[h(1888)][h(1130)+h(1392)](m)}}catch{window["frontier"+h(1420)]=void 0,s[h(1187)](d,s.AWoZB)}}});{let d=e[n(571)](_0x4a2e92[n(735)],0),h=e.fyFqA(_0x136861.low>>>28|e.CIAgs(_0x154c61[n(1372)],4),0),w=e.pbQcA(_0x412db3[n(1372)],24),m=w===0?h===0?d<16384?e.mEXwf(d,128)?1:2:e[n(1095)](d,2097152)?3:4:h<16384?e[n(1833)](h,128)?5:6:e[n(335)](h,2097152)?7:8:w<128?9:10,b=e[n(1139)](_0x20f00e,_0x1d2212,m),p=_0xc13691[n(1772)];switch(m){case 10:p[e[n(1644)](b,9)]=e.HzgxL(e[n(770)](w,7),1);case 9:p[b+8]=m!==9?e[n(1745)](128,w):127&w;case 8:p[e[n(1639)](b,7)]=e.Gfxjh(8,m)?e[n(1751)](e.YKnrk(h,21),128):e[n(1638)](h>>>21,127);case 7:p[e[n(1124)](b,6)]=e[n(1753)](7,m)?e[n(1544)](h,14)|128:e[n(1705)](e[n(362)](h,14),127);case 6:p[e[n(1400)](b,5)]=e.hqrft(6,m)?e[n(479)](e[n(1371)](h,7),128):h>>>7&127;case 5:p[e[n(792)](b,4)]=e[n(1278)](5,m)?128|h:e.Tohke(127,h);case 4:p[e[n(835)](b,3)]=m!==4?e[n(1778)](e[n(822)](d,21),128):e[n(1296)](e.Kgsgi(d,21),127);case 3:p[b+2]=e[n(1278)](3,m)?e[n(660)](d,14)|128:e[n(702)](e[n(907)](d,14),127);case 2:p[e[n(1569)](b,1)]=e.zTZOQ(2,m)?e[n(968)](e[n(347)](d,7),128):e[n(518)](e[n(1371)](d,7),127);case 1:p[b]=e[n(1199)](1,m)?e.qBacL(128,d):e[n(1358)](127,d)}}}function sn(a,n,s){let d=t;return!!a?.find(h=>h[d(1148)]===n&&h[d(823)]===s)}function ar(a,n){let s=t;return a?.[s(1403)](d=>d[s(1148)]===n)?.[s(823)]}let ya=null;async function Gp(){let a=t;if(e.ZLIuf(e.eFcUC,a(436)))_0x49922a[a(932)](_0x534d33);else return ya||(ya=Promise.resolve()[a(862)](Ft[a(547)](Ft,a(415)))),ya}class qp extends wa{constructor(n,s){let d=t;super(),this[d(1856)]=n,this[d(394)]=s,this[d(559)]=void 0,this["_initPro"+d(915)]=null}async[t(1697)](){await this[t(1482)]()}async[t(1482)](){let n=t;if(!this[n(559)]){if(this[n(683)+n(915)])return this._initPromise;try{let s=this[n(1856)],d=this._keyPath;this["_initPro"+n(915)]=(async()=>{let h=n,{openDB:w}=await Gp();this[h(559)]=await e[h(1587)](w,h(1126)+"_"+s,1,{upgrade(m){m[h(442)+"jectStore"](s,{keyPath:d})}})})(),await this[n(683)+n(915)]}catch(s){console.log(s)}finally{this[n(683)+n(915)]=null}}}async get(n){let s=t,d={udHoI:function(h,w){return e.QHSwN(h,w)},SzgfJ:function(h,w){return e.BumBA(h,w)}};try{if(e[s(671)]!==e[s(1065)])return await this[s(1482)](),this[s(559)]?.[s(1546)](this[s(1856)],n);_0x59f604[s(1888)][s(1130)+"ild"](_0x389884)}catch(h){e.AlOTb(e[s(1068)],e[s(1068)])?(_0x3efa09[_0x396992++]=MfyvLb[s(894)](_0xf6525f,6)|192,_0x18c030[_0x213957++]=MfyvLb[s(1657)](63,_0x1f99c3)|128):console[s(1212)](h)}}async[t(1680)](n,s){let d=t;return await this._init(),this[d(559)]?.[d(1541)](this[d(1856)],n)}async[t(522)](n){let s=t;try{return await this._init(),this[s(559)]?.[s(1562)](this._dbName,n)}catch(d){if(e[s(1410)]===e[s(745)])return _0x2e5ad6+=_0x164660&&_0x585ae1.byteLength||0,_0x406526;console[s(1212)](d)}}async[t(1173)](){let n=t;try{return e[n(1583)]===n(1025)?(await this._init(),this[n(559)]?.clear(this[n(1856)])):this[n(559)][n(1675)]}catch(s){console[n(1212)](s)}}async[t(1709)](){let n=t;return await this._init(),this[n(559)]?.getAllKeys(this[n(1856)])}async getAll(){let n=t;return await this[n(1482)](),this[n(559)]?.[n(665)](this._dbName)}async[t(1363)](){let n=t;try{this[n(559)]?.[n(1769)](),this._qosDB=void 0}catch(s){console[n(1212)](s)}}get[t(1675)](){let n=t;try{if(e[n(721)](e[n(1840)],e[n(942)]))this[n(1056)+"s"]=_0x477c68,this[n(1533)+"es"]=_0x649fd4,this[n(789)+n(718)]=0,this["currentE"+n(858)+n(1289)+"t"]=0;else return!!this._qosDB}catch(s){return console[n(1212)](s),!1}}}class jp{constructor(n,s){let d=t;this[d(1243)]=n,this[d(1579)]=s,this[d(559)]=localStorage}async[t(1697)](){}get[t(1708)](){let n=t;return n(1126)+"_"+this[n(1243)]}async[t(1546)](n){let s=t,d=this[s(559)].getItem(this._prefix);return JSON.parse(d||"{}")[n]}async[t(1680)](n,s){let d=t,h=this[d(559)].getItem(this[d(1708)]),w=JSON[d(383)](h||"{}");return w[s||n[this[d(1579)]]]=n,this[d(559)][d(1170)](this._prefix,JSON[d(1202)+"y"](w)),s||n[this._pathKey]}async del(n){let s=t;if(e[s(410)](e.KmbpQ,e[s(1877)])){let d=this[s(559)][s(1062)](this._prefix),h=JSON.parse(d||"{}");return h[n]=void 0,this._qosDB.setItem(this._prefix,JSON[s(1202)+"y"](h))}else this[s(1198)](e[s(500)],_0x323351.message),e[s(1734)](_0x5ba6d3)}async clear(){let n=t;return this[n(559)][n(1173)]()}async[t(1709)](){let n=t,s=this._qosDB[n(1062)](this[n(1708)]),d=JSON[n(383)](e[n(1721)](s,"{}"));return Object.keys(d)}async getAll(){let n=t,s=this[n(559)][n(1062)](this._prefix),d=JSON.parse(e.hxowp(s,"{}"));return Object.values(d)}[t(1363)](){return Promise[t(474)]()}get[t(1675)](){return!!this._qosDB}}class Kp{constructor(n,s){let d=t;this[d(1243)]=n,this[d(1579)]=s,this[d(559)]=On?tt:ei?wx:null}async[t(1697)](){}get[t(1708)](){return"frontier_"+this[t(1243)]}async[t(1546)](n){let s=t,d=this[s(559)][s(1849)+s(1449)](this[s(1708)]);return JSON.parse(e.KyhUy(d,"{}"))[n]}async[t(1680)](n,s){let d=t,h=this._qosDB[d(1849)+d(1449)](this[d(1708)]),w=JSON[d(383)](e[d(1129)](h,"{}"));return w[s||n[this[d(1579)]]]=n,this._qosDB["setStora"+d(1449)](this[d(1708)],JSON.stringify(w)),s||n[this[d(1579)]]}async[t(522)](n){let s=t,d=this[s(559)][s(1849)+"geSync"](this[s(1708)]),h=JSON[s(383)](d||"{}");return h[n]=void 0,this._qosDB.setStorageSync(this[s(1708)],JSON[s(1202)+"y"](h))}async clear(){return this[t(559)].clearStorageSync()}async[t(1709)](){let n=t,s=this[n(559)][n(1849)+n(1421)+"nc"](this._prefix),d=JSON[n(383)](s||"{}");return Object[n(1709)](d)}async[t(665)](){let n=t,s=this[n(559)][n(1849)+n(1421)+"nc"](this[n(1708)]),d=JSON[n(383)](s||"{}");return Object.values(d)}[t(1363)](){return Promise.resolve()}get[t(1675)](){return!!this[t(559)]}}function _l(a,n){let s=t;if(On||On)return new Kp(a,n);if(e[s(1721)](or,ti)&&e[s(1367)](e[s(490)],typeof indexedDB))return new qp(a,n);if(e.CEnSm(or,ti)&&e[s(1367)](e[s(490)],typeof localStorage))return new jp(a,n);throw new Error(s(471)+s(850)+"d")}class Wp{constructor(){let n=t;this[n(700)+n(961)+"Id"]=null,this._interval=36e5,this[n(559)]=_l(e.PEtri,e[n(323)])}async[t(700)+t(1114)](){let n=t;clearInterval(this["_interva"+n(961)+"Id"]),this[n(700)+n(961)+"Id"]=e[n(925)](setInterval,()=>{let s=n;this[s(1516)+s(1405)]()},this._interval)}async openDB(){let n=t,s={OZvna:function(d,h){return e.psbCc(d,h)},ApDIj:function(d,h){return e[q(1387)](d,h)},cZXRV:function(d,h){return d|h},aHhSe:function(d,h){return d<<h},xtefw:function(d,h){return e[q(1645)](d,h)},Npqsr:function(d,h){return e[q(1773)](d,h)},xdoqv:function(d,h){return d<h},jSbne:function(d,h){return e[q(750)](d,h)},JOTHA:function(d,h){return d<<h},IoEfj:function(d,h){return e[q(798)](d,h)},bjmAu:function(d,h){return e[q(1471)](d,h)},xHbWf:function(d,h){return e[q(1440)](d,h)},TMfie:function(d,h){return e[q(994)](d,h)},GXcXh:function(d,h){return e[q(565)](d,h)}};await this[n(559)][n(1697)]()[n(862)](()=>{let d=n;if(e[d(672)](e[d(1477)],"TnpLj"))this[d(700)+d(1114)]();else{let h=_0x29b03d[_0x254ea1++];if(AnFBBR.OZvna(h,127))_0x28d09c+=_0x371042[d(759)+d(755)](h);else if(AnFBBR.ApDIj(h,192)&&h<224)_0x56a8ab+=_0x59c4bc[d(759)+d(755)](AnFBBR.cZXRV(AnFBBR[d(931)](AnFBBR[d(1391)](31,h),6),AnFBBR[d(404)](63,_0x40028a[_0x40a3e2++])));else if(AnFBBR[d(1629)](h,224)&&AnFBBR[d(1412)](h,240))_0x5a8bdd+=_0xae2c10[d(759)+d(755)](AnFBBR.cZXRV(AnFBBR[d(1162)](AnFBBR[d(1172)](AnFBBR.Npqsr(15,h),12),AnFBBR[d(1423)](AnFBBR[d(1391)](63,_0x283a15[_0x5581a6++]),6)),AnFBBR.Npqsr(63,_0x132ede[_0x1102e8++])));else if(AnFBBR[d(1643)](h,240)){let w=AnFBBR.bjmAu(AnFBBR[d(1162)](AnFBBR[d(1162)](AnFBBR[d(1162)](AnFBBR.JOTHA(7&h,18),AnFBBR[d(404)](63,_0x21972c[_0x53a41a++])<<12),(63&_0x11e63c[_0x45b9ed++])<<6),AnFBBR[d(404)](63,_0x34f4e0[_0x3c4b33++])),65536);_0x466674+=_0x388c0d[d(759)+"Code"](AnFBBR[d(1104)](55296,AnFBBR[d(1724)](w,10))),_0x1d2f7c+=_0x462e52[d(759)+"Code"](AnFBBR[d(1104)](56320,AnFBBR[d(1656)](1023,w)))}}})}async["flushExp"+t(1405)](){let n=t;(await this[n(559)]?.[n(665)]()||[])[n(1783)](({timestamp:h})=>h<Date[n(1552)]())[n(1858)](h=>{let w=n;this[w(559)]?.del(h[w(412)+"id"])})}async del(n){let s=t;return this[s(559)]?.[s(522)](n)}async[t(1680)](n,s){let d=t;return e[d(1527)](d(419),e[d(464)])?this[d(1764)+d(858)+"riesCount"]:this._qosDB?.set({message_id:n,timestamp:s})}async[t(1546)](n){let s=t;return this._qosDB?.[s(1546)](n)}async closeDB(){let n=t;clearInterval(this[n(700)+n(961)+"Id"]),await this[n(559)]?.[n(1363)]()}get isReady(){let n=t;return this._qosDB?.[n(1675)]}}function Ea(a){let n=t;if(e.ZwlYi===e[n(1496)]){let s=!!this[n(1224)][n(592)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let d=e[n(1637)](sn,a[n(736)][n(1776)],e[n(374)],"2"),h=d&&sn(a.message[n(1776)],e[n(1518)],"1"),w=d&&e.ISqez(sn,a[n(736)].headers,e[n(350)],"1"),m=w?e[n(1476)](ar,a[n(736)][n(1776)],n(1295)+n(626)+n(1689))?.[n(557)](",")[n(1783)](Boolean)||[]:[];return{enabled:s,isQoSMessage:d,isQoSAck:h,isAckCleanupMessage:w,ackMsgIds:m}}else return this[n(1604)+n(456)+n(879)](_0xf64d41),e.BINtB(_0x3d81d0)}async function yl(){let a=t;if(e.iTPAl(e[a(1742)],e[a(1742)]))this._options[a(1136)]&&_0x1cc057[a(1212)][a(1493)](_0x5ab9fe,[e[a(1468)],..._0x47a5ff]);else return this[a(629)+"ger"]||(this[a(629)+a(1329)]=new Wp),this[a(629)+"ger"].isReady||await this["_QoSMana"+a(1329)][a(1697)](),this[a(629)+a(1329)]}async function $p(a,n){let s=t;if(e[s(919)](e[s(1059)],e[s(1059)])){let{enableAutoAck:d}=this[s(1224)],h=sn(a[s(736)][s(1776)],e[s(1564)],"1"),w=sn(a.message.headers,e.nAwoN,"1"),m=Ea[s(903)](this,a);if(e.GqgWf(d,h)){let{SeqID:b,LogID:p,service:P,LogIDNew:L,method:M}=a[s(736)];this[s(1307)]({SeqID:b,LogID:p,LogIDNew:L,service:P,method:M,headers:[{key:s(1016),value:"1"},{key:e[s(756)],value:e.CEnSm(L,"")},{key:s(1182),value:"0"}]})}w&&!m[s(757)]&&this["_dispatc"+s(1152)+s(809)](a),n()}else PBuhzc[s(490)]!=typeof _0x3abbd5&&_0x3503d2[s(1715)+s(664)]&&_0x4bafc8[s(600)+"operty"](_0x1c9173,_0xe1cdc2[s(1715)+"Tag"],{value:PBuhzc[s(1558)]}),_0x377159[s(600)+s(877)](_0x3cc95b,PBuhzc[s(950)],{value:!0})}async function Vp(a,n){let s=t;this[s(1198)](s(528),a[s(736)]),e[s(1190)](n)}async function Jp(a,n){let s=t,d=e[s(1437)](tn,await e[s(393)](wl,a[s(815)]));try{if(e[s(998)](e[s(1443)],"vDQRo")){_0x41c5d0[s(1115)](_0xb9b639)||(_0x2e0d28=_0x5351e6.fromNumber(_0x455612));let h=e[s(816)](this.high,16),w=65535&this[s(1372)],m=e.ZJClV(this[s(735)],16),b=e.cYiVY(65535,this[s(735)]),p=e.nwnRk(_0x1ec7eb[s(1372)],16),P=e[s(1719)](65535,_0x117891[s(1372)]),L=e[s(1371)](_0x4d6af5[s(735)],16),M=e[s(468)](65535,_0x21d67f[s(735)]),G=0,J=0,Z=0,we=0;return we+=e[s(403)](b,M),Z+=we>>>16,we&=65535,Z+=e[s(892)](m,L),J+=Z>>>16,Z&=65535,J+=e[s(431)](w,P),G+=e[s(1621)](J,16),J&=65535,G+=e[s(508)](h,p),G&=65535,_0x4ce836[s(1364)](e.RZuJK(Z,16)|we,e[s(1602)](G,16)|J,this.unsigned)}else if(e[s(1218)](d[s(326)],Uint8Array)){let h=e[s(723)](this._options[s(532)+s(1293)],Object)?{force:!!this[s(1224)][s(532)+"ncoding"][s(364)],encoding:this[s(1224)][s(532)+s(1293)][s(1867)]?this._options[s(532)+s(1293)][s(1867)][s(827)](/\s/g,"")[s(1461)+s(1267)]():""}:{force:!1,encoding:this[s(1224)][s(532)+s(1293)]?this[s(1224)][s(532)+s(1293)].replace(/\s/g,"")["toLowerC"+s(1267)]():""},w=d[s(532)+s(1293)]?d[s(532)+s(1293)][s(827)](/\s/g,"")[s(1461)+"ase"]():"",m=e[s(441)](this[s(1224)][s(1700)+s(888)],Object)?{force:!!this[s(1224)][s(1700)+s(888)][s(364)],type:this[s(1224)][s(1700)+s(888)][s(327)]?this._options[s(1700)+"ype"][s(327)].replace(/\s/g,"")[s(1461)+s(1267)]():""}:{force:!1,type:this[s(1224)][s(1700)+s(888)]?this[s(1224)][s(1700)+s(888)][s(827)](/\s/g,"").toLowerCase():""},b=d[s(1700)+s(888)]?d[s(1700)+"ype"][s(827)](/\s/g,"")[s(1461)+s(1267)]():"",p=m.force?m[s(327)]:b||m[s(327)],P=h[s(364)]?h.encoding:w||h[s(1867)],L=[e[s(1333)],e[s(637)],e[s(1080)],e[s(1710)]],M=[e[s(603)],e[s(1408)]];this[s(1224)]["enableTransformT"+s(1586)+"ad"]&&L[s(317)](p)&&(!P||M.includes(P))?d[s(552)+"oad"]=ml(d[s(326)],0,d[s(326)].byteLength):d[s(552)+s(1100)]=""}else d[s(552)+s(1100)]=""}catch(h){d[s(552)+s(1100)]="",console.log(h)}a[s(736)]=d,e.nvGsO(n)}function Zp(a,n,s){let d=t,h=e[d(1795)](s,8192),w=e.pSScq(h,1),m=null,b=h;return function(p){let P=d,L={eETet:function(G,J){return e.mqhdB(G,J)},UQKei:function(G,J){return e[q(1235)](G,J)},dwlgb:function(G,J){return G!=J},WzsUR:e[P(490)]};if(e[P(1066)](p,1)||p>w)return e[P(1342)](a,p);if(e[P(1001)](e[P(437)](b,p),h))if(e.IHDJO(e[P(562)],e[P(562)]))m=e[P(343)](a,h),b=0;else{if(_0x524082)return new _0x2db793(_0x3dc264[P(1311)],_0x4cdae5[P(1438)]);if(aAyUZX[P(1733)](_0x12aac7,_0x479c15))return new _0x44446f(_0x5c8d44.url,_0xf8fa4c[P(1438)],_0x22a934[P(1776)]);if(aAyUZX[P(495)](_0x40a6c8,_0x1756d7)&&aAyUZX[P(682)](aAyUZX[P(1703)],typeof _0x3be0c7)&&_0x437175)return new _0x3a3991(_0x5f165f[P(1311)],_0x39cda7[P(1438)+"s"])}let M=n[P(903)](m,b,b+=p);return e[P(940)](7,b)&&(b=e[P(1822)](e[P(1722)](7,b),1)),M}}let Yp=4294967295;function Xp(a,n,s){let d=t;if(e[d(1497)](d(642),e[d(1555)]))return e[d(911)](RangeError,e[d(678)](e[d(1110)](e[d(1568)](e[d(1582)](e[d(1031)](e[d(386)],a),e[d(1064)]),n||1),e.LAkPw),s));this[d(1804)+"sCounter"]?.[d(964)](),this[d(985)](d(1246)+d(1570)+"t","timeout"),this[d(1804)+d(620)]?.[d(1024)+d(444)+"nt"]()?this[d(1720)+"econnect"]():this[d(780)]()}function Qp(a,n,s){let d=t;if(e[d(1588)](s,Yp))throw new Error(e[d(1698)]);let h=3;for(;e.JdQgC(h,0);){let w=255&s;e[d(1637)](va,w,a,e[d(1274)](n,h)),s>>>=8,h--}return e[d(1440)](n,4)}function eg(a,n){let s=t,d=0,h=n,w=e[s(1470)](n,4);for(;e[s(691)](h,w);){let{value:m,offset:b}=ba(a,h);h=b,d=e[s(1739)](e[s(1750)](d,8),0),d+=m}return{value:d,offset:w}}function tg(a,n,s){let d=t;return a?e[d(1678)](a[d(1407)],40)?e[d(678)](e[d(1786)](_a,a,n,s),s):n[d(342)+"e"]?e.hsutd(n[d(342)+"e"](a,s),s):n.write?n.write(a,s)+s:e[d(544)](_a(a,n,s),s):s}function ng(a,n){let s=t,d=new he(e[s(360)](e[s(1398)](e.yuHHa(a[n+4],24),e[s(1428)](a[e[s(947)](n,5)],16)),e[s(750)](a[e.oOdiw(n,6)],8))|a[n+7],e[s(891)](e[s(640)](e[s(509)](e.dvqXp(a[n+0],24),e.eQeaD(a[e.APKqq(n,1)],16)),e[s(1791)](a[e.ktXJw(n,2)],8)),a[n+3]),!0);return n+=8,{value:d,offset:e[s(1649)](n,8)}}function rg(a,n,s){let d=t,h=a[d(735)],w=a[d(1372)];return n[s]=e[d(1621)](w,24),n[s+1]=e[d(818)](e[d(1301)](w,16),255),n[e[d(567)](s,2)]=e.miBit(e.jiyDl(w,8),255),n[e[d(365)](s,3)]=e[d(535)](255,w),n[e.awacv(s,4)]=h>>>24,n[s+5]=e[d(1502)](e[d(1384)](h,16),255),n[e[d(431)](s,6)]=e.UPQXF(e.wVEgY(h,8),255),n[e[d(730)](s,7)]=e[d(1854)](255,h),s+=8,s}function ba(a,n){let s=t;return a[s(1222)+"8"]?{value:a[s(1222)+"8"](n),offset:n+1}:{value:e[s(569)](255,a[n]),offset:e[s(1451)](n,1)}}function va(a,n,s){let d=t;return n[d(543)+"t8"]?n.writeUint8(a,s):n[s]=255&a,e[d(1221)](s,1)}let ig=function(a){return new Uint8Array(a)},sg=e[t(1820)](e[t(490)],typeof Buffer)?Buffer[t(1132)+t(1201)]:e[t(1058)](Zp,ig,Uint8Array[t(337)+"e"][t(1591)]);(()=>{let a=t,n={HijIC:e[a(368)],LPPoE:function(d,h){return e.iOnvC(d,h)},ykENv:function(d,h){return e[a(517)](d,h)},omLrY:function(d,h){return d<h},NAmZN:function(d,h){return e.KKucg(d,h)},OQUDQ:function(d,h){return e[a(1161)](d,h)},PrTqA:function(d,h){return e[a(1641)](d,h)},TcMHJ:function(d,h){return e[a(515)](d,h)},pljpQ:function(d,h){return e[a(1316)](d,h)},ebsNV:function(d,h){return e[a(1409)](d,h)},MHCyl:function(d,h){return e.RTHMR(d,h)},FSKkA:function(d,h){return e[a(1659)](d,h)},QdXJG:function(d,h){return e.NngXn(d,h)},XWfXw:function(d,h){return e[a(1761)](d,h)},xqycc:function(d,h){return e[a(1750)](d,h)},YVlIL:function(d,h){return e[a(1784)](d,h)}},s=4294967295;return function(d,h,w=!0){let m=a,b=n[m(507)][m(557)]("|"),p=0;for(;;){switch(b[p++]){case"0":if(n[m(356)](d[h++],128))return{value:w?s:n[m(1053)](0,s),offset:h};continue;case"1":if(n[m(1590)](d[h++],128))return{value:w?s:n[m(1053)](0,s),offset:h};continue;case"2":if(n.omLrY(d[h++],128))return{value:w?s:0|s,offset:h};continue;case"3":s=n[m(784)](s|n[m(486)](n[m(1469)](127,d[h]),14),0);continue;case"4":s=n[m(920)](s,n[m(1469)](127,d[h])<<21)>>>0;continue;case"5":if(n[m(939)](d[h++],128))return{value:w?s:n[m(920)](0,s),offset:h};continue;case"6":s=n[m(784)](n.ebsNV(127,d[h]),0);continue;case"7":s=n.NAmZN(s|n[m(980)](n[m(1137)](127,d[h]),7),0);continue;case"8":if(n[m(1565)](h+=5,d[m(1407)]))throw h=d.length,Xp(h,10,d[m(1407)]);continue;case"9":if(d[h++]<128)return{value:w?s:n[m(920)](0,s),offset:h};continue;case"10":return{value:w?s:n[m(920)](0,s),offset:h};case"11":s=n[m(1109)](n.TcMHJ(s,n[m(647)](n[m(318)](15,d[h]),28)),0);continue}break}}})();let og=16,Sa=32;function ag(a){let n=t,s=0,d={};for(let h=0;e[n(966)](h,a[n(1407)]);h++)d[a[h][n(466)+n(1573)]]=e[n(972)](gl,a[h][n(466)+n(1573)]),s+=e.zvBEh(14,d[a[h][n(466)+n(1573)]]);return[s,d]}function El(a,n,s){let d=t,h={HsluE:function(w,m,b){return e[q(1640)](w,m,b)},eRERN:function(w,m){return e[q(588)](w,m)},hsKIO:e[d(1265)],ZsoSz:e[d(1045)],KsHBh:function(w,m,b,p){return e[d(1587)](w,m,b,p)},Kovif:e[d(397)],BZequ:e.MnVtS,jPXaa:e.lKCCS,ueTYa:e.PyHSZ};if(e[d(1088)](e[d(462)],d(976)))LSoTnX[d(943)](_0x3a4cd7,_0x132554,LSoTnX[d(933)](127,_0x552dfa)|128),_0x423840>>>=7;else{let[w,m]=e[d(574)](ag,a),b=sg(w),p=0;return a[d(1858)](P=>{let L=d,M=h[L(893)][L(557)]("|"),G=0;for(;;){switch(M[G++]){case"0":console.log(h[L(448)],P,P[L(974)]);continue;case"1":p=rg(he[L(1204)+"er"](P[L(1631)]||n),b,p);continue;case"2":p=h.KsHBh(va,m[P[L(466)+L(1573)]],b,p);continue;case"3":console[L(1212)](h.Kovif,p);continue;case"4":console[L(1212)](h.BZequ,p);continue;case"5":p=h.KsHBh(tg,P["cursor_n"+L(1573)],b,p);continue;case"6":p=h[L(1711)](va,0,b,p);continue;case"7":console.log(h[L(712)],p);continue;case"8":console.log("name",p);continue;case"9":p=h[L(1711)](Qp,b,p,P[L(974)]||0);continue;case"10":console.log(h[L(1166)],p);continue}break}}),{frameType:Sa,headers:[{key:e.lBolV,value:s}],payload:b}}}function cg(a){let n=t,s=0,d=[];for(;e[n(990)](s,a[n(1232)+"th"]);){let{offset:h}=e[n(1266)](ba,a,s);s=h;let w={cursor_name:"",cursor:0,service:0},{value:m,offset:b}=eg(a,s);w.service=m,s=b;let{value:p,offset:P}=e[n(549)](ba,a,s);s=P,w[n(466)+n(1573)]=e[n(1623)](ml,a,s,e[n(544)](s,p)),s+=p;let{value:L,offset:M}=e[n(1467)](ng,a,s);w[n(1631)]=L[n(812)](),s=M,d[n(932)](w)}return d}function dg(){let a=t;return{frameType:Sa,headers:[{key:e[a(1757)],value:e[a(434)]}],payload:void 0}}class lg{constructor(n,s,d){let h=t;this["_cursorN"+h(531)]=n,this._cursorFileName=s,this[h(1571)+h(1554)]=d,this[h(559)]=e.uizKF(_l,this[h(1091)+"ameSpace"],e.lexsB)}async[t(1697)](){let n=t;await this[n(559)][n(1697)]()}async[t(333)+"rs"](){let n=t;if(!this._qosDB[n(1675)])return;let s=this[n(1571)+"Strategy"],d=await this[n(559)][n(665)]();switch(console[n(1212)](e[n(1168)],d),s){case e[n(995)]:return d&&d.length?El(d,0,this["_cursorF"+n(982)]):void 0;case e[n(1802)]:return;case e[n(1231)]:return d&&d.length?El(d,0,this[n(1823)+n(982)]):e[n(1190)](dg)}}async[t(1680)](n,s,d){let h=t,w={eUPTk:function(b,p,P,L){return e[q(1512)](b,p,P,L)}};if(e[h(1669)]!==e[h(1531)])return console[h(1212)](e[h(1874)],n,s,d),this[h(559)][h(1680)]({cursor_name:n,cursor:s,service:d});for(var m in _0x2c67b3)pbqPAA[h(556)](_0x421174,_0x109edc,m,{get:_0x2de917[m],enumerable:!0})}async[t(381)+"rs"](n){let s=t,d=e[s(607)](cg,n);for(let h of d)console[s(1212)](e.gKvuA,d),await this[s(559)][s(1680)](h)}async[t(1546)](n){let s=t;return(await this[s(559)][s(1546)](n))?.[s(1631)]}async[t(1363)](){let n=t;await this[n(559)][n(1363)]()}[t(1848)+t(1194)+t(1192)](n){let s=t;this[s(1823)+s(982)]=n}get[t(1675)](){return this[t(559)].isReady}}let ug=t(1230)+"qos__";async function bl(a){let n=t;if(!this[n(1224)][n(592)+"S"])return null;let{aID:s,fpID:d,messageStrategy:h}=this[n(1224)],w=e.DVTkt(a,ug);try{if(e.vHcDI===e[n(838)])return this[n(875)+n(450)]?a&&this[n(875)+n(450)]["updateCu"+n(1194)+n(1192)](a):this[n(875)+"anager"]=new lg(d+"_"+s+"_"+w,w,h),this._cursorManager[n(1675)]||await this[n(875)+n(450)].openDB(),this[n(875)+"anager"];{let m=0,b={};for(let p=0;e[n(1803)](p,_0x2cfe5a[n(1407)]);p++)b[_0x497848[p]["cursor_n"+n(1573)]]=e[n(1545)](_0x59a1d6,_0x5ca206[p][n(466)+n(1573)]),m+=14+b[_0x5ada70[p][n(466)+"ame"]];return[m,b]}}catch{return null}}async function fg(a,n){let s=t,d=e[s(1406)](sn,a[s(736)].headers,e[s(1671)],"-1"),h=e.PmNRE(sn,a.message.headers,"is_ack","1"),w=ar(a.message[s(1776)],e[s(694)]),m=e[s(1342)](Number,e.nwECz(ar,a.message[s(1776)],e[s(1179)]))||0,b=Ea.call(this,a),p=e[s(1786)](sn,a[s(736)].headers,s(525)+"s","2"),P=ar(a[s(736)][s(1776)],e[s(1799)]),L=e.GeesE(Number,ar(a.message[s(1776)],e[s(553)]));if(b[s(757)])return n();let M=b[s(1615)+s(924)]?await yl.call(this):null;if(e[s(860)](a[s(736)].service,0)&&h&&!d||e.asrSi(a[s(736)][s(974)],0)){if(w&&b[s(1615)+s(924)]&&M)return!!!await M[s(1546)](w)&&(this[s(1604)+s(456)+s(879)](a),await M[s(1680)](w,e[s(1282)](Date[s(1552)](),m))),e[s(1312)](n);if(p){let G=await bl[s(903)](this);if(!G)return this["_dispatchMessage"+s(879)](a),e[s(1312)](n);let J=await G[s(1546)](P)??-1;if(e[s(977)](J,L))this[s(1604)+s(456)+s(879)](a),G[s(1680)](P,L,a[s(736)][s(974)]);else throw new Error("recevied"+s(1354)+s(1887)+L+(" larger "+s(1532)+"al cursor ")+J);return n()}return this[s(1604)+"hMessage"+s(879)](a),n()}}async function hg(a,n){let s=t,d=Ea.call(this,a);if(!d[s(1615)+s(924)])return n();let h=await yl.call(this);if(d["isAckCle"+s(880)+s(1815)]&&d.ackMsgIds[s(1407)])for(let w of d[s(605)+"s"])await h[s(522)](w);e[s(1242)](n)}async function xg(a,n){let s=t,d=a[s(736)][s(1665)+"e"]===og,h=e[s(1203)](a[s(736)][s(1665)+"e"],Sa);if(!d&&!h)return e[s(1242)](n);let w=e[s(1226)](ar,a[s(736)].headers,e.lBolV);if(!w)return e[s(1178)](n);let m=await bl.call(this,w);if(!m)return e.pOfnA(n);if(d){let b=await m[s(333)+"rs"](),p={frameType:b?.["frameType"],SeqID:he[s(1204)+"er"](this[s(670)]++),LogID:he[s(1204)+"er"](this[s(1224)].logIDGenerator()),service:9e3,method:5,headers:b?.headers,payload:b?.[s(326)]},P=e[s(1523)](S,p);this._ws&&this[s(1551)].readyState&&this._ws[s(596)](P)}if(h){let b=a[s(736)][s(326)];b&&m[s(381)+"rs"](b)}}let pg=async function(a,n){let s=t;this._isInit=!1,e[s(1250)](clearTimeout,this[s(744)+s(438)+"utId"]),n()},gg=async function(a,n){let s=t;if(!this[s(1551)]||e[s(1051)](this._ws.readyState,this[s(1344)]))return e[s(1190)](n);let{pingInterval:d}=this[s(1224)];this[s(841)+s(1653)]?.[s(1670)+s(747)+s(1459)]();for(let w=0;e[s(930)](w,this["_message"+s(498)][s(1407)]);w++){let m=this[s(1571)+s(498)][w];if(e[s(476)](this[s(1551)][s(713)+"te"],this[s(1344)])&&m!==null)this[s(1551)]&&this[s(1551)][s(596)](m),this[s(1571)+s(498)][w]=null;else break}this["_message"+s(498)]=this["_message"+s(498)][s(1783)](w=>!!w),this[s(496)+s(1276)+"Id"]=e[s(1096)](setTimeout,()=>this._ping(),d),this["_dispatc"+s(1149)+"nt"](a),this._isBrowser&&this[s(1551)]&&(this[s(1551)].binaryType=this[s(583)+"ype"]);let h=this[s(841)+s(1653)]?.[s(346)+s(1548)+"nt"]();this[s(1198)](s(1754)+h+s(1513)),n()},mg=async function(a,n){let s=t,d=this[s(841)+s(1653)]?.[s(346)+"ntEndpoint"]();this[s(1198)](s(1754)+d),n()};class wg extends wa{constructor(n){let s=t,d={EMXLn:function(b,p){return e.UTijI(b,p)},FWpJl:function(b,p){return b(p)},onqMk:function(b,p){return b<<p},dTqbo:function(b,p){return b&p},uuKco:function(b,p){return e[q(569)](b,p)},aPxsy:function(b,p){return b(p)},keZPw:function(b,p){return e[q(449)](b,p)},qTzkU:e.IpWTz,omNWy:e[s(1491)],tUNQw:function(b,p){return e.wHMwJ(b,p)},HDaEK:e[s(352)],KZaGU:function(b,p,P){return e[s(435)](b,p,P)},PGYwK:e[s(465)],GRnlH:function(b,p){return b(p)},pulBj:function(b,p){return e[s(643)](b,p)},iUwEP:function(b,p){return e[s(1347)](b,p)},dIuyq:function(b,p){return e[s(1313)](b,p)},QSAAR:e[s(1619)],tYgCk:function(b,p){return e[s(906)](b,p)},YTjBu:e[s(1386)],wtyTZ:e.TXyLA,SGoBp:e[s(1694)],ChUyF:e[s(1839)],zFkRT:function(b,p,P){return e.HEIRM(b,p,P)},TGxwa:function(b,p,P,L){return b(p,P,L)},gozvP:function(b,p,P){return b(p,P)},JxuZE:function(b,p){return e.Wybsi(b,p)},RDfqc:function(b,p){return e.ZHCgD(b,p)}};super(),this[s(1577)+s(623)+"line"]=!0,this[s(1134)+"er"]=or,this[s(1618)]=Lp,this[s(1254)+"T"]=On,this._isMiniWX=ei,this[s(842)+"r"]=ti,this[s(1571)+s(498)]=[],this["_endpoin"+s(1653)]=null,this["_readyCl"+s(587)]=!1,this[s(583)+s(888)]=e[s(851)],this[s(744)+s(1188)]=!1,this._connectionTimeoutId=null,this["_reconne"+s(1085)+s(837)]=null,this[s(496)+s(1276)+"Id"]=null,this[s(670)]=0,this[s(1365)]=!1,this[s(473)]="",this[s(629)+"ger"]=null,this[s(875)+s(450)]=null,this[s(1804)+"sCounter"]=null,this._protocols=s(1492),this[s(1685)]=3,this[s(1323)+"NG"]=0,this[s(1344)]=1,this[s(1117)]=2,this[s(1434)]=b=>{let p=s,P={FqMIx:function(L,M){return d[q(1842)](L,M)},TNYBz:function(L,M){return d[q(483)](L,M)},LXpvI:function(L,M){return d[q(1850)](L,M)},xdGVH:function(L,M){return L&M},ESMWh:function(L,M){return L(M)},ICDYH:function(L,M){return d.onqMk(L,M)},ZzyrG:function(L,M){return L&M},rJLmX:function(L,M){return d[q(1842)](L,M)},wOjZm:function(L,M){return d.dTqbo(L,M)},AOUfG:function(L,M){return d[q(452)](L,M)},HJDlk:function(L,M){return d[q(1228)](L,M)}};try{if(d[p(981)](d[p(828)],d.omNWy))pl(this,b,[pg,gg,mg]);else{let L=_0x33b03a[p(1517)+"g"](0,IoEQLk[p(1174)](4,_0x589b03[p(1407)])),M=L[p(1528)](_0x492d7d);_0xba4954[p(932)](M)}}catch(L){if(d.tUNQw(p(706),d.HDaEK)){let M=d.KZaGU(dt,d[p(392)],{message:L[p(736)],code:rn.OPEN_ERROR,error:L});this[p(1604)+p(1055)+"ent"](M)}else _0x15a593=yHKeoF[p(609)](_0x4f98bc,_0xadfbf1),_0x147f51|=yHKeoF[p(1826)](yHKeoF.LXpvI(127,_0x1a1a90),14),yHKeoF[p(1393)](128,_0x39ab9a)&&(_0x132ccb=yHKeoF.ESMWh(_0x52a9af,_0x6ca413),_0x490699|=yHKeoF[p(334)](127&_0xa0571b,21),yHKeoF[p(1728)](128,_0x19cc9d)&&(_0x530c15=yHKeoF[p(385)](_0x2afb8e,_0x2a6961),_0x4d7104=yHKeoF[p(1730)](127,_0x5a2768),yHKeoF[p(1801)](128,_0x5a39a3)&&(_0x551d4a=yHKeoF[p(1871)](_0x4a99c4,_0x844c7f),_0x2b7dca|=yHKeoF[p(1801)](127,_0x5b8afe)<<7)))}},this[s(1284)+"ge"]=async b=>{let p=s;if(d[p(1654)](d.QSAAR,d[p(971)]))_0x2ac862=IoEQLk[p(639)](_0x39221f,_0x10331a),_0xe24997|=IoEQLk[p(1635)](IoEQLk[p(1338)](127,_0x3c4dfd),7);else{let{pingInterval:P,pingFrequency:L}=this[p(1224)];if((d[p(1706)]("hi",b.data)&&d[p(1706)](d[p(1006)],L)||d[p(1010)]===L)&&(this[p(1390)+p(1829)](),this[p(985)](d[p(656)],d.ChUyF),this[p(496)+p(1276)+"Id"]=d[p(1447)](setTimeout,this[p(780)][p(547)](this),P)),b[p(815)]==="hi")return;try{d[p(1553)](pl,this,b,[Jp,$p,hg,xg,fg,Vp])}catch(M){let G=d[p(1447)](dt,d[p(392)],{message:M[p(736)],code:rn[p(1348)+p(1288)],error:M});this[p(1604)+p(1055)+p(963)](G)}}},this[s(1159)]=b=>{let p=s,P=this[p(841)+"tManager"]?.[p(1024)+p(992)+"es"](),L=this[p(841)+"tManager"]?.[p(346)+p(1548)+"nt"]();if(P&&!b[p(736)]){let M=p(1089)+L+(p(1030)+"ax retri"+p(1294)+"ed");this[p(1604)+p(1055)+p(963)](d.gozvP(dt,d.PGYwK,{message:M,code:rn[p(1809)+p(1432)+"R"],error:b}));return}this._ws&&d[p(1794)](this[p(1551)][p(713)+"te"],this[p(1344)])&&this["_disconn"+p(821)](),this[p(1604)+"hErrorEv"+p(963)](d[p(1041)](dt,d[p(392)],{message:b[p(736)],code:rn[p(1832)+p(1026)],error:b}))},this[s(455)]=async b=>{let p=s;this[p(1613)+p(1270)](),this[p(1390)+p(1829)](),this[p(1335)+"sListeners"](),this[p(1551)]=null,this[p(744)+p(1188)]=!1;let P=this[p(841)+p(1653)]?.["checkRea"+p(992)+"es"]();if(!P&&this[p(1350)+"orOnline"]()&&!this[p(804)+p(587)]){let L=this[p(841)+p(1653)]?.["getCurre"+p(1548)+"nt"](),M=this[p(1224)][p(399)+"tInterce"+p(1696)](b[p(1105)],b[p(1606)]);this[p(1604)+"hCloseEvent"](gt(e[p(460)],{code:1006,reason:b[p(1606)]||p(1785)+"ng failed, unkno"+p(1431)+p(882)+p(1746)+L,willReconnect:M})),M&&this[p(744)]();return}if(e[p(934)](1e3,b[p(1105)])&&this[p(804)+p(587)]){this["_dispatc"+p(1500)+p(963)](e[p(435)](gt,e[p(460)],{code:1e3,reason:p(1325)})),this._endpointManager?.[p(1670)+p(747)+p(1459)](),this[p(1804)+"sCounter"]?.[p(1314)+p(1489)]();return}if(e[p(1727)](1e3,b[p(1105)])&&P){if(e[p(1093)](p(537),e[p(1594)]))return _0x1633a6&&IoEQLk[p(948)](!0,_0x476dc2[p(1115)]);{let L=this[p(841)+"tManager"]?.[p(346)+"ntEndpoint"](),M=b[p(1606)];M||(M=await e[p(1101)](Hp,this[p(473)])),M=p(1785)+"ng faile"+p(1642)+M+(p(790)+p(897))+L+(p(861)+p(1273)+p(650)),this[p(1604)+p(1500)+p(963)](gt(e[p(460)],{code:b[p(1105)],reason:M}));let G="connect "+L+(p(1030)+"ax retri"+p(1294)+"ed");this[p(1604)+"hErrorEv"+p(963)](e[p(563)](dt,e[p(465)],{message:G,code:rn[p(1809)+p(1432)+"R"]})),this[p(841)+p(1653)]?.[p(1670)+p(747)+p(1459)](),this[p(1804)+p(620)]?.[p(1314)+p(1489)]();return}}if(b[p(1105)]!==1e3&&!b.reason){let L=this["_endpoin"+p(1653)]?.[p(346)+p(1548)+"nt"]();this[p(1604)+p(1500)+"ent"](e[p(563)](gt,e[p(460)],{code:b.code,reason:p(1785)+p(1884)+"d, unknown reason, hostname: "+L})),this[p(841)+"tManager"]?.[p(1670)+"pointCon"+p(1459)](),this[p(1804)+p(620)]?.[p(1314)+p(1489)]();return}this._dispatchCloseEvent(b),this["_endpoin"+p(1653)]?.[p(1670)+"pointConfig"](),this[p(1804)+p(620)]?.["resetCou"+p(1489)]()},this[s(1560)]=null,this[s(430)]=null,this.onmessage=null,this[s(1701)]=null,this[s(439)+s(370)]=null,this["onReceiv"+s(752)]=null,this[s(1337)+s(763)+"yReconnect"]=null,this[s(482)+s(395)]=this[s(482)+s(395)][s(547)](this),this[s(482)+s(1208)]=this[s(482)+"ffLine"][s(547)](this),this["_handleP"+s(1057)]=this[s(511)+s(1057)][s(547)](this),this[s(511)+s(1861)]=this["_handleP"+s(1861)][s(547)](this),this[s(1224)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1681)](1,0),service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[s(1693)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1231)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:w}=n,m=Array[s(912)](h)?h:e[s(1741)](e[s(1710)],typeof h)?[h]:[];if(!m||e[s(1373)](0,m[s(1407)]))throw new Error(e[s(760)]);if(!e[s(1758)](Bp,w))throw new Error("please p"+s(1361)+s(1732)+s(717)+s(1810)+s(506)+s(382)+s(443));Object[s(904)](this[s(1224)],n),this[s(841)+s(1653)]=new xl(m,this[s(1224)][s(1533)+"es"]),this[s(1804)+"sCounter"]=new Up(this[s(1224)]["pingLoss"+s(315)]),this[s(1224)][s(1072)+s(631)]&&(this[s(1365)]=!0,this[s(744)]()),this._options[s(463)+s(727)+s(568)]&&(this[s(1254)+"T"]||this[s(1490)+"X"]?this[s(1646)+"etWorkCh"+s(432)]():this[s(1134)+"er"]&&this[s(1185)+s(1770)+s(1559)]())}[t(482)+t(395)](){let n=t;this[n(1224)][n(1485)+n(898)+n(1157)]||this[n(804)+n(587)]||this[n(1720)+"econnect"]()}[t(482)+t(1208)](){let n=t;this["_destroy"+n(917)+"t"]();let s=ma(n(399)+"t",{message:e.hMcHq});this["onStopImmediatel"+n(669)+"ct"]&&this[n(1337)+n(763)+n(669)+"ct"](s)}[t(1185)+t(1770)+t(1559)](){let n=t;this._isBrowser&&window[n(1509)+n(1559)]("online",this[n(482)+n(395)]),this[n(1134)+"er"]&&window[n(1509)+n(1559)](e.xNGap,this[n(482)+n(1208)]),this[n(1134)+"er"]&&window[n(1509)+"Listener"](n(1395),this[n(511)+n(1057)]),this._isBrowser&&window[n(1509)+n(1559)](e[n(957)],this[n(511)+"ageShow"])}[t(1111)+t(1770)+"Listener"](){let n=t,s={SofZf:e[n(460)]};e[n(1219)](e[n(685)],e[n(685)])?(this[n(1134)+"er"]&&window["removeEv"+n(864)+n(1499)](n(354),this[n(482)+n(395)]),this[n(1134)+"er"]&&window[n(1193)+n(864)+n(1499)](e[n(1360)],this[n(482)+"ffLine"]),this[n(1134)+"er"]&&window[n(1193)+n(864)+n(1499)](e[n(1807)],this[n(511)+"ageHide"]),this[n(1134)+"er"]&&window[n(1193)+"entListe"+n(1499)](e[n(957)],this[n(511)+"ageShow"])):(_0x4f47db&&_0x49eb18[n(1509)+n(1559)](LyjaNv[n(1038)],()=>_0x6de5bd()),_0x50af87&&_0x18ebff[n(1509)+n(1559)]("versionc"+n(406),()=>_0x366382()))}[t(511)+t(1057)](n){let s=t;!n[s(1399)+"d"]&&(this._isBrowser&&window[s(1193)+s(864)+s(1499)](s(1395),this["_handleP"+s(1057)]),this[s(1134)+"er"]&&window[s(1193)+s(864)+"ner"](s(359),this["_handleP"+s(1861)]),this[s(1769)]()),this[s(1134)+"er"]&&window[s(1193)+"entListener"](e[s(768)],this[s(482)+"nLine"]),this._isBrowser&&window[s(1193)+s(864)+s(1499)](e[s(1360)],this[s(482)+s(1208)])}[t(511)+t(1861)](n){let s=t;n[s(1399)+"d"]&&(this[s(1350)+s(1418)]()&&(!this[s(1551)]||this[s(1551)].readyState!==this.OPEN||e.sYMBO(this[s(1551)][s(713)+"te"],this[s(1323)+"NG"]))&&this[s(482)+s(395)](),this[s(1134)+"er"]&&window[s(1509)+s(1559)](e.ujprw,this[s(482)+s(395)]),this[s(1134)+"er"]&&window[s(1509)+"Listener"](e[s(1360)],this["_handleO"+s(1208)]))}async[t(743)+"eUrl"](n){let s=t,{fpID:d,deviceID:h,bddID:w,ttwID:m,accessKey:b,aID:p,customParams:P={},enableAutoAck:L,enableQoS:M,QoSLevel:G,env:J}=this._options,Z,we,fe;this._isBrowser||this._isMiniWX||this[s(1254)+"T"]?(Z=location&&location[s(1438)]=="https:"?e[s(675)]:e.QXobR,we=n[s(827)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),fe=/^wss(.*:\/\/)/[s(1676)](n)?n:""+Z+we):(Z=e.kcPmj,we=n[s(827)](/(^http)((?:[s]*:\/\/))/,""),fe=/(^ws)((?:[s]*:\/\/))/[s(1676)](we)?we:""+Z+we);let ae=w?s(1279):m?e[s(918)]:e[s(355)],At=w||m||h;if(e[s(1180)](!At,!ae))throw new Error(s(477)+s(1020)+s(1718)+s(709)+"r ttwID");let _g=e[s(908)](s(697),typeof P)?await e[s(820)](P):P,yg=J?zp(J[s(1806)],J.xTTEnv):{},Ia=Object[s(904)]({device_platform:e[s(541)],version_code:e[s(503)],access_key:b,fpid:d,aid:p,[ae]:At,xsack:L?1:0,xaack:L?1:0,xsqos:M?1:0,qos_level:M?G:void 0,qos_sdk_version:2,...yg},_g),Eg=Object[s(1709)](Ia)[s(1687)]((Aa,ka)=>Ia[ka]!==void 0?""+Aa+(Aa?"&":"?")+ka+"="+Ia[ka]:Aa,"");return fe+s(589)+Eg}async[t(744)](){let n=t,s={XLcma:function(d,h){return e.jSnzU(d,h)},iNRzE:function(d,h){return e[q(860)](d,h)},SfeZB:function(d,h){return d+h},OVHhn:function(d,h){return d(h)},ulcTe:function(d,h){return e[q(608)](d,h)},qUSHe:function(d,h){return e[q(1568)](d,h)},vNXRG:function(d,h){return e.IiqBZ(d,h)}};if(!(this[n(744)+"Lock"]||this[n(804)+n(587)])){this[n(744)+n(1188)]=!0;try{let d=this[n(841)+"tManager"]?.[n(962)+n(988)+n(1841)+n(1498)+n(657)](),{timeoutInterval:h}=this._options;if(d){let m=this[n(841)+"tManager"]?.["getCurre"+n(1548)+"nt"](),b=this["_endpoin"+n(1653)]?.["replaceB"+n(1862)+n(836)+n(839)+"unt"](),p=this[n(841)+"tManager"]?.[n(346)+n(1548)+n(1009)+"ount"]();if(b){let P=n(1089)+m+(n(983)+n(861)+n(1273)+"ached, will use "+n(1415)+n(654))+b+(n(1099)+"y"),L=e[n(1368)](dt,n(1069),{message:P,code:rn["MAX_RETR"+n(1432)+"R"]});this[n(1198)](P),this[n(1604)+n(1055)+n(963)](L),this[n(473)]=await this[n(743)+n(848)](b),this[n(1198)](n(1089)+b+" "+p+n(1141)),this._removeWsListeners()}else{let P=n(1089)+m+(n(983)+n(861)+n(1273)+n(650));this[n(1198)](P),this["_dispatc"+n(1055)+n(963)](e[n(1441)](dt,e[n(465)],{message:P,code:rn[n(1809)+"IES_ERROR"]}));return}}else if(e[n(1061)](e[n(1060)],e[n(1060)])){if(goWGgD.XLcma(_0x29d223,1)||goWGgD.iNRzE(_0x1dc40d,_0x3f3ec5))return _0x13cfca(_0x20f422);goWGgD[n(1076)](goWGgD[n(1286)](_0x292afb,_0x4a8059),_0x1e426c)&&(_0x7aa8cc=goWGgD.OVHhn(_0x1f261d,_0x50ce74),_0x3ad941=0);let m=_0x2c0e15.call(_0xb354be,_0x4a6636,_0x2ef684+=_0x34a56c);return goWGgD[n(1014)](7,_0x513623)&&(_0x123307=goWGgD[n(1445)](goWGgD[n(1138)](7,_0x25fd22),1)),m}else{let m=this[n(841)+"tManager"]?.[n(346)+n(1548)+n(1605)+n(796)](),b=this[n(841)+n(1653)]?.[n(346)+n(1548)+n(1009)+"ount"]();this[n(473)]=await this[n(743)+n(848)](e[n(941)](m,"")),this._debug(n(1089)+m+" "+b+n(1141)),this[n(1335)+n(1155)+"rs"]()}if(this[n(1365)])this[n(1365)]=!1;else{let m=ma("reconnect",{message:n(1714)});this[n(439)+n(370)]&&this["onStartR"+n(370)](m)}let w=this[n(841)+n(1653)]?.[n(346)+n(1548)+n(1009)+n(651)]()||0;w>1&&await this._wait(w-1),this[n(1198)]("connecting url: "+this._url+(" protoco"+n(1008))+this[n(742)+"ls"]),this[n(1551)]=e[n(1229)](Mp,{url:this[n(473)],protocols:[this[n(742)+"ls"]],headers:this[n(1224)][n(390)+n(739)+"s"][n(1078)+n(1122)]},this[n(1224)].ws),(this[n(1134)+"er"]||this[n(842)+"r"])&&this[n(1551)]&&(this[n(1551)][n(867)+"pe"]=this[n(583)+n(888)]),this[n(781)+"steners"](),this[n(744)+n(438)+"utId"]=e.IOERG(setTimeout,this._onTimeout[n(547)](this),h)}catch(d){throw this[n(744)+"Lock"]=!1,d}}}["_clearTi"+t(1270)](){let n=t;e.bqyiz(clearTimeout,this[n(744)+n(438)+n(598)]),this[n(744)+n(438)+n(598)]=null}[t(1390)+t(1829)](){let n=t;e[n(788)](clearTimeout,this[n(496)+n(1276)+"Id"]),e[n(1752)](clearTimeout,this[n(928)+"ctTimeoutId"]),this[n(496)+n(1276)+"Id"]=null,this["_reconne"+n(1085)+"tId"]=null}[t(1198)](...n){let s=t;if(e[s(339)](e[s(674)],e[s(1214)])){let d=(s(728)+"0|1")[s(557)]("|"),h=0;for(;;){switch(d[h++]){case"0":_0x1b143f=new _0xa969bf;continue;case"1":_0x260517(w=>({...w,get:(m,b,p)=>_0x5aec39(m,b)||w.get(m,b,p),has:(m,b)=>!!_0x460780(m,b)||w.has(m,b)}));continue;case"2":_0x5f4b66=[PBuhzc[s(1252)],"add",s(1562),PBuhzc.vpYQX];continue;case"3":PBuhzc.THjbH(_0x37f7fc);continue;case"4":_0x4f9a4e=[PBuhzc[s(1813)],PBuhzc[s(854)],PBuhzc[s(956)],PBuhzc[s(803)],PBuhzc[s(1430)]];continue;case"5":_0x46c256();continue}break}}else this[s(1224)][s(1136)]&&console[s(1212)][s(1493)](console,[e.cjKPr,...n])}[t(707)+t(542)+"e"](n){let s=t,{initReconnectInterval:d,maxReconnectInterval:h,reconnectIntervalGrowFactor:w}=this._options,m=e[s(844)](d,Math.pow(w,n-1));return e.XrpIY(m,h)?h:m}[t(780)](){let n=t;if(this._ws&&e[n(1206)](this[n(1551)][n(713)+"te"],this[n(1323)+"NG"])){this[n(1390)+n(1829)](),this[n(496)+n(1276)+"Id"]=setTimeout(this._ping[n(547)](this),this[n(1224)][n(952)+"rval"]);return}if(!this[n(1551)]||e[n(692)](this._ws.readyState,this[n(1344)]))return void this[n(1720)+n(370)]();this._ws&&this._ws[n(596)]("hi"),this[n(928)+n(1085)+"tId"]=e[n(1467)](setTimeout,this[n(1720)+n(370)+"Timeout"].bind(this),this[n(1224)]["pingTime"+n(1047)+n(1524)])}[t(1720)+t(370)+t(1624)](){let n=t;this["_pingLos"+n(620)]?.[n(964)](),this[n(985)](e[n(884)],e[n(749)]),this[n(1804)+"sCounter"]?.[n(1024)+n(444)+"nt"]()?this[n(1720)+n(370)]():this[n(780)]()}[t(1350)+t(1418)](){let n=t;return this._isMiniTT||this[n(1490)+"X"]?this["_miniNav"+n(623)+"line"]:(this[n(1134)+"er"]||this[n(842)+"r"])&&this[n(1224)][n(463)+n(727)+n(568)]?navigator[n(638)]:!0}[t(1720)+"econnect"](){let n=t;!this[n(1350)+n(1418)]()||this[n(804)+n(587)]||(this[n(841)+n(1653)]?.[n(1670)+n(747)+n(1459)](),this[n(1804)+"sCounter"]?.[n(1314)+"nter"](),this[n(1551)]?this[n(1572)+n(821)](1001,e.etDSq,!0):this[n(744)]())}[t(1646)+t(570)+t(432)](){let n=t;this[n(1254)+"T"]?tt[n(1704)+n(425)+n(406)](({isConnected:s})=>{let d=n;this[d(1577)+d(623)+d(1683)]=s,s?this[d(482)+d(395)]():this[d(482)+"ffLine"]()}):this[n(1490)+"X"]&&wx[n(1704)+n(425)+n(406)](({isConnected:s})=>{let d=n;this[d(1577)+d(623)+"line"]=s,s?this["_handleO"+d(395)]():this[d(482)+d(1208)]()})}[t(497)](n){return new Promise(s=>{let d=q;e[d(978)](setTimeout,s,this[d(707)+d(542)+"e"](n))})}[t(1572)+"ect"](n=1e3,s="",d=!1){let h=t;this._ws&&this["_destroy"+h(917)+"t"](n,s,d)}_onTimeout(){let n=t;if(e.xgclC(e.UAjEB,e[n(1716)])){let s=_0x4561fe[n(1589)+"At"](_0x3fc80d);e[n(1176)](s,55296)&&e[n(1249)](s,56319)&&e[n(1860)](e[n(716)](_0xbb808f,1),_0x123d9b)&&(s=e[n(996)](e[n(652)](e[n(1791)](s,10),_0x32e212[n(1589)+"At"](++_0x396b84)),56613888)),_0x4c7d4f+=e[n(1275)](s,128)?1:e.SnKJf(s,2048)?2:e[n(579)](s,65536)?3:4}else{let s=this["_endpoin"+n(1653)]?.[n(346)+n(1548)+"nt"]();this[n(1198)]("connect "+s+n(983)),this[n(1572)+n(821)](1001,n(1362)+n(1684)+n(1402)+"g",!0)}}[t(1307)](n){let s=t,d=Ut(n);this[s(1551)]&&e[s(1501)](this[s(1551)].readyState,this.OPEN)&&(this._ws&&this[s(1551)].send(d),this[s(1198)](e.qSduL,n))}[t(1335)+t(1155)+"rs"](){let n=t,s=e[n(817)][n(557)]("|"),d=0;for(;;){switch(s[d++]){case"0":this[n(1551)][n(1193)+"entListener"](e[n(1063)],this[n(1434)]);continue;case"1":this[n(1551)][n(1193)+n(864)+n(1499)](e[n(465)],this[n(1159)]);continue;case"2":if(!this._ws)return;continue;case"3":this._ws.removeEventListener(n(736),this[n(1284)+"ge"]);continue;case"4":this[n(1551)].removeEventListener(e.fIsLz,this[n(455)]);continue}break}}[t(781)+"steners"](){let n=t,s=e[n(954)][n(557)]("|"),d=0;for(;;){switch(s[d++]){case"0":if(!this[n(1551)])return;continue;case"1":this[n(1551)][n(1509)+"Listener"](e[n(460)],this[n(455)]);continue;case"2":this[n(1551)][n(1509)+"Listener"](e[n(465)],this[n(1159)]);continue;case"3":this[n(1551)][n(1509)+n(1559)](n(832),this[n(1434)]);continue;case"4":this._ws[n(1509)+n(1559)](e[n(1526)],this[n(1284)+"ge"]);continue}break}}[t(846)+t(1383)](n=1e3,s=""){let d=t;try{this[d(1551)]&&this[d(1551)][d(1769)](n,s)}catch{}}["_destroy"+t(917)+"t"](n=1e3,s="",d=!1){let h=t,w={ZKCAg:function(m,b){return e[q(1261)](m,b)},QtnZb:function(m,b){return m(b)}};if(this["_clearPi"+h(1829)](),this[h(1613)+"mer"](),this["_removeW"+h(1155)+"rs"](),this[h(846)+h(1383)](1e3,s),this[h(744)+"Lock"]=!1,d&&this[h(1350)+h(1418)]()&&!this[h(804)+h(587)]){if(this["_endpoin"+h(1653)]?.[h(1024)+"chMaxTries"]())if(e[h(1797)](h(1536),e[h(1251)])){let b=this[h(841)+h(1653)]?.getCurrentEndpoint();this["_dispatchCloseEv"+h(963)](gt(e[h(460)],{code:1006,reason:"connect "+b+(h(983)+h(861)+h(1273)+h(650)),wasClean:!0}))}else return TwnNwd[h(1379)](_0x326c1a,_0x36f9de[h(1493)](TwnNwd[h(1116)](_0x54fb0a,this),_0xa3b7a6));else{let b=this[h(1224)][h(399)+h(916)+"ptor"](n,s);this._dispatchCloseEvent(gt(e[h(460)],{code:n,reason:s,wasClean:!0,willReconnect:b})),b&&this[h(744)]()}return}this._navigatorOnline()||this[h(804)+"osed"]?this[h(1604)+h(1500)+h(963)](e[h(1368)](gt,"close",{code:n,reason:h(1325)})):this[h(1604)+h(1500)+"ent"](e[h(1094)](gt,h(1769),{code:1006,reason:e.QrfAi})),this._ws=null,this[h(841)+"tManager"]?.[h(1670)+h(747)+"fig"](),this[h(1804)+"sCounter"]?.[h(1314)+h(1489)]()}[t(1604)+t(1149)+"nt"](n){let s=t;this[s(985)](e[s(1063)],n),this[s(1701)]&&this.onopen(n)}[t(1604)+t(456)+t(879)](n){let s=t;this[s(985)](e[s(1526)],n),this[s(1870)+"e"]&&this[s(1870)+"e"](n)}["_dispatchAckMess"+t(809)](n){let s=t;this.emit(e[s(1003)],n),this[s(1169)+s(752)]&&this[s(1169)+s(752)](n)}[t(1604)+"hErrorEv"+t(963)](n){let s=t;this[s(985)](e[s(465)],n),this.onerror&&this.onerror(n)}["_dispatc"+t(1500)+"ent"](n){let s=t,d={oxkff:function(h,w){return h(w)},OhhFw:function(h,w){return e.ONkfM(h,w)},pRDla:e[s(426)],xkirs:e[s(958)]};if(e.njuur(e[s(748)],e.LsZkQ)){let h=_0xf968da[s(557)](/\./).map(b=>_0x19141b(b)),w=[];return w[0]=myNlyT[s(801)](_0x5f15c1,h[0]+h[1]),w[1]=myNlyT[s(801)](_0x355834,myNlyT[s(693)](h[2],h[3])),[myNlyT.pRDla,myNlyT.pRDla,myNlyT.pRDla,s(1310),myNlyT[s(859)],myNlyT[s(1123)],w[0],w[1]][s(1086)]("")}else this[s(985)](e.fIsLz,n),this[s(1560)]&&this.onclose(n)}get[t(867)+"pe"](){let n=t;return this[n(1551)]?this[n(1551)][n(867)+"pe"]:this[n(583)+n(888)]}set[t(867)+"pe"](n){let s=t;this[s(583)+s(888)]=n,this[s(1551)]&&(this[s(1551)][s(867)+"pe"]=n)}get[t(1012)+"nt"](){let n=t;return this[n(841)+n(1653)]?.["getCurre"+n(1548)+n(1009)+n(651)]()||0}get[t(411)+"Amount"](){let n=t,s=this[n(1571)+n(498)][n(1687)]((d,h)=>(d+=h&&h[n(1232)+"th"]||0,d),0);return e[n(1e3)](s,this[n(1551)]?this[n(1551)][n(411)+n(1113)]:0)}get[t(530)+"ns"](){let n=t;return this._ws?this[n(1551)][n(530)+"ns"]:""}get[t(1438)](){let n=t;return this[n(1551)]?this[n(1551)][n(1438)]:""}get[t(713)+"te"](){let n=t;return this[n(1551)]?this[n(1551)].readyState:this[n(1224)][n(1072)+n(631)]?this.CONNECTING:this[n(1685)]}get[t(1311)](){let n=t;return this[n(1551)]?this[n(1551)].url:this[n(473)]}[t(1769)](n=1e3,s){let d=t;if(this[d(804)+d(587)]=!0,this["_clearTi"+d(1270)](),this[d(1390)+d(1829)](),this["_dropGlo"+d(1770)+d(1559)](),this[d(629)+d(1329)]?.[d(1363)](),!this._ws)return void this[d(1198)](e[d(729)]);if(e[d(1245)](this[d(1551)].readyState,this.CLOSED)||e[d(753)](this[d(1551)][d(713)+"te"],this[d(1117)]))return void this._debug(d(733)+"s alread"+d(695));this[d(423)+d(917)+"t"](n,s)}async[t(596)](n,s){let d=t,h={TXxer:function(fe,ae,At){return e.Fmhyo(fe,ae,At)}};if(e[d(521)](null,n))throw new Error(e[d(1042)]);e.EBQMx(e.lwWfJ,typeof n)&&(n=JSON.stringify(n)),e[d(1710)]!=typeof n&&!e[d(615)](n,ArrayBuffer)&&!(n[d(566)]&&e[d(1374)](n[d(566)],ArrayBuffer))&&(n=JSON[d(1202)+"y"](n));let w=await wl(n),m=e[d(1317)](Fp,n),{method:b=0,service:p=this._options[d(974)],logID:P=this._options["logIDGen"+d(668)](),headers:L=this._options.headers,payloadEncoding:M=this[d(1224)][d(532)+d(1293)],payloadType:G=this[d(1224)][d(1700)+d(888)],logIDNew:J=this[d(1224)][d(427)+d(1511)][d(1520)+d(887)+"teLogIDNew"]?e.yevXL(i,this[d(1224)][d(427)+d(1511)][d(1838)]):""}=e.NNYzI(s,{});if(!p)throw new Error(e[d(612)]);let Z={SeqID:he[d(1204)+"er"](this[d(670)]++),LogID:he[d(1204)+"er"](P),service:p,method:b,headers:L,payloadEncoding:e[d(441)](M,Object)?M.encoding?M[d(1867)]:"":M,payloadType:e.bbwkK(G,Object)?G[d(327)]?G[d(327)]:m:G||m,payload:w,LogIDNew:J},we=Ut(Z);return this._ws&&e[d(1876)](this[d(1551)][d(713)+"te"],this.OPEN)?(this[d(1551)]&&this[d(1551)][d(596)](we),this._debug(e[d(1032)],Z)):e[d(1740)](this["_message"+d(498)][d(1407)],this[d(1224)]["maxMessageQueueL"+d(1153)])?e[d(1843)]===e[d(1847)]?(QCfZrR[d(1863)](_0x21f3fd,_0x288c8c,82),QCfZrR.TXxer(_0x2eb7f2,_0x1aeed4,_0x4f61be)):(this[d(1571)+d(498)].push(we),this[d(1198)](e[d(1525)],Z)):(this[d(1571)+d(498)][d(1209)](),this[d(1571)+d(498)][d(932)](we)),{seqID:this[d(670)],logID:P,logIDNew:J}}async[t(399)+"t"](n){let s=t,{url:d}=e.GHKTo(n,{}),h=Array[s(912)](d)?d:e.yRXdG(s(1034),typeof d)?[d]:[];n&&Object[s(904)](this[s(1224)],n),h&&h[s(1407)]?this[s(841)+"tManager"]=new xl(h,this[s(1224)][s(1533)+"es"]):this[s(841)+s(1653)]?.[s(1670)+s(747)+s(1459)](),this[s(1804)+s(620)]?.[s(1314)+s(1489)](this[s(1224)][s(1067)+"Count"]),this["_readyCl"+s(587)]=!1,this[s(1551)]&&e.qYfxJ(this[s(1551)][s(713)+"te"],this[s(1685)])?this[s(1572)+"ect"](1e3,e.WiMYy,!0):(this[s(1365)]=!0,this[s(744)]())}async[t(655)](){let n=t;!this[n(744)+n(1188)]&&(e[n(420)](e.lgUUN,e[n(1738)])?this._qosDB?.[n(522)](_0x3054eb.message_id):(this[n(841)+n(1653)]?.[n(1670)+n(747)+n(1459)](),this["_pingLos"+n(620)]?.resetCounter(),this["_readyCl"+n(587)]=!1,this[n(1365)]=!0,this[n(744)]()))}["addEvent"+t(1559)](n,s){this.on(n,s)}[t(1210)+t(879)](n){let s=t,{type:d}=n;this[s(985)](d,n)}["removeEv"+t(864)+t(1499)](n,s){this.off(n,s)}[t(1763)](){let n=t,s={FzrDN:function(d,h){return e[q(475)](d,h)},clzQV:e[n(1839)],Kmwbc:e[n(1694)],ciQbq:n(1246)+n(1570)+"t"};return new Promise((d,h)=>{let w=n,m={CZKoT:function(P,L){return e.zsnsH(P,L)},sBGfX:e.KWqDC};this[w(1390)+w(1829)](),this._pingPongTimeoutId=setTimeout(this[w(780)][w(547)](this),this[w(1224)][w(952)+w(989)]);let b=()=>{let P=w;s[P(1632)](d,s.clzQV),this[P(724)](s[P(1486)],b),this[P(724)](s[P(526)],p)},p=()=>{let P=w;m[P(1339)](h,m.sBGfX),this[P(724)](P(1246)+P(967)+"s",b),this[P(724)]("ping_once_timeout",p)};this.on(e[w(1694)],b),this.on(e.fQset,p),this._ping()})}}})(),Fe[N(593)+N(1817)]=Oe[N(593)+N(1817)],Fe[N(869)+N(514)]=Oe["CustomEr"+N(514)],Fe[N(1017)+"e"]=Oe[N(1017)+"e"],Fe.Event=Oe[N(879)],Fe[N(829)]=Oe.FWS,Fe[N(878)+N(1002)+N(372)]=Oe[N(878)+N(1002)+"vent"],Fe[N(1002)+"vent"]=Oe[N(1002)+N(372)],Fe.OpenEvent=Oe[N(1495)+"t"],Fe[N(1154)+N(1213)]=Oe[N(1154)+N(1213)],Fe[N(1291)+N(1817)]=Oe.createCloseEvent,Fe["createEr"+N(514)]=Oe["createEr"+N(514)],Fe[N(1302)+"ssageEvent"]=Oe[N(1302)+N(421)+"nt"],Fe[N(1341)+N(1319)]=Oe[N(1341)+N(1319)],Fe[N(890)+"connectE"+N(372)]=Oe[N(890)+N(1049)+N(372)],Fe[N(1427)+N(1537)]=Oe[N(1427)+N(1537)],Fe[N(1627)+N(1573)]=Oe[N(1627)+N(1573)];for($o in Oe)[N(593)+N(1817),N(869)+N(514),N(1017)+"e","Event",N(829),"FrontierMessageE"+N(372),N(1002)+N(372),N(1495)+"t","Reconnec"+N(1213),"createCl"+N(1817),N(731)+"rorEvent",N(1302)+N(421)+"nt",N(1341)+N(1319),N(890)+N(1049)+N(372),"decodedF"+N(1537),N(1627)+N(1573)][N(662)]($o)===-1&&(Fe[$o]=Oe[$o]);var $o;Object["definePr"+N(877)](Fe,N(1277)+"le",{value:!0})});import{existsSync as zS,openSync as US}from"node:fs";import{mkdir as HS}from"node:fs/promises";import{dirname as GS}from"node:path";import{fileURLToPath as qS}from"node:url";function KS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Wd(t=Y()){return zS(t.libEntry)?t.libEntry:qS(new URL("../index.ts",import.meta.url))}async function Jx(t={}){let e=t.paths??Y(),r=t.entryOverride??Wd(e),i=KS(e,process.env.COZE_BRIDGE_LOG_MODE);await HS(GS(i),{recursive:!0});let o=US(i,"a"),l=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=it(process.execPath,l,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[as]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return jS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var jS,as,ia=nt(()=>{"use strict";Vt();ne();Re();jS=H("spawn-daemon"),as="COZE_BRIDGE_DAEMON"});import{spawn as z1}from"node:child_process";import{mkdir as U1,unlink as H1,writeFile as G1}from"node:fs/promises";import{dirname as q1,join as j1}from"node:path";function Yr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function K1(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Yr(r)}</key>
21
21
  <string>${Yr(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function R1(t,e){return new Promise((n,i)=>{let s=S1(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 Zr,ds,ca,Qd,xp=rt(()=>{"use strict";ee();Zr=q("supervisor.launchd"),ds="ai.coze.bridge",ca=R1,Qd={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function W1(t,e){return new Promise((r,i)=>{let o=z1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var Zr,ds,ua,tl,pp=nt(()=>{"use strict";ne();Zr=H("supervisor.launchd"),ds="ai.coze.bridge",ua=W1,tl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
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>
@@ -44,11 +44,11 @@ ${e}
44
44
  <key>StandardOutPath</key>
45
45
  <string>${Yr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Yr(t.logFile)}</string>${D1(t.env)}
47
+ <string>${Yr(t.logFile)}</string>${K1(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return C1(t.homeDir,"Library","LaunchAgents",`${ds}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await I1(k1(i),{recursive:!0}),await T1(i,this.renderConfig(t),"utf8"),Zr.info("plist written",{plistPath:i,activate:n}),!n)return;await ca("launchctl",["unload","-w",i]).catch(c=>Zr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ca("launchctl",["load","-w",i]),Zr.info("launchd job loaded",{label:ds});let s=process.getuid?.()??0;await ca("launchctl",["kickstart","-k",`gui/${s}/${ds}`]),Zr.info("launchd job kickstarted",{label:ds,uid:s})},async uninstall(t){let e=this.configPath(t);await ca("launchctl",["unload","-w",e]).catch(n=>Zr.warn("launchctl unload failed (ignored)",{err:String(n)})),await A1(e).catch(n=>{if(n.code!=="ENOENT")throw n}),Zr.info("launchd job removed",{plistPath:e})}}});import{spawn as P1}from"node:child_process";import{mkdir as O1,unlink as L1,writeFile as N1}from"node:fs/promises";import{dirname as M1,join as pp}from"node:path";function la(t,e){return t.isRoot?e:["--user",...e]}function F1(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function ua(t,e){return new Promise((n,i)=>{let s=P1(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 da,Xr,B1,el,gp=rt(()=>{"use strict";ee();da=q("supervisor.systemd"),Xr="coze-bridge.service",B1="/etc/systemd/system";el={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return j1(t.homeDir,"Library","LaunchAgents",`${ds}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await U1(q1(i),{recursive:!0}),await G1(i,this.renderConfig(t),"utf8"),Zr.info("plist written",{plistPath:i,activate:r}),!r)return;await ua("launchctl",["unload","-w",i]).catch(c=>Zr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ua("launchctl",["load","-w",i]),Zr.info("launchd job loaded",{label:ds});let o=process.getuid?.()??0;await ua("launchctl",["kickstart","-k",`gui/${o}/${ds}`]),Zr.info("launchd job kickstarted",{label:ds,uid:o})},async uninstall(t){let e=this.configPath(t);await ua("launchctl",["unload","-w",e]).catch(r=>Zr.warn("launchctl unload failed (ignored)",{err:String(r)})),await H1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Zr.info("launchd job removed",{plistPath:e})}}});import{spawn as $1}from"node:child_process";import{mkdir as V1,unlink as J1,writeFile as Z1}from"node:fs/promises";import{dirname as Y1,join as gp}from"node:path";function ha(t,e){return t.isRoot?e:["--user",...e]}function Q1(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function xa(t,e){return new Promise((r,i)=>{let o=$1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var fa,Xr,X1,nl,mp=nt(()=>{"use strict";ne();fa=H("supervisor.systemd"),Xr="coze-bridge.service",X1="/etc/systemd/system";nl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
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
- ${F1(t.env)}
62
+ ${Q1(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?pp(B1,Xr):pp(t.homeDir,".config","systemd","user",Xr)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),s=t.isRoot?"system":"user";await O1(M1(i),{recursive:!0}),await N1(i,this.renderConfig(t),"utf8"),da.info("systemd unit written",{unitPath:i,mode:s,activate:n}),await ua("systemctl",la(t,["daemon-reload"])),await ua("systemctl",la(t,n?["enable","--now",Xr]:["enable",Xr])),da.info("systemd unit enabled",{unitName:Xr,mode:s,activate:n})},async uninstall(t){let e=this.configPath(t);await ua("systemctl",la(t,["disable","--now",Xr])).catch(n=>da.warn("systemctl disable failed (ignored)",{err:String(n)})),await L1(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await ua("systemctl",la(t,["daemon-reload"])).catch(()=>{}),da.info("systemd unit removed",{unitPath:e})}}});import{spawn as z1}from"node:child_process";import{join as U1}from"node:path";function mp(t,e){return new Promise((n,i)=>{let s=z1(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 tl,fa,nl,wp=rt(()=>{"use strict";ee();tl=q("supervisor.taskscheduler"),fa="CozeBridge",nl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?gp(X1,Xr):gp(t.homeDir,".config","systemd","user",Xr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await V1(Y1(i),{recursive:!0}),await Z1(i,this.renderConfig(t),"utf8"),fa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await xa("systemctl",ha(t,["daemon-reload"])),await xa("systemctl",ha(t,r?["enable","--now",Xr]:["enable",Xr])),fa.info("systemd unit enabled",{unitName:Xr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await xa("systemctl",ha(t,["disable","--now",Xr])).catch(r=>fa.warn("systemctl disable failed (ignored)",{err:String(r)})),await J1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await xa("systemctl",ha(t,["daemon-reload"])).catch(()=>{}),fa.info("systemd unit removed",{unitPath:e})}}});import{spawn as eI}from"node:child_process";import{join as tI}from"node:path";function wp(t,e){return new Promise((r,i)=>{let o=eI(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var rl,pa,il,_p=nt(()=>{"use strict";ne();rl=H("supervisor.taskscheduler"),pa="CozeBridge",il={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
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,51 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return U1(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 mp("schtasks",["/Create","/SC","ONLOGON","/TN",fa,"/TR",n,"/RU",t.userName,"/F"]),tl.info("task scheduler entry created",{task:fa,logFile:t.logFile})},async uninstall(t){await mp("schtasks",["/Delete","/TN",fa,"/F"]).catch(e=>tl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),tl.info("task scheduler entry removed",{task:fa})}}});var _p={};Aa(_p,{buildContext:()=>K1,getSupervisor:()=>H1,launchdSupervisor:()=>Qd,systemdSupervisor:()=>el,taskSchedulerSupervisor:()=>nl});import{homedir as G1,userInfo as q1}from"node:os";function H1(t=process.platform){switch(t){case"darwin":return Qd;case"linux":return el;case"win32":return nl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function W1(){let t={};for(let e of j1){let n=process.env[e];n&&(t[e]=n)}return t}function K1(){let t=X();return{nodeBin:process.execPath,entry:Hd(t),logFile:t.logFile,homeDir:G1(),userName:q1().username,isRoot:process.getuid?.()===0,env:W1()}}var j1,yp=rt(()=>{"use strict";Be();na();xp();gp();wp();j1=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ee();cn();var Pl=q("acp-installer-warmup"),Kg=["claude-code","codex"];async function Ol(t={}){let e=t.ensure??lr,i=(await Promise.allSettled(Kg.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))})}un();ee();import{readdir as cm}from"node:fs/promises";import{mkdir as Bl,readFile as om,writeFile as Fl}from"node:fs/promises";import{join as Oa}from"node:path";var am={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function hr(t,e,n){await Bl(t,{recursive:!0});let i=am[e],s=Oa(t,i);return await Fl(s,n??"","utf8"),s}async function La(t,e,n){let i=Oa(t,".claude");await Bl(i,{recursive:!0});let s=Oa(i,"settings.local.json"),c={};try{let u=await om(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 Fl(s,JSON.stringify(c,null,2),"utf8"),s}var Qe=q("agent-detail-sync"),dm=6e4,lm=5*6e4,ys=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await cm(n)}catch(s){Qe.info("agents dir not found, skip detail sync",{root:n,err:String(s)});return}Qe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async s=>{let c=await Re(s,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Qe.debug("detail sync: skip disconnected agent",{agentId:s});return}try{await this.syncOne(s,c)}catch(d){Qe.warn("detail sync failed for agent, skipping",{agentId:s,err:String(d)})}}})),Qe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,s]of this.retryQueue)e>=s.dueAt&&n.push(i);if(n.length!==0){Qe.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(s){Qe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(s)})}}}async syncOne(e,n){let i=n??await Re(e,this.opts.paths);if(!i){Qe.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){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),m=x?Math.min(x.currentDelay*2,lm):dm;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(s.agentId&&s.agentId!==e){Qe.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"?(Qe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):s.deployType&&Qe.info("detail.deployType",{agentId:e,deployType:s.deployType}),!c){Qe.debug("detail sync: no diff",{agentId:e});return}await Ue(i,this.opts.paths),Qe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Qe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await hr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var rd=Ht(mu(),1);import{createHash as j_}from"node:crypto";import{lstat as Zc,mkdir as Yc,readFile as ho,readdir as r0,rm as Xc,stat as e0,writeFile as Qc}from"node:fs/promises";import{dirname as W_,join as Je,normalize as K_,relative as nd,resolve as ed,sep as i0}from"node:path";import{Readable as s0}from"node:stream";import{pipeline as o0}from"node:stream/promises";import Pm from"events";import it from"fs";import{EventEmitter as Oc}from"node:events";import Xu from"node:stream";import{StringDecoder as Om}from"node:string_decoder";import tf from"node:path";import Ir from"node:fs";import{dirname as Km,parse as $m}from"path";import{EventEmitter as tw}from"events";import xc from"assert";import{Buffer as Wn}from"buffer";import*as Eu from"zlib";import nw from"zlib";import{posix as wr}from"node:path";import{basename as Cw}from"node:path";import Xs from"fs";import Dt from"fs";import Cu from"path";import{win32 as Gw}from"node:path";import Mu from"path";import mf from"node:fs";import i_ from"node:assert";import{randomBytes as wf}from"node:crypto";import ne from"node:fs";import ze from"node:path";import _f from"fs";import ao from"node:fs";import Ti from"node:path";import ct from"node:fs";import u_ from"node:fs/promises";import to from"node:path";import{join as Df}from"node:path";import at from"node:fs";import Of from"node:path";var Dm=Object.defineProperty,Rm=(t,e)=>{for(var n in e)Dm(t,n,{get:e[n],enumerable:!0})},wu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Lm=t=>!!t&&typeof t=="object"&&(t instanceof Vn||t instanceof Xu||Nm(t)||Mm(t)),Nm=t=>!!t&&typeof t=="object"&&t instanceof Oc&&typeof t.pipe=="function"&&t.pipe!==Xu.Writable.prototype.pipe,Mm=t=>!!t&&typeof t=="object"&&t instanceof Oc&&typeof t.write=="function"&&typeof t.end=="function",jt=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),hn=Symbol("emittedEnd"),Is=Symbol("emittingEnd"),li=Symbol("emittedError"),As=Symbol("closed"),_u=Symbol("read"),Ts=Symbol("flush"),yu=Symbol("flushChunk"),_t=Symbol("encoding"),mr=Symbol("decoder"),Ge=Symbol("flowing"),ui=Symbol("paused"),Er=Symbol("resume"),qe=Symbol("buffer"),et=Symbol("pipes"),He=Symbol("bufferLength"),Ua=Symbol("bufferPush"),ks=Symbol("bufferShift"),Xe=Symbol("objectMode"),ke=Symbol("destroyed"),Ga=Symbol("error"),qa=Symbol("emitData"),bu=Symbol("emitEnd"),Ha=Symbol("emitEnd2"),Tt=Symbol("async"),ja=Symbol("abort"),Cs=Symbol("aborted"),fi=Symbol("signal"),Mn=Symbol("dataListeners"),ot=Symbol("discarded"),hi=t=>Promise.resolve().then(t),Bm=t=>t(),Fm=t=>t==="end"||t==="finish"||t==="prefinish",zm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Um=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Qu=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Er](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Gm=class extends Qu{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)}},qm=t=>!!t.objectMode,Hm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Vn=class extends Oc{[Ge]=!1;[ui]=!1;[et]=[];[qe]=[];[Xe];[_t];[Tt];[mr];[jt]=!1;[hn]=!1;[Is]=!1;[As]=!1;[li]=null;[He]=0;[ke]=!1;[fi];[Cs]=!1;[Mn]=0;[ot]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");qm(e)?(this[Xe]=!0,this[_t]=null):Hm(e)?(this[_t]=e.encoding,this[Xe]=!1):(this[Xe]=!1,this[_t]=null),this[Tt]=!!e.async,this[mr]=this[_t]?new Om(this[_t]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[qe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:n}=e;n&&(this[fi]=n,n.aborted?this[ja]():n.addEventListener("abort",()=>this[ja]()))}get bufferLength(){return this[He]}get encoding(){return this[_t]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Xe]}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}[ja](){this[Cs]=!0,this.emit("abort",this[fi]?.reason),this.destroy(this[fi]?.reason)}get aborted(){return this[Cs]}set aborted(t){}write(t,e,n){if(this[Cs])return!1;if(this[jt])throw new Error("write after end");if(this[ke])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[Tt]?hi:Bm;if(!this[Xe]&&!Buffer.isBuffer(t)){if(Um(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(zm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Xe]?(this[Ge]&&this[He]!==0&&this[Ts](!0),this[Ge]?this.emit("data",t):this[Ua](t),this[He]!==0&&this.emit("readable"),n&&i(n),this[Ge]):t.length?(typeof t=="string"&&!(e===this[_t]&&!this[mr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[_t]&&(t=this[mr].write(t)),this[Ge]&&this[He]!==0&&this[Ts](!0),this[Ge]?this.emit("data",t):this[Ua](t),this[He]!==0&&this.emit("readable"),n&&i(n),this[Ge]):(this[He]!==0&&this.emit("readable"),n&&i(n),this[Ge])}read(t){if(this[ke])return null;if(this[ot]=!1,this[He]===0||t===0||t&&t>this[He])return this[Wt](),null;this[Xe]&&(t=null),this[qe].length>1&&!this[Xe]&&(this[qe]=[this[_t]?this[qe].join(""):Buffer.concat(this[qe],this[He])]);let e=this[_u](t||null,this[qe][0]);return this[Wt](),e}[_u](t,e){if(this[Xe])this[ks]();else{let n=e;t===n.length||t===null?this[ks]():typeof n=="string"?(this[qe][0]=n.slice(t),e=n.slice(0,t),this[He]-=t):(this[qe][0]=n.subarray(t),e=n.subarray(0,t),this[He]-=t)}return this.emit("data",e),!this[qe].length&&!this[jt]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[jt]=!0,this.writable=!1,(this[Ge]||!this[ui])&&this[Wt](),this}[Er](){this[ke]||(!this[Mn]&&!this[et].length&&(this[ot]=!0),this[ui]=!1,this[Ge]=!0,this.emit("resume"),this[qe].length?this[Ts]():this[jt]?this[Wt]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[Ge]=!1,this[ui]=!0,this[ot]=!1}get destroyed(){return this[ke]}get flowing(){return this[Ge]}get paused(){return this[ui]}[Ua](t){this[Xe]?this[He]+=1:this[He]+=t.length,this[qe].push(t)}[ks](){return this[Xe]?this[He]-=1:this[He]-=this[qe][0].length,this[qe].shift()}[Ts](t=!1){do;while(this[yu](this[ks]())&&this[qe].length);!t&&!this[qe].length&&!this[jt]&&this.emit("drain")}[yu](t){return this.emit("data",t),this[Ge]}pipe(t,e){if(this[ke])return t;this[ot]=!1;let n=this[hn];return e=e||{},t===wu.stdout||t===wu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[et].push(e.proxyErrors?new Gm(this,t,e):new Qu(this,t,e)),this[Tt]?hi(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[et].find(n=>n.dest===t);e&&(this[et].length===1?(this[Ge]&&this[Mn]===0&&(this[Ge]=!1),this[et]=[]):this[et].splice(this[et].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[ot]=!1,this[Mn]++,!this[et].length&&!this[Ge]&&this[Er]();else if(t==="readable"&&this[He]!==0)super.emit("readable");else if(Fm(t)&&this[hn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[li]){let i=e;this[Tt]?hi(()=>i.call(this,this[li])):i.call(this,this[li])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Mn]=this.listeners("data").length,this[Mn]===0&&!this[ot]&&!this[et].length&&(this[Ge]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Mn]=0,!this[ot]&&!this[et].length&&(this[Ge]=!1)),e}get emittedEnd(){return this[hn]}[Wt](){!this[Is]&&!this[hn]&&!this[ke]&&this[qe].length===0&&this[jt]&&(this[Is]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[As]&&this.emit("close"),this[Is]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==ke&&this[ke])return!1;if(t==="data")return!this[Xe]&&!n?!1:this[Tt]?(hi(()=>this[qa](n)),!0):this[qa](n);if(t==="end")return this[bu]();if(t==="close"){if(this[As]=!0,!this[hn]&&!this[ke])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(t==="error"){this[li]=n,super.emit(Ga,n);let s=!this[fi]||this.listeners("error").length?super.emit("error",n):!1;return this[Wt](),s}else if(t==="resume"){let s=super.emit("resume");return this[Wt](),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[Wt](),i}[qa](t){for(let n of this[et])n.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[Wt](),e}[bu](){return this[hn]?!1:(this[hn]=!0,this.readable=!1,this[Tt]?(hi(()=>this[Ha]()),!0):this[Ha]())}[Ha](){if(this[mr]){let e=this[mr].end();if(e){for(let n of this[et])n.dest.write(e);this[ot]||super.emit("data",e)}}for(let e of this[et])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Xe]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Xe]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Xe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[_t]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ke,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ot]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[jt])return e();let i,s,c=x=>{this.off("data",d),this.off("end",u),this.off(ke,h),e(),s(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(ke,h),this.pause(),i({value:x,done:!!this[jt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(ke,h),e(),i({done:!0,value:void 0})},h=()=>c(new Error("stream destroyed"));return new Promise((x,m)=>{s=m,i=x,this.once(ke,h),this.once("error",c),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ot]=!1;let t=!1,e=()=>(this.pause(),this.off(Ga,e),this.off(ke,e),this.off("end",e),t=!0,{done:!0,value:void 0}),n=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Ga,e),this.once(ke,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[ke])return t?this.emit("error",t):this.emit(ke),this;this[ke]=!0,this[ot]=!0,this[qe].length=0,this[He]=0;let e=this;return typeof e.close=="function"&&!this[As]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return Lm}},jm=it.writev,vn=Symbol("_autoClose"),vt=Symbol("_close"),xi=Symbol("_ended"),ue=Symbol("_fd"),Wa=Symbol("_finished"),Jt=Symbol("_flags"),Ka=Symbol("_flush"),fc=Symbol("_handleChunk"),hc=Symbol("_makeBuf"),Ii=Symbol("_mode"),Ds=Symbol("_needDrain"),Tr=Symbol("_onerror"),kr=Symbol("_onopen"),$a=Symbol("_onread"),vr=Symbol("_onwrite"),Sn=Symbol("_open"),Et=Symbol("_path"),wn=Symbol("_pos"),kt=Symbol("_queue"),Sr=Symbol("_read"),Va=Symbol("_readSize"),Vt=Symbol("_reading"),pi=Symbol("_remain"),Ja=Symbol("_size"),Us=Symbol("_write"),Bn=Symbol("_writing"),Gs=Symbol("_defaultFlag"),jn=Symbol("_errored"),Lc=class extends Vn{[jn]=!1;[ue];[Et];[Va];[Vt]=!1;[Ja];[pi];[vn];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[jn]=!1,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[Et]=t,this[Va]=e.readSize||16*1024*1024,this[Vt]=!1,this[Ja]=typeof e.size=="number"?e.size:1/0,this[pi]=this[Ja],this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[ue]=="number"?this[Sr]():this[Sn]()}get fd(){return this[ue]}get path(){return this[Et]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Sn](){it.open(this[Et],"r",(t,e)=>this[kr](t,e))}[kr](t,e){t?this[Tr](t):(this[ue]=e,this.emit("open",e),this[Sr]())}[hc](){return Buffer.allocUnsafe(Math.min(this[Va],this[pi]))}[Sr](){if(!this[Vt]){this[Vt]=!0;let t=this[hc]();if(t.length===0)return process.nextTick(()=>this[$a](null,0,t));it.read(this[ue],t,0,t.length,null,(e,n,i)=>this[$a](e,n,i))}}[$a](t,e,n){this[Vt]=!1,t?this[Tr](t):this[fc](e,n)&&this[Sr]()}[vt](){if(this[vn]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Tr](t){this[Vt]=!0,this[vt](),this.emit("error",t)}[fc](t,e){let n=!1;return this[pi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[pi]<=0)&&(n=!1,this[vt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[ue]=="number"&&this[Sr](),!1;case"error":return this[jn]?!1:(this[jn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Wm=class extends Lc{[Sn](){let t=!0;try{this[kr](null,it.openSync(this[Et],"r")),t=!1}finally{t&&this[vt]()}}[Sr](){let t=!0;try{if(!this[Vt]){this[Vt]=!0;do{let e=this[hc](),n=e.length===0?0:it.readSync(this[ue],e,0,e.length,null);if(!this[fc](n,e))break}while(!0);this[Vt]=!1}t=!1}finally{t&&this[vt]()}}[vt](){if(this[vn]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,it.closeSync(t),this.emit("close")}}},no=class extends Pm{readable=!1;writable=!0;[jn]=!1;[Bn]=!1;[xi]=!1;[kt]=[];[Ds]=!1;[Et];[Ii];[vn];[ue];[Gs];[Jt];[Wa]=!1;[wn];constructor(t,e){e=e||{},super(e),this[Et]=t,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[Ii]=e.mode===void 0?438:e.mode,this[wn]=typeof e.start=="number"?e.start:void 0,this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[wn]!==void 0?"r+":"w";this[Gs]=e.flags===void 0,this[Jt]=e.flags===void 0?n:e.flags,this[ue]===void 0&&this[Sn]()}emit(t,...e){if(t==="error"){if(this[jn])return!1;this[jn]=!0}return super.emit(t,...e)}get fd(){return this[ue]}get path(){return this[Et]}[Tr](t){this[vt](),this[Bn]=!0,this.emit("error",t)}[Sn](){it.open(this[Et],this[Jt],this[Ii],(t,e)=>this[kr](t,e))}[kr](t,e){this[Gs]&&this[Jt]==="r+"&&t&&t.code==="ENOENT"?(this[Jt]="w",this[Sn]()):t?this[Tr](t):(this[ue]=e,this.emit("open",e),this[Bn]||this[Ka]())}end(t,e){return t&&this.write(t,e),this[xi]=!0,!this[Bn]&&!this[kt].length&&typeof this[ue]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[xi]?(this.emit("error",new Error("write() after end()")),!1):this[ue]===void 0||this[Bn]||this[kt].length?(this[kt].push(t),this[Ds]=!0,!1):(this[Bn]=!0,this[Us](t),!0)}[Us](t){it.write(this[ue],t,0,t.length,this[wn],(e,n)=>this[vr](e,n))}[vr](t,e){t?this[Tr](t):(this[wn]!==void 0&&typeof e=="number"&&(this[wn]+=e),this[kt].length?this[Ka]():(this[Bn]=!1,this[xi]&&!this[Wa]?(this[Wa]=!0,this[vt](),this.emit("finish")):this[Ds]&&(this[Ds]=!1,this.emit("drain"))))}[Ka](){if(this[kt].length===0)this[xi]&&this[vr](null,0);else if(this[kt].length===1)this[Us](this[kt].pop());else{let t=this[kt];this[kt]=[],jm(this[ue],t,this[wn],(e,n)=>this[vr](e,n))}}[vt](){if(this[vn]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},ef=class extends no{[Sn](){let t;if(this[Gs]&&this[Jt]==="r+")try{t=it.openSync(this[Et],this[Jt],this[Ii])}catch(e){if(e?.code==="ENOENT")return this[Jt]="w",this[Sn]();throw e}else t=it.openSync(this[Et],this[Jt],this[Ii]);this[kr](null,t)}[vt](){if(this[vn]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,it.closeSync(t),this.emit("close")}}[Us](t){let e=!0;try{this[vr](null,it.writeSync(this[ue],t,0,t.length,this[wn])),e=!1}finally{if(e)try{this[vt]()}catch{}}}},Vm=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"]]),Jm=t=>!!t.sync&&!!t.file,Zm=t=>!t.sync&&!!t.file,Ym=t=>!!t.sync&&!t.file,Xm=t=>!t.sync&&!t.file,Qm=t=>!!t.file,ew=t=>Vm.get(t)||t,Nc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let s=ew(n);e[s]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Li=(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=Nc(c);if(s?.(h,d),Jm(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(Zm(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(Ym(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(h,d)}else if(Xm(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}),rw=nw.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},rw)),iw=Wn.concat,vu=Object.getOwnPropertyDescriptor(Wn,"concat"),sw=t=>t,Za=vu?.writable===!0||vu?.set!==void 0?t=>{Wn.concat=t?sw:iw}:t=>{},Kn=Symbol("_superWrite"),Rs=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Ya=Symbol("flushFlag"),Mc=class extends Vn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Eu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Eu[e](t)}catch(n){throw new Rs(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 Rs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return xc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Wn.alloc(0),{[Ya]: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}[Kn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Wn.from(t,e)),this.#e)return;xc(this.#t,"zlib binding closed");let i=this.#t._handle,s=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Za(!0);let d;try{let h=typeof t[Ya]=="number"?t[Ya]:this.#r;d=this.#t._processChunk(t,h),Za(!1)}catch(h){Za(!1),this.#o(new Rs(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 Rs(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[Kn](Wn.from(h));for(let x=1;x<d.length;x++)u=this[Kn](d[x])}else u=this[Kn](Wn.from(d));return n&&n(),u}},nf=class extends Mc{#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),xc(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)}}}},ow=class extends nf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Kn](t){return this.#e?(this.#e=!1,t[9]=255,super[Kn](t)):super[Kn](t)}},aw=class extends nf{constructor(t){super(t,"Unzip")}},rf=class extends Mc{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)}},cw=class extends rf{constructor(t){super(t,"BrotliCompress")}},dw=class extends rf{constructor(t){super(t,"BrotliDecompress")}},sf=class extends Mc{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)}},lw=class extends sf{constructor(t){super(t,"ZstdCompress")}},uw=class extends sf{constructor(t){super(t,"ZstdDecompress")}},fw=(t,e)=>{if(Number.isSafeInteger(t))t<0?xw(t,e):hw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},hw=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},xw=(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]=of(s):s===0?e[i-1]=0:(n=!0,e[i-1]=af(s))}},pw=t=>{let e=t[0],n=e===128?mw(t.subarray(1,t.length)):e===255?gw(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},gw=t=>{for(var e=t.length,n=0,i=!1,s=e-1;s>-1;s--){var c=Number(t[s]),d;i?d=of(c):c===0?d=c:(i=!0,d=af(c)),d!==0&&(n-=d*Math.pow(256,e-s-1))}return n},mw=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},of=t=>(255^t)&255,af=t=>(255^t)+1&255,ww={};Rm(ww,{code:()=>Bc,isCode:()=>qs,isName:()=>_w,name:()=>ro,normalFsTypes:()=>cf});var qs=t=>ro.has(t),_w=t=>Bc.has(t),cf=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"]]),Bc=new Map(Array.from(ro).map(t=>[t[1],t[0]])),$n=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,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=Fn(t,e+156,1),c=cf.has(s),d=c?n:void 0,u=c?i:void 0;if(this.path=d?.path??Fn(t,e,100),this.mode=d?.mode??u?.mode??_n(t,e+100,8),this.uid=d?.uid??u?.uid??_n(t,e+108,8),this.gid=d?.gid??u?.gid??_n(t,e+116,8),this.size=d?.size??u?.size??_n(t,e+124,12),this.mtime=d?.mtime??u?.mtime??Xa(t,e+136,12),this.cksum=_n(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),qs(s)&&(this.#e=s||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Fn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Fn(t,e+265,32),this.gname=d?.gname??u?.gname??Fn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??_n(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??_n(t,e+337,8)??0,t[e+475]!==0){let x=Fn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Fn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??Xa(t,e+476,12),this.ctime=n?.ctime??i?.ctime??Xa(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=yw(this.path||"",n),s=i[0],c=i[1];this.needPax=!!i[2],this.needPax=zn(t,e,100,s)||this.needPax,this.needPax=yn(t,e+100,8,this.mode)||this.needPax,this.needPax=yn(t,e+108,8,this.uid)||this.needPax,this.needPax=yn(t,e+116,8,this.gid)||this.needPax,this.needPax=yn(t,e+124,12,this.size)||this.needPax,this.needPax=Qa(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=zn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=zn(t,e+265,32,this.uname)||this.needPax,this.needPax=zn(t,e+297,32,this.gname)||this.needPax,this.needPax=yn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=yn(t,e+337,8,this.devmin)||this.needPax,this.needPax=zn(t,e+345,n,c)||this.needPax,t[e+475]!==0?this.needPax=zn(t,e+345,155,c)||this.needPax:(this.needPax=zn(t,e+345,130,c)||this.needPax,this.needPax=Qa(t,e+476,12,this.atime)||this.needPax,this.needPax=Qa(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,yn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:ro.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Bc.get(t));if(qs(e)||e==="Unsupported")this.#e=e;else if(qs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},yw=(t,e)=>{let n=t,i="",s,c=wr.parse(t).root||".";if(Buffer.byteLength(n)<100)s=[n,i,!1];else{i=wr.dirname(n),n=wr.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=wr.join(wr.basename(i),n),i=wr.dirname(i));while(i!==c&&s===void 0);s||(s=[t.slice(0,99),"",!0])}return s},Fn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),Xa=(t,e,n)=>bw(_n(t,e,n)),bw=t=>t===void 0?void 0:new Date(t*1e3),_n=(t,e,n)=>Number(t[e])&128?pw(t.subarray(e,e+n)):vw(t,e,n),Ew=t=>isNaN(t)?void 0:t,vw=(t,e,n)=>Ew(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),Sw={12:8589934591,8:2097151},yn=(t,e,n,i)=>i===void 0?!1:i>Sw[n]||i<0?(fw(i,t.subarray(e,e+n)),!0):(Iw(t,e,n,i),!1),Iw=(t,e,n,i)=>t.write(Aw(i,n),e,n,"ascii"),Aw=(t,e)=>Tw(Math.floor(t).toString(8),e),Tw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Qa=(t,e,n,i)=>i===void 0?!1:yn(t,e,n,i.getTime()/1e3),kw=new Array(156).join("\0"),zn=(t,e,n,i)=>i===void 0?!1:(t.write(i+kw,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),Ys=class df{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 $n({path:("PaxHeader/"+Cw(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 df(Dw(Rw(e),n),i)}},Dw=(t,e)=>e?Object.assign({},e,t):t,Rw=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(Pw,Object.create(null)),Pw=(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},Ow=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Y=Ow!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Lw=class extends Vn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,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=Y(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?Y(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=Y(t.path)),t.linkpath&&(t.linkpath=Y(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},io=(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))},Nw=1024*1024,pc=Buffer.from([31,139]),gc=Buffer.from([40,181,47,253]),Mw=Math.max(pc.length,gc.length),ft=Symbol("state"),Un=Symbol("writeEntry"),Kt=Symbol("readEntry"),ec=Symbol("nextEntry"),Su=Symbol("processEntry"),Ct=Symbol("extendedHeader"),gi=Symbol("globalExtendedHeader"),xn=Symbol("meta"),Iu=Symbol("emitMeta"),ye=Symbol("buffer"),$t=Symbol("queue"),pn=Symbol("ended"),tc=Symbol("emittedEnd"),Gn=Symbol("emit"),Pe=Symbol("unzip"),Ps=Symbol("consumeChunk"),Os=Symbol("consumeChunkSub"),nc=Symbol("consumeBody"),Au=Symbol("consumeMeta"),Tu=Symbol("consumeHeader"),mi=Symbol("consuming"),rc=Symbol("bufferConcat"),Ls=Symbol("maybeEnd"),_r=Symbol("writing"),gn=Symbol("aborted"),Ns=Symbol("onDone"),qn=Symbol("sawValidEntry"),Ms=Symbol("sawNullBlock"),Bs=Symbol("sawEOF"),ku=Symbol("closeStream"),Bw=()=>!0,Oi=class extends tw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[$t]=[];[ye];[Kt];[Un];[ft]="begin";[xn]="";[Ct];[gi];[pn]=!1;[Pe];[gn]=!1;[qn];[Ms]=!1;[Bs]=!1;[_r]=!1;[mi]=!1;[tc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ns,()=>{(this[ft]==="begin"||this[qn]===!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||Nw,this.filter=typeof t.filter=="function"?t.filter:Bw;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={}){io(this,t,e,n)}[Tu](t,e){this[qn]===void 0&&(this[qn]=!1);let n;try{n=new $n(t,e,this[Ct],this[gi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Ms]?(this[Bs]=!0,this[ft]==="begin"&&(this[ft]="header"),this[Gn]("eof")):(this[Ms]=!0,this[Gn]("nullBlock"));else if(this[Ms]=!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[Un]=new Lw(n,this[Ct],this[gi]);if(!this[qn])if(s.remain){let c=()=>{s.invalid||(this[qn]=!0)};s.on("end",c)}else this[qn]=!0;s.meta?s.size>this.maxMetaEntrySize?(s.ignore=!0,this[Gn]("ignoredEntry",s),this[ft]="ignore",s.resume()):s.size>0&&(this[xn]="",s.on("data",c=>this[xn]+=c),this[ft]="meta"):(this[Ct]=void 0,s.ignore=s.ignore||!this.filter(s.path,s),s.ignore?(this[Gn]("ignoredEntry",s),this[ft]=s.remain?"ignore":"header",s.resume()):(s.remain?this[ft]="body":(this[ft]="header",s.end()),this[Kt]?this[$t].push(s):(this[$t].push(s),this[ec]())))}}}[ku](){queueMicrotask(()=>this.emit("close"))}[Su](t){let e=!0;if(!t)this[Kt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Kt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ec]()),e=!1);return e}[ec](){do;while(this[Su](this[$t].shift()));if(this[$t].length===0){let t=this[Kt];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[nc](t,e){let n=this[Un];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[ft]="header",this[Un]=void 0,n.end()),s.length}[Au](t,e){let n=this[Un],i=this[nc](t,e);return!this[Un]&&n&&this[Iu](n),i}[Gn](t,e,n){this[$t].length===0&&!this[Kt]?this.emit(t,e,n):this[$t].push([t,e,n])}[Iu](t){switch(this[Gn]("meta",this[xn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=Ys.parse(this[xn],this[Ct],!1);break;case"GlobalExtendedHeader":this[gi]=Ys.parse(this[xn],this[gi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[xn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[xn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[gn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[gn])return n?.(),!1;if((this[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[ye]&&(t=Buffer.concat([this[ye],t]),this[ye]=void 0),t.length<Mw)return this[ye]=t,n?.(),!0;for(let d=0;this[Pe]===void 0&&d<pc.length;d++)t[d]!==pc[d]&&(this[Pe]=!1);let s=!1;if(this[Pe]===!1&&this.zstd!==!1){s=!0;for(let d=0;d<gc.length;d++)if(t[d]!==gc[d]){s=!1;break}}let c=this.brotli===void 0&&!s;if(this[Pe]===!1&&c)if(t.length<512)if(this[pn])this.brotli=!0;else return this[ye]=t,n?.(),!0;else try{new $n(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Pe]===void 0||this[Pe]===!1&&(this.brotli||s)){let d=this[pn];this[pn]=!1,this[Pe]=this[Pe]===void 0?new aw({}):s?new uw({}):new dw({}),this[Pe].on("data",h=>this[Ps](h)),this[Pe].on("error",h=>this.abort(h)),this[Pe].on("end",()=>{this[pn]=!0,this[Ps]()}),this[_r]=!0;let u=!!this[Pe][d?"end":"write"](t);return this[_r]=!1,n?.(),u}}this[_r]=!0,this[Pe]?this[Pe].write(t):this[Ps](t),this[_r]=!1;let i=this[$t].length>0?!1:this[Kt]?this[Kt].flowing:!0;return!i&&this[$t].length===0&&this[Kt]?.once("drain",()=>this.emit("drain")),n?.(),i}[rc](t){t&&!this[gn]&&(this[ye]=this[ye]?Buffer.concat([this[ye],t]):t)}[Ls](){if(this[pn]&&!this[tc]&&!this[gn]&&!this[mi]){this[tc]=!0;let t=this[Un];if(t&&t.blockRemain){let e=this[ye]?this[ye].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ye]&&t.write(this[ye]),t.end()}this[Gn](Ns)}}[Ps](t){if(this[mi]&&t)this[rc](t);else if(!t&&!this[ye])this[Ls]();else if(t){if(this[mi]=!0,this[ye]){this[rc](t);let e=this[ye];this[ye]=void 0,this[Os](e)}else this[Os](t);for(;this[ye]&&this[ye]?.length>=512&&!this[gn]&&!this[Bs];){let e=this[ye];this[ye]=void 0,this[Os](e)}this[mi]=!1}(!this[ye]||this[pn])&&this[Ls]()}[Os](t){let e=0,n=t.length;for(;e+512<=n&&!this[gn]&&!this[Bs];)switch(this[ft]){case"begin":case"header":this[Tu](t,e),e+=512;break;case"ignore":case"body":e+=this[nc](t,e);break;case"meta":e+=this[Au](t,e);break;default:throw new Error("invalid state: "+this[ft])}e<n&&(this[ye]=this[ye]?Buffer.concat([t.subarray(e),this[ye]]):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[gn]||(this[Pe]?(t&&this[Pe].write(t),this[Pe].end()):(this[pn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ls]())),this}},Ai=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)},Fw=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},lf=(t,e)=>{let n=new Map(e.map(c=>[Ai(c),!0])),i=t.filter,s=(c,d="")=>{let u=d||$m(c).root||".",h;if(c===u)h=!1;else{let x=n.get(c);h=x!==void 0?x:s(Km(c),u)}return n.set(c,h),h};t.filter=i?(c,d)=>i(c,d)&&s(Ai(c)):c=>s(Ai(c))},zw=t=>{let e=new Oi(t),n=t.file,i;try{i=Ir.openSync(n,"r");let s=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(s.size<c){let d=Buffer.allocUnsafe(s.size),u=Ir.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=Ir.readSync(i,u,0,c,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Ir.closeSync(i)}catch{}}},Uw=(t,e)=>{let n=new Oi(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("end",c),Ir.stat(s,(u,h)=>{if(u)d(u);else{let x=new Lc(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Cr=Li(zw,Uw,t=>new Oi(t),t=>new Oi(t),(t,e)=>{e?.length&&lf(t,e),t.noResume||Fw(t)}),uf=(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:qw,parse:Du}=Gw,Fc=t=>{let e="",n=Du(t);for(;qw(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Du(t)}return[e,t]},so=["|","<",">","?",":"],zc=so.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Hw=new Map(so.map((t,e)=>[t,zc[e]])),jw=new Map(zc.map((t,e)=>[t,so[e]])),Ru=t=>so.reduce((e,n)=>e.split(n).join(Hw.get(n)),t),Ww=t=>zc.reduce((e,n)=>e.split(n).join(jw.get(n)),t),ff=(t,e)=>e?(t=Y(t).replace(/^\.(\/|$)/,""),Ai(e)+"/"+t):Y(t),Kw=16*1024*1024,Pu=Symbol("process"),Ou=Symbol("file"),Lu=Symbol("directory"),mc=Symbol("symlink"),Nu=Symbol("hardlink"),wi=Symbol("header"),Hs=Symbol("read"),wc=Symbol("lstat"),js=Symbol("onlstat"),_c=Symbol("onread"),yc=Symbol("onreadlink"),bc=Symbol("openfile"),Ec=Symbol("onopenfile"),bn=Symbol("close"),Qs=Symbol("mode"),vc=Symbol("awaitDrain"),ic=Symbol("ondrain"),Rt=Symbol("prefix"),hf=class extends Vn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let n=Nc(e);super(),this.path=Y(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||Kw,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=Y(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?Y(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]=Fc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=Ww(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Y(n.absolute||Cu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let s=this.statCache.get(this.absolute);s?this[js](s):this[wc]()}warn(t,e,n={}){return io(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[wc](){Dt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[js](e)})}[js](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Jw(t),this.emit("stat",t),this[Pu]()}[Pu](){switch(this.type){case"File":return this[Ou]();case"Directory":return this[Lu]();case"SymbolicLink":return this[mc]();default:return this.end()}}[Qs](t){return uf(t,this.type==="Directory",this.portable)}[Rt](t){return ff(t,this.prefix)}[wi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new $n({path:this[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Lu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[wi](),this.end()}[mc](){Dt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[yc](e)})}[yc](t){this.linkpath=Y(t),this[wi](),this.end()}[Nu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Y(Cu.relative(this.cwd,t)),this.stat.size=0,this[wi](),this.end()}[Ou](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[Nu](e);this.linkCache.set(t,this.absolute)}if(this[wi](),this.stat.size===0)return this.end();this[bc]()}[bc](){Dt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ec](e)})}[Ec](t){if(this.fd=t,this.#e)return this[bn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[Hs]()}[Hs](){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");Dt.read(t,e,n,i,s,(c,d)=>{if(c)return this[bn](()=>this.emit("error",c));this[_c](d)})}[bn](t=()=>{}){this.fd!==void 0&&Dt.close(this.fd,t)}[_c](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[bn](()=>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[bn](()=>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[ic]():this[vc](()=>this[ic]())}[vc](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)}[ic](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[bn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[Hs]()}},$w=class extends hf{sync=!0;[wc](){this[js](Dt.lstatSync(this.absolute))}[mc](){this[yc](Dt.readlinkSync(this.absolute))}[bc](){this[Ec](Dt.openSync(this.absolute,"r"))}[Hs](){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=Dt.readSync(e,n,i,s,c);this[_c](d),t=!1}finally{if(t)try{this[bn](()=>{})}catch{}}}[vc](t){t()}[bn](t=()=>{}){this.fd!==void 0&&Dt.closeSync(this.fd),t()}},Vw=class extends Vn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,n={}){return io(this,t,e,n)}constructor(t,e={}){let n=Nc(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=Y(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: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?Y(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let s=!1;if(!this.preservePaths){let[d,u]=Fc(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 $n({path:this[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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 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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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)}[Rt](t){return ff(t,this.prefix)}[Qs](t){return uf(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}},Jw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",Zw=class Ar{tail;head;length=0;static create(e=[]){return new Ar(e)}constructor(e=[]){for(let n of e)this.push(n)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let n=e.next,i=e.prev;return n&&(n.prev=i),i&&(i.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,i=e.length;n<i;n++)Xw(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)Qw(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 Ar;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 Ar;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 Ar;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 Ar;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=Yw(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 Yw(t,e,n){let i=e,s=e?e.next:t.head,c=new Uc(n,i,s,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function Xw(t,e){t.tail=new Uc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Qw(t,e){t.head=new Uc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Uc=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}},Bu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Fu=Buffer.alloc(1024),Ws=Symbol("onStat"),_i=Symbol("ended"),yt=Symbol("queue"),yi=Symbol("pendingLinks"),mn=Symbol("current"),Hn=Symbol("process"),bi=Symbol("processing"),Fs=Symbol("processJob"),bt=Symbol("jobs"),sc=Symbol("jobDone"),Ks=Symbol("addFSEntry"),zu=Symbol("addTarEntry"),Sc=Symbol("stat"),Ic=Symbol("readdir"),$s=Symbol("onreaddir"),Vs=Symbol("pipe"),Uu=Symbol("entry"),oc=Symbol("entryOpt"),Js=Symbol("writeEntryClass"),xf=Symbol("write"),ac=Symbol("ondrain"),oo=class extends Vn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Js];onWriteEntry;[yt];[yi]=new Map;[bt]=0;[bi]=!1;[_i]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Y(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]=hf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new ow(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new cw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new lw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[ac]()),this.on("resume",()=>e.resume())}else this.on("drain",this[ac]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[yt]=new Zw,this[bt]=0,this.jobs=Number(t.jobs)||4,this[bi]=!1,this[_i]=!1}[xf](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[_i]=!0,this[Hn](),n&&n(),this}write(t){if(this[_i])throw new Error("write after end");return typeof t=="string"?this[Ks](t):this[zu](t),this.flowing}[zu](t){let e=Y(Mu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new Bu(t.path,e);n.entry=new Vw(t,this[oc](n)),n.entry.on("end",()=>this[sc](n)),this[bt]+=1,this[yt].push(n)}this[Hn]()}[Ks](t){let e=Y(Mu.resolve(this.cwd,t));this[yt].push(new Bu(t,e)),this[Hn]()}[Sc](t){t.pending=!0,this[bt]+=1;let e=this.follow?"stat":"lstat";Xs[e](t.absolute,(n,i)=>{t.pending=!1,this[bt]-=1,n?this.emit("error",n):this[Ws](t,i)})}[Ws](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[mn])this[Fs](t);else{let n=`${e.dev}:${e.ino}`,i=this[yi].get(n);i?i.push(t):this[yi].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Hn]()}[Ic](t){t.pending=!0,this[bt]+=1,Xs.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[bt]-=1,e)return this.emit("error",e);this[$s](t,n)})}[$s](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Hn]()}[Hn](){if(!this[bi]){this[bi]=!0;for(let t=this[yt].head;t&&this[bt]<this.jobs;t=t.next)if(this[Fs](t.value),t.value.ignore){let e=t.next;this[yt].removeNode(t),t.next=e}this[bi]=!1,this[_i]&&this[yt].length===0&&this[bt]===0&&(this.zip?this.zip.end(Fu):(super.write(Fu),super.end()))}}get[mn](){return this[yt]&&this[yt].head&&this[yt].head.value}[sc](t){this[yt].shift(),this[bt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[yi].get(n);if(i){this[yi].delete(n);for(let s of i)s.pending=!1,this[Fs](s)}}this[Hn]()}[Fs](t){if(t.pending&&t.pendingLink&&t===this[mn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[mn]&&!t.piped&&this[Vs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Ws](t,e):this[Sc](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[Ic](t),!t.readdir)return}if(t.entry=this[Uu](t),!t.entry){t.ignore=!0;return}t===this[mn]&&!t.piped&&this[Vs](t)}}}[oc](t){return{onwarn:(e,n,i)=>this.warn(e,n,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[Uu](t){this[bt]+=1;try{return new this[Js](t.path,this[oc](t)).on("end",()=>this[sc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[ac](){this[mn]&&this[mn].entry&&this[mn].entry.resume()}[Vs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let s=t.path,c=s==="./"?"":s.replace(/\/*$/,"/");this[Ks](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={}){io(this,t,e,n)}},Gc=class extends oo{sync=!0;constructor(t){super(t),this[Js]=$w}pause(){}resume(){}[Sc](t){let e=this.follow?"statSync":"lstatSync";this[Ws](t,Xs[e](t.absolute))}[Ic](t){this[$s](t,Xs.readdirSync(t.absolute))}[Vs](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let s=t.path,c=s==="./"?"":s.replace(/\/*$/,"/");this[Ks](c+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[xf](i)})}},e_=(t,e)=>{let n=new Gc(t),i=new ef(t.file,{mode:t.mode||438});n.pipe(i),pf(n,e)},t_=(t,e)=>{let n=new oo(t),i=new no(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 gf(n,e).catch(c=>n.emit("error",c)),s},pf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Cr({file:tf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},gf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Cr({file:tf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},n_=(t,e)=>{let n=new Gc(t);return pf(n,e),n},r_=(t,e)=>{let n=new oo(t);return gf(n,e).catch(i=>n.emit("error",i)),n},kI=Li(e_,t_,n_,r_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),s_=process.env.__FAKE_PLATFORM__||process.platform,yf=s_==="win32",{O_CREAT:bf,O_NOFOLLOW:Gu,O_TRUNC:Ef,O_WRONLY:vf}=_f.constants,Sf=Number(process.env.__FAKE_FS_O_FILENAME__)||_f.constants.UV_FS_O_FILEMAP||0,o_=yf&&!!Sf,a_=512*1024,c_=Sf|Ef|bf|vf,qu=!yf&&typeof Gu=="number"?Gu|Ef|bf|vf:null,If=qu!==null?()=>qu:o_?t=>t<a_?c_:"w":()=>"w",Ac=(t,e,n)=>{try{return ao.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},eo=(t,e,n,i)=>{ao.lchown(t,e,n,s=>{i(s&&s?.code!=="ENOENT"?s:null)})},d_=(t,e,n,i,s)=>{if(e.isDirectory())Af(Ti.resolve(t,e.name),n,i,c=>{if(c)return s(c);let d=Ti.resolve(t,e.name);eo(d,n,i,s)});else{let c=Ti.resolve(t,e.name);eo(c,n,i,s)}},Af=(t,e,n,i)=>{ao.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 eo(t,e,n,i);let d=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return eo(t,e,n,i)}};for(let x of c)d_(t,x,e,n,h)})},l_=(t,e,n,i)=>{e.isDirectory()&&Tf(Ti.resolve(t,e.name),n,i),Ac(Ti.resolve(t,e.name),n,i)},Tf=(t,e,n)=>{let i;try{i=ao.readdirSync(t,{withFileTypes:!0})}catch(s){let c=s;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Ac(t,e,n);throw c}for(let s of i)l_(t,s,e,n);return Ac(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"}},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"}},f_=(t,e)=>{ct.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new kf(t,n?.code||"ENOTDIR")),e(n)})},h_=(t,e,n)=>{t=Y(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,m=e.unlink,_=Y(e.cwd),S=(v,I)=>{v?n(v):I&&h?Af(I,d,u,A=>S(A)):c?ct.chmod(t,s,n):n()};if(t===_)return f_(t,S);if(x)return u_.mkdir(t,{mode:s,recursive:!0}).then(v=>S(null,v??void 0),S);let y=Y(to.relative(_,t)).split("/");Tc(_,y,s,m,_,void 0,S)},Tc=(t,e,n,i,s,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),h=Y(to.resolve(t+"/"+u));ct.mkdir(h,n,Cf(h,e,n,i,s,c,d))},Cf=(t,e,n,i,s,c,d)=>u=>{u?ct.lstat(t,(h,x)=>{if(h)h.path=h.path&&Y(h.path),d(h);else if(x.isDirectory())Tc(t,e,n,i,s,c,d);else if(i)ct.unlink(t,m=>{if(m)return d(m);ct.mkdir(t,n,Cf(t,e,n,i,s,c,d))});else{if(x.isSymbolicLink())return d(new co(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Tc(t,e,n,i,s,c,d))},x_=t=>{let e=!1,n;try{e=ct.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new kf(t,n??"ENOTDIR")}},p_=(t,e)=>{t=Y(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,m=Y(e.cwd),_=v=>{v&&u&&Tf(v,c,d),s&&ct.chmodSync(t,i)};if(t===m)return x_(m),_();if(h)return _(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Y(to.relative(m,t)).split("/"),y;for(let v=S.shift(),I=m;v&&(I+="/"+v);v=S.shift()){I=Y(to.resolve(I));try{ct.mkdirSync(I,i),y=y||I}catch{let A=ct.lstatSync(I);if(A.isDirectory())continue;if(x){ct.unlinkSync(I),ct.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new co(I,I+"/"+S.join("/"))}}return _(y)},cc=Object.create(null),Hu=1e4,yr=new Set,g_=t=>{yr.has(t)?yr.delete(t):cc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=cc[t],n=yr.size-Hu;if(n>Hu/10){for(let i of yr)if(yr.delete(i),delete cc[i],--n<=0)break}return e},m_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,w_=m_==="win32",__=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Df(i,n)),e.push(n||"/"),e},[]),y_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=w_?["win32 parallelization disabled"]:t.map(i=>Ai(Df(g_(i))));let n=new Set(t.map(i=>__(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}},b_=()=>process.umask(),ju=Symbol("onEntry"),kc=Symbol("checkFs"),Wu=Symbol("checkFs2"),Cc=Symbol("isReusable"),ht=Symbol("makeFs"),Dc=Symbol("file"),Rc=Symbol("directory"),Zs=Symbol("link"),Ku=Symbol("symlink"),$u=Symbol("hardlink"),Si=Symbol("ensureNoSymlink"),Vu=Symbol("unsupported"),Ju=Symbol("checkPath"),dc=Symbol("stripAbsolutePath"),En=Symbol("mkdir"),je=Symbol("onError"),zs=Symbol("pending"),Zu=Symbol("pend"),br=Symbol("unpend"),lc=Symbol("ended"),uc=Symbol("maybeClose"),Pc=Symbol("skip"),ki=Symbol("doChown"),Ci=Symbol("uid"),Di=Symbol("gid"),Ri=Symbol("checkedCwd"),E_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Pi=E_==="win32",v_=1024,S_=(t,e)=>{if(!Pi)return ne.unlink(t,e);let n=t+".DELETE."+wf(16).toString("hex");ne.rename(t,n,i=>{if(i)return e(i);ne.unlink(n,e)})},I_=t=>{if(!Pi)return ne.unlinkSync(t);let e=t+".DELETE."+wf(16).toString("hex");ne.renameSync(t,e),ne.unlinkSync(e)},Yu=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,qc=class extends Oi{[lc]=!1;[Ri]=!1;[zs]=0;reservations=new y_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[lc]=!0,this[uc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:v_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Pi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Y(ze.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:b_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[ju](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[uc](){this[lc]&&this[zs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[dc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[s,c]=Fc(n),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Pi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=ze.posix.dirname(t.path),h=ze.posix.normalize(ze.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return s&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute ${e}`,{entry:t,[e]:n})),!0}[Ju](t){let e=Y(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=Y(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[dc](t,"path")||!this[dc](t,"linkpath"))return!1;if(t.absolute=ze.isAbsolute(t.path)?Y(ze.resolve(t.path)):Y(ze.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Y(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=ze.win32.parse(String(t.absolute));t.absolute=i+Ru(String(t.absolute).slice(i.length));let{root:s}=ze.win32.parse(t.path);t.path=s+Ru(t.path.slice(s.length))}return!0}[ju](t){if(!this[Ju](t))return t.resume();switch(i_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[kc](t);default:return this[Vu](t)}}[je](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[br](),e.resume())}[En](t,e,n){h_(Y(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)}[ki](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ci](t){return Yu(this.uid,t.uid,this.processUid)}[Di](t){return Yu(this.gid,t.gid,this.processGid)}[Dc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new no(String(t.absolute),{flags:If(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&ne.close(i.fd,()=>{}),i.write=()=>!0,this[je](u,t),e()});let s=1,c=u=>{if(u){i.fd&&ne.close(i.fd,()=>{}),this[je](u,t),e();return}--s===0&&i.fd!==void 0&&ne.close(i.fd,h=>{h?this[je](h,t):this[br](),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,m=t.mtime;ne.futimes(h,x,m,_=>_?ne.utimes(u,x,m,S=>c(S&&_)):c())}if(typeof h=="number"&&this[ki](t)){s++;let x=this[Ci](t),m=this[Di](t);typeof x=="number"&&typeof m=="number"&&ne.fchown(h,x,m,_=>_?ne.chown(u,x,m,S=>c(S&&_)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[je](u,t),e()}),t.pipe(d)),d.pipe(i)}[Rc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[En](String(t.absolute),n,i=>{if(i){this[je](i,t),e();return}let s=1,c=()=>{--s===0&&(e(),this[br](),t.resume())};t.mtime&&!this.noMtime&&(s++,ne.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[ki](t)&&(s++,ne.chown(String(t.absolute),Number(this[Ci](t)),Number(this[Di](t)),c)),c()})}[Vu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ku](t,e){let n=Y(ze.relative(this.cwd,ze.resolve(ze.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Si](t,this.cwd,n,()=>this[Zs](t,String(t.linkpath),"symlink",e),i=>{this[je](i,t),e()})}[$u](t,e){let n=Y(ze.resolve(this.cwd,String(t.linkpath))),i=Y(String(t.linkpath)).split("/");this[Si](t,this.cwd,i,()=>this[Zs](t,n,"link",e),s=>{this[je](s,t),e()})}[Si](t,e,n,i,s){let c=n.shift();if(this.preservePaths||c===void 0)return i();let d=ze.resolve(e,c);ne.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return s(new co(d,ze.resolve(d,n.join("/"))));this[Si](t,d,n,i,s)})}[Zu](){this[zs]++}[br](){this[zs]--,this[uc]()}[Pc](t){this[br](),t.resume()}[Cc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Pi}[kc](t){this[Zu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[Wu](t,n))}[Wu](t,e){let n=d=>{e(d)},i=()=>{this[En](this.cwd,this.dmode,d=>{if(d){this[je](d,t),n();return}this[Ri]=!0,s()})},s=()=>{if(t.absolute!==this.cwd){let d=Y(ze.dirname(String(t.absolute)));if(d!==this.cwd)return this[En](d,this.dmode,u=>{if(u){this[je](u,t),n();return}c()})}c()},c=()=>{ne.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Pc](t),n();return}if(d||this[Cc](t,u))return this[ht](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=m=>this[ht](m??null,t,n);return h?ne.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ne.rmdir(String(t.absolute),h=>this[ht](h??null,t,n))}if(t.absolute===this.cwd)return this[ht](null,t,n);S_(String(t.absolute),h=>this[ht](h??null,t,n))})};this[Ri]?s():i()}[ht](t,e,n){if(t){this[je](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Dc](e,n);case"Link":return this[$u](e,n);case"SymbolicLink":return this[Ku](e,n);case"Directory":case"GNUDumpDir":return this[Rc](e,n)}}[Zs](t,e,n,i){ne[n](e,String(t.absolute),s=>{s?this[je](s,t):(this[br](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},Rf=class extends qc{sync=!0;[ht](t,e){return super[ht](t,e,()=>{})}[kc](t){if(!this[Ri]){let s=this[En](this.cwd,this.dmode);if(s)return this[je](s,t);this[Ri]=!0}if(t.absolute!==this.cwd){let s=Y(ze.dirname(String(t.absolute)));if(s!==this.cwd){let c=this[En](s,this.dmode);if(c)return this[je](c,t)}}let[e,n]=Ei(()=>ne.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Pc](t);if(e||this[Cc](t,n))return this[ht](null,t);if(n.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=c?Ei(()=>{ne.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ht](d,t)}let[s]=Ei(()=>ne.rmdirSync(String(t.absolute)));this[ht](s,t)}let[i]=t.absolute===this.cwd?[]:Ei(()=>I_(String(t.absolute)));this[ht](i,t)}[Dc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{ne.closeSync(s)}catch(h){u=h}(d||u)&&this[je](d||u,t),e()},s;try{s=ne.openSync(String(t.absolute),If(t.size),n)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[je](d,t)),t.pipe(c)),c.on("data",d=>{try{ne.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{ne.futimesSync(s,u,h)}catch(x){try{ne.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[ki](t)){let u=this[Ci](t),h=this[Di](t);try{ne.fchownSync(s,Number(u),Number(h))}catch(x){try{ne.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[Rc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[En](String(t.absolute),n);if(i){this[je](i,t),e();return}if(t.mtime&&!this.noMtime)try{ne.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ki](t))try{ne.chownSync(String(t.absolute),Number(this[Ci](t)),Number(this[Di](t)))}catch{}e(),t.resume()}[En](t,e){try{return p_(Y(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}}[Si](t,e,n,i,s){if(this.preservePaths||n.length===0)return i();let c=e;for(let d of n){c=ze.resolve(c,d);let[u,h]=Ei(()=>ne.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return s(new co(c,ze.resolve(e,n.join("/"))))}i()}[Zs](t,e,n,i){let s=`${n}Sync`;try{ne[s](e,String(t.absolute)),i(),t.resume()}catch(c){return this[je](c,t)}}},A_=t=>{let e=new Rf(t),n=t.file,i=mf.statSync(n),s=t.maxReadSize||16*1024*1024;new Wm(n,{readSize:s,size:i.size}).pipe(e)},T_=(t,e)=>{let n=new qc(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("close",c),mf.stat(s,(u,h)=>{if(u)d(u);else{let x=new Lc(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Pf=Li(A_,T_,t=>new Rf(t),t=>new qc(t),(t,e)=>{e?.length&&lf(t,e)}),k_=(t,e)=>{let n=new Gc(t),i=!0,s,c;try{try{s=at.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")s=at.openSync(t.file,"w+");else throw h}let d=at.fstatSync(s),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let m=0,_=0;m<512;m+=_){if(_=at.readSync(s,u,m,u.length-m,c+m),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!_)break e}let h=new $n(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(c+x+512>d.size)break;c+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,C_(t,n,c,s,e)}finally{if(i)try{at.closeSync(s)}catch{}}},C_=(t,e,n,i,s)=>{let c=new ef(t.file,{fd:i,start:n});e.pipe(c),R_(e,s)},D_=(t,e)=>{e=Array.from(e);let n=new oo(t),i=(s,c,d)=>{let u=(S,y)=>{S?at.close(s,v=>d(S)):d(null,y)},h=0;if(c===0)return u(null,0);let x=0,m=Buffer.alloc(512),_=(S,y)=>{if(S||y===void 0)return u(S);if(x+=y,x<512&&y)return at.read(s,m,x,m.length-x,h+x,_);if(h===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let v=new $n(m);if(!v.cksumValid)return u(null,h);let I=512*Math.ceil((v.size??0)/512);if(h+I+512>c||(h+=I+512,h>=c))return u(null,h);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,at.read(s,m,0,512,h,_)};at.read(s,m,0,512,h,_)};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+",at.open(t.file,d,u);if(h||!x)return c(h);at.fstat(x,(m,_)=>{if(m)return at.close(x,()=>c(m));i(x,_.size,(S,y)=>{if(S)return c(S);let v=new no(t.file,{fd:x,start:y});n.pipe(v),v.on("error",c),v.on("close",s),P_(n,e)})})};at.open(t.file,d,u)})},R_=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Cr({file:Of.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},P_=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Cr({file:Of.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},vi=Li(k_,D_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Qm(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")}),HI=Li(vi.syncFile,vi.asyncFile,vi.syncNoFile,vi.asyncNoFile,(t,e=[])=>{vi.validate?.(t,e),O_(t)}),O_=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))};un();var xt={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function lo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Lf(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 Nf(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function Mf(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function Jn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Zt();$e();ee();Be();$e();function Dr(t,e){if(lo(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ni(t){return t.startsWith("http://")||t.startsWith("https://")}function Rr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as LA}from"node:fs";import{dirname as MA,join as BA}from"node:path";import{fileURLToPath as zA}from"node:url";var Ot="0.2.1-alpha.10";$e();ee();var fo="1008033",Uf="1289";var Gf="pbbp2",qf="https://www.coze.cn",Hf="/api/coze_claw/resource/get_frontier_key",G_="https://www.coze.cn",q_="wss://frontier.coze.cn";function Pr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??G_}function jf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??q_}function In(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 Bi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Mi=q("handshake");async function Hc(t){let e=Pr(t.endpoint),n=t.timeoutMs??1e4,i=`${Rr(e)}${Hf}?aid=${encodeURIComponent(fo)}`,s={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...In(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),n);Mi.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 T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${v.slice(0,200)}`)}let m=await u.json();if(m.code!==void 0&&m.code!==0)throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${m.code} msg=${m.msg??"-"} logid=${h}`);let _=m.data??{},S=typeof _.access_key=="string"&&_.access_key||typeof _.accessKey=="string"&&_.accessKey||void 0,y=typeof _.device_id=="string"&&_.device_id||typeof _.deviceId=="string"&&_.deviceId||void 0;if(!S||!y){let v=JSON.stringify(m).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${v}`)}return Mi.info("handshake ok",{remoteDeviceId:y,logid:h,traceId:x}),{accessKey:S,deviceId:y}}catch(u){if(u instanceof T)throw Mi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Mi.warn("handshake timeout",{base:e,timeoutMs:n}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let h=u.cause;throw Mi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:h?.code,syscall:h?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var Wc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Lt="auto",jc=15e4;function Kf(t){return{model:Kc(t.model)??Lt,...t.modelToken?{modelToken:t.modelToken}:{}}}function $f(t){return!t||t===Lt}var H_=new Set(["auto","\u81EA\u52A8"]);function Kc(t){let e=t?.trim();if(e)return H_.has(e.toLowerCase())?Lt:e}function Vf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Wc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Lt;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 $f(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Jf(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Lt}"`):$f(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="${Wc}/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??jc;e.push("-c",`model_context_window=${n}`)}return e}function Zf(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function $c(t,e){let{ttEnv:n,usePpe:i}=Bi(t),s={};return n&&(s["x-tt-env"]=n),i&&(s["x-use-ppe"]=i),e&&(s["x-mock-scenario"]=e),s}function Yf(t,e,n){if(!t.modelToken)return{};let i=$c(e,n);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
92
- `)}}function Vc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Jc(t){return t.model||Lt}function Wf(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 Xf(t,e,n,i){if(!t.modelToken)return null;let s=Jc(t),c=$c(e,n),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[Wf(s,d,t.modelInfo?.contextWindow??jc)],h=new Set([s]);for(let m of i??[])!m||h.has(m)||(h.add(m),u.push(Wf(m,["text"],jc)));let x={baseUrl:`${Wc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(x.headers=c),x}function Qf(t,e,n){if(!t.modelToken)return[];let i=$c(e,n),s=[];for(let[c,d]of Object.entries(i))s.push("-c",`model_providers.coze.http_headers.${c}="${d}"`);return s}var ge=q("agent-handlers"),t0=5*1024*1024,$_=1,V_=6,J_=new Set(["node_modules",".git",".coze","dist","build",".next"]),Z_=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Y_=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,X_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Q_(t){let e=t?.trim();return e?X_.test(e)||Y_.test(e)?e:(ge.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function ey(t){return new Promise((e,n)=>{let i=st("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 xo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let n=Jn(e._meta),i=await this.loadAgentCfg(n),s=i?.workspace??Ye(n).workspace,c=i?.skills??[],d=[],u=new Set;for(let h of c){let x=Je(s,h.relPath,"SKILL.md");await e0(x).then(_=>_.isFile()).catch(()=>!1)&&(d.push(iy(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",x=await ty(n,s,h);for(let m of x)u.has(m.relPath)||(u.add(m.relPath),d.push(m.skill))}return{skills:d}}async addSkills(e){e._meta;let n=Jn(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 po({agentId:n,workspace:i.workspace,framework:i.framework,skill:h});go(c,d,x),u.push(h)}return await ci(n,c),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=Jn(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=Je(i.workspace,u.relPath);await Xc(h,{recursive:!0,force:!0}),ge.info("skill removed",{agentId:n,skillId:u.skillId,relPath:u.relPath})}return await ci(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=Jn(e._meta);if(!e.skillName)throw new T("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");ge.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),s=i?.workspace??Ye(n).workspace,c=i?.framework??"claude-code",d=a0(e.skillName),u=Je(id(c),d),h=Je(s,u),x=Je(h,"SKILL.md");if(!await e0(x).then(k=>k.isFile()).catch(()=>!1))throw new T("SKILL_NOT_FOUND",`skill not found locally: ${e.skillName} (${u})`);let _=new rd.default;_.addLocalFolder(h,d);let S=_.toBuffer();if(S.length>n0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${S.length} bytes exceeds limit ${n0}`);let y=await ho(x,{encoding:"utf8"}).then(k=>d0(k).description).catch(()=>{}),v={};this.opts.publishSkillToMarketplace?v=await this.opts.publishSkillToMarketplace({zip:S,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...y?{description:y}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):ge.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let I=v.version??"v1.0",A=v.skillId??e.skillId??c0(n,u);if(i){let k=i.skills??[],P=k.find(b=>b.relPath===u);P?(P.version=I,P.skillId=A):k.push({skillId:A,skillName:e.skillName,relPath:u,version:I,installedAt:Date.now(),...y?{description:y}:{}}),await ci(n,k)}return ge.info("skill published",{agentId:n,skillName:e.skillName,relPath:u,zipBytes:S.length,skillId:A,version:I}),{ok:!0,skillId:A,version:I}}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,ge.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,ge.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d}),h.stop(n).catch(x=>ge.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:s,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return ge.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await Re(n);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return ge.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await hr(i.workspace,i.framework,e.cozeIdentity)}catch(s){throw ge.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(s)}),new T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(s)}`,{cause:s})}return i.cozeIdentity=e.cozeIdentity,await Ue(i),ge.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:i.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async upgradeBridge(e){let n=e.agentId||e._meta?.cozeAgentId;if(!n)throw new T("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Re(n))throw new T("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=["-y"];e.registry&&Ni(e.registry)&&s.push(`--registry=${e.registry}`);let c=Q_(e.targetVersion);s.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&Z_.test(d)&&s.push("--env",d);let u=await ey(s);return ge.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 T("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Re(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ue(i),ge.info("agent disconnected",{agentId:n,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(n,e.reason??"disconnect"),{ok:!0}):(ge.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new T("IPC_BAD_REQUEST",`${xt.DELETE}: missing agentId`);let i=await Re(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=Ye(n);return c==="cloud"?await Xc(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ue(i)),ge.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Dr(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=Kc(e.model)??Lt,i=await Re(e.agentId);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ue(i),ge.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return ge.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=s.model;s.model=n,e.modelInfo&&s.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(s,c).catch(u=>ge.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),ge.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(Dr(e._meta,xt.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${xt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,xt.RESET),await this.runDetailSync(e.agentId,xt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),ge.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 ai(e,s)}async clearPersistedAcpSessionIds(e){let n=await Re(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 Ue(n)}async repairAgent(e){if(Dr(e._meta,xt.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${xt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${xt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){ge.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,xt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){ge.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){ge.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(s)})}}async getFileTree(e){Dr(e._meta,"_agent/getFileTree");let n=e._meta,i=Jn(n),s=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(s,c),u=await Zc(d).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await oi(d,s))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=gy(e.depth);return u.isDirectory()?{tree:await py(s,d,c,h)}:{tree:[{name:my(c),path:f0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Dr(e._meta,"_agent/getFileContent");let n=Jn(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new T("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(i,e.filePath),c=await Zc(s).catch(()=>null);if(!c||!c.isFile())throw new T("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await oi(s,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>t0)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${t0})`);let d=await ho(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 Re(e).catch(()=>null))?.workspace??Ye(e).workspace}safeJoin(e,n){let i=ed(e,n||"."),s=nd(e,i);if(s.startsWith("..")||s===".."||s.startsWith(`..${i0}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return Re(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new T("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function a0(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 id(t){return t==="claude-code"?Je(".claude","skills"):Je(".agents","skills")}function c0(t,e){return(j_("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 ty(t,e,n){let i=id(n),s=Je(e,i),c=await r0(s,{withFileTypes:!0}).catch(()=>null);if(!c)return[];let d=[];for(let u of c){if(!u.isDirectory())continue;let h=u.name,x=Je(i,h),m=Je(s,h,"SKILL.md"),_=await ho(m,{encoding:"utf8"}).catch(()=>null);if(_===null)continue;let S=d0(_);d.push({relPath:x,skill:{skillId:c0(t,x),skillName:S.name||h,...S.description?{description:S.description}:{}}})}return d}var ny=3e4,ry=50*1024*1024,n0=10*1024*1024,Or=3e4;async function po(t){let{agentId:e,workspace:n,framework:i,skill:s}=t;if(!s.skillName)throw new T("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 T("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let u=a0(s.skillName),h=id(i),x=Je(h,u),m=Je(n,x);if(await Yc(m,{recursive:!0}),c){let S=Buffer.from(s.content,"utf8");Fi(S.length),await Qc(Je(m,"SKILL.md"),S,"utf8")}else{let S=await oy(s.downloadUrl);cy(S)?await fy(S,m):dy(S)?await ly(S,m):await Qc(Je(m,"SKILL.md"),S.toString("utf8"),"utf8")}let _={skillId:s.skillId,skillName:s.skillName,relPath:x,installedAt:Date.now(),...s.description?{description:s.description}:{},...s.icon?{icon:s.icon}:{},...s.version?{version:s.version}:{},...s.downloadUrl?{downloadUrl:s.downloadUrl}:{},...s.config?{config:s.config}:{},...s.builtin?{builtin:s.builtin}:{}};return ge.info("skill installed",{agentId:e,skillId:s.skillId,skillName:s.skillName,relPath:x,source:c?"content":"downloadUrl"}),_}function go(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 iy(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 l0(t,e){let n=await Re(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Ot,s=n.skillsRefreshedForVersion;if(s===i)return{status:"noop",count:0};if(!s)return n.skillsRefreshedForVersion=i,await Ue(n,e),{status:"seeded",count:0};let c=[...n.skills??[]],d=new Map(c.map((m,_)=>[m.skillId,_])),u=c.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Ue(n,e),{status:"noop",count:0};let h=0,x=0;for(let m of u)try{await Xc(Je(n.workspace,m.relPath),{recursive:!0,force:!0});let _=await po({agentId:t,workspace:n.workspace,framework:n.framework,skill:sy(m)});go(c,d,_),h+=1}catch(_){x+=1,ge.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(_)})}return n.skills=c,x===0&&(n.skillsRefreshedForVersion=i),await Ue(n,e),ge.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:s,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function oy(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Fi(e);let n=ay(t);return Fi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await ho(e);return Fi(n.length),n}if(Ni(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),ny);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new T("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let s=await i.arrayBuffer();return Fi(s.byteLength),Buffer.from(s)}finally{clearTimeout(n)}}throw new T("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Fi(t){if(t>ry)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 n=!!e[2],i=e[3]??"";return n?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function cy(t){return t.length>=2&&t[0]===31&&t[1]===139}function dy(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 td(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function ly(t,e){let n,i;try{n=new rd.default(t),i=n.getEntries()}catch(d){throw new T("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||td(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new T("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let s=uy(i),c=ed(e);for(let d of i){if(td(d.entryName))continue;let u=d.entryName;if(s&&u.startsWith(s)&&(u=u.slice(s.length)),!u)continue;let h=ed(e,u),x=nd(c,h);if(x.startsWith("..")||x==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Yc(h,{recursive:!0});continue}await Yc(W_(h),{recursive:!0});let m;try{m=d.getData()}catch(_){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${_.message}`,{cause:_})}await Qc(h,m)}}function uy(t){let e;for(let n of t){let i=n.entryName;if(!i||td(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 fy(t,e){await hy(t);let n=Pf({cwd:e,strip:1}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await o0(s0.from(t),n)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(s)}}async function hy(t){let e=[],n=Cr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await o0(s0.from(t),n)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(s)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var xy=5e3;async function py(t,e,n,i){return u0(t,e,n,i,{count:0})}async function u0(t,e,n,i,s){if(i<=0)return[];let c;try{c=await r0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(J_.has(u.name)||u.isSymbolicLink())continue;if(s.count>=xy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=Je(e,u.name),x=K_(Je(n,u.name)),m=null;try{m=await Zc(h)}catch{continue}if(m.isSymbolicLink())continue;s.count++;let _={name:u.name,path:f0(nd(t,h)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(_.children=await u0(t,h,x,i-1,s)),d.push(_)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function gy(t){return!t||t<=0?$_:Math.min(t,V_)}function my(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function f0(t){return t.split(i0).join("/")}ee();var An=q("agent-health-reporter"),wy=1e4,_y=3,zi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??wy,this.livenessFailureThreshold=e.livenessFailureThreshold??_y}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),An.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),An.info("heartbeat stopped"))}async tick(){if(this.inFlight){An.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,An.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let d of this.opts.core.agents.values()){let u=yy(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:Ot,_meta:{cozeDeviceId:e}},s;try{s=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,An.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=s?.authFailures;if(c&&c.length>0&&(An.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(d){An.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){An.warn("onTickEnd hook failed",{err:String(n)})}}};function yy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}un();import{mkdir as ld,rm as ub,stat as fb}from"node:fs/promises";import{homedir as hb}from"node:os";import{join as G0}from"node:path";cn();import{existsSync as Oy}from"node:fs";import{release as Ly}from"node:os";import{basename as Ny,isAbsolute as My}from"node:path";function Ui(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Lr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Nr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Tn(t,e){return{jsonrpc:"2.0",id:t,error:e}}$e();var mo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},J={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 h0(t){return"method"in t&&"id"in t&&t.id!==void 0}function x0(t){return"method"in t&&!("id"in t)}function wo(t){return!("method"in t)&&"id"in t}var by={AGENT_NOT_FOUND:J.AGENT_NOT_FOUND,AGENT_BUSY:J.AGENT_BUSY,AGENT_DISCONNECTED:J.AGENT_DISCONNECTED,AGENT_TIMEOUT:J.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:J.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:J.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:J.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:J.INTERNAL_ERROR,BRIDGE_INTERNAL:J.INTERNAL_ERROR,IPC_AUTH_FAILED:J.INTERNAL_ERROR,IPC_BAD_REQUEST:J.INVALID_REQUEST,METHOD_NOT_FOUND:J.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:J.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:J.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:J.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:J.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:J.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:J.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:J.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:J.FILE_TOO_LARGE,UNSUPPORTED_MIME:J.UNSUPPORTED_MIME,UPLOAD_FAILED:J.UPLOAD_FAILED,UPSTREAM_NOT_READY:J.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:J.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:J.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:J.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:J.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:J.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:J.SKILL_ZIP_TOO_LARGE};function Ey(t){if(t!=null)return t instanceof Error?{name:t.name,message:Gi(t.message)}:typeof t=="string"?Gi(t):typeof t=="object"?Sy(t):t}var vy=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Gi(t){let e=t;for(let[n,i]of vy)e=e.replace(n,i);return e}function Sy(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Gi(i):e[n]=i;return e}function qi(t){if(t instanceof T){let e=Ey(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:by[t.code]??J.INTERNAL_ERROR,message:Gi(t.message),data:n}}return{code:J.INTERNAL_ERROR,message:Gi(t instanceof Error?t.message:String(t))}}function p0(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 T(n,s,{retriable:e?.retriable??!1,cause:c})}function m0(t){return`${JSON.stringify(t)}
95
- `}var g0=10*1024*1024,_o=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>g0){let s=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${s} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${g0} 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 _0={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission","session/set_mode":"session.setMode",initialize:"initialize"},vT=Object.fromEntries(Object.entries(_0).map(([t,e])=>[e,t])),Iy={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Mr=class{seq=0;next(e,n){this.seq+=1;let i=_0[e]??Ay(e),s=Iy[i]??[],c=[i,String(this.seq)];if(s.length>0){let d=s.map(h=>w0(n?.[h]??"")),u=Ty(d).join(":");u&&c.push(u)}else n&&Object.values(n).some(d=>d)&&c.push(Object.values(n).filter(Boolean).map(d=>w0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function Ay(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function w0(t){return t.replace(/[:_\s]+/g,"-")}function Ty(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}ln();import{readFileSync as ky}from"node:fs";var Cy=384;async function sd(t,e=process.env){let n={};for(let[i,s]of Object.entries(e))typeof s=="string"&&(n[i]=s);await fr(t.agentEnvFile,n,{mode:Cy})}function od(t){try{let e=JSON.parse(ky(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function y0(t,e,n={},i=s=>s){return{...i({...t,...od(e)}),...n}}Zt();ar();$e();ee();Be();import{execFileSync as Dy,spawnSync as Ry}from"node:child_process";function Hi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function ji(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),Ry("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ad=new Set;function b0(t){typeof t=="number"&&t>0&&ad.add(t)}function E0(t){typeof t=="number"&&ad.delete(t)}function v0(){for(let t of ad)ji(t,"SIGKILL")}var Br="coze-bridge-daemon";function S0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let s=process.getuid?.()??0;return Dy("pgrep",["-U",String(s),"-f",Br],{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 I0(t,e){if(t.length===0)return;let n=e?.killFn??ji,i=e?.isAliveFn??Hi,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 Py=[{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 A0(t,e){if(!e)return null;for(let n of Py)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 A0(t,e)}function k0(t,e){return A0(t,e)}function Fr(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,m=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:s,rearmMs:Fr(m,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:Fr(c,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Fr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Fr(c,!1,e)}}var D0=Ze("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),By=200,Fy=40,zy=Ze("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Uy=Ze("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Gy=Ze("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),qy=Ze("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Hy=Ze("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),jy=Ze("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),R0=500;function Wy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=R0?t:`${e.slice(0,R0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Ky(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 P0(t){try{return Oy(t)}catch{return}}function $y(t,e){return{platform:process.platform,osRelease:Ly(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:My(e.command)?P0(e.command):void 0,cwd:e.cwd,cwdExists:P0(e.cwd),envKeys:e.envKeys}}function Vy(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Ny(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Nt=class{constructor(e){this.opts=e;this.log=q(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new _o({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Mr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new T("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=y0(process.env,this.opts.agentEnvFile??X().agentEnvFile,this.opts.env,s=>this.sanitizeEnv(s)),i=st(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>By&&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,E0(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=$y(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 T("AGENT_SPAWN_FAILED",Vy(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()));ji(n.pid,"SIGTERM");let s=setTimeout(()=>{n.killed||ji(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:Hy,phase2GateMs:zy,livenessWindowMs:Uy,absoluteMaxMs:Gy,approvalMaxMs:jy,suspendThresholdMs:qy,...n};return this.call("session/prompt",e,D0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Lr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Nr(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(Tn(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=D0,s){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Ui(c,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let h=n.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let m={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(s){let _=this.now(),S={cfg:s,startedAt:_,lastActivityAt:_,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:_,expectedIntervalMs:Fr(0,!1,s),sessionId:u};m.promptTimeout=S;let y=()=>{let v={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=C0(v,S.cfg,I),k=P=>{S.armedAt=I,S.expectedIntervalMs=P,m.timer=setTimeout(y,P)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),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,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(y,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(d)}catch(_){m.timer&&clearTimeout(m.timer),this.pending.delete(c),x(_)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(m0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(wo(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new T("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:Wy(e.result)}),n.resolve(e.result));return}if(x0(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(h0(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(Tn(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(Tn(e.id,qi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=p0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=k0(this.framework,Ky(e));return i?new T(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):n}buildExitError(e,n){if(this.stopReason!==void 0)return new T("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(Fy).join(`
98
- `),s=T0(this.framework,i);return s?new T(s.bridgeCode,s.message,{cause:{reason:s.reason,code:e,signal:n,stderrTail:i}}):new T("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Jy(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 yo=class extends Nt{framework="claude-code";constructor(e){let{command:n,args:i}=si("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 Jy(e)}};cn();import{mkdtempSync as Zy,rmSync as Yy}from"node:fs";import{tmpdir as Xy}from"node:os";import{join as Qy}from"node:path";var bo=class extends Nt{framework="codex";authMethodId;codexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:s,args:c}=si("codex",e.command,i),d=e.isolateCodexHome?Zy(Qy(Xy(),"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{Yy(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};$e();var eb=3e4,zr=class extends Nt{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}`}]},eb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var O0=["default","acceptEdits","plan","auto","bypassPermissions"],L0=["read-only","auto","full-access"];function kn(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return O0.includes(e);case"codex":return L0.includes(e);case"openclaw":return!1}}function cd(t){switch(t){case"claude-code":return O0.join("/");case"codex":return L0.join("/");case"openclaw":return""}}ln();$e();ee();Be();function dd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}cn();var Cn=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((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 Eo=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 Cn,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)Wi(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 Wi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Yt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Zt();ee();import{constants as N0}from"node:fs";import{access as tb}from"node:fs/promises";import{delimiter as nb,join as rb}from"node:path";var St=q("framework-detector"),M0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},ib=[".exe",".cmd",".bat",".ps1"],Zn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??st,access:e.access??tb}}async detect(e){let n=M0[e],i=await this.which(n);if(!i)return St.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(M0).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(nb).filter(Boolean),i=this.env.platform==="win32"?["",...ib]:[""];for(let s of n)for(let c of i){let d=rb(s,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?N0.F_OK:N0.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return St.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return St.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return St.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let s=JSON.parse(i[0]);if(!Array.isArray(s))return St.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?(St.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(St.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:s.length}),null)}catch(s){return St.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 St.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||St.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let 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){St.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&&(ob(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)}})}},sb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function ob(t){return t.replace(sb,"")}import{homedir as ab}from"node:os";import{join as cb}from"node:path";ln();Zt();ar();$e();ee();async function z0(){let t=cb(ab(),".openclaw/openclaw.json");return ur(t)}async function U0(){return(await z0())?.gateway?.auth?.token??""}var B0=q("openclaw.config"),db=[0,5e3,5e3],lb=Ze("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),F0="models.providers.",vo="agents.defaults.models",So=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new Cn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??db,this.cliTimeoutMs=e.cliTimeoutMs??lb}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,B0.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(d)})}}throw new T("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let s=st(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){B0.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",`${F0}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${F0}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${vo}[${e}]`,()=>this.runCli(["config","set",vo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${vo}[${e}]`,`${vo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await z0())?.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 fe=q("agent-manager"),fd="acceptEdits",j0="full-access",W0="read-only";function xb(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 pb=(t,e,n,i,s,c,d,u,h,x)=>{switch(t){case"claude-code":{let m={...s?{...Vf(s),...Yf(s,d,u)}:{},...h??{},IS_SANDBOX:"1"};return new yo({cwd:n,env:m,agentId:i})}case"codex":{let m=s?[...Jf(s),...Qf(s,d,u)]:[],_=j0;x!==void 0&&(kn("codex",x)?_=x:fe.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let S=[...m,...xb(_)],y={...s?Zf(s):{},...h??{}},v=!!s;return new bo({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 zr({command:e,cwd:n,agentId:i,...c?{sessionName:dd(c)}:{}})}};function ud(t){return t==="claude-code"||t==="codex"}function gb(t){let e=[],n=Object.keys(t).sort();for(let i of n){let s=t[i];s!==void 0&&(mb(s)||e.push(`${i}=${s}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return tI(t.homeDir,".coze","bridge","task.xml")},async install(t){let r=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await wp("schtasks",["/Create","/SC","ONLOGON","/TN",pa,"/TR",r,"/RU",t.userName,"/F"]),rl.info("task scheduler entry created",{task:pa,logFile:t.logFile})},async uninstall(t){await wp("schtasks",["/Delete","/TN",pa,"/F"]).catch(e=>rl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),rl.info("task scheduler entry removed",{task:pa})}}});var yp={};Ca(yp,{buildContext:()=>aI,getSupervisor:()=>iI,launchdSupervisor:()=>tl,systemdSupervisor:()=>nl,taskSchedulerSupervisor:()=>il});import{homedir as nI,userInfo as rI}from"node:os";function iI(t=process.platform){switch(t){case"darwin":return tl;case"linux":return nl;case"win32":return il;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function oI(){let t={};for(let e of sI){let r=process.env[e];r&&(t[e]=r)}return t}function aI(){let t=Y();return{nodeBin:process.execPath,entry:Wd(t),logFile:t.logFile,homeDir:nI(),userName:rI().username,isRoot:process.getuid?.()===0,env:oI()}}var sI,Ep=nt(()=>{"use strict";Re();ia();pp();mp();_p();sI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();on();var Ll=H("acp-installer-warmup"),Vg=["claude-code","codex"];async function Nl(t={}){let e=t.ensure??fr,i=(await Promise.allSettled(Vg.map(async o=>{let c=await e(o);Ll.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Ll.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}un();ne();import{readdir as lm}from"node:fs/promises";import{mkdir as zl,readFile as cm,writeFile as Ul}from"node:fs/promises";import{join as Ma}from"node:path";var dm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function hr(t,e,r){await zl(t,{recursive:!0});let i=dm[e],o=Ma(t,i);return await Ul(o,r??"","utf8"),o}async function Ba(t,e,r){let i=Ma(t,".claude");await zl(i,{recursive:!0});let o=Ma(i,"settings.local.json"),c={};try{let u=await cm(o,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}catch{}let l=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")l.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");l.defaultMode===void 0&&(l.defaultMode=r)}return c.permissions=l,await Ul(o,JSON.stringify(c,null,2),"utf8"),o}var Xe=H("agent-detail-sync"),um=6e4,fm=5*6e4,ys=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await lm(r)}catch(o){Xe.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Xe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await De(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Xe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(l){Xe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(l)})}}})),Xe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Xe.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Xe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await De(e,this.opts.paths);if(!i){Xe.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),g=x?Math.min(x.currentDelay*2,fm):um;this.retryQueue.set(e,{dueAt:Date.now()+g,currentDelay:g});return}if(o.agentId&&o.agentId!==e){Xe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,l=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,l=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Xe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Xe.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Xe.debug("detail sync: no diff",{agentId:e});return}await ze(i,this.opts.paths),Xe.info("detail sync: config updated",{agentId:e,identityChanged:l,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Xe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await hr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var id=Ht(_u(),1);import{createHash as K_}from"node:crypto";import{lstat as Yc,mkdir as Xc,readFile as ho,readdir as s0,rm as Qc,stat as n0,writeFile as ed}from"node:fs/promises";import{dirname as W_,join as Ve,normalize as $_,relative as rd,resolve as td,sep as o0}from"node:path";import{Readable as a0}from"node:stream";import{pipeline as c0}from"node:stream/promises";import Lm from"events";import rt from"fs";import{EventEmitter as Mc}from"node:events";import ef from"node:stream";import{StringDecoder as Nm}from"node:string_decoder";import rf from"node:path";import Ir from"node:fs";import{dirname as Vm,parse as Jm}from"path";import{EventEmitter as rw}from"events";import mc from"assert";import{Buffer as Kn}from"buffer";import*as Su from"zlib";import iw from"zlib";import{posix as wr}from"node:path";import{basename as Dw}from"node:path";import Xs from"fs";import Dt from"fs";import Du from"path";import{win32 as Gw}from"node:path";import Fu from"path";import _f from"node:fs";import s_ from"node:assert";import{randomBytes as yf}from"node:crypto";import ie from"node:fs";import Be from"node:path";import Ef from"fs";import ao from"node:fs";import Ai from"node:path";import at from"node:fs";import f_ from"node:fs/promises";import to from"node:path";import{join as Pf}from"node:path";import ot from"node:fs";import Nf from"node:path";var Pm=Object.defineProperty,Om=(t,e)=>{for(var r in e)Pm(t,r,{get:e[r],enumerable:!0})},yu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Mm=t=>!!t&&typeof t=="object"&&(t instanceof Vn||t instanceof ef||Bm(t)||Fm(t)),Bm=t=>!!t&&typeof t=="object"&&t instanceof Mc&&typeof t.pipe=="function"&&t.pipe!==ef.Writable.prototype.pipe,Fm=t=>!!t&&typeof t=="object"&&t instanceof Mc&&typeof t.write=="function"&&typeof t.end=="function",Gt=Symbol("EOF"),qt=Symbol("maybeEmitEnd"),hn=Symbol("emittedEnd"),Is=Symbol("emittingEnd"),di=Symbol("emittedError"),As=Symbol("closed"),Eu=Symbol("read"),ks=Symbol("flush"),bu=Symbol("flushChunk"),mt=Symbol("encoding"),mr=Symbol("decoder"),Ue=Symbol("flowing"),li=Symbol("paused"),br=Symbol("resume"),He=Symbol("buffer"),Qe=Symbol("pipes"),Ge=Symbol("bufferLength"),qa=Symbol("bufferPush"),Ts=Symbol("bufferShift"),Ye=Symbol("objectMode"),ke=Symbol("destroyed"),ja=Symbol("error"),Ka=Symbol("emitData"),vu=Symbol("emitEnd"),Wa=Symbol("emitEnd2"),Tt=Symbol("async"),$a=Symbol("abort"),Cs=Symbol("aborted"),ui=Symbol("signal"),Mn=Symbol("dataListeners"),st=Symbol("discarded"),fi=t=>Promise.resolve().then(t),zm=t=>t(),Um=t=>t==="end"||t==="finish"||t==="prefinish",Hm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Gm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),tf=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[br](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},qm=class extends tf{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},jm=t=>!!t.objectMode,Km=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Vn=class extends Mc{[Ue]=!1;[li]=!1;[Qe]=[];[He]=[];[Ye];[mt];[Tt];[mr];[Gt]=!1;[hn]=!1;[Is]=!1;[As]=!1;[di]=null;[Ge]=0;[ke]=!1;[ui];[Cs]=!1;[Mn]=0;[st]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");jm(e)?(this[Ye]=!0,this[mt]=null):Km(e)?(this[mt]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[mt]=null),this[Tt]=!!e.async,this[mr]=this[mt]?new Nm(this[mt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:r}=e;r&&(this[ui]=r,r.aborted?this[$a]():r.addEventListener("abort",()=>this[$a]()))}get bufferLength(){return this[Ge]}get encoding(){return this[mt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Tt]}set async(t){this[Tt]=this[Tt]||!!t}[$a](){this[Cs]=!0,this.emit("abort",this[ui]?.reason),this.destroy(this[ui]?.reason)}get aborted(){return this[Cs]}set aborted(t){}write(t,e,r){if(this[Cs])return!1;if(this[Gt])throw new Error("write after end");if(this[ke])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[Tt]?fi:zm;if(!this[Ye]&&!Buffer.isBuffer(t)){if(Gm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Hm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ye]?(this[Ue]&&this[Ge]!==0&&this[ks](!0),this[Ue]?this.emit("data",t):this[qa](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):t.length?(typeof t=="string"&&!(e===this[mt]&&!this[mr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[mt]&&(t=this[mr].write(t)),this[Ue]&&this[Ge]!==0&&this[ks](!0),this[Ue]?this.emit("data",t):this[qa](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):(this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue])}read(t){if(this[ke])return null;if(this[st]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[qt](),null;this[Ye]&&(t=null),this[He].length>1&&!this[Ye]&&(this[He]=[this[mt]?this[He].join(""):Buffer.concat(this[He],this[Ge])]);let e=this[Eu](t||null,this[He][0]);return this[qt](),e}[Eu](t,e){if(this[Ye])this[Ts]();else{let r=e;t===r.length||t===null?this[Ts]():typeof r=="string"?(this[He][0]=r.slice(t),e=r.slice(0,t),this[Ge]-=t):(this[He][0]=r.subarray(t),e=r.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[He].length&&!this[Gt]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[Gt]=!0,this.writable=!1,(this[Ue]||!this[li])&&this[qt](),this}[br](){this[ke]||(!this[Mn]&&!this[Qe].length&&(this[st]=!0),this[li]=!1,this[Ue]=!0,this.emit("resume"),this[He].length?this[ks]():this[Gt]?this[qt]():this.emit("drain"))}resume(){return this[br]()}pause(){this[Ue]=!1,this[li]=!0,this[st]=!1}get destroyed(){return this[ke]}get flowing(){return this[Ue]}get paused(){return this[li]}[qa](t){this[Ye]?this[Ge]+=1:this[Ge]+=t.length,this[He].push(t)}[Ts](){return this[Ye]?this[Ge]-=1:this[Ge]-=this[He][0].length,this[He].shift()}[ks](t=!1){do;while(this[bu](this[Ts]())&&this[He].length);!t&&!this[He].length&&!this[Gt]&&this.emit("drain")}[bu](t){return this.emit("data",t),this[Ue]}pipe(t,e){if(this[ke])return t;this[st]=!1;let r=this[hn];return e=e||{},t===yu.stdout||t===yu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Qe].push(e.proxyErrors?new qm(this,t,e):new tf(this,t,e)),this[Tt]?fi(()=>this[br]()):this[br]()),t}unpipe(t){let e=this[Qe].find(r=>r.dest===t);e&&(this[Qe].length===1?(this[Ue]&&this[Mn]===0&&(this[Ue]=!1),this[Qe]=[]):this[Qe].splice(this[Qe].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[st]=!1,this[Mn]++,!this[Qe].length&&!this[Ue]&&this[br]();else if(t==="readable"&&this[Ge]!==0)super.emit("readable");else if(Um(t)&&this[hn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[di]){let i=e;this[Tt]?fi(()=>i.call(this,this[di])):i.call(this,this[di])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Mn]=this.listeners("data").length,this[Mn]===0&&!this[st]&&!this[Qe].length&&(this[Ue]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Mn]=0,!this[st]&&!this[Qe].length&&(this[Ue]=!1)),e}get emittedEnd(){return this[hn]}[qt](){!this[Is]&&!this[hn]&&!this[ke]&&this[He].length===0&&this[Gt]&&(this[Is]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[As]&&this.emit("close"),this[Is]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==ke&&this[ke])return!1;if(t==="data")return!this[Ye]&&!r?!1:this[Tt]?(fi(()=>this[Ka](r)),!0):this[Ka](r);if(t==="end")return this[vu]();if(t==="close"){if(this[As]=!0,!this[hn]&&!this[ke])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[di]=r,super.emit(ja,r);let o=!this[ui]||this.listeners("error").length?super.emit("error",r):!1;return this[qt](),o}else if(t==="resume"){let o=super.emit("resume");return this[qt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[qt](),i}[Ka](t){for(let r of this[Qe])r.dest.write(t)===!1&&this.pause();let e=this[st]?!1:super.emit("data",t);return this[qt](),e}[vu](){return this[hn]?!1:(this[hn]=!0,this.readable=!1,this[Tt]?(fi(()=>this[Wa]()),!0):this[Wa]())}[Wa](){if(this[mr]){let e=this[mr].end();if(e){for(let r of this[Qe])r.dest.write(e);this[st]||super.emit("data",e)}}for(let e of this[Qe])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ye]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Ye]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Ye])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[mt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ke,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[st]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Gt])return e();let i,o,c=x=>{this.off("data",l),this.off("end",u),this.off(ke,f),e(),o(x)},l=x=>{this.off("error",c),this.off("end",u),this.off(ke,f),this.pause(),i({value:x,done:!!this[Gt]})},u=()=>{this.off("error",c),this.off("data",l),this.off(ke,f),e(),i({done:!0,value:void 0})},f=()=>c(new Error("stream destroyed"));return new Promise((x,g)=>{o=g,i=x,this.once(ke,f),this.once("error",c),this.once("end",u),this.once("data",l)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[st]=!1;let t=!1,e=()=>(this.pause(),this.off(ja,e),this.off(ke,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(ja,e),this.once(ke,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[ke])return t?this.emit("error",t):this.emit(ke),this;this[ke]=!0,this[st]=!0,this[He].length=0,this[Ge]=0;let e=this;return typeof e.close=="function"&&!this[As]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return Mm}},Wm=rt.writev,vn=Symbol("_autoClose"),Et=Symbol("_close"),hi=Symbol("_ended"),le=Symbol("_fd"),Va=Symbol("_finished"),$t=Symbol("_flags"),Ja=Symbol("_flush"),pc=Symbol("_handleChunk"),gc=Symbol("_makeBuf"),Si=Symbol("_mode"),Rs=Symbol("_needDrain"),kr=Symbol("_onerror"),Tr=Symbol("_onopen"),Za=Symbol("_onread"),vr=Symbol("_onwrite"),Sn=Symbol("_open"),yt=Symbol("_path"),wn=Symbol("_pos"),Ct=Symbol("_queue"),Sr=Symbol("_read"),Ya=Symbol("_readSize"),Wt=Symbol("_reading"),xi=Symbol("_remain"),Xa=Symbol("_size"),Us=Symbol("_write"),Bn=Symbol("_writing"),Hs=Symbol("_defaultFlag"),jn=Symbol("_errored"),Bc=class extends Vn{[jn]=!1;[le];[yt];[Ya];[Wt]=!1;[Xa];[xi];[vn];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[jn]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[yt]=t,this[Ya]=e.readSize||16*1024*1024,this[Wt]=!1,this[Xa]=typeof e.size=="number"?e.size:1/0,this[xi]=this[Xa],this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[Sr]():this[Sn]()}get fd(){return this[le]}get path(){return this[yt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Sn](){rt.open(this[yt],"r",(t,e)=>this[Tr](t,e))}[Tr](t,e){t?this[kr](t):(this[le]=e,this.emit("open",e),this[Sr]())}[gc](){return Buffer.allocUnsafe(Math.min(this[Ya],this[xi]))}[Sr](){if(!this[Wt]){this[Wt]=!0;let t=this[gc]();if(t.length===0)return process.nextTick(()=>this[Za](null,0,t));rt.read(this[le],t,0,t.length,null,(e,r,i)=>this[Za](e,r,i))}}[Za](t,e,r){this[Wt]=!1,t?this[kr](t):this[pc](e,r)&&this[Sr]()}[Et](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[kr](t){this[Wt]=!0,this[Et](),this.emit("error",t)}[pc](t,e){let r=!1;return this[xi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[xi]<=0)&&(r=!1,this[Et](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[Sr](),!1;case"error":return this[jn]?!1:(this[jn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},$m=class extends Bc{[Sn](){let t=!0;try{this[Tr](null,rt.openSync(this[yt],"r")),t=!1}finally{t&&this[Et]()}}[Sr](){let t=!0;try{if(!this[Wt]){this[Wt]=!0;do{let e=this[gc](),r=e.length===0?0:rt.readSync(this[le],e,0,e.length,null);if(!this[pc](r,e))break}while(!0);this[Wt]=!1}t=!1}finally{t&&this[Et]()}}[Et](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,rt.closeSync(t),this.emit("close")}}},no=class extends Lm{readable=!1;writable=!0;[jn]=!1;[Bn]=!1;[hi]=!1;[Ct]=[];[Rs]=!1;[yt];[Si];[vn];[le];[Hs];[$t];[Va]=!1;[wn];constructor(t,e){e=e||{},super(e),this[yt]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Si]=e.mode===void 0?438:e.mode,this[wn]=typeof e.start=="number"?e.start:void 0,this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[wn]!==void 0?"r+":"w";this[Hs]=e.flags===void 0,this[$t]=e.flags===void 0?r:e.flags,this[le]===void 0&&this[Sn]()}emit(t,...e){if(t==="error"){if(this[jn])return!1;this[jn]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[yt]}[kr](t){this[Et](),this[Bn]=!0,this.emit("error",t)}[Sn](){rt.open(this[yt],this[$t],this[Si],(t,e)=>this[Tr](t,e))}[Tr](t,e){this[Hs]&&this[$t]==="r+"&&t&&t.code==="ENOENT"?(this[$t]="w",this[Sn]()):t?this[kr](t):(this[le]=e,this.emit("open",e),this[Bn]||this[Ja]())}end(t,e){return t&&this.write(t,e),this[hi]=!0,!this[Bn]&&!this[Ct].length&&typeof this[le]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[hi]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[Bn]||this[Ct].length?(this[Ct].push(t),this[Rs]=!0,!1):(this[Bn]=!0,this[Us](t),!0)}[Us](t){rt.write(this[le],t,0,t.length,this[wn],(e,r)=>this[vr](e,r))}[vr](t,e){t?this[kr](t):(this[wn]!==void 0&&typeof e=="number"&&(this[wn]+=e),this[Ct].length?this[Ja]():(this[Bn]=!1,this[hi]&&!this[Va]?(this[Va]=!0,this[Et](),this.emit("finish")):this[Rs]&&(this[Rs]=!1,this.emit("drain"))))}[Ja](){if(this[Ct].length===0)this[hi]&&this[vr](null,0);else if(this[Ct].length===1)this[Us](this[Ct].pop());else{let t=this[Ct];this[Ct]=[],Wm(this[le],t,this[wn],(e,r)=>this[vr](e,r))}}[Et](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},nf=class extends no{[Sn](){let t;if(this[Hs]&&this[$t]==="r+")try{t=rt.openSync(this[yt],this[$t],this[Si])}catch(e){if(e?.code==="ENOENT")return this[$t]="w",this[Sn]();throw e}else t=rt.openSync(this[yt],this[$t],this[Si]);this[Tr](null,t)}[Et](){if(this[vn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,rt.closeSync(t),this.emit("close")}}[Us](t){let e=!0;try{this[vr](null,rt.writeSync(this[le],t,0,t.length,this[wn])),e=!1}finally{if(e)try{this[Et]()}catch{}}}},Zm=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),Ym=t=>!!t.sync&&!!t.file,Xm=t=>!t.sync&&!!t.file,Qm=t=>!!t.sync&&!t.file,ew=t=>!t.sync&&!t.file,tw=t=>!!t.file,nw=t=>Zm.get(t)||t,Fc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=nw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Oi=(t,e,r,i,o)=>Object.assign((c=[],l,u)=>{Array.isArray(c)&&(l=c,c={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let f=Fc(c);if(o?.(f,l),Ym(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,l)}else if(Xm(f)){let x=e(f,l);return u?x.then(()=>u(),u):x}else if(Qm(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(f,l)}else if(ew(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,l)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),sw=iw.constants||{ZLIB_VERNUM:4736},Ot=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},sw)),ow=Kn.concat,Iu=Object.getOwnPropertyDescriptor(Kn,"concat"),aw=t=>t,Qa=Iu?.writable===!0||Iu?.set!==void 0?t=>{Kn.concat=t?aw:ow}:t=>{},Wn=Symbol("_superWrite"),Ds=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},ec=Symbol("flushFlag"),zc=class extends Vn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Su[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Su[e](t)}catch(r){throw new Ds(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new Ds(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return mc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Kn.alloc(0),{[ec]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[Wn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Kn.from(t,e)),this.#e)return;mc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Qa(!0);let l;try{let f=typeof t[ec]=="number"?t[ec]:this.#r;l=this.#t._processChunk(t,f),Qa(!1)}catch(f){Qa(!1),this.#o(new Ds(f,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",f=>this.#o(new Ds(f,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let f=l[0];u=this[Wn](Kn.from(f));for(let x=1;x<l.length;x++)u=this[Wn](l[x])}else u=this[Wn](Kn.from(l));return r&&r(),u}},sf=class extends zc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ot.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ot.Z_FINISH,t.fullFlushFlag=Ot.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Ot.Z_SYNC_FLUSH),mc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},cw=class extends sf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Wn](t){return this.#e?(this.#e=!1,t[9]=255,super[Wn](t)):super[Wn](t)}},dw=class extends sf{constructor(t){super(t,"Unzip")}},of=class extends zc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ot.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ot.BROTLI_OPERATION_FLUSH,super(t,e)}},lw=class extends of{constructor(t){super(t,"BrotliCompress")}},uw=class extends of{constructor(t){super(t,"BrotliDecompress")}},af=class extends zc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ot.ZSTD_e_end,t.fullFlushFlag=Ot.ZSTD_e_flush,super(t,e)}},fw=class extends af{constructor(t){super(t,"ZstdCompress")}},hw=class extends af{constructor(t){super(t,"ZstdDecompress")}},xw=(t,e)=>{if(Number.isSafeInteger(t))t<0?gw(t,e):pw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},pw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},gw=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),r?e[i-1]=cf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=df(o))}},mw=t=>{let e=t[0],r=e===128?_w(t.subarray(1,t.length)):e===255?ww(t):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},ww=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),l;i?l=cf(c):c===0?l=c:(i=!0,l=df(c)),l!==0&&(r-=l*Math.pow(256,e-o-1))}return r},_w=t=>{for(var e=t.length,r=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(r+=o*Math.pow(256,e-i-1))}return r},cf=t=>(255^t)&255,df=t=>(255^t)+1&255,yw={};Om(yw,{code:()=>Uc,isCode:()=>Gs,isName:()=>Ew,name:()=>ro});var Gs=t=>ro.has(t),Ew=t=>Uc.has(t),ro=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Uc=new Map(Array.from(ro).map(t=>[t[1],t[0]])),$n=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,i){Buffer.isBuffer(t)?this.decode(t,e||0,r,i):t&&this.#n(t)}decode(t,e,r,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");this.path=r?.path??Fn(t,e,100),this.mode=r?.mode??i?.mode??_n(t,e+100,8),this.uid=r?.uid??i?.uid??_n(t,e+108,8),this.gid=r?.gid??i?.gid??_n(t,e+116,8),this.size=r?.size??i?.size??_n(t,e+124,12),this.mtime=r?.mtime??i?.mtime??tc(t,e+136,12),this.cksum=_n(t,e+148,12),i&&this.#n(i,!0),r&&this.#n(r);let o=Fn(t,e+156,1);if(Gs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Fn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=r?.uname??i?.uname??Fn(t,e+265,32),this.gname=r?.gname??i?.gname??Fn(t,e+297,32),this.devmaj=r?.devmaj??i?.devmaj??_n(t,e+329,8)??0,this.devmin=r?.devmin??i?.devmin??_n(t,e+337,8)??0,t[e+475]!==0){let l=Fn(t,e+345,155);this.path=l+"/"+this.path}else{let l=Fn(t,e+345,130);l&&(this.path=l+"/"+this.path),this.atime=r?.atime??i?.atime??tc(t,e+476,12),this.ctime=r?.ctime??i?.ctime??tc(t,e+488,12)}let c=256;for(let l=e;l<e+148;l++)c+=t[l];for(let l=e+156;l<e+512;l++)c+=t[l];this.cksumValid=c===this.cksum,this.cksum===void 0&&c===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,i=bw(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=zn(t,e,100,o)||this.needPax,this.needPax=yn(t,e+100,8,this.mode)||this.needPax,this.needPax=yn(t,e+108,8,this.uid)||this.needPax,this.needPax=yn(t,e+116,8,this.gid)||this.needPax,this.needPax=yn(t,e+124,12,this.size)||this.needPax,this.needPax=nc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=zn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=zn(t,e+265,32,this.uname)||this.needPax,this.needPax=zn(t,e+297,32,this.gname)||this.needPax,this.needPax=yn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=yn(t,e+337,8,this.devmin)||this.needPax,this.needPax=zn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=zn(t,e+345,155,c)||this.needPax:(this.needPax=zn(t,e+345,130,c)||this.needPax,this.needPax=nc(t,e+476,12,this.atime)||this.needPax,this.needPax=nc(t,e+488,12,this.ctime)||this.needPax);let l=256;for(let u=e;u<e+148;u++)l+=t[u];for(let u=e+156;u<e+512;u++)l+=t[u];return this.cksum=l,yn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:ro.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Uc.get(t));if(Gs(e)||e==="Unsupported")this.#e=e;else if(Gs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},bw=(t,e)=>{let r=t,i="",o,c=wr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=wr.dirname(r),r=wr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?o=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?o=[r.slice(0,99),i,!0]:(r=wr.join(wr.basename(i),r),i=wr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Fn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),tc=(t,e,r)=>vw(_n(t,e,r)),vw=t=>t===void 0?void 0:new Date(t*1e3),_n=(t,e,r)=>Number(t[e])&128?mw(t.subarray(e,e+r)):Iw(t,e,r),Sw=t=>isNaN(t)?void 0:t,Iw=(t,e,r)=>Sw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Aw={12:8589934591,8:2097151},yn=(t,e,r,i)=>i===void 0?!1:i>Aw[r]||i<0?(xw(i,t.subarray(e,e+r)),!0):(kw(t,e,r,i),!1),kw=(t,e,r,i)=>t.write(Tw(i,r),e,r,"ascii"),Tw=(t,e)=>Cw(Math.floor(t).toString(8),e),Cw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",nc=(t,e,r,i)=>i===void 0?!1:yn(t,e,r,i.getTime()/1e3),Rw=new Array(156).join("\0"),zn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Rw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Ys=class lf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),i=512*Math.ceil(1+r/512),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[c]=0;new $n({path:("PaxHeader/"+Dw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(o),l=Math.floor(Math.log(c)/Math.log(10))+1;return c+l>=Math.pow(10,l)&&(l+=1),l+c+o}static parse(e,r,i=!1){return new lf(Pw(Ow(e),r),i)}},Pw=(t,e)=>e?Object.assign({},e,t):t,Ow=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(Lw,Object.create(null)),Lw=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),l=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(l)*1e3):/^[0-9]+$/.test(l)?+l:l,t},Nw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ee=Nw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),uf=class extends Vn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=ee(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?ee(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=ee(t.path)),t.linkpath&&(t.linkpath=ee(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},io=(t,e,r,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=r instanceof Error&&r.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),t.emit("warn",e,r,i)):r instanceof Error?t.emit("error",Object.assign(r,i)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),i))},Mw=1024*1024,wc=Buffer.from([31,139]),_c=Buffer.from([40,181,47,253]),Bw=Math.max(wc.length,_c.length),lt=Symbol("state"),Un=Symbol("writeEntry"),jt=Symbol("readEntry"),rc=Symbol("nextEntry"),Au=Symbol("processEntry"),Rt=Symbol("extendedHeader"),pi=Symbol("globalExtendedHeader"),xn=Symbol("meta"),ku=Symbol("emitMeta"),_e=Symbol("buffer"),Kt=Symbol("queue"),pn=Symbol("ended"),ic=Symbol("emittedEnd"),Hn=Symbol("emit"),Pe=Symbol("unzip"),Ps=Symbol("consumeChunk"),Os=Symbol("consumeChunkSub"),sc=Symbol("consumeBody"),Tu=Symbol("consumeMeta"),Cu=Symbol("consumeHeader"),gi=Symbol("consuming"),oc=Symbol("bufferConcat"),Ls=Symbol("maybeEnd"),_r=Symbol("writing"),gn=Symbol("aborted"),Ns=Symbol("onDone"),Gn=Symbol("sawValidEntry"),Ms=Symbol("sawNullBlock"),Bs=Symbol("sawEOF"),Ru=Symbol("closeStream"),Fw=()=>!0,Pi=class extends rw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Kt]=[];[_e];[jt];[Un];[lt]="begin";[xn]="";[Rt];[pi];[pn]=!1;[Pe];[gn]=!1;[Gn];[Ms]=!1;[Bs]=!1;[_r]=!1;[gi]=!1;[ic]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ns,()=>{(this[lt]==="begin"||this[Gn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ns,t.ondone):this.on(Ns,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Mw,this.filter=typeof t.filter=="function"?t.filter:Fw;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[Ru]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){io(this,t,e,r)}[Cu](t,e){this[Gn]===void 0&&(this[Gn]=!1);let r;try{r=new $n(t,e,this[Rt],this[pi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Ms]?(this[Bs]=!0,this[lt]==="begin"&&(this[lt]="header"),this[Hn]("eof")):(this[Ms]=!0,this[Hn]("nullBlock"));else if(this[Ms]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let i=r.type;if(/^(Symbolic)?Link$/.test(i)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let o=this[Un]=new uf(r,this[Rt],this[pi]);if(!this[Gn])if(o.remain){let c=()=>{o.invalid||(this[Gn]=!0)};o.on("end",c)}else this[Gn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Hn]("ignoredEntry",o),this[lt]="ignore",o.resume()):o.size>0&&(this[xn]="",o.on("data",c=>this[xn]+=c),this[lt]="meta"):(this[Rt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Hn]("ignoredEntry",o),this[lt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[lt]="body":(this[lt]="header",o.end()),this[jt]?this[Kt].push(o):(this[Kt].push(o),this[rc]())))}}}[Ru](){queueMicrotask(()=>this.emit("close"))}[Au](t){let e=!0;if(!t)this[jt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[jt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[rc]()),e=!1);return e}[rc](){do;while(this[Au](this[Kt].shift()));if(this[Kt].length===0){let t=this[jt];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[sc](t,e){let r=this[Un];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[lt]="header",this[Un]=void 0,r.end()),o.length}[Tu](t,e){let r=this[Un],i=this[sc](t,e);return!this[Un]&&r&&this[ku](r),i}[Hn](t,e,r){this[Kt].length===0&&!this[jt]?this.emit(t,e,r):this[Kt].push([t,e,r])}[ku](t){switch(this[Hn]("meta",this[xn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Rt]=Ys.parse(this[xn],this[Rt],!1);break;case"GlobalExtendedHeader":this[pi]=Ys.parse(this[xn],this[pi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Rt]??Object.create(null);this[Rt]=e,e.path=this[xn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Rt]||Object.create(null);this[Rt]=e,e.linkpath=this[xn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[gn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[gn])return r?.(),!1;if((this[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[_e]&&(t=Buffer.concat([this[_e],t]),this[_e]=void 0),t.length<Bw)return this[_e]=t,r?.(),!0;for(let l=0;this[Pe]===void 0&&l<wc.length;l++)t[l]!==wc[l]&&(this[Pe]=!1);let o=!1;if(this[Pe]===!1&&this.zstd!==!1){o=!0;for(let l=0;l<_c.length;l++)if(t[l]!==_c[l]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Pe]===!1&&c)if(t.length<512)if(this[pn])this.brotli=!0;else return this[_e]=t,r?.(),!0;else try{new $n(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Pe]===void 0||this[Pe]===!1&&(this.brotli||o)){let l=this[pn];this[pn]=!1,this[Pe]=this[Pe]===void 0?new dw({}):o?new hw({}):new uw({}),this[Pe].on("data",f=>this[Ps](f)),this[Pe].on("error",f=>this.abort(f)),this[Pe].on("end",()=>{this[pn]=!0,this[Ps]()}),this[_r]=!0;let u=!!this[Pe][l?"end":"write"](t);return this[_r]=!1,r?.(),u}}this[_r]=!0,this[Pe]?this[Pe].write(t):this[Ps](t),this[_r]=!1;let i=this[Kt].length>0?!1:this[jt]?this[jt].flowing:!0;return!i&&this[Kt].length===0&&this[jt]?.once("drain",()=>this.emit("drain")),r?.(),i}[oc](t){t&&!this[gn]&&(this[_e]=this[_e]?Buffer.concat([this[_e],t]):t)}[Ls](){if(this[pn]&&!this[ic]&&!this[gn]&&!this[gi]){this[ic]=!0;let t=this[Un];if(t&&t.blockRemain){let e=this[_e]?this[_e].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[_e]&&t.write(this[_e]),t.end()}this[Hn](Ns)}}[Ps](t){if(this[gi]&&t)this[oc](t);else if(!t&&!this[_e])this[Ls]();else if(t){if(this[gi]=!0,this[_e]){this[oc](t);let e=this[_e];this[_e]=void 0,this[Os](e)}else this[Os](t);for(;this[_e]&&this[_e]?.length>=512&&!this[gn]&&!this[Bs];){let e=this[_e];this[_e]=void 0,this[Os](e)}this[gi]=!1}(!this[_e]||this[pn])&&this[Ls]()}[Os](t){let e=0,r=t.length;for(;e+512<=r&&!this[gn]&&!this[Bs];)switch(this[lt]){case"begin":case"header":this[Cu](t,e),e+=512;break;case"ignore":case"body":e+=this[sc](t,e);break;case"meta":e+=this[Tu](t,e);break;default:throw new Error("invalid state: "+this[lt])}e<r&&(this[_e]=this[_e]?Buffer.concat([t.subarray(e),this[_e]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[gn]||(this[Pe]?(t&&this[Pe].write(t),this[Pe].end()):(this[pn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ls]())),this}},Ii=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},zw=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},ff=(t,e)=>{let r=new Map(e.map(c=>[Ii(c),!0])),i=t.filter,o=(c,l="")=>{let u=l||Jm(c).root||".",f;if(c===u)f=!1;else{let x=r.get(c);f=x!==void 0?x:o(Vm(c),u)}return r.set(c,f),f};t.filter=i?(c,l)=>i(c,l)&&o(Ii(c)):c=>o(Ii(c))},Uw=t=>{let e=new Pi(t),r=t.file,i;try{i=Ir.openSync(r,"r");let o=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let l=Buffer.allocUnsafe(o.size),u=Ir.readSync(i,l,0,o.size,0);e.end(u===l.byteLength?l:l.subarray(0,u))}else{let l=0,u=Buffer.allocUnsafe(c);for(;l<o.size;){let f=Ir.readSync(i,u,0,c,l);if(f===0)break;l+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Ir.closeSync(i)}catch{}}},Hw=(t,e)=>{let r=new Pi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("end",c),Ir.stat(o,(u,f)=>{if(u)l(u);else{let x=new Bc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Cr=Oi(Uw,Hw,t=>new Pi(t),t=>new Pi(t),(t,e)=>{e?.length&&ff(t,e),t.noResume||zw(t)}),hf=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:qw,parse:Pu}=Gw,Hc=t=>{let e="",r=Pu(t);for(;qw(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Pu(t)}return[e,t]},so=["|","<",">","?",":"],Gc=so.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),jw=new Map(so.map((t,e)=>[t,Gc[e]])),Kw=new Map(Gc.map((t,e)=>[t,so[e]])),Ou=t=>so.reduce((e,r)=>e.split(r).join(jw.get(r)),t),Ww=t=>Gc.reduce((e,r)=>e.split(r).join(Kw.get(r)),t),xf=(t,e)=>e?(t=ee(t).replace(/^\.(\/|$)/,""),Ii(e)+"/"+t):ee(t),$w=16*1024*1024,Lu=Symbol("process"),Nu=Symbol("file"),Mu=Symbol("directory"),yc=Symbol("symlink"),Bu=Symbol("hardlink"),mi=Symbol("header"),qs=Symbol("read"),Ec=Symbol("lstat"),js=Symbol("onlstat"),bc=Symbol("onread"),vc=Symbol("onreadlink"),Sc=Symbol("openfile"),Ic=Symbol("onopenfile"),En=Symbol("close"),Qs=Symbol("mode"),Ac=Symbol("awaitDrain"),ac=Symbol("ondrain"),Pt=Symbol("prefix"),pf=class extends Vn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Fc(e);super(),this.path=ee(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||$w,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=ee(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?ee(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,l]=Hc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=Ww(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ee(r.absolute||Du.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[js](o):this[Ec]()}warn(t,e,r={}){return io(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Ec](){Dt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[js](e)})}[js](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Zw(t),this.emit("stat",t),this[Lu]()}[Lu](){switch(this.type){case"File":return this[Nu]();case"Directory":return this[Mu]();case"SymbolicLink":return this[yc]();default:return this.end()}}[Qs](t){return hf(t,this.type==="Directory",this.portable)}[Pt](t){return xf(t,this.prefix)}[mi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new $n({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this[Qs](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new Ys({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Mu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[mi](),this.end()}[yc](){Dt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[vc](e)})}[vc](t){this.linkpath=ee(t),this[mi](),this.end()}[Bu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ee(Du.relative(this.cwd,t)),this.stat.size=0,this[mi](),this.end()}[Nu](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[Bu](e);this.linkCache.set(t,this.absolute)}if(this[mi](),this.stat.size===0)return this.end();this[Sc]()}[Sc](){Dt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ic](e)})}[Ic](t){if(this.fd=t,this.#e)return this[En]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[qs]()}[qs](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Dt.read(t,e,r,i,o,(c,l)=>{if(c)return this[En](()=>this.emit("error",c));this[bc](l)})}[En](t=()=>{}){this.fd!==void 0&&Dt.close(this.fd,t)}[bc](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[En](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[En](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[ac]():this[Ac](()=>this[ac]())}[Ac](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[ac](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[En](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[qs]()}},Vw=class extends pf{sync=!0;[Ec](){this[js](Dt.lstatSync(this.absolute))}[yc](){this[vc](Dt.readlinkSync(this.absolute))}[Sc](){this[Ic](Dt.openSync(this.absolute,"r"))}[qs](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let l=Dt.readSync(e,r,i,o,c);this[bc](l),t=!1}finally{if(t)try{this[En](()=>{})}catch{}}}[Ac](t){t()}[En](t=()=>{}){this.fd!==void 0&&Dt.closeSync(this.fd),t()}},Jw=class extends Vn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return io(this,t,e,r)}constructor(t,e={}){let r=Fc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=ee(t.path),this.mode=t.mode!==void 0?this[Qs](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?ee(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[l,u]=Hc(this.path);l&&typeof u=="string"&&(this.path=u,o=l)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new $n({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new Ys({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Pt](t){return xf(t,this.prefix)}[Qs](t){return hf(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},Zw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",Yw=class Ar{tail;head;length=0;static create(e=[]){return new Ar(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)Qw(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)e_(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new Ar;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new Ar;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Ar;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Ar;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let l=0;o&&l<e;l++)o=o.next;let c=[];for(let l=0;o&&l<r;l++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let l of i)o=Xw(this,o,l);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=r,this.tail=e,this}};function Xw(t,e,r){let i=e,o=e?e.next:t.head,c=new qc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function Qw(t,e){t.tail=new qc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function e_(t,e){t.head=new qc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var qc=class{list;next;prev;value;constructor(t,e,r,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},zu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Uu=Buffer.alloc(1024),Ks=Symbol("onStat"),wi=Symbol("ended"),wt=Symbol("queue"),_i=Symbol("queue"),mn=Symbol("current"),qn=Symbol("process"),yi=Symbol("processing"),Fs=Symbol("processJob"),_t=Symbol("jobs"),cc=Symbol("jobDone"),Ws=Symbol("addFSEntry"),Hu=Symbol("addTarEntry"),kc=Symbol("stat"),Tc=Symbol("readdir"),$s=Symbol("onreaddir"),Vs=Symbol("pipe"),Gu=Symbol("entry"),dc=Symbol("entryOpt"),Js=Symbol("writeEntryClass"),gf=Symbol("write"),lc=Symbol("ondrain"),oo=class extends Vn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Js];onWriteEntry;[wt];[_i]=new Map;[_t]=0;[yi]=!1;[wi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=ee(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[Js]=pf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new cw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new lw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new fw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[lc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[lc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[wt]=new Yw,this[_t]=0,this.jobs=Number(t.jobs)||4,this[yi]=!1,this[wi]=!1}[gf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[wi]=!0,this[qn](),r&&r(),this}write(t){if(this[wi])throw new Error("write after end");return t instanceof uf?this[Hu](t):this[Ws](t),this.flowing}[Hu](t){let e=ee(Fu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new zu(t.path,e);r.entry=new Jw(t,this[dc](r)),r.entry.on("end",()=>this[cc](r)),this[_t]+=1,this[wt].push(r)}this[qn]()}[Ws](t){let e=ee(Fu.resolve(this.cwd,t));this[wt].push(new zu(t,e)),this[qn]()}[kc](t){t.pending=!0,this[_t]+=1;let e=this.follow?"stat":"lstat";Xs[e](t.absolute,(r,i)=>{t.pending=!1,this[_t]-=1,r?this.emit("error",r):this[Ks](t,i)})}[Ks](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[mn])this[Fs](t);else{let r=`${e.dev}:${e.ino}`,i=this[_i].get(r);i?i.push(t):this[_i].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[qn]()}[Tc](t){t.pending=!0,this[_t]+=1,Xs.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[_t]-=1,e)return this.emit("error",e);this[$s](t,r)})}[$s](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[qn]()}[qn](){if(!this[yi]){this[yi]=!0;for(let t=this[wt].head;t&&this[_t]<this.jobs;t=t.next)if(this[Fs](t.value),t.value.ignore){let e=t.next;this[wt].removeNode(t),t.next=e}this[yi]=!1,this[wi]&&this[wt].length===0&&this[_t]===0&&(this.zip?this.zip.end(Uu):(super.write(Uu),super.end()))}}get[mn](){return this[wt]&&this[wt].head&&this[wt].head.value}[cc](t){this[wt].shift(),this[_t]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[_i].get(r);if(i){this[_i].delete(r);for(let o of i)o.pending=!1,this[Fs](o)}}this[qn]()}[Fs](t){if(t.pending&&t.pendingLink&&t===this[mn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[mn]&&!t.piped&&this[Vs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Ks](t,e):this[kc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[$s](t,e):this[Tc](t),!t.readdir)return}if(t.entry=this[Gu](t),!t.entry){t.ignore=!0;return}t===this[mn]&&!t.piped&&this[Vs](t)}}}[dc](t){return{onwarn:(e,r,i)=>this.warn(e,r,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[Gu](t){this[_t]+=1;try{return new this[Js](t.path,this[dc](t)).on("end",()=>this[cc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[lc](){this[mn]&&this[mn].entry&&this[mn].entry.resume()}[Vs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ws](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){io(this,t,e,r)}},jc=class extends oo{sync=!0;constructor(t){super(t),this[Js]=Vw}pause(){}resume(){}[kc](t){let e=this.follow?"statSync":"lstatSync";this[Ks](t,Xs[e](t.absolute))}[Tc](t){this[$s](t,Xs.readdirSync(t.absolute))}[Vs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ws](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[gf](i)})}},t_=(t,e)=>{let r=new jc(t),i=new nf(t.file,{mode:t.mode||438});r.pipe(i),mf(r,e)},n_=(t,e)=>{let r=new oo(t),i=new no(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((c,l)=>{i.on("error",l),i.on("close",c),r.on("error",l)});return wf(r,e).catch(c=>r.emit("error",c)),o},mf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:rf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},wf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:rf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},r_=(t,e)=>{let r=new jc(t);return mf(r,e),r},i_=(t,e)=>{let r=new oo(t);return wf(r,e).catch(i=>r.emit("error",i)),r},q2=Oi(t_,n_,r_,i_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),o_=process.env.__FAKE_PLATFORM__||process.platform,bf=o_==="win32",{O_CREAT:vf,O_NOFOLLOW:qu,O_TRUNC:Sf,O_WRONLY:If}=Ef.constants,Af=Number(process.env.__FAKE_FS_O_FILENAME__)||Ef.constants.UV_FS_O_FILEMAP||0,a_=bf&&!!Af,c_=512*1024,d_=Af|Sf|vf|If,ju=!bf&&typeof qu=="number"?qu|Sf|vf|If:null,kf=ju!==null?()=>ju:a_?t=>t<c_?d_:"w":()=>"w",Cc=(t,e,r)=>{try{return ao.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},eo=(t,e,r,i)=>{ao.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},l_=(t,e,r,i,o)=>{if(e.isDirectory())Tf(Ai.resolve(t,e.name),r,i,c=>{if(c)return o(c);let l=Ai.resolve(t,e.name);eo(l,r,i,o)});else{let c=Ai.resolve(t,e.name);eo(c,r,i,o)}},Tf=(t,e,r,i)=>{ao.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return eo(t,e,r,i);let l=c.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--l===0)return eo(t,e,r,i)}};for(let x of c)l_(t,x,e,r,f)})},u_=(t,e,r,i)=>{e.isDirectory()&&Cf(Ai.resolve(t,e.name),r,i),Cc(Ai.resolve(t,e.name),r,i)},Cf=(t,e,r)=>{let i;try{i=ao.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Cc(t,e,r);throw c}for(let o of i)u_(t,o,e,r);return Cc(t,e,r)},Rf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},co=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},h_=(t,e)=>{at.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Rf(t,r?.code||"ENOTDIR")),e(r)})},x_=(t,e,r)=>{t=ee(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,l=e.uid,u=e.gid,f=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),x=e.preserve,g=e.unlink,y=ee(e.cwd),S=(v,I)=>{v?r(v):I&&f?Tf(I,l,u,A=>S(A)):c?at.chmod(t,o,r):r()};if(t===y)return h_(t,S);if(x)return f_.mkdir(t,{mode:o,recursive:!0}).then(v=>S(null,v??void 0),S);let _=ee(to.relative(y,t)).split("/");Rc(y,_,o,g,y,void 0,S)},Rc=(t,e,r,i,o,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),f=ee(to.resolve(t+"/"+u));at.mkdir(f,r,Df(f,e,r,i,o,c,l))},Df=(t,e,r,i,o,c,l)=>u=>{u?at.lstat(t,(f,x)=>{if(f)f.path=f.path&&ee(f.path),l(f);else if(x.isDirectory())Rc(t,e,r,i,o,c,l);else if(i)at.unlink(t,g=>{if(g)return l(g);at.mkdir(t,r,Df(t,e,r,i,o,c,l))});else{if(x.isSymbolicLink())return l(new co(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,Rc(t,e,r,i,o,c,l))},p_=t=>{let e=!1,r;try{e=at.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Rf(t,r??"ENOTDIR")}},g_=(t,e)=>{t=ee(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,l=e.gid,u=typeof c=="number"&&typeof l=="number"&&(c!==e.processUid||l!==e.processGid),f=e.preserve,x=e.unlink,g=ee(e.cwd),y=v=>{v&&u&&Cf(v,c,l),o&&at.chmodSync(t,i)};if(t===g)return p_(g),y();if(f)return y(at.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=ee(to.relative(g,t)).split("/"),_;for(let v=S.shift(),I=g;v&&(I+="/"+v);v=S.shift()){I=ee(to.resolve(I));try{at.mkdirSync(I,i),_=_||I}catch{let A=at.lstatSync(I);if(A.isDirectory())continue;if(x){at.unlinkSync(I),at.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new co(I,I+"/"+S.join("/"))}}return y(_)},uc=Object.create(null),Ku=1e4,yr=new Set,m_=t=>{yr.has(t)?yr.delete(t):uc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=uc[t],r=yr.size-Ku;if(r>Ku/10){for(let i of yr)if(yr.delete(i),delete uc[i],--r<=0)break}return e},w_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,__=w_==="win32",y_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Pf(i,r)),e.push(r||"/"),e},[]),E_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=__?["win32 parallelization disabled"]:t.map(i=>Ii(Pf(m_(i))));let r=new Set(t.map(i=>y_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let l=this.#e.get(c);if(!l||l?.[0]!==t)continue;let u=l[1];if(!u){this.#e.delete(c);continue}if(l.shift(),typeof u=="function")o.add(u);else for(let f of u)o.add(f)}for(let c of i){let l=this.#e.get(c),u=l?.[0];if(!(!l||!(u instanceof Set)))if(u.size===1&&l.length===1){this.#e.delete(c);continue}else if(u.size===1){l.shift();let f=l[0];typeof f=="function"&&o.add(f)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},b_=()=>process.umask(),Wu=Symbol("onEntry"),Dc=Symbol("checkFs"),$u=Symbol("checkFs2"),Pc=Symbol("isReusable"),ut=Symbol("makeFs"),Oc=Symbol("file"),Lc=Symbol("directory"),Zs=Symbol("link"),Vu=Symbol("symlink"),Ju=Symbol("hardlink"),vi=Symbol("ensureNoSymlink"),Zu=Symbol("unsupported"),Yu=Symbol("checkPath"),fc=Symbol("stripAbsolutePath"),bn=Symbol("mkdir"),qe=Symbol("onError"),zs=Symbol("pending"),Xu=Symbol("pend"),Er=Symbol("unpend"),hc=Symbol("ended"),xc=Symbol("maybeClose"),Nc=Symbol("skip"),ki=Symbol("doChown"),Ti=Symbol("uid"),Ci=Symbol("gid"),Ri=Symbol("checkedCwd"),v_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Di=v_==="win32",S_=1024,I_=(t,e)=>{if(!Di)return ie.unlink(t,e);let r=t+".DELETE."+yf(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},A_=t=>{if(!Di)return ie.unlinkSync(t);let e=t+".DELETE."+yf(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},Qu=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Kc=class extends Pi{[hc]=!1;[Ri]=!1;[zs]=0;reservations=new E_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[hc]=!0,this[xc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:S_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Di,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ee(Be.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:b_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Wu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[xc](){this[hc]&&this[zs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[fc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Hc(r),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Di&&/^[a-z]:\.\.$/i.test(l[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Be.posix.dirname(t.path),f=Be.posix.normalize(Be.posix.join(u,l.join("/")));if(f.startsWith("../")||f==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[Yu](t){let e=ee(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=ee(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[fc](t,"path")||!this[fc](t,"linkpath"))return!1;if(t.absolute=Be.isAbsolute(t.path)?ee(Be.resolve(t.path)):ee(Be.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:ee(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Be.win32.parse(String(t.absolute));t.absolute=i+Ou(String(t.absolute).slice(i.length));let{root:o}=Be.win32.parse(t.path);t.path=o+Ou(t.path.slice(o.length))}return!0}[Wu](t){if(!this[Yu](t))return t.resume();switch(s_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Dc](t);default:return this[Zu](t)}}[qe](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Er](),e.resume())}[bn](t,e,r){x_(ee(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[ki](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ti](t){return Qu(this.uid,t.uid,this.processUid)}[Ci](t){return Qu(this.gid,t.gid,this.processGid)}[Oc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new no(String(t.absolute),{flags:kf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[qe](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[qe](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,f=>{f?this[qe](f,t):this[Er](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,g=t.mtime;ie.futimes(f,x,g,y=>y?ie.utimes(u,x,g,S=>c(S&&y)):c())}if(typeof f=="number"&&this[ki](t)){o++;let x=this[Ti](t),g=this[Ci](t);typeof x=="number"&&typeof g=="number"&&ie.fchown(f,x,g,y=>y?ie.chown(u,x,g,S=>c(S&&y)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[qe](u,t),e()}),t.pipe(l)),l.pipe(i)}[Lc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[bn](String(t.absolute),r,i=>{if(i){this[qe](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[Er](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[ki](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ti](t)),Number(this[Ci](t)),c)),c()})}[Zu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Vu](t,e){let r=ee(Be.relative(this.cwd,Be.resolve(Be.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[vi](t,this.cwd,r,()=>this[Zs](t,String(t.linkpath),"symlink",e),i=>{this[qe](i,t),e()})}[Ju](t,e){let r=ee(Be.resolve(this.cwd,String(t.linkpath))),i=ee(String(t.linkpath)).split("/");this[vi](t,this.cwd,i,()=>this[Zs](t,r,"link",e),o=>{this[qe](o,t),e()})}[vi](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let l=Be.resolve(e,c);ie.lstat(l,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new co(l,Be.resolve(l,r.join("/"))));this[vi](t,l,r,i,o)})}[Xu](){this[zs]++}[Er](){this[zs]--,this[xc]()}[Nc](t){this[Er](),t.resume()}[Pc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Di}[Dc](t){this[Xu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[$u](t,r))}[$u](t,e){let r=l=>{e(l)},i=()=>{this[bn](this.cwd,this.dmode,l=>{if(l){this[qe](l,t),r();return}this[Ri]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let l=ee(Be.dirname(String(t.absolute)));if(l!==this.cwd)return this[bn](l,this.dmode,u=>{if(u){this[qe](u,t),r();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Nc](t),r();return}if(l||this[Pc](t,u))return this[ut](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[ut](g??null,t,r);return f?ie.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),f=>this[ut](f??null,t,r))}if(t.absolute===this.cwd)return this[ut](null,t,r);I_(String(t.absolute),f=>this[ut](f??null,t,r))})};this[Ri]?o():i()}[ut](t,e,r){if(t){this[qe](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Oc](e,r);case"Link":return this[Ju](e,r);case"SymbolicLink":return this[Vu](e,r);case"Directory":case"GNUDumpDir":return this[Lc](e,r)}}[Zs](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[qe](o,t):(this[Er](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},Of=class extends Kc{sync=!0;[ut](t,e){return super[ut](t,e,()=>{})}[Dc](t){if(!this[Ri]){let o=this[bn](this.cwd,this.dmode);if(o)return this[qe](o,t);this[Ri]=!0}if(t.absolute!==this.cwd){let o=ee(Be.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[bn](o,this.dmode);if(c)return this[qe](c,t)}}let[e,r]=Ei(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Nc](t);if(e||this[Pc](t,r))return this[ut](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[l]=c?Ei(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ut](l,t)}let[o]=Ei(()=>ie.rmdirSync(String(t.absolute)));this[ut](o,t)}let[i]=t.absolute===this.cwd?[]:Ei(()=>A_(String(t.absolute)));this[ut](i,t)}[Oc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{ie.closeSync(o)}catch(f){u=f}(l||u)&&this[qe](l||u,t),e()},o;try{o=ie.openSync(String(t.absolute),kf(t.size),r)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[qe](l,t)),t.pipe(c)),c.on("data",l=>{try{ie.writeSync(o,l,0,l.length)}catch(u){i(u)}}),c.on("end",()=>{let l=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{ie.futimesSync(o,u,f)}catch(x){try{ie.utimesSync(String(t.absolute),u,f)}catch{l=x}}}if(this[ki](t)){let u=this[Ti](t),f=this[Ci](t);try{ie.fchownSync(o,Number(u),Number(f))}catch(x){try{ie.chownSync(String(t.absolute),Number(u),Number(f))}catch{l=l||x}}}i(l)})}[Lc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[bn](String(t.absolute),r);if(i){this[qe](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ki](t))try{ie.chownSync(String(t.absolute),Number(this[Ti](t)),Number(this[Ci](t)))}catch{}e(),t.resume()}[bn](t,e){try{return g_(ee(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[vi](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let l of r){c=Be.resolve(c,l);let[u,f]=Ei(()=>ie.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new co(c,Be.resolve(e,r.join("/"))))}i()}[Zs](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[qe](c,t)}}},k_=t=>{let e=new Of(t),r=t.file,i=_f.statSync(r),o=t.maxReadSize||16*1024*1024;new $m(r,{readSize:o,size:i.size}).pipe(e)},T_=(t,e)=>{let r=new Kc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("close",c),_f.stat(o,(u,f)=>{if(u)l(u);else{let x=new Bc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Lf=Oi(k_,T_,t=>new Of(t),t=>new Kc(t),(t,e)=>{e?.length&&ff(t,e)}),C_=(t,e)=>{let r=new jc(t),i=!0,o,c;try{try{o=ot.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=ot.openSync(t.file,"w+");else throw f}let l=ot.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<l.size;c+=512){for(let g=0,y=0;g<512;g+=y){if(y=ot.readSync(o,u,g,u.length-g,c+g),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!y)break e}let f=new $n(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(c+x+512>l.size)break;c+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,R_(t,r,c,o,e)}finally{if(i)try{ot.closeSync(o)}catch{}}},R_=(t,e,r,i,o)=>{let c=new nf(t.file,{fd:i,start:r});e.pipe(c),P_(e,o)},D_=(t,e)=>{e=Array.from(e);let r=new oo(t),i=(o,c,l)=>{let u=(S,_)=>{S?ot.close(o,v=>l(S)):l(null,_)},f=0;if(c===0)return u(null,0);let x=0,g=Buffer.alloc(512),y=(S,_)=>{if(S||_===void 0)return u(S);if(x+=_,x<512&&_)return ot.read(o,g,x,g.length-x,f+x,y);if(f===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let v=new $n(g);if(!v.cksumValid)return u(null,f);let I=512*Math.ceil((v.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,ot.read(o,g,0,512,f,y)};ot.read(o,g,0,512,f,y)};return new Promise((o,c)=>{r.on("error",c);let l="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&l==="r+")return l="w+",ot.open(t.file,l,u);if(f||!x)return c(f);ot.fstat(x,(g,y)=>{if(g)return ot.close(x,()=>c(g));i(x,y.size,(S,_)=>{if(S)return c(S);let v=new no(t.file,{fd:x,start:_});r.pipe(v),v.on("error",c),v.on("close",o),O_(r,e)})})};ot.open(t.file,l,u)})},P_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:Nf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},O_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:Nf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},bi=Oi(C_,D_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!tw(t))throw new TypeError("file is required");if(t.gzip||t.brotli||t.zstd||t.file.endsWith(".br")||t.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!e?.length)throw new TypeError("no paths specified to add/replace")}),iA=Oi(bi.syncFile,bi.asyncFile,bi.syncNoFile,bi.asyncNoFile,(t,e=[])=>{bi.validate?.(t,e),L_(t)}),L_=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,i)=>e(r,i)&&!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0)):(r,i)=>!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0))};un();var ft={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function lo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Mf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function uo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Bf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Ff(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Jn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Vt();We();ne();Re();We();function Rr(t,e){if(lo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Li(t){return t.startsWith("http://")||t.startsWith("https://")}function Dr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as JA}from"node:fs";import{dirname as YA,join as XA}from"node:path";import{fileURLToPath as ek}from"node:url";var Lt="0.2.1-alpha.2";We();ne();var fo="1008033",Gf="1289";var qf="pbbp2",jf="https://www.coze.cn",Kf="/api/coze_claw/resource/get_frontier_key",G_="https://www.coze.cn",q_="wss://frontier.coze.cn";function Pr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??G_}function Wf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??q_}function In(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Mi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Ni=H("handshake");async function Wc(t){let e=Pr(t.endpoint),r=t.timeoutMs??1e4,i=`${Dr(e)}${Kf}?aid=${encodeURIComponent(fo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...In(t.ppeOverride)},c=new AbortController,l=setTimeout(()=>c.abort(),r);Ni.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),f=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let v=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${v.slice(0,200)}`)}let g=await u.json();if(g.code!==void 0&&g.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${g.code} msg=${g.msg??"-"} logid=${f}`);let y=g.data??{},S=typeof y.access_key=="string"&&y.access_key||typeof y.accessKey=="string"&&y.accessKey||void 0,_=typeof y.device_id=="string"&&y.device_id||typeof y.deviceId=="string"&&y.deviceId||void 0;if(!S||!_){let v=JSON.stringify(g).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${v}`)}return Ni.info("handshake ok",{remoteDeviceId:_,logid:f,traceId:x}),{accessKey:S,deviceId:_}}catch(u){if(u instanceof k)throw Ni.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Ni.warn("handshake timeout",{base:e,timeoutMs:r}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let f=u.cause;throw Ni.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}var $c=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",bt="auto",$f=15e4;function Vf(t){return{model:Vc(t.model)??bt,...t.modelToken?{modelToken:t.modelToken}:{}}}function Jf(t){return!t||t===bt}var j_=new Set(["auto","\u81EA\u52A8"]);function Vc(t){let e=t?.trim();if(e)return j_.has(e.toLowerCase())?bt:e}function Zf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=$c,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||bt;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else Jf(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Yf(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||bt}"`):Jf(t.model)||e.push("-c",`model="${t.model}"`),t.modelToken){e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${$c}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"');let r=t.modelInfo?.contextWindow??$f;e.push("-c",`model_context_window=${r}`)}return e}function Xf(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function Jc(t,e){let{ttEnv:r,usePpe:i}=Mi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function Qf(t,e,r){if(!t.modelToken)return{};let i=Jc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,l])=>`${c}:${l}`).join(`
92
+ `)}}function Zc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function e0(t,e,r){if(!t.modelToken)return null;let i=t.model||bt,o=Jc(e,r),c=["text"];t.modelInfo?.capabilities?.image===!0&&c.push("image");let l={baseUrl:`${$c}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:i,name:i,reasoning:!1,input:c,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??$f,maxTokens:8192,api:"openai-completions"}]};return Object.keys(o).length>0&&(l.headers=o),l}function t0(t,e,r){if(!t.modelToken)return[];let i=Jc(e,r),o=[];for(let[c,l]of Object.entries(i))o.push("-c",`model_providers.coze.http_headers.${c}="${l}"`);return o}var pe=H("agent-handlers"),r0=5*1024*1024,V_=1,J_=6,Z_=new Set(["node_modules",".git",".coze","dist","build",".next"]),Y_=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,X_=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Q_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function ey(t){let e=t?.trim();return e?Q_.test(e)||X_.test(e)?e:(pe.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function ty(t){return new Promise((e,r)=>{let i=it("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=l=>{o||(o=!0,l?r(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",l=>c(l))})}var xo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Jn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ze(r).workspace,c=i?.skills??[],l=[],u=new Set;for(let f of c){let x=Ve(o,f.relPath,"SKILL.md");await n0(x).then(y=>y.isFile()).catch(()=>!1)&&(l.push(sy(f)),u.add(f.relPath))}if(e.scanLocal){let f=i?.framework??"claude-code",x=await ny(r,o,f);for(let g of x)u.has(g.relPath)||(u.add(g.relPath),l.push(g.skill))}return{skills:l}}async addSkills(e){e._meta;let r=Jn(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],l=new Map(c.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await po({agentId:r,workspace:i.workspace,framework:i.framework,skill:f});go(c,l,x),u.push(f)}return await ai(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Jn(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],l=[];for(let u of c){if(!o.has(u.skillId)){l.push(u);continue}let f=Ve(i.workspace,u.relPath);await Qc(f,{recursive:!0,force:!0}),pe.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await ai(r,l),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Jn(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");pe.info("_agent/publishSkill start",{agentId:r,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(r),o=i?.workspace??Ze(r).workspace,c=i?.framework??"claude-code",l=d0(e.skillName),u=Ve(sd(c),l),f=Ve(o,u),x=Ve(f,"SKILL.md");if(!await n0(x).then(T=>T.isFile()).catch(()=>!1))throw new k("SKILL_NOT_FOUND",`skill not found locally: ${e.skillName} (${u})`);let y=new id.default;y.addLocalFolder(f,l);let S=y.toBuffer();if(S.length>i0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${S.length} bytes exceeds limit ${i0}`);let _=await ho(x,{encoding:"utf8"}).then(T=>u0(T).description).catch(()=>{}),v={};this.opts.publishSkillToMarketplace?v=await this.opts.publishSkillToMarketplace({zip:S,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,..._?{description:_}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):pe.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let I=v.version??"v1.0",A=v.skillId??e.skillId??l0(r,u);if(i){let T=i.skills??[],D=T.find(E=>E.relPath===u);D?(D.version=I,D.skillId=A):T.push({skillId:A,skillName:e.skillName,relPath:u,version:I,installedAt:Date.now(),..._?{description:_}:{}}),await ai(r,T)}return pe.info("skill published",{agentId:r,skillName:e.skillName,relPath:u,zipBytes:S.length,skillId:A,version:I}),{ok:!0,skillId:A,version:I}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let l=c.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,pe.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l});continue}let f=c.downstream;c.downstream=void 0,pe.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l}),f.stop(r).catch(x=>pe.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return pe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await De(r);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return pe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await hr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw pe.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await ze(i),pe.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await De(r))throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Li(e.registry)&&o.push(`--registry=${e.registry}`);let c=ey(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&Y_.test(l)&&o.push("--env",l);let u=await ty(o);return pe.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await De(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await ze(i),pe.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(pe.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST",`${ft.DELETE}: missing agentId`);let i=await De(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let l=Ze(r);return c==="cloud"?await Qc(l.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await ze(i)),pe.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Rr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Vc(e.model)??bt,i=await De(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await ze(i),pe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return pe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o).catch(l=>pe.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(l)}));let c=[];for(let[l,u]of o.allSessionQueues())c.push(u.enqueue(async()=>{let f=o.sessions.get(l);f?.downstream&&(await f.downstream.stop(`switchModel: ${r}`).catch(()=>{}),f.downstream=void 0)}));return await Promise.all(c),pe.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:c.length}),{ok:!0}}async resetAgent(e){if(Rr(e._meta,ft.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ft.RESET),await this.runDetailSync(e.agentId,ft.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),pe.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,l]of i.sessions)o.set(c,{modelToken:l.modelToken,tokenGeneratedAt:l.tokenGeneratedAt});await oi(e,o)}async clearPersistedAcpSessionIds(e){let r=await De(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await ze(r)}async repairAgent(e){if(Rr(e._meta,ft.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${ft.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){pe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ft.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){pe.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){pe.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Rr(e._meta,"_agent/getFileTree");let r=e._meta,i=Jn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(o,c),u=await Yc(l).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await si(l,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=my(e.depth);return u.isDirectory()?{tree:await gy(o,l,c,f)}:{tree:[{name:wy(c),path:x0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Rr(e._meta,"_agent/getFileContent");let r=Jn(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await Yc(o).catch(()=>null);if(!c||!c.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await si(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>r0)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${r0})`);let l=await ho(o);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:c.size}:{content:l.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await De(e).catch(()=>null))?.workspace??Ze(e).workspace}safeJoin(e,r){let i=td(e,r||"."),o=rd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${o0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return De(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function d0(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new k("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new k("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function sd(t){return t==="claude-code"?Ve(".claude","skills"):Ve(".agents","skills")}function l0(t,e){return(K_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function u0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
+ ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
94
+ `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let l=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[l]=u)}return i}async function ny(t,e,r){let i=sd(r),o=Ve(e,i),c=await s0(o,{withFileTypes:!0}).catch(()=>null);if(!c)return[];let l=[];for(let u of c){if(!u.isDirectory())continue;let f=u.name,x=Ve(i,f),g=Ve(o,f,"SKILL.md"),y=await ho(g,{encoding:"utf8"}).catch(()=>null);if(y===null)continue;let S=u0(y);l.push({relPath:x,skill:{skillId:l0(t,x),skillName:S.name||f,...S.description?{description:S.description}:{}}})}return l}var ry=3e4,iy=50*1024*1024,i0=10*1024*1024,Or=3e4;async function po(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let c=typeof o.content=="string"&&o.content.length>0,l=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!l)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=d0(o.skillName),f=sd(i),x=Ve(f,u),g=Ve(r,x);if(await Xc(g,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");Bi(S.length),await ed(Ve(g,"SKILL.md"),S,"utf8")}else{let S=await ay(o.downloadUrl);dy(S)?await hy(S,g):ly(S)?await uy(S,g):await ed(Ve(g,"SKILL.md"),S.toString("utf8"),"utf8")}let y={skillId:o.skillId,skillName:o.skillName,relPath:x,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return pe.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:c?"content":"downloadUrl"}),y}function go(t,e,r){let i=e.get(r.skillId);if(i!==void 0){t[i]=r;return}e.set(r.skillId,t.length),t.push(r)}function sy(t){return{skillId:t.skillId,skillName:t.skillName,...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}function oy(t){return{skillId:t.skillId,skillName:t.skillName,...t.downloadUrl?{downloadUrl:t.downloadUrl}:{},...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function f0(t,e){let r=await De(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Lt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],l=new Map(c.map((g,y)=>[g.skillId,y])),u=c.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"noop",count:0};let f=0,x=0;for(let g of u)try{await Qc(Ve(r.workspace,g.relPath),{recursive:!0,force:!0});let y=await po({agentId:t,workspace:r.workspace,framework:r.framework,skill:oy(g)});go(c,l,y),f+=1}catch(y){x+=1,pe.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(y)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await ze(r,e),pe.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function ay(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Bi(e);let r=cy(t);return Bi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await ho(e);return Bi(r.length),r}if(Li(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),ry);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Bi(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Bi(t){if(t>iy)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function cy(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function dy(t){return t.length>=2&&t[0]===31&&t[1]===139}function ly(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],r=t[3];return e===3&&r===4||e===5&&r===6}function nd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function uy(t,e){let r,i;try{r=new id.default(t),i=r.getEntries()}catch(l){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${l.message}`,{cause:l})}for(let l of i){let u=l.entryName;if(!u||nd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=l.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=fy(i),c=td(e);for(let l of i){if(nd(l.entryName))continue;let u=l.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=td(e,u),x=rd(c,f);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await Xc(f,{recursive:!0});continue}await Xc(W_(f),{recursive:!0});let g;try{g=l.getData()}catch(y){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${y.message}`,{cause:y})}await ed(f,g)}}function fy(t){let e;for(let r of t){let i=r.entryName;if(!i||nd(i))continue;let o=i.indexOf("/");if(o<=0)return;let c=i.slice(0,o+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function hy(t,e){await xy(t);let r=Lf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await c0(a0.from(t),r)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function xy(t){let e=[],r=Cr({onReadEntry:c=>{let l=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${l.slice(0,100)}`);return}if(l.startsWith("/")||l.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(l)){e.push(`tar entry absolute path: ${l}`);return}l.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${l}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await c0(a0.from(t),r)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var py=5e3;async function gy(t,e,r,i){return h0(t,e,r,i,{count:0})}async function h0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await s0(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if(Z_.has(u.name)||u.isSymbolicLink())continue;if(o.count>=py){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=Ve(e,u.name),x=$_(Ve(r,u.name)),g=null;try{g=await Yc(f)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let y={name:u.name,path:x0(rd(t,f)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(y.children=await h0(t,f,x,i-1,o)),l.push(y)}return l.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),l}function my(t){return!t||t<=0?V_:Math.min(t,J_)}function wy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function x0(t){return t.split(o0).join("/")}ne();var An=H("agent-health-reporter"),_y=1e4,yy=3,Fi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??_y,this.livenessFailureThreshold=e.livenessFailureThreshold??yy}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),An.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),An.info("heartbeat stopped"))}async tick(){if(this.inFlight){An.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,An.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let l of this.opts.core.agents.values()){let u=Ey(l);if(!u)continue;let f={agentId:l.agentId,status:u};l.patToken&&(f.patToken=l.patToken),l.accountId&&(f.accountId=l.accountId),r.push(f)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Lt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(l){this.consecutiveFailures+=1,An.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let c=o?.authFailures;if(c&&c.length>0&&(An.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(l=>l.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(l){An.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){An.warn("onTickEnd hook failed",{err:String(r)})}}};function Ey(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}un();import{mkdir as hd,rm as CE,stat as RE}from"node:fs/promises";import{homedir as DE}from"node:os";import{join as j0}from"node:path";on();import{existsSync as Ly}from"node:fs";import{release as Ny}from"node:os";import{basename as My,isAbsolute as By}from"node:path";function zi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Lr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Nr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function kn(t,e){return{jsonrpc:"2.0",id:t,error:e}}We();var mo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},X={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function p0(t){return"method"in t&&"id"in t&&t.id!==void 0}function g0(t){return"method"in t&&!("id"in t)}function wo(t){return!("method"in t)&&"id"in t}var by={AGENT_NOT_FOUND:X.AGENT_NOT_FOUND,AGENT_BUSY:X.AGENT_BUSY,AGENT_DISCONNECTED:X.AGENT_DISCONNECTED,AGENT_TIMEOUT:X.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:X.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:X.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:X.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:X.INTERNAL_ERROR,BRIDGE_INTERNAL:X.INTERNAL_ERROR,IPC_AUTH_FAILED:X.INTERNAL_ERROR,IPC_BAD_REQUEST:X.INVALID_REQUEST,METHOD_NOT_FOUND:X.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:X.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:X.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:X.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:X.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:X.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:X.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:X.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:X.FILE_TOO_LARGE,UNSUPPORTED_MIME:X.UNSUPPORTED_MIME,UPLOAD_FAILED:X.UPLOAD_FAILED,UPSTREAM_NOT_READY:X.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:X.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:X.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:X.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:X.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:X.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:X.SKILL_ZIP_TOO_LARGE};function vy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Ui(t.message)}:typeof t=="string"?Ui(t):typeof t=="object"?Iy(t):t}var Sy=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Ui(t){let e=t;for(let[r,i]of Sy)e=e.replace(r,i);return e}function Iy(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Ui(i):e[r]=i;return e}function Hi(t){if(t instanceof k){let e=vy(t.cause),r={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(r.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(r.reason=e.reason),{code:by[t.code]??X.INTERNAL_ERROR,message:Ui(t.message),data:r}}return{code:X.INTERNAL_ERROR,message:Ui(t instanceof Error?t.message:String(t))}}function m0(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:l,...u}=e;c=u}return new k(r,o,{retriable:e?.retriable??!1,cause:c})}function _0(t){return`${JSON.stringify(t)}
95
+ `}var w0=10*1024*1024,_o=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>w0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${w0} bytes`)}),[]}let r=this.buffer.split(`
96
+ `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(l){this.onError?.({line:c,error:l})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var E0={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission","session/set_mode":"session.setMode",initialize:"initialize"},Fk=Object.fromEntries(Object.entries(E0).map(([t,e])=>[e,t])),Ay={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Mr=class{seq=0;next(e,r){this.seq+=1;let i=E0[e]??ky(e),o=Ay[i]??[],c=[i,String(this.seq)];if(o.length>0){let l=o.map(f=>y0(r?.[f]??"")),u=Ty(l).join(":");u&&c.push(u)}else r&&Object.values(r).some(l=>l)&&c.push(Object.values(r).filter(Boolean).map(l=>y0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function ky(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function y0(t){return t.replace(/[:_\s]+/g,"-")}function Ty(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}ln();import{readFileSync as Cy}from"node:fs";var Ry=384;async function od(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await dn(t.agentEnvFile,r,{mode:Ry})}function Gi(t){try{let e=JSON.parse(Cy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function yo(t,e,r={},i=o=>o){return{...i({...t,...Gi(e)}),...r}}Vt();cr();We();ne();Re();import{execFileSync as Dy,spawnSync as Py}from"node:child_process";function qi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function ji(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Py("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ad=new Set;function b0(t){typeof t=="number"&&t>0&&ad.add(t)}function v0(t){typeof t=="number"&&ad.delete(t)}function S0(){for(let t of ad)ji(t,"SIGKILL")}var Br="coze-bridge-daemon";function I0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return Dy("pgrep",["-U",String(o),"-f",Br],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
97
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function A0(t,e){if(t.length===0)return;let r=e?.killFn??ji,i=e?.isAliveFn??qi,o=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),c=e?.graceMs??3e3,l=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(f=>i(f));u+=l)await o(Math.min(l,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var Oy=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed|\.resolve is not a function/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find module[^\n]*node_modules[\\/]@(agentclientprotocol[\\/]claude-agent-acp|zed-industries[\\/]codex-acp)/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function k0(t,e){if(!e)return null;for(let r of Oy)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function T0(t,e){return k0(t,e)}function C0(t,e){return k0(t,e)}function Fr(t,e,r){return!e&&r.firstUpdateMs>0&&t<r.firstUpdateMs?Math.max(1,r.firstUpdateMs-t):t<r.phase2GateMs?Math.max(1,r.phase2GateMs-t):Math.max(1,r.livenessWindowMs)}function R0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,g=r-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Fr(g,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,l=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=l?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:Fr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Fr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Fr(c,!1,e)}}var D0=Je("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Fy=200,zy=40,Uy=Je("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Hy=Je("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Gy=Je("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),qy=Je("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),jy=Je("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Ky=Je("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),P0=500;function Wy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=P0?t:`${e.slice(0,P0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function $y(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:r}=t;if(typeof r=="string")e.push(r);else if(r&&typeof r=="object")try{e.push(JSON.stringify(r))}catch{}return e.join(" ")}function O0(t){try{return Ly(t)}catch{return}}function Vy(t,e){return{platform:process.platform,osRelease:Ny(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:By(e.command)?O0(e.command):void 0,cwd:e.cwd,cwdExists:O0(e.cwd),envKeys:e.envKeys}}function Jy(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${My(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Nt=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new _o({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Mr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=yo(process.env,this.opts.agentEnvFile??Y().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=it(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,b0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>Fy&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,c)=>{this.stopped=!0,v0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,l=Vy(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:l}),this.failAllPending(new k("AGENT_SPAWN_FAILED",Jy(c,l),{cause:l}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));ji(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||ji(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r){let i={firstUpdateMs:jy,phase2GateMs:Uy,livenessWindowMs:Hy,absoluteMaxMs:Gy,approvalMaxMs:Ky,suspendThresholdMs:qy,...r};return this.call("session/prompt",e,D0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Lr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Nr(e,r))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(kn(e,r))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,r,i=D0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=zi(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let f=r.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,x)=>{let g={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let y=this.now(),S={cfg:o,startedAt:y,lastActivityAt:y,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:y,expectedIntervalMs:Fr(0,!1,o),sessionId:u};g.promptTimeout=S;let _=()=>{let v={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=R0(v,S.cfg,I),T=D=>{S.armedAt=I,S.expectedIntervalMs=D,g.timer=setTimeout(_,D)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};g.timer=setTimeout(_,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(g.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,g);try{this.writeFrame(l)}catch(y){g.timer&&clearTimeout(g.timer),this.pending.delete(c),x(y)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(_0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(wo(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new k("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:Wy(e.result)}),r.resolve(e.result));return}if(g0(e)){if(e.method==="session/update"){let r=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,r))}for(let i of this.updateHandlers)try{Promise.resolve(i(r)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(p0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let l=typeof i.status=="string"?i.status:void 0,u=l==="completed"||l==="failed"||l==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(kn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let r of this.agentRequestHandlers)try{await r(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(kn(e.id,Hi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=m0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=C0(this.framework,$y(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):r}buildExitError(e,r){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(zy).join(`
98
+ `),o=T0(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${r})`,{cause:{code:e,signal:r,stderrTail:i}})}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Zy(t){let e={};for(let[r,i]of Object.entries(t))i!==void 0&&(r.startsWith("CLAUDE")||r==="AI_AGENT"||r==="BAGGAGE"||(e[r]=i));return e}var Eo=class extends Nt{framework="claude-code";constructor(e){let{command:r,args:i}=ii("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return Zy(e)}};on();import{spawn as Yy}from"node:child_process";import{closeSync as Xy,existsSync as M0,mkdirSync as Qy,mkdtempSync as eE,openSync as tE,readFileSync as nE,readSync as rE,readdirSync as iE,rmSync as sE,statSync as oE}from"node:fs";import{homedir as aE,tmpdir as cE}from"node:os";import{join as Ki}from"node:path";Re();var dd=9e4,dE=64*1024,lE=100;function uE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?dd:Math.max(1,Math.floor(e*1e3))}function fE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?dd:Math.max(1,Math.floor(e))}function hE(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[r,i]of Object.entries(t))typeof i=="string"&&(e[r]=i);return Object.keys(e).length>0?e:void 0}function L0(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:dd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let r=typeof e.command=="string"?e.command.trim():"";if(!r)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,o=hE(e.env);return{command:r,timeoutMs:e.timeout_ms===void 0?uE(e.timeout):fE(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function cd(t){if(Array.isArray(t))return t.flatMap(i=>cd(i));if(!t||typeof t!="object"){let i=L0(t);return i?[i]:[]}let e=t;if(e.hooks)return cd(e.hooks);let r=L0(e);return r?[r]:[]}function xE(t){let e=Ki(t,"hooks.json");if(!M0(e))return[];let r=JSON.parse(nE(e,"utf8")),o=r.hooks&&typeof r.hooks=="object"?r.hooks:r;return cd(o.Stop??o.stop)}function pE(t,e){let r=Ki(t,"sessions");if(!M0(r))return;let i=[],o=c=>{let l;try{l=iE(c,{withFileTypes:!0})}catch{return}for(let u of l){let f=Ki(c,u.name);if(u.isDirectory())o(f);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:f,mtimeMs:oE(f).mtimeMs})}catch{}}};o(r),i.sort((c,l)=>l.mtimeMs-c.mtimeMs);for(let c of i.slice(0,lE))if(gE(c.path,e))return c.path;return i[0]?.path}function gE(t,e){let r;try{r=tE(t,"r");let i=Buffer.alloc(dE),o=rE(r,i,0,i.length,0),c=i.subarray(0,o).toString("utf8");return c.includes(JSON.stringify(e))||c.includes(e)}catch{return!1}finally{if(r!==void 0)try{Xy(r)}catch{}}}function mE(t){return Gi(t??Y().agentEnvFile)}function N0(t){let e=t?.trim();return e||void 0}function wE(t){let e=mE(t.agentEnvFile),r=N0(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(r)return r;let i=N0(t.env?.HOME??e.HOME??process.env.HOME)??aE();return Ki(i,".codex")}var bo=class extends Nt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ii("codex",e.command,i),l=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??eE(Ki(cE(),"coze-bridge-codex-home-")):wE(e),u=!!e.isolateCodexHome&&!!l&&!e.codexHomeDir&&e.env?.CODEX_HOME!==l;e.isolateCodexHome&&l&&!u&&Qy(l,{recursive:!0});let f=e.isolateCodexHome&&l?{...e.env??{},CODEX_HOME:l}:e.env,x={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...f?{env:f}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=l,this.cleanupCodexHomeDir=u}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}async sessionPrompt(e){let r=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),r}async runStopHooksBestEffort(e){let r=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!r)return;let i;try{i=xE(r)}catch(l){this.log.warn("codex stop hook load failed",{codexHomeDir:r,err:String(l)});return}if(i.length===0)return;let o=pE(r,e),c=JSON.stringify({hook_event_name:"Stop",session_id:e,...o?{transcript_path:o}:{},trigger:"coze-bridge"});await Promise.all(i.map(async l=>{try{await this.runHookCommand(l,c)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:r,command:l.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,r){return new Promise((i,o)=>{let c=Yy(e.command,{cwd:e.cwd??this.opts.cwd,env:yo(process.env,this.opts.agentEnvFile??Y().agentEnvFile,{...this.opts.env??{},...e.env??{}}),shell:!0,stdio:["pipe","ignore","pipe"]}),l="",u=setTimeout(()=>{c.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);c.stderr?.setEncoding("utf8"),c.stderr?.on("data",f=>{l+=f,l.length>4e3&&(l=l.slice(-4e3))}),c.on("error",f=>{clearTimeout(u),o(f)}),c.on("close",(f,x)=>{if(clearTimeout(u),f===0){i();return}o(new Error(`hook exited code=${f} signal=${x} stderr=${l.slice(-1e3)}`))}),c.stdin.end(`${r}
99
+ `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{sE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};We();var _E=3e4,zr=class extends Nt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let r=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${r}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=r,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},_E))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var B0=["default","acceptEdits","plan","auto","bypassPermissions"],F0=["read-only","auto","full-access"];function Tn(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return B0.includes(e);case"codex":return F0.includes(e);case"openclaw":return!1}}function ld(t){switch(t){case"claude-code":return B0.join("/");case"codex":return F0.join("/");case"openclaw":return""}}ln();We();ne();Re();function ud(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}on();var Cn=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((r,i)=>{this.slots.push({task:e,resolve:r,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let r=await e.task();e.resolve(r)}catch(r){e.reject(r)}}}finally{this.running=!1}}}};var vo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new Cn,this.sessionQueues.set(e,r)),r}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let r=this.sessionQueues.get(e);return!!r&&!r.isDisposed}async dispose(e){this.status="stopped";let r=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(r);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let r=[];for(let[,i]of this.sessions)Wi(i),i.downstream&&(r.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(r),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Wi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Jt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Vt();ne();import{constants as z0}from"node:fs";import{access as yE}from"node:fs/promises";import{delimiter as EE,join as bE}from"node:path";var vt=H("framework-detector"),U0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},vE=[".exe",".cmd",".bat",".ps1"],Zn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??it,access:e.access??yE}}async detect(e){let r=U0[e],i=await this.which(r);if(!i)return vt.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,l]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return l&&(u.defaultAgent=l),u}async detectAll(){let e=await Promise.all(Object.keys(U0).map(async i=>[i,await this.detect(i)])),r={};for(let[i,o]of e)o&&(r[i]=o);return r}async which(e){let r=this.env.pathEnv.split(EE).filter(Boolean),i=this.env.platform==="win32"?["",...vE]:[""];for(let o of r)for(let c of i){let l=bE(o,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?z0.F_OK:z0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return vt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return vt.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return vt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return vt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(l=>l?.isDefault===!0);return c?!c.id||!c.workspace?(vt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(vt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return vt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return vt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||vt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let l=JSON.parse(c[0]);typeof l.gateway?.port=="number"&&(o.port=l.gateway.port),typeof l.service?.runtime?.status=="string"&&(o.runtime=l.service.runtime.status),!i&&typeof l.rpc?.error=="string"&&(o.detail=l.rpc.error)}catch(l){vt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(l)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(IE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,l,u=f=>{c||(c=!0,l&&clearTimeout(l),i(f))};try{let f=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});l=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{o+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},SE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function IE(t){return t.replace(SE,"")}import{homedir as G0}from"node:os";import{join as Io}from"node:path";ln();Vt();cr();We();ne();async function q0(){let t=Io(G0(),".openclaw/openclaw.json");return(await an(t))?.gateway?.auth?.token??""}var Yn=H("openclaw.config"),AE=[0,5e3,5e3],kE=Je("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),H0="models.providers.",So="agents.defaults.models",TE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function fd(t,e){if(!Array.isArray(t))return!1;let r=new Set(t);return e.every(i=>r.has(i))}var Ao=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Cn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??AE,this.cliTimeoutMs=e.cliTimeoutMs??kE,this.openclawDir=e.openclawDir??Io(G0(),".openclaw")}async withRetry(e,r){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(l=>setTimeout(l,c));try{return await r()}catch(l){i=l,Yn.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(l)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=it(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",l=!1,u=x=>{l||(l=!0,clearTimeout(f),x())};o.stderr?.on("data",x=>{c+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?r():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",r])))}catch(i){Yn.warn(`${e} failed (best-effort)`,{configPath:r,err:String(i)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${H0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${H0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${So}[${e}]`,()=>this.runCli(["config","set",So,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${So}[${e}]`,`${So}.${e}`)}ensureAgent(e,r,i){let o=["agents","add",e,"--workspace",r,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}async ensureAcpDeviceScopes(){try{let e=Io(this.openclawDir,"identity","device.json"),i=(await an(e))?.deviceId?.trim();if(!i)return Yn.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Io(this.openclawDir,"devices","paired.json"),c=await an(o),l=c?.[i];if(!c||!l)return Yn.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=[...TE],f=l.tokens?.operator;return fd(l.scopes,u)&&fd(l.approvedScopes,u)&&fd(f?.scopes,u)?(Yn.debug("acp device already has full operator scopes",{deviceId:i}),!1):(l.scopes=[...u],l.approvedScopes=[...u],f&&(f.scopes=[...u]),await dn(o,c,{mode:384}),Yn.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:u}),!0)}catch(e){return Yn.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};var ue=H("agent-manager"),pd="acceptEdits",$0="full-access",V0="read-only";function PE(t){switch(t){case"read-only":return["-c",'sandbox_mode="read-only"',"-c",'approval_policy="on-request"'];case"auto":return["-c",'sandbox_mode="workspace-write"',"-c",'approval_policy="on-failure"'];case"full-access":return["-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"']}}var OE=(t,e,r,i,o,c,l,u,f,x)=>{switch(t){case"claude-code":{let g={...o?{...Zf(o),...Qf(o,l,u)}:{},...f??{},IS_SANDBOX:"1"};return new Eo({cwd:r,env:g,agentId:i})}case"codex":{let g=o?[...Yf(o),...t0(o,l,u)]:[],y=$0;x!==void 0&&(Tn("codex",x)?y=x:ue.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let S=[...g,...PE(y)],_={...o?Xf(o):{},...f??{}},v=!!o;return new bo({cwd:r,agentId:i,...S.length>0?{extraArgs:S}:{},...Object.keys(_).length>0?{env:_}:{},...v?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new zr({command:e,cwd:r,agentId:i,...c?{sessionName:ud(c)}:{}})}};function xd(t){return t==="claude-code"||t==="codex"}function LE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(NE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
99
100
  `)}
100
- `}function mb(t){if(t.includes(`
101
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var wb={path:"",version:"cloud-deployed"},q0="openclaw_gateway_unavailable",_b="openclaw_default_agent_missing";function H0(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 yb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},bb=6e4,Io=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??pb,this.createTimeoutMs=e.createTimeoutMs??bb,this.detectorFactory=e.detectorFactory??(()=>new Zn),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new So({command:n})),this.openclawConfigDir=e.openclawConfigDir??G0(hb(),".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=>{fe.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=G0(e,".env");if(await fb(n).then(c=>c.isFile()).catch(()=>!1)){fe.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let s=gb({...process.env,...od(this.paths.agentEnvFile)});await dn(n,s,{mode:384}),fe.info("openclaw .env bootstrapped",{envFile:n,bytes:s.length}),await this.getOpenclawConfig().restartGateway(),fe.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){if(!e.agentId)throw new T("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new T("IPC_BAD_REQUEST","framework required");let i=await Re(e.agentId,this.paths).catch(()=>null),s=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")fe.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(k=>fe.warn("dispose stale agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else if(s&&c.deployType!=="cloud")fe.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(k=>fe.warn("dispose drifted agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){fe.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let k=await Re(e.agentId,this.paths).catch(()=>null);k&&(k.patToken=e.patToken,await Ue(k,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){fe.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let k=await Re(e.agentId,this.paths).catch(()=>null);k&&(k.modelInfo=e.modelInfo,await Ue(k,this.paths))}return fe.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 T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Ye(e.agentId,this.paths),h=s?"cloud":"local",x=e.framework==="openclaw"&&h==="local",m;x&&!n?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let _=m??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??_??u.workspace,y=new AbortController,v=setTimeout(()=>y.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{s&&ud(e.framework)&&await lr(e.framework,y.signal);let k=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await ld(u.root,{recursive:!0}),await ld(S,{recursive:!0}),await ld(u.logs,{recursive:!0}),k(),x||await hr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await La(S,"cloud"):await La(S,"local",fd)),k();let P=i,b=Kf({model:e.model??P?.model}),D=Lf(e._meta)??P?.accountId,O=e.patToken??P?.patToken,F=h==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new Eo({agentId:e.agentId,framework:e.framework,workspace:S,model:b.model??Lt,deployType:h,...D?{accountId:D}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",P?.sessions){let K=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Z,ae]of Object.entries(P.sessions)){let ce={acpSessionId:ae.acpSessionId,modelToken:ae.modelToken,tokenGeneratedAt:ae.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};K?ae.permissionMode===void 0?(ce.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",fe.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Z,framework:e.framework,fallback:ce.permissionMode})):kn(e.framework,ae.permissionMode)?ce.permissionMode=ae.permissionMode:fe.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Z,framework:e.framework,value:ae.permissionMode}):ae.permissionMode!==void 0&&fe.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Z,framework:e.framework,deployType:h}),ae.cozeGroupId&&(ce.cozeGroupId=ae.cozeGroupId),I.sessions.set(Z,ce)}let te=Object.keys(P.sessions).length;te>0&&fe.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:te})}this.registry.register(I),A=!0;let B={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:b.model};h==="cloud"&&(B.deployType="cloud"),D&&(B.accountId=D),O&&(B.patToken=O),F&&(B.modelInfo=F),P?.skills&&(B.skills=P.skills),P?.agentName&&(B.agentName=P.agentName),P?.description&&(B.description=P.description),B.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Ot,e.framework==="openclaw"&&h==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):fe.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 K=[...B.skills??[]],te=new Map(K.map((ce,R)=>[ce.skillId,R])),Z=await Promise.allSettled(V.map(ce=>po({agentId:e.agentId,workspace:S,framework:e.framework,skill:ce}))),ae=0;for(let[ce,R]of Z.entries()){let U=V[ce];U&&(R.status==="fulfilled"?(go(K,te,R.value),ae++):fe.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(R.reason)}))}ae>0&&(B.skills=K,fe.info("initialSkills installed",{agentId:e.agentId,installed:ae,requested:V.length}))}return await Ue(B,this.paths),fe.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(k){throw fe.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 ub(u.root,{recursive:!0,force:!0}).catch(P=>fe.warn("rm agent dir failed (ignored)",{err:String(P)})),k instanceof T?k:new T("AGENT_SPAWN_FAILED",String(k),{cause:k})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,n,i,s,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&ud(e.framework))u=wb;else throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);ud(e.framework)&&!gs(e.framework)&&(fe.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await lr(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:i,cozeEnv:s,mockScenario:c,command:u.path});else{let m=e.sessions.get(i),_=Yt(e)?m?.permissionMode??j0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,s,c,this.buildBinShimPathEnv(),_)}try{return await x.start(),await x.initialize(yb),x}catch(m){let _=x instanceof Nt?x.getStderrTail():[];throw _.length>0&&fe.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof T?m.code:"unknown",recentStderr:_}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,m)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let s=await this.detectorFactory().probeOpenclawGateway(n);if(!s.reachable)return new T("AGENT_ENV_NOT_READY",H0(s),{cause:{reason:q0}})}catch(s){fe.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(s)})}return i instanceof T?i:new T("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};fe.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 fe.info("openclaw lazy re-detect success",{agentId:n.defaultAgent.id,workspace:n.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=n,{id:n.defaultAgent.id,workspace:n.defaultAgent.workspace};throw new T("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:_b}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new T("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new T("AGENT_ENV_NOT_READY",H0(n),{cause:{reason:q0}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:s,cozeEnv:c,mockScenario:d,command:u}=e,h=dd(s);if(n.deployType==="local"){let _=await this.ensureOpenclawDefaultAgent();return new zr({command:u,cwd:_.workspace,agentId:_.id,sessionName:h})}let x=await U0(),m;if(i?.modelToken){let _=Vc(s),S=Jc(i),y=`${_}/${S}`;if(!this.ensuredProviders.has(y)){let v=this.getOpenclawConfig(),I=await v.getAllowlistModelsForProvider(_),A=Xf(i,c,d,I);A&&(await v.ensureProvider(_,A),await v.addModelToAllowlist(y),this.ensuredProviders.add(y))}m=y}return new zr({command:u,cwd:n.workspace,agentId:n.agentId,sessionName:h,...x?{gatewayToken:x}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,s=n??e.model;for(let c of e.sessions.keys()){let d=Vc(c),u=`${d}/${s}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,fe.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,fe.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 kb}from"node:fs";import{basename as Y0}from"node:path";$e();ee();import{promises as Eb}from"node:fs";import{basename as vb}from"node:path";var K0=q("file-upload"),Sb="/api/coze_claw/file/agent_upload",Ib=6e4;async function $0(t,e={}){let i=`${Rr(Pr(e.handshakeBase))}${Sb}`,s=e.timeoutMs??Ib,c=await Eb.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...In(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),s);K0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),_=m.headers.get("x-tt-logid")??"";if(!m.ok){let v=await m.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${_}: ${v.slice(0,200)}`)}let S=await m.json();if(S.code!==void 0&&S.code!==0)throw new T("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${_}`);let y=S.data?.file?.file_url;if(!y)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${_}: ${JSON.stringify(S).slice(0,200)}`);return K0.info("file upload ok",{uri:y,logid:_}),{uri:y}}catch(m){throw m instanceof T?m:m.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${s}ms) for ${vb(t.path)}`):new T("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(x)}}$e();ee();import{extname as Ab}from"node:path";var Tb={".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 V0(t){let e=Ab(t).toLowerCase();return Tb[e]??"application/octet-stream"}Be();var Ao=q("agent-send"),J0=50*1024*1024;function X0(t,e,n){let i=t.get(e);if(!i)throw new T("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new T("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let s=i.sessions.get(n);if(!s)throw new T("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:s}}async function Q0(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&&(Ao.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(m=>setTimeout(m,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function eh(t,e){let{session:n,runtime:i}=X0(e.core,t.agentId,t.sessionId);if(!await oi(t.path,n.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let s=await kb.stat(t.path).catch(()=>null);if(!s||!s.isFile())throw new T("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(s.size>J0)throw new T("FILE_TOO_LARGE",`${s.size} bytes > limit ${J0}`);let c=await V0(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new T("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??Y0(t.path),u;try{u=await $0({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 Ao.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:s.size,mime:c,code:x instanceof T?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId: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 Q0(e,n,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Ao.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 th(t,e){let{session:n,runtime:i}=X0(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new T("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let s=t.name??Y0(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 Q0(e,n,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Ao.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 nh(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}cn();Zt();ee();var Mt=q("coze-cli-installer"),rh="@coze/cli@latest",Cb="coze",ih="0.1.8",Db=5e3,Rb=5e3,Pb=9e4,sh=1e4,Ki=null,To=!1;async function xd(t,e={}){if(To)return;if(Ki)return Ki;let n=e.exec??zf;return Ki=(async()=>{try{let i=await Ob(Cb,n),s=!1;if(i){let d=await Lb(n);if(d===void 0)Mt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(nh(d,ih))Mt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:ih}),s=!0;else{Mt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),To=!0;return}}let c=s?"upgrade-only":"full";Mt.info("coze-cli install start",{package:rh,mode:c});try{await n("npm",["i","-g","--prefer-online",rh],{timeout:Pb,maxBuffer:10*1024*1024}),Mt.info("coze-cli install ok")}catch(d){Mt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(s){To=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:sh}),Mt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Mt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:sh}),Mt.info("coze auth login ok")}catch(d){Mt.warn("coze auth login failed",{err:String(d)});return}To=!0}finally{Ki=null}})(),Ki}async function Ob(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:Db});return Pa(i)}catch{return}}async function Lb(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:Rb});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}ln();Be();var Nb=10*6e4;function oh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Nb:e}function ko(t){return ur(t??X().configFile)}function $i(t,e){return fr(e??X().configFile,t)}import{randomBytes as tE}from"node:crypto";ar();$e();ee();import{createReadStream as Mb}from"node:fs";import{mkdir as Bb,readFile as Fb,realpath as zb,stat as Ub,writeFile as Gb}from"node:fs/promises";import{basename as qb,dirname as pd,isAbsolute as Hb,join as jb,relative as Wb,resolve as ah,sep as Kb}from"node:path";import{createInterface as $b}from"node:readline";var dh=q("fs-rpc"),Vi=Ze("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function lh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>Vi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${Vi} bytes`);let i=await fh(t.path,e);return await Bb(pd(i),{recursive:!0}),await Gb(i,t.content,"utf8"),dh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function uh(t,e){let n=await fh(t.path,e),i=await Ub(n),s=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Vi&&!s)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Vi} bytes`);let c;if(s&&i.size>Vi)c=await Vb(n,t.line??1,t.limit);else{let d=await Fb(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 dh.info("fs/read_text_file ok",{path:n,size:c.length}),{content:c}}async function Vb(t,e,n){let i=$b({input:Mb(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 fh(t,e){if(typeof t!="string"||t.length===0)throw new T("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([ch(ah(e)),ch(ah(t))]),s=Wb(n,i);if(Jb(s,Kb,Hb(s)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Jb(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function ch(t){let e=[],n=t;for(;n!==pd(n);)try{let i=await zb(n);return e.length?jb(i,...e.reverse()):i}catch{e.push(qb(n)),n=pd(n)}return t}ee();var hh=q("prompt-multimodal"),xh=10*1024*1024,Zb=15e3,Yb=6;async function ph(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 Xb(d))}}let s=Array.from({length:Math.min(Yb,t.length)},()=>i());return await Promise.all(s),e}function gh(t){return t.some(e=>e.type==="image")}async function Xb(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Ni(e.uri))return t;try{let{buf:n,contentType:i}=await eE(e.uri),s=e.mimeType||Qb(i)||"application/octet-stream";return hh.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 hh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Qb(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function eE(t){let e=new AbortController,n=setTimeout(()=>e.abort(),Zb);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>xh)throw new Error(`image too large: ${s.byteLength} bytes (max ${xh})`);return{buf:Buffer.from(s),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}un();$e();ee();var W=q("core"),nE=3e4,rE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,iE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",sE="\u5BA1\u6279\u5DF2\u8D85\u65F6",oE=3e4,Co=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Mr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=oh(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(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(n=>n.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of n)await this.agents.get(i)?.killAllRuntimes("reload");return n}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,i){let 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)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:c,signal:d}),Wi(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){W.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(Tn(s,{code:J.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>W.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:J.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:J.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(wo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&rE.test(i)?this.currentCozeEnv=i:i&&W.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,J.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let c=await s(e,this);n!==null&&await this.upstream.send(Nr(n,c));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Nr(n,s));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Nr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,J.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(s){W.error("handleFrame failed",{method:e.method,err:String(s)}),n!==null&&await this.upstream.send(Tn(n,qi(s)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new T("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new T("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(i);if(!s)throw this.disconnectedAgents.has(i)?new T("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new T("AGENT_NOT_FOUND",`agent not found: ${i}`);let 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,m=uo(n._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:s.agentId,cloudSessionId:c}),this.synthesizePromptReply(s,h,c,iE,x,m)}}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{W.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}=Mf(i);switch(n){case"session/new":{let c=aE();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=s;return W.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 T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Yt(e)?Nf(i._meta):void 0;if(u!==void 0&&!kn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${cd(e.framework)}`);let h=await this.ensureRuntime(e,d);if(u!==void 0&&h.permissionMode===void 0&&(h.permissionMode=u,await this.persistSessionMapping(e)),h.replySeq=0,await this.ensureDownstream(e,d,h),!h.downstream||!h.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&h.permissionMode!==void 0&&h.permissionMode!==u){let S=h.permissionMode;h.permissionMode=u,await this.persistSessionMapping(e);try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(y){throw h.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),y}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(h.acpSessionId,x):e.activeTriggers.delete(h.acpSessionId);let m=uo(i._meta);if(m?e.activeGroupIds.set(h.acpSessionId,m):e.activeGroupIds.delete(h.acpSessionId),m&&h.cozeGroupId!==m&&(h.cozeGroupId=m,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&gh(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let _=await ph(c.prompt);try{let S=await h.downstream.sessionPrompt({...c,sessionId:h.acpSessionId,prompt:_});return h.lastActiveAt=Date.now(),S}catch(S){if(S instanceof T&&S.code==="AGENT_APPROVAL_TIMEOUT"){let y=h.pendingPermission;y&&(y.downstream.respondAgentRequest(y.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(y.upstreamId),h.pendingPermission=void 0);let v=h.acpSessionId,I=v?e.activeTriggers.get(v):void 0,A=v?e.activeGroupIds.get(v):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,h,d,sE,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,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:h.acpSessionId}),S.stop("reload-after-turn").catch(y=>W.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 T("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new T("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=s,d=c.sessionId,u=c.modeId,h=uo(i._meta);if(!d)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Yt(e))throw e.framework==="openclaw"?new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new T("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!kn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${cd(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let m=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(_){throw x.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),_}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new T("IPC_BAD_REQUEST",`session method not supported: ${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 W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets: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"?fd:W0),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(xt.GEN_MODEL_TOKEN,i,oE);if(!s?.modelToken)throw new T("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return s.modelToken}catch(s){throw s instanceof T&&s.code==="MODEL_TOKEN_GEN_FAILED"?s:new T("MODEL_TOKEN_GEN_FAILED",s instanceof Error?s.message:String(s),{cause:s})}}async ensureDownstream(e,n,i){if(Wi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new T("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=3,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=s&&Date.now()-u<c)throw new T("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&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=h,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await h.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let m=await h.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw W.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){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(Wi(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let s=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),s&&s.stop("idle timeout").catch(c=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let 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(Lr("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(Lr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}},_meta:u})).catch(h=>W.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){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(s);if(!c){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(lE(n)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Yt(e)){let m=d.currentModeId;kn(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(_=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(_)}))):typeof m=="string"&&!kn(e.framework,m)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:m})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Lr("session/update",{...n,sessionId:s,_meta:u})).catch(m=>W.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:J.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 lh(c,s);n.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await uh(c,s);n.respondAgentRequest(i.id,d)}}catch(s){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(s)}),n.respondAgentRequestError(i.id,qi(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 m=u?e.activeGroupIds.get(u):void 0;m&&(x.cozeGroupId=m);let _=u?this.reverseSessionId(e,u):void 0,S=_?e.sessions.get(_):void 0;S&&(S.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:s});let y={...c,..._?{sessionId:_}:{},_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:_,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(Ui(s,"session/request_permission",y)).catch(v=>{this.pendingUpstream.delete(s),W.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),n.respondAgentRequestError(i.id,{code:J.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?(W.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"&&cE(e.result,s),W.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 mo(e.error)):i.value.resolve(e.result);return}W.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 W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:c}),{value:d,key:c}}}sendRequest(e,n,i=nE){let s=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(s),d(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(s,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(Ui(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 ai(e.agentId,n,this.paths)}catch(n){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,s]of e.sessions.entries())if(s.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Tn(e,{code:n,message:i,data:{bridgeVersion:Ot}}))}};function aE(){return tE(16).toString("hex")}function cE(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=n.outcome;if(!i||typeof i!="object"){W.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var dE=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function lE(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 dE.some(c=>s.startsWith(c))}ln();ee();Be();import{randomBytes as uE}from"node:crypto";import{createServer as fE}from"node:http";var hE=1e6,mh=q("ipc"),Do=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??X()}async start(){this.token=uE(32).toString("hex");let e=fE((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(),mh.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 dn(this.paths.portFile,String(this.port)),await dn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){Ji(n,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(s);if(!c){Ji(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await xE(e)}catch(u){Ji(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Ji(n,200,u??{ok:!0})}catch(u){mh.error("IPC handler failed",{key:s,err:String(u)}),Ji(n,500,{error:u instanceof Error?u.message:String(u)})}}};function Ji(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function xE(t){let e=[],n=0;for await(let s of t){let c=s;if(n+=c.length,n>hE)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 Nv=Ht(fx(),1),Mv=Ht(zo(),1),Bv=Ht(qr(),1),Fv=Ht(Ad(),1),zv=Ht(Cd(),1),Uv=Ht(Nd(),1),Ex=Ht(Ho(),1),Gv=Ht(bx(),1);var vx=Ex.default;$e();ee();var{FWS:rS}=Lx(),Le=q("upstream.frontier"),Mx="application/json",Bx="none",iS=15e3;function sS(t){class e extends vx{constructor(i){super(i,Gf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Le.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,s){this.guardTeardown(),super.close(i,s)}terminate(){this.guardTeardown(),super.terminate()}send(i,...s){if(Il("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let d=Buffer.from(c.slice(0,128)).toString("hex");Le.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){Le.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...s)}}return e}var is=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Le.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:qf,...In(this.opts.ppeOverride)},n=sS(e),i=jf(this.opts.urlOverride),s={url:i,ws:n,fpID:Uf,aID:fo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Mx,force:!0},payloadEncoding:{encoding:Bx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new rS(s),d=!1,u=null,h,x,m=new Promise((y,v)=>{h=y,x=v}),_=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?x(y):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Le.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&_();for(let v of this.connectHandlers)Promise.resolve(v({initial:y})).catch(I=>Le.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,Le.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{Le.warn("frontier error",{code:y.code,msg:y.message}),_(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},c.onmessage=y=>this.handleMessage(y),this.fws=c;let S=this.opts.openTimeoutMs??iS;u=setTimeout(()=>{_(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await m}catch(y){try{c.close(1e3,"open failed")}catch(v){Le.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Le.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Le.warn("frontier send refused: upstream not started",{method:i}),new T("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Le.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new T("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let s=JSON.stringify(e),c=e;Fx(c)||Le.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:s.length});try{await n.send(s,{service:33555712,method:1,payloadType:Mx,payloadEncoding:Bx})}catch(u){throw Le.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new T("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let 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){Le.debug("drop non-adapter frontier frame",{service:n});return}let i=cS(e);if(!i){Le.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Le.debug("frame received but no onFrame handler",{size:i.length});return}let s;try{s=JSON.parse(i)}catch(d){Le.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=s;Fx(c)||Le.info("frontier frame in",{logid:aS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:oS(i)}),Promise.resolve(this.handler(s)).catch(d=>Le.warn("frontier frame handler threw",{err:String(d)}))}};function Fx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var zx=2e3;function oS(t){return t.length<=zx?t:`${t.slice(0,zx)}...<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 cS(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}}$e();ee();var zd=q("skill-publish"),dS="/api/marketplace/product/skill/publish_with_assets",lS=15e4;async function Ux(t,e={}){let i=`${Rr(Pr(e.handshakeBase))}${dS}`,s=e.timeoutMs??lS,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...In(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),s);zd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),m=x.headers.get("x-tt-logid")??"";if(!x.ok){let y=await x.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${m}: ${y.slice(0,200)}`)}let _=await x.json();if(zd.info("skill publish response",{logid:m,httpStatus:x.status,code:_.code,msg:_.msg,dataSkillId:_.data?.skill_id??"",dataVersion:_.data?.version??""}),_.code!==void 0&&_.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${_.code} msg=${_.msg??"-"} logid=${m}`);let S={};return _.data?.skill_id!==void 0&&_.data.skill_id!==""&&(S.skillId=String(_.data.skill_id)),_.data?.version&&(S.version=_.data.version),zd.info("skill publish ok",{logid:m,skillId:S.skillId??"",version:S.version??""}),S}catch(x){throw x instanceof T?x:x.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${s}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}ee();var Ud=q("upstream.switchable"),Xo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;Ud.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 Ud.error("swap target start failed, reverting",{err:String(s)}),this.inner=i,s}await i.stop(n??"swapped").catch(s=>Ud.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()}};ee();var Gd=q("upstream"),Vr=class{handler=null;async start(){Gd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Gd.info("NoopUpstream stopped",{reason:e})}async send(e){Gd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};$e();ee();ln();ee();Be();import{promises as uS}from"node:fs";var Gx=q("pat-token-store");async function Qo(t=X()){try{let n=(await uS.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Gx.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"&&Gx.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ss(t,e=X()){if(!t)throw new Error("writePatToken: empty patToken");await dn(e.patTokenFile,t,{mode:384})}Be();Be();import{promises as ea}from"node:fs";import{join as fS}from"node:path";function hS(t,e){return`#!/bin/sh
101
+ `}function NE(t){if(t.includes(`
102
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var ME={path:"",version:"cloud-deployed"},K0="openclaw_gateway_unavailable",BE="openclaw_default_agent_missing";function W0(t){let e=[t.port!==void 0?`port=${t.port}`:"",t.runtime?`runtime=${t.runtime}`:"",t.detail??""].filter(Boolean).join(", ");return`openclaw gateway \u672A\u8FD0\u884C/\u4E0D\u53EF\u8FBE${e?` (${e})`:""}; \u8BF7\u542F\u52A8 openclaw gateway`}var FE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},zE=6e4,ko=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??OE,this.createTimeoutMs=e.createTimeoutMs??zE,this.detectorFactory=e.detectorFactory??(()=>new Zn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Ao({command:r,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??j0(DE(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{ue.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=j0(e,".env");if(await RE(r).then(c=>c.isFile()).catch(()=>!1)){ue.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=LE({...process.env,...Gi(this.paths.agentEnvFile)});await cn(r,o,{mode:384}),ue.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ue.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await De(e.agentId,this.paths).catch(()=>null),o=lo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")ue.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>ue.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")ue.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>ue.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){ue.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await De(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await ze(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ue.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await De(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await ze(T,this.paths))}return ue.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework])throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Ze(e.agentId,this.paths),f=o?"cloud":"local",x=e.framework==="openclaw"&&f==="local",g;x&&!r?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let y=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??y??u.workspace,_=new AbortController,v=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&xd(e.framework)&&await fr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await hd(u.root,{recursive:!0}),await hd(S,{recursive:!0}),await hd(u.logs,{recursive:!0}),T(),x||await hr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Ba(S,"cloud"):await Ba(S,"local",pd)),T();let D=i,E=Vf({model:e.model??D?.model}),C=Mf(e._meta)??D?.accountId,O=e.patToken??D?.patToken,F=f==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new vo({agentId:e.agentId,framework:e.framework,workspace:S,model:E.model??bt,deployType:f,...C?{accountId:C}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",D?.sessions){let $=f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Q,se]of Object.entries(D.sessions)){let oe={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};$?se.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",ue.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Q,framework:e.framework,fallback:oe.permissionMode})):Tn(e.framework,se.permissionMode)?oe.permissionMode=se.permissionMode:ue.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Q,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&ue.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Q,framework:e.framework,deployType:f}),se.cozeGroupId&&(oe.cozeGroupId=se.cozeGroupId),I.sessions.set(Q,oe)}let re=Object.keys(D.sessions).length;re>0&&ue.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(I),A=!0;let B={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:E.model};f==="cloud"&&(B.deployType="cloud"),C&&(B.accountId=C),O&&(B.patToken=O),F&&(B.modelInfo=F),D?.skills&&(B.skills=D.skills),D?.agentName&&(B.agentName=D.agentName),D?.description&&(B.description=D.description),B.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):ue.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let V=e.initialSkills??[];if(V.length>0){let $=[...B.skills??[]],re=new Map($.map((oe,R)=>[oe.skillId,R])),Q=await Promise.allSettled(V.map(oe=>po({agentId:e.agentId,workspace:S,framework:e.framework,skill:oe}))),se=0;for(let[oe,R]of Q.entries()){let U=V[oe];U&&(R.status==="fulfilled"?(go($,re,R.value),se++):ue.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(R.reason)}))}se>0&&(B.skills=$,ue.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:V.length}))}return await ze(B,this.paths),ue.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(T){throw ue.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await CE(u.root,{recursive:!0,force:!0}).catch(D=>ue.warn("rm agent dir failed (ignored)",{err:String(D)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&xd(e.framework))u=ME;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);xd(e.framework)&&!gs(e.framework)&&(ue.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await fr(e.framework));let f=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:f,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else{let g=e.sessions.get(i),y=Jt(e)?g?.permissionMode??$0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,this.buildBinShimPathEnv(),y)}try{return await x.start(),await x.initialize(FE),x}catch(g){let y=x instanceof Nt?x.getStderrTail():[];throw y.length>0&&ue.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof k?g.code:"unknown",recentStderr:y}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,g)}}async resolveSpawnFailure(e,r,i){if(e.framework==="openclaw"&&e.deployType==="local"&&r)try{let o=await this.detectorFactory().probeOpenclawGateway(r);if(!o.reachable)return new k("AGENT_ENV_NOT_READY",W0(o),{cause:{reason:K0}})}catch(o){ue.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};ue.warn("openclaw default agent stale or missing, attempting lazy re-detect");let r=await this.detectorFactory().detect("openclaw");if(r?.defaultAgent?.id&&r.defaultAgent.workspace)return ue.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:BE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new k("AGENT_ENV_NOT_READY",W0(r),{cause:{reason:K0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:l,command:u}=e,f=ud(o);if(r.deployType==="local"){let S=await this.ensureOpenclawDefaultAgent();return new zr({command:u,cwd:S.workspace,agentId:S.id,sessionName:f})}let x=await q0();try{await this.getOpenclawConfig().ensureAcpDeviceScopes()}catch(S){ue.warn("acp device scope ensure failed (ignored)",{err:String(S)})}let g=i?e0(i,c,l):null,y;if(g){let S=Zc(o),v=g.models[0]?.id??bt,I=`${S}/${v}`;if(!this.ensuredProviders.has(I)){let A=this.getOpenclawConfig();await A.ensureProvider(S,g),await A.addModelToAllowlist(I),this.ensuredProviders.add(I)}y=I}return new zr({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:f,...x?{gatewayToken:x}:{},...y?{slashModelOnStart:y}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let r=this.openclawConfigCache;for(let i of e.sessions.keys()){let o=Zc(i),c=`${o}/${e.model}`,l=!0;try{await r.removeProvider(o)}catch(u){l=!1,ue.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:o,err:String(u)})}try{await r.removeModelFromAllowlist(c)}catch(u){l=!1,ue.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:c,err:String(u)})}l&&this.ensuredProviders.delete(c)}}};import{randomUUID as Q0}from"node:crypto";import{promises as WE}from"node:fs";import{basename as eh}from"node:path";We();ne();import{promises as UE}from"node:fs";import{basename as HE}from"node:path";var J0=H("file-upload"),GE="/api/coze_claw/file/agent_upload",qE=6e4;async function Z0(t,e={}){let i=`${Dr(Pr(e.handshakeBase))}${GE}`,o=e.timeoutMs??qE,c=await UE.readFile(t.path),l=new FormData;l.append("agent_id",t.agentId),l.append("session_id",t.sessionId),l.append("file_name",t.name),l.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...In(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);J0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let g=await fetch(i,{method:"POST",headers:u,body:l,signal:f.signal}),y=g.headers.get("x-tt-logid")??"";if(!g.ok){let v=await g.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${y}: ${v.slice(0,200)}`)}let S=await g.json();if(S.code!==void 0&&S.code!==0)throw new k("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${y}`);let _=S.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${y}: ${JSON.stringify(S).slice(0,200)}`);return J0.info("file upload ok",{uri:_,logid:y}),{uri:_}}catch(g){throw g instanceof k?g:g.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${HE(t.path)}`):new k("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}We();ne();import{extname as jE}from"node:path";var KE={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function Y0(t){let e=jE(t).toLowerCase();return KE[e]??"application/octet-stream"}Re();var To=H("agent-send"),X0=50*1024*1024;function th(t,e,r){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new k("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function nh(t,e,r,i,o,c){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(x){u=x,f<2&&(To.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(g=>setTimeout(g,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function rh(t,e){let{session:r,runtime:i}=th(e.core,t.agentId,t.sessionId);if(!await si(t.path,r.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await WE.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>X0)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${X0}`);let c=await Y0(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let l=t.name??eh(t.path),u;try{u=await Z0({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:l,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw To.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:x instanceof k?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let f={sessionUpdate:"agent_file",messageId:Q0(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:l,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await nh(e,r,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),To.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:l,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function ih(t,e){let{session:r,runtime:i}=th(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new k("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??eh(t.path),c={sessionUpdate:"group_file",messageId:Q0(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await nh(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),To.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:o,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function sh(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(r.length,i.length);for(let c=0;c<o;c++){let l=r[c]??0,u=i[c]??0;if(l<u)return!0;if(l>u)return!1}return!1}on();Vt();ne();var Mt=H("coze-cli-installer"),oh="@coze/cli@latest",$E="coze",ah="0.1.8",VE=5e3,JE=5e3,ZE=9e4,ch=1e4,$i=null,Co=!1;async function md(t,e={}){if(Co)return;if($i)return $i;let r=e.exec??Hf;return $i=(async()=>{try{let i=await YE($E,r),o=!1;if(i){let l=await XE(r);if(l===void 0)Mt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(sh(l,ah))Mt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:ah}),o=!0;else{Mt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),Co=!0;return}}let c=o?"upgrade-only":"full";Mt.info("coze-cli install start",{package:oh,mode:c});try{await r("npm",["i","-g","--prefer-online",oh],{timeout:ZE,maxBuffer:10*1024*1024}),Mt.info("coze-cli install ok")}catch(l){Mt.warn("coze-cli install failed (skip subsequent steps)",{err:String(l)});return}if(o){Co=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:ch}),Mt.info("coze config set xTTEnv ok",{env:t.env})}catch(l){Mt.warn("coze config set failed (continue to auth login)",{err:String(l)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:ch}),Mt.info("coze auth login ok")}catch(l){Mt.warn("coze auth login failed",{err:String(l)});return}Co=!0}finally{$i=null}})(),$i}async function YE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:VE});return Na(i)}catch{return}}async function XE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:JE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}ln();Re();var QE=10*6e4;function dh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?QE:e}function Ro(t){return an(t??Y().configFile)}function Vi(t,e){return dn(e??Y().configFile,t)}import{randomBytes as _b}from"node:crypto";cr();We();ne();import{createReadStream as eb}from"node:fs";import{mkdir as tb,readFile as nb,realpath as rb,stat as ib,writeFile as sb}from"node:fs/promises";import{basename as ob,dirname as wd,isAbsolute as ab,join as cb,relative as db,resolve as lh,sep as lb}from"node:path";import{createInterface as ub}from"node:readline";var fh=H("fs-rpc"),Ji=Je("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function hh(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Ji)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Ji} bytes`);let i=await ph(t.path,e);return await tb(wd(i),{recursive:!0}),await sb(i,t.content,"utf8"),fh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function xh(t,e){let r=await ph(t.path,e),i=await ib(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Ji&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Ji} bytes`);let c;if(o&&i.size>Ji)c=await fb(r,t.line??1,t.limit);else{let l=await nb(r,"utf8");if(o){let u=l.split(`
103
+ `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;c=u.slice(f,x).join(`
104
+ `)}else c=l}return fh.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function fb(t,e,r){let i=ub({input:eb(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,l=[],u=0;try{for await(let f of i)if(u>=o&&u<c&&l.push(f),u++,u>=c)break}finally{i.close()}return l.join(`
105
+ `)}async function ph(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([uh(lh(e)),uh(lh(t))]),o=db(r,i);if(hb(o,lb,ab(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function hb(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function uh(t){let e=[],r=t;for(;r!==wd(r);)try{let i=await rb(r);return e.length?cb(i,...e.reverse()):i}catch{e.push(ob(r)),r=wd(r)}return t}ne();var gh=H("prompt-multimodal"),mh=10*1024*1024,xb=15e3,pb=6;async function wh(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,l=t[c];l!==void 0&&(e[c]=await gb(l))}}let o=Array.from({length:Math.min(pb,t.length)},()=>i());return await Promise.all(o),e}function _h(t){return t.some(e=>e.type==="image")}async function gb(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Li(e.uri))return t;try{let{buf:r,contentType:i}=await wb(e.uri),o=e.mimeType||mb(i)||"application/octet-stream";return gh.info("image uri fetched and inlined",{uri:e.uri,bytes:r.length,mimeType:o}),{type:"image",data:r.toString("base64"),mimeType:o}}catch(r){return gh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function mb(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function wb(t){let e=new AbortController,r=setTimeout(()=>e.abort(),xb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=await i.arrayBuffer();if(o.byteLength>mh)throw new Error(`image too large: ${o.byteLength} bytes (max ${mh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}un();We();ne();var W=H("core"),yb=3e4,Eb=/^(boe|ppe)_[A-Za-z0-9_-]+$/,bb="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",vb="\u5BA1\u6279\u5DF2\u8D85\u65F6",Sb=3e4,Do=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Mr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=dh(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,l)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:l}),Wi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(kn(o,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(l=>W.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:X.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:X.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(wo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&Eb.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Nr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Nr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Nr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(o){W.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(kn(r,Hi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let f=o.sessions.get(c);if(f?.pendingPermission){let x=r._meta?.cozeTriggerMsgId,g=uo(r._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,bb,x,g)}}let l=Date.now(),u=!1;try{let f=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,f}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-l,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Ff(i);switch(r){case"session/new":{let c=Ib();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,l=c.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Jt(e)?Bf(i._meta):void 0;if(u!==void 0&&!Tn(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${ld(e.framework)}`);let f=await this.ensureRuntime(e,l);if(u!==void 0&&f.permissionMode===void 0&&(f.permissionMode=u,await this.persistSessionMapping(e)),f.replySeq=0,await this.ensureDownstream(e,l,f),!f.downstream||!f.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&f.permissionMode!==void 0&&f.permissionMode!==u){let S=f.permissionMode;f.permissionMode=u,await this.persistSessionMapping(e);try{await f.downstream.setSessionMode({sessionId:f.acpSessionId,modeId:u})}catch(_){throw f.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),_}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(f.acpSessionId,x):e.activeTriggers.delete(f.acpSessionId);let g=uo(i._meta);if(g?e.activeGroupIds.set(f.acpSessionId,g):e.activeGroupIds.delete(f.acpSessionId),g&&f.cozeGroupId!==g&&(f.cozeGroupId=g,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&_h(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let y=await wh(c.prompt);try{let S=await f.downstream.sessionPrompt({...c,sessionId:f.acpSessionId,prompt:y});return f.lastActiveAt=Date.now(),S}catch(S){if(S instanceof k&&S.code==="AGENT_APPROVAL_TIMEOUT"){let _=f.pendingPermission;_&&(_.downstream.respondAgentRequest(_.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(_.upstreamId),f.pendingPermission=void 0);let v=f.acpSessionId,I=v?e.activeTriggers.get(v):void 0,A=v?e.activeGroupIds.get(v):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:l}),await this.synthesizePromptReply(e,f,l,vb,I,A)}throw S}finally{if(e.activeTriggers.delete(f.acpSessionId),e.activeGroupIds.delete(f.acpSessionId),f.pendingPermission=void 0,f.reloadAfterTurn){f.reloadAfterTurn=!1;let S=f.downstream;S&&(f.downstream=void 0,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:f.acpSessionId}),S.stop("reload-after-turn").catch(_=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(_)})))}else f.downstream?.isAlive()&&this.armIdleTimer(e,l,f)}}case"session/cancel":{let l=o.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(l);if(e.hasSessionQueue(l)){let f=e.getSessionQueue(l);f.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:f.size}),f.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${l}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,l=c.sessionId,u=c.modeId,f=uo(i._meta);if(!l)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Jt(e))throw e.framework==="openclaw"?new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new k("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Tn(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${ld(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(l)??await this.ensureRuntime(e,l);if(x.permissionMode===u)return{};let g=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(y){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),y}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:l,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[l,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:l,runtime:u,oldMode:u.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let l of o)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let l of o){let u=l.runtime.downstream,f=l.runtime.acpSessionId;u?.isAlive()&&f&&c.push({downstream:u,acpSessionId:f,oldMode:l.oldMode,runtime:l.runtime})}for(let l of c)try{await l.downstream.setSessionMode({sessionId:l.acpSessionId,modeId:i})}catch(u){for(let f of o)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r){let i=e.sessions.get(r);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Jt(e)&&(c.permissionMode=e.framework==="claude-code"?pd:V0),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(ft.GEN_MODEL_TOKEN,i,Sb);if(!o?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return o.modelToken}catch(o){throw o instanceof k&&o.code==="MODEL_TOKEN_GEN_FAILED"?o:new k("MODEL_TOKEN_GEN_FAILED",o instanceof Error?o.message:String(o),{cause:o})}}async ensureDownstream(e,r,i){if(Wi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=o&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${l} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let f;try{f=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=l+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let g=await f.sessionNew({cwd:e.workspace});i.acpSessionId=g.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),Jt(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,r,i){if(Wi(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let l=e.activeTriggers.get(r.acpSessionId);l&&(c.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Lr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,l){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),l&&(u.cozeGroupId=l),await this.upstream.send(Lr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(Tb(r)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=r.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&Jt(e)){let g=l.currentModeId;Tn(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(y=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(y)}))):typeof g=="string"&&!Tn(e.framework,g)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:g})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Lr("session/update",{...r,sessionId:o,_meta:u})).catch(g=>W.warn("forward update failed",{agentId:e.agentId,err:String(g)}))}handleAgentRequest(e,r,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,r,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,i);return}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:X.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},l=await hh(c,o);r.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await xh(c,o);r.respondAgentRequest(i.id,l)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Hi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let g=u?e.activeGroupIds.get(u):void 0;g&&(x.cozeGroupId=g);let y=u?this.reverseSessionId(e,u):void 0,S=y?e.sessions.get(y):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let _={...c,...y?{sessionId:y}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:y}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:y,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(zi(o,"session/request_permission",_)).catch(v=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),r.respondAgentRequestError(i.id,{code:X.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&Ab(e.result,o),W.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new mo(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),l=e.get(c);if(l)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:l,key:c}}}sendRequest(e,r,i=yb){let o=this.upstreamIds.next(e);return new Promise((c,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),l(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:l,timer:u}),this.upstream.send(zi(o,e,r)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),l(f)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Jt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await oi(e.agentId,r,this.paths)}catch(r){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(kn(e,{code:r,message:i,data:{bridgeVersion:Lt}}))}};function Ib(){return _b(16).toString("hex")}function Ab(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){W.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var kb=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function Tb(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let i=r;if(i.type!=="text"||typeof i.text!="string")return!1;let{text:o}=i;return kb.some(c=>o.startsWith(c))}ln();ne();Re();import{randomBytes as Cb}from"node:crypto";import{createServer as Rb}from"node:http";var Db=1e6,yh=H("ipc"),Po=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??Y()}async start(){this.token=Cb(32).toString("hex");let e=Rb((i,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let r=e.address();if(!r||typeof r!="object")throw new Error("failed to obtain IPC port");return this.port=r.port,await this.persistAuthFiles(),yh.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,i)=>{e.close(o=>o?i(o):r())}),this.server=null)}async persistAuthFiles(){await cn(this.paths.portFile,String(this.port)),await cn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Zi(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Zi(r,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await Pb(e)}catch(u){Zi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);Zi(r,200,u??{ok:!0})}catch(u){yh.error("IPC handler failed",{key:o,err:String(u)}),Zi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Zi(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function Pb(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>Db)throw new Error("body too large");e.push(c)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var Xv=Ht(px(),1),Qv=Ht(Ho(),1),eS=Ht(Gr(),1),tS=Ht(Cd(),1),nS=Ht(Pd(),1),rS=Ht(Fd(),1),Ix=Ht(Ko(),1),iS=Ht(Sx(),1);var Ax=Ix.default;We();ne();var{FWS:yS}=Bx(),Le=H("upstream.frontier"),zx="application/json",Ux="none",ES=15e3;function bS(t){class e extends Ax{constructor(i){super(i,qf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Le.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(kl("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let l=Buffer.from(c.slice(0,128)).toString("hex");Le.debug("WS raw frame out",{bytes:c.byteLength,headHex:l})}catch(c){Le.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var ss=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Le.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:jf,...In(this.opts.ppeOverride)},r=bS(e),i=Wf(this.opts.urlOverride),o={url:i,ws:r,fpID:Gf,aID:fo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:zx,force:!0},payloadEncoding:{encoding:Ux,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new yS(o),l=!1,u=null,f,x,g=new Promise((_,v)=>{f=_,x=v}),y=_=>{l||(l=!0,u&&(clearTimeout(u),u=null),_?x(_):f())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Le.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&y();for(let v of this.connectHandlers)Promise.resolve(v({initial:_})).catch(I=>Le.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=_=>{this.opened=!1,Le.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{Le.warn("frontier error",{code:_.code,msg:_.message}),y(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let S=this.opts.openTimeoutMs??ES;u=setTimeout(()=>{y(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await g}catch(_){try{c.close(1e3,"open failed")}catch(v){Le.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){Le.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Le.warn("frontier send refused: upstream not started",{method:i}),new k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Le.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;Hx(c)||Le.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:zx,payloadEncoding:Ux})}catch(u){throw Le.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=r(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let r=e.message?.service;if(r!==33555712){Le.debug("drop non-adapter frontier frame",{service:r});return}let i=IS(e);if(!i){Le.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Le.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(l){Le.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let c=o;Hx(c)||Le.info("frontier frame in",{logid:SS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:vS(i)}),Promise.resolve(this.handler(o)).catch(l=>Le.warn("frontier frame handler threw",{err:String(l)}))}};function Hx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Gx=2e3;function vS(t){return t.length<=Gx?t:`${t.slice(0,Gx)}...<truncated, total ${t.length} chars>`}function SS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function IS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}We();ne();var Gd=H("skill-publish"),AS="/api/marketplace/product/skill/publish_with_assets",kS=15e4;async function qx(t,e={}){let i=`${Dr(Pr(e.handshakeBase))}${AS}`,o=e.timeoutMs??kS,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let l={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...In(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);Gd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...l,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:l,body:c,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${_.slice(0,200)}`)}let y=await x.json();if(Gd.info("skill publish response",{logid:g,httpStatus:x.status,code:y.code,msg:y.msg,dataSkillId:y.data?.skill_id??"",dataVersion:y.data?.version??""}),y.code!==void 0&&y.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${y.code} msg=${y.msg??"-"} logid=${g}`);let S={};return y.data?.skill_id!==void 0&&y.data.skill_id!==""&&(S.skillId=String(y.data.skill_id)),y.data?.version&&(S.version=y.data.version),Gd.info("skill publish ok",{logid:g,skillId:S.skillId??"",version:S.version??""}),S}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(f)}}ne();var qd=H("upstream.switchable"),ea=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;qd.info("swap upstream",{reason:r});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw qd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>qd.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var jd=H("upstream"),Vr=class{handler=null;async start(){jd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){jd.info("NoopUpstream stopped",{reason:e})}async send(e){jd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};We();ne();ln();ne();Re();import{promises as TS}from"node:fs";var jx=H("pat-token-store");async function ta(t=Y()){try{let r=(await TS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(jx.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):r}catch(e){let r=e?.code;return r!=="ENOENT"&&jx.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function os(t,e=Y()){if(!t)throw new Error("writePatToken: empty patToken");await cn(e.patTokenFile,t,{mode:384})}Re();Re();import{promises as na}from"node:fs";import{join as CS}from"node:path";function RS(t,e){return`#!/bin/sh
105
106
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
106
- `}function xS(t,e){return`@echo off\r
107
+ `}function DS(t,e){return`@echo off\r
107
108
  "${e}" "${t}" %*\r
108
- `}async function qx(t,e=X()){let n=e.binDir;await ea.mkdir(n,{recursive:!0});let i=fS(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),s=process.execPath,c=process.platform==="win32"?xS(t,s):hS(t,s);return await ea.readFile(i,"utf8").catch(()=>null)===c||(await ea.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ea.chmod(i,493)),n}ee();Be();import{execSync as Hx}from"node:child_process";import{readFileSync as jx,unlinkSync as pS}from"node:fs";import{mkdir as gS,open as mS,readFile as Wx,unlink as qd,writeFile as wS}from"node:fs/promises";import{dirname as _S}from"node:path";var yS=q("single-instance"),bS=t=>new Promise(e=>setTimeout(e,t)),ta=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??X().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Hi(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&&yS.warn("removing stale pid file",{stalePid:i}),await wS(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 Wx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await qd(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let n=await Wx(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 gS(_S(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let s;try{s=await mS(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 bS(this.claimLockIntervalMs);continue}await qd(n).catch(()=>{});continue}try{return await s.writeFile(String(this.selfPid)),await e()}finally{await s.close().catch(()=>{}),await qd(n).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${n} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=jx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Br)||n.includes("lib/index.js"))}catch{}try{let n=Hx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Br)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Hx(`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{jx(this.pidFile,"utf8").trim()===String(this.selfPid)&&pS(this.pidFile)}catch{}})}};na();ee();var nr=q("daemon.upstream-watchdog"),CS=12e4,DS=9e5,RS=3e4;function jd(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ra=class{constructor(e){this.opts=e;this.softMs=e.softMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",CS),this.hardMs=e.hardMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",DS),this.intervalMs=e.intervalMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",RS),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),nr.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&nr.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&nr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,nr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){nr.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:n,hardMs:this.hardMs}),this.opts.onFatal(n);return}n>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,nr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>nr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var H=q("daemon");async function Vx(){let t=X();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){vl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:R=>Ye(R,t).logs,listAgentIds:()=>ms(t)});try{let{writeFileSync:R}=await import("node:fs");R(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
109
+ `}async function Kx(t,e=Y()){let r=e.binDir;await na.mkdir(r,{recursive:!0});let i=CS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?DS(t,o):RS(t,o);return await na.readFile(i,"utf8").catch(()=>null)===c||(await na.writeFile(i,c,"utf8"),process.platform!=="win32"&&await na.chmod(i,493)),r}ne();Re();import{execSync as Wx}from"node:child_process";import{readFileSync as $x,unlinkSync as PS}from"node:fs";import{mkdir as OS,open as LS,readFile as Vx,unlink as Kd,writeFile as NS}from"node:fs/promises";import{dirname as MS}from"node:path";var BS=H("single-instance"),FS=t=>new Promise(e=>setTimeout(e,t)),ra=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Y().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>qi(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&BS.warn("removing stale pid file",{stalePid:i}),await NS(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return r.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),r}async release(){if(this.acquired){try{(await Vx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Kd(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let r=await Vx(e,"utf8"),i=Number.parseInt(r.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(r){if(r.code==="ENOENT")return null;throw r}}async withClaimLock(e){let r=`${this.pidFile}.lock`;await OS(MS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await LS(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=await this.readPidFrom(r);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await FS(this.claimLockIntervalMs);continue}await Kd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Kd(r).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${r} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let r=$x(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Br)||r.includes("lib/index.js"))}catch{}try{let r=Wx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Br)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Wx(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let o=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return o.includes("node")||o.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{$x(this.pidFile,"utf8").trim()===String(this.selfPid)&&PS(this.pidFile)}catch{}})}};ia();ne();var rr=H("daemon.upstream-watchdog"),WS=12e4,$S=9e5,VS=3e4;function $d(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var sa=class{constructor(e){this.opts=e;this.softMs=e.softMs??$d("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",WS),this.hardMs=e.hardMs??$d("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",$S),this.intervalMs=e.intervalMs??$d("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",VS),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),rr.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&rr.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&rr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,rr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){rr.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:r,hardMs:this.hardMs}),this.opts.onFatal(r);return}r>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,rr.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>rr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var j=H("daemon");async function Yx(){let t=Y();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Il({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:R=>Ze(R,t).logs,listAgentIds:()=>ms(t)});try{let{writeFileSync:R}=await import("node:fs");R(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
109
110
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
110
111
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
111
- `)}catch{}}let e=new ta({processTitle:Br}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await ko(),s=i??{};xs({pid:process.pid}),H.info(i?"loaded bridge config":"initialized bridge config");let c=new Xo(new Vr),d=null,u=new Co({upstream:c,paths:t,bridgeConfig:s,sessionSpawner:async(R,U,j,Q)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(R,U,j,Q)}}),h=new Io({paths:t,config:s,registry:u});d=h;let x,m,_=null,S={},y,v=null,I=null,A=null,k=new Cn;function P(R,U){return k.enqueue(()=>D(R,U))}function b(){I||(I=new ra({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:R=>{if(process.env[os]==="1"){H.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:R});return}H.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:R}),process.exit(1)}})),I.start()}async function D(R,U){let j=R,Q=j?.privatecode;if(!Q)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let nt=Bi(j.env),me=j.handshake_url,we=j.frontier_url,At=$x(j.env,me,we);if(A=j,!U?.force&&x===Q&&m===At){let Ee=await PS(t);return u.agents.size===0&&Ee?(H.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),sa(t,h).catch(Ce=>H.warn("connect-noop auto-revive error (ignored)",{err:String(Ce)}))):H.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let mt=!!x&&x!==Q,rn=m!==void 0&&m!==At,Gt=mt||rn,sn=await Hc({privatecode:Q,...me?{endpoint:me}:{},ppeOverride:nt});if(Gt){H.warn("connect config switched, resetting agents",{pcChanged:mt,envChanged:rn,previousPc:x?ia(x):"",nextPc:ia(Q)});for(let Ee of[...u.agents.values()])await Ee.dispose("connect config switch").catch(()=>{}),u.agents.delete(Ee.agentId);u.disconnectedAgents.size>0&&(H.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Vr,"connect switch").catch(()=>{})}_=sn.deviceId,xs({deviceId:_,pid:process.pid}),xd({patToken:Q,env:j.env}).catch(Ee=>H.warn("coze-cli setup error (ignored)",{err:String(Ee)}));let Qr=new is({handshake:sn,privatecode:Q,...we?{urlOverride:we}:{},ppeOverride:nt,getPatTokenForAgent:Ee=>u.agents.get(Ee)?.patToken});return await c.swap(Qr,"connect"),x=Q,m=At,S=nt,y=me,j.mock_scenario!==void 0&&(u.setMockScenario(j.mock_scenario),H.info("mock scenario set",{scenario:j.mock_scenario})),v||(v=new zi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>B.retryPending().catch(Ee=>H.warn("detailSync.retryPending failed (ignored)",{err:String(Ee)})),onAuthFailures:V})),v.start(),b(),Gt&&sa(t,h).catch(Ee=>H.warn("post-connect-switch auto-revive error (ignored)",{err:String(Ee)})),ss(Q,t).catch(Ee=>H.warn("writePatToken after /connect failed (ignored)",{err:String(Ee)})),H.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async R=>h.createAgent(R.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},F=new xo({agents:u.agents,publishSkillToMarketplace:async R=>{let U=u.agents.get(R.agentId)?.patToken??x;if(!U)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Ux({patToken:U,zip:R.zip,...R.skillId?{skillId:R.skillId}:{},skillName:R.skillName,...R.description?{description:R.description}:{},agentId:R.agentId,...R.accountId?{accountId:R.accountId}:{}},{handshakeBase:y,ppeOverride:S})},disposeAndMarkDisconnected:async(R,U)=>{let j=u.agents.get(R);if(j){await h.cleanupOpenclawSessionProviders(j).catch(nt=>H.warn("cleanup openclaw providers failed (ignored)",{agentId:R,err:String(nt)}));let Q=!0;try{await j.dispose(`disconnect: ${U}`)}catch(nt){Q=!1,H.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:R,err:String(nt)}),j.status="error"}Q&&(j.status="disconnected",u.unregister(R),u.disconnectedAgents.add(R))}else u.disconnectedAgents.add(R)},disposeForDelete:async(R,U)=>{let j=u.agents.get(R);j&&(await h.cleanupOpenclawSessionProviders(j).catch(Q=>H.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:R,err:String(Q)})),await j.dispose(`delete: ${U}`).catch(Q=>H.warn("dispose during delete failed (ignored)",{agentId:R,err:String(Q)})),u.unregister(R)),u.disconnectedAgents.delete(R)},detailSyncer:async R=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(R)},cleanupOpenclawProviders:async(R,U)=>{await h.cleanupOpenclawSessionProviders(R,U)},openclawRepair:async(R,U)=>{await h.openclawRepair(R,U)},isRuntimePendingPermission:R=>u.hasPendingPermissionFor(R)});u.registerExtension("_agent/listSkills",R=>F.listSkills(R.params)),u.registerExtension("_agent/addSkills",R=>F.addSkills(R.params)),u.registerExtension("_agent/removeSkills",R=>F.removeSkills(R.params)),u.registerExtension("_agent/publishSkill",R=>F.publishSkill(R.params)),u.registerExtension("_agent/getFileTree",R=>F.getFileTree(R.params)),u.registerExtension("_agent/getFileContent",R=>F.getFileContent(R.params)),u.registerExtension("_agent/update",R=>F.updateAgent(R.params)),u.registerExtension("_agent/disconnect",R=>F.disconnectAgent(R.params)),u.registerExtension("_agent/switchModel",R=>F.switchModel(R.params)),u.registerExtension("_agent/reset",R=>F.resetAgent(R.params)),u.registerExtension("_agent/repair",R=>F.repairAgent(R.params)),u.registerExtension("_agent/delete",R=>F.deleteAgent(R.params)),u.registerExtension("_agent/upgrade",R=>F.upgradeBridge(R.params));let B=new ys({paths:t,handlers:F,agentManager:h,sendDetail:R=>u.sendRequest("_agent/detail",R)});O.ref=B;let V=async R=>{await Promise.allSettled(R.map(async U=>{try{await F.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),H.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(j){H.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(j)})}}))};c.onConnect(({initial:R})=>{H.info("frontier upstream connected, triggering detail sync",{initial:R}),B.syncAll(R?"initial-connect":"reconnect").catch(U=>H.warn("detail sync top-level error (ignored)",{err:String(U)}))});let K=new Do({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let R=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[os]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:_??"",frameworksCache:s.frameworksCache??{},...R?{mockScenario:R}:{}}}},{method:"POST",path:"/pair",handler:async R=>{let U=R,j=U?.privatecode,Q=U?.pairing_code;if(!j||!Q)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let nt=Bi(U.env),me=U.handshake_url,we=U.frontier_url,At=$x(U.env,me,we),mt=!!x&&x!==j,rn=m!==void 0&&m!==At,Gt=mt||rn,sn=await Hc({privatecode:j,...me?{endpoint:me}:{},ppeOverride:nt});if(Gt){H.warn("pair config switched, resetting agents",{pcChanged:mt,envChanged:rn,previousPc:x?ia(x):"",nextPc:ia(j),previousEnvKey:m??"",nextEnvKey:At});for(let Ce of[...u.agents.values()])await Ce.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ce.agentId);u.disconnectedAgents.size>0&&(H.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Vr,"pair switch").catch(()=>{})}_=sn.deviceId,xs({deviceId:_,pid:process.pid}),xd({patToken:j,env:U.env}).catch(Ce=>H.warn("coze-cli setup error (ignored)",{err:String(Ce)}));let Qr=new is({handshake:sn,privatecode:j,...we?{urlOverride:we}:{},ppeOverride:nt,getPatTokenForAgent:Ce=>u.agents.get(Ce)?.patToken});await c.swap(Qr,"pair");try{let Ce=new Zn;s.frameworksCache=await Ce.detectAll(),await $i(s),H.info("frameworks_cache refreshed before pair",{detected:Object.keys(s.frameworksCache)})}catch(Ce){H.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ce)})}let Ee=Object.keys(s.frameworksCache??{});try{let Ce=await u.sendRequest("_agent/pair",{pairCode:Q,patToken:j,frameworks:Ee,_meta:{cozeDeviceId:_}});H.info("_agent/pair ok",{pairResult:Ce}),x=j,m=At,S=nt,y=me,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),H.info("mock scenario set",{scenario:U.mock_scenario})),ss(j,t).catch(Ne=>H.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),v||(v=new zi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>B.retryPending().catch(Ne=>H.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:V})),v.start(),b(),Gt&&sa(t,h).catch(Ne=>H.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let rr;return U.agent_id&&(rr=await LS(U.agent_id,t,h,Ne=>u.sendRequest("_agent/detail",Ne),j).catch(Ne=>(H.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Ne)}),{ok:!1,agentId:U.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...rr?{agent:rr}:{}}}catch(Ce){return H.error("_agent/pair failed",{err:String(Ce)}),{ok:!1,note:`pair failed: ${String(Ce)}`}}}},{method:"POST",path:"/connect",handler:R=>P(R)},{method:"POST",path:"/_agent/create",handler:async R=>{let U=R;return{ok:!0,result:await h.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async R=>{let U=R;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 j=U;return await(j.groupFile?th:eh)(j,{core:u,patToken:x,handshakeBase:y,ppeOverride:S})}catch(j){if(j instanceof T)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async R=>{let U=R?.agent_id,j=await u.reloadAgents(U);return H.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(H.info("IPC /shutdown received"),setImmediate(()=>{ce.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:te,token:Z}=await K.start();try{await qx(t.libEntry,t)}catch(R){H.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(R)})}await u.start(),NS({paths:t,core:u,agentManager:h,detectAll:async()=>(s.frameworksCache=await new Zn().detectAll(),await $i(s),s.frameworksCache)}).catch(R=>H.warn("startup warmup error (ignored)",{err:String(R)})),Ol().then(async()=>{let{probeAcpVersion:R}=await Promise.resolve().then(()=>(cn(),Rl));for(let U of["claude-code","codex"]){let j=await R(U);j&&H.info("acp wrapper version",{framework:U,version:j})}}).catch(R=>H.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(R)}));let ae=null,ce={port:te,token:Z,core:u,ipc:K,shutdown(R){return ae||(H.info("daemon shutdown",{reason:R}),ae=(async()=>{v?.stop(),I?.stop(),await u.stop(R),await K.stop(),await e.release()})(),ae)}};for(let R of["SIGTERM","SIGINT"])process.on(R,()=>{ce.shutdown(R).then(()=>process.exit(0))});return process.on("exit",()=>v0()),process.on("unhandledRejection",R=>{H.error("unhandledRejection",{reason:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0})}),process.on("uncaughtException",R=>{H.error("uncaughtException (will exit, supervisor will restart)",{message:R.message,stack:R.stack,name:R.name});try{process.stderr.write(`FATAL uncaughtException: ${R.stack??R.message}
112
- `)}catch{}process.exit(1)}),H.info("daemon ready",{port:te,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(s.frameworksCache??{}),libVersion:s.libVersion??"dev"}),BS({cliSpawned:process.env[os]==="1",readPatToken:()=>Qo(t),connect:P}).catch(R=>H.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(R)})),ce}async function PS(t){return ms(t).length>0}function ia(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function $x(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function OS(t,e){let n=ms(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(un(),_s));for(let c of n){await s(c,t).catch(d=>H.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),H.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),H.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){H.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function LS(t,e,n,i,s){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(un(),_s)),d=await c(t,e);if(d){if(d.deletedAt)throw new T("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);H.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let m=Jx(d),_={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...s?{patToken:s}:{},...m?{_meta:m}:{}};return await n.createAgent(_),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}H.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new T("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let h={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...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 NS(t){let e=t.logger??H;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 OS(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await sa(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await MS(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function sa(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(()=>(un(),_s));H.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){H.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){H.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){H.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{H.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){H.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),d+=1}}return H.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function MS(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 l0(s,t)).status==="refreshed"&&(i+=1)}catch(c){H.warn("refresh builtin skills failed (skipping agent)",{agentId:s,err:String(c)})}return i>0&&H.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function BS(t){let e=t.logger??H;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}na();Be();import{readFile as Zx}from"node:fs/promises";var nn=class{paths;constructor(e){this.paths=e??X()}async probe(e=1e3){let n=await oa(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:zS(i)}}}async request(e){let n=await oa(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:FS(h)}}finally{clearTimeout(d)}}};async function oa(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 FS(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function zS(t){return t instanceof Error?t.message:String(t)}Zt();ee();ar();import{spawn as US}from"node:child_process";import{userInfo as Xx}from"node:os";var Wd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",GS=new Set(["bash","zsh","sh","dash","ksh"]),Yx=Ze("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),qS=2e3;function HS(t,e=Wd){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 jS(){let t=(process.env.SHELL??"").trim()||(Xx().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return GS.has(e)?t:null}function WS(t){return new Promise(e=>{let n=`printf '%s' '${Wd}'; env; printf '%s' '${Wd}'`,i;try{i=US(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Xx().homedir}})}catch{e(null);return}let s="",c=!1,d=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{c||(c=!0,clearTimeout(h),clearTimeout(x),e(m))};i.stdout?.on("data",m=>{s+=m.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(s.length>0?s:null));let h=setTimeout(()=>d("SIGTERM"),Yx),x=setTimeout(()=>{d("SIGKILL"),u(s.length>0?s:null)},Yx+qS)})}async function Kd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=jS();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??WS)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let s=HS(i);return s==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:s}}Be();function Pn(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}}cn();import{chmod as KS,copyFile as Qx,mkdir as tp,readFile as cs,rename as ep,rm as Jd,stat as Zd,writeFile as $S}from"node:fs/promises";import{homedir as QR}from"node:os";import{dirname as VS,join as Ut,resolve as Yd,sep as as}from"node:path";import{fileURLToPath as JS}from"node:url";Zt();ee();Be();var Jr=q("dist-install");function np(){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 ZS(){return process.platform==="win32"?"codex-acp.exe":"codex-acp"}function YS(t){let e=JS(t),n=VS(e),i=`${as}src${as}`;if(n.includes(i)||n.endsWith(`${as}src${as}cli`))return null;let s=Yd(n,"index.js"),c=Yd(n,"..","package.json");return{dist:s,pkgJson:c}}async function Xd(t={}){let e=t.paths??X(),n=YS(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 cs(s,"utf8"));c=v.version??"unknown",d=v.dependencies??{}}catch(v){return Jr.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=ps.map(v=>({name:v,spec:d[v]??"latest"})),h=u.map(({name:v,spec:I})=>`${v}@${I}`),x=await ko(e.configFile)??{},m=x.libVersion,_=await cs(e.libEntry).then(()=>!0).catch(()=>!1),S=m===c,y=await rp(e,u);if(S&&_&&y)return{kind:"already-current",libVersion:c};if(!S||!_){await tp(e.libDir,{recursive:!0}),await Qx(i,e.libEntry),await Qx(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=Yd(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
114
- `;await cs(v,"utf8").catch(()=>null)!==I&&await $S(v,I)}return y||(t.installWrappers?await t.installWrappers(e,h):await QS(e,h,u)),x.libVersion=c,await $i(x,e.configFile),Jr.info("dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),S&&_?{kind:"already-current",libVersion:c}:m?{kind:"version-changed",fromVersion:m,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function rp(t,e){for(let n of e){let i=Ut(t.libDir,"node_modules",...n.name.split("/"),"package.json"),s;try{s=JSON.parse(await cs(i,"utf8"))}catch(d){return Jr.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 Jr.warn("wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!XS(c,n.spec))return Jr.warn("wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:c,expected:n.spec}),!1}return!!await ip(Ut(t.libDir,"node_modules"))}function XS(t,e){let n=$d(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=$d(i.slice(1));if(!c)return!0;if(Vd(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 Vd(n,d)<0}let s=$d(i);return s?Vd(n,s)===0:!0}function $d(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Vd(t,e){for(let n=0;n<3;n++){let i=(t[n]??0)-(e[n]??0);if(i!==0)return i}return 0}async function QS(t,e,n){await n1(t.installLock,async()=>{if(await rp(t,n))return;let i=Math.random().toString(36).slice(2,10),s=`${t.libDir}${as}.staging-${process.pid}-${i}`,c=Ut(s,"node_modules"),d=Ut(t.libDir,"node_modules");try{await tp(s,{recursive:!0}),await e1(e,s),await t1(c);let u=`${d}.trash-${i}`;await ep(d,u).catch(()=>{}),await ep(c,d),await Jd(u,{recursive:!0,force:!0}).catch(()=>{}),Jr.info("wrapper closure installed",{liveNm:d,specs:e})}finally{await Jd(s,{recursive:!0,force:!0}).catch(()=>{})}})}function e1(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=st("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 t1(t){for(let e of ps){let n=Ut(t,...e.split("/")),i=JSON.parse(await cs(Ut(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=Ut(t,".bin",s),d=await Zd(c);process.platform!=="win32"&&!(d.mode&73)&&await KS(c,d.mode|73).catch(()=>{})}if(!await ip(t)){let e=np()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex-acp binary \u7F3A\u5931`)}}async function ip(t){let e=np();if(!e)return!0;let n=Ut(t,...e.split("/")),i=Ut(n,"package.json"),s=Ut(n,"bin",ZS()),[c,d]=await Promise.all([Zd(i).then(u=>u.isFile()).catch(()=>!1),Zd(s).then(u=>u.isFile()).catch(()=>!1)]);return c&&d}async function n1(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 Jd(t,{force:!0}).catch(()=>{})}}ka();ee();Be();import{closeSync as op,fstatSync as ap,openSync as cp,readFileSync as r1,readSync as i1,readdirSync as s1,statSync as o1}from"node:fs";import{join as aa}from"node:path";var a1=new Set(["debug","info","warn","error"]);function dp(t){let e=t,n=Pn(e,"--agent-id");e=n.rest;let i=Pn(e,"--date");e=i.rest;let s=Pn(e,"-n","--lines");e=s.rest;let c=Pn(e,"--level");e=c.rest;let d=Pn(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&&a1.has(c.value)?c.value:void 0,m={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(m.agentId=n.value),i.value&&(m.date=i.value),x&&(m.level=x),d.value&&(m.grep=d.value),m}function c1(t,e){return t.agentId?aa(Ye(t.agentId,e).logs,cr("agent",t.date)):aa(e.bridgeLogsDir,cr("bridge",t.date))}function d1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function l1(t,e){let n;try{n=s1(t)}catch{return[]}let i=[];for(let s of n){let c=Ta(s,e);if(!c)continue;let d=0;try{d=o1(aa(t,s)).size}catch{}i.push({file:aa(t,s),date:c,size:d})}return i.sort((s,c)=>c.date.localeCompare(s.date)),i}function lp(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"&&!Al(n,e.level))return!1}return!0}var sp={debug:"90",info:"36",warn:"33",error:"31"},u1=new Set(["ts","level","module","msg"]);function f1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function up(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=f1(n.ts),s=typeof n.level=="string"?n.level:"",c=s.toUpperCase().padEnd(5);e.color&&sp[s]&&(c=`\x1B[${sp[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])=>!u1.has(x)).map(([x,m])=>` ${x}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${d} ${u}${h}`}function h1(t,e,n){let c=r1(t,"utf8").split(`
115
- `).filter(d=>d.length>0).filter(d=>lp(d,{level:e.level,grep:e.grep}));for(let d of d1(c,e.lines))process.stdout.write(`${up(d,{raw:e.raw,color:n})}
116
- `)}async function fp(t,e){let n=e.paths??X(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Ye(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=l1(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??Ln(new Date),c=c1({agentId:t.agentId,date:s},n);try{h1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
112
+ `)}catch{}}let e=new ra({processTitle:Br}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Ro(),o=i??{};xs({pid:process.pid}),j.info(i?"loaded bridge config":"initialized bridge config");let c=new ea(new Vr),l=null,u=new Do({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(R,U,K,te)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(R,U,K,te)}}),f=new ko({paths:t,config:o,registry:u});l=f;let x,g,y=null,S={},_,v=null,I=null,A=null,T=new Cn;function D(R,U){return T.enqueue(()=>C(R,U))}function E(){I||(I=new sa({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:R=>{if(process.env[as]==="1"){j.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:R});return}j.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:R}),process.exit(1)}})),I.start()}async function C(R,U){let K=R,te=K?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let et=Mi(K.env),ge=K.handshake_url,me=K.frontier_url,It=Zx(K.env,ge,me);if(A=K,!U?.force&&x===te&&g===It){let Ee=await JS(t);return u.agents.size===0&&Ee?(j.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),aa(t,f).catch(Te=>j.warn("connect-noop auto-revive error (ignored)",{err:String(Te)}))):j.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let pt=!!x&&x!==te,tn=g!==void 0&&g!==It,Ut=pt||tn,nn=await Wc({privatecode:te,...ge?{endpoint:ge}:{},ppeOverride:et});if(Ut){j.warn("connect config switched, resetting agents",{pcChanged:pt,envChanged:tn,previousPc:x?oa(x):"",nextPc:oa(te)});for(let Ee of[...u.agents.values()])await Ee.dispose("connect config switch").catch(()=>{}),u.agents.delete(Ee.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Vr,"connect switch").catch(()=>{})}y=nn.deviceId,xs({deviceId:y,pid:process.pid}),md({patToken:te,env:K.env}).catch(Ee=>j.warn("coze-cli setup error (ignored)",{err:String(Ee)}));let Qr=new ss({handshake:nn,privatecode:te,...me?{urlOverride:me}:{},ppeOverride:et,getPatTokenForAgent:Ee=>u.agents.get(Ee)?.patToken});return await c.swap(Qr,"connect"),x=te,g=It,S=et,_=ge,K.mock_scenario!==void 0&&(u.setMockScenario(K.mock_scenario),j.info("mock scenario set",{scenario:K.mock_scenario})),v||(v=new Fi({core:u,getDeviceId:()=>y??"",onTickEnd:()=>B.retryPending().catch(Ee=>j.warn("detailSync.retryPending failed (ignored)",{err:String(Ee)})),onAuthFailures:V})),v.start(),E(),Ut&&aa(t,f).catch(Ee=>j.warn("post-connect-switch auto-revive error (ignored)",{err:String(Ee)})),os(te,t).catch(Ee=>j.warn("writePatToken after /connect failed (ignored)",{err:String(Ee)})),j.info("/connect: WS established",{deviceId:y}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async R=>f.createAgent(R.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},F=new xo({agents:u.agents,publishSkillToMarketplace:async R=>{let U=u.agents.get(R.agentId)?.patToken??x;if(!U)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return qx({patToken:U,zip:R.zip,...R.skillId?{skillId:R.skillId}:{},skillName:R.skillName,...R.description?{description:R.description}:{},agentId:R.agentId,...R.accountId?{accountId:R.accountId}:{}},{handshakeBase:_,ppeOverride:S})},disposeAndMarkDisconnected:async(R,U)=>{let K=u.agents.get(R);if(K){await f.cleanupOpenclawSessionProviders(K).catch(et=>j.warn("cleanup openclaw providers failed (ignored)",{agentId:R,err:String(et)}));let te=!0;try{await K.dispose(`disconnect: ${U}`)}catch(et){te=!1,j.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:R,err:String(et)}),K.status="error"}te&&(K.status="disconnected",u.unregister(R),u.disconnectedAgents.add(R))}else u.disconnectedAgents.add(R)},disposeForDelete:async(R,U)=>{let K=u.agents.get(R);K&&(await f.cleanupOpenclawSessionProviders(K).catch(te=>j.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:R,err:String(te)})),await K.dispose(`delete: ${U}`).catch(te=>j.warn("dispose during delete failed (ignored)",{agentId:R,err:String(te)})),u.unregister(R)),u.disconnectedAgents.delete(R)},detailSyncer:async R=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(R)},cleanupOpenclawProviders:async R=>{await f.cleanupOpenclawSessionProviders(R)},openclawRepair:async(R,U)=>{await f.openclawRepair(R,U)},isRuntimePendingPermission:R=>u.hasPendingPermissionFor(R)});u.registerExtension("_agent/listSkills",R=>F.listSkills(R.params)),u.registerExtension("_agent/addSkills",R=>F.addSkills(R.params)),u.registerExtension("_agent/removeSkills",R=>F.removeSkills(R.params)),u.registerExtension("_agent/publishSkill",R=>F.publishSkill(R.params)),u.registerExtension("_agent/getFileTree",R=>F.getFileTree(R.params)),u.registerExtension("_agent/getFileContent",R=>F.getFileContent(R.params)),u.registerExtension("_agent/update",R=>F.updateAgent(R.params)),u.registerExtension("_agent/disconnect",R=>F.disconnectAgent(R.params)),u.registerExtension("_agent/switchModel",R=>F.switchModel(R.params)),u.registerExtension("_agent/reset",R=>F.resetAgent(R.params)),u.registerExtension("_agent/repair",R=>F.repairAgent(R.params)),u.registerExtension("_agent/delete",R=>F.deleteAgent(R.params)),u.registerExtension("_agent/upgrade",R=>F.upgradeBridge(R.params));let B=new ys({paths:t,handlers:F,agentManager:f,sendDetail:R=>u.sendRequest("_agent/detail",R)});O.ref=B;let V=async R=>{await Promise.allSettled(R.map(async U=>{try{await F.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),j.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(K){j.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(K)})}}))};c.onConnect(({initial:R})=>{j.info("frontier upstream connected, triggering detail sync",{initial:R}),B.syncAll(R?"initial-connect":"reconnect").catch(U=>j.warn("detail sync top-level error (ignored)",{err:String(U)}))});let $=new Po({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let R=u.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[as]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:y??"",frameworksCache:o.frameworksCache??{},...R?{mockScenario:R}:{}}}},{method:"POST",path:"/pair",handler:async R=>{let U=R,K=U?.privatecode,te=U?.pairing_code;if(!K||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let et=Mi(U.env),ge=U.handshake_url,me=U.frontier_url,It=Zx(U.env,ge,me),pt=!!x&&x!==K,tn=g!==void 0&&g!==It,Ut=pt||tn,nn=await Wc({privatecode:K,...ge?{endpoint:ge}:{},ppeOverride:et});if(Ut){j.warn("pair config switched, resetting agents",{pcChanged:pt,envChanged:tn,previousPc:x?oa(x):"",nextPc:oa(K),previousEnvKey:g??"",nextEnvKey:It});for(let Te of[...u.agents.values()])await Te.dispose("pair config switch").catch(()=>{}),u.agents.delete(Te.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Vr,"pair switch").catch(()=>{})}y=nn.deviceId,xs({deviceId:y,pid:process.pid}),md({patToken:K,env:U.env}).catch(Te=>j.warn("coze-cli setup error (ignored)",{err:String(Te)}));let Qr=new ss({handshake:nn,privatecode:K,...me?{urlOverride:me}:{},ppeOverride:et,getPatTokenForAgent:Te=>u.agents.get(Te)?.patToken});await c.swap(Qr,"pair");try{let Te=new Zn;o.frameworksCache=await Te.detectAll(),await Vi(o),j.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Te){j.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Te)})}let Ee=Object.keys(o.frameworksCache??{});try{let Te=await u.sendRequest("_agent/pair",{pairCode:te,patToken:K,frameworks:Ee,_meta:{cozeDeviceId:y}});j.info("_agent/pair ok",{pairResult:Te}),x=K,g=It,S=et,_=ge,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),j.info("mock scenario set",{scenario:U.mock_scenario})),os(K,t).catch(Ne=>j.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),v||(v=new Fi({core:u,getDeviceId:()=>y??"",onTickEnd:()=>B.retryPending().catch(Ne=>j.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:V})),v.start(),E(),Ut&&aa(t,f).catch(Ne=>j.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let ir;return U.agent_id&&(ir=await YS(U.agent_id,t,f,Ne=>u.sendRequest("_agent/detail",Ne),K).catch(Ne=>(j.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Ne)}),{ok:!1,agentId:U.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...ir?{agent:ir}:{}}}catch(Te){return j.error("_agent/pair failed",{err:String(Te)}),{ok:!1,note:`pair failed: ${String(Te)}`}}}},{method:"POST",path:"/connect",handler:R=>D(R)},{method:"POST",path:"/_agent/create",handler:async R=>{let U=R;return{ok:!0,result:await f.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async R=>{let U=R;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let K=U;return await(K.groupFile?ih:rh)(K,{core:u,patToken:x,handshakeBase:_,ppeOverride:S})}catch(K){if(K instanceof k)return{ok:!1,code:K.code,message:K.message};throw K}}},{method:"POST",path:"/reload",handler:async R=>{let U=R?.agent_id,K=await u.reloadAgents(U);return j.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:K}),{ok:!0,recycled:K}}},{method:"POST",path:"/shutdown",handler:async()=>(j.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:Q}=await $.start();try{await Kx(t.libEntry,t)}catch(R){j.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(R)})}await u.start(),XS({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new Zn().detectAll(),await Vi(o),o.frameworksCache)}).catch(R=>j.warn("startup warmup error (ignored)",{err:String(R)})),Nl().then(async()=>{let{probeAcpVersion:R}=await Promise.resolve().then(()=>(on(),Ol));for(let U of["claude-code","codex"]){let K=await R(U);K&&j.info("acp wrapper version",{framework:U,version:K})}}).catch(R=>j.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(R)}));let se=null,oe={port:re,token:Q,core:u,ipc:$,shutdown(R){return se||(j.info("daemon shutdown",{reason:R}),se=(async()=>{v?.stop(),I?.stop(),await u.stop(R),await $.stop(),await e.release()})(),se)}};for(let R of["SIGTERM","SIGINT"])process.on(R,()=>{oe.shutdown(R).then(()=>process.exit(0))});return process.on("exit",()=>S0()),process.on("unhandledRejection",R=>{j.error("unhandledRejection",{reason:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0})}),process.on("uncaughtException",R=>{j.error("uncaughtException (will exit, supervisor will restart)",{message:R.message,stack:R.stack,name:R.name});try{process.stderr.write(`FATAL uncaughtException: ${R.stack??R.message}
113
+ `)}catch{}process.exit(1)}),j.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),e1({cliSpawned:process.env[as]==="1",readPatToken:()=>ta(t),connect:D}).catch(R=>j.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(R)})),oe}async function JS(t){return ms(t).length>0}function oa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Zx(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function ZS(t,e){let r=ms(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(un(),_s));for(let c of r){await o(c,t).catch(l=>j.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.deletedAt?(e.disconnectedAgents.add(c),j.info("agent marked deleted on startup",{agentId:c,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(c),j.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){j.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function YS(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(un(),_s)),l=await c(t,e);if(l){if(l.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${l.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);j.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let g=Xx(l),y={agentId:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...o?{patToken:o}:{},...g?{_meta:g}:{}};return await r.createAgent(y),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}j.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(f);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function XS(t){let e=t.logger??j;try{let r=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(r??{})})}catch(r){e.warn("framework detection failed (using cached)",{err:String(r)})}await ZS(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await aa(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await QS(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function aa(t,e){let{readdir:r}=await import("node:fs/promises"),i;try{i=await r(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>(un(),_s));j.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,l=0;for(let u of i){let f;try{f=await o(u,t)}catch(x){j.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),l+=1;continue}if(!f){l+=1;continue}if(f.deletedAt){j.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),l+=1;continue}if(f.disconnectedAt){j.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),l+=1;continue}try{j.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=Xx(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){j.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),l+=1}}return j.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,total:i.length}}async function QS(t){let{readdir:e}=await import("node:fs/promises"),r;try{r=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(r.length===0)return{refreshed:0,total:0};let i=0;for(let o of r)try{(await f0(o,t)).status==="refreshed"&&(i+=1)}catch(c){j.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&j.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function e1(t){let e=t.logger??j;if(t.cliSpawned)return"skipped-cli";let r=await t.readPatToken();return r?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:r}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function Xx(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ia();Re();import{readFile as Qx}from"node:fs/promises";var en=class{paths;constructor(e){this.paths=e??Y()}async probe(e=1e3){let r=await ca(this.paths);if(!r)return{kind:"not-running"};try{let i=await this.fetch(r,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...r}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:n1(i)}}}async request(e){let r=await ca(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let i=r.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,l=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),f=await u.text();return{status:u.status,body:t1(f)}}finally{clearTimeout(l)}}};async function ca(t){try{let[e,r]=await Promise.all([Qx(t.portFile,"utf8"),Qx(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=r.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function t1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function n1(t){return t instanceof Error?t.message:String(t)}Vt();ne();cr();import{spawn as r1}from"node:child_process";import{userInfo as tp}from"node:os";var Vd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",i1=new Set(["bash","zsh","sh","dash","ksh"]),ep=Je("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),s1=2e3;function o1(t,e=Vd){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let l of o.split(`
114
+ `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.slice(u+1))}return c}function a1(){let t=(process.env.SHELL??"").trim()||(tp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return i1.has(e)?t:null}function c1(t){return new Promise(e=>{let r=`printf '%s' '${Vd}'; env; printf '%s' '${Vd}'`,i;try{i=r1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??tp().homedir}})}catch{e(null);return}let o="",c=!1,l=g=>{try{i.pid&&process.kill(-i.pid,g)}catch{}},u=g=>{c||(c=!0,clearTimeout(f),clearTimeout(x),e(g))};i.stdout?.on("data",g=>{o+=g.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>l("SIGTERM"),ep),x=setTimeout(()=>{l("SIGKILL"),u(o.length>0?o:null)},ep+s1)})}async function Jd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=a1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??c1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=o1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Re();function Pn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],l=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,l=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),l=!0;break}}l||r.push(c)}return{value:i,rest:r}}on();import{chmod as d1,copyFile as np,mkdir as ip,readFile as da,rename as rp,rm as Zd,stat as sp,writeFile as l1}from"node:fs/promises";import{homedir as mP}from"node:os";import{dirname as u1,join as Jr,resolve as Yd,sep as cs}from"node:path";import{fileURLToPath as f1}from"node:url";Vt();ne();Re();var Xd=H("dist-install");function h1(t){let e=f1(t),r=u1(e),i=`${cs}src${cs}`;if(r.includes(i)||r.endsWith(`${cs}src${cs}cli`))return null;let o=Yd(r,"index.js"),c=Yd(r,"..","package.json");return{dist:o,pkgJson:c}}async function el(t={}){let e=t.paths??Y(),r=h1(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,l;try{let S=JSON.parse(await da(o,"utf8"));c=S.version??"unknown",l=S.dependencies??{}}catch(S){return Xd.warn("cannot read source package.json,skip dist install",{err:String(S)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(S)}`}}let u=ri.map(S=>`${S}@${l[S]??"latest"}`),f=await Ro(e.configFile)??{},x=f.libVersion,g=await da(e.libEntry).then(()=>!0).catch(()=>!1),y=x===c;if(y&&g&&await Qd(e))return{kind:"already-current",libVersion:c};if(!y||!g){await ip(e.libDir,{recursive:!0}),await np(i,e.libEntry),await np(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let S=Yd(e.libDir,"package.json"),_=`${JSON.stringify({type:"module"},null,2)}
115
+ `;await da(S,"utf8").catch(()=>null)!==_&&await l1(S,_)}return(!y||!await Qd(e))&&await(t.installWrappers??x1)(e,u),f.libVersion=c,await Vi(f,e.configFile),Xd.info("dist installed",{libEntry:e.libEntry,fromVersion:x,toVersion:c}),y&&g?{kind:"already-current",libVersion:c}:x?{kind:"version-changed",fromVersion:x,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Qd(t){for(let e of ri){let r=Jr(t.libDir,"node_modules",...e.split("/"),"package.json");if(!await sp(r).then(o=>o.isFile()).catch(()=>!1))return!1}return!0}async function x1(t,e){await m1(t.installLock,async()=>{if(await Qd(t))return;let r=Math.random().toString(36).slice(2,10),i=`${t.libDir}${cs}.staging-${process.pid}-${r}`,o=Jr(i,"node_modules"),c=Jr(t.libDir,"node_modules");try{await ip(i,{recursive:!0}),await p1(e,i),await g1(o);let l=`${c}.trash-${r}`;await rp(c,l).catch(()=>{}),await rp(o,c),await Zd(l,{recursive:!0,force:!0}).catch(()=>{}),Xd.info("wrapper closure installed",{liveNm:c,specs:e})}finally{await Zd(i,{recursive:!0,force:!0}).catch(()=>{})}})}function p1(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=it("npm",r,{stdio:["ignore","pipe","pipe"]}),l="";c.stderr?.on("data",f=>{l.length<8192&&(l+=f.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",f=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(f)}`))}),c.once("close",f=>{clearTimeout(u),f===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${l.trim().slice(0,2e3)}`))})})}async function g1(t){for(let e of ri){let r=Jr(t,...e.split("/")),i=JSON.parse(await da(Jr(r,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let c=Jr(t,".bin",o),l=await sp(c);process.platform!=="win32"&&!(l.mode&73)&&await d1(c,l.mode|73).catch(()=>{})}}async function m1(t,e){let{open:r}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await r(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await Zd(t,{force:!0}).catch(()=>{})}}Da();ne();Re();import{closeSync as ap,fstatSync as cp,openSync as dp,readFileSync as w1,readSync as _1,readdirSync as y1,statSync as E1}from"node:fs";import{join as la}from"node:path";var b1=new Set(["debug","info","warn","error"]);function lp(t){let e=t,r=Pn(e,"--agent-id");e=r.rest;let i=Pn(e,"--date");e=i.rest;let o=Pn(e,"-n","--lines");e=o.rest;let c=Pn(e,"--level");e=c.rest;let l=Pn(e,"--grep");e=l.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,x=c.value&&b1.has(c.value)?c.value:void 0,g={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(g.agentId=r.value),i.value&&(g.date=i.value),x&&(g.level=x),l.value&&(g.grep=l.value),g}function v1(t,e){return t.agentId?la(Ze(t.agentId,e).logs,dr("agent",t.date)):la(e.bridgeLogsDir,dr("bridge",t.date))}function S1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function I1(t,e){let r;try{r=y1(t)}catch{return[]}let i=[];for(let o of r){let c=Ra(o,e);if(!c)continue;let l=0;try{l=E1(la(t,o)).size}catch{}i.push({file:la(t,o),date:c,size:l})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function up(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let r;try{r=JSON.parse(t).level}catch{return!0}if(typeof r=="string"&&!Tl(r,e.level))return!1}return!0}var op={debug:"90",info:"36",warn:"33",error:"31"},A1=new Set(["ts","level","module","msg"]);function k1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function fp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=k1(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&op[o]&&(c=`\x1B[${op[o]}m${c}\x1B[0m`);let l=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",f=Object.entries(r).filter(([x])=>!A1.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${l} ${u}${f}`}function T1(t,e,r){let c=w1(t,"utf8").split(`
116
+ `).filter(l=>l.length>0).filter(l=>up(l,{level:e.level,grep:e.grep}));for(let l of S1(c,e.lines))process.stdout.write(`${fp(l,{raw:e.raw,color:r})}
117
+ `)}async function hp(t,e){let r=e.paths??Y(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?Ze(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=I1(l,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
118
+ `),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
119
+ `);return 0}let o=t.date??Ln(new Date),c=v1({agentId:t.agentId,date:o},r);try{T1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
119
120
  \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 g1(c,t,i),0}var x1=500;function p1(t){try{let e=cp(t,"r");try{return ap(e).size}finally{op(e)}}catch{return 0}}async function g1(t,e,n){let i=p1(t),s="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let h=cp(t,"r");try{let x=ap(h).size;if(x>i){let m=Buffer.allocUnsafe(x-i),_=i1(h,m,0,m.length,i);u=m.subarray(0,_).toString("utf8"),i+=_}}finally{op(h)}}catch{}if(u){let h=(s+u).split(`
122
- `);s=h.pop()??"";for(let x of h)x.length>0&&lp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${up(x,{raw:e.raw,color:n})}
123
- `)}await new Promise(h=>setTimeout(h,x1))}}finally{process.off("SIGINT",d)}}import{basename as m1,resolve as w1}from"node:path";Be();var _1=9e4,y1={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 b1(t){return y1[t]??1}async function hp(t,e={}){let n=e.paths??X();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
121
+ (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
122
+ `),1}return t.follow&&await D1(c,t,i),0}var C1=500;function R1(t){try{let e=dp(t,"r");try{return cp(e).size}finally{ap(e)}}catch{return 0}}async function D1(t,e,r){let i=R1(t),o="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let f=dp(t,"r");try{let x=cp(f).size;if(x>i){let g=Buffer.allocUnsafe(x-i),y=_1(f,g,0,g.length,i);u=g.subarray(0,y).toString("utf8"),i+=y}}finally{ap(f)}}catch{}if(u){let f=(o+u).split(`
123
+ `);o=f.pop()??"";for(let x of f)x.length>0&&up(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${fp(x,{raw:e.raw,color:r})}
124
+ `)}await new Promise(f=>setTimeout(f,C1))}}finally{process.off("SIGINT",l)}}import{basename as P1,resolve as O1}from"node:path";Re();var L1=9e4,N1={PATH_OUTSIDE_WORKSPACE:3,FILE_TOO_LARGE:3,UNSUPPORTED_MIME:3,MODEL_MODALITY_UNSUPPORTED:3,IPC_BAD_REQUEST:3,AGENT_NOT_FOUND:4,IPC_AUTH_FAILED:4,AGENT_DISCONNECTED:5,UPLOAD_FAILED:5,UPSTREAM_NOT_READY:5,UPSTREAM_DISCONNECTED:5,UPSTREAM_HANDSHAKE_FAILED:5,AGENT_BUSY:1,AGENT_SPAWN_FAILED:1,AGENT_TIMEOUT:1,AGENT_FRAME_IDLE_TIMEOUT:1,AGENT_PROTOCOL_ERROR:1,AGENT_TURN_ABORTED:1,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,OPERATION_NOT_ALLOWED_FOR_CLOUD:1,METHOD_NOT_FOUND:1,AGENT_DEPENDENCY_INSTALL_FAILED:1,AGENT_APPROVAL_TIMEOUT:1,AGENT_ENV_NOT_READY:1,SKILL_NOT_FOUND:1,SKILL_ZIP_TOO_LARGE:1};function M1(t){return N1[t]??1}async function xp(t,e={}){let r=e.paths??Y();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
124
125
  `),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 oa(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:w1(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 E1(i,"/agent/send",s,_1)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
126
+ `),3;let i=await ca(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
127
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:O1(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},c;try{c=await B1(i,"/agent/send",o,L1)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
127
128
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
128
- `),b1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
129
- `);else{let d=t.name??m1(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} (${v1(c.bytes)})
131
- `)}return 0}async function E1(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 v1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var vp=q("cli");function Ke(t,e){let{value:n,rest:i}=Pn(t,e);return{value:n,rest:i}}function ha(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
132
- `)}function $1(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}=Ke(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 V1(e.slice(1));if(e[0]==="log")return{mode:"log",...dp(e.slice(1))};if(e[0]==="connect")return J1(e.slice(1));if(e.includes("--status"))return ha("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ha("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ha("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ha("--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}=Ke(n,"--pat-token");n=s;let{value:c,rest:d}=Ke(n,"--pair-code");n=d;let{value:u,rest:h}=Ke(n,"--env");n=h;let{value:x,rest:m}=Ke(n,"--handshake-url");n=m;let{value:_,rest:S}=Ke(n,"--frontier-url");n=S;let{value:y,rest:v}=Ke(n,"--mock-scenario");n=v;let{value:I}=Ke(n,"--agent-id"),A=n.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),_&&(k.frontierUrl=_),y&&(k.mockScenario=y),I&&(k.agentId=I),A&&(k.skipRebuildEnv=!0),k}function V1(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}=Ke(i,"--caption");i=c;let{value:d,rest:u}=Ke(i,"--name");i=u;let{value:h,rest:x}=Ke(i,"--agent-id");i=x;let{value:m,rest:_}=Ke(i,"--session-id");i=_;let{value:S,rest:y}=Ke(i,"--mime");i=y;let v=i.includes("--group-file");i=i.filter(k=>k!=="--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),m&&(A.sessionId=m),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function J1(t){let e=t,{value:n,rest:i}=Ke(e,"--pat-token");e=i;let{value:s,rest:c}=Ke(e,"--env");e=c;let{value:d,rest:u}=Ke(e,"--handshake-url");e=u;let{value:h,rest:x}=Ke(e,"--frontier-url");e=x;let{value:m,rest:_}=Ke(e,"--mock-scenario");e=_;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),m&&(y.mockScenario=m),S&&(y.skipRebuildEnv=!0),y}var Z1=`
129
+ `),M1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
130
+ `);else{let l=t.name??P1(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${l} (uri=${u})
131
+ `)}else process.stdout.write(`Sent ${t.kind} ${l} (${F1(c.bytes)})
132
+ `)}return 0}async function B1(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let l=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await l.text(),f=u?JSON.parse(u):null;return f&&typeof f=="object"&&"ok"in f?f:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${l.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function F1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var vp=H("cli");function Ke(t,e){let{value:r,rest:i}=Pn(t,e);return{value:r,rest:i}}function ga(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
133
+ `)}function cI(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:D}=Ke(e.slice(1),"--agent-id");return D?{mode:"reload",agentId:D}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return dI(e.slice(1));if(e[0]==="log")return{mode:"log",...lp(e.slice(1))};if(e[0]==="connect")return lI(e.slice(1));if(e.includes("--status"))return ga("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ga("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ga("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ga("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:o}=Ke(r,"--pat-token");r=o;let{value:c,rest:l}=Ke(r,"--pair-code");r=l;let{value:u,rest:f}=Ke(r,"--env");r=f;let{value:x,rest:g}=Ke(r,"--handshake-url");r=g;let{value:y,rest:S}=Ke(r,"--frontier-url");r=S;let{value:_,rest:v}=Ke(r,"--mock-scenario");r=v;let{value:I}=Ke(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:c};return u&&(T.env=u),x&&(T.handshakeUrl=x),y&&(T.frontierUrl=y),_&&(T.mockScenario=_),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function dI(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=Ke(i,"--caption");i=c;let{value:l,rest:u}=Ke(i,"--name");i=u;let{value:f,rest:x}=Ke(i,"--agent-id");i=x;let{value:g,rest:y}=Ke(i,"--session-id");i=y;let{value:S,rest:_}=Ke(i,"--mime");i=_;let v=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return o&&(A.caption=o),l&&(A.name=l),f&&(A.agentId=f),g&&(A.sessionId=g),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function lI(t){let e=t,{value:r,rest:i}=Ke(e,"--pat-token");e=i;let{value:o,rest:c}=Ke(e,"--env");e=c;let{value:l,rest:u}=Ke(e,"--handshake-url");e=u;let{value:f,rest:x}=Ke(e,"--frontier-url");e=x;let{value:g,rest:y}=Ke(e,"--mock-scenario");e=y;let S=e.includes("--skip-rebuild-env"),_={mode:"connect"};return r&&(_.privatecode=r),o&&(_.env=o),l&&(_.handshakeUrl=l),f&&(_.frontierUrl=f),g&&(_.mockScenario=g),S&&(_.skipRebuildEnv=!0),_}var uI=`
133
134
  coze-bridge - local bridge daemon for cloud Agent Service
134
135
 
135
136
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -210,57 +211,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
210
211
 
211
212
  Internal:
212
213
  <node> <entry> --daemon daemon mode (OS supervisor only)
213
- `.trimStart();async function Sp(t=process.argv,e={}){let n=$1(t);switch(n.mode){case"help":return process.stdout.write(Z1),0;case"version":return process.stdout.write(`${Ot}
214
- `),0;case"daemon":{try{await Vx()}catch(i){return vp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return Y1(e);case"stop":return Ap(e);case"reload":return e2(n.agentId,e);case"log":return fp(n,e);case"update":return X1(e);case"purge":return n2(e);case"service-install":return r2(e);case"service-uninstall":return i2(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),s2(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),o2(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return hp({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 Ip(t){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(t.pidFile).catch(()=>{}),e(t.portFile).catch(()=>{}),e(t.tokenFile).catch(()=>{})])}async function Y1(t){let e=t.paths??X(),n=new nn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
214
+ `.trimStart();async function Sp(t=process.argv,e={}){let r=cI(t);switch(r.mode){case"help":return process.stdout.write(uI),0;case"version":return process.stdout.write(`${Lt}
215
+ `),0;case"daemon":{try{await Yx()}catch(i){return vp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return fI(e);case"stop":return Ap(e);case"reload":return pI(r.agentId,e);case"log":return hp(r,e);case"update":return hI(e);case"purge":return gI(e);case"service-install":return mI(e);case"service-uninstall":return wI(e);case"pair":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),_I(r.privatecode,r.pairingCode,e,i,r.agentId,r.skipRebuildEnv)}case"connect":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),yI(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return xp({kind:r.kind,path:r.path,...r.agentId?{agentId:r.agentId}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.caption?{caption:r.caption}:{},...r.name?{name:r.name}:{},...r.groupFile?{groupFile:!0}:{},...r.mimeType?{mimeType:r.mimeType}:{},json:r.json},e)}}async function Ip(t){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(t.pidFile).catch(()=>{}),e(t.portFile).catch(()=>{}),e(t.tokenFile).catch(()=>{})])}async function fI(t){let e=t.paths??Y(),r=new en(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
215
216
  `),1;if(i.kind==="stale")return await Ip(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 Ap(t){let e=t.paths??X(),n=new nn(e),i=t.daemonSweep??(async()=>{let h=S0();return await I0(h),h}),s=async()=>{t.skipProcessKill||await i(e)},c=await ls(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
219
- `)}let u=await n.probe();if(u.kind==="not-running")return await s(),process.stdout.write(d?`coze-bridge: stopped
217
+ `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
218
+ ${JSON.stringify(o.body,null,2)}
219
+ `),0}async function Ap(t){let e=t.paths??Y(),r=new en(e),i=t.daemonSweep??(async()=>{let f=I0();return await A0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await ls(t),l=!1;if(c)try{await c.uninstall(),l=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
220
+ `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(l?`coze-bridge: stopped
220
221
  `:`coze-bridge: not running
221
- `),0;if(u.kind==="stale")return await Ip(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 X1(t){return await Ap(t),(t.spawnNpx??Q1)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function Q1(t){return new Promise(e=>{let n=st("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
226
- `),e(1)})})}async function e2(t,e){let n=new nn(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)
222
+ `),0;if(u.kind==="stale")return await Ip(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
223
+ `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
224
+ `),0}catch(f){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
225
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
226
+ `),1)}}async function hI(t){return await Ap(t),(t.spawnNpx??xI)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function xI(t){return new Promise(e=>{let r=it("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
227
+ `),e(1)})})}async function pI(t,e){let r=new en(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
228
+ `),1;try{let o=await r.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let c=o.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
228
229
  `):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 ls(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(yp(),_p)),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??a2,c=t.paths??X();if(n.kind==="connected"){if(!t2(n.body))return n;ut(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=>ut(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await Ep(c.pidFile,s)}let d=t.spawnDaemon??Kx,u=await ls(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;ut(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){ut(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}ut(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 Ep(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)}
230
+ `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
231
+ `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
232
+ `),1}}async function ls(t){if(t.supervisor){let c=t.supervisor,l={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(l,u),uninstall:()=>c.uninstall(l)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Ep(),yp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function kp(t,e){let r=await e.probe();if(r.kind==="connected")return r;let i=t.spawnDaemon??Jx,o=t.waitTimeoutMs??15e3,c=t.sleep??bI,l=t.paths??Y(),u=await ls(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await bp(e,o,c);if(f.kind==="connected")return f;kt(l.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:o})}catch(f){kt(l.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}kt(l.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await EI(l.pidFile,c)}else u&&await u.install({activate:!1}).catch(f=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(f)}
232
233
  `));return process.stdout.write(`coze-bridge: starting daemon...
233
- `),await d({paths:t.paths}),bp(e,i,s)}function t2(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 n2(t){let e=new nn(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 ls(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??X(),{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)}
234
+ `),await i({paths:t.paths}),bp(e,o,c)}async function gI(t){let e=new en(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
235
+ `);try{await e.request({method:"POST",path:"/shutdown"})}catch(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
236
+ `)}await new Promise(l=>setTimeout(l,500))}let i=await ls(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
237
+ `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
238
+ `)}let o=t.paths??Y(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
239
+ `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
239
240
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
240
- `),0}async function r2(t){let e=await ls(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
241
+ `),0}async function mI(t){let e=await ls(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
241
242
  `),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 i2(t){let e=await ls(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 kp(t,e,n){if(e)return ut(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(ut(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(ut(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
- `),ut(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function s2(t,e,n,i={},s,c){let d=new nn(n.paths),u=n.paths??X(),h=await kp(u,c,n.reconstructEnv??Kd);if(await sd(u,h).catch(_=>ut(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(_)})),!n.skipDistInstall){let _=await Xd({paths:n.paths});_.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${_.fromVersion} \u2192 ${_.toVersion}
247
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):_.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${_.libVersion}
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 m={privatecode:t,pairing_code:e};i.env&&(m.env=i.env),i.handshakeUrl&&(m.handshake_url=i.handshakeUrl),i.frontierUrl&&(m.frontier_url=i.frontierUrl),i.mockScenario&&(m.mock_scenario=i.mockScenario),s&&(m.agent_id=s);try{let _=await d.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(_.status===200&&_.body?.ok){let S=_.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
243
+ `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
244
+ `),1}}async function wI(t){let e=await ls(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
245
+ `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
246
+ `),1}}async function Tp(t,e,r){if(e)return kt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(kt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(kt(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
247
+ `),kt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function _I(t,e,r,i={},o,c){let l=new en(r.paths),u=r.paths??Y(),f=await Tp(u,c,r.reconstructEnv??Jd);if(await od(u,f).catch(y=>kt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(y)})),!r.skipDistInstall){let y=await el({paths:r.paths});y.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${y.fromVersion} \u2192 ${y.toVersion}
248
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):y.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${y.libVersion}
249
+ `)}let x=await kp(r,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
250
+ `),1;let g={privatecode:t,pairing_code:e};i.env&&(g.env=i.env),i.handshakeUrl&&(g.handshake_url=i.handshakeUrl),i.frontierUrl&&(g.frontier_url=i.frontierUrl),i.mockScenario&&(g.mock_scenario=i.mockScenario),o&&(g.agent_id=o);try{let y=await l.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(y.status===200&&y.body?.ok){let S=y.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
250
251
  `),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(_.body)}
252
- `),1}catch(_){return process.stderr.write(`coze-bridge: pair failed: ${String(_)}
253
- `),1}}async function o2(t,e,n={},i){let s=e.paths??X(),c=t??await Qo(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 nn(e.paths),u=await kp(s,i,e.reconstructEnv??Kd);if(await sd(s,u).catch(m=>ut(s.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await Xd({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
254
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
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 m=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
257
- `),t!==void 0&&await ss(c,s).catch(_=>vp.warn("writePatToken after connect failed (ignored)",{err:String(_)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
258
- `),1)}catch(m){return process.stderr.write(`coze-bridge: connect failed: ${String(m)}
259
- `),1}}async function 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 Ep(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||!Hi(u))return;await e(i)}}function a2(t){return new Promise(e=>setTimeout(e,t))}ee();function c2(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=c2(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
252
+ `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(y.body)}
253
+ `),1}catch(y){return process.stderr.write(`coze-bridge: pair failed: ${String(y)}
254
+ `),1}}async function yI(t,e,r={},i){let o=e.paths??Y(),c=t??await ta(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let l=new en(e.paths),u=await Tp(o,i,e.reconstructEnv??Jd);if(await od(o,u).catch(g=>kt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await el({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
255
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
256
+ `)}let f=await kp(e,l);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
257
+ `),1;let x={privatecode:c};r.env&&(x.env=r.env),r.handshakeUrl&&(x.handshake_url=r.handshakeUrl),r.frontierUrl&&(x.frontier_url=r.frontierUrl),r.mockScenario&&(x.mock_scenario=r.mockScenario);try{let g=await l.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return g.status===200&&g.body?.ok?(process.stdout.write(`coze-bridge: connected (${g.body.note??"ok"})
258
+ `),t!==void 0&&await os(c,o).catch(y=>vp.warn("writePatToken after connect failed (ignored)",{err:String(y)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
259
+ `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
260
+ `),1}}async function bp(t,e,r){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await r(200)}return t.probe(500)}async function EI(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let l;try{l=await o(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!qi(u))return;await e(i)}}function bI(t){return new Promise(e=>setTimeout(e,t))}ne();function vI(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let r=Number(e[1]),i=Number(e[2]??0);return r<18||r===18&&i<4?"fatal":r<20?"warn":"ok"}function Cp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=vI(t);if(i==="ok")return;let o=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
261
+ `),r(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${o},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
261
262
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
262
263
  npx -y coze-bridge@latest stop
263
264
  npx -y coze-bridge@latest connect
264
265
 
265
- `)}Cp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Sl("warn");Sp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
266
+ `)}Cp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Al("warn");Sp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
266
267
  `),process.exit(1)});