coze-bridge 0.3.1-beta.1 → 0.3.2-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +80 -79
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
|
|
|
5
5
|
const require = __coze_createRequire(import.meta.url);
|
|
6
6
|
const __filename = __coze_fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __coze_dirname(__filename);
|
|
8
|
-
var am=Object.create;var
|
|
8
|
+
var am=Object.create;var Ga=Object.defineProperty;var cm=Object.getOwnPropertyDescriptor;var dm=Object.getOwnPropertyNames;var lm=Object.getPrototypeOf,um=Object.prototype.hasOwnProperty;var pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var it=(t,e)=>()=>(t&&(e=t(t=0)),e);var de=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),qa=(t,e)=>{for(var n in e)Ga(t,n,{get:e[n],enumerable:!0})},fm=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dm(e))!um.call(t,o)&&o!==n&&Ga(t,o,{get:()=>e[o],enumerable:!(i=cm(e,o))||i.enumerable});return t};var Wt=(t,e,n)=>(n=t!=null?am(lm(t)):{},fm(e||!t||!t.__esModule?Ga(n,"default",{value:t,enumerable:!0}):n,t));function Xe(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var fr=it(()=>{"use strict"});import{createWriteStream as hm,mkdirSync as xm,readdirSync as pm,unlinkSync as gm}from"node:fs";import{join as Hl}from"node:path";function Nn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function hr(t,e){return`${t}-${e}.log`}function ja(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function mm(t,e,n){let i=a=>{let[d,u,f]=a.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>n}function ys(t,e,n,i){let o;try{o=pm(t)}catch{return}for(let a of o){let d=ja(a,e);if(d&&mm(d,n,i))try{gm(Hl(t,a))}catch{}}}var li,Wa=it(()=>{"use strict";li=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Nn(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{xm(this.dir,{recursive:!0});let n=hm(Hl(this.dir,hr(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
|
|
9
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&&
|
|
11
|
-
`;_m(t,{recursive:!0}),wm(ym(t,
|
|
12
|
-
`;if(
|
|
13
|
-
`),{cause:a})}}async function
|
|
14
|
-
`,n)}var qt=nt(()=>{"use strict"});import{promises as eu,readdirSync as Hm}from"node:fs";import{homedir as Gm}from"node:os";import{sep as qm,join as Re,resolve as tu}from"node:path";function V(t){let e=t??Gm(),n=Re(e,".coze"),i=Re(n,"bridge"),o=Re(i,"lib"),a=Re(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:Re(o,"index.js"),binDir:Re(i,"bin"),pidFile:Re(i,"bridge.pid"),portFile:Re(i,"bridge.port"),tokenFile:Re(i,"bridge.token"),patTokenFile:Re(i,"pat-token"),agentEnvFile:Re(i,"agent-env.json"),logFile:Re(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:Re(a,"daemon-stdio.log"),installLock:Re(i,"install.lock"),configFile:Re(i,"config.json"),agentsRoot:Re(n,"agents")}}function De(t,e=V()){let n=Re(e.agentsRoot,t);return{root:n,config:Re(n,"config.json"),workspace:Re(n,"workspace"),logs:Re(n,"logs")}}function Is(t=V()){try{return Hm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ui(t,e){let n=await eu.realpath(tu(t)).catch(()=>null);if(!n)return!1;let i=await eu.realpath(tu(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?n.toLowerCase():n,a=process.platform==="win32"?i.toLowerCase():i;return o===a||o.startsWith(a+qm)}var Ae=nt(()=>{"use strict"});var As={};Ha(As,{AGENT_CONFIG_FILE_MODE:()=>ks,enforceAgentConfigMode:()=>Km,loadAgentConfig:()=>Ee,persistAgentSessions:()=>fi,persistAgentSkills:()=>hi,saveAgentConfig:()=>He});import{chmod as jm,stat as Wm}from"node:fs/promises";function Ee(t,e){return fn(De(t,e).config)}function He(t,e){return hn(De(t.agentId,e).config,t,{mode:ks})}async function Km(t,e){if(process.platform==="win32")return;let n=De(t,e).config;try{let i=await Wm(n);if(!i.isFile())return;let o=i.mode&511;o!==ks&&(await jm(n,ks),nu.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;nu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function fi(t,e,n){let i=await Ee(t,n);i&&(i.sessions=Object.fromEntries(e),await He(i,n))}async function hi(t,e,n){let i=await Ee(t,n);i&&(i.skills=e,await He(i,n))}var nu,ks,jt=nt(()=>{"use strict";qt();te();Ae();nu=U("agent-config"),ks=384});var Za=ce((vk,su)=>{su.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Cs=ce(au=>{var ou={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Xm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(n,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(ou))au[t]=Xm(ou[t])});var fu=ce((Ik,uu)=>{var Qm=xe("fs"),Be=xe("path"),cu=Za(),ew=Cs(),tw=typeof process=="object"&&process.platform==="win32",du=t=>typeof t=="object"&&t!==null,lu=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function ve(t){this.sep=Be.sep,this.fs=Qm,du(t)&&du(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}uu.exports=ve;ve.prototype.makeDir=function(t){let e=this;function n(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(a){if(!(!a||a.substr(-1,1)===":")){o+=e.sep+a;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw ew.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};ve.prototype.writeFileTo=function(t,e,n,i){let o=this;if(o.fs.existsSync(t)){if(!n)return!1;var a=o.fs.statSync(t);if(a.isDirectory())return!1}var d=Be.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};ve.prototype.writeFileToAsync=function(t,e,n,i,o){typeof i=="function"&&(o=i,i=void 0);let a=this;a.fs.exists(t,function(d){if(d&&!n)return o(!1);a.fs.stat(t,function(u,h){if(d&&h.isDirectory())return o(!1);var x=Be.dirname(t);a.fs.exists(x,function(g){g||a.makeDir(x),a.fs.open(t,"w",438,function(m,S){m?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(_,v){a.fs.write(v,e,0,e.length,0,function(){a.fs.close(v,function(){a.fs.chmod(t,i||438,function(){o(!0)})})})})}):S?a.fs.write(S,e,0,e.length,0,function(){a.fs.close(S,function(){a.fs.chmod(t,i||438,function(){o(!0)})})}):a.fs.chmod(t,i||438,function(){o(!0)})})})})})};ve.prototype.findFiles=function(t){let e=this;function n(i,o,a){typeof o=="boolean"&&(a=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let h=Be.join(i,u),x=e.fs.statSync(h);(!o||o.test(h))&&d.push(Be.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(d=d.concat(n(h,o,a)))}),d}return n(t,void 0,!0)};ve.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(o,a){if(o)return e(o);let d=a.length;if(!d)return e(null,i);a.forEach(function(u){u=Be.join(t,u),n.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Be.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(g,m){if(g)return e(g);i=i.concat(m),--d||e(null,i)}):--d||e(null,i))})})})};ve.prototype.getAttributes=function(){};ve.prototype.setAttributes=function(){};ve.crc32update=function(t,e){return lu[(t^e)&255]^t>>>8};ve.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=ve.crc32update(n,t[i++]);return~n>>>0};ve.methodToString=function(t){switch(t){case cu.STORED:return"STORED ("+t+")";case cu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ve.canonical=function(t){if(!t)return"";let e=Be.posix.normalize("/"+t.split("\\").join("/"));return Be.join(".",e)};ve.zipnamefix=function(t){if(!t)return"";let e=Be.posix.normalize("/"+t.split("\\").join("/"));return Be.posix.join(".",e)};ve.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let i=n-1;i>=0;i--)if(e(t[i],i,t))return t[i]};ve.sanitize=function(t,e){t=Be.resolve(Be.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var a=Be.normalize(Be.join(t,n.slice(i,o).join(Be.sep)));if(a.indexOf(t)===0)return a}return Be.normalize(Be.join(t,Be.basename(e)))};ve.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};ve.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};ve.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};ve.fromDate2DOS=function(t){let e=0,n=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),n=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|n};ve.isWin=tw;ve.crcTable=lu});var xu=ce((kk,hu)=>{var nw=xe("path");hu.exports=function(t,{fs:e}){var n=t||"",i=a(),o=null;function a(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(o=e.statSync(n),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=nw.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 gu=ce((Ak,pu)=>{pu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var wr=ce((Tk,mr)=>{mr.exports=fu();mr.exports.Constants=Za();mr.exports.Errors=Cs();mr.exports.FileAttr=xu();mr.exports.decoder=gu()});var wu=ce((Ck,mu)=>{var xn=wr(),z=xn.Constants;mu.exports=function(){var t=20,e=10,n=0,i=0,o=0,a=0,d=0,u=0,h=0,x=0,g=0,m=0,S=0,_=0,v=0;t|=xn.isWin?2560:768,n|=z.FLG_EFS;let I={extraLen:0},k=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,P=E=>Math.max(0,E)&255;return o=xn.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return n},set flags(E){n=E},get flags_efs(){return(n&z.FLG_EFS)>0},set flags_efs(E){E?n|=z.FLG_EFS:n&=~z.FLG_EFS},get flags_desc(){return(n&z.FLG_DESC)>0},set flags_desc(E){E?n|=z.FLG_DESC:n&=~z.FLG_DESC},get method(){return i},set method(E){switch(E){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=E},get time(){return xn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=xn.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=k(E)},get timeHighByte(){return P(o>>>8)},get crc(){return a},set crc(E){a=k(E)},get compressedSize(){return d},set compressedSize(E){d=k(E)},get size(){return u},set size(E){u=k(E)},get fileNameLength(){return h},set fileNameLength(E){h=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return g},set commentLength(E){g=E},get diskNumStart(){return m},set diskNumStart(E){m=k(E)},get inAttr(){return S},set inAttr(E){S=k(E)},get attr(){return _},set attr(E){_=k(E)},get fileAttr(){return(_||0)>>16&4095},get offset(){return v},set offset(E){v=k(E)},get encrypted(){return(n&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+x+g},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var R=E.slice(v,v+z.LOCHDR);if(R.readUInt32LE(0)!==z.LOCSIG)throw xn.Errors.INVALID_LOC();I.version=R.readUInt16LE(z.LOCVER),I.flags=R.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=R.readUInt16LE(z.LOCHOW),I.time=R.readUInt32LE(z.LOCTIM),I.crc=R.readUInt32LE(z.LOCCRC),I.compressedSize=R.readUInt32LE(z.LOCSIZ),I.size=R.readUInt32LE(z.LOCLEN),I.fnameLen=R.readUInt16LE(z.LOCNAM),I.extraLen=R.readUInt16LE(z.LOCEXT);let D=v+z.LOCHDR+I.fnameLen,M=D+I.extraLen;return E.slice(D,M)},loadFromBinary:function(E){if(E.length!==z.CENHDR||E.readUInt32LE(0)!==z.CENSIG)throw xn.Errors.INVALID_CEN();t=E.readUInt16LE(z.CENVEM),e=E.readUInt16LE(z.CENVER),n=E.readUInt16LE(z.CENFLG),i=E.readUInt16LE(z.CENHOW),o=E.readUInt32LE(z.CENTIM),a=E.readUInt32LE(z.CENCRC),d=E.readUInt32LE(z.CENSIZ),u=E.readUInt32LE(z.CENLEN),h=E.readUInt16LE(z.CENNAM),x=E.readUInt16LE(z.CENEXT),g=E.readUInt16LE(z.CENCOM),m=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(n,z.LOCFLG),E.writeUInt16LE(i,z.LOCHOW),E.writeUInt32LE(o,z.LOCTIM),E.writeUInt32LE(a,z.LOCCRC),E.writeUInt32LE(d,z.LOCSIZ),E.writeUInt32LE(u,z.LOCLEN),E.writeUInt16LE(h,z.LOCNAM),E.writeUInt16LE(I.extraLen,z.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(z.CENHDR+h+x+g);return E.writeUInt32LE(z.CENSIG,0),E.writeUInt16LE(t,z.CENVEM),E.writeUInt16LE(e,z.CENVER),E.writeUInt16LE(n,z.CENFLG),E.writeUInt16LE(i,z.CENHOW),E.writeUInt32LE(o,z.CENTIM),E.writeUInt32LE(a,z.CENCRC),E.writeUInt32LE(d,z.CENSIZ),E.writeUInt32LE(u,z.CENLEN),E.writeUInt16LE(h,z.CENNAM),E.writeUInt16LE(x,z.CENEXT),E.writeUInt16LE(g,z.CENCOM),E.writeUInt16LE(m,z.CENDSK),E.writeUInt16LE(S,z.CENATT),E.writeUInt32LE(_,z.CENATX),E.writeUInt32LE(v,z.CENOFF),E},toJSON:function(){let E=function(R){return R+" bytes"};return{made:t,version:e,flags:n,method:xn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(h),extraLength:E(x),commentLength:E(g),diskNumStart:m,inAttr:S,attr:_,offset:v,centralHeaderSize:E(z.CENHDR+h+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var yu=ce((Pk,_u)=>{var _r=wr(),_e=_r.Constants;_u.exports=function(){var t=0,e=0,n=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return n},set size(a){n=a},get offset(){return i},set offset(a){i=a},get commentLength(){return o},set commentLength(a){o=a},get mainHeaderSize(){return _e.ENDHDR+o},loadFromBinary:function(a){if((a.length!==_e.ENDHDR||a.readUInt32LE(0)!==_e.ENDSIG)&&(a.length<_e.ZIP64HDR||a.readUInt32LE(0)!==_e.ZIP64SIG))throw _r.Errors.INVALID_END();a.readUInt32LE(0)===_e.ENDSIG?(t=a.readUInt16LE(_e.ENDSUB),e=a.readUInt16LE(_e.ENDTOT),n=a.readUInt32LE(_e.ENDSIZ),i=a.readUInt32LE(_e.ENDOFF),o=a.readUInt16LE(_e.ENDCOM)):(t=_r.readBigUInt64LE(a,_e.ZIP64SUB),e=_r.readBigUInt64LE(a,_e.ZIP64TOT),n=_r.readBigUInt64LE(a,_e.ZIP64SIZE),i=_r.readBigUInt64LE(a,_e.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(_e.ENDHDR+o);return a.writeUInt32LE(_e.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,_e.ENDSUB),a.writeUInt16LE(e,_e.ENDTOT),a.writeUInt32LE(n,_e.ENDSIZ),a.writeUInt32LE(i,_e.ENDOFF),a.writeUInt16LE(o,_e.ENDCOM),a.fill(" ",_e.ENDHDR),a},toJSON:function(){let a=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:a(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Xa=ce(Ya=>{Ya.EntryHeader=wu();Ya.MainHeader=yu()});var Eu=ce((Dk,bu)=>{bu.exports=function(t){var e=xe("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var o=e.createDeflateRaw(n),a=[],d=0;o.on("data",function(u){a.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),h=0;u.fill(0);for(var x=0;x<a.length;x++){var g=a[x];g.copy(u,h),h+=g.length}i&&i(u)}),o.end(t)}}}});var Su=ce((Ok,vu)=>{var rw=+(process.versions?process.versions.node:"").split(".")[0]||0;vu.exports=function(t,e){var n=xe("zlib");let i=rw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var a=n.createInflateRaw(i),d=[],u=0;a.on("data",function(h){d.push(h),u+=h.length}),a.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var g=0;g<d.length;g++){var m=d[g];m.copy(h,x),x+=m.length}o&&o(h)}),a.end(t)}}}});var Cu=ce((Nk,Tu)=>{"use strict";var{randomFillSync:Iu}=xe("crypto"),iw=Cs(),sw=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,ku=(t,e)=>sw[(t^e)&255]^t>>>8,xi=()=>typeof Iu=="function"?Iu(Buffer.alloc(12)):xi.node();xi.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 Ps={genSalt:xi};function Rs(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])}Rs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=ku(e[0],t),e[1]+=e[0]&255,e[1]=Au(e[1],134775813)+1,e[2]=ku(e[2],e[1]>>>24),t};Rs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Au(t,t^1)>>8&255};function ow(t){let e=new Rs(t);return function(n){let i=Buffer.alloc(n.length),o=0;for(let a of n)i[o++]=e.updateKeys(a^e.next());return i}}function aw(t){let e=new Rs(t);return function(n,i,o=0){i||(i=Buffer.alloc(n.length));for(let a of n){let d=e.next();i[o++]=a^d,e.updateKeys(a)}return i}}function cw(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=ow(n),o=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==a)throw iw.WRONG_PASSWORD();return i(t.slice(12))}function dw(t){Buffer.isBuffer(t)&&t.length>=12?Ps.genSalt=function(){return t.slice(0,12)}:t==="node"?Ps.genSalt=xi.node:Ps.genSalt=xi}function lw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=aw(n),a=Ps.genSalt();a[11]=e.crc>>>24&255,i&&(a[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(a,d),o(t,d,12)}Tu.exports={decrypt:cw,encrypt:lw,_salter:dw}});var Pu=ce(Ds=>{Ds.Deflater=Eu();Ds.Inflater=Su();Ds.ZipCrypto=Cu()});var ec=ce((Mk,Ru)=>{var de=wr(),uw=Xa(),Se=de.Constants,Qa=Pu();Ru.exports=function(t,e){var n=new uw.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let g=t,m=typeof g.decoder=="object"?g.decoder:de.decoder;x=m.hasOwnProperty("efs")?m.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(de.crc32(E)!==n.localHeader.crc)return!1}else{let R={},D=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(D)==Se.LOCSIG||e.readUInt32LE(D)==Se.CENSIG)throw de.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==Se.EXTSIG)R.crc=e.readUInt32LE(D+Se.EXTCRC),R.compressedSize=e.readUInt32LE(D+Se.EXTSIZ),R.size=e.readUInt32LE(D+Se.EXTLEN);else if(e.readUInt16LE(D+12)===19280)R.crc=e.readUInt32LE(D+Se.EXTCRC-4),R.compressedSize=e.readUInt32LE(D+Se.EXTSIZ-4),R.size=e.readUInt32LE(D+Se.EXTLEN-4);else throw de.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==n.compressedSize||R.size!==n.size||R.crc!==n.crc)throw de.Errors.DESCRIPTOR_FAULTY();if(de.crc32(E)!==R.crc)return!1}return!0}function v(E,R,D){if(typeof R>"u"&&typeof E=="string"&&(D=E,E=void 0),a)return E&&R&&R(Buffer.alloc(0),de.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var M=S();if(M.length===0)return E&&R&&R(M),M;if(n.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw de.Errors.INVALID_PASS_PARAM();M=Qa.ZipCrypto.decrypt(M,n,D)}var N=Buffer.alloc(n.size);switch(n.method){case de.Constants.STORED:if(M.copy(N),_(N))return E&&R&&R(N),N;throw E&&R&&R(N,de.Errors.BAD_CRC()),de.Errors.BAD_CRC();case de.Constants.DEFLATED:var J=new Qa.Inflater(M,n.size);if(E)J.inflateAsync(function(K){K.copy(K,0),R&&(_(K)?R(K):R(K,de.Errors.BAD_CRC()))});else{if(J.inflate(N).copy(N,0),!_(N))throw de.Errors.BAD_CRC(`"${m.decode(i)}"`);return N}break;default:throw E&&R&&R(Buffer.alloc(0),de.Errors.UNKNOWN_METHOD()),de.Errors.UNKNOWN_METHOD()}}function I(E,R){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&R&&R(S()),S();if(d.length&&!a){var D;switch(n.method){case de.Constants.STORED:return n.compressedSize=n.size,D=Buffer.alloc(d.length),d.copy(D),E&&R&&R(D),D;default:case de.Constants.DEFLATED:var M=new Qa.Deflater(d);if(E)M.deflateAsync(function(J){D=Buffer.alloc(J.length),n.compressedSize=J.length,J.copy(D),R&&R(D)});else{var N=M.deflate();return n.compressedSize=N.length,N}M=null;break}}else if(E&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function k(E,R){return de.readBigUInt64LE(E,R)}function T(E){try{for(var R=0,D,M,N;R+4<E.length;)D=E.readUInt16LE(R),R+=2,M=E.readUInt16LE(R),R+=2,N=E.slice(R,R+M),R+=M,Se.ID_ZIP64===D&&P(N)}catch{throw de.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(E){var R,D,M,N;E.length>=Se.EF_ZIP64_SCOMP&&(R=k(E,Se.EF_ZIP64_SUNCOMP),n.size===Se.EF_ZIP64_OR_32&&(n.size=R)),E.length>=Se.EF_ZIP64_RHO&&(D=k(E,Se.EF_ZIP64_SCOMP),n.compressedSize===Se.EF_ZIP64_OR_32&&(n.compressedSize=D)),E.length>=Se.EF_ZIP64_DSN&&(M=k(E,Se.EF_ZIP64_RHO),n.offset===Se.EF_ZIP64_OR_32&&(n.offset=M)),E.length>=Se.EF_ZIP64_DSN+4&&(N=E.readUInt32LE(Se.EF_ZIP64_DSN),n.diskNumStart===Se.EF_ZIP64_OR_16&&(n.diskNumStart=N))}return{get entryName(){return m.decode(i)},get rawEntryName(){return i},set entryName(E){i=de.toBuffer(E,m.encode);var R=i[i.length-1];a=R===47||R===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,n.extraLength=E.length,T(E)},get comment(){return m.decode(o)},set comment(E){if(o=de.toBuffer(E,m.encode),n.commentLength=o.length,o.length>65535)throw de.Errors.COMMENT_TOO_LONG()},get name(){var E=m.decode(i);return a?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){d=de.toBuffer(E,de.decoder.encode),!a&&d.length?(n.size=d.length,n.method=de.Constants.DEFLATED,n.crc=de.crc32(E),n.changed=!0):n.method=de.Constants.STORED},getData:function(E){return n.changed?d:v(!1,null,E)},getDataAsync:function(E,R){n.changed?E(d):v(!0,E,R)},set attr(E){n.attr=E},get attr(){return n.attr},set header(E){n.loadFromBinary(E)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var E=n.centralHeaderToBinary(),R=de.Constants.CENHDR;return i.copy(E,R),R+=i.length,u.copy(E,R),R+=n.extraLength,o.copy(E,R),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=h.length;let R=n.localHeaderToBinary(),D=Buffer.alloc(R.length+i.length+n.extraLocalLength);return R.copy(D,E),E+=R.length,i.copy(D,E),E+=i.length,h.copy(D,E),E+=h.length,D},toJSON:function(){let E=function(R){return"<"+(R&&R.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Nu=ce((Bk,Ou)=>{var Du=ec(),fw=Xa(),Je=wr();Ou.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),a=new fw.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:g,decoder:m}=x;t?v(x.readEntries):d=!0;function S(){let k=new Set;for(let T of Object.keys(i)){let P=T.split("/");if(P.pop(),!!P.length)for(let E=0;E<P.length;E++){let R=P.slice(0,E+1).join("/")+"/";k.add(R)}}for(let T of k)if(!(T in i)){let P=new Du(x);P.entryName=T,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,h.add(P)}}function _(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Je.Constants.CENHDR)throw Je.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var k=a.offset,T=0;T<n.length;T++){var P=k,E=new Du(x,t);E.header=t.slice(P,P+=Je.Constants.CENHDR),E.entryName=t.slice(P,P+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(P,P+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(P,P+E.header.commentLength)),k+=E.header.centralHeaderSize,n[T]=E,i[E.entryName]=E}h.clear(),S()}function v(k){var T=t.length-Je.Constants.ENDHDR,P=Math.max(0,T-65535),E=P,R=t.length,D=-1,M=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===Je.Constants.ENDSIG){D=T,M=T,R=T+Je.Constants.ENDHDR,E=T-Je.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Je.Constants.END64SIG){E=P;continue}if(t.readUInt32LE(T)===Je.Constants.ZIP64SIG){D=T,R=T+Je.readBigUInt64LE(t,T+Je.Constants.ZIP64SIZE)+Je.Constants.ZIP64LEAD;break}}if(D==-1)throw Je.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(D,R)),a.commentLength&&(o=t.slice(M+Je.Constants.ENDHDR)),k&&_()}function I(){n.length>1&&!g&&n.sort((k,T)=>k.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(k=>!h.has(k))},get comment(){return m.decode(o)},set comment(k){o=Je.toBuffer(k,m.encode),a.commentLength=o.length},getEntryCount:function(){return d?n.length:a.diskEntries},forEach:function(k){this.entries.forEach(k)},getEntry:function(k){return d||_(),i[k]||null},setEntry:function(k){d||_(),n.push(k),i[k.entryName]=k,a.totalEntries=n.length},deleteFile:function(k,T=!0){d||_();let P=i[k];this.getEntryChildren(P,T).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(k){d||_();let T=i[k],P=n.indexOf(T);P>=0&&(n.splice(P,1),delete i[k],a.totalEntries=n.length)},getEntryChildren:function(k,T=!0){if(d||_(),typeof k=="object")if(k.isDirectory&&T){let P=[],E=k.entryName;for(let R of n)R.entryName.startsWith(E)&&P.push(R);return P}else return[k];return[]},getChildCount:function(k){if(k&&k.isDirectory){let T=this.getEntryChildren(k);return T.includes(k)?T.length-1:T.length}return 0},compressToBuffer:function(){d||_(),I();let k=[],T=[],P=0,E=0;a.size=0,a.offset=0;let R=0;for(let N of this.entries){let J=N.getCompressedData();N.header.offset=E;let K=N.packLocalHeader(),se=K.length+J.length;E+=se,k.push(K),k.push(J);let X=N.packCentralHeader();T.push(X),a.size+=X.length,P+=se+X.length,R++}P+=a.mainHeaderSize,a.offset=E,a.totalEntries=R,E=0;let D=Buffer.alloc(P);for(let N of k)N.copy(D,E),E+=N.length;for(let N of T)N.copy(D,E),E+=N.length;let M=a.toBinary();return o&&o.copy(M,Je.Constants.ENDHDR),M.copy(D,E),t=D,d=!1,D},toAsyncBuffer:function(k,T,P,E){try{d||_(),I();let R=[],D=[],M=0,N=0,J=0;a.size=0,a.offset=0;let K=function(se){if(se.length>0){let X=se.shift(),re=X.entryName+X.extra.toString();P&&P(re),X.getCompressedDataAsync(function(ae){E&&E(re),X.header.offset=N;let C=X.packLocalHeader(),F=C.length+ae.length;N+=F,R.push(C),R.push(ae);let H=X.packCentralHeader();D.push(H),a.size+=H.length,M+=F+H.length,J++,K(se)})}else{M+=a.mainHeaderSize,a.offset=N,a.totalEntries=J,N=0;let X=Buffer.alloc(M);R.forEach(function(ae){ae.copy(X,N),N+=ae.length}),D.forEach(function(ae){ae.copy(X,N),N+=ae.length});let re=a.toBinary();o&&o.copy(re,Je.Constants.ENDHDR),re.copy(X,N),t=X,d=!1,k(X)}};K(Array.from(this.entries))}catch(R){T(R)}}}}});var Bu=ce((Fk,Mu)=>{var be=wr(),ye=xe("path"),hw=ec(),xw=Nu(),Ln=(...t)=>be.findLast(t,e=>typeof e=="boolean"),Lu=(...t)=>be.findLast(t,e=>typeof e=="string"),pw=(...t)=>be.findLast(t,e=>typeof e=="function"),gw={noSort:!1,readEntries:!1,method:be.Constants.NONE,fs:null};Mu.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),gw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=be.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new be(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=be.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=be.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw be.Errors.INVALID_FILENAME();let a=new xw(n,i),{canonical:d,sanitize:u,zipnamefix:h}=be;function x(_){if(_&&a){var v;if(typeof _=="string"&&(v=a.getEntry(ye.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(v=a.getEntry(_.entryName)),v)return v}return null}function g(_){let{join:v,normalize:I,sep:k}=ye.posix;return v(ye.isAbsolute(_)?"/":".",I(k+_.split("\\").join(k)+k))}function m(_){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:"",ye.relative(_,v)+I};return{readFile:function(_,v){var I=x(_);return I&&I.getData(v)||null},childCount:function(_){let v=x(_);if(v)return a.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 k=I.getData();if(k&&k.length)return k.toString(v||"utf8")}return""},readAsTextAsync:function(_,v,I){var k=x(_);k?k.getDataAsync(function(T,P){if(P){v(T,P);return}T&&T.length?v(T.toString(I||"utf8")):v("")}):v("")},deleteFile:function(_,v=!0){var I=x(_);I&&a.deleteFile(I.entryName,v)},deleteEntry:function(_){var v=x(_);v&&a.deleteEntry(v.entryName)},addZipComment:function(_){a.comment=_},getZipComment:function(){return a.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,k){if(o.fs.existsSync(_)){v=v?g(v):"";let T=ye.win32.basename(ye.win32.normalize(_));v+=I||T;let P=o.fs.statSync(_),E=P.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);P.isDirectory()&&(v+=o.sep),this.addFile(v,E,k,P)}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,v){_=typeof _=="object"?_:{localPath:_};let I=ye.resolve(_.localPath),{comment:k}=_,{zipPath:T,zipName:P}=_,E=this;o.fs.stat(I,function(R,D){if(R)return v(R,!1);T=T?g(T):"";let M=ye.win32.basename(ye.win32.normalize(I));if(T+=P||M,D.isFile())o.fs.readFile(I,function(N,J){return N?v(N,!1):(E.addFile(T,J,k,D),setImmediate(v,void 0,!0))});else if(D.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),k,D),setImmediate(v,void 0,!0)})},addLocalFolder:function(_,v,I){if(I=m(I),v=v?g(v):"",_=ye.normalize(_),o.fs.existsSync(_)){let k=o.findFiles(_),T=this;if(k.length)for(let P of k){let E=ye.join(v,S(_,P));I(E)&&T.addLocalFile(P,ye.dirname(E))}}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,v,I,k){k=m(k),I=I?g(I):"",_=ye.normalize(_);var T=this;o.fs.open(_,"r",function(P){if(P&&P.code==="ENOENT")v(void 0,be.Errors.FILE_NOT_FOUND(_));else if(P)v(void 0,P);else{var E=o.findFiles(_),R=-1,D=function(){if(R+=1,R<E.length){var M=E[R],N=S(_,M).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),k(N)?o.fs.stat(M,function(J,K){J&&v(void 0,J),K.isFile()?o.fs.readFile(M,function(se,X){se?v(void 0,se):(T.addFile(I+N,X,"",K),D())}):(T.addFile(I+N+"/",Buffer.alloc(0),"",K),D())}):process.nextTick(()=>{D()})}else v(!0,void 0)};D()}})},addLocalFolderAsync2:function(_,v){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=ye.resolve(g(_.localPath));let{zipPath:k,filter:T,namefix:P}=_;T instanceof RegExp?T=(function(D){return function(M){return D.test(M)}})(T):typeof T!="function"&&(T=function(){return!0}),k=k?g(k):"",P=="latin1"&&(P=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=D=>D);let E=D=>ye.join(k,P(S(localPath,D))),R=D=>ye.win32.basename(ye.win32.normalize(P(D)));o.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?v(void 0,be.Errors.FILE_NOT_FOUND(localPath)):D?v(void 0,D):o.findFilesAsync(localPath,function(M,N){if(M)return v(M);N=N.filter(J=>T(E(J))),N.length||v(void 0,!1),setImmediate(N.reverse().reduce(function(J,K){return function(se,X){if(se||X===!1)return setImmediate(J,se,!1);I.addLocalFileAsync({localPath:K,zipPath:ye.dirname(E(K)),zipName:R(K)},J)}},v))})})},addLocalFolderPromise:function(_,v){return new Promise((I,k)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},v),(T,P)=>{T&&k(T),P&&I(this)})})},addFile:function(_,v,I,k){_=h(_);let T=x(_),P=T!=null;P||(T=new hw(i),T.entryName=_),T.comment=I||"";let E=typeof k=="object"&&k instanceof o.fs.Stats;E&&(T.header.time=k.mtime);var R=T.isDirectory?16:0;let D=T.isDirectory?16384:32768;return E?D|=4095&k.mode:typeof k=="number"?D|=4095&k:D|=T.isDirectory?493:420,R=(R|D<<16)>>>0,T.attr=R,T.setData(v),P||a.setEntry(T),T},getEntries:function(_){return a.password=_,a?a.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return a.getEntryCount()},forEach:function(_){return a.forEach(_)},extractEntryTo:function(_,v,I,k,T,P){k=Ln(!1,k),T=Ln(!1,T),I=Ln(!0,I),P=Lu(T,P);var E=x(_);if(!E)throw be.Errors.NO_ENTRY();var R=d(E.entryName),D=u(v,P&&!E.isDirectory?P:I?R:ye.basename(R));if(E.isDirectory){var M=a.getEntryChildren(E);return M.forEach(function(K){if(K.isDirectory)return;var se=K.getData();if(!se)throw be.Errors.CANT_EXTRACT_FILE();var X=d(K.entryName),re=u(v,I?X:ye.basename(X));let ae=T?K.header.fileAttr:void 0;o.writeFileTo(re,se,k,ae)}),!0}var N=E.getData(a.password);if(!N)throw be.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(D)&&!k)throw be.Errors.CANT_OVERRIDE();let J=T?_.header.fileAttr:void 0;return o.writeFileTo(D,N,k,J),!0},test:function(_){if(!a)return!1;for(var v in a.entries)try{if(v.isDirectory)continue;var I=a.entries[v].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,v,I,k){if(I=Ln(!1,I),k=Lu(I,k),v=Ln(!1,v),!a)throw be.Errors.NO_ZIP();a.entries.forEach(function(T){var P=u(_,d(T.entryName));if(T.isDirectory){o.makeDir(P);return}var E=T.getData(k);if(!E)throw be.Errors.CANT_EXTRACT_FILE();let R=I?T.header.fileAttr:void 0;o.writeFileTo(P,E,v,R);try{o.fs.utimesSync(P,T.header.time,T.header.time)}catch{throw be.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,v,I,k){if(k=pw(v,I,k),I=Ln(!1,I),v=Ln(!1,v),!k)return new Promise((D,M)=>{this.extractAllToAsync(_,v,I,function(N){N?M(N):D(this)})});if(!a){k(be.Errors.NO_ZIP());return}_=ye.resolve(_);let T=D=>u(_,ye.normalize(d(D.entryName))),P=(D,M)=>new Error(D+': "'+M+'"'),E=[],R=[];a.entries.forEach(D=>{D.isDirectory?E.push(D):R.push(D)});for(let D of E){let M=T(D),N=I?D.header.fileAttr:void 0;try{o.makeDir(M),N&&o.fs.chmodSync(M,N),o.fs.utimesSync(M,D.header.time,D.header.time)}catch{k(P("Unable to create folder",M))}}R.reverse().reduce(function(D,M){return function(N){if(N)D(N);else{let J=ye.normalize(d(M.entryName)),K=u(_,J);M.getDataAsync(function(se,X){if(X)D(X);else if(!se)D(be.Errors.CANT_EXTRACT_FILE());else{let re=I?M.header.fileAttr:void 0;o.writeFileToAsync(K,se,v,re,function(ae){ae||D(P("Unable to write file",K)),o.fs.utimes(K,M.header.time,M.header.time,function(C){C?D(P("Unable to set times",K)):D()})})}})}}},k)()},writeZip:function(_,v){if(arguments.length===1&&typeof _=="function"&&(v=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=a.compressToBuffer();if(I){var k=o.writeFileTo(_,I,!0);typeof v=="function"&&v(k?null:new Error("failed"),"")}}},writeZipPromise:function(_,v){let{overwrite:I,perm:k}=Object.assign({overwrite:!0},v);return new Promise((T,P)=>{!_&&i.filename&&(_=i.filename),_||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let R=D=>D?T(D):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,E,I,k,R)},P)})},toBufferPromise:function(){return new Promise((_,v)=>{a.toAsyncBuffer(_,v)})},toBuffer:function(_,v,I,k){return typeof _=="function"?(a.toAsyncBuffer(_,v,I,k),null):a.compressToBuffer()}}}});import{execFile as Sy,spawn as Iy,spawnSync as nT}from"node:child_process";import{promisify as ky}from"node:util";function Ty(t){if(process.platform!=="win32")return!1;if(s0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(s0,"").toLowerCase();return Ay.has(n)}function o0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return Ty(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function st(t,e=[],n={}){return Iy(t,e,o0(t,n))}function a0(t,e=[],n={}){return Cy(t,e,o0(t,n))}var Ay,s0,Cy,Yt=nt(()=>{"use strict";Ay=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),s0=/\.(cmd|bat|ps1)$/i;Cy=ky(Sy)});var en=ce((hD,ix)=>{"use strict";var nx=["nodebuffer","arraybuffer","fragments"],rx=typeof Blob<"u";rx&&nx.push("blob");ix.exports={BINARY_TYPES:nx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:rx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var rs=ce((xD,Ko)=>{"use strict";var{EMPTY_BUFFER:Wv}=en(),Ld=Buffer[Symbol.species];function Kv(t,e){if(t.length===0)return Wv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let a=t[o];n.set(a,i),i+=a.length}return i<e?new Ld(n.buffer,n.byteOffset,i):n}function sx(t,e,n,i,o){for(let a=0;a<o;a++)n[i+a]=t[a]^e[a&3]}function ox(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function $v(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 Ld(t):ArrayBuffer.isView(t)?e=new Ld(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Md.readOnly=!1),e}Ko.exports={concat:Kv,mask:sx,toArrayBuffer:$v,toBuffer:Md,unmask:ox};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");Ko.exports.mask=function(e,n,i,o,a){a<48?sx(e,n,i,o,a):t.mask(e,n,i,o,a)},Ko.exports.unmask=function(e,n){e.length<32?ox(e,n):t.unmask(e,n)}}catch{}});var dx=ce((pD,cx)=>{"use strict";var ax=Symbol("kDone"),Bd=Symbol("kRun"),Fd=class{constructor(e){this[ax]=()=>{this.pending--,this[Bd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Bd]()}[Bd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ax])}}};cx.exports=Fd});var Jr=ce((gD,hx)=>{"use strict";var is=xe("zlib"),lx=rs(),Vv=dx(),{kStatusCode:ux}=en(),Jv=Buffer[Symbol.species],Zv=Buffer.from([0,0,255,255]),Vo=Symbol("permessage-deflate"),tn=Symbol("total-length"),$r=Symbol("callback"),Pn=Symbol("buffers"),Vr=Symbol("error"),$o,zd=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,!$o){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;$o=new Vv(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[$r];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let o=n[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=a}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=o})}),e}decompress(e,n,i){$o.add(o=>{this._decompress(e,n,(a,d)=>{o(),i(a,d)})})}compress(e,n,i){$o.add(o=>{this._compress(e,n,(a,d)=>{o(),i(a,d)})})}_decompress(e,n,i){let o=this._isServer?"client":"server";if(!this._inflate){let a=`${o}_max_window_bits`,d=typeof this.params[a]!="number"?is.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=is.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Vo]=this,this._inflate[tn]=0,this._inflate[Pn]=[],this._inflate.on("error",Xv),this._inflate.on("data",fx)}this._inflate[$r]=i,this._inflate.write(e),n&&this._inflate.write(Zv),this._inflate.flush(()=>{let a=this._inflate[Vr];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=lx.concat(this._inflate[Pn],this._inflate[tn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[tn]=0,this._inflate[Pn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let o=this._isServer?"server":"client";if(!this._deflate){let a=`${o}_max_window_bits`,d=typeof this.params[a]!="number"?is.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=is.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[tn]=0,this._deflate[Pn]=[],this._deflate.on("data",Yv)}this._deflate[$r]=i,this._deflate.write(e),this._deflate.flush(is.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=lx.concat(this._deflate[Pn],this._deflate[tn]);n&&(a=new Jv(a.buffer,a.byteOffset,a.length-4)),this._deflate[$r]=null,this._deflate[tn]=0,this._deflate[Pn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};hx.exports=zd;function Yv(t){this[Pn].push(t),this[tn]+=t.length}function fx(t){if(this[tn]+=t.length,this[Vo]._maxPayload<1||this[tn]<=this[Vo]._maxPayload){this[Pn].push(t);return}this[Vr]=new RangeError("Max payload size exceeded"),this[Vr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Vr][ux]=1009,this.removeListener("data",fx),this.reset()}function Xv(t){if(this[Vo]._inflate=null,this[Vr]){this[$r](this[Vr]);return}t[ux]=1007,this[$r](t)}});var Zr=ce((mD,Jo)=>{"use strict";var{isUtf8:xx}=xe("buffer"),{hasBlob:Qv}=en(),eS=[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 tS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ud(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 nS(t){return Qv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Jo.exports={isBlob:nS,isValidStatusCode:tS,isValidUTF8:Ud,tokenChars:eS};if(xx)Jo.exports.isValidUTF8=function(t){return t.length<24?Ud(t):xx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");Jo.exports.isValidUTF8=function(e){return e.length<32?Ud(e):t(e)}}catch{}});var Wd=ce((wD,Ex)=>{"use strict";var{Writable:rS}=xe("stream"),px=Jr(),{BINARY_TYPES:iS,EMPTY_BUFFER:gx,kStatusCode:sS,kWebSocket:oS}=en(),{concat:Hd,toArrayBuffer:aS,unmask:cS}=rs(),{isValidStatusCode:dS,isValidUTF8:mx}=Zr(),Zo=Buffer[Symbol.species],gt=0,_x=1,yx=2,bx=3,Gd=4,qd=5,Yo=6,jd=class extends rS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||iS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[oS]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=gt}_write(e,n,i){if(this._opcode===8&&this._state==gt)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Zo(i.buffer,i.byteOffset+e,i.length-e),new Zo(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=n.length-e;e>=i.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new Zo(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 gt:this.getInfo(e);break;case _x:this.getPayloadLength16(e);break;case yx:this.getPayloadLength64(e);break;case bx:this.getMask();break;case Gd:this.getData(e);break;case qd:case Yo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(n[0]&64)===64;if(i&&!this._extensions[px.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=_x:this._payloadLength===127?this._state=yx:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=bx:this._state=Gd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Gd}getData(e){let n=gx;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&&cS(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=qd,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[px.extensionName].decompress(e,this._fin,(o,a)=>{if(o)return n(o);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(d);return}this._fragments.push(a)}this.dataMessage(n),this._state===gt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=gt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Hd(i,n):this._binaryType==="arraybuffer"?o=aS(Hd(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=gt):(this._state=Yo,setImmediate(()=>{this.emit("message",o,!0),this._state=gt,this.startLoop(e)}))}else{let o=Hd(i,n);if(!this._skipUTF8Validation&&!mx(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===qd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=gt):(this._state=Yo,setImmediate(()=>{this.emit("message",o,!1),this._state=gt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,gx),this.end();else{let i=e.readUInt16BE(0);if(!dS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let o=new Zo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!mx(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(a);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=gt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=gt):(this._state=Yo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=gt,this.startLoop(n)}))}createError(e,n,i,o,a){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=a,d[sS]=o,d}};Ex.exports=jd});var Vd=ce((yD,Ix)=>{"use strict";var{Duplex:_D}=xe("stream"),{randomFillSync:lS}=xe("crypto"),vx=Jr(),{EMPTY_BUFFER:uS,kWebSocket:fS,NOOP:hS}=en(),{isBlob:Yr,isValidStatusCode:xS}=Zr(),{mask:Sx,toBuffer:tr}=rs(),mt=Symbol("kByteLength"),pS=Buffer.alloc(4),Xo=8*1024,nr,Xr=Xo,kt=0,gS=1,mS=2,Kd=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=kt,this.onerror=hS,this[fS]=void 0}static frame(e,n){let i,o=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||pS,n.generateMask?n.generateMask(i):(Xr===Xo&&(nr===void 0&&(nr=Buffer.alloc(Xo)),lS(nr,0,Xo),Xr=0),i[0]=nr[Xr++],i[1]=nr[Xr++],i[2]=nr[Xr++],i[3]=nr[Xr++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[mt]!==void 0?u=n[mt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=n.mask&&n.readOnly&&!d);let h=u;u>=65536?(a+=8,h=127):u>125&&(a+=2,h=126);let x=Buffer.allocUnsafe(o?u+a:a);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[a-4]=i[0],x[a-3]=i[1],x[a-2]=i[2],x[a-1]=i[3],d?[x,e]:o?(Sx(e,i,x,a,u),[x]):(Sx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,o){let a;if(e===void 0)a=uS;else{if(typeof e!="number"||!xS(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");a=Buffer.allocUnsafe(2+u),a.writeUInt16BE(e,0),typeof n=="string"?a.write(n,2):a.set(n,2)}}let d={[mt]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==kt?this.enqueue([this.dispatch,a,!1,d,o]):this.sendFrame(t.frame(a,d),o)}ping(e,n,i){let o,a;if(typeof e=="string"?(o=Buffer.byteLength(e),a=!1):Yr(e)?(o=e.size,a=!1):(e=tr(e),o=e.length,a=tr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[mt]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};Yr(e)?this._state!==kt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==kt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let o,a;if(typeof e=="string"?(o=Buffer.byteLength(e),a=!1):Yr(e)?(o=e.size,a=!1):(e=tr(e),o=e.length,a=tr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[mt]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};Yr(e)?this._state!==kt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==kt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[vx.extensionName],a=n.binary?2:1,d=n.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):Yr(e)?(u=e.size,h=!1):(e=tr(e),u=e.length,h=tr.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[mt]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:h,rsv1:d};Yr(e)?this._state!==kt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==kt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[mt],this._state=mS,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick($d,this,u,o);return}this._bufferedBytes-=i[mt];let d=tr(a);n?this.dispatch(d,n,i,o):(this._state=kt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(a=>{process.nextTick(wS,this,a,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let a=this._extensions[vx.extensionName];this._bufferedBytes+=i[mt],this._state=gS,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");$d(this,h,o);return}this._bufferedBytes-=i[mt],this._state=kt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===kt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][mt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][mt],this._queue.push(e)}sendFrame(e,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)}};Ix.exports=Kd;function $d(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],a=o[o.length-1];typeof a=="function"&&a(e)}}function wS(t,e,n){$d(t,e,n),t.onerror(e)}});var Nx=ce((bD,Ox)=>{"use strict";var{kForOnEventAttribute:ss,kListener:Jd}=en(),kx=Symbol("kCode"),Ax=Symbol("kData"),Tx=Symbol("kError"),Cx=Symbol("kMessage"),Px=Symbol("kReason"),Qr=Symbol("kTarget"),Rx=Symbol("kType"),Dx=Symbol("kWasClean"),nn=class{constructor(e){this[Qr]=null,this[Rx]=e}get target(){return this[Qr]}get type(){return this[Rx]}};Object.defineProperty(nn.prototype,"target",{enumerable:!0});Object.defineProperty(nn.prototype,"type",{enumerable:!0});var rr=class extends nn{constructor(e,n={}){super(e),this[kx]=n.code===void 0?0:n.code,this[Px]=n.reason===void 0?"":n.reason,this[Dx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[kx]}get reason(){return this[Px]}get wasClean(){return this[Dx]}};Object.defineProperty(rr.prototype,"code",{enumerable:!0});Object.defineProperty(rr.prototype,"reason",{enumerable:!0});Object.defineProperty(rr.prototype,"wasClean",{enumerable:!0});var ei=class extends nn{constructor(e,n={}){super(e),this[Tx]=n.error===void 0?null:n.error,this[Cx]=n.message===void 0?"":n.message}get error(){return this[Tx]}get message(){return this[Cx]}};Object.defineProperty(ei.prototype,"error",{enumerable:!0});Object.defineProperty(ei.prototype,"message",{enumerable:!0});var os=class extends nn{constructor(e,n={}){super(e),this[Ax]=n.data===void 0?null:n.data}get data(){return this[Ax]}};Object.defineProperty(os.prototype,"data",{enumerable:!0});var _S={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[ss]&&o[Jd]===e&&!o[ss])return;let i;if(t==="message")i=function(a,d){let u=new os("message",{data:d?a:a.toString()});u[Qr]=this,Qo(e,this,u)};else if(t==="close")i=function(a,d){let u=new rr("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Qr]=this,Qo(e,this,u)};else if(t==="error")i=function(a){let d=new ei("error",{error:a,message:a.message});d[Qr]=this,Qo(e,this,d)};else if(t==="open")i=function(){let a=new nn("open");a[Qr]=this,Qo(e,this,a)};else return;i[ss]=!!n[ss],i[Jd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Jd]===e&&!n[ss]){this.removeListener(t,n);break}}};Ox.exports={CloseEvent:rr,ErrorEvent:ei,Event:nn,EventTarget:_S,MessageEvent:os};function Qo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var ea=ce((ED,Lx)=>{"use strict";var{tokenChars:as}=Zr();function Ft(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function yS(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,a=!1,d,u,h=-1,x=-1,g=-1,m=0;for(;m<t.length;m++)if(x=t.charCodeAt(m),d===void 0)if(g===-1&&as[x]===1)h===-1&&(h=m);else if(m!==0&&(x===32||x===9))g===-1&&h!==-1&&(g=m);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let _=t.slice(h,g);x===44?(Ft(e,_,n),n=Object.create(null)):d=_,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(u===void 0)if(g===-1&&as[x]===1)h===-1&&(h=m);else if(x===32||x===9)g===-1&&h!==-1&&(g=m);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m),Ft(n,t.slice(h,g),!0),x===44&&(Ft(e,d,n),n=Object.create(null),d=void 0),h=g=-1}else if(x===61&&h!==-1&&g===-1)u=t.slice(h,m),h=g=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(o){if(as[x]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);h===-1?h=m:i||(i=!0),o=!1}else if(a)if(as[x]===1)h===-1&&(h=m);else if(x===34&&h!==-1)a=!1,g=m;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(x===34&&t.charCodeAt(m-1)===61)a=!0;else if(g===-1&&as[x]===1)h===-1&&(h=m);else if(h!==-1&&(x===32||x===9))g===-1&&(g=m);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let _=t.slice(h,g);i&&(_=_.replace(/\\/g,""),i=!1),Ft(n,u,_),x===44&&(Ft(e,d,n),n=Object.create(null),d=void 0),u=void 0,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(h===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=m);let S=t.slice(h,g);return d===void 0?Ft(e,S,n):(u===void 0?Ft(n,S,!0):i?Ft(n,u,S.replace(/\\/g,"")):Ft(n,u,S),Ft(e,d,n)),e}function bS(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(o=>{let a=i[o];return Array.isArray(a)||(a=[a]),a.map(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Lx.exports={format:bS,parse:yS}});var ia=ce((ID,$x)=>{"use strict";var ES=xe("events"),vS=xe("https"),SS=xe("http"),Fx=xe("net"),IS=xe("tls"),{randomBytes:kS,createHash:AS}=xe("crypto"),{Duplex:vD,Readable:SD}=xe("stream"),{URL:Zd}=xe("url"),Rn=Jr(),TS=Wd(),CS=Vd(),{isBlob:PS}=Zr(),{BINARY_TYPES:Mx,CLOSE_TIMEOUT:RS,EMPTY_BUFFER:ta,GUID:DS,kForOnEventAttribute:Yd,kListener:OS,kStatusCode:NS,kWebSocket:Ke,NOOP:zx}=en(),{EventTarget:{addEventListener:LS,removeEventListener:MS}}=Nx(),{format:BS,parse:FS}=ea(),{toBuffer:zS}=rs(),Ux=Symbol("kAborted"),Xd=[8,13],rn=["CONNECTING","OPEN","CLOSING","CLOSED"],US=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends ES{constructor(e,n,i){super(),this._binaryType=Mx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ta,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]),Hx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Mx.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let o=new TS({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new CS(e,this._extensions,i.generateMask);this._receiver=o,this._sender=a,this._socket=e,o[Ke]=this,a[Ke]=this,e[Ke]=this,o.on("conclude",qS),o.on("drain",jS),o.on("error",WS),o.on("message",KS),o.on("ping",$S),o.on("pong",VS),a.onerror=JS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",jx),e.on("data",ra),e.on("end",Wx),e.on("error",Kx),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())}),qx(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){Qd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ta,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){Qd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ta,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){Qd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Rn.extensionName]||(o.compress=!1),this._sender.send(e||ta,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(me,"CONNECTING",{enumerable:!0,value:rn.indexOf("CONNECTING")});Object.defineProperty(me.prototype,"CONNECTING",{enumerable:!0,value:rn.indexOf("CONNECTING")});Object.defineProperty(me,"OPEN",{enumerable:!0,value:rn.indexOf("OPEN")});Object.defineProperty(me.prototype,"OPEN",{enumerable:!0,value:rn.indexOf("OPEN")});Object.defineProperty(me,"CLOSING",{enumerable:!0,value:rn.indexOf("CLOSING")});Object.defineProperty(me.prototype,"CLOSING",{enumerable:!0,value:rn.indexOf("CLOSING")});Object.defineProperty(me,"CLOSED",{enumerable:!0,value:rn.indexOf("CLOSED")});Object.defineProperty(me.prototype,"CLOSED",{enumerable:!0,value:rn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(me.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(me.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Yd])return e[OS];return null},set(e){for(let n of this.listeners(t))if(n[Yd]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Yd]:!0})}})});me.prototype.addEventListener=LS;me.prototype.removeEventListener=MS;$x.exports=me;function Hx(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:RS,protocolVersion:Xd[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,!Xd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Xd.join(", ")})`);let a;if(e instanceof Zd)a=e;else try{a=new Zd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),t._url=a.href;let d=a.protocol==="wss:",u=a.protocol==="ws+unix:",h;if(a.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!a.pathname?h="The URL's pathname is empty":a.hash&&(h="The URL contains a fragment identifier"),h){let I=new SyntaxError(h);if(t._redirects===0)throw I;na(t,I);return}let x=d?443:80,g=kS(16).toString("base64"),m=d?vS.request:SS.request,S=new Set,_;if(o.createConnection=o.createConnection||(d?GS:HS),o.defaultPort=o.defaultPort||x,o.port=a.port||x,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Rn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=BS({[Rn.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!US.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:a.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[k,T]of Object.entries(I))i.headers[k.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),v=t._req=m(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=m(o);o.timeout&&v.on("timeout",()=>{dt(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[Ux]||(v=t._req=null,na(t,I))}),v.on("response",I=>{let k=I.headers.location,T=I.statusCode;if(k&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){dt(t,v,"Maximum redirects exceeded");return}v.abort();let P;try{P=new Zd(k,e)}catch{let R=new SyntaxError(`Invalid URL: ${k}`);na(t,R);return}Hx(t,P,n,i)}else t.emit("unexpected-response",v,I)||dt(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,k,T)=>{if(t.emit("upgrade",I),t.readyState!==me.CONNECTING)return;v=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){dt(t,k,"Invalid Upgrade header");return}let E=AS("sha1").update(g+DS).digest("base64");if(I.headers["sec-websocket-accept"]!==E){dt(t,k,"Invalid Sec-WebSocket-Accept header");return}let R=I.headers["sec-websocket-protocol"],D;if(R!==void 0?S.size?S.has(R)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":S.size&&(D="Server sent no subprotocol"),D){dt(t,k,D);return}R&&(t._protocol=R);let M=I.headers["sec-websocket-extensions"];if(M!==void 0){if(!_){dt(t,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=FS(M)}catch{dt(t,k,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(N);if(J.length!==1||J[0]!==Rn.extensionName){dt(t,k,"Server indicated an extension that was not requested");return}try{_.accept(N[Rn.extensionName])}catch{dt(t,k,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Rn.extensionName]=_}t.setSocket(k,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(v,t):v.end()}function na(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function HS(t){return t.path=t.socketPath,Fx.connect(t)}function GS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Fx.isIP(t.host)?"":t.host),IS.connect(t)}function dt(t,e,n){t._readyState=me.CLOSING;let i=new Error(n);Error.captureStackTrace(i,dt),e.setHeader?(e[Ux]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(na,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Qd(t,e,n){if(e){let i=PS(e)?e.size:zS(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${rn[t.readyState]})`);process.nextTick(n,i)}}function qS(t,e){let n=this[Ke];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Ke]!==void 0&&(n._socket.removeListener("data",ra),process.nextTick(Gx,n._socket),t===1005?n.close():n.close(t,e))}function jS(){let t=this[Ke];t.isPaused||t._socket.resume()}function WS(t){let e=this[Ke];e._socket[Ke]!==void 0&&(e._socket.removeListener("data",ra),process.nextTick(Gx,e._socket),e.close(t[NS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Bx(){this[Ke].emitClose()}function KS(t,e){this[Ke].emit("message",t,e)}function $S(t){let e=this[Ke];e._autoPong&&e.pong(t,!this._isServer,zx),e.emit("ping",t)}function VS(t){this[Ke].emit("pong",t)}function Gx(t){t.resume()}function JS(t){let e=this[Ke];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,qx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function qx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function jx(){let t=this[Ke];if(this.removeListener("close",jx),this.removeListener("data",ra),this.removeListener("end",Wx),t._readyState=me.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Ke]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Bx),t._receiver.on("finish",Bx))}function ra(t){this[Ke]._receiver.write(t)||this.pause()}function Wx(){let t=this[Ke];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function Kx(){let t=this[Ke];this.removeListener("error",Kx),this.on("error",zx),t&&(t._readyState=me.CLOSING,this.destroy())}});var Yx=ce((AD,Zx)=>{"use strict";var kD=ia(),{Duplex:ZS}=xe("stream");function Vx(t){t.emit("close")}function YS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Jx(t){this.removeListener("error",Jx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function XS(t,e){let n=!0,i=new ZS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,d){let u=!d&&i._readableState.objectMode?a.toString():a;i.push(u)||t.pause()}),t.once("error",function(a){i.destroyed||(n=!1,i.destroy(a))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,a){if(t.readyState===t.CLOSED){a(o),process.nextTick(Vx,i);return}let d=!1;t.once("error",function(h){d=!0,a(h)}),t.once("close",function(){d||a(o),process.nextTick(Vx,i)}),n&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,a,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,a,d)});return}t.send(o,d)},i.on("end",YS),i.on("error",Jx),i}Zx.exports=XS});var el=ce((TD,Xx)=>{"use strict";var{tokenChars:QS}=Zr();function e1(t){let e=new Set,n=-1,i=-1,o=0;for(o;o<t.length;o++){let d=t.charCodeAt(o);if(i===-1&&QS[d]===1)n===-1&&(n=o);else if(o!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=o);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let a=t.slice(n,o);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return e.add(a),e}Xx.exports={parse:e1}});var sp=ce((PD,ip)=>{"use strict";var t1=xe("events"),sa=xe("http"),{Duplex:CD}=xe("stream"),{createHash:n1}=xe("crypto"),Qx=ea(),ir=Jr(),r1=el(),i1=ia(),{CLOSE_TIMEOUT:s1,GUID:o1,kWebSocket:a1}=en(),c1=/^[+/0-9A-Za-z]{22}==$/,ep=0,tp=1,rp=2,tl=class extends t1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:s1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:i1,...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=sa.createServer((i,o)=>{let a=sa.STATUS_CODES[426];o.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),o.end(a)}),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=d1(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,a,d)=>{this.handleUpgrade(o,a,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ep}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===rp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(cs,this);return}if(e&&this.once("close",e),this._state!==tp)if(this._state=tp,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(cs,this):process.nextTick(cs,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{cs(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,o){n.on("error",np);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){sr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){sr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!c1.test(a)){sr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){sr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ds(n,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=r1.parse(h)}catch{sr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&g!==void 0){let S=new ir({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Qx.parse(g);_[ir.extensionName]&&(S.accept(_[ir.extensionName]),m[ir.extensionName]=S)}catch{sr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(S,(_,v,I,k)=>{if(!_)return ds(n,v||401,I,k);this.completeUpgrade(m,a,x,e,n,i,o)});return}if(!this.options.verifyClient(S))return ds(n,401)}this.completeUpgrade(m,a,x,e,n,i,o)}completeUpgrade(e,n,i,o,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[a1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ep)return ds(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${n1("sha1").update(n+o1).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;m&&(x.push(`Sec-WebSocket-Protocol: ${m}`),g._protocol=m)}if(e[ir.extensionName]){let m=e[ir.extensionName].params,S=Qx.format({[ir.extensionName]:[m]});x.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",x,o),a.write(x.concat(`\r
|
|
10
|
+
`),this.stream=void 0;return}this.currentDate!==void 0&&ys(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 wm,mkdirSync as _m}from"node:fs";import{join as ym}from"node:path";function ql(t){let e=t.retentionDays??vm,n=t.clock??(()=>Nn(new Date));Es={bridgeSink:new li(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new li(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();ys(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])ys(t.agentLogsDir(o),"agent",i,e)}function Sm(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function jl(t){Ka=t}function Wl(t){return xr[Ka]<=xr[t]}function Kl(t,e){let n=xr[t];return n===void 0?!0:n>=xr[e]}function vs(t){Gl={...t}}function $l(t){let e=(u,f=2)=>String(u).padStart(f,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",o=Math.abs(n),a=e(Math.floor(o/60)),d=e(o%60);return`${Nn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function st(t,e,n,i,o){try{let a=`${JSON.stringify({ts:$l(new Date),level:e,module:n,msg:i,...o})}
|
|
11
|
+
`;_m(t,{recursive:!0}),wm(ym(t,hr("bridge",Nn(new Date))),a)}catch{}}function Im(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function bs(t,e,n,i,o){if(xr[t]<xr[Ka])return;let a=`${JSON.stringify({ts:$l(new Date),level:t,module:e,msg:n,...Gl,...i})}
|
|
12
|
+
`;if(Es){let d=Im(o,i),u=d?Sm(Es,d):Es.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?Em.write(a):bm.write(a)}function G(t,e){return{debug:(n,i)=>bs("debug",t,n,i,e),info:(n,i)=>bs("info",t,n,i,e),warn:(n,i)=>bs("warn",t,n,i,e),error:(n,i)=>bs("error",t,n,i,e),child:n=>G(`${t}.${n}`,e),forAgent:n=>G(t,n)}}var xr,Ka,bm,Em,Gl,vm,Es,te=it(()=>{"use strict";fr();Wa();xr={debug:10,info:20,warn:30,error:40},Ka=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),bm=process.stdout,Em=process.stderr,Gl={},vm=Xe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Es=null});var A,Je=it(()=>{"use strict";A=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 Yl={};qa(Yl,{ACP_WRAPPER_NPM_PACKAGES:()=>Is,_resetAcpInstallerForTests:()=>Pm,_setBinaryPathCacheForTests:()=>Dm,buildAcpSpawn:()=>ui,ensureAcpInstalled:()=>gr,getAcpBinaryPath:()=>As,pickWhichLine:()=>Za,probeAcpVersion:()=>Rm,resolveAcpCommand:()=>Jl});import{readFileSync as Vl}from"node:fs";import{createRequire as Am}from"node:module";import{dirname as km,resolve as Tm}from"node:path";function Va(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Za(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=i=>e.find(o=>o.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function Cm(t){let e=Zl.resolve(`${t.npmPackage}/package.json`),n=km(e),i=JSON.parse(Vl(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 Tm(n,o)}async function gr(t,e){let n=$a[t];if(!n)throw new A("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=pr.get(t);if(i)return i;let o=Va(t);if(o)return pr.set(t,o),Ss.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let a=Cm(n);return pr.set(t,a),Ss.info("acp wrapper resolved",{framework:t,binary:n.binary,path:a}),a}catch(a){throw Ss.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(a)}),new A("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:a})}}async function Rm(t){let e=$a[t];if(e)try{let n=Zl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Vl(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Ss.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function As(t){return pr.get(t)}function Jl(t,e){if(e)return e;let n=Va(t);if(n)return n;let i=As(t);if(!i)throw new A("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function ui(t,e,n){if(e)return{command:e,args:[...n]};let i=Va(t);if(i)return{command:i,args:[...n]};let o=Jl(t);return{command:process.execPath,args:[o,...n]}}function Pm(){pr.clear()}function Dm(t,e){pr.set(t,e)}var Ss,$a,Is,Zl,pr,fn=it(()=>{"use strict";Je();te();Ss=G("agents.acp-installer"),$a={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Is=Object.values($a).filter(t=>t!==void 0).map(t=>t.npmPackage),Zl=Am(import.meta.url),pr=new Map});import{chmod as Lm,mkdir as Nm,readFile as Mm,rename as Bm,rm as Fm,writeFile as zm}from"node:fs/promises";import{dirname as Um}from"node:path";async function hn(t){try{let e=await Mm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ct(t,e,n){await Nm(Um(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await zm(i,e,{encoding:"utf8",mode:n?.mode}),await Bm(i,t),n?.mode!==void 0&&await Lm(t,n.mode)}catch(o){throw await Fm(i,{force:!0}).catch(()=>{}),o}}async function xn(t,e,n){await ct(t,`${JSON.stringify(e,null,2)}
|
|
14
|
+
`,n)}var Kt=it(()=>{"use strict"});import{promises as eu,readdirSync as Hm}from"node:fs";import{homedir as Gm}from"node:os";import{sep as qm,join as Le,resolve as tu}from"node:path";function Z(t){let e=t??Gm(),n=Le(e,".coze"),i=Le(n,"bridge"),o=Le(i,"lib"),a=Le(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:Le(o,"index.js"),binDir:Le(i,"bin"),pidFile:Le(i,"bridge.pid"),portFile:Le(i,"bridge.port"),tokenFile:Le(i,"bridge.token"),patTokenFile:Le(i,"pat-token"),agentEnvFile:Le(i,"agent-env.json"),logFile:Le(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:Le(a,"daemon-stdio.log"),installLock:Le(i,"install.lock"),configFile:Le(i,"config.json"),agentsRoot:Le(n,"agents")}}function Re(t,e=Z()){let n=Le(e.agentsRoot,t);return{root:n,config:Le(n,"config.json"),workspace:Le(n,"workspace"),logs:Le(n,"logs")}}function ks(t=Z()){try{return Hm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function fi(t,e){let n=await eu.realpath(tu(t)).catch(()=>null);if(!n)return!1;let i=await eu.realpath(tu(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?n.toLowerCase():n,a=process.platform==="win32"?i.toLowerCase():i;return o===a||o.startsWith(a+qm)}var Pe=it(()=>{"use strict"});var Cs={};qa(Cs,{AGENT_CONFIG_FILE_MODE:()=>Ts,enforceAgentConfigMode:()=>Km,loadAgentConfig:()=>Ie,persistAgentSessions:()=>hi,persistAgentSkills:()=>xi,saveAgentConfig:()=>qe});import{chmod as jm,stat as Wm}from"node:fs/promises";function Ie(t,e){return hn(Re(t,e).config)}function qe(t,e){return xn(Re(t.agentId,e).config,t,{mode:Ts})}async function Km(t,e){if(process.platform==="win32")return;let n=Re(t,e).config;try{let i=await Wm(n);if(!i.isFile())return;let o=i.mode&511;o!==Ts&&(await jm(n,Ts),nu.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;nu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function hi(t,e,n){let i=await Ie(t,n);i&&(i.sessions=Object.fromEntries(e),await qe(i,n))}async function xi(t,e,n){let i=await Ie(t,n);i&&(i.skills=e,await qe(i,n))}var nu,Ts,$t=it(()=>{"use strict";Kt();te();Pe();nu=G("agent-config"),Ts=384});var Xa=de((v2,su)=>{su.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 Ps=de(au=>{var ou={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Xm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(n,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(ou))au[t]=Xm(ou[t])});var fu=de((I2,uu)=>{var Qm=pe("fs"),ze=pe("path"),cu=Xa(),ew=Ps(),tw=typeof process=="object"&&process.platform==="win32",du=t=>typeof t=="object"&&t!==null,lu=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=ze.sep,this.fs=Qm,du(t)&&du(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}uu.exports=Ae;Ae.prototype.makeDir=function(t){let e=this;function n(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(a){if(!(!a||a.substr(-1,1)===":")){o+=e.sep+a;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw ew.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};Ae.prototype.writeFileTo=function(t,e,n,i){let o=this;if(o.fs.existsSync(t)){if(!n)return!1;var a=o.fs.statSync(t);if(a.isDirectory())return!1}var d=ze.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ae.prototype.writeFileToAsync=function(t,e,n,i,o){typeof i=="function"&&(o=i,i=void 0);let a=this;a.fs.exists(t,function(d){if(d&&!n)return o(!1);a.fs.stat(t,function(u,f){if(d&&f.isDirectory())return o(!1);var x=ze.dirname(t);a.fs.exists(x,function(p){p||a.makeDir(x),a.fs.open(t,"w",438,function(m,v){m?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(_,b){a.fs.write(b,e,0,e.length,0,function(){a.fs.close(b,function(){a.fs.chmod(t,i||438,function(){o(!0)})})})})}):v?a.fs.write(v,e,0,e.length,0,function(){a.fs.close(v,function(){a.fs.chmod(t,i||438,function(){o(!0)})})}):a.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ae.prototype.findFiles=function(t){let e=this;function n(i,o,a){typeof o=="boolean"&&(a=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let f=ze.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&d.push(ze.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(d=d.concat(n(f,o,a)))}),d}return n(t,void 0,!0)};Ae.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(o,a){if(o)return e(o);let d=a.length;if(!d)return e(null,i);a.forEach(function(u){u=ze.join(t,u),n.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(ze.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(p,m){if(p)return e(p);i=i.concat(m),--d||e(null,i)}):--d||e(null,i))})})})};Ae.prototype.getAttributes=function(){};Ae.prototype.setAttributes=function(){};Ae.crc32update=function(t,e){return lu[(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 cu.STORED:return"STORED ("+t+")";case cu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ae.canonical=function(t){if(!t)return"";let e=ze.posix.normalize("/"+t.split("\\").join("/"));return ze.join(".",e)};Ae.zipnamefix=function(t){if(!t)return"";let e=ze.posix.normalize("/"+t.split("\\").join("/"));return ze.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=ze.resolve(ze.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var a=ze.normalize(ze.join(t,n.slice(i,o).join(ze.sep)));if(a.indexOf(t)===0)return a}return ze.normalize(ze.join(t,ze.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=tw;Ae.crcTable=lu});var xu=de((A2,hu)=>{var nw=pe("path");hu.exports=function(t,{fs:e}){var n=t||"",i=a(),o=null;function a(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(o=e.statSync(n),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=nw.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 gu=de((k2,pu)=>{pu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var _r=de((T2,wr)=>{wr.exports=fu();wr.exports.Constants=Xa();wr.exports.Errors=Ps();wr.exports.FileAttr=xu();wr.exports.decoder=gu()});var wu=de((C2,mu)=>{var pn=_r(),U=pn.Constants;mu.exports=function(){var t=20,e=10,n=0,i=0,o=0,a=0,d=0,u=0,f=0,x=0,p=0,m=0,v=0,_=0,b=0;t|=pn.isWin?2560:768,n|=U.FLG_EFS;let S={extraLen:0},I=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,R=E=>Math.max(0,E)&255;return o=pn.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return n},set flags(E){n=E},get flags_efs(){return(n&U.FLG_EFS)>0},set flags_efs(E){E?n|=U.FLG_EFS:n&=~U.FLG_EFS},get flags_desc(){return(n&U.FLG_DESC)>0},set flags_desc(E){E?n|=U.FLG_DESC:n&=~U.FLG_DESC},get method(){return i},set method(E){switch(E){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=E},get time(){return pn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=pn.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=I(E)},get timeHighByte(){return R(o>>>8)},get crc(){return a},set crc(E){a=I(E)},get compressedSize(){return d},set compressedSize(E){d=I(E)},get size(){return u},set size(E){u=I(E)},get fileNameLength(){return f},set fileNameLength(E){f=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return S.extraLen},set extraLocalLength(E){S.extraLen=E},get commentLength(){return p},set commentLength(E){p=E},get diskNumStart(){return m},set diskNumStart(E){m=I(E)},get inAttr(){return v},set inAttr(E){v=I(E)},get attr(){return _},set attr(E){_=I(E)},get fileAttr(){return(_||0)>>16&4095},get offset(){return b},set offset(E){b=I(E)},get encrypted(){return(n&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+f+x+p},get realDataOffset(){return b+U.LOCHDR+S.fnameLen+S.extraLen},get localHeader(){return S},loadLocalHeaderFromBinary:function(E){var P=E.slice(b,b+U.LOCHDR);if(P.readUInt32LE(0)!==U.LOCSIG)throw pn.Errors.INVALID_LOC();S.version=P.readUInt16LE(U.LOCVER),S.flags=P.readUInt16LE(U.LOCFLG),S.flags_desc=(S.flags&U.FLG_DESC)>0,S.method=P.readUInt16LE(U.LOCHOW),S.time=P.readUInt32LE(U.LOCTIM),S.crc=P.readUInt32LE(U.LOCCRC),S.compressedSize=P.readUInt32LE(U.LOCSIZ),S.size=P.readUInt32LE(U.LOCLEN),S.fnameLen=P.readUInt16LE(U.LOCNAM),S.extraLen=P.readUInt16LE(U.LOCEXT);let D=b+U.LOCHDR+S.fnameLen,M=D+S.extraLen;return E.slice(D,M)},loadFromBinary:function(E){if(E.length!==U.CENHDR||E.readUInt32LE(0)!==U.CENSIG)throw pn.Errors.INVALID_CEN();t=E.readUInt16LE(U.CENVEM),e=E.readUInt16LE(U.CENVER),n=E.readUInt16LE(U.CENFLG),i=E.readUInt16LE(U.CENHOW),o=E.readUInt32LE(U.CENTIM),a=E.readUInt32LE(U.CENCRC),d=E.readUInt32LE(U.CENSIZ),u=E.readUInt32LE(U.CENLEN),f=E.readUInt16LE(U.CENNAM),x=E.readUInt16LE(U.CENEXT),p=E.readUInt16LE(U.CENCOM),m=E.readUInt16LE(U.CENDSK),v=E.readUInt16LE(U.CENATT),_=E.readUInt32LE(U.CENATX),b=E.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(U.LOCHDR);return E.writeUInt32LE(U.LOCSIG,0),E.writeUInt16LE(e,U.LOCVER),E.writeUInt16LE(n,U.LOCFLG),E.writeUInt16LE(i,U.LOCHOW),E.writeUInt32LE(o,U.LOCTIM),E.writeUInt32LE(a,U.LOCCRC),E.writeUInt32LE(d,U.LOCSIZ),E.writeUInt32LE(u,U.LOCLEN),E.writeUInt16LE(f,U.LOCNAM),E.writeUInt16LE(S.extraLen,U.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(U.CENHDR+f+x+p);return E.writeUInt32LE(U.CENSIG,0),E.writeUInt16LE(t,U.CENVEM),E.writeUInt16LE(e,U.CENVER),E.writeUInt16LE(n,U.CENFLG),E.writeUInt16LE(i,U.CENHOW),E.writeUInt32LE(o,U.CENTIM),E.writeUInt32LE(a,U.CENCRC),E.writeUInt32LE(d,U.CENSIZ),E.writeUInt32LE(u,U.CENLEN),E.writeUInt16LE(f,U.CENNAM),E.writeUInt16LE(x,U.CENEXT),E.writeUInt16LE(p,U.CENCOM),E.writeUInt16LE(m,U.CENDSK),E.writeUInt16LE(v,U.CENATT),E.writeUInt32LE(_,U.CENATX),E.writeUInt32LE(b,U.CENOFF),E},toJSON:function(){let E=function(P){return P+" bytes"};return{made:t,version:e,flags:n,method:pn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(f),extraLength:E(x),commentLength:E(p),diskNumStart:m,inAttr:v,attr:_,offset:b,centralHeaderSize:E(U.CENHDR+f+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var yu=de((R2,_u)=>{var yr=_r(),Ee=yr.Constants;_u.exports=function(){var t=0,e=0,n=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return n},set size(a){n=a},get offset(){return i},set offset(a){i=a},get commentLength(){return o},set commentLength(a){o=a},get mainHeaderSize(){return Ee.ENDHDR+o},loadFromBinary:function(a){if((a.length!==Ee.ENDHDR||a.readUInt32LE(0)!==Ee.ENDSIG)&&(a.length<Ee.ZIP64HDR||a.readUInt32LE(0)!==Ee.ZIP64SIG))throw yr.Errors.INVALID_END();a.readUInt32LE(0)===Ee.ENDSIG?(t=a.readUInt16LE(Ee.ENDSUB),e=a.readUInt16LE(Ee.ENDTOT),n=a.readUInt32LE(Ee.ENDSIZ),i=a.readUInt32LE(Ee.ENDOFF),o=a.readUInt16LE(Ee.ENDCOM)):(t=yr.readBigUInt64LE(a,Ee.ZIP64SUB),e=yr.readBigUInt64LE(a,Ee.ZIP64TOT),n=yr.readBigUInt64LE(a,Ee.ZIP64SIZE),i=yr.readBigUInt64LE(a,Ee.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(Ee.ENDHDR+o);return a.writeUInt32LE(Ee.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,Ee.ENDSUB),a.writeUInt16LE(e,Ee.ENDTOT),a.writeUInt32LE(n,Ee.ENDSIZ),a.writeUInt32LE(i,Ee.ENDOFF),a.writeUInt16LE(o,Ee.ENDCOM),a.fill(" ",Ee.ENDHDR),a},toJSON:function(){let a=function(d,u){let f=d.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:a(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ec=de(Qa=>{Qa.EntryHeader=wu();Qa.MainHeader=yu()});var Eu=de((D2,bu)=>{bu.exports=function(t){var e=pe("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var o=e.createDeflateRaw(n),a=[],d=0;o.on("data",function(u){a.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),f=0;u.fill(0);for(var x=0;x<a.length;x++){var p=a[x];p.copy(u,f),f+=p.length}i&&i(u)}),o.end(t)}}}});var Su=de((O2,vu)=>{var rw=+(process.versions?process.versions.node:"").split(".")[0]||0;vu.exports=function(t,e){var n=pe("zlib");let i=rw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var a=n.createInflateRaw(i),d=[],u=0;a.on("data",function(f){d.push(f),u+=f.length}),a.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var p=0;p<d.length;p++){var m=d[p];m.copy(f,x),x+=m.length}o&&o(f)}),a.end(t)}}}});var Cu=de((L2,Tu)=>{"use strict";var{randomFillSync:Iu}=pe("crypto"),iw=Ps(),sw=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}),ku=(t,e)=>Math.imul(t,e)>>>0,Au=(t,e)=>sw[(t^e)&255]^t>>>8,pi=()=>typeof Iu=="function"?Iu(Buffer.alloc(12)):pi.node();pi.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 Ds={genSalt:pi};function Os(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])}Os.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Au(e[0],t),e[1]+=e[0]&255,e[1]=ku(e[1],134775813)+1,e[2]=Au(e[2],e[1]>>>24),t};Os.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return ku(t,t^1)>>8&255};function ow(t){let e=new Os(t);return function(n){let i=Buffer.alloc(n.length),o=0;for(let a of n)i[o++]=e.updateKeys(a^e.next());return i}}function aw(t){let e=new Os(t);return function(n,i,o=0){i||(i=Buffer.alloc(n.length));for(let a of n){let d=e.next();i[o++]=a^d,e.updateKeys(a)}return i}}function cw(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=ow(n),o=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==a)throw iw.WRONG_PASSWORD();return i(t.slice(12))}function dw(t){Buffer.isBuffer(t)&&t.length>=12?Ds.genSalt=function(){return t.slice(0,12)}:t==="node"?Ds.genSalt=pi.node:Ds.genSalt=pi}function lw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=aw(n),a=Ds.genSalt();a[11]=e.crc>>>24&255,i&&(a[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(a,d),o(t,d,12)}Tu.exports={decrypt:cw,encrypt:lw,_salter:dw}});var Ru=de(Ls=>{Ls.Deflater=Eu();Ls.Inflater=Su();Ls.ZipCrypto=Cu()});var nc=de((M2,Pu)=>{var le=_r(),uw=ec(),ke=le.Constants,tc=Ru();Pu.exports=function(t,e){var n=new uw.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let p=t,m=typeof p.decoder=="object"?p.decoder:le.decoder;x=m.hasOwnProperty("efs")?m.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(le.crc32(E)!==n.localHeader.crc)return!1}else{let P={},D=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(D)==ke.LOCSIG||e.readUInt32LE(D)==ke.CENSIG)throw le.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==ke.EXTSIG)P.crc=e.readUInt32LE(D+ke.EXTCRC),P.compressedSize=e.readUInt32LE(D+ke.EXTSIZ),P.size=e.readUInt32LE(D+ke.EXTLEN);else if(e.readUInt16LE(D+12)===19280)P.crc=e.readUInt32LE(D+ke.EXTCRC-4),P.compressedSize=e.readUInt32LE(D+ke.EXTSIZ-4),P.size=e.readUInt32LE(D+ke.EXTLEN-4);else throw le.Errors.DESCRIPTOR_UNKNOWN();if(P.compressedSize!==n.compressedSize||P.size!==n.size||P.crc!==n.crc)throw le.Errors.DESCRIPTOR_FAULTY();if(le.crc32(E)!==P.crc)return!1}return!0}function b(E,P,D){if(typeof P>"u"&&typeof E=="string"&&(D=E,E=void 0),a)return E&&P&&P(Buffer.alloc(0),le.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var M=v();if(M.length===0)return E&&P&&P(M),M;if(n.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw le.Errors.INVALID_PASS_PARAM();M=tc.ZipCrypto.decrypt(M,n,D)}var N=Buffer.alloc(n.size);switch(n.method){case le.Constants.STORED:if(M.copy(N),_(N))return E&&P&&P(N),N;throw E&&P&&P(N,le.Errors.BAD_CRC()),le.Errors.BAD_CRC();case le.Constants.DEFLATED:var J=new tc.Inflater(M,n.size);if(E)J.inflateAsync(function(V){V.copy(V,0),P&&(_(V)?P(V):P(V,le.Errors.BAD_CRC()))});else{if(J.inflate(N).copy(N,0),!_(N))throw le.Errors.BAD_CRC(`"${m.decode(i)}"`);return N}break;default:throw E&&P&&P(Buffer.alloc(0),le.Errors.UNKNOWN_METHOD()),le.Errors.UNKNOWN_METHOD()}}function S(E,P){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&P&&P(v()),v();if(d.length&&!a){var D;switch(n.method){case le.Constants.STORED:return n.compressedSize=n.size,D=Buffer.alloc(d.length),d.copy(D),E&&P&&P(D),D;default:case le.Constants.DEFLATED:var M=new tc.Deflater(d);if(E)M.deflateAsync(function(J){D=Buffer.alloc(J.length),n.compressedSize=J.length,J.copy(D),P&&P(D)});else{var N=M.deflate();return n.compressedSize=N.length,N}M=null;break}}else if(E&&P)P(Buffer.alloc(0));else return Buffer.alloc(0)}function I(E,P){return le.readBigUInt64LE(E,P)}function T(E){try{for(var P=0,D,M,N;P+4<E.length;)D=E.readUInt16LE(P),P+=2,M=E.readUInt16LE(P),P+=2,N=E.slice(P,P+M),P+=M,ke.ID_ZIP64===D&&R(N)}catch{throw le.Errors.EXTRA_FIELD_PARSE_ERROR()}}function R(E){var P,D,M,N;E.length>=ke.EF_ZIP64_SCOMP&&(P=I(E,ke.EF_ZIP64_SUNCOMP),n.size===ke.EF_ZIP64_OR_32&&(n.size=P)),E.length>=ke.EF_ZIP64_RHO&&(D=I(E,ke.EF_ZIP64_SCOMP),n.compressedSize===ke.EF_ZIP64_OR_32&&(n.compressedSize=D)),E.length>=ke.EF_ZIP64_DSN&&(M=I(E,ke.EF_ZIP64_RHO),n.offset===ke.EF_ZIP64_OR_32&&(n.offset=M)),E.length>=ke.EF_ZIP64_DSN+4&&(N=E.readUInt32LE(ke.EF_ZIP64_DSN),n.diskNumStart===ke.EF_ZIP64_OR_16&&(n.diskNumStart=N))}return{get entryName(){return m.decode(i)},get rawEntryName(){return i},set entryName(E){i=le.toBuffer(E,m.encode);var P=i[i.length-1];a=P===47||P===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,n.extraLength=E.length,T(E)},get comment(){return m.decode(o)},set comment(E){if(o=le.toBuffer(E,m.encode),n.commentLength=o.length,o.length>65535)throw le.Errors.COMMENT_TOO_LONG()},get name(){var E=m.decode(i);return a?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return S(!1,null)},getCompressedDataAsync:function(E){S(!0,E)},setData:function(E){d=le.toBuffer(E,le.decoder.encode),!a&&d.length?(n.size=d.length,n.method=le.Constants.DEFLATED,n.crc=le.crc32(E),n.changed=!0):n.method=le.Constants.STORED},getData:function(E){return n.changed?d:b(!1,null,E)},getDataAsync:function(E,P){n.changed?E(d):b(!0,E,P)},set attr(E){n.attr=E},get attr(){return n.attr},set header(E){n.loadFromBinary(E)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var E=n.centralHeaderToBinary(),P=le.Constants.CENHDR;return i.copy(E,P),P+=i.length,u.copy(E,P),P+=n.extraLength,o.copy(E,P),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=f.length;let P=n.localHeaderToBinary(),D=Buffer.alloc(P.length+i.length+n.extraLocalLength);return P.copy(D,E),E+=P.length,i.copy(D,E),E+=i.length,f.copy(D,E),E+=f.length,D},toJSON:function(){let E=function(P){return"<"+(P&&P.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Lu=de((B2,Ou)=>{var Du=nc(),fw=ec(),Ye=_r();Ou.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),a=new fw.MainHeader,d=!1,u=null;let f=new Set,x=e,{noSort:p,decoder:m}=x;t?b(x.readEntries):d=!0;function v(){let I=new Set;for(let T of Object.keys(i)){let R=T.split("/");if(R.pop(),!!R.length)for(let E=0;E<R.length;E++){let P=R.slice(0,E+1).join("/")+"/";I.add(P)}}for(let T of I)if(!(T in i)){let R=new Du(x);R.entryName=T,R.attr=16,R.temporary=!0,n.push(R),i[R.entryName]=R,f.add(R)}}function _(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Ye.Constants.CENHDR)throw Ye.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var I=a.offset,T=0;T<n.length;T++){var R=I,E=new Du(x,t);E.header=t.slice(R,R+=Ye.Constants.CENHDR),E.entryName=t.slice(R,R+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(R,R+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(R,R+E.header.commentLength)),I+=E.header.centralHeaderSize,n[T]=E,i[E.entryName]=E}f.clear(),v()}function b(I){var T=t.length-Ye.Constants.ENDHDR,R=Math.max(0,T-65535),E=R,P=t.length,D=-1,M=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(R=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===Ye.Constants.ENDSIG){D=T,M=T,P=T+Ye.Constants.ENDHDR,E=T-Ye.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Ye.Constants.END64SIG){E=R;continue}if(t.readUInt32LE(T)===Ye.Constants.ZIP64SIG){D=T,P=T+Ye.readBigUInt64LE(t,T+Ye.Constants.ZIP64SIZE)+Ye.Constants.ZIP64LEAD;break}}if(D==-1)throw Ye.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(D,P)),a.commentLength&&(o=t.slice(M+Ye.Constants.ENDHDR)),I&&_()}function S(){n.length>1&&!p&&n.sort((I,T)=>I.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(I=>!f.has(I))},get comment(){return m.decode(o)},set comment(I){o=Ye.toBuffer(I,m.encode),a.commentLength=o.length},getEntryCount:function(){return d?n.length:a.diskEntries},forEach:function(I){this.entries.forEach(I)},getEntry:function(I){return d||_(),i[I]||null},setEntry:function(I){d||_(),n.push(I),i[I.entryName]=I,a.totalEntries=n.length},deleteFile:function(I,T=!0){d||_();let R=i[I];this.getEntryChildren(R,T).map(P=>P.entryName).forEach(this.deleteEntry)},deleteEntry:function(I){d||_();let T=i[I],R=n.indexOf(T);R>=0&&(n.splice(R,1),delete i[I],a.totalEntries=n.length)},getEntryChildren:function(I,T=!0){if(d||_(),typeof I=="object")if(I.isDirectory&&T){let R=[],E=I.entryName;for(let P of n)P.entryName.startsWith(E)&&R.push(P);return R}else return[I];return[]},getChildCount:function(I){if(I&&I.isDirectory){let T=this.getEntryChildren(I);return T.includes(I)?T.length-1:T.length}return 0},compressToBuffer:function(){d||_(),S();let I=[],T=[],R=0,E=0;a.size=0,a.offset=0;let P=0;for(let N of this.entries){let J=N.getCompressedData();N.header.offset=E;let V=N.packLocalHeader(),se=V.length+J.length;E+=se,I.push(V),I.push(J);let X=N.packCentralHeader();T.push(X),a.size+=X.length,R+=se+X.length,P++}R+=a.mainHeaderSize,a.offset=E,a.totalEntries=P,E=0;let D=Buffer.alloc(R);for(let N of I)N.copy(D,E),E+=N.length;for(let N of T)N.copy(D,E),E+=N.length;let M=a.toBinary();return o&&o.copy(M,Ye.Constants.ENDHDR),M.copy(D,E),t=D,d=!1,D},toAsyncBuffer:function(I,T,R,E){try{d||_(),S();let P=[],D=[],M=0,N=0,J=0;a.size=0,a.offset=0;let V=function(se){if(se.length>0){let X=se.shift(),re=X.entryName+X.extra.toString();R&&R(re),X.getCompressedDataAsync(function(ae){E&&E(re),X.header.offset=N;let C=X.packLocalHeader(),z=C.length+ae.length;N+=z,P.push(C),P.push(ae);let q=X.packCentralHeader();D.push(q),a.size+=q.length,M+=z+q.length,J++,V(se)})}else{M+=a.mainHeaderSize,a.offset=N,a.totalEntries=J,N=0;let X=Buffer.alloc(M);P.forEach(function(ae){ae.copy(X,N),N+=ae.length}),D.forEach(function(ae){ae.copy(X,N),N+=ae.length});let re=a.toBinary();o&&o.copy(re,Ye.Constants.ENDHDR),re.copy(X,N),t=X,d=!1,I(X)}};V(Array.from(this.entries))}catch(P){T(P)}}}}});var Bu=de((F2,Mu)=>{var Se=_r(),ve=pe("path"),hw=nc(),xw=Lu(),Mn=(...t)=>Se.findLast(t,e=>typeof e=="boolean"),Nu=(...t)=>Se.findLast(t,e=>typeof e=="string"),pw=(...t)=>Se.findLast(t,e=>typeof e=="function"),gw={noSort:!1,readEntries:!1,method:Se.Constants.NONE,fs:null};Mu.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),gw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=Se.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Se(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Se.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Se.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw Se.Errors.INVALID_FILENAME();let a=new xw(n,i),{canonical:d,sanitize:u,zipnamefix:f}=Se;function x(_){if(_&&a){var b;if(typeof _=="string"&&(b=a.getEntry(ve.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(b=a.getEntry(_.entryName)),b)return b}return null}function p(_){let{join:b,normalize:S,sep:I}=ve.posix;return b(ve.isAbsolute(_)?"/":".",S(I+_.split("\\").join(I)+I))}function m(_){return _ instanceof RegExp?(function(b){return function(S){return b.test(S)}})(_):typeof _!="function"?()=>!0:_}let v=(_,b)=>{let S=b.slice(-1);return S=S===o.sep?o.sep:"",ve.relative(_,b)+S};return{readFile:function(_,b){var S=x(_);return S&&S.getData(b)||null},childCount:function(_){let b=x(_);if(b)return a.getChildCount(b)},readFileAsync:function(_,b){var S=x(_);S?S.getDataAsync(b):b(null,"getEntry failed for:"+_)},readAsText:function(_,b){var S=x(_);if(S){var I=S.getData();if(I&&I.length)return I.toString(b||"utf8")}return""},readAsTextAsync:function(_,b,S){var I=x(_);I?I.getDataAsync(function(T,R){if(R){b(T,R);return}T&&T.length?b(T.toString(S||"utf8")):b("")}):b("")},deleteFile:function(_,b=!0){var S=x(_);S&&a.deleteFile(S.entryName,b)},deleteEntry:function(_){var b=x(_);b&&a.deleteEntry(b.entryName)},addZipComment:function(_){a.comment=_},getZipComment:function(){return a.comment||""},addZipEntryComment:function(_,b){var S=x(_);S&&(S.comment=b)},getZipEntryComment:function(_){var b=x(_);return b&&b.comment||""},updateFile:function(_,b){var S=x(_);S&&S.setData(b)},addLocalFile:function(_,b,S,I){if(o.fs.existsSync(_)){b=b?p(b):"";let T=ve.win32.basename(ve.win32.normalize(_));b+=S||T;let R=o.fs.statSync(_),E=R.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);R.isDirectory()&&(b+=o.sep),this.addFile(b,E,I,R)}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,b){_=typeof _=="object"?_:{localPath:_};let S=ve.resolve(_.localPath),{comment:I}=_,{zipPath:T,zipName:R}=_,E=this;o.fs.stat(S,function(P,D){if(P)return b(P,!1);T=T?p(T):"";let M=ve.win32.basename(ve.win32.normalize(S));if(T+=R||M,D.isFile())o.fs.readFile(S,function(N,J){return N?b(N,!1):(E.addFile(T,J,I,D),setImmediate(b,void 0,!0))});else if(D.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),I,D),setImmediate(b,void 0,!0)})},addLocalFolder:function(_,b,S){if(S=m(S),b=b?p(b):"",_=ve.normalize(_),o.fs.existsSync(_)){let I=o.findFiles(_),T=this;if(I.length)for(let R of I){let E=ve.join(b,v(_,R));S(E)&&T.addLocalFile(R,ve.dirname(E))}}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,b,S,I){I=m(I),S=S?p(S):"",_=ve.normalize(_);var T=this;o.fs.open(_,"r",function(R){if(R&&R.code==="ENOENT")b(void 0,Se.Errors.FILE_NOT_FOUND(_));else if(R)b(void 0,R);else{var E=o.findFiles(_),P=-1,D=function(){if(P+=1,P<E.length){var M=E[P],N=v(_,M).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),I(N)?o.fs.stat(M,function(J,V){J&&b(void 0,J),V.isFile()?o.fs.readFile(M,function(se,X){se?b(void 0,se):(T.addFile(S+N,X,"",V),D())}):(T.addFile(S+N+"/",Buffer.alloc(0),"",V),D())}):process.nextTick(()=>{D()})}else b(!0,void 0)};D()}})},addLocalFolderAsync2:function(_,b){let S=this;_=typeof _=="object"?_:{localPath:_},localPath=ve.resolve(p(_.localPath));let{zipPath:I,filter:T,namefix:R}=_;T instanceof RegExp?T=(function(D){return function(M){return D.test(M)}})(T):typeof T!="function"&&(T=function(){return!0}),I=I?p(I):"",R=="latin1"&&(R=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof R!="function"&&(R=D=>D);let E=D=>ve.join(I,R(v(localPath,D))),P=D=>ve.win32.basename(ve.win32.normalize(R(D)));o.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?b(void 0,Se.Errors.FILE_NOT_FOUND(localPath)):D?b(void 0,D):o.findFilesAsync(localPath,function(M,N){if(M)return b(M);N=N.filter(J=>T(E(J))),N.length||b(void 0,!1),setImmediate(N.reverse().reduce(function(J,V){return function(se,X){if(se||X===!1)return setImmediate(J,se,!1);S.addLocalFileAsync({localPath:V,zipPath:ve.dirname(E(V)),zipName:P(V)},J)}},b))})})},addLocalFolderPromise:function(_,b){return new Promise((S,I)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},b),(T,R)=>{T&&I(T),R&&S(this)})})},addFile:function(_,b,S,I){_=f(_);let T=x(_),R=T!=null;R||(T=new hw(i),T.entryName=_),T.comment=S||"";let E=typeof I=="object"&&I instanceof o.fs.Stats;E&&(T.header.time=I.mtime);var P=T.isDirectory?16:0;let D=T.isDirectory?16384:32768;return E?D|=4095&I.mode:typeof I=="number"?D|=4095&I:D|=T.isDirectory?493:420,P=(P|D<<16)>>>0,T.attr=P,T.setData(b),R||a.setEntry(T),T},getEntries:function(_){return a.password=_,a?a.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return a.getEntryCount()},forEach:function(_){return a.forEach(_)},extractEntryTo:function(_,b,S,I,T,R){I=Mn(!1,I),T=Mn(!1,T),S=Mn(!0,S),R=Nu(T,R);var E=x(_);if(!E)throw Se.Errors.NO_ENTRY();var P=d(E.entryName),D=u(b,R&&!E.isDirectory?R:S?P:ve.basename(P));if(E.isDirectory){var M=a.getEntryChildren(E);return M.forEach(function(V){if(V.isDirectory)return;var se=V.getData();if(!se)throw Se.Errors.CANT_EXTRACT_FILE();var X=d(V.entryName),re=u(b,S?X:ve.basename(X));let ae=T?V.header.fileAttr:void 0;o.writeFileTo(re,se,I,ae)}),!0}var N=E.getData(a.password);if(!N)throw Se.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(D)&&!I)throw Se.Errors.CANT_OVERRIDE();let J=T?_.header.fileAttr:void 0;return o.writeFileTo(D,N,I,J),!0},test:function(_){if(!a)return!1;for(var b in a.entries)try{if(b.isDirectory)continue;var S=a.entries[b].getData(_);if(!S)return!1}catch{return!1}return!0},extractAllTo:function(_,b,S,I){if(S=Mn(!1,S),I=Nu(S,I),b=Mn(!1,b),!a)throw Se.Errors.NO_ZIP();a.entries.forEach(function(T){var R=u(_,d(T.entryName));if(T.isDirectory){o.makeDir(R);return}var E=T.getData(I);if(!E)throw Se.Errors.CANT_EXTRACT_FILE();let P=S?T.header.fileAttr:void 0;o.writeFileTo(R,E,b,P);try{o.fs.utimesSync(R,T.header.time,T.header.time)}catch{throw Se.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,b,S,I){if(I=pw(b,S,I),S=Mn(!1,S),b=Mn(!1,b),!I)return new Promise((D,M)=>{this.extractAllToAsync(_,b,S,function(N){N?M(N):D(this)})});if(!a){I(Se.Errors.NO_ZIP());return}_=ve.resolve(_);let T=D=>u(_,ve.normalize(d(D.entryName))),R=(D,M)=>new Error(D+': "'+M+'"'),E=[],P=[];a.entries.forEach(D=>{D.isDirectory?E.push(D):P.push(D)});for(let D of E){let M=T(D),N=S?D.header.fileAttr:void 0;try{o.makeDir(M),N&&o.fs.chmodSync(M,N),o.fs.utimesSync(M,D.header.time,D.header.time)}catch{I(R("Unable to create folder",M))}}P.reverse().reduce(function(D,M){return function(N){if(N)D(N);else{let J=ve.normalize(d(M.entryName)),V=u(_,J);M.getDataAsync(function(se,X){if(X)D(X);else if(!se)D(Se.Errors.CANT_EXTRACT_FILE());else{let re=S?M.header.fileAttr:void 0;o.writeFileToAsync(V,se,b,re,function(ae){ae||D(R("Unable to write file",V)),o.fs.utimes(V,M.header.time,M.header.time,function(C){C?D(R("Unable to set times",V)):D()})})}})}}},I)()},writeZip:function(_,b){if(arguments.length===1&&typeof _=="function"&&(b=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var S=a.compressToBuffer();if(S){var I=o.writeFileTo(_,S,!0);typeof b=="function"&&b(I?null:new Error("failed"),"")}}},writeZipPromise:function(_,b){let{overwrite:S,perm:I}=Object.assign({overwrite:!0},b);return new Promise((T,R)=>{!_&&i.filename&&(_=i.filename),_||R("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let P=D=>D?T(D):R("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,E,S,I,P)},R)})},toBufferPromise:function(){return new Promise((_,b)=>{a.toAsyncBuffer(_,b)})},toBuffer:function(_,b,S,I){return typeof _=="function"?(a.toAsyncBuffer(_,b,S,I),null):a.compressToBuffer()}}}});import{execFile as Sy,spawn as Iy,spawnSync as nT}from"node:child_process";import{promisify as Ay}from"node:util";function Ty(t){if(process.platform!=="win32")return!1;if(s0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(s0,"").toLowerCase();return ky.has(n)}function o0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return Ty(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function at(t,e=[],n={}){return Iy(t,e,o0(t,n))}function a0(t,e=[],n={}){return Cy(t,e,o0(t,n))}var ky,s0,Cy,en=it(()=>{"use strict";ky=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),s0=/\.(cmd|bat|ps1)$/i;Cy=Ay(Sy)});var nn=de((hD,ix)=>{"use strict";var nx=["nodebuffer","arraybuffer","fragments"],rx=typeof Blob<"u";rx&&nx.push("blob");ix.exports={BINARY_TYPES:nx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:rx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var is=de((xD,Vo)=>{"use strict";var{EMPTY_BUFFER:Wv}=nn(),Bd=Buffer[Symbol.species];function Kv(t,e){if(t.length===0)return Wv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let a=t[o];n.set(a,i),i+=a.length}return i<e?new Bd(n.buffer,n.byteOffset,i):n}function sx(t,e,n,i,o){for(let a=0;a<o;a++)n[i+a]=t[a]^e[a&3]}function ox(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function $v(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Fd(t){if(Fd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Bd(t):ArrayBuffer.isView(t)?e=new Bd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Fd.readOnly=!1),e}Vo.exports={concat:Kv,mask:sx,toArrayBuffer:$v,toBuffer:Fd,unmask:ox};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=pe("bufferutil");Vo.exports.mask=function(e,n,i,o,a){a<48?sx(e,n,i,o,a):t.mask(e,n,i,o,a)},Vo.exports.unmask=function(e,n){e.length<32?ox(e,n):t.unmask(e,n)}}catch{}});var dx=de((pD,cx)=>{"use strict";var ax=Symbol("kDone"),zd=Symbol("kRun"),Ud=class{constructor(e){this[ax]=()=>{this.pending--,this[zd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[zd]()}[zd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ax])}}};cx.exports=Ud});var Jr=de((gD,hx)=>{"use strict";var ss=pe("zlib"),lx=is(),Vv=dx(),{kStatusCode:ux}=nn(),Zv=Buffer[Symbol.species],Jv=Buffer.from([0,0,255,255]),Jo=Symbol("permessage-deflate"),rn=Symbol("total-length"),Vr=Symbol("callback"),Pn=Symbol("buffers"),Zr=Symbol("error"),Zo,Hd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Zo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Zo=new Vv(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[Vr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let o=n[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=a}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=o})}),e}decompress(e,n,i){Zo.add(o=>{this._decompress(e,n,(a,d)=>{o(),i(a,d)})})}compress(e,n,i){Zo.add(o=>{this._compress(e,n,(a,d)=>{o(),i(a,d)})})}_decompress(e,n,i){let o=this._isServer?"client":"server";if(!this._inflate){let a=`${o}_max_window_bits`,d=typeof this.params[a]!="number"?ss.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=ss.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Jo]=this,this._inflate[rn]=0,this._inflate[Pn]=[],this._inflate.on("error",Xv),this._inflate.on("data",fx)}this._inflate[Vr]=i,this._inflate.write(e),n&&this._inflate.write(Jv),this._inflate.flush(()=>{let a=this._inflate[Zr];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=lx.concat(this._inflate[Pn],this._inflate[rn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[rn]=0,this._inflate[Pn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let o=this._isServer?"server":"client";if(!this._deflate){let a=`${o}_max_window_bits`,d=typeof this.params[a]!="number"?ss.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=ss.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[rn]=0,this._deflate[Pn]=[],this._deflate.on("data",Yv)}this._deflate[Vr]=i,this._deflate.write(e),this._deflate.flush(ss.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=lx.concat(this._deflate[Pn],this._deflate[rn]);n&&(a=new Zv(a.buffer,a.byteOffset,a.length-4)),this._deflate[Vr]=null,this._deflate[rn]=0,this._deflate[Pn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};hx.exports=Hd;function Yv(t){this[Pn].push(t),this[rn]+=t.length}function fx(t){if(this[rn]+=t.length,this[Jo]._maxPayload<1||this[rn]<=this[Jo]._maxPayload){this[Pn].push(t);return}this[Zr]=new RangeError("Max payload size exceeded"),this[Zr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zr][ux]=1009,this.removeListener("data",fx),this.reset()}function Xv(t){if(this[Jo]._inflate=null,this[Zr]){this[Vr](this[Zr]);return}t[ux]=1007,this[Vr](t)}});var Yr=de((mD,Yo)=>{"use strict";var{isUtf8:xx}=pe("buffer"),{hasBlob:Qv}=nn(),eS=[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 tS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Gd(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 nS(t){return Qv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Yo.exports={isBlob:nS,isValidStatusCode:tS,isValidUTF8:Gd,tokenChars:eS};if(xx)Yo.exports.isValidUTF8=function(t){return t.length<24?Gd(t):xx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=pe("utf-8-validate");Yo.exports.isValidUTF8=function(e){return e.length<32?Gd(e):t(e)}}catch{}});var $d=de((wD,Ex)=>{"use strict";var{Writable:rS}=pe("stream"),px=Jr(),{BINARY_TYPES:iS,EMPTY_BUFFER:gx,kStatusCode:sS,kWebSocket:oS}=nn(),{concat:qd,toArrayBuffer:aS,unmask:cS}=is(),{isValidStatusCode:dS,isValidUTF8:mx}=Yr(),Xo=Buffer[Symbol.species],wt=0,_x=1,yx=2,bx=3,jd=4,Wd=5,Qo=6,Kd=class extends rS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||iS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[oS]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=wt}_write(e,n,i){if(this._opcode===8&&this._state==wt)return i();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 Xo(i.buffer,i.byteOffset+e,i.length-e),new Xo(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=n.length-e;e>=i.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new Xo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case wt:this.getInfo(e);break;case _x:this.getPayloadLength16(e);break;case yx:this.getPayloadLength64(e);break;case bx:this.getMask();break;case jd:this.getData(e);break;case Wd:case Qo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(n[0]&64)===64;if(i&&!this._extensions[px.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=_x:this._payloadLength===127?this._state=yx:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=bx:this._state=jd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=jd}getData(e){let n=gx;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&&cS(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Wd,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[px.extensionName].decompress(e,this._fin,(o,a)=>{if(o)return n(o);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(d);return}this._fragments.push(a)}this.dataMessage(n),this._state===wt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=wt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=qd(i,n):this._binaryType==="arraybuffer"?o=aS(qd(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=wt):(this._state=Qo,setImmediate(()=>{this.emit("message",o,!0),this._state=wt,this.startLoop(e)}))}else{let o=qd(i,n);if(!this._skipUTF8Validation&&!mx(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===Wd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=wt):(this._state=Qo,setImmediate(()=>{this.emit("message",o,!1),this._state=wt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,gx),this.end();else{let i=e.readUInt16BE(0);if(!dS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let o=new Xo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!mx(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(a);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=wt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=wt):(this._state=Qo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=wt,this.startLoop(n)}))}createError(e,n,i,o,a){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=a,d[sS]=o,d}};Ex.exports=Kd});var Jd=de((yD,Ix)=>{"use strict";var{Duplex:_D}=pe("stream"),{randomFillSync:lS}=pe("crypto"),vx=Jr(),{EMPTY_BUFFER:uS,kWebSocket:fS,NOOP:hS}=nn(),{isBlob:Xr,isValidStatusCode:xS}=Yr(),{mask:Sx,toBuffer:nr}=is(),_t=Symbol("kByteLength"),pS=Buffer.alloc(4),ea=8*1024,rr,Qr=ea,Tt=0,gS=1,mS=2,Vd=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Tt,this.onerror=hS,this[fS]=void 0}static frame(e,n){let i,o=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||pS,n.generateMask?n.generateMask(i):(Qr===ea&&(rr===void 0&&(rr=Buffer.alloc(ea)),lS(rr,0,ea),Qr=0),i[0]=rr[Qr++],i[1]=rr[Qr++],i[2]=rr[Qr++],i[3]=rr[Qr++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[_t]!==void 0?u=n[_t]:(e=Buffer.from(e),u=e.length):(u=e.length,o=n.mask&&n.readOnly&&!d);let f=u;u>=65536?(a+=8,f=127):u>125&&(a+=2,f=126);let x=Buffer.allocUnsafe(o?u+a:a);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=f,f===126?x.writeUInt16BE(u,2):f===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.mask?(x[1]|=128,x[a-4]=i[0],x[a-3]=i[1],x[a-2]=i[2],x[a-1]=i[3],d?[x,e]:o?(Sx(e,i,x,a,u),[x]):(Sx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,o){let a;if(e===void 0)a=uS;else{if(typeof e!="number"||!xS(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");a=Buffer.allocUnsafe(2+u),a.writeUInt16BE(e,0),typeof n=="string"?a.write(n,2):a.set(n,2)}}let d={[_t]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Tt?this.enqueue([this.dispatch,a,!1,d,o]):this.sendFrame(t.frame(a,d),o)}ping(e,n,i){let o,a;if(typeof e=="string"?(o=Buffer.byteLength(e),a=!1):Xr(e)?(o=e.size,a=!1):(e=nr(e),o=e.length,a=nr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[_t]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};Xr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Tt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let o,a;if(typeof e=="string"?(o=Buffer.byteLength(e),a=!1):Xr(e)?(o=e.size,a=!1):(e=nr(e),o=e.length,a=nr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[_t]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};Xr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Tt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[vx.extensionName],a=n.binary?2:1,d=n.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Xr(e)?(u=e.size,f=!1):(e=nr(e),u=e.length,f=nr.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[_t]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:f,rsv1:d};Xr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Tt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[_t],this._state=mS,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Zd,this,u,o);return}this._bufferedBytes-=i[_t];let d=nr(a);n?this.dispatch(d,n,i,o):(this._state=Tt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(a=>{process.nextTick(wS,this,a,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let a=this._extensions[vx.extensionName];this._bufferedBytes+=i[_t],this._state=gS,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Zd(this,f,o);return}this._bufferedBytes-=i[_t],this._state=Tt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===Tt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][_t],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][_t],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Ix.exports=Vd;function Zd(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],a=o[o.length-1];typeof a=="function"&&a(e)}}function wS(t,e,n){Zd(t,e,n),t.onerror(e)}});var Lx=de((bD,Ox)=>{"use strict";var{kForOnEventAttribute:os,kListener:Yd}=nn(),Ax=Symbol("kCode"),kx=Symbol("kData"),Tx=Symbol("kError"),Cx=Symbol("kMessage"),Rx=Symbol("kReason"),ei=Symbol("kTarget"),Px=Symbol("kType"),Dx=Symbol("kWasClean"),sn=class{constructor(e){this[ei]=null,this[Px]=e}get target(){return this[ei]}get type(){return this[Px]}};Object.defineProperty(sn.prototype,"target",{enumerable:!0});Object.defineProperty(sn.prototype,"type",{enumerable:!0});var ir=class extends sn{constructor(e,n={}){super(e),this[Ax]=n.code===void 0?0:n.code,this[Rx]=n.reason===void 0?"":n.reason,this[Dx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Ax]}get reason(){return this[Rx]}get wasClean(){return this[Dx]}};Object.defineProperty(ir.prototype,"code",{enumerable:!0});Object.defineProperty(ir.prototype,"reason",{enumerable:!0});Object.defineProperty(ir.prototype,"wasClean",{enumerable:!0});var ti=class extends sn{constructor(e,n={}){super(e),this[Tx]=n.error===void 0?null:n.error,this[Cx]=n.message===void 0?"":n.message}get error(){return this[Tx]}get message(){return this[Cx]}};Object.defineProperty(ti.prototype,"error",{enumerable:!0});Object.defineProperty(ti.prototype,"message",{enumerable:!0});var as=class extends sn{constructor(e,n={}){super(e),this[kx]=n.data===void 0?null:n.data}get data(){return this[kx]}};Object.defineProperty(as.prototype,"data",{enumerable:!0});var _S={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[os]&&o[Yd]===e&&!o[os])return;let i;if(t==="message")i=function(a,d){let u=new as("message",{data:d?a:a.toString()});u[ei]=this,ta(e,this,u)};else if(t==="close")i=function(a,d){let u=new ir("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[ei]=this,ta(e,this,u)};else if(t==="error")i=function(a){let d=new ti("error",{error:a,message:a.message});d[ei]=this,ta(e,this,d)};else if(t==="open")i=function(){let a=new sn("open");a[ei]=this,ta(e,this,a)};else return;i[os]=!!n[os],i[Yd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Yd]===e&&!n[os]){this.removeListener(t,n);break}}};Ox.exports={CloseEvent:ir,ErrorEvent:ti,Event:sn,EventTarget:_S,MessageEvent:as};function ta(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var na=de((ED,Nx)=>{"use strict";var{tokenChars:cs}=Yr();function Ht(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function yS(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,a=!1,d,u,f=-1,x=-1,p=-1,m=0;for(;m<t.length;m++)if(x=t.charCodeAt(m),d===void 0)if(p===-1&&cs[x]===1)f===-1&&(f=m);else if(m!==0&&(x===32||x===9))p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let _=t.slice(f,p);x===44?(Ht(e,_,n),n=Object.create(null)):d=_,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(u===void 0)if(p===-1&&cs[x]===1)f===-1&&(f=m);else if(x===32||x===9)p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),Ht(n,t.slice(f,p),!0),x===44&&(Ht(e,d,n),n=Object.create(null),d=void 0),f=p=-1}else if(x===61&&f!==-1&&p===-1)u=t.slice(f,m),f=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(o){if(cs[x]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);f===-1?f=m:i||(i=!0),o=!1}else if(a)if(cs[x]===1)f===-1&&(f=m);else if(x===34&&f!==-1)a=!1,p=m;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(x===34&&t.charCodeAt(m-1)===61)a=!0;else if(p===-1&&cs[x]===1)f===-1&&(f=m);else if(f!==-1&&(x===32||x===9))p===-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let _=t.slice(f,p);i&&(_=_.replace(/\\/g,""),i=!1),Ht(n,u,_),x===44&&(Ht(e,d,n),n=Object.create(null),d=void 0),u=void 0,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(f===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let v=t.slice(f,p);return d===void 0?Ht(e,v,n):(u===void 0?Ht(n,v,!0):i?Ht(n,u,v.replace(/\\/g,"")):Ht(n,u,v),Ht(e,d,n)),e}function bS(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(o=>{let a=i[o];return Array.isArray(a)||(a=[a]),a.map(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Nx.exports={format:bS,parse:yS}});var oa=de((ID,$x)=>{"use strict";var ES=pe("events"),vS=pe("https"),SS=pe("http"),Fx=pe("net"),IS=pe("tls"),{randomBytes:AS,createHash:kS}=pe("crypto"),{Duplex:vD,Readable:SD}=pe("stream"),{URL:Xd}=pe("url"),Dn=Jr(),TS=$d(),CS=Jd(),{isBlob:RS}=Yr(),{BINARY_TYPES:Mx,CLOSE_TIMEOUT:PS,EMPTY_BUFFER:ra,GUID:DS,kForOnEventAttribute:Qd,kListener:OS,kStatusCode:LS,kWebSocket:Ve,NOOP:zx}=nn(),{EventTarget:{addEventListener:NS,removeEventListener:MS}}=Lx(),{format:BS,parse:FS}=na(),{toBuffer:zS}=is(),Ux=Symbol("kAborted"),el=[8,13],on=["CONNECTING","OPEN","CLOSING","CLOSED"],US=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_e=class t extends ES{constructor(e,n,i){super(),this._binaryType=Mx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ra,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]),Hx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Mx.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let o=new TS({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new CS(e,this._extensions,i.generateMask);this._receiver=o,this._sender=a,this._socket=e,o[Ve]=this,a[Ve]=this,e[Ve]=this,o.on("conclude",qS),o.on("drain",jS),o.on("error",WS),o.on("message",KS),o.on("ping",$S),o.on("pong",VS),a.onerror=ZS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",jx),e.on("data",sa),e.on("end",Wx),e.on("error",Kx),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,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ft(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())}),qx(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){tl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ra,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){tl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ra,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){tl(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Dn.extensionName]||(o.compress=!1),this._sender.send(e||ra,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ft(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(_e,"CONNECTING",{enumerable:!0,value:on.indexOf("CONNECTING")});Object.defineProperty(_e.prototype,"CONNECTING",{enumerable:!0,value:on.indexOf("CONNECTING")});Object.defineProperty(_e,"OPEN",{enumerable:!0,value:on.indexOf("OPEN")});Object.defineProperty(_e.prototype,"OPEN",{enumerable:!0,value:on.indexOf("OPEN")});Object.defineProperty(_e,"CLOSING",{enumerable:!0,value:on.indexOf("CLOSING")});Object.defineProperty(_e.prototype,"CLOSING",{enumerable:!0,value:on.indexOf("CLOSING")});Object.defineProperty(_e,"CLOSED",{enumerable:!0,value:on.indexOf("CLOSED")});Object.defineProperty(_e.prototype,"CLOSED",{enumerable:!0,value:on.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_e.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_e.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Qd])return e[OS];return null},set(e){for(let n of this.listeners(t))if(n[Qd]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Qd]:!0})}})});_e.prototype.addEventListener=NS;_e.prototype.removeEventListener=MS;$x.exports=_e;function Hx(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:PS,protocolVersion:el[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,!el.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${el.join(", ")})`);let a;if(e instanceof Xd)a=e;else try{a=new Xd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),t._url=a.href;let d=a.protocol==="wss:",u=a.protocol==="ws+unix:",f;if(a.protocol!=="ws:"&&!d&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!a.pathname?f="The URL's pathname is empty":a.hash&&(f="The URL contains a fragment identifier"),f){let S=new SyntaxError(f);if(t._redirects===0)throw S;ia(t,S);return}let x=d?443:80,p=AS(16).toString("base64"),m=d?vS.request:SS.request,v=new Set,_;if(o.createConnection=o.createConnection||(d?GS:HS),o.defaultPort=o.defaultPort||x,o.port=a.port||x,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Dn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=BS({[Dn.extensionName]:_.offer()})),n.length){for(let S of n){if(typeof S!="string"||!US.test(S)||v.has(S))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(S)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),u){let S=o.path.split(":");o.socketPath=S[0],o.path=S[1]}let b;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:a.host;let S=i&&i.headers;if(i={...i,headers:{}},S)for(let[I,T]of Object.entries(S))i.headers[I.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let S=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!S||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,S||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),b=t._req=m(o),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=m(o);o.timeout&&b.on("timeout",()=>{ft(t,b,"Opening handshake has timed out")}),b.on("error",S=>{b===null||b[Ux]||(b=t._req=null,ia(t,S))}),b.on("response",S=>{let I=S.headers.location,T=S.statusCode;if(I&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){ft(t,b,"Maximum redirects exceeded");return}b.abort();let R;try{R=new Xd(I,e)}catch{let P=new SyntaxError(`Invalid URL: ${I}`);ia(t,P);return}Hx(t,R,n,i)}else t.emit("unexpected-response",b,S)||ft(t,b,`Unexpected server response: ${S.statusCode}`)}),b.on("upgrade",(S,I,T)=>{if(t.emit("upgrade",S),t.readyState!==_e.CONNECTING)return;b=t._req=null;let R=S.headers.upgrade;if(R===void 0||R.toLowerCase()!=="websocket"){ft(t,I,"Invalid Upgrade header");return}let E=kS("sha1").update(p+DS).digest("base64");if(S.headers["sec-websocket-accept"]!==E){ft(t,I,"Invalid Sec-WebSocket-Accept header");return}let P=S.headers["sec-websocket-protocol"],D;if(P!==void 0?v.size?v.has(P)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":v.size&&(D="Server sent no subprotocol"),D){ft(t,I,D);return}P&&(t._protocol=P);let M=S.headers["sec-websocket-extensions"];if(M!==void 0){if(!_){ft(t,I,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=FS(M)}catch{ft(t,I,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(N);if(J.length!==1||J[0]!==Dn.extensionName){ft(t,I,"Server indicated an extension that was not requested");return}try{_.accept(N[Dn.extensionName])}catch{ft(t,I,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Dn.extensionName]=_}t.setSocket(I,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(b,t):b.end()}function ia(t,e){t._readyState=_e.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function HS(t){return t.path=t.socketPath,Fx.connect(t)}function GS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Fx.isIP(t.host)?"":t.host),IS.connect(t)}function ft(t,e,n){t._readyState=_e.CLOSING;let i=new Error(n);Error.captureStackTrace(i,ft),e.setHeader?(e[Ux]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ia,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function tl(t,e,n){if(e){let i=RS(e)?e.size:zS(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${on[t.readyState]})`);process.nextTick(n,i)}}function qS(t,e){let n=this[Ve];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Ve]!==void 0&&(n._socket.removeListener("data",sa),process.nextTick(Gx,n._socket),t===1005?n.close():n.close(t,e))}function jS(){let t=this[Ve];t.isPaused||t._socket.resume()}function WS(t){let e=this[Ve];e._socket[Ve]!==void 0&&(e._socket.removeListener("data",sa),process.nextTick(Gx,e._socket),e.close(t[LS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Bx(){this[Ve].emitClose()}function KS(t,e){this[Ve].emit("message",t,e)}function $S(t){let e=this[Ve];e._autoPong&&e.pong(t,!this._isServer,zx),e.emit("ping",t)}function VS(t){this[Ve].emit("pong",t)}function Gx(t){t.resume()}function ZS(t){let e=this[Ve];e.readyState!==_e.CLOSED&&(e.readyState===_e.OPEN&&(e._readyState=_e.CLOSING,qx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function qx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function jx(){let t=this[Ve];if(this.removeListener("close",jx),this.removeListener("data",sa),this.removeListener("end",Wx),t._readyState=_e.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Ve]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Bx),t._receiver.on("finish",Bx))}function sa(t){this[Ve]._receiver.write(t)||this.pause()}function Wx(){let t=this[Ve];t._readyState=_e.CLOSING,t._receiver.end(),this.end()}function Kx(){let t=this[Ve];this.removeListener("error",Kx),this.on("error",zx),t&&(t._readyState=_e.CLOSING,this.destroy())}});var Yx=de((kD,Jx)=>{"use strict";var AD=oa(),{Duplex:JS}=pe("stream");function Vx(t){t.emit("close")}function YS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Zx(t){this.removeListener("error",Zx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function XS(t,e){let n=!0,i=new JS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,d){let u=!d&&i._readableState.objectMode?a.toString():a;i.push(u)||t.pause()}),t.once("error",function(a){i.destroyed||(n=!1,i.destroy(a))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,a){if(t.readyState===t.CLOSED){a(o),process.nextTick(Vx,i);return}let d=!1;t.once("error",function(f){d=!0,a(f)}),t.once("close",function(){d||a(o),process.nextTick(Vx,i)}),n&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,a,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,a,d)});return}t.send(o,d)},i.on("end",YS),i.on("error",Zx),i}Jx.exports=XS});var nl=de((TD,Xx)=>{"use strict";var{tokenChars:QS}=Yr();function e1(t){let e=new Set,n=-1,i=-1,o=0;for(o;o<t.length;o++){let d=t.charCodeAt(o);if(i===-1&&QS[d]===1)n===-1&&(n=o);else if(o!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=o);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let a=t.slice(n,o);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return e.add(a),e}Xx.exports={parse:e1}});var sp=de((RD,ip)=>{"use strict";var t1=pe("events"),aa=pe("http"),{Duplex:CD}=pe("stream"),{createHash:n1}=pe("crypto"),Qx=na(),sr=Jr(),r1=nl(),i1=oa(),{CLOSE_TIMEOUT:s1,GUID:o1,kWebSocket:a1}=nn(),c1=/^[+/0-9A-Za-z]{22}==$/,ep=0,tp=1,rp=2,rl=class extends t1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:s1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:i1,...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=aa.createServer((i,o)=>{let a=aa.STATUS_CODES[426];o.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),o.end(a)}),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=d1(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,a,d)=>{this.handleUpgrade(o,a,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ep}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===rp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ds,this);return}if(e&&this.once("close",e),this._state!==tp)if(this._state=tp,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(ds,this):process.nextTick(ds,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ds(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,o){n.on("error",np);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){or(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){or(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!c1.test(a)){or(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){or(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ls(n,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=r1.parse(f)}catch{or(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&p!==void 0){let v=new sr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Qx.parse(p);_[sr.extensionName]&&(v.accept(_[sr.extensionName]),m[sr.extensionName]=v)}catch{or(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(_,b,S,I)=>{if(!_)return ls(n,b||401,S,I);this.completeUpgrade(m,a,x,e,n,i,o)});return}if(!this.options.verifyClient(v))return ls(n,401)}this.completeUpgrade(m,a,x,e,n,i,o)}completeUpgrade(e,n,i,o,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[a1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ep)return ls(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${n1("sha1").update(n+o1).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;m&&(x.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[sr.extensionName]){let m=e[sr.extensionName].params,v=Qx.format({[sr.extensionName]:[m]});x.push(`Sec-WebSocket-Extensions: ${v}`),p._extensions=e}this.emit("headers",x,o),a.write(x.concat(`\r
|
|
15
15
|
`).join(`\r
|
|
16
|
-
`)),a.removeListener("error",np),
|
|
16
|
+
`)),a.removeListener("error",np),p.setSocket(a,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ds,this)})),u(p,o)}};ip.exports=rl;function d1(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 ds(t){t._state=rp,t.emit("close")}function np(){this.destroy()}function ls(t,e,n,i){n=n||aa.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} ${aa.STATUS_CODES[e]}\r
|
|
17
17
|
`+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
|
|
18
18
|
`)+`\r
|
|
19
19
|
\r
|
|
20
|
-
`+n)}function sr(t,e,n,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,sr),t.emit("wsClientError",d,n,e)}else ds(n,i,o,a)}});var wp=ce(ze=>{"use strict";var L=j;(function(t,e){let n=j,i=t();for(;;)try{if(-parseInt(n(1439))/1+-parseInt(n(564))/2+-parseInt(n(472))/3*(-parseInt(n(558))/4)+parseInt(n(393))/5+-parseInt(n(448))/6*(parseInt(n(1465))/7)+parseInt(n(407))/8+-parseInt(n(1573))/9*(-parseInt(n(1557))/10)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(fa,681100);var m1=Object[L(167)+L(893)],w1=Object["getOwnPr"+L(1221)+L(266)],hp=(t,e)=>function(){return t&&(e=(0,t[w1(t)[0]])(t=0)),e},_1=(t,e)=>{for(var n in e)m1(t,n,{get:e[n],enumerable:!0})};function y1(){return cp||(cp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function b1(){let t=L;return dp||(dp=[IDBCursor[t(1068)+"e"][t(1566)],IDBCursor[t(1068)+"e"].continue,IDBCursor[t(1068)+"e"][t(1077)+t(509)+"ey"]])}function E1(t){let e=L,n={huGBW:function(o,a){return o!=a},eIosp:function(o,a){return o instanceof a},zcwYI:"DPMgg",IzNna:e(1286),HBhvE:function(o,a){return o(a)},KfoJy:function(o){return o()},XyKRZ:function(o,a){return o(a)},GjgwT:function(o,a){return o===a},WijQP:e(397),qRqKp:e(863)},i=new Promise((o,a)=>{let d=e,u={PnZVI:function(h,x){return n[j(475)](h,x)},LkIVr:function(h,x){return h+x}};if(n[d(1296)](d(397),n[d(1430)])){let h=()=>{let m=d,S={OZRFR:function(_,v){return n[j(1591)](_,v)},zEHga:m(1289),ugrEi:function(_,v){return n[m(784)](_,v)},LepiX:m(221)+m(184)};if(n.zcwYI===m(663))t[m(1531)+m(696)+"ner"](n[m(948)],x),t[m(1531)+"entListe"+m(1409)](m(863),g);else return S[m(292)](S.zEHga,typeof _0x2ddf80)&&(S.ugrEi(_0x4ac679,_0x21683e)||_0x20dc9d[m(689)]&&_0x172887[m(689)]instanceof _0x530a05)||S.zEHga!=typeof _0x5ca73e?"":(_0x16af5f[m(1029)](_0x1c3b23),S[m(633)])},x=()=>{let m=d;n[m(1129)](o,n.HBhvE(Ut,t[m(1560)])),h()},g=()=>{let m=d;n[m(1129)](a,t[m(863)]),n.KfoJy(h)};t[d(1164)+d(819)](n[d(948)],x),t[d(1164)+d(819)](n[d(1339)],g)}else{let h=u[d(125)](_0x57cc10,_0x167c22),x=_0x41e498[d(1123)];return _0x1f43cb.limit=u[d(804)](_0x1b0ef6[d(1574)],h),x}});return i.then(o=>{n[e(784)](o,IDBCursor)&&rl.set(o,t)})[e(1393)](()=>{}),la.set(i,t),i}function v1(t){let e=L,n={kSeQZ:function(o,a){return o===a},gcJCJ:"error",kcyds:"abort",soViq:function(o){return o()},Zqidf:function(o,a){return o(a)},URrMz:function(o){return o()},lOlLs:e(517)};if(da[e(1503)](t))return;let i=new Promise((o,a)=>{let d=e,u={TudgC:function(m){return m()},JfnFP:function(m){return n[j(1421)](m)},RKvuk:function(m,S){return n[j(900)](m,S)},kLEvw:d(630)+"or",ZPmaM:function(m){return n[d(1297)](m)}},h=()=>{let m=d;if(n[m(993)]("omXjR",m(1541)))return new _0x49ab79(_0x18c4e8,{data:_0x19585a,message:_0x561dd6});t[m(1531)+"entListener"](m(517),x),t[m(1531)+m(696)+m(1409)](n[m(1217)],g),t[m(1531)+m(696)+"ner"](n[m(179)],g)},x=()=>{let m=d;u.TudgC(o),u[m(1394)](h)},g=()=>{let m=d;u[m(1322)](a,t[m(863)]||new DOMException(u[m(237)],u.kLEvw)),u[m(247)](h)};t[d(1164)+d(819)](n[d(898)],x),t.addEventListener(n.gcJCJ,g),t[d(1164)+d(819)](n[d(179)],g)});da[e(1094)](t,i)}function S1(t){ua=t(ua)}function I1(t){let e=L,n={nhtOu:function(i,o){return i(o)},oGPns:function(i,o){return i(o)},qBuXM:function(i,o){return i(o)},cpyHK:function(i,o){return i===o},LPEaF:function(i,o){return i in o},FSmjW:"objectStoreNames"};return n[e(1073)](t,IDBDatabase[e(1068)+"e"]["transact"+e(1358)])&&!n.LPEaF(n[e(941)],IDBTransaction[e(1068)+"e"])?function(i,...o){let a=e,d=t.call(n[a(1210)](ls,this),i,...o);return nl[a(1094)](d,i.sort?i[a(811)]():[i]),n.oGPns(Ut,d)}:b1()[e(505)](t)?function(...i){let o=e;return t[o(1351)](n.qBuXM(ls,this),i),n[o(1360)](Ut,rl[o(1058)](this))}:function(...i){let o=e;return n[o(1360)](Ut,t[o(1351)](n[o(1210)](ls,this),i))}}function k1(t){let e=L,n={FIlhy:function(i,o){return i===o},FUpyA:function(i,o){return i(o)},hguuX:function(i,o,a){return i(o,a)},ziArI:function(i){return i()}};return n[e(1323)](typeof t,e(422))?n[e(223)](I1,t):(t instanceof IDBTransaction&&v1(t),n[e(665)](xp,t,n[e(1010)](y1))?new Proxy(t,ua):t)}function Ut(t){let e=L,n={YHsLD:function(o,a){return o instanceof a},uAngT:function(o,a){return o(a)},gCVno:function(o,a){return o!==a}};if(n[e(789)](t,IDBRequest))return n.uAngT(E1,t);if(aa[e(1503)](t))return aa[e(1058)](t);let i=k1(t);return n.gCVno(i,t)&&(aa.set(t,i),la[e(1094)](i,t)),i}var xp,cp,dp,rl,da,nl,aa,la,ua,ls,lp=hp({"node_modules/idb/build/wrap-idb-value.js"(){let t=L,e={KytcA:function(n,i){return n<=i},StLbl:t(984)+t(1353)+t(609)+t(414)+t(1028),PbTYs:function(n,i){return n===i},CjxBA:function(n,i){return n+i},UWMhv:function(n,i){return n===i},MerCb:t(1282),vwHnQ:function(n,i){return n instanceof i},NFWbi:t(1106),PlAug:function(n,i){return n===i},IdcAA:t(821)+t(1092),sPsei:function(n,i){return n===i},SAPBf:t(1415),LPOdf:function(n,i){return n(i)},zaeLC:function(n,i,o,a){return n(i,o,a)},soksl:function(n,i){return n instanceof i},VRhjX:function(n,i){return n===i},qHiuz:function(n,i){return n!==i},dHmZO:t(130)};xp=(n,i)=>i[t(508)](o=>n instanceof o),rl=new WeakMap,da=new WeakMap,nl=new WeakMap,aa=new WeakMap,la=new WeakMap,ua={get(n,i,o){let a=t;if(e.UWMhv(e[a(1138)],e[a(1138)])){if(e[a(1001)](n,IDBTransaction)){if(e[a(1076)](i,e.NFWbi))return da.get(n);if(e[a(1213)](i,e[a(1014)]))return n[a(821)+a(1092)]||nl[a(1058)](n);if(e[a(1549)](i,e[a(150)]))return o["objectSt"+a(1092)][1]?void 0:o[a(821)+a(1342)](o[a(821)+a(1092)][0])}return e[a(1259)](Ut,n[i])}else return e[a(473)](_0x46b7ea,_0x2a45a9)?_0xe1acf2[a(1307)](new _0x109bc5(e[a(1308)])):(_0x4ed1d9=_0x443580,e[a(132)](_0x18b09b,_0x3a8591[a(1276)])?_0x5409f7.resolve():_0x44c3d5[_0x1e119f][a(456)](_0x32c595)(_0x4b0271,_0x392d89[a(456)](null,e[a(330)](_0x5c7dfc,1))))},set(n,i,o){return n[i]=o,!0},has(n,i){let o=t;if(e.soksl(n,IDBTransaction)&&(e[o(1293)](i,e.NFWbi)||i===e[o(150)]))if(e[o(699)](e[o(1198)],e[o(1198)]))e[o(677)](_0x1f8057,this,_0x47fe74,[_0x20b080,_0x26c436,_0x52ce56,_0x32ba7a,_0x172dd9,_0x1f530e]);else return!0;return i in n}},ls=n=>la[t(1058)](n)}}),pp={};_1(pp,{deleteDB:()=>T1,openDB:()=>A1,unwrap:()=>ls,wrap:()=>Ut});function A1(t,e,{blocked:n,upgrade:i,blocking:o,terminated:a}={}){let d=L,u={oSXPd:function(g,m,S,_,v){return g(m,S,_,v)},hyAOV:function(g,m){return g(m)},PHOki:function(g,m){return g(m)},AjgNv:d(577),PztRO:d(260)+d(1492),obOBd:d(698)+d(1012),ebPxf:d(1348)},h=indexedDB.open(t,e),x=u[d(534)](Ut,h);return i&&h[d(1164)+d(819)](u[d(1581)],g=>{let m=d;u[m(520)](i,u[m(1256)](Ut,h[m(1560)]),g[m(1046)+"on"],g.newVersion,u[m(534)](Ut,h[m(961)+m(1358)]))}),n&&h["addEvent"+d(819)](u.ebPxf,()=>n()),x[d(1444)](g=>{let m=d;a&&g[m(1164)+m(819)](u[m(775)],()=>a()),o&&g[m(1164)+m(819)](u[m(225)],()=>o())})[d(1393)](()=>{}),x}function T1(t,{blocked:e}={}){let n=L,i={KhJBk:n(1348),ZmmkI:function(a,d){return a(d)}},o=indexedDB["deleteDa"+n(729)](t);return e&&o[n(1164)+n(819)](i[n(226)],()=>e()),i[n(1328)](Ut,o)[n(1444)](()=>{})}function up(t,e){let n=L,i={SDaaA:n(923),jKEOJ:function(h,x){return h in x},qnnxC:n(1289)};if(!(t instanceof IDBDatabase&&!i[n(528)](e,t)&&typeof e===i[n(742)]))return;if(ca[n(1058)](e))return ca[n(1058)](e);let o=e.replace(/FromIndex$/,""),a=e!==o,d=mp[n(505)](o);if(!i.jKEOJ(o,(a?IDBIndex:IDBObjectStore).prototype)||!(d||gp[n(505)](o)))return;let u=async function(h,...x){let g=n,m=this[g(961)+"ion"](h,d?g(977)+"e":i[g(1253)]),S=m[g(1415)];return a&&(S=S[g(917)](x[g(135)]())),(await Promise.all([S[o](...x),d&&m[g(1106)]]))[0]};return ca.set(e,u),u}var gp,mp,ca,C1=hp({"node_modules/idb/build/index.js"(){let t=L,e={weZJe:"5|0|1|2|4|3",jrFuq:t(421),XDskE:"getAll",DlADF:"getAllKeys",HGWGC:t(1298),DxtWw:t(797),Gpncp:t(693),EqaQk:"delete",iqKRj:t(155),zQlWQ:function(o,a){return o(a)}},n=e.weZJe[t(690)]("|"),i=0;for(;;){switch(n[i++]){case"0":lp();continue;case"1":gp=[t(1058),e.jrFuq,e[t(1460)],e[t(631)],e[t(1083)]];continue;case"2":mp=[e[t(920)],e[t(1192)],e[t(839)],e.iqKRj];continue;case"3":e.zQlWQ(S1,o=>({...o,get:(a,d,u)=>up(a,d)||o.get(a,d,u),has:(a,d)=>!!up(a,d)||o[t(1503)](a,d)}));continue;case"4":ca=new Map;continue;case"5":lp();continue}break}}}),P1={idb:function(t){let e=L;t[e(947)]=Promise[e(1596)]()[e(1444)](()=>(C1(),pp)).then(function(n){return n})}},fp={};function zt(t){let e=L,n={bNXaw:e(813)+"4",rYzMo:function(u,h){return u!==h}},i=n[e(1570)][e(690)]("|"),o=0;for(;;){switch(i[o++]){case"0":if(n[e(1142)](void 0,a))return a[e(947)];continue;case"1":P1[t](d,d[e(947)],zt);continue;case"2":var a=fp[t];continue;case"3":var d=fp[t]={exports:{}};continue;case"4":return d[e(947)]}break}}zt.d=(t,e)=>{let n=j;for(var i in e)zt.o(e,i)&&!zt.o(t,i)&&Object[n(167)+n(893)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=L;zt.o=(e,n)=>Object.prototype[t(1144)+t(893)][t(687)](e,n)})(),(()=>{let t=L,e={hOLZo:function(n,i){return n!=i},MdSVe:t(913)+"le"};zt.r=n=>{let i=t;e[i(794)](i(233)+"d",typeof Symbol)&&Symbol[i(1509)+i(385)]&&Object[i(167)+i(893)](n,Symbol[i(1509)+i(385)],{value:"Module"}),Object["definePr"+i(893)](n,e[i(1212)],{value:!0})}})();function fa(){let t=["AKvYquu","EvnWrKe","AgvKtwf4uMu","y29UBMvJDca","wuH2qvq","vhrPD24","z2vtEw5J","tfzhquK","BezSDxnO","y29UDgv4Da","tMPnDM0","BffwtLK","D2Toshu","vwnjEKK","BMvY","v3D2rfO","Dg9cExrLC0i","tw1bEei","r3nts3a","zxj2AwnL","C3rVCMu","CKrUD1C","r3nIq1O","vMngAgy","BeHHBMrSzxi","u1bbrvC","C29wAxe","Agncz2C","vKDMrey","se5NufG","B3jRzxjhBg8","vw1UDuy","DgjrtNm","zw1PDa","x3fVC0rc","v2LQuva","EvnYu1C","x2LUAxrhBg8","u2TPCcbWyxm","r09bCwG","rvjst1i","t25VA24","Cg9PBNrbBMq","BNnlteO","ote0ntK3B3znsNLV","tuTAB3u","CeXyt2O","r3zetuO","AxnrB1nnzxm","DgHLBG","Cgf5Bg9Hzeu","yMLUyxj5vhK","x2jPBMfYEvq","Dw5ZAwDUzwq","AwDUDNK","zMLSDgvY","t1bftG","s1j0vNG","DwvNAMu","v01bq3u","tLfVwey","Fdr8m3W3","vezNvwK","D1foDuS","zxjFywnRx20","werZA0u","EMrUDLG","ywnRDxbfBMq","CMHmq0e","CMThz3C","mtrbu2rxDNy","x29UugfNzu4","Au5Tyue","AKLSs1C","uKHmA2W","C2XPy2u","v0DpEgC","wLz2zfO","qLvpv1m","Ehfny2G","EgHNBfa","rLb5s2C","AvrLthe","x2LUDgvYDMe","ignVzgu6ia","rM1KBu4","tvnguMK","tePkz0O","CKjos3y","zMLSzw5HBwu","ywWGy3vYC28","t1bftL9fuLi","BfP5r2y","y29UC3rYDwm","DMfSDwvZ","z0Tcv1q","u2vXsuq","AgfUz2u","x29UrxjYB3i","AgLNAa","qxLdrxu","D1LVv00","s1nYEKS","Afr3zfq","B0vKwMO","rwvcqNa","wMH4s0q","uKHPrha","AgfZ","zgv2AwnLx2K","zwn0","CffLDKG","CwDpteu","zKPHrLa","Dg9tDhjPBMC","wK1Mq1q","EMTHCfu","BNrbBMrvCgq","x29WDgLVBNm","y2vZC0HHBMq","Exn2qwu","ywnOzwqSihC","yK9pCvq","yxnZAwDU","vwj2DNa","Aw5N","ihrPBwvVDxq","BLb5rhq","BNbqt1y","BNrLCG","C2v0sxrLBq","qvf0s3K","AxLHwwS","zvjysvC","Aev6Cxu","Ae1ywge","CMvTB3zLrxy","ww5jt24","BIWGAg9ZDg4","zxmGCMvHy2G","igzPzwXKoIa","v2vPEgLUsLm","C3vurMG","yxKSihrYEsa","y2HLy2Tszwe","u0nwBNC","B0nNsLq","B25ozxr3B3i","rNDJtfG","BgLZDgvUtMu","wvvYrLC","EuH0zw0","CgfNzwHPzgu","EfLPywC","C1bZzwK","C2nYAxb0","D2LSBfjLy28","ywXqBxG","zxPVrhK","ugrsvMS","y3jLyxrLrxi","yNL0zxm","mtG0me1gAKLvEq","wxzkv2S","zMDLu2S","CMvZDwX0","DfPsDhi","DLrYALG","BNrWqM8","Aevhtfe","B2nRzxq","ywr2yw5Jzq","Cufrs3K","lcbxzwjtB2m","BM93","yK5yyxC","l3DZl3yY","y2HHCKnVzgu","mte3ndqXENHQsKvx","B2zMC2v0","zMLUza","x2LZqNjVD3m","thDnC2S","ywX3yxLZ","vxbKyxrLq28","x0rctMfTzq","B2jpqMq","zxjFBxnNAwq","uxnTALm","yKfnq3O","quXm","DujrD2C","vKDZufy","y3vYCMvUDeK","r0DQEwu","Bhm6ia","AhvhqLC","qNbLB0e","DgL6wwG","zMHgA1y","DNzREue","CMvZB2X2zq","z1rPBwvVDxq","thvMCum","y2uGBM90igK","EeTfvvK","C2fTzey","ug5AvKK","Aw5PDcbrB1m","uKPtruq","B25JBg9Zzq","t3jjz1m","BuDAqvO","zfDVCMTLCKC","ugjuwxm","uMvHzcbWyxm","sxzVq20","C2HPzNq","D3L0tgq","ywDLu2HVDW","B3nLrxzLBNq","tg9Nsuq","z1H2vwK","zfbLtxC","x2zVCM1HDeu","qvrqvLG","DMvYC2LVBG","C2vYDMLJzq","ruzXv0S","s29MtvC","wu9oEK0","o2nOyxjZzxq","u0fqqMy","ug9lsKO","r1L2DhK","wKDfzKC","x2n1CNnVCK4","y2XLyxi","rLjptLrjrvi","C09YvLm","ywrKq291BNq","vvPWBge","twvZC2fNzuu","D2L0ruO","EfPHt0i","suXNz3y","z09Nv2K","tLrMuxm","Be9kDue","zgvMAw5Luhi","su1Xq2i","CKLwzMC","zMzLCG","DeLK","surHwgO","thvzAuq","Bwf4tg9ZC0m","D3m6lY8","jMPZy2fSBgi","wg9bBvO","tLPWzuC","A2n5zhm","CMfTzq","vMHKAMC","zwLxq2u","sgjsvMW","Aw9Ul2PZB24","ywnRtxnNswq","rwHKEfy","su5Vr3C","t3bLBKv2zw4","v3DJq2O","D2fZq2XLyw4","DKHKCvK","vLz4zuG","vLj4C0K","uurqAxm","uwLYEeG","ywnRx2nVzgu","pxv0zI04","C3vIC3rYAw4","ruLnyLC","ChvwENO","uLDtvgO","B2P4D2m","Ae9Wzw5fDMu","z2j2vwK","ALnns08","uxvLDwu","D1j1yuO","ANjpzvy","BK96veG","DNDXBuS","Ec1TC2CTCw8","B25tDg9Wsw0","ihzHBgLKihm","yLf1zvy","uuXcAue","y3vYC29Yx24","DcbSAw1PDa","Cerfvg0","y2ffu3u","q3vZDg9Trxi","yxbWBgLJyxq","q0XtrK4","rLvWEue","x3jLBw92zvC","uhP0uK8","s2HkqMS","BNDUt3a","uuvvuK8","A3rQq20","BMfTzq","wLH3v2O","C2vUza","Dw5KzwzPBMu","y3jLyxrLt2i","v1rVz2S","uhLqEu4","A0XfDNC","yuT0wge","CNjVCK1LC3m","zePVrwK","zw5XDwv1zq","B25MDwi","CfLUyvi","AevYCM9Yrxy","CMvKDwnL","ihrYEsbYzwm","wLbTyu0","nhWZ","qKPdv3e","x3bHDgHlzxK","CgjICdi","BwvZC2fNzv8","uwXoufe","Bwv0Ag9K","CMfNzvn5BMm","yxrHlcbKyxq","tKvjBui","Bg9IywXty28","wLDPrhq","DMvYC2LVBMm","B1zIENm","CuLxqNC","x2nSzwfYugK","wenIv0G","yuTiBeq","BwvZ","vxf0vMm","thL0yM0","BNvTyMvY","y2HnyxHdB3u","BMvJDa","Cg9W","DhLWzq","uMPlDLq","AKDjt2i","tMfmCwS","DMfS","qLzcrLG","Bg9N","CMv0CNLdB3u","y25kt0O","Ec1TC2CTy3u","wfzPtxy","uwDnB0i","DhHyu0m","Dg9hzw5LCMe","uxvZsxG","rKPAzMG","zMzMzG","yMPNrgi","txfTAxm","t1PsrLi","tgXUuw8","DgvmB2Djre4","CgLUz0LUDgu","twLZC2LUzYa","BuPYDKK","D256wNK","zK5qyuC","DhjPzxmGCMu","qvLlthy","v0T6uLm","Ae1LC3nHz2u","rujWuxa","CMvJB25Uzwm","C0Xf","EKHvr0K","vuHuy1e","wgrYruu","tg9NsurozxC","zMLN","uhLoAfq","sKj4rMm","ze55wxy","C1PHyxa","r2TTv0y","D1juEKC","Ee9utwq","C0nVDw50zxi","zxjFDhrS","DMvUDa","r2XJvKu","uuvMu2G","ExbL","zhbfBhq","BwLUAvbYB2C","y3vYCMvUDeu","B1DIz1e","x2LZsw5PDa","q2P4qKe","sfrRB0S","BMDLza","Cujgzvy","zw5HyMXLuw8","BwvZC2fNztO","BwvY","s21Wsxq","BxnNsuq","ywDL","z3HVrwi","DvHKAxe","Aw9UvgLTzw8","C1nYDLG","wwX0Auy","uK9jr3q","wgLZvLu","zv9ZDwnJzxm","CLfdBKu","uhbVCNa","sw9NwNa","Agvbqw8","yxnL","AujqqxO","B25mAw5L","tgzVEfm","tMXksei","surKwgi","yMfSu2nVCgu","BMLbt0m","CMvHzhLtDge","y0XbuwC","x2HHBMrSzu8","tg9JAW","Aw50zwDLCIa","ALfRq2W","re5cwM0","B3jpBMXPBMu","BMnVzgLUzW","y2XVC2veqG","ign1CNnVCIa","B3bLBG","yvHksfa","Aur1whi","ihrPBwvZ","B2f3vKi","wMHNug8","x2rLC3rYB3K","twz3zNi","zNjVBujPDhm","Bg93","uLbZDMi","qLnyDe4","sK5XtKi","x29UvgLTzw8","vgfN","q2rxuLK","q0HIu2W","vfLNvw0","q3vZDg9Tq2W","vMvTrK4","terrEvG","u0zlyxm","mtqWnZK1mhnWteP5Eq","rhv4ExC","zNjVBunOyxi","BML0AwfSAxO","DLf6wg8","vxnPvwm","zgvJB2rLzey","EhrJzgu","DeLUDgvYy2u","ChvZAa","yxn1yK8","DxbKyxrLq3u","tevRug0","C0Hfzxu","mtu2ndG0mg10wvzbyG","v0vYA0W","vwfpzgS","u2vYDMLJzvC","uhLks04","qLLstNm","Dgv4DfbHEwW","Aw1LCYbPBIa","De1HBMfNzxi","uvbUC3K","q2jnEva","A2n5zNu","x2nVBM5Ly3q","sLbKD3e","z2v0s2v5","zNvUy3rPB24","CxPAyMK","sfrYrvK","Dw50","yMfSrxzLBNq","zLnTz1e","q2TwEKu","C3nHz2vfDMu","vMHZCMC","r1H4A2q","q2jlv00","Bwf4twvZC2e","Ec11C2uT","tMrSr1a","B2HuyuW","y29UBMvJDeu","zw5NDgG","CgLUz0XVC3m","t2jwzgi","qungz3C","CgfNzxnOB3C","AxnAzxjV","Be5prMC","t2L1DuW","Cg9PBNrdB24","BM5Ly3q","mJi4mdi4ofLWvuLbqW","wKHKEw0","uNHVrwC","qwThsxG","DxjS","t29Uy3K","yMLUyxj5","AgvHzgvYCW","yMLUza","qNjPzgDL","DgLTzw91DcW","z29PBMCGyxC","CMvZzxrfBMq","yNv4BK8","z2v0qwXSs2u","Ef9MCM9UDgK","uLr6D3K","CMrRwhe","Axnby2TdBgu","r2TtuuO","vhHmEKi","vhDcEuG","AuXwquG","Aenqr2G","m01Lvu1lvW","s3L0y0e","BuLHyu8","whLluLO","B3vUDa","sK1OCe4","zv90Aw1LB3u","q05ktge","ugv1tuq","BgLUzw5V","zNrXvMC","C3rLBMvYCW","vgr1BfC","B25fCNjVCG","Cejfve4","tg5PDvi","ExLWsxe","BMzbBw0","Ahbvq3C","B1v4DKq","ChjVDg9JB2W","CMvTB3zLq2G","Dhn2C2S","Cw9Z","BKjsswm","yw51Ce1LC3m","yK5zDwe","uKH6Cxi","yMTPu3q","C2v0u3rVCMe","x0vysvnu","Bw5ADuS","y3jLyxrLuMu","Aw5JBhvKzxm","EMfdqw4","s1P5Au4","C29Tzq","uhjPBwfYEuS","y29UBMvJDfm","x3bPBMDmB3m","nhW2Fdn8mNW","zgTfv0m","yujxuNO","x3nVy2TLDa","C2vUzf9Hy2S","y29TCgXLDgu","rvDRru8","CNnVCL92ywW","B1nyugq","CMvJzxzPzwq","AuTkAgm","A2v5CW","EgvJwhm","Dw5RBM93BIa","y2XLyxjtDg8","CM1yvuK","AKTft0O","Dg9cExrLCW","qNnItwe","t3rtqxO","icSG","D2rMvKu","ueHpA2K","CLzHBhvLCW","zwrPyxrLBhK","qw1VDw50","C01YEhK","u25IDfC","CgLUz19VBMm","BwnWr24","lcbOB3n0BMe","u3rYyxrLz3K","t3HAChC","y3vZDg9Tshq","s0jRENm","sLj5BMS","ywrKt25L","sNnxBeW","zMX1C2HfEha","CIb0DhDjra","zxjFAxnFywm","uuTxs3a","zxjHDg9Y","CfHRy2m","sM9fvuK","z2v0sxrLBq","mJuZnZK5nM5Yyu5Oua","Cgr0Cva","x2LZtwLUAvC","zLbyCxC","zM5qrfC","u1Hiquy","mJmXmZGZnejyyxrura","uefgELK","vw5PBxbSzw0","v1zHugC","rxHAExC","AwXK","rgjczxi","Cgf5Bg9Hza","q2X2ruK","s2nMsum","Aw12vxO","u3b6AuC","aaaaaaaaaaa","y2XVC2u","Ahr0Ca","y3jLyxrLq2W","r1DJBg0","veTnC2m","C3rHCNq","DhDVCMTdAge","zLbhwKm","ChrQq3O","vMHUv0S","zMHYBem","BxnN","igfYCMf5yNu","AwrI","EM5bv3C","zcWGDw5RBM8","B25tDgfYDfi","DgLUzYbZzxi","uKvUq1G","veLoEK8","Aw9UB0y","y29UBMvJDgK","x2LUAxq","CM92AwrLigi","zw5KCg9PBNq","z2v0qwXS","BKjstu4","u0jfqMq","ELnXwfq","y29SBM8","ufvjC1m","m3WXFdr8mNW","BhrPCgXLihq","x2nSzwfYvgK","seHsqvu","yw1Lu3bHy2u","zw5HyMXLvhi","sKncAKy","B0TsBNO","yKPmAfq","DezVvg4","ihrVihjLDhi","CMLLC0nVDw4","rLDt","Bxnpy2S","D2LTD0O","rMvcDMu","Dhj1y3rVCIa","zNjVBuj5Dgu","qun2Due","zNjVBNrPzxi","x2vUzhbVAw4","CM9YrxzLBNq","qwjVCNrfCNi","rgXbrey","vwTeAuG","tgvWAvG","B2zM","CMvHzfvjBNq","Dgv4Dc9Qyxy","uezqtee","CxDkCKy","A2Pry3i","Dg9Y","wxrUsuq","DeX3z0e","v2vKEMK","sw9Ss0y","uMvQs2i","z2v0q3vYC28","tKfusvzfx0u","C0nZC1K","DurgsLO","sMXstKu","svzzEMW","Dg9iyxnO","z1vRAgy","ChDIrNy","x3DZ","z2vjBMzVu3K","C2fNzq","z2vY","AM9PBG","yMrFzgLK","AxzArxC","CgfiwvO","rfbnz2C","q0Xpu0ve","AgD1DvG","t0DYzuW","rvnyq1G","ChvxqLy","qvzVANO","ufrqzMW","ww5dCLm","AfrUs20","ENjKt0m","BNruCMLLC0m","DMvY","x2HHBMrSzvi","EMfLtem","yw5Hz2vY","zufJAW","svzPEMu","rMTLy3K","x29Ut3bLBG","BgPYExC","C0jf","ywTnrxe","Ew9nu2S","y2fSBa","yxv0BW","yNvMzMvY","C3bSAxq","zMPRD0e","yLvesKW","ywrK","sxbkthm","sg1yEuC","zw50tgLZDgu","uNLsteO","DxbNCMfKzw4","CuHPDxO","zgLZCgf0y2G","qwDQsKu","CuXLzKy","zgrjrcWGzgu","BffPsLO","DhbizwfKzxi","AgH1AhK","wMXUtuK","q29Kzq","C2TWyuK","x2rPC2nVBM4","x3bPBMC","wKHUqKK","DK1nC08","rhvHv3O","s0DtCNm","ig1LC3nHz2u","z1Pxuee","qK9ezhO","D1f0z3u","igzHAwWSig0","Cw1tzxi","B25VCgvU","u1vsq0e","uNDwvfe","Aw1zrgC","zLnsC2S","zfDdvgy","ugrVuMi","DgfIyxnL","zw5JB2rPBMC","Bun4t1C","z1PQBLK","AxHSwe8","rLrey0S","B2nRzxrgywK","tvvLDwW","CMvHC29U","s2DsvuO","AgPQqKW","BNLuthK","v1fXuxa","Cw5UEem","EuHKtMS","wMPpzhC","twjKsLa","yw1LoIa","zcWG","ywXSq3vYC28","v2DUvfm","uePTA0y","vfrly3u","tfPMyMW","ywnOzwq","vw5Oyw5KBgu","rKPzv3O","CMvZzxruCMK","C1vTEva","twv5t2K","yxnJCMLWDa","C1vWCuy","DvP6Eem","ExjSCu8","Bg9Nsurhzw4","ywnR","CMvXDwLYzwq","DxrVuMvJB24","Aw47y2HHCNm","C3bSAwnL","yuPXshq","Dxj6CKC","y3vYC29YlNm","vKjTzM8","t0LSrhu","D0zoy1a","qwPNtNy","D3vbyu8","z0vIr3a","surcwwK","vKX1zxy","BMCGB3iGyw4","vfPqreO","D2r3yNq","CYbWyxjHBxm","zuLVC3a","B2zMBgLUzq","vxnMwvq","AKjRChK","rNjVBNrPzxi","wuHZteq","tfDMrNC","EfvZzuvUDG","AhPeCxu","zgvIDwC","Ae9mwM8","EhbLrve","EvjLy29UBMu","Chv0","y29Uy2f0","vuXMsKG","sK9REha","AwXSihvZzsa","CfP4u1a","Dxrjza","tgTjvNi","ysbTDxn0igi","yKHVv2m","x2LUAxrqCM8","rezOAue","x3bYzwzPEa","y0fluuC","C29YDa","x3vYBa","mNWWFdn8mxW","BM56C0C","yuvzt1y","tufyx1jfvfi","ywXty29Wzq","yuXsq0O","tgLZDgvUzxi","zuzpBem","B2jQzwn0u3q","CufKyKK","lcbTyxGGCMu","zgrfzgi","Efrurw52","EeT6s0C","zw5fDMvUDa","ugjUugC","r2LduNy","uKXJv2u","y1PyBfa","x2DLDeLUDgu","rejvs3u","wwDRAge","z2v0u3rVCMe","B25TzxnZywC","uhjQBgq","D2zzr0O","rxfHuwS","Ee5uu0y","B2nRzxrtDwm","CNzHBfzHBhu","q09otKvdveK","sffvr0y","x21LC3nHz2u","DKTzzgG","CfHor1u","vejssgK","DwLIuxy","D3jPDgvvAw4","suvtx0vsuK8","sevlB3C","u0XHzMy","B0nLteS","rNrvtuq","u0HXCMW","y0PLuxq","swjqyw8","C2vYDMvYvgK","CYbHBhjLywq","BwLZzq","y3ruAw1LB3u","zxjYB3i","wMPJs1G","mdaWmdaWmda","AffdqwK","x3jLywr5q2W","yMfJA3vWigu","yLrNvMm","qvviwLu","x21PBMLoyxy","Buffs0W","vgLTzw91Da","wufWsNG","q0vdrKK","yxGGCMv0CMK","zgjeExK","zgvS","z0TPDfu","zxPzr3y","x2rItMfTzq","uKPSqNq","yNL0zu9MzNm","sMLouum","BMv3vMvYC2K","yNL0zuXLBMC","AvH6weW","C2vYDMLJzs0","q0v0A0y","r1n5ELG","BwvZC2fNzq","sNPWzxm","B3bLCNr5","rfnwDMm","A1Luu1C","BeXUr08","CNzHBa","Be9Sthm","ugTbEg8","wNfPzgy","AKnmA00","AxnbCNjHEq","su9quLq","rg9huue","y29Kzq","v0HUBu8","zwzZzLK","yM9KEq","BfPwDMS","CMvWBgfJzq","zM9Yy2u","EfbmrNa","x19LC01Vzhu","zwnVBM5Ly3q","rMzwt0y","D0XwqKi","Aw5KzxG","uwjNu3K","r1LmCxq","rhH0v3C","CfHhyLm","C0jfsLK","CMvHzg9UBhK","uhf4Axi","B3bLBKrc","BwfUDwfSihi","zuvgBxi","AxnszwfKEq","whDTv20","C3jJ","yKTeuNG","CfrVzvO","zxq9DxrMltG","vNrRA1e","zxHmzeC","B25LCNjVCG","z0PrwNy","yw5Zyxi","zgLZywjSzue","AxnmB25N","rLnTALC","u2jZCwK","wM1Tzvm","BKXPBMu","yLPpsgi","BMrWB2LUDfq","zxHWB3j0CW","sxPoBMe","B25nzxnZywC","yKPvsKm","ENffruO","vxvZBLe","rNLWrg0","CLviwvi","s1zmuNO","rgDYsuS","v0HLCfy","DK5Pwwq","swvqqMS","wLzUu1q","DhjHBNnHy3q","x2HHBMrSzva","BgPHrNO","ihn1y2nLC3m","we5PEK8","r0PKzeG","DcbVzIbYyw4","s2LxB2S","AenSB3nLrxy","txHjCNO","AKvlENO","q0TotMK","vvrcyNK","A1zZDw8","AxnFywnR","B21hAhe","CMvHzhDYAxq","ywDLrxzLBNq","DhjPBq","DgHHBIbSB2m","rgvKAwnHDgu","CLfTu2G","A2v5","BMv4DcGPigm","Cgu6ia","B0LUrwS","u2rkz3C","DezUq3C","rw52Cwu","z2jeAeC","wfrurLm","CMTLCKDSB2i","A1nLuvO","wwjRwge","CgXLyxnLiha","r3zLrey","rhrmqNO","zgf0yq","shvtuxC","EwLrsKS","DNDiBLe","q3Lgzfm","tMfTzq","ENneCgm","DLLOA2m","ELnQy2K","BMTyqNq","Dev2zw50","q2Dcu2G","EMLbCKK","wgrkuhy","zwvKzwq","Bg9NsurozxC","swrJque","s2PXD0S","ELr4t0m","CgLUz09Uy2u","vvPVrNe","Bfbbt0K","DMfSDwu","q09oveLovuu","r1Pxwuq","Aw5KzxHpzG","ueH4BxG","tNDHDKi","EeTHC0W","AxjLza","ChjVy2vZCW","CgfYC2u","Dg9mB3DLCKm","zMzKt1u","uwXjwu0","DxnMse8","BMrLEa","B1PjB1m","rxjUzMG","ihzHBgLKigq","BNv2u0e","BfrPBwvVDxq","Dhr3Awq","y3jLyxrLrwW","EffNEwe","A1n0yxr1C0m","te55y08","wLzIsfK","B2XKvMvYC2K","yvP3DNe","x2rPC3bHDgm","Bwu6ia","B25SAw5L","zMXVB3i","uMjqsw0","q2jsre8","zevQy0q","BMDuAw1LCG","zvrcBMe","zxH0zw5ZAw8","z2v0","x1fVu01HBMe","zgrjDKW","t2nAtw0","AefJA01LC3m","x3bPBMDqB24","r2vusgu","EMrVB2i","x194x21Zz18","ywXPzcb1CMW","ChjVDg90Exa","nxW0Fdn8mhW","BNb2wxy","BLL1Euu","ywDLsgLKzq","y3b5seS","tw9KDwXL","BM9MDLu","vvDnAhy","y29UDgLUDwu","z3LKyLe","CM92AwrLihy","tKjkELy","x2rYB3bhBg8","zxH0ugf5Bg8","seDxr0m","DgLTzw91Da","zNjHBwvuExa","m3W0Fdv8mNW","C0XPC3rLBMu","r1nIDgq","AKnHDg4","y29UBMvJDa","y3PVEMO","B3jLtMfTzxm","Axj0qvK","C2v0","ihbYB3rVy28","De5NqLu","sNj6sfC","EgPqD3m","q0Xpu0LorW","C3rYAw5NAwy","BMDZtNu","qwLlrvy","txfir0C","CvDvufa","tKHUEMi","zg9Uzq","y3vYDMfSDwu","sgn3yuu","DgHgzeO","y3jLyxrLtwu","B2fK","rvnzCMm","ueTyDxC","DvPvD0q","vfjJtwq","q29UzMLN","DxzTA3e","x2DLBMvYyxq","wg1cDxe","sKPAswi","mxW5Fdv8mNW","BMHXveC","BgLTAxq","B2LUDfjLywm","DhbLv3O","tLv2BLu","vwzNsvG","t0nSr0u","sejODKu","DhjPzxm","AMXYsg0","sNrOvxO","sLnptLa","Aezbz2W","r21HqKW","zxjFCw9Z","y3vYC29Yx2y","twvYq2i","DxH4Ewq","BMCGzMfPBgu","t2D0Ahu","CLL6tw8","nhWZFdb8mxW","AgfZt3DUuhi","te9XvNy","wuXWwNC","Cg93","DMnTzwO","B3nLza","tvPpreW","EKL3su8","BxrRwue","B3bLBIa","B0fhuw8","Dg9oDw1Izxi","CMvUDevUzha","tKDFrvjst1i","ywnRpwzYB24","DgvZDa","EuL3BgW","B05WuMi","nNWWFdH8mta","zxjYtxnN","ywrKrxzLBNq","Aw5L","yNLL","z2vrDwv1zuW","Eg5lzhO","CNnVCKzPBgu","B0XJqui","nhWZFdf8nxW","D1bWreG","zNjVBu51Bwi","zw50","rhrltNu","zeH3v1a","mNWX","yxv0B21HDgK","C2nlA0q","rLzbBgu","BgLUzq","x3bYB3rVy28","EuTJC2y","sfb2seC","nxW3Fdb8mq","zwPjzNq","y09Wzw4","D2XPsKy","AwPbswq","x2n1CNnVCKy","x29UtwvZC2e","r3bUy3a","AwXLx25HBwu","B25szwnLAxy","x3DHAxq","x2LZtwLUAvq","zM9jCfe","zeHTwK8","yw1L","sevpAeu","vePqz3u","x2LZv29YA2u","CeDvEK8","ExPLuuy","CxDYBLm","zw5JB2rLrNi","Aw5Lza","y3jLyxrLt3a","zMzmAw5L","BMH0t3u","C1veD2G","twrtvMu","ugXbDwC","Cgf5Bg9Hzfq","Bwf4uMv0CMK","EvLrzwK","z2nkq0O","x2XPC3rLBMu","DuroAha","EvzHyve","B3bLCNr5tMe","v2DNrfa","ywnRx2LK","BLfmv0m","zLfOq0G","CM92AwrLige","zvvYBa","Dg9VigXHCMC","vNDRzKm","shf0Age","DxvOBw4","uKDouLq","sMjTueS","tuvtu0fhrv8","sNzztu4","y2HnyxHuCMK","x3nLCuLK","B25Uzwn0Aw4","v1DwExy","z2u6ia","twT2Awe","C1PMCey","BhHpzfe","AvjiwKC","CKjly3u","D3nZoI8V","Dg94tfa","y2HLy2TdDxi","DxL0zKW","y2XVC2uSihC","yxbWzw5Kq2G","DKPtzKe","u0rHyue","mhWY","yw5Nzq","AhLbt1y","BNrfBMrWB2K","y2nODu0","tfbpzgy","u0f2qvm","t2jQzwn0","BxPtEu0","ywXSB2nvBNm","zxjFCw9Zx2e","zM9YrwfJAa","ywjuwe0","vhLlwxe","s1fPCKm","suzwwge","r3H4rM4","q0HSuNG","zgvSzxrL","DxzUDfm","r0HIvK4","ChrVCG","BgvUz3rO","EMDgEuW","rxzLBNq","C3Lhufe","zxHpuKW","svDMA1y","rNDJqui","x2rLyNvN","EKHYCe4","EsbJBg9Zzwq","C3vJy2vZCW","sgH3rMy","vfLuCgi","C3rYAw5N","y2PzDva","DLrOugG","C2v0q3vYC28","vLjOALG","uKTdA3G","B25dBg9Zzq","r2PND1q","vvjYtxO","y291BNq","v2vIu29JA2u","Dgv4Dc9WBge","uwvosfK","A1jSCfu","wKHRz2W","yxKSig5LDhC","uMLRtLG","zxrxB3jRq2G","CMvQzwn0","u3rmyMW","uNLZqNG","BwvKAwf0zwW","ug9hrNa","s2vxBuK","mNWWFdf8nxW","x2fKzfDZtgK","m3WYFdf8nhW","yxjYyxLIDwy","BNH2EgC","ihjLy29UBMu","y3vYC29Y","C3vIyxjYyxK","rvv5vMG","uKT2DwS","rKLSAhK","DgfYz2v0","EfjhBNi","wvb5A04","zff3q1e","wM1TA0K","CMvZzxrdB3u","x25HDMLNyxq","x2nYzwf0zvm","uMvJB25Uzwm","x29Uq2XVC2u","ueLSuvO","vhHuvhy","AKDpvwG","BMrWB2LUDca","AMjHzwy","CvjXs3a","DhPcCfC","zMvcExm","B3jL","DMX1qLe","vxzzsKe","qM9vz1u","CunRAvm","AwXLtMfTzq","yMXVy2TLza","Bu52BMu","r0vIzKq","yxbWBhK","C2v0zgi","ywXSzwqGBxu","thrnreO","yKDQthe","D3jPDgu","z3noA2G","Aw9U","AwDHDg9Yt24","Cuj1we0","q291BNq","uvv5CxG","uMT4vw0","D24GCMvHC28","x3DZsw5ZDge","tKPhr3m","Eenovw8","veXZEum","sMPSyLy","tKLcvgy","C2DPza","x3jLy29UBMu","x3nLBMrby2S","reiGzMfPBgu","te1UEuu","rxjYB3jdB2q","CgLUz1rPBwu","tM9Az3i","tuHqwgK","D3Dyy0W","y3r4","DM52vKi","suzKqMO","vNPcEvC","BgvY","uvfpyuq","DvHkD0S","x2n1CNnVCK0","A0PMvu4","wMTzzNO","z2v0q3vYCMu","uLjpuG","y2f0y2G","sMzUrLa"];return fa=function(){return t},fa()}var Oe={};function j(t,e){t=t-121;let n=fa(),i=n[t];if(j.mMufBd===void 0){var o=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",m="";for(let S=0,_,v,I=0;v=h.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++)m+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(m)};j.LCaEdo=o,j.AWiixH={},j.mMufBd=!0}let a=n[0],d=t+a,u=j.AWiixH[d];return u?i=u:(i=j.LCaEdo(i),j.AWiixH[d]=i),i}(()=>{let t=L,e={Mqmis:function(c,r){return c+r},WggDP:function(c,r){return c*r},DNBZm:function(c,r){return c+r},rkGgw:function(c,r){return c(r)},IWfkV:function(c,r,s){return c(r,s)},wPzaN:"message_id",vwqmK:t(496),ddEdb:function(c,r){return c(r)},IVYzl:function(c,r){return c(r)},vNiYd:function(c,r){return c+r},ngsNu:"0000",XTTFS:t(289),aBWRz:t(865)+t(865)+t(865)+t(865),qAdbI:function(c,r){return c(r)},KofMW:t(1084),LJJgJ:"ping_once_success",Mkvia:t(540)+t(478)+"t",VcFhf:function(c,r){return c!=r},FTmOr:t(1074),txXSC:t(913)+"le",zdoob:function(c,r){return c>r},CbKWM:function(c,r){return c<r},pQevH:function(c,r){return c-r},HHRAU:function(c,r){return c===r},MeyOi:t(1303),qIWBw:function(c,r){return c!==r},hQCAi:function(c,r){return c!==r},lQiJZ:t(661),zHUGI:function(c,r){return c!==r},ZWiDt:t(1031),iXzXL:t(760),tsvsk:function(c,r){return c>>>r},gbvUi:function(c,r,s){return c(r,s)},LEkPm:function(c,r){return c(r)},nnzsG:function(c,r){return c===r},IREEA:t(296)+t(765)+t(1535)+t(1020),ionoF:function(c){return c()},SpziG:function(c,r,s){return c(r,s)},uvmkq:function(c,r){return c(r)},RyRLJ:function(c,r){return c(r)},INoGw:function(c,r){return c<<r},fgeSk:function(c,r){return c&r},npPOV:function(c,r){return c&r},ATPVX:function(c,r){return c&r},sUmyP:function(c,r){return c(r)},TwByH:function(c,r){return c<<r},vKYdh:t(1564),IFdBj:function(c,r,s){return c(r,s)},oKRnz:function(c,r){return c!==r},dNyYv:function(c,r,s){return c(r,s)},nOzTH:function(c,r){return c!==r},aKHlD:function(c,r,s){return c(r,s)},hCPGh:function(c,r,s){return c(r,s)},xtcde:t(890),rpwza:t(1026),BpeoA:function(c,r,s){return c(r,s)},greMc:function(c,r){return c!==r},KPhkr:function(c,r,s){return c(r,s)},cLAQg:function(c,r){return c!==r},AQDws:t(544),zTxOC:function(c,r,s){return c(r,s)},TyKYq:function(c,r){return c!==r},QbgSy:function(c,r,s){return c(r,s)},UvYJA:function(c,r){return c(r)},zSjci:function(c,r){return c(r)},FzPLB:function(c,r,s){return c(r,s)},HOAID:function(c,r,s){return c(r,s)},YbkXa:function(c,r,s){return c(r,s)},HNgPX:function(c,r,s){return c(r,s)},LDQyX:function(c,r){return c(r)},uxxyd:function(c,r,s){return c(r,s)},UtaaT:function(c,r){return c(r)},wliJF:function(c,r,s){return c(r,s)},IvoCm:function(c,r){return c(r)},HbRVl:function(c,r){return c(r)},KOyJs:t(296)+t(765)+t(1535)+t(1491),FVAle:t(296)+t(765)+t(1535)+t(139),hjjBL:function(c,r){return c===r},tVOsq:t(296)+t(765)+t(1535)+t(145),gbDhG:t(296)+t(765)+" field: "+t(254),PUIsS:function(c,r){return c(r)},gZjnY:function(c,r,s){return c(r,s)},AVojz:function(c,r){return c+r},LtMDJ:t(566)+"ented ty"+t(985),vnvVB:function(c,r){return c===r},czozj:"NDOBz",ExZyw:function(c,r){return c>>r},EhdxV:function(c,r){return c>=r},WMACu:function(c,r){return c-r},rBNKv:t(531),JlRNE:function(c,r){return c===r},wQtgu:t(1433)+"t limit",yKcsf:function(c,r){return c>=r},nBRMN:function(c,r,s,l){return c(r,s,l)},Envqe:function(c,r){return c>r},uXJwK:"VWvze",NZpeG:function(c,r){return c*r},YnCrS:t(133)+t(217),oEdZj:function(c,r){return c+r},Trvms:t(617),mcpGn:function(c,r,s){return c(r,s)},bKDRx:t(733),GYLqt:function(c,r){return c&r},HEKow:function(c,r){return c>=r},ySpFA:function(c,r){return c+r},BSXtN:function(c,r){return c!==r},zdnvX:function(c,r){return c|r},JbmPK:function(c,r){return c==r},Wedzi:function(c,r){return c>=r},VtkkQ:function(c,r){return c+r},YPykN:function(c,r){return c<<r},znAWw:function(c,r){return c|r},QZfTo:function(c,r){return c&r},EFqWK:function(c,r){return c<<r},ySrSW:function(c,r){return c&r},ansar:function(c,r){return c<r},ZjOdw:function(c,r){return c<=r},mtkYA:function(c,r){return c+r},xYiag:function(c,r){return c+r},VfxDM:function(c,r){return c+r},Onokn:function(c,r){return c+r},ZVnST:function(c,r){return c|r},KeWmI:function(c,r){return c|r},QeNHY:function(c,r){return c<<r},GiCRv:function(c,r){return c<<r},ZHnBI:function(c,r){return c&r},Vhdjg:function(c,r){return c<r},RWSTj:function(c,r,s){return c(r,s)},UTBby:function(c,r){return c+r},pXkcc:function(c,r){return c>>r},fPGZC:function(c,r){return c&r},syGPQ:function(c,r){return c(r)},hhuhy:function(c,r){return c>=r},ZHdym:function(c,r){return c<r},JOkxp:function(c,r){return c+r},WVaPg:function(c,r){return c-r},RJSED:function(c,r){return c<<r},qCkiS:function(c,r){return c<r},fSRsk:function(c,r){return c<r},aaLJL:function(c,r,s){return c(r,s)},fQhCH:function(c,r){return c+r},WWVyv:function(c,r){return c<r},XNizO:function(c,r){return c===r},vvkyA:t(1134),CKNNi:function(c,r){return c|r},MSFRi:function(c,r){return c&r},uvntS:function(c,r){return c&r},wRuaJ:function(c,r){return c|r},CbMyP:function(c,r){return c&r},yIwll:function(c,r){return c>>r},zrdOC:function(c,r){return c|r},jCLkM:function(c,r){return c&r},dkEWC:function(c,r){return c>>r},Jqxzc:function(c,r,s){return c(r,s)},GJddH:function(c,r){return c+r},bUDJL:function(c,r,s){return c(r,s)},WgnTS:function(c,r){return c(r)},kzJWR:function(c,r){return c>=r},ignvy:function(c,r){return c|r},XCbWH:function(c,r,s){return c(r,s)},VRxsI:function(c,r){return c instanceof r},lPAOI:function(c,r,s){return c(r,s)},cAKQG:function(c,r){return c>>>r},PIlQZ:function(c,r){return c(r)},cjYuP:function(c,r){return c===r},lLnGO:t(547),QZDWX:function(c,r){return c<<r},UmnuF:function(c,r){return c(r)},zsDpc:function(c,r){return c&r},sMrxy:function(c,r){return c<<r},dOwzh:function(c,r){return c&r},kRlpU:function(c,r){return c===r},exLdG:t(1113),mnZuK:function(c,r){return c(r)},lxOdQ:function(c,r){return c&r},wbcNL:"uDFJZ",pToeZ:function(c,r){return c<<r},GmaBL:t(1201),JPdwq:function(c,r){return c&r},PAFzY:function(c,r){return c(r)},KiWok:function(c,r){return c<<r},dhaBy:function(c,r){return c<<r},NEImB:function(c,r){return c>>>r},dJoEi:function(c,r){return c>>>r},MqHGG:function(c,r){return c>>>r},bJLhT:function(c,r){return c===r},nfAmm:function(c,r){return c<r},JCBjF:function(c,r){return c<r},nxvxg:function(c,r){return c&r},IpJLs:function(c,r){return c&r},LZfbl:function(c,r){return c+r},mAEKL:function(c,r){return c!==r},WErkL:function(c,r){return c&r},rQCnE:function(c,r){return c>>>r},wdwbt:function(c,r){return c+r},aZwvq:function(c,r){return c|r},TRcMd:function(c,r){return c+r},KVLRz:function(c,r){return c|r},jrOeV:function(c,r){return c!==r},PHxmx:function(c,r){return c+r},pELXL:function(c,r){return c>>>r},eMrSx:function(c,r){return c&r},GkmWF:function(c,r){return c+r},GxxFn:function(c,r){return c>>>r},pSpKe:function(c,r){return c&r},JJZIb:t(715),hpUCw:function(c,r){return c===r},ekizx:"HmXyG",ObVdb:function(c,r){return c|r},tzBpW:function(c,r){return c|r},wLUpf:function(c,r){return c<<r},rmXUI:function(c,r){return c<<r},QsmjS:function(c,r){return c|r},TYTpb:function(c,r){return c<<r},NdlGP:function(c,r){return c|r},cJeQt:function(c,r){return c<<r},dPeMw:function(c,r){return c<<r},RwVTQ:function(c,r){return c<<r},JjlbV:function(c,r){return c>>>r},IFVXa:function(c,r){return c<<r},gZWPA:function(c,r){return c|r},KjqSZ:function(c,r){return c|r},ULfJH:function(c,r){return c&r},bTgVc:function(c,r){return c&r},Ernfh:function(c,r){return c>>>r},rghvO:function(c,r){return c>>>r},JBxFc:function(c,r){return c<=r},omGhq:function(c,r){return c%r},lDZid:function(c,r){return c|r},NaLqk:function(c,r){return c*r},ezYGv:function(c,r){return c>>>r},JiNQC:function(c,r){return c>>>r},jIlKW:function(c,r){return c===r},TYgUm:t(996),BYRNs:function(c,r){return c>>>r},SURCA:function(c,r){return c&r},PTPfl:function(c,r){return c&r},xZaOB:function(c,r){return c+r},imYDg:function(c,r){return c>>>r},wjBEw:function(c,r){return c|r},REnCX:function(c,r){return c<<r},fNPaG:t(787),BJCWq:function(c,r){return c!==r},EIMbW:function(c,r){return c===r},lZyGf:function(c,r){return c===r},KQirC:function(c,r){return c===r},aLRCJ:function(c,r){return c>>>r},GHbVN:function(c,r){return c&r},jlrHm:function(c,r){return c&r},jQkCl:function(c,r){return c>>>r},eEyuk:function(c,r){return c>>>r},PTmyK:function(c,r){return c&r},cFOCB:function(c,r){return c>>>r},kpmNg:function(c,r){return c&r},oZgAV:function(c,r){return c>>>r},dHwWP:"OPEN_ERROR",xQgya:t(816)+"IES_ERROR",xecXs:t(843)+t(1157),IDBYi:function(c,r){return c===r},bEqCg:function(c,r,s){return c(r,s)},urzrG:t(305)+"t",sCssY:"stop imm"+t(536)+t(1318)+"ct",vHdqY:function(c,r){return c===r},YvJWk:t(356),buxnO:function(c,r){return c>=r},NJGGs:function(c,r){return c===r},wimwJ:function(c,r){return c-r},WQqQp:function(c,r,s){return c(r,s)},JEhva:t(1242),aJqHt:t(1463),yHQuD:function(c,r){return c>r},BVBFX:function(c,r){return c===r},ntpBo:t(863),wuAaO:function(c,r){return c===r},nofvU:"PNUsm",pZxSP:function(c,r){return c+r},MZODL:t(1148),GkSQJ:t(436),zSqXT:function(c,r,s){return c(r,s)},RTzwy:function(c,r,s){return c(r,s)},EeBBp:function(c,r,s,l){return c(r,s,l)},pDETm:"OcYuO",YUrFW:t(750),HPvHG:t(577),WTogk:function(c,r){return c(r)},xKzKG:t(698)+t(1012),uXdiq:function(c,r){return c!==r},FwcLX:t(340),xpeEQ:t(371),ktjCm:function(c,r,s){return c(r,s)},DuaWz:"HKnqY",nYuyE:t(891),TBRHi:t(1562),hLJnz:function(c,r,s){return c(r,s)},VVxeH:function(c,r,s){return c(r,s)},onfub:t(216)+t(1199),UyVsJ:"NISvc",oAGQo:function(c,r){return c instanceof r},pGUzO:function(c,r){return c+r},vluBQ:function(c,r){return c>r},oCeLK:function(c,r){return c!==r},wkNHu:function(c,r){return c||r},FypDm:function(c,r){return c!=r},eEFmr:t(233)+"d",SDzVS:function(c,r){return c||r},GSbtd:function(c,r){return c<=r},eFOlC:t(984)+"alled multiple t"+t(414)+"process",YsIXP:function(c,r){return c===r},IOPRT:function(c,r){return c<r},AQtKy:function(c,r){return c!==r},LniuR:function(c,r){return c>=r},ZhxKD:function(c,r){return c<=r},rDnwW:function(c,r){return c<r},yVaaQ:function(c,r){return c<r},CNJLa:function(c,r){return c|r},gsWgc:function(c,r){return c&r},Lytbm:function(c,r){return c>>r},aXJHP:function(c,r){return c&r},uZzxC:function(c,r){return c===r},gKitU:t(1417),EBpQp:t(986),iBPAz:function(c,r){return c<r},bOOqT:function(c,r){return c&r},rIVfg:function(c,r){return c===r},qgOLE:function(c,r){return c+r},CGINN:t(1171)+t(1254),RysBx:"MESSAGE_"+t(1435),lpxJW:t(173),qBFeV:t(312),tizYh:function(c,r){return c-r},pXNGU:function(c,r){return c<r},kkkqY:function(c,r){return c>=r},LwMsk:function(c,r){return c|r},hcItB:function(c,r){return c&r},yYQei:function(c,r){return c-r},kSwHA:function(c,r){return c|r},pYnaR:function(c,r){return c|r},iTeLq:function(c,r){return c|r},heAAo:function(c,r){return c&r},EmYNJ:function(c,r){return c<<r},xqMch:function(c,r){return c&r},Pqxir:function(c,r){return c<<r},wQNuK:function(c,r){return c&r},VhnWK:function(c,r){return c&r},eTGJR:function(c,r){return c+r},ZVbHY:function(c,r){return c&r},PyJKN:function(c,r){return c<r},VwkfC:function(c,r){return c<r},GYvty:function(c,r){return c===r},JsWlL:function(c,r){return c===r},scKkD:function(c,r){return c&r},LfoxS:t(1313)+t(248),QEURO:function(c,r){return c|r},oUxvD:function(c,r){return c+r},aKtXa:function(c,r){return c|r},DtLBz:function(c,r){return c&r},CzGgB:function(c,r){return c&r},wLVBB:function(c,r){return c>>r},esVCu:function(c,r){return c&r},lGHGu:function(c,r){return c|r},msOck:function(c,r){return c>>r},CyFdS:function(c,r){return c|r},thMeQ:function(c,r){return c&r},cchuM:function(c,r){return c>>r},kJfUN:function(c,r){return c|r},Fkecy:function(c,r){return c&r},AkGIx:t(1289),zkapU:function(c,r){return c(r)},PdRVk:function(c,r){return c instanceof r},RbPIm:function(c,r){return c!=r},oWbgQ:function(c,r){return c!=r},YONzM:t(221)+t(184),RGNRT:"text/plain;chars"+t(933),gUkhf:"boe",iyaYk:"ppe",bNYua:function(c,r){return c<<r},CElbH:function(c,r){return c!==r},qnQaA:t(572),nPyDt:t(1005),JthUz:function(c,r){return c(r)},efsfY:t(525)+t(737),oGnYq:function(c,r){return c(r)},MwOTS:t(1550),cnJOJ:t(176)+t(1158)+"tierJSONP",fPXqw:t(683),UcIzI:function(c,r){return c!==r},aavGo:t(484),CLSFN:function(c,r){return c===r},yoMSk:t(1402),Vasix:t(721),JvYMN:function(c,r,s){return c(r,s)},FJYWz:function(c,r,s){return c(r,s)},ZXwWj:function(c,r){return c(r)},RikNX:t(1249),KgRUJ:"bye",ZlQop:"lNOFg",kVsuo:function(c,r){return c+r},DSVvc:function(c,r){return c!==r},xCwbf:"LHQzE",PbnPg:t(480),uuhmn:function(c,r){return c||r},puWBV:function(c,r){return c||r},GEbfD:function(c,r){return c||r},eTBna:function(c,r){return c||r},SLaff:function(c,r){return c||r},FTDcK:function(c,r){return c||r},fjkwA:function(c,r){return c||r},skpaI:t(126)+t(1374)+"d",mzSyM:"qos",gsNkh:function(c,r){return c===r},jGIOb:t(325),IDaXj:"RcBci",nyTLy:t(797),NHRSc:t(693),GZWYD:"delete",YtnID:t(155),SHqrl:function(c){return c()},qLefF:t(421),MHPXi:t(602),hEzqu:t(462)+"ys",uibQv:"count",xbhPr:t(283),PqgNq:"xIGBG",VBmfo:t(957),Duxyw:t(1315)+"0",hTnKm:"WfqgA",xKEUY:function(c,r,s,l){return c(r,s,l)},xnKdz:"x_fronti"+t(1136),LBYiu:t(463)+t(1264)+"ck",NBJzV:function(c,r,s,l){return c(r,s,l)},QDPis:t(463)+t(1459)+t(1371),eiWCe:t(1050),AYKLv:t(785),IogZp:t(442),HEOhE:function(c,r,s,l){return c(r,s,l)},LsAHM:"need_ack",rQmSh:function(c,r,s,l){return c(r,s,l)},asubO:t(975),fJaFP:function(c,r){return c&&r},abTXM:function(c,r){return c!==r},ijAId:t(1197),QLBiA:t(963),FeBve:function(c,r){return c||r},RKCkx:t(196),vThPh:"3|4|2|1|0",LufqC:function(c,r){return c!=r},usfHO:t(999),IDdXb:"received",gydbQ:function(c,r,s){return c(r,s)},gKBWT:function(c,r){return c(r)},uZUwD:"QRYuq",FtUMD:t(1530),KRtVx:function(c,r){return c instanceof r},XiNUa:function(c,r){return c instanceof r},FnYOA:t(221)+"ion/json"+t(149)+t(197),wfYGJ:t(454),ZlnMI:function(c,r,s,l){return c(r,s,l)},JNqNB:function(c,r){return c===r},CHlRx:t(959),xCNUo:function(c,r){return c+r},nsKLJ:function(c,r){return c&r},hcBgg:function(c,r){return c|r},qRYCR:function(c,r){return c>=r},LMnyE:function(c,r){return c>r},xRGnr:t(364)+t(1228)+"e",mIaaO:function(c,r){return c>=r},GulUw:t(563),hzDqu:function(c,r){return c<r},rBKcu:"oooHW",oVbzs:function(c,r){return c<<r},VemFN:t(1143)+"2",UHTcQ:function(c,r){return c+r},ddIvL:function(c,r){return c<<r},samdF:function(c,r){return c+r},PdoRb:function(c,r){return c<<r},VLuev:function(c,r){return c<<r},lQeFw:function(c,r){return c+r},uQLxt:function(c,r){return c<<r},bkiSt:function(c,r){return c+r},uZIgF:function(c,r){return c&r},wnzZy:function(c,r){return c>>>r},aNYsz:function(c,r){return c+r},ESXCX:function(c,r,s,l,f){return c(r,s,l,f)},kjQcr:function(c,r){return c+r},xjPws:function(c,r){return c+r},FwpWr:function(c,r){return c>r},FJZfh:"gJYIY",pLXOj:function(c,r){return c===r},npvYv:t(1578),AiKEV:t(1286),FuhgQ:t(971),iNmaA:t(344),qAQKy:function(c,r){return c>>>r},ECVUd:function(c,r){return c|r},xwvVJ:function(c,r){return c<<r},fnPDW:function(c,r){return c&r},jSMKO:function(c,r){return c|r},uBQwg:function(c,r){return c<<r},RCMTe:function(c,r){return c&r},xkaxD:function(c,r){return c|r},sSrvX:function(c,r){return c&r},TyBDZ:function(c,r){return c|r},zgFyL:function(c,r){return c<<r},JrzHW:function(c,r){return c&r},yHdNk:function(c,r){return c<r},lOJuA:function(c,r){return c|r},BoUgU:function(c,r){return c>r},wPJUE:t(833),OGreL:function(c,r){return c|r},IVize:function(c,r,s){return c(r,s)},RjKvT:"EslMw",dhhii:t(1121)+t(1162)+t(1456),DgrIK:"name",wYoWM:t(145),uegje:t(1107),iDuXr:t(888)+t(230),AUHZU:function(c,r,s,l){return c(r,s,l)},zIwIO:function(c,r){return c===r},TKMsc:t(1106),UZpla:function(c,r){return c!==r},pwbFv:t(236),AhZnh:t(1363),witEJ:function(c,r){return c(r)},gOgWi:t(1137)+t(1193),MmAxB:function(c,r){return c===r},TINzO:t(727),jCuIX:function(c,r,s,l){return c(r,s,l)},kYTSW:t(748)+t(535),XdJPv:t(1585),UfgIX:"INSTANT",iRHZG:t(1021),XoAmZ:function(c,r,s,l){return c(r,s,l)},VGfDF:t(1352),dQwCQ:t(1502),TxLzB:t(834),fhrlC:"setcursor",SFKas:t(764),pBETN:function(c,r){return c!==r},EmUqT:t(1109),GGjye:function(c,r){return c!==r},TFgUi:t(573),oawVB:function(c,r){return c||r},UqtVc:"code",gArSK:function(c,r,s){return c(r,s)},QgMoB:t(463)+t(1582),PhQfd:t(463)+t(320),pwggA:t(211)+"s",ysvAe:t(282)+"rsor_name",zqEEJ:function(c,r,s){return c(r,s)},tkLwL:t(282)+t(519)+"ue",yHtem:function(c){return c()},CdWRY:function(c){return c()},lZVvk:function(c){return c()},ROIGt:function(c){return c()},feBys:function(c,r){return c&r},Uynxk:function(c,r){return c&r},GsAMn:function(c,r){return c<r},LiovQ:function(c,r){return c(r)},BsbMa:t(1211),akMEq:t(1587),bQueV:function(c,r){return c===r},YLpZw:function(c){return c()},qwJrF:function(c){return c()},qzZbi:function(c,r){return c!==r},tFnCw:function(c,r,s){return c(r,s)},RHLkl:function(c,r){return c===r},Pporp:function(c,r){return c===r},RejKb:t(688),JrZOf:t(1552),KBkzs:function(c,r,s){return c(r,s)},UusnQ:function(c,r,s){return c(r,s)},ZjwyZ:function(c,r){return c(r)},qWUPP:t(317),xPLFp:"XjDpv",irtAY:function(c,r){return c/r},XwmWm:t(995)+t(1079)+t(1067),QQOaD:"pagehide",HTrEY:function(c,r){return c!==r},SdJgw:t(1406),LOqVv:"https:",tZRtr:t(1246),sOrVS:t(175),imvUz:t(660),kQRlu:t(1040),SfKki:t(1504)+"d",rlXsm:function(c,r){return c||r},xMMRt:function(c,r,s){return c(r,s)},TTaRn:"web",exORL:"fws_1.0.0",CgBSh:function(c){return c()},JFrVo:function(c,r,s){return c(r,s)},NjMvm:t(488),kYVxj:function(c,r){return c||r},iQDwG:t(582),Mfwfr:function(c,r){return c>r},tbQNs:function(c,r){return c(r)},WmvYk:t(156)+">",PFNkS:function(c,r){return c>r},NwavB:"JFLYV",jErAE:function(c,r){return c===r},SCVnw:"HUFZD",JtWBJ:t(459)+t(1538)+"reconnec"+t(594)+t(675),FmdmN:function(c,r){return c==r},FPyKg:function(c,r,s){return c(r,s)},vJSfA:t(165),IolKF:function(c,r){return c===r},LNycO:t(290),OClGE:t(458)+t(246)+t(1238)+"g",IMqCb:function(c,r){return c>=r},GlcVE:t(323),GOAqh:t(608)+"0",RwYRG:function(c,r){return c!==r},ACvuA:t(899),yiQJK:function(c,r,s){return c(r,s)},KqrXM:function(c,r,s){return c(r,s)},QlIYM:t(459)+t(1304)+"ork offl"+t(1165),Ogthu:function(c,r){return c===r},UsiUc:t(153),vVdyj:t(1250)+t(860)+t(1285),UZoFq:function(c,r){return c==r},MUeul:t(995)+t(1226)+t(1037)+t(256)+t(805)+"e a stri"+t(780)+t(589)+t(170),bAMCz:function(c,r){return c==r},PmZUm:t(269),ZuYfN:function(c,r){return c(r)},TLsyC:function(c,r){return c(r)},XmBuq:"please p"+t(1226)+t(213)+t(1414),mNvne:function(c,r){return c instanceof r},KZyiN:"sent",MKZou:function(c,r){return c===r},UVJBL:t(570),jbaef:t(241),ojxwc:function(c,r){return c==r},PoKJJ:function(c,r){return c!==r},bGjLq:t(926)+t(914)+t(1520),wbQEr:"1|0|4|2|3",caESu:function(c,r){return c instanceof r},yrlqO:function(c,r){return c instanceof r},jdwIE:t(1420),SLNDm:function(c,r){return c*r},WwcCj:"Window",TTKcu:function(c,r){return c!=r},HTkoK:function(c,r){return c===r},RHzqr:"Object",FTMwr:function(c,r){return c===r},VryVh:t(981)+t(131)+t(258)+"pe",CECFI:function(c,r){return c!=r},fhFkV:function(c,r){return c==r},CEtkF:function(c,r){return c!=r},mPGpN:function(c,r){return c!=r},WwvDZ:function(c,r){return c===r},rrcJo:function(c,r){return c===r},Zfgbm:"SharedWo"+t(992)+t(817),RxoEg:t(410)+t(1425)+t(358),gBGvX:function(c,r){return c!=r},mJrvI:function(c,r){return c===r},zHrpN:function(c,r){return c!=r},AfWTR:t(1066)+"qos__"};zt.r(Oe),zt.d(Oe,{FWS:()=>rm,CustomErrorEvent:()=>vl,createCloseEvent:()=>_t,ReconnectEvent:()=>El,createErrorEvent:()=>lt,decodedFrame:()=>on,createOpenEvent:()=>Cl,CustomCloseEvent:()=>Sl,createReconnectEvent:()=>Ca,FrontierMessageEvent:()=>kl,encodeFrame:()=>Ht,createMessageEvent:()=>Tl,OpenEvent:()=>Al,ErrorCode:()=>cn,Event:()=>cr,MessageEvent:()=>Il});let n="";function i(c=""){let r=t,s="02",l=""+Date[r(1569)](),f=n||(n=h(c)),p=Math.random().toString(16)[r(1470)](-6);return s+l+f+p}function o(){let c=t;return e[c(291)](e[c(1222)](1e4,Date.now()),Math[c(1051)](e[c(1222)](1e4,Math.random())))}function a(c){let r=t;return e[r(366)](e.rkGgw(Array,8).join("0"),parseInt(c,10)[r(1509)](2))[r(1470)](-8)}function d(c){let r=t;return e[r(291)](e.rkGgw(Array,4).join("0"),e[r(1281)](parseInt,c,2)[r(1509)](16))[r(1470)](-4)}function u(c){let r=t;if(e[r(210)]===e.vwqmK){let s=c[r(690)](/\./).map(p=>a(p)),l=[];return l[0]=e.ddEdb(d,s[0]+s[1]),l[1]=e[r(651)](d,e[r(958)](s[2],s[3])),[e[r(1101)],e[r(1101)],e.ngsNu,e[r(1101)],e[r(1101)],e[r(991)],l[0],l[1]][r(659)]("")}else this[r(1478)+r(1039)+"Id"]=null,this._interval=36e5,this[r(1429)]=_0x516641(r(495),e.wPzaN)}function h(c){let r=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(c),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(1159)](c);return s?u(c):l?x(c):e[r(514)]}function x(c){let r=t,s="",l=[],f=0,p=0,y=!0,b=e.ngsNu;if(c.indexOf("::")>-1){let w=c[r(690)]("::");for(let B=0;B<w[r(1276)];B++){let q=w[B];if(e[r(1065)](q[r(1023)](":"),0)){let Z=q[r(690)](":");y&&(f=Z.length),p+=Z[r(1276)];for(let $=0;e.CbKWM($,Z[r(1276)]);$++)if(Z[$][r(1276)]!==4){let ke=b.substring(0,e[r(1506)](4,Z[$][r(1276)])),Pe=ke.concat(Z[$]);l[r(402)](Pe)}else l[r(402)](Z[$]);y=!1}else if(e[r(611)]("rTRox",e[r(758)]))e[r(822)](_0x34759a,e.KofMW),this[r(634)](e[r(1482)],_0x224eb7),this[r(634)](e[r(1241)],_0x253ef2);else{if(e[r(262)](4,q[r(1276)]))if(e[r(866)](r(661),e[r(704)]))fOfifz.VcFhf("undefined",typeof _0x3223c5)&&_0x4636ca.toStringTag&&_0x4f33a1[r(167)+r(893)](_0x2156b6,_0x58a51b[r(1509)+r(385)],{value:fOfifz.FTmOr}),_0x50328d[r(167)+r(893)](_0x39ec95,fOfifz[r(285)],{value:!0});else{let Z=b.substring(0,4-q[r(1276)]),$=Z[r(798)](q);l[r(402)]($)}else l[r(402)](q);y&&(f+=1),p+=1,y=!1}}let O="";for(let B=0;B<e.pQevH(8,p);B++)O=O[r(798)](b);for(let B=0;e.CbKWM(B,l.length);B++)e[r(611)](B,f)&&(s=s[r(798)](O)),s=s[r(798)](l[B]);return s}{let w=c.split(":");for(let O=0;O<w.length;O++){let B=w[O];if(e[r(307)](4,w[O][r(1276)])){if(e.zHUGI(e[r(259)],e.ZWiDt))return this[r(628)+r(415)]?.["getCurre"+r(1257)+r(674)+"ount"]()||0;{let q=b[r(198)+"g"](0,e[r(1506)](4,w[O].length)),Z=q[r(798)](B);s=s.concat(Z)}}else s=s[r(798)](B)}return s}}function g(c,r){let s=t,l={Hqtha:function(y,b,w){return e[j(1281)](y,b,w)},paHYZ:s(863)},f=c[s(983)];if(e[s(866)](void 0,f))if(e[s(307)](s(1205),e[s(887)]))e[s(1281)](pe,r,10),F(r,f);else{let y=l[s(1230)](_0x5b624e,l[s(662)],{message:_0xdbd19f[s(891)],code:_0x13685c["MESSAGE_"+s(1435)],error:_0x462801});this._dispatchErrorEvent(y)}let p=c[s(1020)];e.hQCAi(void 0,p)&&(e.IWfkV(pe,r,18),e[s(1281)](F,r,p))}function m(c){let r=t,s={};e:for(;!e[r(651)](K,c);){let l=e.IVYzl(fe,c);switch(e[r(494)](l,3)){case 0:break e;case 1:s.key=e.gbvUi(C,c,e.LEkPm(fe,c));break;case 2:s.value=e[r(1281)](C,c,e[r(824)](fe,c));break;default:e[r(204)](T,c,7&l)}}if(s[r(983)]===void 0)throw new Error(r(296)+"required"+r(1535)+"key");if(e.nnzsG(void 0,s[r(1020)]))throw new Error(e.IREEA);return s}function S(c){let r=t,s=e[r(597)](R);return e[r(575)](_,c,s),e[r(1117)](N,s)}function _(c,r){let s=t,l=c[s(1491)];e[s(866)](void 0,l)&&(e[s(846)]==="Vclfr"?(_0x483e16=e.RyRLJ(_0x21233a,_0x6e09b8),_0x47289f|=e.INoGw(127&_0x3bcc63,21),e[s(1559)](128,_0x375225)&&(_0x5a5486=e[s(822)](_0x43c383,_0xed7f51),_0x28d77e=e[s(1523)](127,_0xd3f85c),e[s(143)](128,_0x42ed94)&&(_0x3ad7e1=e[s(757)](_0x4bc8da,_0x1961db),_0x48d9b8|=e[s(469)](e[s(1523)](127,_0x138c88),7)))):(e[s(204)](pe,r,8),wt(r,l)));let f=c[s(139)];e[s(866)](void 0,f)&&(e[s(1383)](pe,r,16),e[s(575)](wt,r,f));let p=c[s(145)];e.oKRnz(void 0,p)&&(e[s(1281)](pe,r,24),e[s(314)](wt,r,e[s(405)](P,p)));let y=c[s(254)];y!==void 0&&(e[s(314)](pe,r,32),e[s(204)](wt,r,P(y)));let b=c.headers;if(e[s(209)](void 0,b))for(let Pe of b){e.aKHlD(pe,r,42);let ln=R();e[s(314)](g,Pe,ln),pe(r,ln[s(1123)]),e[s(471)](H,r,ln),e[s(651)](D,ln)}let w=c[s(1445)+s(368)];if(e[s(615)](void 0,w))if(e[s(400)]!==e.rpwza)e.aKHlD(pe,r,50),e[s(265)](F,r,w);else return _0xb52470?.find(Pe=>Pe[s(983)]===_0x37bf91)?.[s(1020)];let O=c.payloadType;O!==void 0&&(e.BpeoA(pe,r,58),e.hCPGh(F,r,O));let B=c[s(571)];e.greMc(void 0,B)&&(pe(r,66),e.KPhkr(pe,r,B[s(1276)]),e[s(1592)](ae,r,B));let q=c[s(310)];q!==void 0&&(e[s(361)](e.AQDws,s(544))?_0x3f7a5c[s(947)]=_0x2b6003[s(1596)]().then(()=>(_0x10b470(),_0x4e68e3))[s(1444)](function(Pe){return Pe}):(pe(r,74),e[s(1016)](F,r,q)));let Z=c[s(859)+"ming"];e[s(361)](void 0,Z)&&(e[s(1016)](pe,r,82),e[s(575)](F,r,Z));let $=c[s(338)];e[s(1267)](void 0,$)&&(e.dNyYv(pe,r,90),e[s(918)](F,r,$));let ke=c.frameType;e[s(361)](void 0,ke)&&(e[s(314)](pe,r,96),wt(r,e.UvYJA(P,ke)))}function v(c){return I(e[t(1006)](M,c))}function I(c){let r=t,s={};e:for(;!K(c);){let l=fe(c);switch(e[r(494)](l,3)){case 0:break e;case 1:s.SeqID=e.FzPLB(At,c,!0);break;case 2:s[r(139)]=e[r(575)](At,c,!0);break;case 3:s[r(145)]=e[r(757)](fe,c);break;case 4:s[r(254)]=fe(c);break;case 5:{let f=k(c);(s[r(455)]||(s.headers=[]))[r(402)](e[r(1464)](m,c)),c[r(1123)]=f;break}case 6:s[r(1445)+r(368)]=e.HOAID(C,c,e.qAdbI(fe,c));break;case 7:s[r(1214)+r(324)]=e.YbkXa(C,c,fe(c));break;case 8:s.payload=e[r(1424)](re,c,e[r(1344)](fe,c));break;case 9:s[r(310)]=C(c,e[r(391)](fe,c));break;case 10:s[r(859)+"ming"]=e[r(1139)](C,c,e.UtaaT(fe,c));break;case 11:s[r(338)]=e[r(1188)](C,c,e[r(134)](fe,c));break;case 12:s[r(1085)+"e"]=e[r(183)](fe,c);break;default:e[r(575)](T,c,e[r(1523)](7,l))}}if(e.nnzsG(void 0,s[r(1491)]))throw new Error(e.KOyJs);if(e.HHRAU(void 0,s[r(139)]))throw new Error(e[r(1180)]);if(e.hjjBL(void 0,s[r(145)]))throw new Error(e.tVOsq);if(e.nnzsG(void 0,s[r(254)]))throw new Error(e[r(990)]);return s}function k(c){let r=t,s=e[r(607)](fe,c),l=c[r(1123)];return c.limit=c[r(1574)]+s,l}function T(c,r){let s=t;switch(r){case 0:for(;128&e[s(651)](ee,c););break;case 2:e[s(732)](J,c,fe(c));break;case 5:J(c,4);break;case 1:e[s(994)](J,c,8);break;default:throw new Error(e[s(669)](e[s(1354)],r))}}function P(c){let r=t;return e.vnvVB(e[r(1091)],r(1007))?new _0x532625(_0x12bd62):(c|=0,{low:c,high:e.ExZyw(c,31),unsigned:e[r(186)](c,0)})}let E=[];function R(){let c=t,r=E[c(272)]();return r?(r[c(1574)]=r[c(1123)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(c){E[t(402)](c)}function M(c){return{bytes:c,offset:0,limit:c[t(1276)]}}function N(c){let r=t;if(e[r(814)](e[r(1483)],"LebFA")){let s=_0x10229b[r(198)+"g"](0,e[r(1454)](4,_0x4a0899[_0x8ad826].length)),l=s[r(798)](_0x52e29b[_0x27f725]);_0x2cb6f5.push(l)}else{let s=c[r(1556)],l=c.limit;return e[r(650)](s[r(1276)],l)?s:s.subarray(0,l)}}function J(c,r){let s=t;if(c[s(1574)]+r>c.limit)throw new Error(e.wQtgu);c[s(1574)]+=r}function K(c){let r=t;return e[r(1183)](c[r(1574)],c[r(1123)])}function se(c,r){let s=t,l=c[s(1556)],f=c[s(1574)],p=c[s(1123)],y=e.vNiYd(f,r);if(e[s(989)](y,l[s(1276)]))if(e.HHRAU(e[s(1387)],e[s(1387)])){let b=new Uint8Array(e[s(178)](2,y));b.set(l),c.bytes=b}else throw _0x251598=_0x41dd2c[s(1276)],e[s(603)](_0x2dfa0c,_0x251fb3,10,_0x32bf1f[s(1276)]);return c[s(1574)]=y,y>p&&(c.limit=y),f}function X(c,r){let s=t,l=c.offset;if(e[s(989)](e[s(291)](l,r),c[s(1123)]))throw new Error(e[s(671)]);return c[s(1574)]+=r,l}function re(c,r){let s=t,l=e[s(1139)](X,c,r);return c[s(1556)][s(1320)](l,e.oEdZj(l,r))}function ae(c,r){let s=t;if(e[s(650)](e.Trvms,s(1186)))return this[s(1429)][s(526)+s(255)]();{let l=se(c,r[s(1276)]);c[s(1556)][s(1094)](r,l)}}function C(c,r){let s=t,l=X(c,r),f=String[s(395)+s(708)],p=c[s(1556)],y="\uFFFD",b="";for(let w=0;e.CbKWM(w,r);w++)if(e[s(814)](e[s(931)],"ixlXO")){let O=p[e[s(1499)](w,l)],B,q,Z,$;e[s(919)](128,O)===0?b+=f(O):(224&O)===192?e[s(852)](w+1,r)?b+=y:(B=p[e[s(1396)](e.oEdZj(w,l),1)],e[s(382)](e.fgeSk(192,B),128)?b+=y:($=e[s(1461)](e[s(187)](e[s(1559)](31,O),6),63&B),e[s(432)]($,128)?b+=y:(b+=f($),w++))):e[s(1233)](e[s(1559)](240,O),224)?e[s(643)](w+2,r)?b+=y:(B=p[e[s(958)](e[s(934)](w,l),1)],q=p[e[s(291)](w+l,2)],e[s(1559)](B|e[s(1326)](q,8),49344)!==32896?b+=y:($=e[s(591)](e[s(591)](e[s(187)](e.QZfTo(15,O),12),e.EFqWK(63&B,6)),e[s(1431)](63,q)),e[s(938)]($,2048)||e[s(1183)]($,55296)&&e[s(744)]($,57343)?b+=y:(b+=e[s(697)](f,$),w+=2))):e.JbmPK(e.ySrSW(248,O),240)?e[s(186)](w+3,r)?b+=y:(B=p[e[s(1152)](w+l,1)],q=p[e[s(1548)](w+l,2)],Z=p[e.VfxDM(e[s(1436)](w,l),3)],e[s(262)](e[s(591)](B|e[s(146)](q,8),Z<<16)&12632256,8421504)?b+=y:($=e[s(960)](e[s(960)](e[s(1312)](e.QeNHY(e[s(919)](7,O),18),(63&B)<<12),e[s(829)](e.npPOV(63,q),6)),e[s(712)](63,Z)),e[s(181)]($,65536)||e[s(989)]($,1114111)?b+=y:($-=65536,b+=e[s(201)](f,e[s(973)](e[s(555)]($,10),55296),e[s(291)](e[s(584)](1023,$),56320)),w+=3))):b+=y}else{let O=e.ionoF(_0x1c8560);return e.mcpGn(_0x18a92f,_0x334bf1,O),e.HbRVl(_0x28d012,O)}return b}function F(c,r){let s=t,l=r.length,f=0;for(let b=0;b<l;b++){let w=r[s(1572)+"At"](b);e[s(706)](w,55296)&&w<=56319&&e[s(449)](e[s(800)](b,1),l)&&(w=e[s(567)](e[s(127)](w,10)+r[s(1572)+"At"](++b),56613888)),f+=e[s(1346)](w,128)?1:w<2048?2:e[s(726)](w,65536)?3:4}e.aaLJL(pe,c,f);let p=e.QbgSy(se,c,f),y=c.bytes;for(let b=0;e[s(449)](b,l);b++){let w=r[s(1572)+"At"](b);e[s(1183)](w,55296)&&w<=56319&&e[s(726)](e[s(1225)](b,1),l)&&(w=e[s(1506)]((w<<10)+r[s(1572)+"At"](++b),56613888)),e[s(1239)](w,128)?y[p++]=w:e.XNizO(e[s(1595)],s(942))?(fOfifz[s(824)](_0x33379f,fOfifz.syGPQ(_0x3bd398,_0x4d83c4[s(1560)])),_0x3df665()):(e.CbKWM(w,2048)?y[p++]=e[s(972)](e.MSFRi(e[s(555)](w,6),31),192):(w<65536?y[p++]=e[s(960)](e[s(1273)](e[s(568)](w,12),15),224):(y[p++]=e[s(1312)](e.ZHnBI(w>>18,7),240),y[p++]=e[s(207)](e[s(417)](e[s(1160)](w,12),63),128)),y[p++]=e[s(673)](e[s(901)](e[s(513)](w,6),63),128)),y[p++]=e.ZVnST(63&w,128))}}function H(c,r){let s=t,l=e.Jqxzc(se,c,r[s(1123)]),f=c[s(1556)],p=r[s(1556)];for(let y=0,b=r[s(1123)];e.CbKWM(y,b);y++)f[e.GJddH(y,l)]=p[y]}function ee(c){let r=t;return c[r(1556)][e[r(692)](X,c,1)]}function Ue(c,r){let s=t,l=se(c,1);c[s(1556)][l]=r}function fe(c){let r=t,s=0,l=0,f;do f=e[r(749)](ee,c),s<32&&(l|=e.TwByH(e[r(901)](127,f),s)),s+=7;while(128&f);return l}function pe(c,r){let s=t;for(r>>>=0;e.kzJWR(r,128);)e[s(1424)](Ue,c,e[s(1449)](e[s(143)](127,r),128)),r>>>=7;e[s(264)](Ue,c,r)}function At(c,r){let s=t,l={puVzz:function(w,O,B){return e[j(1019)](w,O,B)},rdkXq:s(305)+"t",hTwdT:function(w,O){return e.tsvsk(w,O)},pXGbS:function(w,O){return e.cAKQG(w,O)},UaOdk:function(w,O){return w+O},iLVAH:function(w,O){return e[s(178)](w,O)}},f=0,p=0,y=0,b;if(b=e.PIlQZ(ee,c),f=e[s(919)](127,b),128&b)if(e.cjYuP(e[s(896)],e[s(896)])){if(b=ee(c),f|=e.QZDWX(127&b,7),128&b&&(b=e[s(1426)](ee,c),f|=e[s(1523)](127,b)<<14,e[s(1004)](128,b)&&(b=e[s(1279)](ee,c),f|=e[s(538)](e.dOwzh(127,b),21),e[s(919)](128,b)&&(b=ee(c),p=127&b,128&b))))if(e[s(1302)](e[s(935)],s(1113))){if(b=e[s(503)](ee,c),p|=e[s(1243)](127,b)<<7,128&b){if(e.wbcNL!==s(649)){let w=l[s(200)](_0x103adf,l[s(465)],{message:"start"});this.onStartReconnect&&this[s(593)+s(914)](w)}else if(b=e.mnZuK(ee,c),p|=e[s(932)](127&b,14),128&b&&(b=e[s(405)](ee,c),p|=e.YPykN(e[s(1243)](127,b),21),e.zsDpc(128,b)))if(e[s(965)](s(1201),e[s(1135)]))b=e[s(1426)](ee,c),y=127&b,e[s(420)](128,b)&&(b=e.PAFzY(ee,c),y|=e.KiWok(e[s(1481)](127,b),7));else return this[s(1448)]?l[s(1498)](this[s(1494)],0)*_0x3d1145+l[s(921)](this[s(380)],0):l[s(409)](l[s(470)](this.high,_0x50dd85),l[s(1498)](this[s(380)],0))}}else return this[s(655)]?this._ws[s(360)+"te"]:this[s(1513)][s(1178)+"cOpen"]?this.CONNECTING:this[s(664)]}else fOfifz[s(193)](_0x499d74,_0x1ef2b1)&&_0x54b241[s(1094)](_0x163e3d,_0x53036c);return{low:f|e.TwByH(p,28),high:e[s(960)](p>>>4,e.dhaBy(y,24)),unsigned:r}}function wt(c,r){let s=t,l=e[s(810)](r[s(380)],0),f=e[s(257)](e[s(591)](e[s(240)](r[s(380)],28),e[s(1301)](r[s(1494)],4)),0),p=e[s(1103)](r[s(1494)],24),y=e[s(1382)](0,p)?e[s(616)](0,f)?l<16384?e[s(1346)](l,128)?1:2:e[s(489)](l,2097152)?3:4:f<16384?e[s(726)](f,128)?5:6:e[s(614)](f,2097152)?7:8:e[s(1239)](p,128)?9:10,b=e[s(264)](se,c,y),w=c[s(1556)];switch(y){case 10:w[e[s(366)](b,9)]=e[s(1317)](e[s(810)](p,7),1);case 9:w[e.ySpFA(b,8)]=e.nOzTH(9,y)?e.zrdOC(128,p):e[s(694)](127,p);case 8:w[e.LZfbl(b,7)]=e[s(872)](8,y)?f>>>21|128:e[s(408)](e[s(348)](f,21),127);case 7:w[e.wdwbt(b,6)]=y!==7?e[s(1047)](f>>>14,128):e.ySrSW(e[s(240)](f,14),127);case 6:w[e.TRcMd(b,5)]=e[s(1267)](6,y)?e[s(955)](e.cAKQG(f,7),128):e.dJoEi(f,7)&127;case 5:w[b+4]=e[s(208)](5,y)?128|f:e[s(1243)](127,f);case 4:w[e[s(1024)](b,3)]=y!==4?e[s(1312)](e.pELXL(l,21),128):e.eMrSx(e[s(810)](l,21),127);case 3:w[e[s(316)](b,2)]=e[s(866)](3,y)?e.CKNNi(e[s(1270)](l,14),128):e[s(1559)](e[s(257)](l,14),127);case 2:w[b+1]=y!==2?e[s(673)](e.GxxFn(l,7),128):e.zsDpc(l>>>7,127);case 1:w[b]=e[s(872)](1,y)?128|l:e.pSpKe(127,l)}}function on(c){return v(c)}function Ht(c){return e[t(1120)]===e.JJZIb?e.rkGgw(S,c):new _0x33e9ae(_0x13e5ef,_0x4f2f00,_0x4d4da9)}let an=65536,oi=t(576),we=an*an,Ce=e.SLNDm(we,we),ar=e[t(1093)](Ce,2),Me=String.prototype[t(1572)+"At"];class he{constructor(r,s,l){let f=t;this[f(940)]=!0,this[f(380)]=e[f(207)](0,r),this.high=e.KVLRz(0,s),this[f(1448)]=!!l}static[t(940)](r){return r&&r[t(940)]===!0}static[t(379)](r,s,l){return new he(r,s,l)}static[t(625)+"s"](r,s,l){let f=t;return l?he[f(625)+f(306)](r,s):he[f(625)+f(684)](r,s)}static[t(625)+t(306)](r,s){let l=t,f={MbdJP:function(p,y){return e.bJLhT(p,y)},WtLir:function(p,y){return e.WWVyv(p,y)}};if(e[l(490)](e.ekizx,l(695)))return new he(e.ObVdb(e[l(1340)](r[0],e.wLUpf(r[1],8)),e.rmXUI(r[2],16))|e[l(1301)](r[3],24),e[l(1461)](e[l(673)](e[l(1583)](r[4],r[5]<<8),e[l(1288)](r[6],16)),e[l(968)](r[7],24)),s);if(_0x36e052===void 0)this[l(1218)+"rs"]={};else if(f[l(745)](void 0,_0x20df1f))this[l(1218)+"rs"][_0x3424e7]=null;else{let p=this._listeners[_0x383f37];if(p)for(let y=0;f.WtLir(y,p[l(1276)]);)f.MbdJP(p[y].fn,_0x19a81b)?p.splice(y,1):++y}return this}static["fromByte"+t(684)](r,s){let l=t;return new he(e.zdnvX(e[l(435)](e.zrdOC(e[l(857)](r[4],24),e[l(141)](r[5],16)),r[6]<<8),r[7]),e[l(1340)](e.KVLRz(e[l(435)](r[0]<<24,e[l(724)](r[1],16)),e[l(146)](r[2],8)),r[3]),s)}static fromHash(r){let s=t;return e[s(490)](r,oi)?bl:new he(e.JjlbV(e.aZwvq(e[s(1583)](Me[s(687)](r,0),e[s(1269)](Me[s(687)](r,1),8))|Me[s(687)](r,2)<<16,Me[s(687)](r,3)<<24),0),e[s(717)](e.KjqSZ(Me[s(687)](r,4)|Me[s(687)](r,5)<<8,e.dPeMw(Me.call(r,6),16)),Me[s(687)](r,7)<<24)>>>0,!0)}[t(652)](){let r=t;return String[r(395)+"Code"](255&this[r(380)],e.ULfJH(e.NEImB(this.low,8),255),e[r(869)](e[r(348)](this.low,16),255),e.MqHGG(this[r(380)],24),e[r(1559)](255,this[r(1494)]),e[r(919)](e.Ernfh(this[r(1494)],8),255),this[r(1494)]>>>16&255,e.rghvO(this.high,24))}static[t(1173)+"er"](r,s=!0){let l=t;if(e[l(757)](isNaN,r))return s?pg:bl;if(s){if(e[l(643)](r,Ce))return mg}else{if(e[l(313)](r,-ar))return wg;if(e.Wedzi(e[l(1024)](r,1),ar))return gg}return he[l(379)](e.tzBpW(e[l(976)](r,we),0),e.lDZid(r/we,0),s)}[t(1155)](){let r=t;return this[r(1448)]?e[r(966)](e[r(276)](e[r(880)](this.high,0),we),e[r(884)](this[r(380)],0)):e[r(752)](this[r(1494)]*we,this.low>>>0)}[t(443)](){let r=t;return this.high===0&&e[r(1468)](0,this[r(380)])}add(r){let s=t,l={WHnmO:function(f,p,y,b){return f(p,y,b)}};if(e[s(382)](e[s(388)],e[s(388)]))l[s(906)](_0x1880f7,this,_0x1c83c3,[_0x1b6140,_0x32a04e,_0x219134]);else{he[s(940)](r)||(r=he.fromNumber(r));let f=this[s(1494)]>>>16,p=65535&this[s(1494)],y=e[s(412)](this[s(380)],16),b=e[s(723)](65535,this[s(380)]),w=e[s(1270)](r[s(1494)],16),O=65535&r[s(1494)],B=e.cAKQG(r[s(380)],16),q=e[s(670)](65535,r[s(380)]),Z=0,$=0,ke=0,Pe=0;return Pe+=e[s(162)](b,q),ke+=Pe>>>16,Pe&=65535,ke+=e[s(291)](y,B),$+=e[s(725)](ke,16),ke&=65535,$+=e.VtkkQ(p,O),Z+=$>>>16,$&=65535,Z+=f+w,Z&=65535,he[s(379)](e.wjBEw(e[s(141)](ke,16),Pe),e[s(673)](e[s(595)](Z,16),$),this[s(1448)])}}equals(r){let s=t;return e[s(299)]===s(787)?(he[s(940)](r)||(r=he[s(1173)+"er"](r)),e[s(249)](this[s(1448)],r.unsigned)&&e.jIlKW(e[s(880)](this[s(1494)],31),1)&&e.EIMbW(e[s(1369)](r.high,31),1)?!1:e.lZyGf(this.high,r[s(1494)])&&e.KQirC(this.low,r[s(380)])):((this[s(1218)+"rs"][_0x309d3d]||(this._listeners[_0x5ad9cd]=[]))[s(402)]({fn:_0x45c58a,ctx:_0x1af793||this}),this)}[t(548)](){let r=t;return this.low===-1&&e.nnzsG(-1,this[r(1494)])?he[r(379)](0,0,this[r(1448)]):this.low===-1?he[r(379)](0,this[r(1494)]+1,this.unsigned):he[r(379)](e[r(782)](this[r(380)],1),this[r(1494)],this.unsigned)}[t(529)](r){return r?this.toBytesLE():this[t(1411)+"E"]()}toBytesLE(){let r=t,s=this.high,l=this[r(380)];return[e[r(799)](255,l),e[r(712)](l>>>8,255),e[r(799)](l>>>16,255),e[r(818)](l,24),e[r(723)](255,s),e.GHbVN(e[r(1036)](s,8),255),e[r(1131)](e[r(365)](s,16),255),e.eEyuk(s,24)]}[t(1411)+"E"](){let r=t,s=this.high,l=this[r(380)];return[s>>>24,e.PTmyK(e[r(880)](s,16),255),e[r(1243)](s>>>8,255),e[r(1273)](255,s),e.cFOCB(l,24),e[r(1274)](e[r(884)](l,16),255),e.kpmNg(e.oZgAV(l,8),255),e[r(1131)](255,l)]}}let bl=new he(0,0,!1),pg=new he(0,0,!0),gg=he[t(379)](-1,2147483647,!1),mg=he[t(379)](-1,-1,!0),wg=he.fromBits(0,-2147483648,!1);var cn=(function(c){let r=t,s=(r(1069)+r(1177))[r(690)]("|"),l=0;for(;;){switch(s[l++]){case"0":c[c[r(1234)+r(1435)]=5004]=r(1234)+"ERROR";continue;case"1":return c;case"2":c[c[r(1486)+"OR"]=5005]=e[r(1176)];continue;case"3":c[c[e[r(1042)]]=5003]=e[r(1042)];continue;case"4":c[c[e[r(524)]]=5002]=e[r(524)];continue;case"5":c[c[r(647)+r(1392)]=5001]="NATIVE_E"+r(1392);continue}break}})({});class cr{constructor(r){let s=t;this.type=r,this[s(1324)]=null}}class El extends cr{constructor(r,s){let l=t;super(r),this[l(891)]=s&&s[l(891)]||null}}class vl extends cr{constructor(r,s){let l=t;super(r),this[l(863)]=s&&s[l(863)]||null,this.colno=s&&s[l(606)]||0,this.filename=s&&s[l(1484)]||"",this[l(481)]=s&&s[l(481)]||0,this.message=s&&s[l(891)]||"",this.code=s&&s[l(905)]||5001}}class Sl extends cr{constructor(r,s){let l=t;e[l(778)](l(950),"IvvZo")?this._socket&&this[l(515)].close({code:_0x2c98b2,reason:_0x3e6b62}):(super(r),this.code=s&&s.code||0,this[l(737)]=s&&s[l(737)]||"",this[l(190)]=s&&s.wasClean||!1,this[l(1551)+l(447)]=s&&s[l(1551)+"nnect"]||!1)}}class Il extends cr{constructor(r,s){let l=t;super(r),this[l(998)]=s&&s[l(998)]||null}}class kl extends Il{constructor(r,s){let l=t;super(r),this[l(998)]=s&&s[l(998)]||null,this.message=s&&s[l(891)]||null}}class Al extends cr{constructor(r,s){let l=t;super(r),this[l(998)]=s&&s.data||null}}function lt(c,{message:r,code:s,error:l}){let f=t,p={MxIrz:function(y,b,w){return e.bEqCg(y,b,w)},aEYOV:e[f(770)],wwkgd:e[f(648)]};if(e[f(191)](f(1399),f(1399)))return new vl(c,{message:r,code:s,error:l});{this["_destroy"+f(1299)+"t"]();let y=p[f(970)](_0x635124,p[f(815)],{message:p.wwkgd});this[f(212)+f(1310)+"yReconnect"]&&this[f(212)+f(1310)+f(796)+"ct"](y)}}function _t(c,{code:r,reason:s,wasClean:l,willReconnect:f}){return new Sl(c,{code:r,reason:s,wasClean:l,willReconnect:f})}function Tl(c,{data:r,message:s}){return new kl(c,{data:r,message:s})}function Cl(c,{data:r}){return new Al(c,{data:r})}function Ca(c,{message:r}){return new El(c,{message:r})}class Pl{constructor(r,s){let l=t;this[l(601)+"s"]=r,this.maxRetries=s,this[l(1588)+l(1034)]=0,this[l(327)+"ndpointTriesCount"]=0}[t(460)+"pointCon"+t(311)](){let r=t;this[r(1588)+r(1034)]=0,this[r(327)+r(946)+r(619)+"t"]=0}[t(756)+"es"](){let r=t;this[r(327)+r(946)+r(619)+"t"]=0}[t(1391)+t(1257)+"nt"](){let r=t;return this[r(601)+"s"][this["currentI"+r(1034)]]}[t(1391)+t(1257)+t(674)+t(476)](){let r=t;return this[r(327)+"ndpointT"+r(619)+"t"]}[t(1539)+t(1236)+"es"](){let r=t;return e[r(1558)]===e[r(1558)]?!!(e[r(461)](this[r(1588)+r(1034)],this.endpoints[r(1276)])||e[r(1366)](this[r(1588)+"ndex"],e[r(622)](this[r(601)+"s"][r(1276)],1))&&e.kRlpU(this[r(327)+"ndpointT"+r(619)+"t"],this[r(1215)+"es"])):!0}[t(1248)+t(1156)+t(1124)+"hedMaxRe"+t(1130)](){let r=t;if(e[r(611)](e.JEhva,e[r(769)]))_0x5b0752-=65536,_0x293068+=e[r(741)](_0x5b7088,(_0x20e0bb>>10)+55296,(1023&_0xc839f)+56320),_0x343817+=3;else return e[r(1233)](this[r(1588)+r(1034)],this[r(601)+"s"][r(1276)])?!0:e.yHQuD(this[r(327)+r(946)+"riesCount"],this.maxRetries)}["replaceB"+t(1462)+t(1437)+t(1579)+t(425)](){let r=t;return this[r(327)+r(946)+r(619)+"t"]=1,this[r(1588)+"ndex"]++,this[r(601)+"s"][this["currentI"+r(1034)]]}[t(1391)+"ntEndpoi"+t(1512)+"ateCount"](){let r=t;return this[r(327)+"ndpointT"+r(619)+"t"]++,this[r(1391)+"ntEndpoint"]()}}let dr=(e[t(927)]!=typeof globalThis&&e[t(189)]===globalThis["construc"+t(640)][t(230)]||e[t(751)](e[t(927)],typeof window)&&e[t(331)](e[t(189)],window[t(1488)+"tor"][t(230)]))&&e.oWbgQ(t(233)+"d",typeof document),On=e.eEFmr!=typeof globalThis&&(e[t(1468)](e.RHzqr,globalThis[t(1488)+t(640)].name)||e.FTMwr(e.VryVh,globalThis[t(1488)+t(640)][t(230)]))&&e[t(875)](e[t(927)],typeof tt),ai=(e[t(953)](e[t(927)],typeof globalThis)&&e[t(1441)](e.RHzqr,globalThis[t(1488)+t(640)][t(230)])||e[t(1594)](t(233)+"d",typeof globalThis)||e[t(889)](e.eEFmr,typeof globalThis)&&!!globalThis[t(1536)+t(457)])&&e.mPGpN(e[t(927)],typeof wx),ci=e[t(927)]!=typeof globalThis&&(e[t(1410)](e.VryVh,globalThis[t(1488)+t(640)][t(230)])||e.rrcJo(e.Zfgbm,globalThis[t(1488)+"tor"][t(230)])||e[t(1382)](e[t(450)],globalThis[t(1488)+"tor"][t(230)]))&&e.FypDm(e.eEFmr,typeof self),_g=e.gBGvX(e[t(927)],typeof globalThis)&&e[t(297)](t(1261),globalThis[t(1488)+t(640)][t(230)])&&e[t(1284)]("undefined",typeof global)&&e[t(1410)](e[t(499)],global[t(1488)+t(640)][t(230)])&&e[t(751)](e[t(927)],typeof process)&&!!process[t(144)];class Pa{constructor(){let r=t;this[r(1218)+"rs"]={}}[t(1428)](r,...s){let l=t,f=this[l(1218)+"rs"][r];if(f)f[l(1470)]()[l(1265)](p=>p.fn[l(1351)](p[l(1381)],s));else if(e[l(278)](e[l(1563)],r)&&!this.onerror){let p=s[l(1276)]&&s[0];if(e[l(193)](p,Error))throw p;let y=new Error(e[l(1499)](l(754)+"d error.",p?e.Onokn(" ("+p.message,")"):""));throw y[l(1404)]=p,p}return this}off(r,s){let l=t;if(e[l(814)](void 0,r))this[l(1218)+"rs"]={};else if(s===void 0)this[l(1218)+"rs"][r]=null;else{let f=this[l(1218)+"rs"][r];if(f)for(let p=0;e.nfAmm(p,f[l(1276)]);)f[p].fn===s?f[l(768)](p,1):++p}return this}on(r,s,l){let f=t;return(this[f(1218)+"rs"][r]||(this[f(1218)+"rs"][r]=[])).push({fn:s,ctx:l||this}),this}}class yg extends Pa{[t(142)+t(239)+"age"](r){let s=t;return r[s(1163)]||r.errNo?(s(335)+" "+(r.errMsg||"")+s(1479)+(r.errNo||""))[s(979)]():JSON.stringify(r)}constructor(r,s,l){let f=t;if(e[f(776)](e[f(1075)],e[f(1075)]))super(),this[f(515)]=null,ai&&wx[f(510)+"ocket"]&&(this[f(515)]=wx["connectS"+f(1565)]({url:r,protocols:s,header:l,fail:this[f(1331)+f(735)+f(1419)][f(456)](this),success:this[f(1331)+f(841)+"cessHand"+f(1385)].bind(this)})),On&&tt[f(510)+"ocket"]&&(this[f(515)]=tt[f(510)+f(1565)]({url:r,protocols:s,header:l,fail:this[f(1331)+f(735)+"lHandler"].bind(this),success:this[f(1331)+"ocketSuc"+f(1514)+f(1385)][f(456)](this)}));else return _0x14dd35||(_0x2ca90c=[_0x5adba7,_0xd89324,_0x110344,_0x54a6cc,_0x579f8b])}[t(1331)+t(841)+t(1514)+t(1385)](){let r=t,s={ByIPE:function(l,f){return e.nnzsG(l,f)},NIBTf:function(l,f){return l===f},EgTGa:function(l,f){return e[j(802)](l,f)},DtKNu:function(l,f){return e.TRcMd(l,f)}};if(e[r(866)](e[r(1150)],e[r(467)]))Promise[r(1596)]()[r(1444)](()=>{let l=r;this[l(1314)+l(483)]()});else return this.low===-1&&CQWEpC.ByIPE(-1,this[r(1494)])?_0xc0e29d.fromBits(0,0,this[r(1448)]):CQWEpC[r(1370)](-1,this.low)?_0x27c37b.fromBits(0,CQWEpC.EgTGa(this.high,1),this[r(1448)]):_0x3aecf6[r(379)](CQWEpC[r(1175)](this[r(380)],1),this[r(1494)],this[r(1448)])}["_createS"+t(735)+"lHandler"](r){let s=t,l={NQoXF:function(f,p){return e[j(183)](f,p)},AgjJE:function(f,p){return e.WTogk(f,p)},WKzRS:e[s(826)]};if(e[s(341)](e[s(1543)],e[s(1543)])){let{offset:f}=e.BpeoA(_0x264c9f,_0x5032ac,_0xedeff8);_0x245a5b=f;let p={cursor_name:"",cursor:0,service:0},{value:y,offset:b}=e.zSqXT(_0x331936,_0xd6a5f4,_0x21fcf3);p[s(145)]=y,_0x51dd0d=b;let{value:w,offset:O}=e[s(464)](_0x9bd391,_0xc5506a,_0x304975);_0x3c1b15=O,p["cursor_n"+s(1199)]=e[s(1500)](_0x4e3420,_0x11e5eb,_0xfe8420,e[s(316)](_0x568062,w)),_0xd1ee2+=w;let{value:B,offset:q}=e.mcpGn(_0x5ee641,_0x247388,_0x14c3fb);p.cursor=B[s(1155)](),_0x527f8b=q,_0x24ab57[s(402)](p)}else Promise[s(1596)]()[s(1444)](()=>{let f=s;if(e.bJLhT(e[f(218)],e[f(1545)])){let p={gJQZv:function(y,b){let w=f;return dyqbSu[w(1455)](y,b)},sHEeu:function(y,b){let w=f;return dyqbSu[w(701)](y,b)}};_0x562dd2["addEvent"+f(819)](dyqbSu[f(302)],y=>{let b=f;_0x30b00c(p[b(937)](_0x262b88,_0x1094d3[b(1560)]),y[b(1046)+"on"],y[b(885)+"on"],p[b(406)](_0x1b6e28,_0x809b01[b(961)+"ion"]))})}else{let p=lt(e.ntpBo,{message:this[f(142)+"rrorMessage"](r)});this[f(1428)](e[f(1563)],p);let y=e[f(575)](_t,e[f(1184)],{reason:this[f(142)+"rrorMessage"](r)});this.emit(e[f(1184)],y)}})}[t(1314)+"steners"](){let r=t,s={dEjcD:e[r(1184)],jCatn:function(l,f){return l(f)},QPnsy:function(l,f,p,y){return l(f,p,y)},mFrHp:function(l,f){return e[r(208)](l,f)},ZMfCT:e[r(714)],EQvvy:e[r(1071)],RPsvb:function(l,f,p){return l(f,p)},ILggv:e[r(848)],yWyww:e.ntpBo,iKJhc:function(l,f,p){return e.HNgPX(l,f,p)}};this._socket.onOpen(l=>{let f=r;this[f(1428)](e[f(795)],e[f(229)](Cl,e[f(795)],{...l,data:l[f(1163)]||""}))}),this[r(515)][r(1295)](l=>{let f=r;this[f(1428)](f(577),_t(s[f(1054)],{...l}))}),this[r(515)][r(949)+"e"](l=>{let f=r;if(s.mFrHp(s[f(1510)],s[f(1510)])){let p=new _0x150971(s[f(1089)](_0x418af6,_0x3264fe));return s[f(416)](_0x230a24,_0x6ff473,p,0),p}else this.emit(s.EQvvy,s[f(381)](Tl,f(891),{...l}))}),this[r(515)][r(485)](l=>{let f=r,p={Ooncy:function(y,b){return s[j(1089)](y,b)}};s[f(163)]!==s.ILggv?(_0x398c25[_0x353c67[_0x2a0978][f(216)+f(1199)]]=p[f(453)](_0x1a4154,_0x41c99c[_0x5a46ca][f(216)+"ame"]),_0x35248e+=14+_0x639942[_0x270571[_0x3ed6c2][f(216)+"ame"]]):this[f(1428)](s.yWyww,s[f(522)](lt,s.yWyww,{...l,message:l[f(1163)]||""}))})}[t(232)](r){let s=t,l={YnIOn:function(f,p,y){return e[j(201)](f,p,y)},TSqqz:e[s(242)]};if(e[s(1290)](s(359),e.UyVsJ))this[s(154)+s(612)]=_0x24f130,this[s(1190)+s(1347)]=_0x374998,this["_message"+s(543)]=_0x5d7ed2,this._qosDB=l[s(1532)](_0x4069c0,this[s(154)+s(612)],l.TSqqz);else if(e[s(1154)](r,Uint8Array)){let f=r.buffer[s(1470)](r[s(883)+"et"],e[s(1203)](r[s(886)+"th"],r[s(883)+"et"]));this[s(515)]&&this._socket[s(232)]({data:f,fail:p=>{let y=s;this.emit(e.ntpBo,e.hLJnz(lt,e[y(1563)],{message:this[y(142)+y(239)+y(339)](p)}))}})}else this[s(515)]&&this._socket[s(232)]({data:r,fail:f=>{let p=s;this[p(1428)](e[p(1563)],e[p(192)](lt,p(863),{message:this["_formatE"+p(239)+p(339)](f)}))}})}close(r,s){let l=t;this[l(515)]&&this[l(515)][l(577)]({code:r,reason:s})}[t(1164)+"Listener"](r,s){this.on(r,s)}[t(1531)+"entListe"+t(1409)](r,s){this[t(634)](r,s)}get readyState(){let r=t;return this[r(515)][r(360)+"te"]}get binaryType(){return this[t(515)].binaryType}set[t(1446)+"pe"](r){}get url(){let r=t;return this[r(515)][r(452)]}get[t(492)](){let r=t;return this[r(515)][r(492)]}get[t(1057)+"ns"](){let r=t,s={pdtqP:function(l,f){return l<f},vMMsO:function(l,f){return e[j(1343)](l,f)},zaCAn:function(l,f){return l(f)},OrIgS:function(l,f){return e[j(1343)](l,f)},DoGQA:function(l,f){return e[j(669)](l,f)},ZjcKX:function(l,f){return l&f},ptjCz:function(l,f){return l+f},HhwFf:function(l,f){return e[j(440)](l,f)}};if(e[r(854)](r(777),r(777))){if(s[r(559)](_0x29fa9a,1)||s[r(713)](_0x5f030d,_0x729afc))return s[r(506)](_0x406200,_0x53060e);s[r(129)](s[r(904)](_0x212f4c,_0xbd1442),_0x2fce81)&&(_0x59697a=_0x17044c(_0x5419ae),_0x53e7a5=0);let l=_0x93e3dd.call(_0x5039d2,_0x592eee,_0x24ef3a+=_0x14caf3);return s[r(864)](7,_0x55ff0d)&&(_0x466614=s[r(585)](s[r(1287)](7,_0x4c7a42),1)),l}else return this[r(515)].extensions}get["buffered"+t(537)](){return 0}}function bg(c,r){let s=t;if(r)return new r(c[s(452)],c.protocol);if(ai||On)return new yg(c.url,c.protocol,c[s(455)]);if(e[s(1407)](dr,ci)&&e[s(953)](e[s(927)],typeof WebSocket)&&WebSocket)return new WebSocket(c[s(452)],c[s(492)+"s"])}function Eg(c){let r=t;return!!(c||ai&&wx[r(510)+r(1565)]||On&&tt.connectSocket||e.SDzVS(dr,ci)&&e[r(1418)](r(233)+"d",typeof WebSocket)&&WebSocket)}function Rl(c,r,s){let l=-1;async function f(p){let y=j;return e[y(1088)](p,l)?Promise[y(1307)](new Error(e[y(820)])):(l=p,e.YsIXP(p,s[y(1276)])?Promise[y(1596)]():s[p].bind(c)(r,f[y(456)](null,e.JOkxp(p,1))))}f(0)}function Dl(c){let r=t,s={gXvUi:function(l,f){return e[j(487)](l,f)},hPpMx:function(l,f){return e[j(1501)](l,f)},VkLhp:function(l,f){return e[j(1416)](l,f)},NHnzb:function(l,f){return e[j(291)](l,f)},jMOFB:function(l,f){return l<<f},QUyqx:function(l,f){return e[j(181)](l,f)},tNgBU:function(l,f){return e[j(591)](l,f)},ZmmeS:function(l,f){return e[j(1220)](l,f)},UJNlc:function(l,f){return e[j(479)](l,f)},cZXlP:function(l,f){return e.gsWgc(l,f)},BUOWS:function(l,f){return e[j(268)](l,f)},dbDyy:function(l,f){return l&f},KagvW:function(l,f){return e[j(568)](l,f)},mCxOW:function(l,f){return e[j(372)](l,f)},wPpDH:function(l,f){return l>>f},ARBGO:function(l,f){return l|f},TZPDJ:function(l,f){return e[j(1274)](l,f)}};if(e[r(761)](e[r(879)],e[r(879)])){let l=0,f=0;for(let p=0;e[r(614)](p,c[r(1276)]);++p)if(e[r(341)](e[r(304)],e[r(304)])){let y=_0x580ca0[r(1572)+"At"](_0x662968);NjNzhd[r(140)](y,55296)&&NjNzhd.hPpMx(y,56319)&&NjNzhd.VkLhp(NjNzhd[r(1105)](_0x639df7,1),_0x5127f2)&&(y=NjNzhd[r(1105)](NjNzhd.jMOFB(y,10),_0x5197ff[r(1572)+"At"](++_0x578bbd))-56613888),NjNzhd[r(1362)](y,128)?_0x1b2f3d[_0x1df7d1++]=y:(y<2048?_0x403493[_0x567009++]=NjNzhd[r(1096)](y>>6&31,192):(NjNzhd[r(943)](y,65536)?_0xed5dcd[_0xfbff6f++]=NjNzhd.UJNlc(NjNzhd[r(831)](NjNzhd[r(1473)](y,12),15),224):(_0x167eab[_0x3341be++]=NjNzhd[r(877)](NjNzhd.KagvW(y,18),7)|240,_0x35fb82[_0x42b29d++]=NjNzhd[r(731)](NjNzhd[r(1172)](y,12),63)|128),_0x4dafa4[_0x125027++]=NjNzhd.UJNlc(y>>6&63,128)),_0x3e542f[_0xb8b70a++]=NjNzhd.ARBGO(NjNzhd[r(781)](63,y),128))}else f=c[r(1572)+"At"](p),e[r(353)](f,128)?l+=1:f<2048?l+=2:e[r(278)](e[r(1517)](64512,f),55296)&&e[r(169)](64512&c[r(1572)+"At"](e[r(1507)](p,1)),56320)?(++p,l+=4):l+=3;return l}else{let l=_0x3dbdde[r(690)](":");for(let f=0;e[r(903)](f,l[r(1276)]);f++){let p=l[f];if(e[r(1526)](4,l[f][r(1276)])){let y=_0x2d5530[r(198)+"g"](0,e[r(1506)](4,l[f].length)),b=y.concat(p);_0x1d7d20=_0x1e2fc0[r(798)](b)}else _0x31ca4e=_0x41e5e5[r(798)](p)}return _0x2f2f26}}function Ol(c,r,s){let l=t,f={wFNcP:e.CGINN,tLwgA:e[l(1176)],bZOHb:e.xQgya,vXNwL:e[l(524)],IbPao:l(647)+l(1392),yzeQF:e[l(1309)]};if(e[l(616)](e.lpxJW,e[l(333)])){let p=f[l(774)][l(690)]("|"),y=0;for(;;){switch(p[y++]){case"0":_0x12e815[_0x25b8f8[lSHSOW[l(642)]]=5005]=lSHSOW[l(642)];continue;case"1":_0x3562f9[_0x511a40[lSHSOW[l(945)]]=5003]=lSHSOW[l(945)];continue;case"2":return _0x10a71a;case"3":_0x1eb5eb[_0x18aa3f[lSHSOW.vXNwL]=5002]=l(843)+"NG_ERROR";continue;case"4":_0x329d10[_0x29da70[lSHSOW[l(858)]]=5001]=lSHSOW[l(858)];continue;case"5":_0x2d2620[_0x290d3e[lSHSOW.yzeQF]=5004]=lSHSOW[l(1204)];continue}break}}else{if(e[l(353)](e[l(1593)](s,r),1))return"";let p="";for(let y=r;e[l(432)](y,s);){let b=c[y++];if(b<=127)p+=String[l(395)+"Code"](b);else if(e[l(643)](b,192)&&e[l(847)](b,224))p+=String[l(395)+l(708)](e[l(479)](e.GiCRv(e[l(723)](31,b),6),63&c[y++]));else if(e.kkkqY(b,224)&&b<240)p+=String[l(395)+l(708)](e[l(1577)](e.hcItB(15,b)<<12,(63&c[y++])<<6)|e.pSpKe(63,c[y++]));else if(b>=240){let w=e[l(1216)](e.kSwHA(e[l(243)](e[l(1477)](e[l(351)](7,b)<<18,e.EmYNJ(e[l(1474)](63,c[y++]),12)),e[l(924)](e[l(1458)](63,c[y++]),6)),e[l(586)](63,c[y++])),65536);p+=String[l(395)+l(708)](e.eTGJR(55296,w>>10)),p+=String["fromChar"+l(708)](e[l(1396)](56320,e[l(1045)](1023,w)))}}return p}}function Ra(c,r,s){let l=t,f=s,p,y;for(let b=0;e[l(411)](b,c[l(1276)]);++b)if(p=c[l(1572)+"At"](b),e[l(1239)](p,128))r[s++]=p;else if(e[l(1229)](p,2048))r[s++]=e[l(1477)](e[l(555)](p,6),192),r[s++]=e[l(1312)](e[l(869)](63,p),128);else if(e[l(152)](64512&p,55296)&&e[l(549)](e[l(1179)](64512,y=c.charCodeAt(e[l(1499)](b,1))),56320)){let w=e[l(355)][l(690)]("|"),O=0;for(;;){switch(w[O++]){case"0":++b;continue;case"1":r[s++]=e[l(228)](p>>18,240);continue;case"2":p=e[l(491)](e.DNBZm(65536,e[l(932)](e[l(694)](1023,p),10)),1023&y);continue;case"3":r[s++]=e.aKtXa(e[l(997)](63,p),128);continue;case"4":r[s++]=e.zdnvX(e.CzGgB(e[l(916)](p,6),63),128);continue;case"5":r[s++]=e[l(238)](e.esVCu(e.pXkcc(p,12),63),128);continue}break}}else r[s++]=e.lGHGu(e[l(621)](p,12),224),r[s++]=e[l(1002)](e.thMeQ(e[l(1258)](p,6),63),128),r[s++]=e.kJfUN(e[l(681)](63,p),128);return e[l(1593)](s,f)}async function Nl(c){let r=t;if(e[r(1233)](e[r(451)],typeof c)){let s=new Uint8Array(e[r(1511)](Dl,c));return e.nBRMN(Ra,c,s,0),s}return e[r(1554)](c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c.buffer,c[r(883)+"et"],c[r(886)+"th"])}function vg(c){let r=t;try{return e[r(1052)](e[r(451)],typeof c)&&(e[r(193)](c,ArrayBuffer)||c.buffer&&e[r(193)](c[r(689)],ArrayBuffer))||e[r(328)](e[r(451)],typeof c)?"":(JSON[r(1029)](c),e[r(148)])}catch{return e[r(1233)](r(1289),typeof c)?e[r(1232)]:""}}let Sg=(c,r)=>{let s=t;switch(c){case e[s(653)]:case e[s(1527)]:return{[s(434)+c]:1,"x-tt-env":r};default:return{}}};class Ig{constructor(r){let s=t;this[s(174)+"ount"]=r,this.count=0}[t(158)](){let r=t;this[r(1298)]++}["checkRea"+t(270)+"nt"](){let r=t;return this[r(1298)]>=this[r(174)+r(476)]}[t(1329)+t(1524)](r=0){let s=t,l={QirxH:function(f,p){return f|p},uqxZw:function(f,p){return e[j(498)](f,p)},ezoDy:function(f,p){return e[j(681)](f,p)},ZkYfz:function(f,p){return f<p}};e.CElbH(e.qnQaA,e[s(1522)])?(this[s(174)+s(476)]=r,this.count=0):(_0x55ed1f=LszZBl[s(195)](LszZBl.uqxZw(31&_0x28a98b,6),LszZBl[s(1553)](63,_0x24d33b)),LszZBl[s(1390)](_0x136c30,128)?_0x5b6a80+=_0x1f157a:(_0x41f464+=_0x90bbd4(_0x31221d),_0x291a25++))}}async function kg(c){let r=t,s={NUvnU:function(l,f){return e.JthUz(l,f)},WGOxg:e[r(907)],OIlDu:function(l,f){return e.oGnYq(l,f)},tpeWz:e.MwOTS,QKWKp:r(578),eRXIW:e[r(281)],XdrEE:function(l,f){return e[r(615)](l,f)},nNqVm:e[r(561)]};return new Promise(l=>{let f=r,p={HcwaE:function(y,b){return s.NUvnU(y,b)},epnJD:function(y,b){return y===b}};if(!dr)return s[f(773)](l,s[f(1471)]);try{let y=document[f(1041)+"ement"](s[f(1125)]);window[f(627)+f(1133)]=b=>{let w=f;document[w(908)][w(493)+"ild"](y),window[w(627)+w(1133)]=void 0,s[w(1126)](l,b&&b[w(588)]||s.WGOxg)},y[f(273)]=f(636)+f(759),y[f(930)]=c.replace(/^ws/,s[f(553)])+s[f(1528)];try{document.body[f(1251)+f(569)](y)}catch{document.body[f(493)+f(569)](y)}}catch{if(s[f(309)](s.nNqVm,s.nNqVm)){let y=p[f(1108)](_0x4ccb45,_0x3ba804);this[f(655)]&&p.epnJD(this[f(655)].readyState,this[f(1451)])&&(this[f(655)]&&this[f(655)][f(232)](y),this._debug(f(516),_0x1538bd))}else window[f(627)+"JSONP"]=void 0,l(s[f(1471)])}})}function dn(c,r,s){let l=t,f={RLcWe:function(p,y){return e[j(1334)](p,y)},sBEJY:e[l(907)]};if(e[l(1408)](e.aavGo,e.aavGo))_0x172c46[l(627)+l(1133)]=void 0,wSNLyx[l(830)](_0x3771e5,wSNLyx[l(922)]);else return!!c?.[l(1575)](p=>p[l(983)]===r&&p.value===s)}function lr(c,r){let s=t;return c?.find(l=>l.key===r)?.[s(1020)]}let Da=null;async function Ag(){let c=t;return Da||(Da=Promise[c(1596)]().then(zt.bind(zt,c(590)))),Da}class Tg extends Pa{constructor(r,s){let l=t;super(),this[l(881)]=r,this._keyPath=s,this[l(1429)]=void 0,this["_initPro"+l(861)]=null}async[t(925)](){let r=t;if(e[r(222)](e[r(686)],e[r(686)]))await this[r(599)]();else return!!this._qosDB}async[t(599)](){let r=t,s={NoZgr:function(l){return e[j(597)](l)},NpBsg:function(l,f){return e.qIWBw(l,f)},BODdz:e.Vasix,VzByW:function(l,f,p,y){return e[j(603)](l,f,p,y)}};if(!this[r(1429)]){if(this[r(807)+"mise"])return this[r(807)+r(861)];try{let l=this[r(881)],f=this._keyPath;this[r(807)+"mise"]=(async()=>{let p=r,y={GXxkd:function(b){return s.NoZgr(b)},wPzSN:function(b){return s.NoZgr(b)}};if(s.NpBsg(s.BODdz,s[p(718)]))srZNzK[p(431)](_0x1ed1b9),srZNzK.wPzSN(_0xe48208);else{let{openDB:b}=await s[p(1378)](Ag);this[p(1429)]=await s[p(1384)](b,p(627)+"_"+l,1,{upgrade(w){w[p(234)+"jectStore"](l,{keyPath:f})}})}})(),await this[r(807)+r(861)]}catch(l){console.log(l)}finally{this[r(807)+r(861)]=null}}}async[t(1058)](r){let s=t;try{if(e.hQCAi(e[s(1305)],s(1249)))e[s(1235)](_0x419e65,_0x1a33fe,24),e.FJYWz(_0x2fceee,_0x58bfeb,e[s(231)](_0x4bd17f,_0x126b13));else return await this[s(599)](),this[s(1429)]?.[s(1058)](this._dbName,r)}catch(l){console[s(279)](l)}}async set(r,s){return await this[t(599)](),this._qosDB?.put(this._dbName,r)}async[t(878)](r){let s=t;try{return await this._init(),this[s(1429)]?.[s(1272)](this[s(881)],r)}catch(l){console.log(l)}}async[t(155)](){let r=t;try{return await this[r(599)](),this._qosDB?.clear(this[r(881)])}catch(s){console.log(s)}}async keys(){let r=t;if(e.JsWlL(r(444),e.ZlQop))return await this._init(),this._qosDB?.[r(462)+"ys"](this._dbName);this[r(1048)+"hCloseEv"+r(1174)](_0x14c624(e.HPvHG,{code:1e3,reason:e[r(738)]})),this[r(628)+"tManager"]?.["resetEnd"+r(446)+r(311)](),this[r(511)+r(319)]?.["resetCou"+r(1524)]()}async[t(602)](){let r=t;return await this[r(599)](),this[r(1429)]?.[r(602)](this[r(881)])}async closeDB(){let r=t;try{if(e.DSVvc(e.xCwbf,e[r(828)]))this[r(1429)]?.[r(577)](),this[r(1429)]=void 0;else{let s=_0x6d1919.split(/\./).map(p=>_0xc971be(p)),l=[];return l[0]=e[r(503)](_0x565540,e[r(1225)](s[0],s[1])),l[1]=_0x4df188(e[r(974)](s[2],s[3])),[e.ngsNu,e[r(1101)],e[r(1101)],"0000",e[r(1101)],e[r(991)],l[0],l[1]][r(659)]("")}}catch(s){console[r(279)](s)}}get[t(928)](){let r=t;try{return!!this[r(1429)]}catch(s){return console.log(s),!1}}}class Cg{constructor(r,s){let l=t;this[l(1580)]=r,this._pathKey=s,this[l(1429)]=localStorage}async[t(925)](){}get[t(809)](){return"frontier_"+this[t(1580)]}async[t(1058)](r){let s=t,l=this._qosDB[s(557)](this[s(809)]);return JSON.parse(e[s(1231)](l,"{}"))[r]}async[t(1094)](r,s){let l=t,f=this._qosDB[l(557)](this[l(809)]),p=JSON.parse(e[l(668)](f,"{}"));return p[s||r[this[l(250)]]]=r,this[l(1429)][l(1525)](this[l(809)],JSON[l(1100)+"y"](p)),s||r[this[l(250)]]}async[t(878)](r){let s=t,l=this._qosDB[s(557)](this._prefix),f=JSON[s(1029)](e[s(1231)](l,"{}"));return f[r]=void 0,this[s(1429)][s(1525)](this._prefix,JSON[s(1100)+"y"](f))}async clear(){let r=t;return this[r(1429)][r(155)]()}async keys(){let r=t,s=this._qosDB.getItem(this[r(809)]),l=JSON[r(1029)](e[r(1350)](s,"{}"));return Object[r(523)](l)}async[t(602)](){let r=t,s=this[r(1429)][r(557)](this[r(809)]),l=JSON[r(1029)](e[r(1056)](s,"{}"));return Object[r(1489)](l)}[t(369)](){return Promise[t(1596)]()}get[t(928)](){return!!this[t(1429)]}}class Pg{constructor(r,s){let l=t;this[l(1580)]=r,this[l(250)]=s,this._qosDB=On?tt:ai?wx:null}async[t(925)](){}get[t(809)](){return t(627)+"_"+this._DBName}async get(r){let s=t,l=this[s(1429)][s(835)+s(1401)](this[s(809)]);return JSON[s(1029)](e[s(853)](l,"{}"))[r]}async[t(1094)](r,s){let l=t,f=this[l(1429)][l(835)+l(1401)](this[l(809)]),p=JSON[l(1029)](f||"{}");return p[s||r[this[l(250)]]]=r,this[l(1429)][l(501)+"geSync"](this[l(809)],JSON[l(1100)+"y"](p)),s||r[this[l(250)]]}async[t(878)](r){let s=t,l=this._qosDB[s(835)+s(1401)](this[s(809)]),f=JSON[s(1029)](l||"{}");return f[r]=void 0,this[s(1429)].setStorageSync(this._prefix,JSON[s(1100)+"y"](f))}async[t(155)](){let r=t;return this[r(1429)]["clearSto"+r(255)]()}async keys(){let r=t,s=this[r(1429)][r(835)+"geInfoSync"](this[r(809)]),l=JSON[r(1029)](s||"{}");return Object[r(523)](l)}async[t(602)](){let r=t,s=this[r(1429)][r(835)+r(656)+"nc"](this[r(809)]),l=JSON.parse(e[r(734)](s,"{}"));return Object.values(l)}[t(369)](){return Promise.resolve()}get[t(928)](){return!!this._qosDB}}function Ll(c,r){let s=t;if(e.uuhmn(On,On))return new Pg(c,r);if(e[s(668)](dr,ci)&&e[s(927)]!=typeof indexedDB)return new Tg(c,r);if(e[s(691)](dr,ci)&&e[s(927)]!=typeof localStorage)return new Cg(c,r);throw new Error(e[s(709)])}class Rg{constructor(){let r=t;this._intervalTimeoutId=null,this[r(1478)+"l"]=36e5,this[r(1429)]=e.uxxyd(Ll,e[r(1262)],e.wPzaN)}async[t(1478)+t(1403)](){let r=t;e[r(1132)](clearInterval,this["_interva"+r(1039)+"Id"]),this[r(1478)+r(1039)+"Id"]=e[r(755)](setInterval,()=>{let s=r;this[s(550)+s(1027)]()},this._interval)}async[t(925)](){let r=t;if(e[r(1357)](e[r(275)],e[r(172)])){if(this[r(1513)][r(939)+r(766)+"nect"]||this[r(867)+r(1149)])return;this["_handleR"+r(914)]()}else await this[r(1429)].openDB()[r(1444)](()=>{let s=r;this[s(1478)+s(1403)]()})}async flushExpired(){let r=t;(await this._qosDB?.getAll()||[])[r(1450)](({timestamp:f})=>f<Date.now()).forEach(f=>{let p=r;this[p(1429)]?.[p(878)](f[p(252)+"id"])})}async[t(878)](r){let s=t;if(e[s(490)](e.xbhPr,"ArQcB")){let l=(s(1086)+"1|0")[s(690)]("|"),f=0;for(;;){switch(l[f++]){case"0":fOfifz[s(824)](_0x136730,p=>({...p,get:(y,b,w)=>_0x32ce7d(y,b)||p[s(1058)](y,b,w),has:(y,b)=>!!_0x42a36b(y,b)||p[s(1503)](y,b)}));continue;case"1":_0x53f4d7=new _0x22cdcb;continue;case"2":_0x2205c4=[fOfifz[s(740)],fOfifz.NHRSc,fOfifz[s(1022)],fOfifz[s(641)]];continue;case"3":fOfifz[s(856)](_0x5f5877);continue;case"4":_0x4260f0();continue;case"5":_0x34968c=["get",fOfifz[s(702)],fOfifz[s(1379)],fOfifz[s(1529)],fOfifz[s(849)]];continue}break}}else return this[s(1429)]?.[s(878)](r)}async[t(1094)](r,s){let l=t;if(e[l(199)](e.PqgNq,e[l(772)]))this[l(1580)]=_0x141d27,this[l(250)]=_0x209e81,this._qosDB=_0x4d321b;else return this._qosDB?.[l(1094)]({message_id:r,timestamp:s})}async get(r){let s=t;return this._qosDB?.[s(1058)](r)}async closeDB(){let r=t;clearInterval(this[r(1478)+"lTimeoutId"]),await this[r(1429)]?.[r(369)]()}get[t(928)](){let r=t;if(e[r(672)]==="ALlPN"){let s=e[r(394)][r(690)]("|"),l=0;for(;;){switch(s[l++]){case"0":this._ws["removeEventListe"+r(1409)](e[r(1563)],this[r(1493)]);continue;case"1":this[r(655)][r(1531)+r(696)+r(1409)](e[r(1184)],this[r(1333)]);continue;case"2":this._ws[r(1531)+r(696)+r(1409)](e[r(795)],this[r(682)]);continue;case"3":if(!this[r(655)])return;continue;case"4":this[r(655)][r(1531)+"entListe"+r(1409)](r(891),this[r(1191)+"ge"]);continue}break}}else return this[r(1429)]?.[r(928)]}}function Oa(c){let r=t,s=!!this[r(1513)][r(334)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(123)](dn,c[r(891)][r(455)],e[r(1168)],"2"),f=l&&dn(c[r(891)][r(455)],e.LBYiu,"1"),p=l&&e[r(1080)](dn,c[r(891)].headers,r(463)+r(552)+"k","1"),y=p?lr(c[r(891)][r(455)],e[r(194)])?.[r(690)](",")[r(1450)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:p,ackMsgIds:y}}async function Ml(){let c=t;return this["_QoSMana"+c(658)]||(this["_QoSMana"+c(658)]=new Rg),this[c(1059)+c(658)][c(928)]||await this[c(1059)+"ger"].openDB(),this[c(1059)+c(658)]}async function Dg(c,r){let s=t,{enableAutoAck:l}=this[s(1513)],f=e.HEOhE(dn,c.message.headers,e.LsAHM,"1"),p=e.rQmSh(dn,c[s(891)].headers,e.asubO,"1"),y=Oa.call(this,c);if(e[s(1508)](l,f))if(e[s(1266)](e[s(1189)],e[s(215)])){let{SeqID:b,LogID:w,service:O,LogIDNew:B,method:q}=c[s(891)];this[s(1373)]({SeqID:b,LogID:w,LogIDNew:B,service:O,method:q,headers:[{key:e[s(403)],value:"1"},{key:s(1223),value:e[s(623)](B,"")},{key:e[s(1294)],value:"0"}]})}else this[s(1576)+"er"]&&_0x5a9c2d[s(1164)+s(819)](e.eiWCe,this[s(362)+s(944)]),this[s(1576)+"er"]&&_0x3a965f[s(1164)+"Listener"](e.AYKLv,this["_handleO"+s(1209)]),this[s(1576)+"er"]&&_0x1665af[s(1164)+"Listener"](s(1547),this[s(962)+s(1072)]),this[s(1576)+"er"]&&_0x24f59e["addEvent"+s(819)](e[s(350)],this[s(962)+"ageShow"]);p&&!y.isQoSAck&&this[s(1048)+s(1062)+s(978)](c),r()}async function Og(c,r){let s=t,l={SnbtW:e[s(1291)],nhqTG:function(f,p){return e[s(121)](f,p)},oZIoS:s(233)+"d"};if(e[s(1033)]===s(1038)){let f=l[s(539)][s(690)]("|"),p=0;for(;;){switch(f[p++]){case"0":return!1;case"1":if((_0x3c028b||_0x292870)&&ABPwdk[s(1122)](ABPwdk[s(1035)],typeof _0x4f1155)&&_0x20b5f4)return!0;continue;case"2":if(_0x41e37d&&_0x2b181b[s(510)+s(1565)])return!0;continue;case"3":if(_0x33c7e1)return!0;continue;case"4":if(_0x2d2dfb&&_0x4f3f94[s(510)+"ocket"])return!0;continue}break}}else this._debug(e[s(357)],c[s(891)]),e[s(597)](r)}async function Ng(c,r){let s=t,l=on(await e[s(1490)](Nl,c[s(998)]));try{if(l[s(571)]instanceof Uint8Array){if(e[s(1357)](e[s(1114)],e[s(855)]))return _0x58469b[s(821)+s(1092)]||_0x20495c[s(1058)](_0x161132);{let f=e[s(1452)](this[s(1513)][s(1445)+s(368)],Object)?{force:!!this[s(1513)][s(1445)+"ncoding"].force,encoding:this[s(1513)][s(1445)+"ncoding"].encoding?this._options[s(1445)+s(368)][s(730)][s(910)](/\s/g,"")[s(1030)+s(352)]():""}:{force:!1,encoding:this._options[s(1445)+s(368)]?this[s(1513)]["payloadE"+s(368)][s(910)](/\s/g,"")[s(1030)+s(352)]():""},p=l[s(1445)+s(368)]?l[s(1445)+s(368)][s(910)](/\s/g,"").toLowerCase():"",y=e.XiNUa(this[s(1513)][s(1214)+s(324)],Object)?{force:!!this[s(1513)][s(1214)+s(324)][s(911)],type:this[s(1513)][s(1214)+s(324)].type?this[s(1513)][s(1214)+s(324)][s(273)][s(910)](/\s/g,"")[s(1030)+"ase"]():""}:{force:!1,type:this[s(1513)][s(1214)+s(324)]?this[s(1513)][s(1214)+s(324)][s(910)](/\s/g,"")[s(1030)+"ase"]():""},b=l["payloadT"+s(324)]?l[s(1214)+s(324)][s(910)](/\s/g,"")[s(1030)+s(352)]():"",w=y[s(911)]?y.type:b||y[s(273)],O=f[s(911)]?f[s(730)]:p||f.encoding,B=[s(1300)+s(767)+s(933),e.YONzM,e.FnYOA,e[s(451)]],q=["none_none",e[s(838)]];this[s(1513)][s(613)+"ansformT"+s(1082)+"ad"]&&B[s(505)](w)&&(!O||q[s(505)](O))?l[s(413)+s(1111)]=e.ZlnMI(Ol,l[s(571)],0,l[s(571)][s(886)+"th"]):l[s(413)+"oad"]=""}}else l[s(413)+s(1111)]=""}catch(f){if(e[s(383)](e[s(1271)],e.CHlRx))l[s(413)+s(1111)]="",console.log(f);else{let p=this[s(628)+s(415)]?.[s(1391)+"ntEndpoint"](),y=this[s(1513)][s(305)+"tInterce"+s(1275)](_0x2b4f99.code,_0x111a62[s(737)]);this[s(1048)+s(969)+s(1174)](e[s(1078)](_0x3d9dd2,s(577),{code:1006,reason:_0x4f1589.reason||s(598)+s(1140)+s(592)+"wn reaso"+s(1533)+s(746)+p,willReconnect:y})),y&&this[s(419)]();return}}c.message=l,e[s(856)](r)}function Lg(c,r,s){let l=t,f=e[l(734)](s,8192),p=f>>>1,y=null,b=f;return function(w){let O=l;if(w<1||e[O(1343)](w,p))return c(w);e[O(1367)](b,w)>f&&(y=c(f),b=0);let B=r[O(687)](y,b,b+=w);return e[O(1438)](7,b)&&(b=e[O(366)](e[O(1422)](7,b),1)),B}}let Mg=4294967295;function Bg(c,r,s){let l=t,f={UsfYT:function(p,y){return e.qRYCR(p,y)}};return l(1472)==="EWuHa"?sBbaOC[l(786)](_0x77e5f2[l(1574)],_0x2757eb[l(1123)]):e.LDQyX(RangeError,e[l(1203)](e[l(162)](e[l(966)]("index ou"+l(967)+l(1240),c),l(532))+e[l(668)](r,1)," > ")+s)}function Fg(c,r,s){let l=t;if(e[l(1375)](s,Mg))throw new Error(e[l(1325)]);let f=3;for(;e[l(474)](f,0);)if(e[l(776)](e.GulUw,l(563))){let p=e[l(1317)](255,s);e.nBRMN(La,p,c,e[l(366)](r,f)),s>>>=8,f--}else _0x464b68=fOfifz[l(822)](_0x291474,_0x302c43);return r+4}function zg(c,r){let s=t,l=0,f=r,p=r+4;for(;e[s(614)](f,p);)if(e.hpUCw(e[s(1245)],s(1170))){let y=this._listeners[_0x8cabd1];if(y)for(let b=0;e[s(792)](b,y[s(1276)]);)e.HHRAU(y[b].fn,_0x1ba639)?y[s(768)](b,1):++b}else{let{value:y,offset:b}=e[s(994)](Na,c,f);f=b,l=e[s(261)](l,8)>>>0,l+=y}return{value:l,offset:p}}function Ug(c,r,s){let l=t,f=e[l(390)][l(690)]("|"),p=0;for(;;){switch(f[p++]){case"0":if(r.utf8Write)return e[l(308)](r.utf8Write(c,s),s);continue;case"1":if(r[l(1356)])return e[l(1115)](r[l(1356)](c,s),s);continue;case"2":return e[l(1500)](Ra,c,r,s)+s;case"3":if(c.length<40)return e.TRcMd(Ra(c,r,s),s);continue;case"4":if(!c)return s;continue}break}}function Hg(c,r){let s=t,l=new he(e[s(968)](c[e[s(1548)](r,4)],24)|e[s(1060)](c[e[s(124)](r,5)],16)|e[s(728)](c[e[s(162)](r,6)],8)|c[r+7],e.ZVnST(e[s(527)](c[e[s(1507)](r,0)],24),e[s(779)](c[e.lQeFw(r,1)],16))|e.uQLxt(c[e[s(669)](r,2)],8)|c[r+3],!0);return r+=8,{value:l,offset:e.LZfbl(r,8)}}function Gg(c,r,s){let l=t,f=c[l(380)],p=c[l(1494)];return r[s]=e.cFOCB(p,24),r[e[l(1225)](s,1)]=e[l(348)](p,16)&255,r[e[l(974)](s,2)]=p>>>8&255,r[s+3]=e[l(799)](255,p),r[e.xYiag(s,4)]=e.rQCnE(f,24),r[e[l(316)](s,5)]=e[l(420)](e.JjlbV(f,16),255),r[e[l(500)](s,6)]=e.uZIgF(e[l(298)](f,8),255),r[e.aNYsz(s,7)]=255&f,s+=8,s}function Na(c,r){let s=t,l={nrngD:function(f,p,y,b,w){return e[j(667)](f,p,y,b,w)},GvDMJ:function(f,p){return e[j(503)](f,p)}};if(e[s(854)](s(1247),s(427)))return c[s(635)+"8"]?{value:c[s(635)+"8"](r),offset:e[s(639)](r,1)}:{value:e[s(417)](255,c[r]),offset:r+1};bduaSK.nrngD(_0x57fab9,bduaSK.GvDMJ(_0x4baf0c,_0x44b351[s(1560)]),_0xd3812e[s(1046)+"on"],_0x4e4133.newVersion,bduaSK[s(1442)](_0x3c426a,_0x4c343c[s(961)+"ion"]))}function La(c,r,s){let l=t;return r.writeUint8?r[l(850)+"t8"](c,s):r[s]=e[l(1474)](255,c),e[l(1098)](s,1)}let qg=function(c){let r=t;if(e.CElbH(e.FJZfh,e[r(288)])){if(e.FwpWr(e[r(162)](_0x1c8dc6[r(1574)],_0x5bdb9c),_0x34e27f[r(1123)]))throw new _0x18bb12(e[r(719)]);_0x550849[r(1574)]+=_0x41744f}else return new Uint8Array(c)},jg=e[t(927)]!=typeof Buffer?Buffer[t(1263)+"afe"]:e[t(755)](Lg,qg,Uint8Array.prototype[t(1320)]),Wg=16,Ma=32;function Kg(c){let r=t,s={CkVzE:function(p,y,b){return p(y,b)},ZhgPo:function(p,y,b){return e[j(680)](p,y,b)}},l=0,f={};for(let p=0;p<c.length;p++)e[r(341)](e[r(274)],e[r(274)])?(uYJfgd[r(428)](_0x596cb8,_0x5ecf86,58),uYJfgd[r(376)](_0x2e308d,_0x4c4798,_0xb0b065)):(f[c[p][r(216)+r(1199)]]=Dl(c[p]["cursor_n"+r(1199)]),l+=e[r(1115)](14,f[c[p]["cursor_n"+r(1199)]]));return[l,f]}function Bl(c,r,s){let l=t;if(e[l(159)](e[l(654)],e.AhZnh)){let[f,p]=Kg(c),y=e[l(161)](jg,f),b=0;return c.forEach(w=>{let O=l,B=e.dhhii[O(690)]("|"),q=0;for(;;){switch(B[q++]){case"0":b=e.NBJzV(La,p[w[O(216)+O(1199)]],y,b);continue;case"1":console.log(O(771)+O(1414),w,w[O(145)]);continue;case"2":b=e[O(1200)](Fg,y,b,w[O(145)]||0);continue;case"3":b=Gg(he[O(1173)+"er"](w[O(1319)]||r),y,b);continue;case"4":console[O(279)](e[O(956)],b);continue;case"5":console[O(279)]("header",b);continue;case"6":console.log(e[O(1496)],b);continue;case"7":console.log(e[O(1453)],b);continue;case"8":console[O(279)](e[O(373)],b);continue;case"9":b=e.nBRMN(La,0,y,b);continue;case"10":b=e[O(870)](Ug,w["cursor_n"+O(1199)],y,b);continue}break}}),{frameType:Ma,headers:[{key:e[l(164)],value:s}],payload:y}}else return _0x5ee902 instanceof _0x549390&&(fOfifz[l(1151)](_0x2d5855,fOfifz[l(581)])||fOfifz[l(1268)](_0x41308b,l(1415)))?!0:_0x45db9a in _0x575ff7}function $g(c){let r=t;if(e[r(1412)](e[r(596)],"dWCTf")){let s=0,l=[];for(;e[r(1220)](s,c[r(886)+"th"]);){let{offset:f}=Na(c,s);s=f;let p={cursor_name:"",cursor:0,service:0},{value:y,offset:b}=zg(c,s);p[r(145)]=y,s=b;let{value:w,offset:O}=e.gydbQ(Na,c,s);s=O,p["cursor_n"+r(1199)]=e.jCuIX(Ol,c,s,s+w),s+=w;let{value:B,offset:q}=Hg(c,s);p[r(1319)]=B[r(1155)](),s=q,l.push(p)}return l}else _0x766bf5[r(413)+"oad"]="",_0x52486e[r(279)](_0x16cdd2)}function Vg(){let c=t;return{frameType:Ma,headers:[{key:e[c(164)],value:"FILE_NOT"+c(502)}],payload:void 0}}class Jg{constructor(r,s,l){let f=t;this["_cursorN"+f(612)]=r,this[f(1190)+f(1347)]=s,this[f(845)+f(543)]=l,this._qosDB=e[f(1188)](Ll,this["_cursorN"+f(612)],f(216)+"ame")}async[t(925)](){let r=t;await this[r(1429)][r(925)]()}async[t(646)+"rs"](){let r=t;if(e[r(1487)]("tbMII","JOyna"))return _0x3fce80[r(1556)][e[r(575)](_0x5a67f4,_0x5a0367,1)];{if(!this[r(1429)].isReady)return;let s=this["_message"+r(543)],l=await this[r(1429)][r(602)]();switch(console[r(279)](e[r(895)],l),s){case e[r(1011)]:return l&&l[r(1276)]?e[r(603)](Bl,l,0,this._cursorFileName):void 0;case e[r(1127)]:return;case e[r(1244)]:return l&&l[r(1276)]?e[r(177)](Bl,l,0,this[r(1190)+r(1347)]):e[r(856)](Vg)}}}async[t(1094)](r,s,l){let f=t;return console.log(e[f(1423)],r,s,l),this[f(1429)][f(1094)]({cursor_name:r,cursor:s,service:l})}async[t(1292)+"rs"](r){let s=t;if(e[s(1302)](e[s(1327)],e[s(468)]))_0x25654d[s(908)][s(1251)+"ild"](_0x5bbc07);else{let l=e[s(1006)]($g,r);for(let f of l)console[s(279)](e[s(587)],l),await this[s(1429)].set(f)}}async get(r){let s=t;return(await this[s(1429)][s(1058)](r))?.[s(1319)]}async closeDB(){let r=t;await this._qosDB[r(369)]()}[t(404)+"rsorFile"+t(1003)](r){let s=t,l={Prjld:e.SFKas};e[s(486)](e.EmUqT,e.EmUqT)?(this[s(1428)](l[s(837)],_0x3d7c0c),this[s(1194)+s(679)]&&this[s(1194)+s(679)](_0x2407f6)):this[s(1190)+"ileName"]=r}get isReady(){return this[t(1429)].isReady}}let Zg=e.AfWTR;async function Fl(c){let r=t;if(e[r(1589)](e.TFgUi,e[r(1457)]))_0xa31f4d=_0x173418[r(798)](_0x3ba7fb),_0xa3e44f=_0x11b660[r(798)](_0x17afcc[_0x1a682c]);else{if(!this[r(1513)].enableQoS)return null;let{aID:s,fpID:l,messageStrategy:f}=this._options,p=e[r(375)](c,Zg);try{return this[r(1388)+r(678)]?c&&this[r(1388)+r(678)]["updateCu"+r(1169)+r(1003)](c):this[r(1388)+r(678)]=new Jg(l+"_"+s+"_"+p,p,f),this[r(1388)+r(678)][r(928)]||await this[r(1388)+"anager"][r(925)](),this[r(1388)+r(678)]}catch{return null}}}async function Yg(c,r){let s=t,l=e.rQmSh(dn,c.message.headers,e[s(267)],"-1"),f=e[s(982)](dn,c.message[s(455)],e.asubO,"1"),p=e.gArSK(lr,c.message.headers,e[s(284)]),y=Number(lr(c[s(891)][s(455)],e.PhQfd))||0,b=Oa[s(687)](this,c),w=e[s(603)](dn,c[s(891)][s(455)],e.pwggA,"2"),O=lr(c.message.headers,e[s(1515)]),B=e[s(651)](Number,e[s(951)](lr,c.message[s(455)],e.tkLwL));if(b.isQoSAck)return e[s(856)](r);let q=b[s(1443)+s(657)]?await Ml[s(687)](this):null;if(c[s(891)][s(145)]>0&&f&&!l||e[s(989)](c.message[s(145)],0)){if(p&&b.isQoSMessage&&q)return!!!await q[s(1058)](p)&&(this[s(1048)+s(303)+s(1278)](c),await q.set(p,Date[s(1569)]()+y)),e[s(1546)](r);if(w){let Z=await Fl.call(this);if(!Z)return this[s(1048)+s(303)+s(1278)](c),e[s(386)](r);let $=await Z[s(1058)](O)??-1;if($<B)this[s(1048)+s(303)+s(1278)](c),Z[s(1094)](O,B,c[s(891)].service);else throw new Error(s(521)+s(716)+s(370)+B+(" larger "+s(980)+s(1485)+"r ")+$);return e.ionoF(r)}return this["_dispatc"+s(303)+s(1278)](c),e.lZVvk(r)}}async function Xg(c,r){let s=t,l=Oa[s(687)](this,c);if(!l["isQoSMes"+s(657)])return e.yHtem(r);let f=await Ml[s(687)](this);if(l[s(466)+s(497)+"age"]&&l[s(185)+"s"].length)for(let p of l.ackMsgIds)await f[s(878)](p);e[s(345)](r)}async function Qg(c,r){let s=t,l={XisVU:function(f,p){return e[j(1277)](f,p)},JoEUI:function(f,p){return e[j(1243)](f,p)},qJXIN:function(f,p){return e[j(1341)](f,p)},AyCEu:function(f,p){return e.Uynxk(f,p)},YdkIR:function(f,p){return e.GsAMn(f,p)},nQLWC:function(f,p){return f>=p},zzqmG:function(f,p){return f<=p},UBtaQ:function(f,p){return e.LiovQ(f,p)}};if(e[s(152)](e[s(530)],e[s(685)]))_0x205055=CljExz[s(346)](CljExz[s(556)](15,_0x8651a8),12)|CljExz[s(346)](CljExz.qJXIN(63,_0x4d885c),6)|CljExz[s(1495)](63,_0x439fb4),CljExz.YdkIR(_0x1813af,2048)||CljExz[s(1224)](_0x18041c,55296)&&CljExz.zzqmG(_0x48076e,57343)?_0x20d1ec+=_0x1a7998:(_0x25e18d+=CljExz.UBtaQ(_0x4dd3c7,_0x2b4327),_0x5937cd+=2);else{let f=c[s(891)][s(1085)+"e"]===Wg,p=e[s(214)](c.message[s(1085)+"e"],Ma);if(!f&&!p)return r();let y=e[s(951)](lr,c[s(891)][s(455)],e[s(164)]);if(!y)return e[s(1146)](r);let b=await Fl[s(687)](this,y);if(!b)return r();if(f){let w=await b[s(646)+"rs"](),O={frameType:w?.["frameType"],SeqID:he[s(1173)+"er"](this._seqId++),LogID:he[s(1173)+"er"](this[s(1513)][s(763)+s(554)]()),service:9e3,method:5,headers:w?.headers,payload:w?.payload},B=S(O);this[s(655)]&&this._ws[s(360)+"te"]&&this[s(655)][s(232)](B)}if(p){let w=c.message[s(571)];w&&b[s(1292)+"rs"](w)}}}let em=async function(c,r){let s=t;this[s(329)]=!1,e[s(565)](clearTimeout,this["_connect"+s(342)+s(803)]),e[s(638)](r)},tm=async function(c,r){let s=t,l={wdfVE:function(y,b,w){return e[j(541)](y,b,w)},suTFh:e.HPvHG};if(!this[s(655)]||e[s(423)](this[s(655)][s(360)+"te"],this[s(1451)]))return e[s(1546)](r);let{pingInterval:f}=this[s(1513)];this["_endpoin"+s(415)]?.["resetEnd"+s(446)+"fig"]();for(let y=0;e[s(1416)](y,this[s(845)+s(206)][s(1276)]);y++)if(e[s(549)](s(1519),s(632)))this[s(1428)](s(577),iOjjtm[s(533)](_0x1b0920,iOjjtm[s(1537)],{..._0x4374b8}));else{let b=this[s(845)+s(206)][y];if(e[s(761)](this[s(655)][s(360)+"te"],this[s(1451)])&&b!==null)this._ws&&this[s(655)][s(232)](b),this[s(845)+"Queue"][y]=null;else break}this[s(845)+s(206)]=this[s(845)+"Queue"].filter(y=>!!y),this._pingPongTimeoutId=e[s(732)](setTimeout,()=>this._ping(),f),this[s(1048)+s(203)+"nt"](c),this[s(1576)+"er"]&&this[s(655)]&&(this[s(655)][s(1446)+"pe"]=this[s(1447)+s(324)]);let p=this[s(628)+s(415)]?.[s(1391)+s(1257)+"nt"]();this._debug(s(1153)+p+s(964)),e[s(386)](r)},nm=async function(c,r){let s=t,l=this[s(628)+s(415)]?.[s(1391)+s(1257)+"nt"]();this[s(1283)](s(1153)+l),e[s(909)](r)};class rm extends Pa{constructor(r){let s=t,l={DFhiA:function(f,p,y,b){return f(p,y,b)},CHbSl:function(f,p,y){return e[j(988)](f,p,y)},nwnOp:s(863),xhglP:function(f,p){return e[s(1469)](f,p)},ACFgw:function(f,p){return e.Pporp(f,p)},aCIoP:e[s(645)],QlNPQ:s(540)+"e_success",wwXcL:function(f,p){return f===p},QusIx:function(f,p,y,b){return e[s(707)](f,p,y,b)},KjqwK:function(f,p,y){return f(p,y)},LWfFw:e.JrZOf,ESYrc:function(f,p,y){return e[s(546)](f,p,y)},LlnQo:function(f,p,y){return e[s(229)](f,p,y)},RJlBt:e[s(1184)],GWclm:function(f,p){return e[s(1408)](f,p)},xOTMd:function(f,p){return e[s(208)](f,p)},EUyVh:function(f,p,y){return e[s(952)](f,p,y)},FfVOF:function(f,p,y){return e.dNyYv(f,p,y)},SBEBd:function(f,p){return e.ZjwyZ(f,p)}};if(e[s(1104)]!==e[s(912)]){super(),this[s(871)+s(1359)+s(1181)]=!0,this[s(1576)+"er"]=dr,this._isNode=_g,this[s(1196)+"T"]=On,this._isMiniWX=ai,this[s(1202)+"r"]=ci,this[s(845)+s(206)]=[],this[s(628)+s(415)]=null,this[s(867)+s(1149)]=!1,this[s(1447)+s(324)]=s(1316)+"fer",this._connectLock=!1,this[s(419)+s(342)+s(803)]=null,this[s(1372)+s(862)+s(171)]=null,this[s(1063)+s(1597)+"Id"]=null,this._seqId=0,this[s(329)]=!1,this[s(812)]="",this["_QoSMana"+s(658)]=null,this[s(1388)+s(678)]=null,this[s(511)+s(319)]=null,this._protocols=s(251),this[s(664)]=3,this.CONNECTING=0,this.OPEN=1,this[s(1099)]=2,this[s(682)]=b=>{let w=s;try{l[w(808)](Rl,this,b,[em,tm,nm])}catch(O){let B=l[w(387)](lt,l[w(227)],{message:O[w(891)],code:cn[w(1486)+"OR"],error:O});this[w(1048)+"hErrorEvent"](B)}},this._onMessage=async b=>{let w=s,{pingInterval:O,pingFrequency:B}=this._options;if((l[w(1475)]("hi",b[w(998)])&&l.xhglP("always",B)||l[w(441)](l.aCIoP,B))&&(this[w(263)+"ngTimer"](),this[w(1428)](l[w(253)],w(1286)),this[w(1063)+"gTimeoutId"]=setTimeout(this[w(711)][w(456)](this),O)),!l.wwXcL("hi",b[w(998)]))try{l[w(287)](Rl,this,b,[Ng,Dg,Xg,Qg,Yg,Og])}catch(q){let Z=l[w(1015)](lt,w(863),{message:q[w(891)],code:cn[w(1234)+w(1435)],error:q});this[w(1048)+w(244)+w(1174)](Z)}},this[s(1493)]=b=>{let w=s,O={DsZnS:function(Z,$,ke){return l[j(387)](Z,$,ke)}},B=this["_endpoin"+w(415)]?.[w(1539)+"chMaxTries"](),q=this[w(628)+w(415)]?.[w(1391)+"ntEndpoint"]();if(B&&!b[w(891)])if(l.ACFgw("alPmx",l[w(790)])){let Z="connect "+q+(" fail, m"+w(876)+w(1534)+"ed");this[w(1048)+w(244)+w(1174)](l[w(1112)](lt,w(863),{message:Z,code:cn[w(816)+w(851)+"R"],error:b}));return}else CUytNm.DsZnS(_0x3d2d1b,_0x39e089,74),_0x446cfe(_0x5576b3,_0x3ed722);this._ws&&l[w(1380)](this._ws[w(360)+"te"],this[w(1451)])&&this[w(710)+w(1505)](),this[w(1048)+"hErrorEv"+w(1174)](l[w(293)](lt,l[w(227)],{message:b.message,code:cn[w(647)+w(1392)],error:b}))},this._onClose=async b=>{let w=s;this[w(610)+w(336)](),this[w(263)+w(1055)](),this["_removeW"+w(1087)+"rs"](),this[w(655)]=null,this["_connect"+w(363)]=!1;let O=this[w(628)+w(415)]?.[w(1539)+w(1236)+"es"]();if(!O&&this[w(1330)+w(367)]()&&!this["_readyCl"+w(1149)]){let B=this[w(628)+w(415)]?.["getCurre"+w(1257)+"nt"](),q=this[w(1513)][w(305)+w(401)+w(1275)](b[w(905)],b[w(737)]);this[w(1048)+w(969)+w(1174)](l[w(1112)](_t,l.RJlBt,{code:1006,reason:b[w(737)]||"connecti"+w(1140)+w(592)+w(1364)+w(1533)+w(746)+B,willReconnect:q})),q&&this._connect();return}if(l[w(580)](1e3,b[w(905)])&&this[w(867)+"osed"]){this[w(1048)+w(969)+w(1174)](l[w(387)](_t,w(577),{code:1e3,reason:w(1166)})),this[w(628)+w(415)]?.["resetEnd"+w(446)+w(311)](),this[w(511)+w(319)]?.[w(1329)+w(1524)]();return}if(l[w(318)](1e3,b[w(905)])&&O){let B=this[w(628)+"tManager"]?.[w(1391)+w(1257)+"nt"](),q=b.reason;q||(q=await kg(this[w(812)])),q=w(598)+w(1140)+w(747)+q+(w(542)+w(1049))+B+(w(823)+w(300)+w(753)),this[w(1048)+w(969)+"ent"](l[w(1015)](_t,w(577),{code:b[w(905)],reason:q}));let Z="connect "+B+(" fail, m"+w(876)+w(1534)+"ed");this[w(1048)+w(244)+w(1174)](l[w(1321)](lt,l[w(227)],{message:Z,code:cn[w(816)+w(851)+"R"]})),this[w(628)+w(415)]?.[w(460)+w(446)+"fig"](),this[w(511)+"sCounter"]?.[w(1329)+w(1524)]();return}if(l[w(580)](1e3,b[w(905)])&&!b.reason){let B=this[w(628)+w(415)]?.[w(1391)+"ntEndpoint"]();this[w(1048)+w(969)+w(1174)](l[w(915)](_t,l[w(882)],{code:b[w(905)],reason:"connecti"+w(1140)+w(592)+w(1364)+w(1533)+w(746)+B})),this[w(628)+w(415)]?.[w(460)+w(446)+"fig"](),this[w(511)+w(319)]?.[w(1329)+w(1524)]();return}this[w(1048)+w(969)+w(1174)](b),this[w(628)+w(415)]?.[w(460)+w(446)+"fig"](),this["_pingLos"+w(319)]?.["resetCou"+w(1524)]()},this[s(128)]=null,this[s(936)]=null,this[s(836)+"e"]=null,this[s(722)]=null,this["onStartR"+s(914)]=null,this[s(1194)+"eAck"]=null,this[s(212)+s(1310)+"yReconnect"]=null,this["_handleO"+s(944)]=this["_handleO"+s(944)][s(456)](this),this[s(362)+s(1209)]=this["_handleO"+s(1209)][s(456)](this),this["_handleP"+s(1072)]=this[s(962)+s(1072)][s(456)](this),this[s(962)+s(137)]=this[s(962)+s(137)].bind(this),this[s(1513)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e.irtAY(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(645)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1244)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:p}=r,y=Array[s(902)](f)?f:s(1289)==typeof f?[f]:[];if(!y||e[s(739)](0,y[s(1276)]))throw new Error(e[s(929)]);if(!Eg(p))throw new Error(s(995)+"rovide w"+s(783)+s(1568)+"ket cons"+s(624)+"is undef"+s(1207));Object[s(1518)](this[s(1513)],r),this["_endpoin"+s(415)]=new Pl(y,this[s(1513)][s(1215)+"es"]),this["_pingLos"+s(319)]=new Ig(this[s(1513)][s(439)+s(1361)]),this._options[s(1178)+s(1187)]&&(this[s(329)]=!0,this[s(419)]()),this[s(1513)]["listenNetworkCha"+s(332)]&&(this[s(1196)+"T"]||this._isMiniWX?this[s(1466)+"etWorkCh"+s(1255)]():this._isBrowser&&this[s(1432)+s(426)+s(819)]())}else{let f=_0x66d4c1[s(687)](gHrzBZ[s(604)](_0x3d6294,this),_0x46ae54,..._0x597721);return _0x5ddad7.set(f,_0x95c134[s(811)]?_0x1a5f09[s(811)]():[_0x5552f1]),gHrzBZ[s(604)](_0x240d84,f)}}[t(362)+"nLine"](){let r=t;this[r(1513)][r(939)+r(766)+r(271)]||this[r(867)+r(1149)]||this["_handleR"+r(914)]()}[t(362)+t(1209)](){let r=t;this[r(377)+"WebSocket"]();let s=Ca(e[r(770)],{message:e[r(648)]});this[r(212)+"mediatelyReconnect"]&&this[r(212)+r(1310)+r(796)+"ct"](s)}[t(1432)+t(426)+t(819)](){let r=t;this[r(1576)+"er"]&&window[r(1164)+r(819)](e[r(182)],this[r(362)+"nLine"]),this[r(1576)+"er"]&&window[r(1164)+r(819)](e[r(301)],this["_handleO"+r(1209)]),this._isBrowser&&window[r(1164)+r(819)](e[r(1386)],this[r(962)+r(1072)]),this._isBrowser&&window[r(1164)+r(819)](e.IogZp,this[r(962)+"ageShow"])}[t(1081)+t(426)+"Listener"](){let r=t;this[r(1576)+"er"]&&window[r(1531)+"entListe"+r(1409)](e[r(182)],this[r(362)+"nLine"]),this[r(1576)+"er"]&&window[r(1531)+r(696)+r(1409)](e[r(301)],this["_handleO"+r(1209)]),this._isBrowser&&window[r(1531)+r(696)+r(1409)](e.QQOaD,this["_handleP"+r(1072)]),this[r(1576)+"er"]&&window[r(1531)+r(696)+r(1409)](e[r(350)],this[r(962)+r(137)])}_handlePageHide(r){let s=t;!r.persisted&&(this._isBrowser&&window[s(1531)+s(696)+"ner"](e[s(1386)],this._handlePageHide),this[s(1576)+"er"]&&window[s(1531)+s(696)+"ner"](s(442),this["_handleP"+s(137)]),this[s(577)]()),this._isBrowser&&window[s(1531)+s(696)+"ner"](s(1050),this[s(362)+"nLine"]),this._isBrowser&&window[s(1531)+s(696)+"ner"](e[s(301)],this["_handleO"+s(1209)])}[t(962)+t(137)](r){let s=t;r.persisted&&(this[s(1330)+"orOnline"]()&&(!this._ws||e[s(424)](this[s(655)][s(360)+"te"],this[s(1451)])||e[s(894)](this._ws[s(360)+"te"],this[s(843)+"NG"]))&&this[s(362)+s(944)](),this[s(1576)+"er"]&&window[s(1164)+s(819)](e[s(182)],this[s(362)+s(944)]),this[s(1576)+"er"]&&window[s(1164)+s(819)]("offline",this[s(362)+"ffLine"]))}async[t(1118)+t(1227)](r){let s=t;if(e[s(1408)](e[s(987)],e[s(987)]))return _0x3b7cf5[s(279)](e[s(1423)],_0x428527,_0x1ad69d,_0x502c15),this._qosDB[s(1094)]({cursor_name:_0x57e95c,cursor:_0x3009d2,service:_0x162bf2});{let{fpID:l,deviceID:f,bddID:p,ttwID:y,accessKey:b,aID:w,customParams:O={},enableAutoAck:B,enableQoS:q,QoSLevel:Z,env:$}=this[s(1513)],ke,Pe,ln;this._isBrowser||this[s(560)+"X"]||this[s(1196)+"T"]?(ke=location&&e.JbmPK(e[s(1145)],location.protocol)?e[s(1561)]:e[s(157)],Pe=r[s(910)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),ln=/^wss(.*:\/\/)/[s(1159)](r)?r:""+ke+Pe):(ke=e.tZRtr,Pe=r[s(910)](/(^http)((?:[s]*:\/\/))/,""),ln=/(^ws)((?:[s]*:\/\/))/[s(1159)](Pe)?Pe:""+ke+Pe);let zl=p?e[s(574)]:y?e.kQRlu:e.SfKki,Ul=p||y||f;if(e.rlXsm(!Ul,!zl))throw new Error(s(995)+s(600)+s(703)+"viceID o"+s(551));let im=e[s(1233)](s(422),typeof O)?await e[s(1546)](O):O,sm=$?e.xMMRt(Sg,$[s(791)],$[s(825)]):{},Ba=Object[s(1518)]({device_platform:e.TTaRn,version_code:e[s(1280)],access_key:b,fpid:l,aid:w,[zl]:Ul,xsack:B?1:0,xaack:B?1:0,xsqos:q?1:0,qos_level:q?Z:void 0,qos_sdk_version:2,...sm},im),om=Object.keys(Ba)[s(245)]((Fa,za)=>Ba[za]!==void 0?""+Fa+(Fa?"&":"?")+za+"="+Ba[za]:Fa,"");return ln+s(1571)+om}}async[t(419)](){let r=t,s={HQUGF:function(l,f){return l(f)},HxhnD:function(l,f){return e[j(651)](l,f)},jCDWn:function(l){return e[j(597)](l)},bHoWc:function(l){return e[j(1009)](l)},FKAyi:e[r(1102)],kcyfu:"error"};if(!(this[r(419)+r(363)]||this[r(867)+"osed"])){this[r(419)+r(363)]=!0;try{let l=this["_endpoin"+r(415)]?.[r(1248)+r(1156)+r(1124)+r(1397)+r(1130)](),{timeoutInterval:f}=this._options;if(l){let y=this[r(628)+r(415)]?.["getCurre"+r(1257)+"nt"](),b=this[r(628)+"tManager"]?.["replaceB"+r(1462)+r(1437)+"UpdateCo"+r(425)](),w=this[r(628)+r(415)]?.[r(1391)+r(1257)+r(674)+"ount"]();if(b){if(e[r(361)](r(430),r(430)))return r(627)+"_"+this._DBName;{let O=r(1398)+y+(r(1521)+r(823)+r(300)+r(1516)+r(801)+r(868)+r(1337))+b+(r(618)+"y"),B=e.JFrVo(lt,r(863),{message:O,code:cn[r(816)+r(851)+"R"]});this[r(1283)](O),this[r(1048)+r(244)+r(1174)](B),this[r(812)]=await this[r(1118)+r(1227)](b),this[r(1283)]("connect "+b+" "+w+" times"),this[r(224)+r(1087)+"rs"]()}}else{if(e[r(1468)](e[r(1405)],r(840)))return _0x456a2c(_0x391c36);{let O=r(1398)+y+(r(1521)+r(823)+r(300)+r(753));this[r(1283)](O),this[r(1048)+r(244)+r(1174)](lt(e[r(1563)],{message:O,code:cn[r(816)+r(851)+"R"]}));return}}}else{let y=this["_endpoin"+r(415)]?.["getCurre"+r(1257)+r(1512)+"ateCount"](),b=this["_endpoin"+r(415)]?.[r(1391)+"ntEndpoi"+r(674)+r(476)]();this[r(812)]=await this[r(1118)+r(1227)](e.kYVxj(y,"")),this[r(1283)]("connect "+y+" "+b+r(374)),this[r(224)+r(1087)+"rs"]()}if(this[r(329)])this[r(329)]=!1;else{let y=Ca(e[r(770)],{message:e.iQDwG});this[r(593)+"econnect"]&&this[r(593)+r(914)](y)}let p=this["_endpoin"+r(415)]?.[r(1391)+r(1257)+"ntTriesCount"]()||0;e[r(378)](p,1)&&await this[r(1195)](e[r(567)](p,1)),this._debug("connecting url: "+this._url+(r(1095)+r(1590))+this._protocols),this._ws=e[r(605)](bg,{url:this._url,protocols:[this[r(1182)+"ls"]],headers:this[r(1513)][r(326)+"ramParams"][r(545)+r(705)]},this[r(1513)].ws),(this[r(1576)+"er"]||this[r(1202)+"r"])&&this[r(655)]&&(this[r(655)].binaryType=this["_binaryT"+r(324)]),this[r(1314)+r(483)](),this["_connect"+r(342)+r(803)]=setTimeout(this[r(384)+"ut"][r(456)](this),f)}catch(l){if(r(1260)===r(637)){let f=()=>{let b=r;_0x3fe860[b(1531)+b(696)+"ner"]("success",p),_0x3eb440[b(1531)+"entListe"+b(1409)](b(863),y)},p=()=>{let b=r;qZJrtB[b(844)](_0x249561,qZJrtB.HxhnD(_0x4245b5,_0x75437b[b(1560)])),qZJrtB.jCDWn(f)},y=()=>{let b=r;_0x4754a6(_0x36aa58.error),qZJrtB[b(806)](f)};_0x418e09[r(1164)+r(819)](qZJrtB.FKAyi,p),_0x219b37[r(1164)+r(819)](qZJrtB[r(418)],y)}else throw this[r(419)+"Lock"]=!1,l}}}["_clearTi"+t(336)](){let r=t;e[r(1427)](clearTimeout,this[r(419)+r(342)+r(803)]),this[r(419)+r(342)+r(803)]=null}[t(263)+t(1055)](){let r=t;clearTimeout(this[r(1063)+"gTimeoutId"]),e.LiovQ(clearTimeout,this["_reconne"+r(862)+"tId"]),this[r(1063)+r(1597)+"Id"]=null,this[r(1372)+"ctTimeou"+r(171)]=null}[t(1283)](...r){let s=t;this._options[s(793)]&&console.log.apply(console,[e.WmvYk,...r])}[t(832)+t(842)+"e"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:p}=this._options,y=l*Math[s(1147)](p,e[s(1593)](r,1));return e.PFNkS(y,f)?f:y}_ping(){let r=t;if(this._ws&&e[r(349)](this._ws[r(360)+"te"],this[r(843)+"NG"]))if(e.nOzTH(e[r(1025)],e.NwavB)){let s=this._qosDB["getStora"+r(656)+"nc"](this[r(809)]),l=_0x1c1acb[r(1029)](s||"{}");return _0x29ce58[r(1489)](l)}else{this[r(263)+r(1055)](),this[r(1063)+r(1597)+"Id"]=setTimeout(this[r(711)].bind(this),this._options["pingInte"+r(897)]);return}if(!this[r(655)]||e.CElbH(this[r(655)][r(360)+"te"],this[r(1451)]))return void this[r(676)+r(914)]();this._ws&&this[r(655)][r(232)]("hi"),this[r(1372)+r(862)+r(171)]=e.VVxeH(setTimeout,this[r(676)+r(914)+r(873)][r(456)](this),this[r(1513)][r(1377)+"outInter"+r(277)])}[t(676)+t(914)+"Timeout"](){let r=t;this[r(511)+r(319)]?.addCount(),this.emit(e.Mkvia,e[r(147)]),this[r(511)+"sCounter"]?.[r(1539)+r(270)+"nt"]()?this[r(676)+"econnect"]():this[r(711)]()}[t(1330)+t(367)](){let r=t;if(e[r(1395)]("HUFZD",e[r(1540)]))return this[r(1196)+"T"]||this[r(560)+"X"]?this["_miniNav"+r(1359)+"line"]:(this[r(1576)+"er"]||this[r(1202)+"r"])&&this[r(1513)][r(1544)+r(583)+"nged"]?navigator[r(354)]:!0;e[r(1006)](_0x3faf70,this[r(1478)+r(1039)+"Id"]),this[r(1478)+r(1039)+"Id"]=_0x2d8b2a(()=>{this["flushExp"+r(1027)]()},this[r(1478)+"l"])}[t(676)+"econnect"](){let r=t;!this[r(1330)+r(367)]()||this[r(867)+r(1149)]||(this[r(628)+r(415)]?.[r(460)+r(446)+"fig"](),this["_pingLos"+r(319)]?.[r(1329)+"nter"](),this[r(655)]?this[r(710)+"ect"](1001,e.JtWBJ,!0):this[r(419)]())}[t(1466)+t(1306)+t(1255)](){let r=t;if(e[r(1267)]("BMMKF","CShrG"))this[r(1196)+"T"]?tt[r(1542)+r(1043)+r(1492)](({isConnected:s})=>{let l=r;this[l(871)+l(1359)+l(1181)]=s,s?this["_handleO"+l(944)]():this[l(362)+l(1209)]()}):this._isMiniWX&&wx[r(1542)+"kStatusC"+r(1492)](({isConnected:s})=>{let l=r;this[l(871)+l(1359)+"line"]=s,s?this[l(362)+l(944)]():this["_handleO"+l(1209)]()});else{if(e[r(1480)](e.AkGIx,typeof _0x448067)){let s=new _0x8e3cd6(e[r(1426)](_0x42deaa,_0x2b7134));return e[r(177)](_0x57fee4,_0x50deaf,s,0),s}return e[r(1154)](_0x2fe53c,_0x54e477)?new _0x5be16a(_0x4bd669):new _0x2f4684(_0x4e9a22[r(689)],_0x4674f0[r(883)+"et"],_0xd3de20[r(886)+"th"])}}[t(1195)](r){return new Promise(s=>{let l=j;setTimeout(s,this[l(832)+l(842)+"e"](r))})}["_disconn"+t(1505)](r=1e3,s="",l=!1){let f=t,p={CbRDO:function(y,b,w){return e[j(1476)](y,b,w)},Ttiwn:function(y,b){return y===b},Jzpes:e[f(1563)]};if(e[f(761)](e[f(1252)],f(315))){let y=this[f(628)+f(415)]?.[f(1539)+f(1236)+"es"](),b=this["_endpoin"+f(415)]?.["getCurre"+f(1257)+"nt"]();if(y&&!_0x50ef74[f(891)]){let w=f(1398)+b+(f(720)+"ax retri"+f(1534)+"ed");this[f(1048)+"hErrorEvent"](hbvDUw[f(1053)](_0x22935d,f(863),{message:w,code:_0x27e283[f(816)+f(851)+"R"],error:_0x5d5f61}));return}this[f(655)]&&hbvDUw[f(1400)](this[f(655)][f(360)+"te"],this[f(1451)])&&this[f(710)+"ect"](),this["_dispatc"+f(244)+f(1174)](hbvDUw.CbRDO(_0x18fdc7,hbvDUw[f(892)],{message:_0x2beed9[f(891)],code:_0x31acf2["NATIVE_E"+f(1392)],error:_0x53ebdb}))}else{if(!this._ws)return;this["_destroy"+f(1299)+"t"](r,s,l)}}[t(384)+"ut"](){let r=t,s={uDNhp:function(l,f){return e.sUmyP(l,f)}};if(e[r(644)](e[r(1044)],e[r(1044)])){let l=this[r(628)+"tManager"]?.[r(1391)+r(1257)+"nt"]();this[r(1283)]("connect "+l+r(1521)),this[r(710)+r(1505)](1001,e[r(1128)],!0)}else return function(l,...f){let p=r,y=_0x447b8a[p(687)](AJGPoe[p(1219)](_0x72aa62,this),l,...f);return _0xfd125f[p(1094)](y,l[p(811)]?l[p(811)]():[l]),AJGPoe[p(1219)](_0x1a4f88,y)}}[t(1373)](r){let s=t,l=e[s(235)](Ht,r);this[s(655)]&&this[s(655)].readyState===this[s(1451)]&&(this._ws&&this[s(655)][s(232)](l),this[s(1283)]("send_ack",r))}[t(224)+"sListeners"](){let r=t,s={OcZMm:function(l,f){return e[j(168)](l,f)},NOney:function(l,f){return l+f}};if(e[r(423)](e.GlcVE,e[r(322)])){if(_0x54296e<=-_0x50ba08)return _0x30dcd4;if(AKqsvQ[r(1061)](AKqsvQ.NOney(_0x269702,1),_0x5644d5))return _0x4bf518}else{if(!this._ws)return;this[r(655)][r(1531)+"entListe"+r(1409)](e[r(795)],this[r(682)]),this[r(655)][r(1531)+r(696)+"ner"](e.HPvHG,this._onClose),this._ws[r(1531)+r(696)+"ner"](e[r(1071)],this[r(1191)+"ge"]),this[r(655)][r(1531)+r(696)+"ner"](e[r(1563)],this[r(1493)])}}[t(1314)+t(483)](){let r=t,s=e[r(1434)][r(690)]("|"),l=0;for(;;){switch(s[l++]){case"0":this._ws[r(1164)+r(819)](e[r(1563)],this[r(1493)]);continue;case"1":this._ws[r(1164)+r(819)](e[r(795)],this[r(682)]);continue;case"2":this[r(655)]["addEvent"+r(819)](e[r(1071)],this[r(1191)+"ge"]);continue;case"3":if(!this[r(655)])return;continue;case"4":this[r(655)][r(1164)+r(819)](e[r(1184)],this[r(1333)]);continue}break}}[t(1365)+"nceClose"](r=1e3,s=""){let l=t;try{this[l(655)]&&this[l(655)][l(577)](r,s)}catch{}}[t(377)+"WebSocket"](r=1e3,s="",l=!1){let f=t,p={ftqVg:function(y,b){return y(b)}};if(this[f(263)+"ngTimer"](),this[f(610)+f(336)](),this["_removeW"+f(1087)+"rs"](),this[f(1365)+"nceClose"](1e3,s),this["_connect"+f(363)]=!1,l&&this._navigatorOnline()&&!this["_readyCl"+f(1149)]){if(this[f(628)+f(415)]?.["checkRea"+f(1236)+"es"]())if(e.RwYRG(e[f(626)],e.ACvuA))jaemru[f(482)](_0x126a1a,_0x1b20f7[f(863)]),_0x123947();else{let b=this._endpointManager?.[f(1391)+f(1257)+"nt"]();this[f(1048)+f(969)+f(1174)](e[f(1e3)](_t,e[f(1184)],{code:1006,reason:f(1398)+b+(f(1521)+f(823)+f(300)+f(753)),wasClean:!0}))}else{let b=this[f(1513)]["reconnec"+f(401)+f(1275)](r,s);this["_dispatc"+f(969)+f(1174)](e[f(464)](_t,e.HPvHG,{code:r,reason:s,wasClean:!0,willReconnect:b})),b&&this[f(419)]()}return}this[f(1330)+f(367)]()||this[f(867)+f(1149)]?this[f(1048)+f(969)+f(1174)](e.KqrXM(_t,"close",{code:r,reason:e[f(738)]})):this[f(1048)+f(969)+f(1174)](e[f(192)](_t,e[f(1184)],{code:1006,reason:e[f(1032)]})),this[f(655)]=null,this[f(628)+"tManager"]?.["resetEndpointCon"+f(311)](),this["_pingLos"+f(319)]?.[f(1329)+f(1524)]()}[t(1048)+t(203)+"nt"](r){let s=t;this[s(1428)](e.xpeEQ,r),this[s(722)]&&this.onopen(r)}[t(1048)+t(303)+t(1278)](r){let s=t;this[s(1428)](e[s(1071)],r),this[s(836)+"e"]&&this.onmessage(r)}[t(1048)+t(1062)+"ageEvent"](r){let s=t;this[s(1428)](e[s(392)],r),this[s(1194)+s(679)]&&this.onReceiveAck(r)}[t(1048)+t(244)+"ent"](r){let s=t;this.emit(s(863),r),this[s(936)]&&this.onerror(r)}["_dispatc"+t(969)+t(1174)](r){let s=t;this[s(1428)](e[s(1184)],r),this[s(128)]&&this[s(128)](r)}get[t(1446)+"pe"](){let r=t;return this[r(655)]?this._ws.binaryType:this[r(1447)+r(324)]}set binaryType(r){let s=t;this[s(1447)+"ype"]=r,this._ws&&(this._ws.binaryType=r)}get[t(280)+"nt"](){let r=t;return this[r(628)+"tManager"]?.["getCurrentEndpoi"+r(674)+r(476)]()||0}get["buffered"+t(537)](){let r=t;if(e[r(1141)](e[r(398)],e[r(398)])){let s=this._messageQueue[r(245)]((l,f)=>(l+=f&&f[r(886)+"th"]||0,l),0);return e.oUxvD(s,this._ws?this._ws["buffered"+r(537)]:0)}else return this._qosDB?.[r(1058)](_0xeff592)}get[t(1057)+"ns"](){let r=t;return this[r(655)]?this[r(655)][r(1057)+"ns"]:""}get[t(492)](){let r=t;return this._ws?this[r(655)][r(492)]:""}get readyState(){let r=t;return this[r(655)]?this[r(655)][r(360)+"te"]:this[r(1513)]["automati"+r(1187)]?this[r(843)+"NG"]:this[r(664)]}get[t(452)](){let r=t;return this[r(655)]?this[r(655)].url:this[r(812)]}close(r=1e3,s){let l=t,f=(l(512)+l(1185)).split("|"),p=0;for(;;){switch(f[p++]){case"0":if(e.NJGGs(this[l(655)][l(360)+"te"],this[l(664)])||e[l(191)](this._ws[l(360)+"te"],this[l(1099)]))return void this._debug(e.vVdyj);continue;case"1":this[l(377)+l(1299)+"t"](r,s);continue;case"2":this[l(1081)+l(426)+l(819)]();continue;case"3":this["_clearPi"+l(1055)]();continue;case"4":this[l(867)+l(1149)]=!0;continue;case"5":this[l(1059)+l(658)]?.[l(369)]();continue;case"6":this[l(610)+"mer"]();continue;case"7":if(!this._ws)return void this[l(1283)](l(1250)+"s instan"+l(122)+l(396)+"ed");continue}break}}async[t(232)](r,s){let l=t;if(e[l(1018)](null,r))throw new Error(e[l(736)]);e[l(1584)](e.PmZUm,typeof r)&&(r=JSON[l(1100)+"y"](r)),l(1289)!=typeof r&&!e.PdRVk(r,ArrayBuffer)&&!(r[l(689)]&&e[l(1452)](r[l(689)],ArrayBuffer))&&(r=JSON[l(1100)+"y"](r));let f=await e.ZuYfN(Nl,r),p=e[l(1368)](vg,r),{method:y=0,service:b=this._options[l(145)],logID:w=this[l(1513)][l(763)+l(554)](),headers:O=this._options[l(455)],payloadEncoding:B=this._options[l(1445)+l(368)],payloadType:q=this._options[l(1214)+l(324)],logIDNew:Z=this[l(1513)][l(1013)+"Config"]["enableAu"+l(286)+l(294)+"ew"]?e.JthUz(i,this._options[l(1013)+l(1116)].userIp):""}=s||{};if(!b)throw new Error(e[l(1119)]);let $={SeqID:he[l(1173)+"er"](this[l(1237)]++),LogID:he[l(1173)+"er"](w),service:b,method:y,headers:O,payloadEncoding:B instanceof Object?B[l(730)]?B[l(730)]:"":B,payloadType:e[l(1349)](q,Object)?q.type?q[l(273)]:p:q||p,payload:f,LogIDNew:Z},ke=e.syGPQ(Ht,$);if(this._ws&&this[l(655)].readyState===this[l(1451)])this[l(655)]&&this[l(655)][l(232)](ke),this[l(1283)](e[l(507)],$);else if(this[l(845)+"Queue"][l(1276)]<this[l(1513)][l(433)+l(1167)+l(438)])if(e[l(1440)](e.UVJBL,l(570)))this[l(845)+l(206)][l(402)](ke),this[l(1283)](e[l(1338)],$);else return this._qosDB?.set({message_id:_0x4cf1c7,timestamp:_0x58ad9a});else this[l(845)+l(206)].shift(),this["_message"+l(206)][l(402)](ke);return{seqID:this[l(1237)],logID:w,logIDNew:Z}}async[t(305)+"t"](r){let s=t,{url:l}=e[s(375)](r,{}),f=Array[s(902)](l)?l:e[s(202)]("string",typeof l)?[l]:[];r&&Object[s(1518)](this[s(1513)],r),f&&f[s(1276)]?this[s(628)+s(415)]=new Pl(f,this[s(1513)][s(1215)+"es"]):this["_endpoin"+s(415)]?.["resetEnd"+s(446)+"fig"](),this["_pingLos"+s(319)]?.[s(1329)+s(1524)](this[s(1513)]["pingLoss"+s(1361)]),this[s(867)+"osed"]=!1,this._ws&&e[s(151)](this[s(655)][s(360)+"te"],this[s(664)])?this[s(710)+s(1505)](1e3,e[s(1355)],!0):(this._isInit=!0,this[s(419)]())}async[t(1090)](){let r=t;if(!this[r(419)+r(363)]){let s=e.wbQEr[r(690)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(511)+"sCounter"]?.["resetCou"+r(1524)]();continue;case"1":this[r(628)+"tManager"]?.["resetEnd"+r(446)+r(311)]();continue;case"2":this[r(329)]=!0;continue;case"3":this._connect();continue;case"4":this[r(867)+r(1149)]=!1;continue}break}}}addEventListener(r,s){this.on(r,s)}[t(700)+t(1278)](r){let s=t,{type:l}=r;this[s(1428)](l,r)}[t(1531)+t(696)+t(1409)](r,s){let l=t;if(e.UcIzI(e.jdwIE,l(1161)))this.off(r,s);else try{return e[l(1418)](e[l(451)],typeof _0x3c00c3)&&(e[l(219)](_0x56664a,_0x328df1)||_0x15be36[l(689)]&&e[l(762)](_0xa0b631[l(689)],_0xcdd910))||e.AkGIx!=typeof _0x50b4d?"":(_0x45746c[l(1029)](_0x1bb3a1),l(221)+l(184))}catch{return e[l(451)]==typeof _0x2585a7?e[l(1232)]:""}}[t(1017)](){let r=t,s={EWkEO:function(l,f){return e.syGPQ(l,f)},GeTHe:r(540)+"e_success",JMhpN:e[r(1241)],jGOUh:e[r(147)]};return new Promise((l,f)=>{let p=r;this[p(263)+p(1055)](),this[p(1063)+"gTimeoutId"]=e[p(204)](setTimeout,this[p(711)][p(456)](this),this[p(1513)][p(295)+"rval"]);let y=()=>{let w=p;s[w(518)](l,w(1286)),this[w(634)](s[w(1064)],y),this[w(634)](s[w(477)],b)},b=()=>{let w=p;s.EWkEO(f,s[w(1336)]),this[w(634)](s[w(1064)],y),this[w(634)](s[w(477)],b)};this.on(p(540)+p(347)+"s",y),this.on(e[p(1241)],b),this[p(711)]()})}}})(),ze["CustomCl"+L(138)]=Oe.CustomCloseEvent,ze.CustomErrorEvent=Oe[L(220)+L(629)],ze[L(1376)+"e"]=Oe[L(1376)+"e"],ze[L(1278)]=Oe[L(1278)],ze[L(620)]=Oe[L(620)],ze["Frontier"+L(160)+L(321)]=Oe[L(788)+L(160)+L(321)],ze["MessageE"+L(321)]=Oe[L(160)+L(321)],ze.OpenEvent=Oe[L(188)+"t"],ze[L(1332)+L(1008)]=Oe[L(1332)+"tEvent"],ze[L(579)+"oseEvent"]=Oe.createCloseEvent,ze[L(1555)+"rorEvent"]=Oe[L(1555)+L(629)],ze[L(1110)+"ssageEvent"]=Oe[L(1110)+L(429)+"nt"],ze.createOpenEvent=Oe["createOp"+L(827)],ze["createRe"+L(437)+L(321)]=Oe[L(504)+L(437)+L(321)],ze[L(399)+"rame"]=Oe[L(399)+"rame"],ze[L(1206)+L(1199)]=Oe[L(1206)+L(1199)];for(oa in Oe)[L(389)+L(138),L(220)+L(629),L(1376)+"e",L(1278),L(620),L(788)+L(160)+"vent",L(160)+L(321),L(188)+"t",L(1332)+L(1008),"createCl"+L(138),"createEr"+L(629),"createMessageEvent",L(1208)+L(827),L(504)+"connectEvent",L(399)+L(180),L(1206)+"ame"][L(1023)](oa)===-1&&(ze[oa]=Oe[oa]);var oa;Object[L(167)+L(893)](ze,L(913)+"le",{value:!0})});import{existsSync as Y1,openSync as X1}from"node:fs";import{mkdir as Q1}from"node:fs/promises";import{dirname as eI}from"node:path";import{fileURLToPath as tI}from"node:url";function rI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function cl(t=V()){return Y1(t.libEntry)?t.libEntry:tI(new URL("../index.ts",import.meta.url))}async function Pp(t={}){let e=t.paths??V(),n=t.entryOverride??cl(e),i=rI(e,process.env.COZE_BRIDGE_LOG_MODE);await Q1(eI(i),{recursive:!0});let o=X1(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=st(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[hs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return nI.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var nI,hs,ma=nt(()=>{"use strict";Yt();te();Ae();nI=U("spawn-daemon"),hs="COZE_BRIDGE_DAEMON"});import{spawn as e2}from"node:child_process";import{mkdir as t2,unlink as n2,writeFile as r2}from"node:fs/promises";import{dirname as i2,join as s2}from"node:path";function ii(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function o2(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${ii(n)}</key>
|
|
21
|
-
<string>${
|
|
20
|
+
`+n)}function or(t,e,n,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,or),t.emit("wsClientError",d,n,e)}else ls(n,i,o,a)}});var wp=de(Ce=>{"use strict";var L=B;(function(t,e){let n=B,i=t();for(;;)try{if(-parseInt(n(725))/1*(-parseInt(n(1743))/2)+parseInt(n(1641))/3*(parseInt(n(409))/4)+parseInt(n(1854))/5*(parseInt(n(1582))/6)+parseInt(n(1596))/7+parseInt(n(1726))/8+parseInt(n(1519))/9*(parseInt(n(476))/10)+-parseInt(n(1528))/11===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(xa,238802);var m1=Object["definePr"+L(933)],w1=Object[L(952)+L(939)+L(1287)],hp=(t,e)=>function(){return t&&(e=(0,t[w1(t)[0]])(t=0)),e},_1=(t,e)=>{let n={hrSON:function(o,a,d,u){return o(a,d,u)}};for(var i in e)n.hrSON(m1,t,i,{get:e[i],enumerable:!0})};function y1(){return cp||(cp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function b1(){let t=L;return dp||(dp=[IDBCursor.prototype[t(972)],IDBCursor[t(875)+"e"].continue,IDBCursor.prototype["continue"+t(720)+"ey"]])}function E1(t){let e=L,n={yadPC:e(443),ICJac:"error",jMGRr:function(o,a){return o!==a},bWQNO:e(1193),jmbTo:function(o,a){return o(a)},JMDCn:function(o){return o()},MJVyJ:function(o,a){return o|a},YOZis:function(o,a){return o&a},guqRf:function(o,a){return o>>a},QjEMe:function(o,a){return o(a)},aZdTx:function(o,a){return o===a},hJdjm:e(1553),miTWF:function(o,a){return o instanceof a}},i=new Promise((o,a)=>{let d=e,u={fFOct:function(m,v){return n[B(1749)](m,v)},HRRiW:function(m,v){return m&v},lDZnW:function(m,v){return n[B(1749)](m,v)},BjCdV:function(m,v){return n[B(1428)](m,v)},scFpB:function(m,v){return n[B(496)](m,v)},WgIAi:function(m,v){return n[B(1428)](m,v)},VuDmZ:function(m,v){return m+v},StUcu:function(m,v){return m+v},kgfcb:function(m,v){return m<<v},nkXjn:function(m,v){return n.QjEMe(m,v)},NYVtv:function(m){return n.JMDCn(m)}},f=()=>{let m=B;t[m(1550)+m(1436)+"ner"](n[m(1138)],x),t[m(1550)+m(1436)+"ner"](n[m(1458)],p)},x=()=>{let m=B;if(n.jMGRr("sRGpJ",n[m(1844)])){let v=(m(736)+"3|0").split("|"),_=0;for(;;){switch(v[_++]){case"0":_0x268e70[_0x54ae72++]=u[m(400)](u[m(970)](63,_0x2160a6),128);continue;case"1":_0x1024c1[_0x21badc++]=u.lDZnW(u[m(1518)](u[m(499)](_0x36b4d0,12),63),128);continue;case"2":++_0x502a47;continue;case"3":_0x237382[_0x10ee95++]=u[m(400)](u[m(1565)](_0x5295ac>>6,63),128);continue;case"4":_0x14fea1[_0x46049c++]=u[m(1150)](u.scFpB(_0x23dfa0,18),240);continue;case"5":_0x361025=u[m(1488)](u[m(1744)](65536,u.kgfcb(u.WgIAi(1023,_0x46fec6),10)),1023&_0x43e320);continue}break}}else n[m(1705)](o,n.jmbTo(qt,t[m(762)])),n[m(734)](f)},p=()=>{let m=B;u[m(1007)](a,t[m(749)]),u.NYVtv(f)};t["addEvent"+d(1810)](n[d(1138)],x),t[d(1323)+d(1810)](n[d(1458)],p)});return i[e(1663)](o=>{let a=e;if(n[a(907)](n[a(501)],a(1827)))return!!_0x478832?.[a(1457)](d=>d[a(1484)]===_0x598226&&d.value===_0x398c70);n[a(1487)](o,IDBCursor)&&sl[a(598)](o,t)})[e(660)](()=>{}),fa[e(598)](i,t),i}function v1(t){let e=L,n={ciUQJ:e(749),EhvXc:e(1575),CsKHN:function(o){return o()},rcYFz:"complete"};if(ua[e(1106)](t))return;let i=new Promise((o,a)=>{let d=e,u={yOiKV:function(m,v){return m(v)},iTuZU:d(613)+"or"},f=()=>{let m=d;t[m(1550)+m(1436)+"ner"](m(508),x),t[m(1550)+m(1436)+m(871)](n[m(1736)],p),t[m(1550)+m(1436)+m(871)](n.EhvXc,p)},x=()=>{let m=d;o(),n[m(1580)](f)},p=()=>{let m=d;u[m(865)](a,t[m(749)]||new DOMException(m(613)+"or",u[m(850)])),f()};t[d(1323)+d(1810)](n[d(1097)],x),t.addEventListener(n[d(1736)],p),t[d(1323)+d(1810)]("abort",p)});ua[e(598)](t,i)}function S1(t){ha={DTVYR:function(i,o){return i(o)}}[L(500)](t,ha)}function I1(t){let e=L,n={ZkrLB:function(i,o){return i(o)},SiNoC:function(i,o){return i(o)},jcvBP:function(i,o){return i(o)},FVTRl:function(i,o){return i(o)},TGhXo:function(i,o){return i===o},oIedZ:function(i,o){return i in o},aIxem:function(i,o){return i===o},gekGa:e(1128),noqEq:"ywEyB",nISkQ:function(i){return i()}};return n.TGhXo(t,IDBDatabase[e(875)+"e"]["transact"+e(1729)])&&!n[e(539)](e(1218)+e(815),IDBTransaction[e(875)+"e"])?n[e(713)](n[e(1203)],n[e(1717)])?_0xe7dc9a["objectSt"+e(815)]||_0x13bbb4[e(493)](_0x19118b):function(i,...o){let a=e,d=t[a(444)](n[a(1185)](us,this),i,...o);return il.set(d,i[a(874)]?i[a(874)]():[i]),n[a(790)](qt,d)}:n[e(1475)](b1).includes(t)?function(...i){let o=e;return t[o(662)](n[o(732)](us,this),i),n[o(732)](qt,sl[o(493)](this))}:function(...i){let o=e;return qt(t[o(662)](n[o(1209)](us,this),i))}}function A1(t){let e=L,n={Uitqb:function(i,o){return i===o},afDPP:function(i,o){return i(o)},QflQX:function(i,o,a){return i(o,a)}};return n.Uitqb(typeof t,e(1115))?n[e(1024)](I1,t):(t instanceof IDBTransaction&&n[e(1024)](v1,t),n[e(1186)](xp,t,y1())?new Proxy(t,ha):t)}function qt(t){let e=L,n={ScWOz:function(o,a){return o instanceof a},qJkxo:function(o,a){return o(a)}};if(n[e(668)](t,IDBRequest))return n.qJkxo(E1,t);if(da.has(t))return da[e(493)](t);let i=n.qJkxo(A1,t);return i!==t&&(da.set(t,i),fa[e(598)](i,t)),i}var xp,cp,dp,sl,ua,il,da,fa,ha,us,lp=hp({"node_modules/idb/build/wrap-idb-value.js"(){let t=L,e={rgxYu:t(443),DVaDX:t(948)+t(557)+"s",ArGIA:t(948)+t(1304)+"t",AuGZK:function(n,i){return n===i},vntll:t(1472),UYnYV:function(n,i){return n instanceof i},wycrl:function(n,i){return n===i},MYpXm:t(1094),tEFHr:function(n,i){return n===i},ycSEd:t(1218)+t(815),VxLSY:t(532),fdUFn:function(n,i){return n(i)},FvcLx:function(n,i){return n>i},KiYBI:function(n,i){return n!==i},qBxmT:t(583)};xp=(n,i)=>i[t(1507)](o=>n instanceof o),sl=new WeakMap,ua=new WeakMap,il=new WeakMap,da=new WeakMap,fa=new WeakMap,ha={get(n,i,o){let a=t,d={aVPiy:e[a(1297)],VVksm:e.ArGIA};if(e.AuGZK(e[a(688)],a(849))){let u={WyRKk:e[a(505)],Irhcn:e[a(1297)]};return new _0x34cf4a((f,x)=>{let p=a,m={JdJJv:function(b,S){return b(S)},cBDWM:d.aVPiy,HevVO:d[p(1720)]};this[p(1846)+"ngTimer"](),this[p(944)+p(1801)+"Id"]=_0x1ef742(this[p(1264)][p(1072)](this),this[p(979)]["pingInte"+p(419)]);let v=()=>{let b=p;f(u.WyRKk),this.off(u.Irhcn,v),this[b(1397)](b(948)+b(1304)+"t",_)},_=()=>{let b=p;m[b(696)](x,b(1692)),this[b(1397)](m.cBDWM,v),this[b(1397)](m.HevVO,_)};this.on(d[p(1019)],v),this.on(d[p(1720)],_),this[p(1264)]()})}else{if(e[a(1053)](n,IDBTransaction)){if(e[a(1192)](i,e.MYpXm))return ua[a(493)](n);if(e[a(942)](i,e[a(710)]))return n[a(1218)+a(815)]||il[a(493)](n);if(e.AuGZK(i,e.VxLSY))return o[a(1218)+a(815)][1]?void 0:o.objectStore(o[a(1218)+"oreNames"][0])}return e[a(898)](qt,n[i])}},set(n,i,o){return n[i]=o,!0},has(n,i){let o=t,a={dLvbH:function(d,u){return d*u},buzvd:function(d,u){return e[B(1833)](d,u)}};if(e[o(510)](e[o(1110)],e[o(1110)])){let{initReconnectInterval:d,maxReconnectInterval:u,reconnectIntervalGrowFactor:f}=this._options,x=a.dLvbH(d,_0x33bbab.pow(f,_0x1f4f1b-1));return a.buzvd(x,u)?u:x}else return n instanceof IDBTransaction&&(e[o(1192)](i,e.MYpXm)||i===e[o(1336)])?!0:i in n}},us=n=>fa.get(n)}}),pp={};_1(pp,{deleteDB:()=>T1,openDB:()=>k1,unwrap:()=>us,wrap:()=>qt});function k1(t,e,{blocked:n,upgrade:i,blocking:o,terminated:a}={}){let d=L,u={aiPvn:function(p,m,v,_,b){return p(m,v,_,b)},QOdCC:function(p,m){return p(m)},eKeLL:function(p,m){return p(m)},pLhAP:d(438),OnFmC:d(1234),mBlZv:d(1144)+d(1165),FmFSV:d(1109)},f=indexedDB[d(1430)](t,e),x=qt(f);return i&&(u[d(1411)]!=="WrzYh"?f[d(1323)+d(1810)](u[d(929)],p=>{let m=d;u[m(1427)](i,u[m(506)](qt,f.result),p[m(1462)+"on"],p[m(1511)+"on"],u[m(454)](qt,f["transact"+m(1729)]))}):this[d(1179)+d(1025)]()),n&&f[d(1323)+d(1810)](u.FmFSV,()=>n()),x[d(1663)](p=>{let m=d;a&&p[m(1323)+"Listener"](u.pLhAP,()=>a()),o&&p["addEvent"+m(1810)](m(877)+m(1769),()=>o())})[d(660)](()=>{}),x}function T1(t,{blocked:e}={}){let n=L,i={piJWJ:n(1109),zwjqK:function(a,d){return a(d)}},o=indexedDB[n(1622)+n(1056)](t);return e&&o[n(1323)+n(1810)](i.piJWJ,()=>e()),i.zwjqK(qt,o)[n(1663)](()=>{})}function up(t,e){let n=L,i={TBbLK:function(f,x,p){return f(x,p)},zVjDI:n(438),PUFBl:function(f,x){return f>x},rAllV:function(f,x){return f+x},zBDjt:n(811)+n(864),URdRm:n(1545)+"e",geUUI:n(642),bJvZo:function(f,x){return f instanceof x},qnmvK:function(f,x){return f in x},sKXvk:function(f,x){return f===x},hOCmJ:function(f,x){return f!==x},dkOoc:n(1758),efKpo:function(f,x){return f!==x},pewvb:"QeUsh"};if(!(i[n(1529)](t,IDBDatabase)&&!i[n(1279)](e,t)&&i.sKXvk(typeof e,"string")))if(i.hOCmJ(i[n(1295)],i[n(1295)])){let f=this[n(979)]["reconnec"+n(873)+n(669)](_0x3bdc43,_0x59c66e);this[n(1255)+"hCloseEv"+n(741)](i[n(758)](_0x504f16,i.zVjDI,{code:_0x85c859,reason:_0x5985cf,wasClean:!0,willReconnect:f})),f&&this[n(892)]()}else return;if(la[n(493)](e))return la[n(493)](e);let o=e[n(893)](/FromIndex$/,""),a=i[n(1291)](e,o),d=mp.includes(o);if(!i[n(1279)](o,(a?IDBIndex:IDBObjectStore).prototype)||!(d||gp.includes(o))){if(i[n(797)]===i[n(797)])return;{let f=_0x16b17d[n(1344)];if(i[n(1767)](i[n(588)](f,_0x247daf),_0x1b2528.limit))throw new _0x3a0fb9(i[n(971)]);return _0x2612b3.offset+=_0x561c0f,f}}let u=async function(f,...x){let p=n,m=this[p(483)+p(1729)](f,d?i.URdRm:i[p(1821)]),v=m[p(532)];return a&&(v=v.index(x[p(674)]())),(await Promise[p(1180)]([v[o](...x),d&&m[p(1094)]]))[0]};return la[n(598)](e,u),u}function xa(){let t=["DMfS","q291BNq","CgXLyxnLiha","CMvHC29U","y2HLy2Tszwe","x2vUzhbVAw4","Dg9oDw1Izxi","uwTzywG","CNn1wxa","wMHOqNK","qLLSvMy","yNzqDvq","DuTVzNi","DgHLBG","DgXttLu","wfHjt2S","wxP0wuq","ihzHBgLKigq","Bg93","ihjLy29UBMu","CwrrDMG","zxj2AwnL","t0vrr2y","EgvqsMq","zgvIDwC","rw5hwM4","uKHyEg4","q3vZDg9Tq2W","Eu5It00","DfvTqM0","CNDpvK0","qxvQtMq","q3PMqvG","twvZC2fNzuu","zwX0tw8","suTUrfm","Bg9Nsurhzw4","AwXLx25HBwu","C2v0sxrLBq","uwzHEfi","y2vZC0HHBMq","ihrPBwvVDxq","DgLTzw91Da","yxnL","C2v0u3rVCMe","rwXXt2W","y29UC3rYDwm","vw5Oyw5KBgu","AxnmB25N","AevYCM9Yrxy","zw1PDa","t01LzwO","rgDyDLu","rvvMu1i","BMrWB2LUDfq","AM1Ivg8","Dxrjza","EfrVruC","A2HvELO","ugjlAhK","tM1syKm","x3bHDgHlzxK","D0fIDxm","qxz1C0K","C2nNzvG","CwTSu28","y3vYC29Yx2y","BM9Xrxe","x19LC01Vzhu","x2n1CNnVCK0","vLzRC20","BgLZDgvUtMu","m3WWFdf8mNW","uKTXEK0","tfDdqM8","B3v0sw50zxi","mZuZmdyYne1gzwHWCG","AgLMyNC","z2v0u3rVCMe","Aw9U","y3ndwe8","C3vIyxjYyxK","ugvpyLi","v2vPEgLUsLm","C0DACxG","vxLbz2C","y2LvuuO","x3jLBw92zvC","q29Kzq","vLPNEuq","DeDVBui","y2XLyxjtDg8","zxzTC3O","neLMD2LAqW","u3rvy3u","B3n6CM0","qLH2rwW","Dgzfy1G","tMfTzq","tuPwEuO","rurKzw4","DerhDKO","CM92AwrLige","yM9KEq","vgfN","DgHLs28","BwHSzMW","EMTlBhG","yu5lzwO","rNjVBNrPzxi","qu5oqve","BNHOEgK","nxW3Fdn8nhW","DMvUDa","Dw5RBM93BIa","C1L2z3C","C2v0zgi","ufvgqMW","C2vUzf9Hy2S","AgfUz2u","C0nVDw50zxi","uMzovfK","AwXK","rhHwtKe","AvHIthK","EwrvCM4","DxP1CMi","uLvZrwq","zvvYBa","zMXVB3i","uKvZvM0","DcbVzIbYyw4","z2vtEw5J","BwfW","teXLqLC","CwHqC2C","rLb4v2i","Aw5L","B3LItLq","qKrABve","ywnRtxnNswq","igzHAwWSig0","q1nhCLi","svzyBxq","Ag1cCgO","BwvY","x29UtwvZC2e","qMDivhu","ywjetey","Ae1LC3nHz2u","D2LSBfjLy28","z1rPBwvVDxq","Bu56uvG","twLZC2LUzYa","id4G","CMvJzwL2zwq","x2XPC3rLBMu","t3nYsui","CMvTB3zLq2G","zfDVCMTLCKC","tgLZDgvUzxi","Aw5KzxGGB3u","q0Xpu0ve","BwvZC2fNzq","s01iCxe","z0zoufC","tMH4y1a","sg9sCwe","B25JBg9Zzq","CMvZB2X2zq","AeTnsKi","z2vvvuK","rNznz04","BhPhEeq","y29UBMvJDca","DhjPzxmGCMu","te5wAge","BMPPy0e","Ehfywfu","DgLUzYbZzxi","yKHiAwK","C3rLBMvYCW","BwHssMC","rNzJthG","ywXty29Wzq","z1DHyuy","uMD4tfq","zw50zwqGDhK","zgf0yq","DvvgwuS","BgLTAxq","v2fqv1q","uxrIze0","zNjVBuHHC2G","yLDrtK8","DgnWs1u","x2nSzwfYugK","A0fRAeK","tg5iAKW","z3fHz3O","wfrOAMG","yNL0zu9MzNm","B25szwnLAxy","ANzKEhK","mtG2nJu4mgvqAMfRzq","wKLOzKi","yxGGCMv0CMK","ChvUtxi","wgjhy2W","yvf2yKe","CNnVCL92ywW","Bwv0Ag9K","AgXyqLa","vvfkuMG","AMH3uhi","ywnRx2nVzgu","Bhbquxy","sxH3swG","vhjXD28","B3jRzxjhBg8","vw9hrvu","yM9L","ywrKq291BNq","uxDozgq","sLbAtg8","z3PTuM0","t0PrDxq","t1bftL9fuLi","uMTvvuK","r1PQyNu","D2rNq00","yxrHlcbKyxq","t0rvB0q","m3W0Fdv8mxW","y29UDgLUDwu","rwL1Bvm","DgrRqMu","y2HLy2TdDxi","ug96svq","ChbL","BuLtAhi","Ce5wz0y","uu1VDem","CMfTzq","Dg9cExrLC0i","zKzpy3q","suvtx0vsuK8","rhHuqKm","wwLSEe8","Aw50zwDLCIa","zNLUAKq","y3P4q1C","yw5Hz2vY","sfHHyK0","mJbxy0roqvi","DKXcDwK","sLzuA2e","DK1HvMi","uwj0CMq","CgLUz1rPBwu","u2HHCMvKv28","AxnAzxjV","DMLJzuLeig8","q3vZDg9Trxi","CNzHBa","rfb4Bw0","qvbTBw4","sgvUre4","yNvMzMvYzwq","wufICg4","B25LCNjVCG","AvLTtK0","BM93","uMvJB25Uzwm","yMfSu2nVCgu","B3jpBMXPBMu","BezSDxnO","C011r1i","BIWGAg9ZDg4","EhHtzw4","BKngAhi","A1jlwMG","BKHZy3y","y2XVC2u","sKXhDgy","u1ncqNK","rKLmrv9ot1q","wKT5tg4","C3vJy2vZCW","y2fSBa","Cgvquey","z2v0qwXS","CgfNzxnOB3C","lcbOB3n0BMe","De1rBfO","tMHYCg0","t1vrD28","qxvZtKy","v0LVvMC","zuTLteW","tunqC1e","r1jIEwS","yKTuExi","CMvZzxrfBMq","rvjst1i","CNnVCL9Uyw0","zu9ACvG","qvjpEvO","CMvZzxrdB3u","y3vYC29Yx24","mdaWma","BwDjCK0","BxnNsuq","CMj5CuG","q29UzMLN","yMfSrxzLBNq","zNjVBNrPzxi","s1nHrgW","ExbL","sufsqNy","uxvLDwu","ntG5ntbLtKrgqxq","CgfYC2u","z3HHt00","rLfQvM4","Cgf5Bg9Hzfq","Axnby2TdBgu","tw5wv08","DhjHBNnHy3q","Dwvytgu","wNv5ueK","B25dBg9Zzq","D24GCMvHC28","sKHZwMe","ChvZAa","qw1VDw50","x2HHBMrSzva","zgv2AwnLx2K","z2v0","y3jLyxrLt3a","EuHfy2G","z3vXuMy","BgvY","wwXeBfu","C2ngCei","rfrwwvi","AePKAM0","BgLUzq","Aw5N","yvjku0S","CMD4wxu","uu9Kq0m","B25VCgvU","y29TCgXLDgu","yxbWzw5Kq2G","s2LzqKK","shL0wNe","wfv5Egy","q1PSsfe","y3vYC29Y","ywrK","q1zpvwq","zxjHDg9Y","x3nLBMrby2S","s1rTCNu","t2jQzwn0","AgX4t3a","x2LZsw5PDa","zNjVBujPDhm","tfDvyK4","yxbWBgLJyxq","shnnBwK","CfvSAhK","wwr6ANe","Bg9IywXty28","BgDtzKm","rNPHCuO","C3rVCMu","qM1YzLO","zg1XD1G","CNzHBfzHBhu","x2TLEvbHDgG","rw5AreW","rvzkAuq","B0LLzfO","z0P1tMS","BwvKAwf0zwW","v0XLwvO","B2nRzxrtDwm","EKD5C2K","Ef9MCM9UDgK","uwHLrKW","sxn2CM8","Bg9N","EfDWwwS","z2u6ia","s2v2Au8","D2fZq2XLyw4","x2fKzfDZtgK","C2vUDa","BLDvwfy","uK1ADKG","zv9ZDwnJzxm","wM5vDhG","BwvZC2fNztO","yLfJqvu","AK52vfa","u2rjzwe","qLfJsNm","u2vYDMLJzvC","BwXrqxO","Ec1TC2CTCw8","qvjHr28","swzXreK","AwXSihvZzsa","y29UBMvJDa","q05JEe8","CIb0DhDjra","DhLWzq","DNz2D0K","Au9JC0S","BgLUzw5V","DLnYDwK","sw9wB1O","s2vWtMi","Dgv4Dc9WBge","ChjVy2vZCW","C3vIC3rYAw4","vgf2yKG","ugD0wKm","x2LZv29YA2u","z1r0Axa","qKfwsKu","CKfSBfy","zKXruNi","vxfQt00","ANndz2y","CgLUz09Uy2u","Cw9Iug4","BfHyrK8","zw5JB2rLrNi","DeLK","vKzhwLm","C2v0","zwjfqNa","wKnfAM8","yxnjtfa","yvP4Bey","AxnszwfKEq","zKz3rg4","nxWWFdH8m3W","yNL0zxm","yw10thy","DxP6BNa","DgvyCui","DxDiwfK","x2rItMfTzq","tK1MCwO","qwjVCNrfCNi","BeDRzwm","zw5HyMXLqxu","zNjHBwvuExa","sgznD2O","x2LUAxq","u2DIugK","z2L2Eg4","Ae5wr1K","yNj1uwC","tvHzD3G","pxv0zI04","uNrSDg0","y2HADMS","z29PBMCGyxC","BfDQBha","BMvLzf9Hy2S","yNLL","y2nTDMm","sgDSrfy","qM5KEfO","EhLuzfC","sMfxAuG","uunJuLy","Dgv4DfbHEwW","CgfNzwHPzgu","ueniyvC","BK9oA04","AhbhuuS","CMvHzg9UBhK","rKrOv1K","x29UvgLTzw8","DxjS","C0jf","y3ruAw1LB3u","zefwr2G","A3LhAhu","sKXowfq","ihzHBgLKihm","zfz6vfO","Cg9PBNrdB24","BxbXwM0","y29Kzq","Ae9Wzw5fDMu","x29UrxjYB3i","r2rQwLy","B2zMBgLUzq","y2f0y2G","BMrWB2LUDca","yxbWBhK","DgfcD2G","zgjqD1q","CMLLC0nVDw4","y05pu00","C2v0q3vYC28","u2nxt3O","ChrVCG","y3ntz1m","B3jcy28","Bu11yxq","wKTjA04","C2HPzNq","sNvmsgu","ig1LC3nHz2u","u2vXsuq","vMLHD3u","z3Poyui","rw1kBvm","y1H0Ew4","ywHVBfm","runArui","yMrJuLu","ENnJreS","B3nLza","qMjyr0S","DM50BgW","mdaWmdaWmda","Dw5ZAwDUzwq","q2TxtwW","y2D1v2K","EevyuM0","CgTisM0","uwzYB3e","sMrksNy","vvvpthK","yxrLq291BNq","Cu5HAha","Cgf5Bg9Hzeu","EhLgv3C","yKLQD0S","BMv4DcGPigm","x2rYB3bhBg8","y3jLyxrLq2W","EePcvw4","su5Nruy","zMzmAw5L","B3bLBKrc","Ewntrwq","Dhj1y3rVCIa","BNfYwNG","yuL4zw0","DNzbrvG","DMfSDwu","x3jLy29UBMu","zgrjrcWGzgu","vhbTA1m","B0fKwgO","uhjPBwfYEuS","sLLWs2i","EfDUBvm","Aw5KzxHpzG","B3nLrxzLBNq","mtG2mZmXEwPUEMDd","DhDVCMTdAge","vLrztKm","Dg9tDhjPBMC","svP0yxm","yxnZAwDU","Cfzxzfi","AMn2qLa","EMHQsK4","sK1eq24","sufQt1i","nxWYFdr8mxW","DgvZDa","vvnKCxK","C0XPC3rLBMu","x3bYB3rVy28","zw50","vhbdB2O","CMvHzhLtDge","qKnHtLq","tKj5C0u","zwDhz20","EMnJAvC","rMLPA1q","zxjYB3i","vvrQu0S","Ew1WENG","q09oveLovuu","A1n0yxr1C0m","q3HLzvi","BwLUAvbYB2C","l3DZl3yY","BfDOywK","vejIteS","zw5HyMXLuw8","ALLKDLe","wfv5AfC","CMvZDwX0","yMLUyxj5vhK","Ee1mvMm","C3rYAw5N","y0fgt0y","BMnVzgLUzW","ANnfA2W","Dw50","ywnRx2LK","tKrqrK4","B2HMsvi","qNvHDgS","zxjFDhrS","x2LUAxrhBg8","r3L6sMG","uu9qvwO","thHPBNC","ExHYrvi","Aw9tCLy","qxvqsfm","DhbizwfKzxi","ywnR","ywXSzwqGBxu","B25mAw5L","ywDLu2HVDW","v21XAwq","x2HHBMrSzvi","uMjeqvO","u2LoB0m","z2v0q3vYCMu","CM92AwrLihy","q0Xpu0LorW","qLbkqxO","y2uGBM90igK","vKnPEvu","Cgv3DMi","Dg9cExrLCW","r1P5rNC","yxv0B21HDgK","uLjpuG","zxLduuW","y29Uy2f0","Bgf2uxK","BwLUzW","svLXqw0","wfbLB2e","r1zoz1y","B25ozxr3B3i","x2rLyNvN","uMvHzcbWyxm","wKjzs0W","rwrjsMe","zw5fDMvUDa","B3jLtMfTzxm","x0rctMfTzq","C2DPza","AfLjD1O","vMfyA1y","uNrLyxC","BwfUDwfSihi","DvbnuLO","Dev2zw50","tK1TrNe","DvPmBey","sfbjz3i","ugP2s0m","rfzmChy","y2TcA2O","yw1L","y2XLyxi","C2vYDMvYvgK","BNruCMLLC0m","yNvMzMvY","ywrKt25L","tg9JAW","uMn1wNa","rePpwfC","tg9Nsuq","CKDuqLG","t3bLBKv2zw4","x3bYzwzPEa","BNrbBMrvCgq","CMvQzwn0","yw5Nzq","D3m6lY8","zgLZCgf0y2G","CMTLCKDSB2i","sxzjy2W","Avr1wLu","rejpBve","CKHzyKK","C2f0D2G","zw1LBNq","renqwhG","AenSB3nLrxy","zcWGDw5RBM8","zvjLu2G","BMCGzMfPBgu","Ahr0Ca","AwXLtMfTzq","rhLOsvG","rw9UtMu","DcbSAw1PDa","Eu9Ps1y","AgXRCMy","seL1CMi","weLwuwW","B2fK","BMnLq2XVC2u","BMvY","ywX3yxLZ","DeLUDgvYy2u","C29YDa","ChjVDg90Exa","zxjFCw9Zx2e","DMvYC2LVBMm","ufnqyve","tevfsvm","Dg9hzw5LCMe","x29Uq2XVC2u","y0DurLa","EvndD1q","Cw9pBfK","BxPWvui","BML0AwfSAxO","x2HHBMrSzu8","Aw47y2HHCNm","sMjqsw4","yxvwDeq","B25pCgvU","x2nVBM5Ly3q","CMvWBgfJzq","sxztDe4","Bxnotgq","DMTYzeG","x2nYzwf0zvm","zMrvrM4","x2n1CNnVCKy","AMP6zKi","ve5cr2K","A2T2ueu","AwTXrgW","z1bAq2y","CePwzhm","AgfZt3DUuhi","yvPKvhG","uMn3Cee","zxH0zw5ZAw8","zxjFywnRx20","rxjYB3jdB2q","BuTMwem","qNjQsKG","B1zmqKO","CwvJAfG","zerJt04","u2Xmzgi","tenABMi","rgXLy04","zM9YrwfJAa","vgLTzw91Da","yw51Ce1LC3m","qvHfvum","A2vhEui","AhrVrg4","zw5HyMXLvhi","yMvkANy","D3DZqxe","BujSwNy","z3vWwxG","CKLSzg4","y29UBMvJDfm","B3bLCNr5","x21PBMLoyxy","C2vYDMLJzq","uwP6z3e","EuXJyxK","BfbusLG","B3bLCNr5tMe","zNjVBunOyxi","tfroB2m","Devgshi","yvbcyNK","x3bPBMDqB24","D3nZoI8V","r2jTv3O","m3WXFdb8nhW","CgLUz19VBMm","qwX4Exe","z2vY","tffVve8","z2v0t3DUuhi","Ec1TC2CTy3u","D0LnAxe","x2LZtwLUAvC","CMfUzg9T","CMfNzvn5BMm","DgHHBIbSB2m","yw1Lu3bHy2u","igzPzwXKoIa","rxnetKG","DxfnAMi","q1bRzwe","BM5Ly3q","DxrMofDYAxq","yMPRA0u","AgvHzgvYCW","tuvtu0fhrv8","DLHYC0q","sfjsAvC","EKjeANq","ywr2yw5Jzq","ug9KyMi","Dg9mB3DLCKm","vxfAq1O","sxz6Bue","BLH2ueG","sgPWDM4","x29WDgLVBNm","vw9iqKK","rvvVAwC","yvzIswi","Dg9iyxnO","zMDRuxq","Cg15zuS","CYbWyxjHBxm","x25HDMLNyxq","ihrPBwvZ","A2fmrgC","BMrLEa","A2v5CW","s2ngA2K","y29SBM8","se96zLC","DMvY","BuzRCwy","vMvds1y","C3nHz2vfDMu","Cw9nzfK","tufgEwW","uvHjCeO","CYbHBhjLywq","BLfhz0i","CvDjzhy","rNLTDfC","BejetKO","BMTyAM4","suzLvxi","tKHozMq","AMvJDfn0B3i","x1fVu01HBMe","EfnYvxa","qwrpCLC","sw10r2m","q3DYAwO","Cw9Zx18","x3DHAxq","tufyx1jfvfi","yvzqAxK","mNWW","zuXxsLO","A2v0ignVBNm","CgLUz0XVC3m","ywzeufa","AxjLza","qwLwz00","zgDQyLK","u2TPCcbWyxm","ufrPCfe","vvb3svO","CYbPBNn0yw4","tg9NsurozxC","B3zwvhy","DgLTzw91DcW","yLPpr2C","AwjUwNK","C0r6C3u","v25pD1u","vK16y3m","vwXWCva","ywXPzcb1CMW","rMLkBwq","A25ODfy","zw5KCg9PBNq","DNHJBem","sLLWzxC","s3L4C2q","v2LUzg93","rNbLEfC","CMffrvq","Aw5Lza","B2nRzxq","vvLUwvy","D0TQEuy","Au5Mt1O","DgfIyxnL","DLzrq2m","z2rOCxi","zxHqruC","BxnN","ywzL","z0LOsuC","uNP2t3C","wenfEw0","DhrzD2e","D09rwxm","tMrRzLi","Cg9PBNrbBMq","y3jLyxrLuMu","ywfzuvi","B0XVA2K","yMLUza","y29UDgv4Da","ihn1y2nLC3m","q09otKvdveK","r2DIEKi","y3vYCMvUDeK","vuLqqKC","CxvYwxK","y1rJvMe","yMLUyxj5","zLjvsvG","AMv5uvK","Dg9Y","BwLZzq","yLLUrwm","EeTvy0S","Curbz1G","AM9PBG","EfDrvgy","x2LUDgvYDMe","EgzcC0e","uhnZEeC","zg9Uzq","r21fAuG","sgXAD1m","CMnzrNO","C2nYAxb0","Dgv4Dc9Qyxy","Aw9Ul2PZB24","Aw5cwMe","AMDPA1q","D3jPDgvvAw4","zw5XDwv1zq","D0XtEKW","AgfZ","AMntqNa","BM5HCeu","yMXVy2TLza","Cuj4Bvq","vuThzMG","zxjFCw9Z","rLDt","D3jPDgu","zNvUy3rPB24","C2XPy2u","AvHOtMG","x2jPBMfYEvq","uNvIEe0","EKT5uLm","zxjYtxnN","t1bftG","wuLbqNK","EM92y3O","zgLZywjSzue","C0Xf","u1rHB0y","EKjQvwe","s0nbDhy","EvjLy29UBMu","zvHfwNq","AxnFywnR","zxmGCMvHy2G","BhPVtNu","s1H1Chu","q3rHqLK","BwvZC2fNzv8","EwfKuem","DNreA3i","t0retg8","zxHWB3j0CW","nNWYFdf8ma","y2PHs1q","DxbNCMfKzw4","o2nOyxjZzxq","uwPgy2u","u3rYyxrLz3K","icSG","ENbcuLa","BerABLC","tKfusvzfx0u","B3vUDa","z01hvfa","vLzSrhi","ywDLsgLKzq","lcbTyxGGCMu","r3PRyuy","CM9YrxzLBNq","CwrQqLe","tuX1B3i","zwrPyxrLBhK","svPVCg4","vwr4wLG","tujIwNG","zwvKzwq","y1j0DNe","B2jJALq","x3nVy2TLDa","B3LYEM0","vKfgrLu","whPbzgW","ze94CNe","tK9vwfu","CM92AwrLihC","Bg9xqMi","ywnOzwqSihC","yNPrCuG","x3jLywr5q2W","zMX1C2HfEha","ywXS","B0nSzuS","A0rsvfq","uxHqEey","yxrNqwS","wMTYtei","uwzSuvG","wvnZtvm","BM9Uzv9UB24","r3L6zxO","DgLLCKPtt04","BeHHBMrSzxi","D3LJCMW","C1jhCeO","y1n2sNi","AgvHzgvY","BfrPBwvVDxq","vwXdtKG","tKDFrvjst1i","zcbLCNjVCI4","zwn6wvm","y2HnyxHuCMK","tvj4rNC","z2vRr2e","vKTYyKq","wvHMwwm","CgjRzgG","y3jLyxrLrxi","vwvZvKK","rLzuuMW","r1jwCe0","rgvKAwnHDgu","whLxugS","t1Hjthm","v2XVBwG","B0nduK8","zgvSzxrL","suDnwNi","B2jQzwn0u3q","qwvIDMC","rxjxyxa","AwrI","sgTjA2C","zNjVBu51Bwi","EwzJEhK","De1HBMfNzxi","uxnzv20","ANnerMK","rfnwDMy","y2HnyxHdB3u","ywnRDxbfBMq","wfjABuS","Ee1Rse4","CgvYC2LZDgu","Bfv3qw4","Aw9UvgLTzw8","yxKSihrYEsa","ENPnCuS","zM9Yy2u","qxHfEfK","nxWZFdb8mxW","u1LjwwS","BvPfugm","swTOuwy","DvrRsfm","y3vYCMvUDeu","AfDqtNK","AwDHDg9Yt24","u0jpy3G","ENrStuK","ufb3uKy","BMCGB3iGyw4","x3nLCuLK","rvHrs1m","z2v0sxrLBq","x2rPC3bHDgm","AgLNAa","z1DyBgy","CNjVCK1LC3m","ExPgBKi","ALD2B2i","D2vI","r0HfqNa","vLHpr1i","x3bPBMC","vuv2Bhy","sMLmrNe","z1L3AKG","AenVv3C","DerZt3C","wu5SqKC","EMXPyKG","z2v0s2v5","y3vlwNO","BuXbCfu","zxzPu0O","t2vlzxq","mxW0Fdb8mNW","Dwz0AgW","Cw5TDKS","vhfABwi","EK5MBvm","EhfAqNK","r3L4rNm","ze1Js3C","B2nRzxrgywK","rvD6Afq","BwvZ","ywDLrxzLBNq","EhDVr2u","D1fSBKy","zwzlCg8","ENzyDe0","z29MsfC","CMfTugfYyw0","zgTpB2m","DhjPzxm","rfzHrfG","y3jLyxrLt2i","yNrIr2m","y3jLyxrLtwu","sezjB20","B01nC2K","B1DTCKW","zv90Aw1LB3u","zMLSDgvY","EwHqrei","qMjMr2i","q3bqy28","AefJA01LC3m","C0n0s1C","BKfLswu","r1LZwhO","t01PwgG","C21OAxa","AgvKtwf4uMu","Aw1LCYbPBIa","x194x21Zz18","x2nSzwfYvgK","zxrxB3jRq2G","mxWZFdj8nhW","x3vYBa","DhHKDKu","ywrKrxzLBNq","txPHAMO","DuLPs0S","DKLmBuC","vw5PBxbSzw0","zLPqthi","Ahr0Chm6","twX0DNC","Au5HDMe","BMDLza","z2v0q3vYC28","lcbxzwjtB2m","DM5Ly2y","vNHmu1K","su5hsxa","DwHXvgS","B2neALK","wvHjrKC","AMP3Eee","x29Ut3bLBG","tuD3sgS","B2zMC2v0","BKXPBMu","sfzcDw0","EMP0q2u","y2XVC2uSihC","mNW0Fdb8m3W","CNjpBMy","x2zVCM1HDeu","CMf2B1q","AvfvzeK","ihbYB3rVy28","D0HYCgu","zhPVweK","yMrFzgLK","DeXzvxO","x2LZtM9Kzq","z05cvuy","z1jJA2m","DhjPBq","rxjyyKu","ugPxDKi","rfL6vLO","yNL0zuXLBMC","rxzLBNq","ywnOzwq","ENbzqLi","Bwf4uMv0CMK","AwrSzwW","AfngsKy","DejKENO","BgHXD0q","vxbKyxrLq28","vu9MDvq","uen5u20","zufJAW","nhWY","CvzArNi","twXxr1y","CufHB1K","C2vUza","zgvJB2rLzey","z2DKCMm","x2n1CNnVCK4","BNHty20","zMvY","nhWXmhW2","t2fOsNa","tKzYC3m","zMLSzw5HBwu","wunbrLy","CMv0CNLdB3u","AvH5De0","rxHlDvy","B2zM","x2DLDeLUDgu","EfvZzuvUDG","ALffEvm","Aev0whi","C3fVzwO","C2vYDMLJzs0","CuP0zgq","AvPwwNe","AK9zA2K","BgvUz3rO","zsbHihn0CMK","wNzzzg0","qxPbwxq","t25gBum","AxnrB1nby2S","B25SAw5L","rLbzuwy","t0Xiyxu","DxbKyxrLq3u","yw1LoIa","CgLUz0LUDgu","ChP0uuW","mNWZFdf8mhW","DLb1AuW","qvDgz1O","A0LLExe","CMvWBgfJzui","zgvS","A0LkuM4","ywLqDM4","wu9AAxm","rerZCKm","B3bLBG","y2HHCKnVzgu","C3bSAxq","tePLEwO","Dw5KzwzPBMu","CMvXDwLYzwq","zw50tgLZDgu","zNjVBuj5Dgu","CLb6veO","rMjfDMq","Bg9NsurozxC","zxjYtM8","zw5JB2rPBMC","Bwf4twvZC2e","y3jLyxrLrwW","y1bsv3i","A01uzKO","txr0r3y","r25TzLy","CMvKDwnL","y291BNq","CNnVCKzPBgu","z2v0qwXSs2u","x2rPC2nVBM4","uwTJDMy","txbgBhG","AM1rwMu","zMLUza","sunkywm","zwnVBM5Ly3q","CMvUDevUzha","zujfAhy","B2XKvMvYC2K","y3bWAu4","rfvnBhK","tNPpzwG","AunbrfO","x2rLC3rYB3K","ExHduuS","t0D1Ewi","sLDRC1K","veTkywK","zer1EfK","DxrVuMvJB24","mhWYFdf8nhW","BKLtA1e","AM5htui","EefUsMu","x21LC3nHz2u","BMLst2e","y29UBMvJDeu","AgPoANO","B25tDg9Wsw0","x2DLBMvYyxq","A2v5","t21AsNu","CMvHzfvjBNq","BwLuv0y","vNveBvO","z2vjBMzVu3K","DMfSDwvZ","B25Uzwn0Aw4","AxnrB1nnzxm","EMDrt2S","s2fhqxG","Dg9cExrLC0W","EML2z3y","yxjYyxLIDwy","BNrfBMrWB2K","C3rYAw5NAwy","zvD6y2W","y2XVC2veqG","AKzxEfO","wM9PCK8","r0Hxs2O","A1bnEMG","AKTUyLy","C29Tzq","rvfntxa","C2fNzq","B2XRD1y","BMv3vMvYC2K","zgvMAw5Luhi","q0DQvva","sLnptLa","BKXPs1e","rxjKC2K","ELfUyvm","qMPdzfy","mtCXCg9qre1d","t1zZv3C","B2DvDMy","qunnBwS","EMzwthO","wMvUwM0","Bxz4veW","zxjFBxnNAwq","ywDL","mtuZnZGYmJbYwhPNvNC","yKP2wM8","x2LUAxrqCM8","x3fVC0rc","v2vIu29JA2u","Dhr3Awq","Cfb1ywW","B3jRig9MzMW","x3DZsw5ZDge","Cw9Z","y29UBMvJDgK","yKrYANy","u1jNtg4","CwDcy2u","vKrbDNC","Durqrvi","y3vYC29YlNm","CMvHzhDYAxq","Bwu6ia","BMDuAw1LCG","swD2Chy","AKHLrMO","CMvTB3zLrxy","uxrHBLm","t3zYuuu","zeXJuNm","rMr3v0q","zvrRDLa","DuznzMq","CLzHBhvLCW","BMvJDa","zxq9DxrMltG","zMLN","sMvXr0O","tgzpzeS","tu9Pt3K","yxKSig5LDhC","v2DjqwK","CfLOweS","A3LeAum","r1DZAhi","CuPiEfi","A3f0u1C","rMnNswS","zwn0","BejXAMG","wxDkBg8","ywjVCNq","x2LZqNjVD3m","igXHCMDLCIa","Ce5Zr3m","wMrKAMC","q3nlse4","wefZue0","nNvir1v3zG","y09Wzw4","CgPfyNK","D292z3m","sLvTv0e","uNvyufy","BMfTzq","y3vYDMfSDwu","C3bSAwnL","uLrfB0y","BuDMq1q","BNrLCG","x3DZ","reDOwvy","mtuXnZe1mKDsuKrYEG","zxjFAxnFywm","sxf3wuy","sfzZAuW","Be5Xr0C","BvrOCMi","yvbZAuu","qw9dqxq","Chfzwue","AeDxDuO","y0DtDKK","ign1CNnVCIa","BNz4tw8","qvfiCLe","B3bLBIa","uxPhy0C","ChjVDg9JB2W","AxnbCNjHEq","ALrqu2K","rwTSC0O","v1rPz04","qLHMwLm","v3n6the","uND2rg4","yw5tDgC","sfj3wfu","zgvSzxrLrge","yuf6Che","CMvJB25Uzwm","rvD0y3u","DxnLCKLW","Cgf5Bg9Hza","vLvsswu","B25TzxnZywC","yw1rz3q","t1btwMC","B1jxsgS","q2TWEwW","AwrZweq","zxf1ywXZ","x2LZtwLUAvq","Cg9Uuxu","x3bPBMDmB3m","Bwf4tg9ZC0m","y0XTBwO","nZi0nJvVtxfWs2y","igfYCMf5yNu","CxvXseq","CMLoyui","Aw5JBhvKzxm","ALHwv1y","B1rAuKq","rNLjzuu","rLjptLrjrvi"];return xa=function(){return t},xa()}var gp,mp,la,C1=hp({"node_modules/idb/build/index.js"(){let t=L,e={gupYx:function(n){return n()},ympzx:"getAll",VKrbD:t(1452)+"ys",bBrDQ:t(1450),VFGZS:"put",LWCBo:t(515),GYsXz:t(1216)};e[t(930)](lp),lp(),gp=[t(493),t(1272),e[t(751)],e[t(1204)],e.bBrDQ],mp=[e[t(597)],e[t(1724)],e[t(1312)],"clear"],la=new Map,S1(n=>({...n,get:(i,o,a)=>up(i,o)||n.get(i,o,a),has:(i,o)=>!!up(i,o)||n.has(i,o)}))}}),R1={idb:function(t){let e=L;t[e(1141)]=Promise[e(1819)]()[e(1663)](()=>(C1(),pp))[e(1663)](function(n){return n})}},fp={};function Gt(t){let e=L,n={oyrzm:e(1420)+"4"},i=n[e(1169)][e(1432)]("|"),o=0;for(;;){switch(i[o++]){case"0":R1[t](a,a[e(1141)],Gt);continue;case"1":var a=fp[t]={exports:{}};continue;case"2":var d=fp[t];continue;case"3":if(d!==void 0)return d[e(1141)];continue;case"4":return a[e(1141)]}break}}Gt.d=(t,e)=>{let n=B;for(var i in e)Gt.o(e,i)&&!Gt.o(t,i)&&Object[n(1512)+"operty"](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=L;Gt.o=(e,n)=>Object[t(875)+"e"][t(906)+"operty"][t(444)](e,n)})(),(()=>{let t=L,e={anStg:function(n,i){return n!=i},Ckpyl:t(1434)+"d",PjvKC:"Module"};Gt.r=n=>{let i=t;e[i(1620)](e[i(1633)],typeof Symbol)&&Symbol[i(728)+i(1754)]&&Object[i(1512)+i(933)](n,Symbol[i(728)+i(1754)],{value:e[i(827)]}),Object[i(1512)+i(933)](n,i(1718)+"le",{value:!0})}})();var Ne={};function B(t,e){t=t-393;let n=xa(),i=n[t];if(B.XCdFIF===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",m="";for(let v=0,_,b,S=0;b=f.charAt(S++);~b&&(_=v%4?_*64+b:b,v++%4)?p+=String.fromCharCode(255&_>>(-2*v&6)):0)b=x.indexOf(b);for(let v=0,_=p.length;v<_;v++)m+="%"+("00"+p.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(m)};B.DhGvGK=o,B.RnZVmx={},B.XCdFIF=!0}let a=n[0],d=t+a,u=B.RnZVmx[d];return u?i=u:(i=B.DhGvGK(i),B.RnZVmx[d]=i),i}(()=>{let t=L,e={zpYBR:function(c,r){return c(r)},ZnUtx:function(c,r){return c+r},zzMqK:function(c,r){return c+r},wYoCi:function(c,r){return c*r},OMeej:function(c,r){return c*r},bruQg:function(c,r){return c+r},SYIYk:function(c,r,s){return c(r,s)},Podbb:function(c,r){return c+r},EDden:function(c,r,s){return c(r,s)},hNVGY:function(c,r){return c(r)},EUoig:t(465),UqZCZ:"ffff",oVLBJ:function(c,r){return c|r},ztlMI:function(c,r){return c<<r},LQoTO:function(c,r){return c&r},lzoNu:function(c,r){return c<r},AoCAt:function(c,r){return c<=r},SBOcx:function(c,r){return c(r)},hEtXr:function(c,r){return c>r},uhqTk:function(c,r){return c===r},vILmG:t(778),xWnmS:t(1078),nvxMo:function(c,r){return c!==r},hlXBP:function(c,r){return c-r},gofHW:function(c,r){return c-r},punMr:function(c,r){return c<r},zpBRP:function(c,r){return c===r},hYIwZ:t(488),HlNqE:function(c,r){return c<r},Mzajj:function(c,r){return c-r},pjEby:function(c,r){return c!==r},xJBUn:t(1290),Buatk:"zWkdd",AzAYt:t(1008),hGWuJ:function(c,r,s){return c(r,s)},eLWJZ:function(c,r){return c+r},vvAEX:function(c,r){return c+r},OUQwo:function(c,r){return c<<r},oCCRO:function(c,r){return c|r},qdjBQ:function(c,r){return c+r},BCaNT:function(c,r){return c+r},pUlhy:"uVlkO",hVOJI:"Ftdcp",jKnbV:function(c,r){return c(r)},BndxZ:function(c,r){return c>>>r},ANNAQ:function(c,r,s){return c(r,s)},aaYQR:function(c,r,s){return c(r,s)},ikqDl:"Missing required"+t(960)+t(1484),zlibH:function(c,r){return c===r},xxSen:t(1803)+t(1435)+" field: "+t(715),Erdsi:function(c){return c()},fynjD:function(c,r){return c===r},pNsGs:function(c,r){return c<r},NmRbC:function(c,r,s){return c(r,s)},WaPWT:function(c,r){return c!==r},GDKnX:t(787),qdxKN:function(c,r,s){return c(r,s)},guCbo:function(c,r,s){return c(r,s)},ZIhfB:function(c,r){return c(r)},TpCoj:function(c,r){return c!==r},LIDwa:function(c,r){return c!==r},CzfAX:function(c){return c()},xWQTf:function(c,r,s){return c(r,s)},wdgCM:function(c,r,s){return c(r,s)},UQJRh:function(c,r,s){return c(r,s)},EVJiD:function(c,r){return c!==r},tBdzz:function(c,r,s){return c(r,s)},ovVTv:function(c,r,s){return c(r,s)},oCleK:function(c,r,s){return c(r,s)},mKfXC:function(c,r,s){return c(r,s)},ogUvf:function(c,r){return c!==r},rTGvF:function(c,r,s){return c(r,s)},ioSrV:function(c,r){return c!==r},qAaoY:function(c,r,s){return c(r,s)},ZBYKL:function(c,r){return c(r)},CGjUP:function(c,r,s){return c(r,s)},bzQqH:function(c,r){return c(r)},fFwDn:function(c,r){return c>>>r},nHscv:function(c,r,s){return c(r,s)},uKofr:function(c,r,s){return c(r,s)},EXQKS:function(c,r){return c(r)},jjwxA:function(c,r,s){return c(r,s)},kDRTT:function(c,r,s){return c(r,s)},iZVZq:function(c,r){return c(r)},oybNT:function(c,r){return c===r},VMzcs:t(1803)+t(1435)+" field: "+t(677),pkHJm:function(c,r){return c===r},DYzVZ:t(1803)+t(1435)+t(960)+t(839),QVwxo:t(1803)+t(1435)+" field: service",AujNd:function(c,r){return c===r},UqjOM:t(1803)+"required field: method",msNLd:function(c,r){return c(r)},NFrss:function(c,r){return c+r},nxScm:function(c,r){return c&r},qJHxR:function(c,r,s){return c(r,s)},jmBcI:t(1327)+t(1837)+"pe: ",mlQAz:function(c,r){return c>>r},VZgyD:function(c,r){return c>=r},YlDlU:function(c,r){return c!==r},INgEF:"koTtc",SlLdb:function(c,r){return c===r},IKnDS:function(c,r){return c>r},AXEUC:t(1028)+t(864),UPwIZ:function(c,r){return c|r},NMfqj:function(c,r){return c<<r},QzGcG:function(c,r){return c<<r},pmyeK:function(c,r){return c|r},eBEhv:function(c,r){return c!==r},MRxFw:function(c,r){return c+r},aVbIb:t(811)+t(864),LTNoc:function(c,r,s){return c(r,s)},loWBb:function(c,r){return c+r},gMGTP:function(c,r){return c+r},zovcz:function(c,r){return c&r},evmsz:function(c,r){return c===r},tDGvJ:function(c,r){return c&r},PCySm:function(c,r){return c>=r},teXqB:function(c,r){return c+r},cguWi:function(c,r){return c+r},beJjv:function(c,r){return c&r},zQnaS:function(c,r){return c|r},gTtip:function(c,r){return c&r},ZKIkN:t(1470),tbSZo:t(902),FdwWD:function(c,r){return c(r)},AWFgZ:function(c,r){return c==r},vPuiL:function(c,r){return c+r},gdhqr:function(c,r){return c!==r},Rteaw:function(c,r){return c&r},yhPDB:function(c,r){return c<<r},xfBsA:function(c,r){return c<<r},sGZqx:function(c,r){return c&r},CZlHQ:function(c,r){return c&r},hjNjz:function(c,r){return c>=r},jFWxZ:function(c,r){return c===r},EiumS:"FztXe",GZyFw:function(c,r){return c(r)},OXILs:function(c,r){return c==r},hSFJF:function(c,r){return c+r},DyhIX:function(c,r){return c+r},pRLAj:function(c,r){return c+r},NJheo:function(c,r){return c+r},lavQy:function(c,r){return c+r},uZLlF:function(c,r){return c&r},SRgLn:function(c,r){return c|r},zgQOk:function(c,r){return c|r},sZukz:function(c,r){return c<<r},fLQRr:function(c,r){return c+r},IAjOR:t(1649)+">",Isvro:function(c,r){return c<r},cjaKT:function(c,r){return c<r},xWpYk:function(c,r){return c<r},ACMmk:function(c,r,s){return c(r,s)},JiRwr:function(c,r){return c<r},vXrsD:function(c,r){return c===r},LnHjL:"THugn",Gyzez:function(c,r){return c>=r},qJtdd:function(c,r){return c+r},KSaDl:function(c,r){return c<r},KXupu:function(c,r){return c<r},CPkea:function(c,r){return c|r},DUMly:function(c,r){return c&r},sCtKW:function(c,r){return c|r},oszrm:function(c,r){return c&r},dmqwX:function(c,r){return c>>r},IYqAm:function(c,r){return c&r},TKJai:function(c,r){return c>>r},OEQGf:function(c,r){return c&r},DVLpv:function(c,r){return c&r},wLSzL:function(c,r){return c|r},cSvJr:function(c,r){return c>=r},yfcxy:function(c,r){return c<=r},MOiOy:function(c,r){return c>=r},orIGV:function(c,r){return c|r},pYhXK:function(c,r){return c/r},bIjwK:t(813),GgbzB:function(c,r){return c&r},NMmFq:function(c,r){return c&r},JeqGJ:function(c,r,s){return c(r,s)},HenDN:function(c,r,s){return c(r,s)},givxn:function(c,r,s){return c(r,s)},EQMMp:function(c,r){return c(r)},FyIeE:function(c,r){return c&r},auVtD:function(c,r){return c<<r},RcwpA:function(c,r){return c<<r},pVWdR:function(c,r){return c&r},rwOVM:function(c,r){return c&r},DCPXx:function(c,r){return c<<r},pqYYA:function(c,r){return c&r},cPRWr:t(619),scgeX:function(c,r){return c(r)},ODDLo:function(c,r){return c&r},dzoXI:function(c,r){return c!==r},BJWVA:"qDoki",JbPIn:t(1876),IVXmt:function(c,r){return c&r},gPZCf:function(c,r){return c&r},lXXFO:function(c,r){return c<<r},uDPER:function(c,r){return c|r},CNcxO:function(c,r){return c<<r},hifbw:function(c,r){return c|r},QxPxF:function(c,r){return c===r},IvStN:function(c,r){return c<r},wovgs:function(c,r){return c<r},GyzJh:function(c,r){return c<r},sqoej:function(c,r){return c<r},RTEoF:function(c,r){return c+r},lBDNJ:function(c,r){return c+r},VCiyU:function(c,r){return c>>>r},BmrfZ:function(c,r){return c>>>r},PbKhy:function(c,r){return c+r},PozIT:function(c,r){return c!==r},nCFhr:function(c,r){return c|r},IZtas:function(c,r){return c>>>r},ccmvc:function(c,r){return c!==r},JkWwp:function(c,r){return c|r},UdxZX:function(c,r){return c>>>r},IZopn:function(c,r){return c!==r},qhyCp:function(c,r){return c|r},nAeIe:function(c,r){return c>>>r},rHYbI:function(c,r){return c&r},VXOGR:function(c,r){return c+r},ARaGo:function(c,r){return c>>>r},QXIpJ:function(c,r){return c<r},xToEG:function(c,r){return c|r},xePJd:function(c,r){return c>>r},VaXkV:t(1775),mZEPc:function(c,r){return c|r},UEvlv:function(c,r){return c|r},qklSo:function(c,r){return c|r},GZjbu:function(c,r){return c<<r},nxhxi:function(c,r){return c<<r},bYnEc:function(c,r){return c|r},mvxTL:function(c,r){return c|r},YztYD:function(c,r){return c<<r},jjzfB:function(c,r){return c|r},QheFL:function(c,r){return c|r},LNVha:function(c,r){return c<<r},jQEyS:function(c,r){return c|r},idlel:function(c,r){return c<<r},xSrUp:function(c,r){return c<<r},tfEcX:function(c,r){return c===r},jArVb:function(c,r){return c|r},tlSNU:function(c,r){return c<<r},VTYNC:function(c,r){return c|r},nWUXV:function(c,r){return c<<r},iXytM:function(c,r){return c<<r},eXEZt:function(c,r){return c&r},bmood:function(c,r){return c>>>r},MJkpx:function(c,r){return c!==r},gxaOM:t(1246),sDzsu:function(c,r){return c<=r},tdnzI:function(c,r){return c|r},JJLdq:function(c,r){return c===r},yHEch:function(c,r){return c===r},ZuyPI:function(c,r){return c&r},tUmBm:function(c,r){return c+r},jsCgf:function(c,r){return c>>>r},OXCSz:function(c,r){return c>>>r},CxeeR:function(c,r){return c>>>r},jFseD:function(c,r){return c<<r},NOUXU:function(c,r){return c|r},IqwYF:function(c,r){return c!==r},uPBaV:t(1814),aPsiE:function(c,r){return c!==r},Qbtrd:function(c,r){return c===r},jmQZe:function(c,r){return c<r},InwrJ:"aPhRM",ZKIIe:function(c,r){return c&r},wIMiq:t(1009),LfaNy:t(1849),IkhQf:function(c,r){return c>>>r},Furgk:function(c,r){return c&r},FPYQf:function(c,r){return c>>>r},JaWiH:function(c,r){return c>>>r},ZWdvu:function(c,r){return c>>>r},xCANA:function(c,r){return c&r},PssxG:function(c,r){return c>>>r},wKjyF:t(1883)+t(1020),YIABy:t(1877)+"OR",zkKlx:t(1151)+t(801),nLiKQ:"CONNECTI"+t(1198),xtTxr:t(1018)+t(401)+"R",GHEBp:function(c,r){return c===r},TUGwA:t(1600),xKUcK:t(607),FEVCf:t(1581),kIJRn:function(c,r){return c||r},NCaMf:function(c,r){return c!==r},MGwHk:t(1637),gzNaB:function(c,r){return c>=r},Zddjg:t(749),wHrpe:function(c,r){return c instanceof r},HytZq:function(c,r){return c+r},jWvob:t(1697)+t(1199),xqXXU:function(c,r){return c===r},nQGgB:t(1716)+t(1687),ImtGc:t(441)+"_EXIST",fZaKL:function(c,r){return c!==r},qVZFr:t(1539),HgBVq:function(c,r,s){return c(r,s)},oLoki:t(1430),mLApU:t(438),QMotC:function(c,r,s){return c(r,s)},JYpKb:t(1813),qNahp:function(c,r,s){return c(r,s)},GmEiH:function(c,r){return c||r},RcuZp:function(c,r){return c!=r},ErXbE:"undefined",obcjT:function(c,r,s,l){return c(r,s,l)},HGAQl:t(1618),Rtltm:function(c,r){return c||r},lPTJX:t(703)+t(784)+"ltiple t"+t(1316)+t(581),jhwPr:function(c,r){return c|r},hgdFX:function(c,r){return c<<r},vSrui:function(c,r){return c&r},qdQvh:function(c,r){return c<<r},UlpqP:function(c,r){return c&r},dbPwT:t(947)+"2",czxCW:function(c,r){return c+r},bQcAU:function(c,r){return c+r},oRWHk:t(608),MCPsQ:t(853),hmBpj:function(c,r){return c<r},DLdgm:t(701),kPMzh:function(c,r){return c<r},LLeBW:function(c,r){return c&r},HglDV:function(c,r){return c===r},NhxcP:function(c,r){return c&r},kNkKk:function(c,r){return c<r},gYacW:function(c,r){return c<=r},ECZEB:function(c,r){return c|r},XPeoa:function(c,r){return c<<r},fRUIX:function(c,r){return c&r},ibnZy:function(c,r){return c&r},BAVJE:function(c,r){return c&r},mNzQX:function(c,r){return c>=r},mWcQm:function(c,r){return c&r},Hjpvn:function(c,r){return c&r},yxCQK:function(c,r){return c<r},uUFYK:function(c,r){return c<r},cjsFB:t(1571),nAqAo:t(764),DGhYV:function(c,r){return c|r},raEET:function(c,r){return c|r},twYlI:function(c,r){return c===r},bHHii:function(c,r){return c+r},Viawu:t(1240)+t(1379),theKo:function(c,r){return c|r},EnZDL:function(c,r){return c+r},kIeyq:function(c,r){return c>>r},taBwh:function(c,r){return c>>r},MBbZx:function(c,r){return c|r},EJYqL:function(c,r){return c-r},XbGcl:"sioLh",lACtz:function(c,r){return c==r},NzOeh:t(765),VJYKv:"AaWVM",HFIom:function(c,r,s,l){return c(r,s,l)},AvusI:function(c,r){return c!=r},DDsrC:t(781),eReSh:"hUZxs",cDYQe:"text/pla"+t(888)+t(1559),NDPFN:function(c,r){return c!==r},xqZBy:t(1005),JXPag:t(1871),jvdxy:t(394),JxZoK:function(c,r){return c||r},Mltvw:"OIgLB",ZZsAo:t(531),DSVvf:function(c,r){return c>=r},OsrIB:t(1764)+t(1653),EmJmS:t(1098),KeviO:t(1099)+"ascript",gJuNk:function(c,r){return c+r},OahJp:t(860),VVlDr:"&jscallback=fron"+t(1190)+"P",zfVLz:t(1047),hKMJB:function(c,r){return c(r)},MttGv:function(c,r){return c(r)},GCstk:t(1221),csSgS:t(689)+t(689)+t(689)+t(689),QCcRV:function(c,r,s,l){return c(r,s,l)},knhtV:t(1785),qechX:t(1455),orBco:function(c,r){return c!==r},PsdSO:t(601),VAFFU:t(1562),GWshr:t(1393),vkrdH:t(1606),yzFnB:t(1616),niROa:function(c,r){return c||r},vxclC:t(1026),Cwrij:function(c,r){return c||r},CtaBY:function(c,r){return c===r},DgXvU:"CULiI",cNOSM:function(c,r){return c||r},pNVgF:t(578),rPzTJ:function(c,r){return c||r},OGuyb:"init QoSDB failed",ZenZm:t(1631),bZOGg:t(1537),ttYwa:t(1137)+"id",CMHPA:t(579),jYdvQ:t(1353),hlkrf:function(c,r){return c>=r},khUzZ:function(c,r){return c<=r},jgikT:function(c,r){return c-r},MAFyl:function(c,r){return c+r},EWzhT:function(c,r){return c<r},rbyqH:t(563),Qkcvf:t(545)+t(876)+"ck",zivgv:t(545)+t(1597)+"k",ZKyLn:t(545)+t(910)+t(817),egGgm:t(1132),BHJok:t(770),tcpKU:function(c,r){return c||r},nXvPH:t(1865),aholS:function(c){return c()},riNaB:function(c,r){return c!==r},QjFce:t(681),mThrb:t(1805),TABTV:function(c){return c()},RwvDn:function(c,r){return c instanceof r},UyAgg:t(525)+t(1100),vMaVb:t(525)+t(1100)+t(1145)+t(624),BgHTu:t(1188)+"e",gWaaF:function(c){return c()},PjWvB:function(c,r){return c(r)},dOxrq:function(c,r){return c&r},RubxM:function(c,r){return c+r},eDOft:function(c,r){return c(r)},CcKGP:function(c,r){return c&r},RfNTY:function(c,r){return c!==r},xiKAG:"XzAdl",PsykK:function(c,r){return c||r},BkHJe:function(c,r){return c>>>r},EsDNH:function(c,r){return c===r},OVsWw:t(1786),VURIe:function(c,r){return c(r)},DBOmQ:function(c,r){return c+r},DJAhk:function(c,r){return c+r},sYvgw:t(1811)+t(1781)+"ge: ",eOZqX:t(1148),HkIkg:t(1804),RgxLT:function(c,r){return c>r},WIoVg:t(404)+"too large",gYwjH:function(c,r){return c>=r},atgAk:function(c,r,s,l){return c(r,s,l)},amQgt:function(c,r,s){return c(r,s)},QtanS:function(c,r){return c<<r},tRPVW:"1|4|3|2|0",lJUVe:function(c,r){return c+r},txdvE:function(c,r){return c<r},hyYdv:function(c,r){return c+r},AdOrW:function(c,r){return c>>>r},gFNPW:t(640),RbDAZ:function(c,r){return c|r},GRbyk:function(c,r){return c|r},btbGc:function(c,r){return c|r},iOcsK:function(c,r){return c<<r},eltMo:function(c,r){return c+r},BbfGb:function(c,r){return c|r},IvzmA:function(c,r){return c<<r},Wlomh:function(c,r){return c+r},UoHBI:function(c,r){return c(r)},AROyZ:t(443),ueXLe:t(948)+t(557)+"s",kyGhu:t(948)+t(1304)+"t",EklsJ:"wLYpb",wGFXx:function(c,r){return c&r},dsExu:function(c,r){return c>>>r},rTVJl:function(c,r){return c&r},ywFIM:function(c,r){return c+r},eyCQL:function(c,r){return c+r},wfEzj:function(c,r){return c&r},emrgh:function(c,r){return c+r},zvXtM:function(c,r){return c&r},YAbpn:function(c,r){return c-r},JuLHe:function(c,r){return c|r},ocDjY:function(c,r){return c<<r},dAVGh:function(c,r){return c&r},YSsMS:function(c,r){return c&r},wwsAq:function(c,r){return c+r},qoMdY:function(c,r,s){return c(r,s)},vQEMW:function(c,r,s){return c(r,s)},bKTyr:function(c,r,s){return c(r,s)},hCoWw:function(c,r,s){return c(r,s)},jHeFj:t(1592),UUOLy:function(c,r){return c+r},YNlBG:function(c,r){return c>>>r},pJVds:function(c,r){return c>>>r},xmNwi:function(c,r){return c>>>r},ExKuV:function(c,r){return c<r},HlZwS:function(c,r){return c|r},wopcm:function(c,r,s,l){return c(r,s,l)},jsDFi:t(1544)+t(1671),YXfYc:function(c,r,s,l){return c(r,s,l)},FvMgN:function(c,r,s,l){return c(r,s,l)},HVsiL:t(935),PSPaQ:function(c,r,s,l){return c(r,s,l)},GzkaF:function(c,r,s,l){return c(r,s,l)},vtDkr:t(1589),RKqzM:function(c,r,s){return c(r,s)},qobPn:t(1624)+"t",DPxmm:"stop imm"+t(1161)+t(1669)+"ct",WLeYZ:function(c,r){return c===r},HXabM:"LdZgc",PPwRF:function(c,r,s){return c(r,s)},pKcSO:"ALL",bvPuT:function(c,r,s,l){return c(r,s,l)},cppiN:t(752),ElqOl:function(c,r,s,l){return c(r,s,l)},dQvBu:t(1766),ErWap:function(c,r){return c(r)},CrBNH:"setcursor",tMQlZ:function(c,r){return c===r},xyTdW:t(750),CdIya:"avaeP",jXVWV:t(1269),eWzcl:t(883),zKyRS:function(c,r){return c||r},fgkQt:"timeout",aPBby:function(c,r){return c(r)},mFkqf:t(545)+t(1526),ZoirO:function(c,r){return c(r)},qFRzS:t(545)+t(774),XXIOk:function(c,r,s,l){return c(r,s,l)},JLNXT:t(566)+"s",ZjuIe:function(c,r,s){return c(r,s)},tdkBe:function(c,r,s){return c(r,s)},XThjh:function(c,r){return c>r},IGMZr:function(c,r){return c>r},iNava:t(474),nnapE:function(c,r){return c+r},FQjVn:function(c){return c()},EUfSR:function(c){return c()},oWmrL:function(c){return c()},ufthl:function(c){return c()},kRKZh:function(c,r){return c===r},uzurb:function(c){return c()},UoGEU:function(c){return c()},kqtSW:t(638),FDhWY:function(c,r){return c===r},mMuat:t(1080),vnecf:function(c,r){return c===r},xAnJe:function(c,r){return c!==r},uTkHS:function(c,r,s){return c(r,s)},chZvk:function(c){return c()},XUyxf:function(c,r,s){return c(r,s)},bENXa:function(c,r){return c===r},BYlVf:function(c,r,s){return c(r,s)},XCEym:"blocked",GVNgV:t(1574),TzZed:function(c,r){return c===r},DWErH:t(872),oMMsi:"auto",INGIp:function(c,r){return c+r},czlad:function(c,r){return c!==r},WnOwU:function(c,r,s){return c(r,s)},kyDiC:"bye",VeCKV:function(c,r){return c(r)},DRmLz:t(1107),fFWNW:t(1647),ggdrc:t(1497)+t(1388),EJUeP:"pbbp2",qurYy:function(c,r){return c===r},exPEG:function(c,r){return c(r)},syOCI:t(1652)+t(1174)+t(986)+t(1334)+t(1022)+t(711)+"is undef"+t(1051),bFlAN:function(c,r,s){return c(r,s)},KTmru:function(c,r,s){return c(r,s)},FpexW:function(c,r,s){return c(r,s)},PeObR:t(627)+t(1564)+t(1535)+t(1787),BDZmQ:t(1746),uwHXY:t(1413),ravoT:t(659),EnGZn:"pageshow",QwNdd:t(949),FiJmd:function(c,r){return c!==r},lGkec:function(c,r){return c!==r},xwoGe:t(1329),UlwdF:t(945),zGPVt:t(1357),OvrQE:t(492)+"d",iYmNM:"please provide b"+t(717)+t(417)+t(572),uIiKK:function(c,r){return c==r},jOYki:function(c){return c()},aRJSK:"fws_1.0.0",lWJEl:function(c,r){return c||r},GHWKj:function(c,r,s){return c(r,s)},mhlfl:"start",EwMTo:function(c,r){return c>r},qDAgX:function(c,r,s){return c(r,s)},pPual:function(c,r){return c!==r},rGTBX:t(1029),xEXRm:function(c,r){return c!==r},JPZLo:t(1308),CSGrR:function(c,r){return c*r},BXfZS:function(c,r,s){return c(r,s)},Nhrpm:function(c,r,s){return c(r,s)},tJUZA:t(627)+t(1236)+t(1624)+t(1829)+t(995),pztQL:t(901),lWhai:t(1034)+" try rec"+t(1491)+"g",RkUUI:function(c,r){return c===r},UzHlg:t(1768),STaoF:t(1722)+"4",rykxa:"0|2|4|3|1",YilxO:function(c,r,s){return c(r,s)},Ydzjq:function(c,r,s){return c(r,s)},kaLDg:function(c,r,s){return c(r,s)},MnVWO:function(c,r,s){return c(r,s)},gNBUF:t(1328),wAbus:function(c,r){return c!==r},kracM:t(1823),cRtvq:t(1257),nqrZx:function(c,r){return c===r},OzVQB:t(1348)+t(1002)+"y closed",QVauF:t(1348)+t(1031)+t(795)+t(886)+"ed",LWUbN:function(c,r){return c&r},tGomB:function(c,r){return c!==r},NdkfR:t(1556),zNfmS:function(c,r){return c==r},Qjzgq:t(1652)+t(1752)+t(1667)+t(1881)+"a must b"+t(1408)+t(1251)+t(1642)+"ffer",qoOlY:function(c,r){return c==r},OksLq:function(c,r){return c(r)},HfMwj:function(c,r){return c||r},Aebvg:function(c,r){return c===r},JYpew:function(c,r){return c<r},EWtcu:t(1104),KcFki:function(c,r){return c!==r},iCADZ:function(c,r){return c==r},NBysE:t(821)+"econnect"+t(503),uPMRZ:t(1621),XDrzg:"9|7|1|2|"+t(605)+t(1389),keGyB:function(c,r,s,l){return c(r,s,l)},htoDn:t(1195),cGTFP:function(c,r,s,l){return c(r,s,l)},GdjZV:t(1588),HOzfW:"service-"+t(1588),cAFOF:function(c,r,s,l){return c(r,s,l)},rrOnf:t(1476),grhwC:t(794),ebEBp:function(c,r){return c===r},csCXO:t(1817),QkYah:t(544),quqHD:function(c,r,s){return c(r,s)},TJCDe:t(602),gIhIG:t(1847),aAzpq:"\0\0\0\0\0\0\0\0",DlecN:function(c,r){return c*r},PCHaW:function(c,r){return c/r},noBLq:t(1048),RUsEd:function(c,r){return c===r},XyWPk:function(c,r){return c===r},tLYUz:function(c,r){return c===r},DxTBC:t(1211)+t(1809)+t(529)+"pe",TMMNx:function(c,r){return c===r},zhjJN:t(520),inBZa:function(c,r){return c!=r},VDAvw:t(415)+t(848)+t(1834),KaGAx:t(564)+t(1869)+t(429),mpqZm:function(c,r){return c!=r},LJeyj:function(c,r){return c===r},ijupe:t(1317)+t(1016)};Gt.r(Ne),Gt.d(Ne,{FWS:()=>rm,CustomErrorEvent:()=>Il,createCloseEvent:()=>bt,ReconnectEvent:()=>Sl,createErrorEvent:()=>ht,decodedFrame:()=>cn,createOpenEvent:()=>Pl,CustomCloseEvent:()=>Al,createReconnectEvent:()=>Pa,FrontierMessageEvent:()=>Tl,encodeFrame:()=>jt,createMessageEvent:()=>Rl,OpenEvent:()=>Cl,ErrorCode:()=>ln,Event:()=>dr,MessageEvent:()=>kl});let n="";function i(c=""){let r=t,s="02",l=""+Date[r(427)](),h=n||(n=e[r(1369)](f,c)),g=Math[r(956)]()[r(728)](16)[r(1116)](-6);return e.ZnUtx(e[r(558)](e.zzMqK(s,l),h),g)}function o(){let c=t;return e.wYoCi(1e4,Date[c(427)]())+Math[c(1779)](e[c(1701)](1e4,Math[c(956)]()))}function a(c){let r=t;return e.bruQg(Array(8)[r(1089)]("0"),e.SYIYk(parseInt,c,10).toString(2))[r(1116)](-8)}function d(c){let r=t;return e[r(973)](e.zpYBR(Array,4)[r(1089)]("0"),e[r(1750)](parseInt,c,2)[r(728)](16)).slice(-4)}function u(c){let r=t,s=c[r(1432)](/\./)[r(1783)](g=>a(g)),l=[];return l[0]=e[r(621)](d,s[0]+s[1]),l[1]=e[r(1369)](d,s[2]+s[3]),[e.EUoig,e[r(981)],e[r(981)],e[r(981)],e[r(981)],e[r(975)],l[0],l[1]][r(1089)]("")}function f(c){let r=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(737)](c),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(737)](c);return s?e[r(1369)](u,c):l?x(c):r(689)+"00000000"+r(689)+r(689)}function x(c){let r=t,s="",l=[],h=0,g=0,y=!0,k=e[r(981)];if(e[r(1401)](c[r(723)]("::"),-1)){let w=c[r(1432)]("::");for(let H=0;H<w.length;H++)if(e.uhqTk(e[r(1326)],e[r(722)]))_0x216265=e[r(914)](e[r(1249)](e.LQoTO(15,_0x511335),12)|e[r(951)](63,_0x21c7bb)<<6,e[r(951)](63,_0x491cee)),e.lzoNu(_0x5252cd,2048)||_0x2f2fe3>=55296&&e[r(1603)](_0x39ac55,57343)?_0x17fe2c+=_0x488ddf:(_0x1e0006+=e[r(1248)](_0x276d99,_0x19ff92),_0x31eb48+=2);else{let F=w[H];if(e.hEtXr(F[r(723)](":"),0)){let W=F[r(1432)](":");y&&(h=W[r(1407)]),g+=W[r(1407)];for(let K=0;K<W.length;K++)if(e[r(1608)](4,W[K].length)){let ce=k[r(582)+"g"](0,4-W[K][r(1407)]),be=ce[r(803)](W[K]);l.push(be)}else l.push(W[K]);y=!1}else{if(e.nvxMo(4,F[r(1407)])){let W=k[r(582)+"g"](0,e[r(1862)](4,F[r(1407)])),K=W[r(803)](F);l[r(489)](K)}else l.push(F);y&&(h+=1),g+=1,y=!1}}let O="";for(let H=0;e[r(1134)](H,e[r(1293)](8,g));H++)O=O[r(803)](k);for(let H=0;e[r(1857)](H,l[r(1407)]);H++)if(e.zpBRP(H,h)){if(e[r(1608)](e.hYIwZ,e[r(818)]))return new _0x374173(_0x404df7,{code:_0x14fa1e,reason:_0x5f3916,wasClean:_0x2149ab,willReconnect:_0x54d380});s=s[r(803)](O),s=s[r(803)](l[H])}else s=s.concat(l[H]);return s}{let w=c[r(1432)](":");for(let O=0;e.HlNqE(O,w[r(1407)]);O++){let H=w[O];if(e.nvxMo(4,w[O][r(1407)])){let F=k[r(582)+"g"](0,e[r(1324)](4,w[O].length)),W=F.concat(H);s=s[r(803)](W)}else s=s[r(803)](H)}return s}}function p(c,r){let s=t,l={MLuor:function(h,g,y){return e.EDden(h,g,y)},UOfuT:function(h,g){return h+g}};if(e[s(1584)](e[s(706)],e[s(773)])){let h=c[s(1484)];if(h!==void 0)if(e.pjEby(e[s(1410)],s(1689)))me(r,10),e.hGWuJ(z,r,h);else{let{offset:y}=_0x376a76(_0x5064fd,_0x47fc2a);_0xd9eea6=y;let k={cursor_name:"",cursor:0,service:0},{value:w,offset:O}=l[s(1160)](_0x13390b,_0x3c3a81,_0x4ed646);k[s(935)]=w,_0x1bd2f6=O;let{value:H,offset:F}=l[s(1160)](_0x3ddbf6,_0x4c180d,_0x4661ca);_0x4672da=F,k[s(464)+s(830)]=_0x152c5f(_0xc03002,_0x423064,l[s(1376)](_0x29b3fd,H)),_0x402e23+=H;let{value:W,offset:K}=_0x39bda6(_0x318464,_0x64e29);k.cursor=W[s(1656)](),_0x3052d4=K,_0x3b717a.push(k)}let g=c[s(715)];e[s(1584)](void 0,g)&&(me(r,18),e[s(1605)](z,r,g))}else return this._socket.protocol}function m(c){let r=t,s={YXIFG:function(l,h){return e[B(914)](l,h)},ohfIR:function(l,h){return l<<h},pePPF:function(l,h){return e[B(1021)](l,h)},TqZmb:function(l,h){return e[B(714)](l,h)},PgtZC:function(l,h){return e.OUQwo(l,h)},eczYS:function(l,h){return l|h},aQvbA:function(l,h){return e[B(1215)](l,h)},AQHrQ:function(l,h){return e[B(1159)](l,h)},jsEkl:function(l,h){return e[B(744)](l,h)}};if(e.nvxMo(e[r(527)],e.hVOJI)){let l={};e:for(;!e[r(1369)](V,c);){let h=e[r(1506)](he,c);switch(e.BndxZ(h,3)){case 0:break e;case 1:l.key=C(c,he(c));break;case 2:l[r(715)]=e[r(1760)](C,c,e[r(621)](he,c));break;default:e[r(1070)](T,c,7&h)}}if(e[r(1338)](void 0,l[r(1484)]))throw new Error(e[r(903)]);if(e[r(1271)](void 0,l.value))throw new Error(e[r(434)]);return l}else{let l=new _0x118435(s[r(1340)](s[r(1340)](s.YXIFG(s.ohfIR(_0x4ee840[s[r(445)](_0x2cd13e,4)],24),s[r(772)](_0x4cd135[s[r(1280)](_0x22b02f,5)],16)),s[r(584)](_0x3838f1[_0x275428+6],8)),_0x5b6c0f[_0x54ee3f+7]),s[r(1200)](s[r(1340)](s[r(1859)](s[r(584)](_0x66de74[_0x228c18+0],24),_0x50f557[s[r(1609)](_0x4020a0,1)]<<16),s[r(584)](_0x25a5c[s.TqZmb(_0x4720dc,2)],8)),_0x9abfa8[s[r(768)](_0x4c6636,3)]),!0);return _0x3fd716+=8,{value:l,offset:s[r(445)](_0x59c8ad,8)}}}function v(c){let r=t;if(e[r(1584)](r(1867),r(1448))){let s=e[r(1516)](P);return _(c,s),e.zpYBR(N,s)}else _0x4d9545.set(_0x592938,_0x5a361a),_0x1bc6ce[r(598)](_0x1112e2,_0x41ad0d)}function _(c,r){let s=t,l={QOPUj:function(ge,Ge){return e[B(405)](ge,Ge)},mgIrM:function(ge,Ge){return e.pNsGs(ge,Ge)}},h=c[s(677)];e[s(1608)](void 0,h)&&(e[s(1750)](me,r,8),e[s(1710)](yt,r,h));let g=c.LogID;e[s(1584)](void 0,g)&&(e[s(1605)](me,r,16),yt(r,g));let y=c[s(935)];if(e[s(1841)](void 0,y))if(s(1832)===e.GDKnX){if(l.QOPUj(void 0,_0x5c8063))this[s(1806)+"rs"]={};else if(_0x230250===void 0)this[s(1806)+"rs"][_0x1124d3]=null;else{let ge=this[s(1806)+"rs"][_0x502d44];if(ge)for(let Ge=0;l[s(466)](Ge,ge[s(1407)]);)l[s(777)](ge[Ge].fn,_0x52bd83)?ge[s(1590)](Ge,1):++Ge}return this}else e.qdxKN(me,r,24),e.guCbo(yt,r,e[s(1855)](R,y));let k=c.method;e[s(742)](void 0,k)&&(me(r,32),e[s(1070)](yt,r,e[s(1248)](R,k)));let w=c[s(967)];if(e.LIDwa(void 0,w))for(let ge of w){e[s(1760)](me,r,42);let Ge=e[s(1682)](P);p(ge,Ge),e.xWQTf(me,r,Ge[s(1840)]),e[s(1880)](q,r,Ge),e[s(1369)](D,Ge)}let O=c[s(700)+s(767)];O!==void 0&&(e[s(1070)](me,r,50),e[s(1863)](z,r,O));let H=c[s(480)+s(473)];e[s(538)](void 0,H)&&(e[s(1241)](me,r,58),z(r,H));let F=c[s(1627)];F!==void 0&&(e[s(1373)](me,r,66),e[s(1033)](me,r,F[s(1407)]),e[s(1181)](ae,r,F));let W=c.LogIDNew;W!==void 0&&(e[s(912)](me,r,74),z(r,W));let K=c[s(832)+"ming"];e[s(1521)](void 0,K)&&(e.rTGvF(me,r,82),z(r,K));let ce=c[s(467)];e[s(780)](void 0,ce)&&(e[s(1750)](me,r,90),e[s(1382)](z,r,ce));let be=c[s(616)+"e"];e[s(1521)](void 0,be)&&(me(r,96),e[s(1033)](yt,r,e[s(812)](R,be)))}function b(c){return e[t(1855)](S,M(c))}function S(c){let r=t,s={LZDQM:function(h,g,y){return e[B(1513)](h,g,y)},UlCNH:function(h,g){return h|g},eyJJt:function(h,g){return e[B(951)](h,g)}},l={};e:for(;!e.bzQqH(V,c);)if(e.uhqTk(r(913),r(913))){let h=e[r(1506)](he,c);switch(e[r(604)](h,3)){case 0:break e;case 1:l[r(677)]=e[r(437)](Ct,c,!0);break;case 2:l.LogID=e[r(1662)](Ct,c,!0);break;case 3:l[r(935)]=e.bzQqH(he,c);break;case 4:l[r(1861)]=e[r(812)](he,c);break;case 5:{let g=e[r(1369)](I,c);(l[r(967)]||(l[r(967)]=[]))[r(489)](e[r(1253)](m,c)),c.limit=g;break}case 6:l[r(700)+r(767)]=e[r(1341)](C,c,he(c));break;case 7:l[r(480)+r(473)]=C(c,he(c));break;case 8:l[r(1627)]=e[r(1182)](re,c,e[r(621)](he,c));break;case 9:l[r(1032)]=e[r(1760)](C,c,he(c));break;case 10:l[r(832)+r(805)]=C(c,e.bzQqH(he,c));break;case 11:l[r(467)]=C(c,e[r(1405)](he,c));break;case 12:l[r(616)+"e"]=e.iZVZq(he,c);break;default:T(c,7&h)}}else s.LZDQM(_0x39f76d,_0xfb2312,s[r(1197)](s.eyJJt(127,_0x15f062),128)),_0x1f3aa3>>>=7;if(e[r(1788)](void 0,l[r(677)]))throw new Error(e[r(1039)]);if(e[r(694)](void 0,l[r(839)]))throw new Error(e[r(1365)]);if(e[r(1149)](void 0,l[r(935)]))throw new Error(e.QVwxo);if(e[r(1681)](void 0,l[r(1861)]))throw new Error(e[r(590)]);return l}function I(c){let r=t,s=e[r(895)](he,c),l=c[r(1840)];return c[r(1840)]=e[r(1391)](c[r(1344)],s),l}function T(c,r){let s=t;switch(r){case 0:for(;e.nxScm(128,e[s(1369)](ee,c)););break;case 2:e.oCleK(J,c,he(c));break;case 5:J(c,4);break;case 1:e[s(1569)](J,c,8);break;default:throw new Error(e[s(1391)](e.jmBcI,r))}}function R(c){let r=t;return c|=0,{low:c,high:e[r(565)](c,31),unsigned:e[r(1739)](c,0)}}let E=[];function P(){let c=t,r=E.pop();return r?(r[c(1344)]=r[c(1840)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(c){let r=t;if(e.YlDlU(e[r(707)],e[r(707)]))return _0x4b2217||(_0x447f8=[_0x1b8067[r(875)+"e"].advance,_0x320e69[r(875)+"e"].continue,_0x5a0562[r(875)+"e"][r(1884)+r(720)+"ey"]]);E[r(489)](c)}function M(c){return{bytes:c,offset:0,limit:c.length}}function N(c){let r=t,s=c.bytes,l=c.limit;return e[r(917)](s[r(1407)],l)?s:s[r(1731)](0,l)}function J(c,r){let s=t;if(e.IKnDS(c[s(1344)]+r,c.limit))throw new Error(e[s(923)]);c[s(1344)]+=r}function V(c){let r=t;return c[r(1344)]>=c[r(1840)]}function se(c,r){let s=t,l={RzvOw:function(h,g){return e[B(914)](h,g)},bFxaz:function(h,g){return e[B(1030)](h,g)},bVzLc:function(h,g){return e[B(1030)](h,g)},XIVQl:function(h,g){return e[B(612)](h,g)},FWGnF:function(h,g){return e[B(1611)](h,g)},eTkvP:function(h,g){return e[B(985)](h,g)},SdIea:function(h,g){return e[B(1030)](h,g)},pgXKM:function(h,g){return e[B(612)](h,g)}};if(e[s(1461)](s(966),s(779))){let h=c[s(606)],g=c[s(1344)],y=c.limit,k=e.MRxFw(g,r);if(k>h[s(1407)]){let w=new Uint8Array(e[s(1701)](2,k));w[s(598)](h),c[s(606)]=w}return c[s(1344)]=k,k>y&&(c[s(1840)]=k),g}else return new _0x4f857d(l[s(1063)](l.bFxaz(l.bVzLc(_0x322baa[4]<<24,l[s(868)](_0x7aaddf[5],16)),l.FWGnF(_0x40ad7a[6],8)),_0x1316cf[7]),l[s(1555)](l[s(562)](l.XIVQl(_0x131fcd[0],24)|l.pgXKM(_0x26b74a[1],16),l[s(868)](_0x4c7abe[2],8)),_0xc321c7[3]),_0x4e20f0)}function X(c,r){let s=t,l=c[s(1344)];if(e[s(1685)](e.eLWJZ(l,r),c[s(1840)]))throw new Error(e[s(982)]);return c.offset+=r,l}function re(c,r){let s=t,l=e.LTNoc(X,c,r);return c[s(606)][s(1731)](l,e[s(1175)](l,r))}function ae(c,r){let s=t,l=e.NmRbC(se,c,r.length);c[s(606)].set(r,l)}function C(c,r){let s=t,l=e[s(1181)](X,c,r),h=String[s(940)+s(1738)],g=c[s(606)],y="\uFFFD",k="";for(let w=0;e[s(1578)](w,r);w++){let O=g[e[s(1153)](w,l)],H,F,W,K;e[s(1338)](e[s(1124)](128,O),0)?k+=e[s(1405)](h,O):e.evmsz(e.tDGvJ(224,O),192)?e[s(1377)](e.vvAEX(w,1),r)?k+=y:(H=g[e[s(609)](e[s(692)](w,l),1)],e[s(927)](192,H)!==128?k+=y:(K=e.zQnaS(e.NMfqj(e[s(586)](31,O),6),63&H),e.HlNqE(K,128)?k+=y:e[s(742)](e[s(673)],e.tbSZo)?(k+=e[s(1554)](h,K),w++):_0x41fb50[s(548)](_0x2a2c88))):e[s(1422)](240&O,224)?w+2>=r?k+=y:(H=g[e.vPuiL(e[s(1021)](w,l),1)],F=g[e[s(1202)](e[s(622)](w,l),2)],e[s(1058)](e[s(820)](e[s(985)](H,e[s(1306)](F,8)),49344),32896)?k+=y:(K=e[s(1215)](e.xfBsA(e[s(1734)](15,O),12),e[s(513)](63,H)<<6)|63&F,K<2048||e.hjNjz(K,55296)&&e[s(1603)](K,57343)?k+=y:e[s(1502)](e.EiumS,e[s(1885)])?(k+=e[s(799)](h,K),w+=2):(_0x1b93f0+=e.SBOcx(_0x44628f,_0x21bfca),_0x2315fb++))):e[s(1213)](e[s(1124)](248,O),240)?e[s(1481)](e[s(1421)](w,3),r)?k+=y:(H=g[e[s(1372)](e[s(862)](w,l),1)],F=g[e.pRLAj(w+l,2)],W=g[e.NJheo(e[s(804)](w,l),3)],e[s(1521)](e.uZLlF(e[s(1540)](e[s(914)](H,e.ztlMI(F,8)),e.xfBsA(W,16)),12632256),8421504)?k+=y:(K=e[s(1493)](e[s(451)](e[s(825)](7,O),18),e.sZukz(e[s(1734)](63,H),12))|e[s(1092)](63&F,6)|63&W,K<65536||K>1114111?k+=y:(K-=65536,k+=h(e[s(1021)](K>>10,55296),e.fLQRr(e[s(586)](1023,K),56320)),w+=3))):k+=y}return k}function z(c,r){let s=t,l=r[s(1407)],h=0;for(let k=0;e.Isvro(k,l);k++){let w=r[s(1431)+"At"](k);w>=55296&&e.AoCAt(w,56319)&&e[s(547)](k+1,l)&&(w=e[s(1237)](e[s(1611)](w,10),r[s(1431)+"At"](++k))-56613888),h+=e[s(1134)](w,128)?1:e.cjaKT(w,2048)?2:e[s(549)](w,65536)?3:4}e[s(1522)](me,c,h);let g=se(c,h),y=c[s(606)];for(let k=0;e.JiRwr(k,l);k++)if(e[s(969)](s(1284),e[s(1848)]))this[s(979)][s(1674)]&&_0x2630d6.log[s(662)](_0x1eb31e,[e[s(735)],..._0x30e230]);else{let w=r[s(1431)+"At"](k);e[s(1189)](w,55296)&&w<=56319&&e[s(1404)](k,1)<l&&(w=e[s(1237)](e[s(1306)](w,10),r[s(1431)+"At"](++k))-56613888),e[s(472)](w,128)?y[g++]=w:(e[s(1135)](w,2048)?y[g++]=e[s(963)](e[s(1464)](e.mlQAz(w,6),31),192):(w<65536?y[g++]=e[s(1310)](e.oszrm(e[s(534)](w,12),15),224):(y[g++]=e[s(806)](e[s(1471)](w,18),7)|240,y[g++]=e[s(1672)](e[s(534)](w,12),63)|128),y[g++]=e[s(828)](w>>6,63)|128),y[g++]=e[s(1105)](e[s(586)](63,w),128))}}function q(c,r){let s=t,l=e[s(1382)](se,c,r.limit),h=c[s(606)],g=r[s(606)];for(let y=0,k=r[s(1840)];y<k;y++)h[y+l]=g[y]}function ee(c){let r=t;return c.bytes[e[r(1241)](X,c,1)]}function He(c,r){let s=t;if(e.pjEby(e[s(702)],s(526))){let l=e[s(1341)](se,c,1);c[s(606)][l]=r}else{if(e.hNVGY(_0x344ff1,_0x38a9b3))return _0x1bf3b2?_0x4050f8:_0x5bf51b;if(_0x471fd5){if(e[s(1194)](_0x2c3fe9,_0x24310f))return _0x35f3f7}else{if(e[s(1224)](_0x1d32ee,-_0x2f2158))return _0x15af41;if(e[s(1563)](_0x20b1ba+1,_0x2745d9))return _0x245250}return _0x522eff[s(523)](e.UPwIZ(_0x3d09af%_0x13046f,0),e.orIGV(e[s(1566)](_0x1dab81,_0x4896d8),0),_0x280060)}}function he(c){let r=t,s=0,l=0,h;do h=ee(c),s<32&&(l|=e[r(1076)](127,h)<<s),s+=7;while(e[r(824)](128,h));return l}function me(c,r){let s=t;for(r>>>=0;r>=128;)e[s(1561)](He,c,e.Rteaw(127,r)|128),r>>>=7;e[s(422)](He,c,r)}function Ct(c,r){let s=t,l=0,h=0,g=0,y;if(y=e.EQMMp(ee,c),l=e[s(1648)](127,y),128&y&&(y=ee(c),l|=e[s(890)](127&y,7),128&y&&(y=e[s(1253)](ee,c),l|=e[s(908)](e[s(731)](127,y),14),e[s(1680)](128,y)&&(y=e[s(1248)](ee,c),l|=e[s(855)](e.nxScm(127,y),21),e[s(1464)](128,y)&&(y=ee(c),h=e[s(1604)](127,y),e.pqYYA(128,y))))))if(e[s(405)](e[s(1445)],s(619))){if(y=e[s(1714)](ee,c),h|=e[s(1140)](127,y)<<7,128&y)if(e.dzoXI(e.BJWVA,e[s(889)]))y=e[s(1177)](ee,c),h|=e[s(908)](e[s(1793)](127,y),14),e[s(904)](128,y)&&(y=e.hNVGY(ee,c),h|=e.lXXFO(127&y,21),e.gPZCf(128,y)&&(y=ee(c),g=127&y,128&y&&(y=ee(c),g|=e.RcwpA(e.oszrm(127,y),7))));else return this._ws?this._ws[s(909)+"ns"]:""}else return e[s(558)](_0x3b3a8a(4)[s(1089)]("0"),e[s(620)](_0x3eca75,_0x4a41ce,2)[s(728)](16))[s(1116)](-4);return{low:e[s(1543)](l,e[s(571)](h,28)),high:e[s(604)](h,4)|g<<24,unsigned:r}}function yt(c,r){let s=t,l=e[s(633)](r[s(1668)],0),h=e[s(1727)](e[s(604)](r.low,28),e[s(1249)](r.high,4))>>>0,g=e[s(633)](r[s(1256)],24),y=g===0?e.QxPxF(0,h)?l<16384?e[s(1143)](l,128)?1:2:e[s(894)](l,2097152)?3:4:e[s(1585)](h,16384)?e[s(1578)](h,128)?5:6:e[s(776)](h,2097152)?7:8:e[s(1402)](g,128)?9:10,k=se(c,y),w=c[s(606)];switch(y){case 10:w[e[s(1591)](k,9)]=e[s(1464)](e.fFwDn(g,7),1);case 9:w[e.loWBb(k,8)]=e.ogUvf(9,y)?e[s(1540)](128,g):e[s(1140)](127,g);case 8:w[e[s(1006)](k,7)]=e[s(1356)](8,y)?e[s(796)](h,21)|128:e.BmrfZ(h,21)&127;case 7:w[e[s(1709)](k,6)]=e[s(393)](7,y)?e[s(435)](e.IZtas(h,14),128):e[s(796)](h,14)&127;case 6:w[e[s(1237)](k,5)]=e[s(631)](6,y)?e.JkWwp(h>>>7,128):e.tDGvJ(h>>>7,127);case 5:w[k+4]=e.EVJiD(5,y)?e[s(963)](128,h):e[s(1745)](127,h);case 4:w[e[s(973)](k,3)]=e[s(393)](4,y)?e[s(963)](e[s(1163)](l,21),128):e.CZlHQ(e[s(796)](l,21),127);case 3:w[k+2]=e[s(1162)](3,y)?e.qhyCp(e[s(1311)](l,14),128):e[s(852)](e[s(604)](l,14),127);case 2:w[e[s(1263)](k,1)]=e.pjEby(2,y)?e[s(985)](l>>>7,128):e.CZlHQ(e[s(567)](l,7),127);case 1:w[k]=e[s(1461)](1,y)?e[s(963)](128,l):e[s(824)](127,l)}}function cn(c){return e.zpYBR(b,c)}function jt(c){return e[t(1508)](v,c)}let dn=65536,ai=e[t(1623)],ye=e[t(1792)](dn,dn),Oe=e[t(919)](ye,ye),cr=e[t(639)](Oe,2),Fe=String[t(875)+"e"][t(1431)+"At"];class xe{constructor(r,s,l){let h=t;e[h(538)](e[h(819)],e[h(819)])?(e[h(1001)](_0x43d48c,65536)?_0x18c3ca[_0x5a50e4++]=e[h(927)](e[h(1471)](_0x525bff,12),15)|224:(_0x314178[_0xeda403++]=e[h(1793)](e[h(565)](_0x4e1fdc,18),7)|240,_0x6a9fa5[_0x4fdbf2++]=e[h(1707)](e[h(1604)](e.dmqwX(_0x54cbfb,12),63),128)),_0x4c7e47[_0x279eb2++]=e[h(963)](e[h(1673)](_0x1fefa4,6)&63,128)):(this[h(1698)]=!0,this[h(1668)]=0|r,this.high=e[h(1242)](0,s),this.unsigned=!!l)}static[t(1698)](r){return r&&e.pkHJm(!0,r.isLong)}static[t(523)](r,s,l){return new xe(r,s,l)}static fromBytes(r,s,l){let h=t;return l?xe[h(1437)+h(1126)](r,s):xe[h(1437)+h(646)](r,s)}static[t(1437)+t(1126)](r,s){let l=t;return new xe(e[l(1265)](e.pmyeK(e[l(1715)](r[0],e[l(1879)](r[1],8)),e[l(594)](r[2],16)),e[l(1761)](r[3],24)),e[l(1086)](e[l(1525)](r[4],e.YztYD(r[5],8)),r[6]<<16)|r[7]<<24,s)}static[t(1437)+t(646)](r,s){let l=t;return new xe(e[l(963)](e[l(900)](e.QheFL(e[l(1306)](r[4],24),r[5]<<16),e.LNVha(r[6],8)),r[7]),e[l(1707)](e[l(1400)](e[l(546)](e[l(1371)](r[0],24),e[l(1012)](r[1],16)),r[2]<<8),r[3]),s)}static[t(1843)](r){let s=t;return e[s(1747)](r,ai)?vl:new xe(e[s(1163)](e.jArVb(e.xToEG(e[s(1517)](Fe[s(444)](r,0),e[s(1666)](Fe[s(444)](r,1),8)),Fe.call(r,2)<<16),e[s(1664)](Fe[s(444)](r,3),24)),0),e[s(1163)](e.zQnaS(e[s(727)](Fe[s(444)](r,4),e.nWUXV(Fe.call(r,5),8))|e[s(1666)](Fe[s(444)](r,6),16),e[s(1395)](Fe[s(444)](r,7),24)),0),!0)}[t(983)](){let r=t;return String[r(940)+r(1738)](e[r(828)](255,this[r(1668)]),e[r(1131)](e[r(729)](this[r(1668)],8),255),e[r(1311)](this[r(1668)],16)&255,this[r(1668)]>>>24,e[r(1751)](255,this[r(1256)]),e.beJjv(e[r(1163)](this[r(1256)],8),255),e.bmood(this[r(1256)],16)&255,e[r(1163)](this[r(1256)],24))}static[t(1223)+"er"](r,s=!0){let l=t;if(isNaN(r))return s?pg:vl;if(s){if(r>=Oe)return mg}else if(e.MJkpx(e.gxaOM,e[l(478)]))++_0x2bbb6d,_0x171b27+=4;else{if(e[l(1037)](r,-cr))return wg;if(e.MRxFw(r,1)>=cr)return gg}return xe[l(523)](r%ye|0,e.tdnzI(e.pYhXK(r,ye),0),s)}toNumber(){let r=t;return this[r(690)]?(this[r(1256)]>>>0)*ye+e[r(796)](this[r(1668)],0):e[r(1175)](this[r(1256)]*ye,e[r(1311)](this[r(1668)],0))}[t(416)](){return e.JJLdq(0,this.high)&&e.yHEch(0,this.low)}[t(515)](r){let s=t;xe[s(1698)](r)||(r=xe[s(1223)+"er"](r));let l=this[s(1256)]>>>16,h=e[s(485)](65535,this[s(1256)]),g=e[s(633)](this[s(1668)],16),y=65535&this.low,k=r[s(1256)]>>>16,w=65535&r[s(1256)],O=e[s(633)](r[s(1668)],16),H=e[s(1124)](65535,r[s(1668)]),F=0,W=0,K=0,ce=0;return ce+=e[s(1679)](y,H),K+=e[s(591)](ce,16),ce&=65535,K+=g+O,W+=e.OXCSz(K,16),K&=65535,W+=e[s(804)](h,w),F+=e[s(754)](W,16),W&=65535,F+=e.pRLAj(l,k),F&=65535,xe[s(523)](e[s(1517)](e.jFseD(K,16),ce),e[s(1173)](e[s(1826)](F,16),W),this[s(690)])}[t(1635)](r){let s=t,l={OxhuE:function(h,g){return e[B(1739)](h,g)}};return e[s(1598)](e.uPBaV,e.uPBaV)?l.OxhuE(this[s(1450)],this[s(1639)+"ount"]):(xe[s(1698)](r)||(r=xe[s(1223)+"er"](r)),e[s(1602)](this[s(690)],r[s(690)])&&e[s(1742)](this[s(1256)]>>>31,1)&&e.fynjD(e[s(567)](r.high,31),1)?!1:e[s(413)](this[s(1256)],r.high)&&this[s(1668)]===r[s(1668)])}[t(835)](){let r=t;return e[r(969)](-1,this.low)&&e.evmsz(-1,this[r(1256)])?xe[r(523)](0,0,this[r(690)]):this[r(1668)]===-1?xe[r(523)](0,this[r(1256)]+1,this[r(690)]):xe[r(523)](this[r(1668)]+1,this[r(1256)],this[r(690)])}[t(798)](r){let s=t,l={nyTLa:function(h,g){return e[B(1456)](h,g)},JUmWA:function(h,g){return e[B(1714)](h,g)}};if(e.InwrJ===e.InwrJ)return r?this[s(1495)+"E"]():this[s(399)+"E"]();{let h=0,g={};for(let y=0;l.nyTLa(y,_0x570fa3[s(1407)]);y++)g[_0x49ec1c[y][s(464)+"ame"]]=l[s(1586)](_0x5d31d7,_0x3eaddf[y][s(464)+s(830)]),h+=14+g[_0x3d21a0[y][s(464)+s(830)]];return[h,g]}}[t(1495)+"E"](){let r=t,s=this[r(1256)],l=this[r(1668)];return[255&l,e[r(1140)](l>>>8,255),e.pqYYA(l>>>16,255),l>>>24,e[r(1140)](255,s),e.uZLlF(s>>>8,255),e.ZKIIe(e[r(604)](s,16),255),e[r(533)](s,24)]}[t(399)+"E"](){let r=t;if(e[r(954)]===e.LfaNy){let h=(r(1277)+"3")[r(1432)]("|"),g=0;for(;;){switch(h[g++]){case"0":var s=_0x1aeb60[_0x42b29e]={exports:{}};continue;case"1":var l=_0x32f387[_0x53add9];continue;case"2":_0x3d4980[_0x2ca206](s,s[r(1141)],_0x408068);continue;case"3":return s[r(1141)];case"4":if(UtxsnM[r(1602)](void 0,l))return l[r(1141)];continue}break}}else{let h=this[r(1256)],g=this[r(1668)];return[e[r(1243)](h,24),e.Furgk(e[r(1414)](h,16),255),e[r(806)](e[r(635)](h,8),255),255&h,e.ZWdvu(g,24),e.xCANA(e[r(1163)](g,16),255),e[r(806)](e[r(1093)](g,8),255),e[r(1672)](255,g)]}}}let vl=new xe(0,0,!1),pg=new xe(0,0,!0),gg=xe[t(523)](-1,2147483647,!1),mg=xe[t(523)](-1,-1,!0),wg=xe[t(523)](0,-2147483648,!1);var ln=(function(c){let r=t,s=e[r(1054)][r(1432)]("|"),l=0;for(;;){switch(s[l++]){case"0":return c;case"1":c[c[r(968)+r(459)]=5004]=r(968)+r(459);continue;case"2":c[c[e.YIABy]=5005]=e[r(1123)];continue;case"3":c[c[e[r(1757)]]=5001]=e[r(1757)];continue;case"4":c[c[e[r(1515)]]=5002]=e[r(1515)];continue;case"5":c[c[e.xtTxr]=5003]=r(1018)+r(401)+"R";continue}break}})({});class dr{constructor(r){this.type=r,this.target=null}}class Sl extends dr{constructor(r,s){let l=t;super(r),this[l(1813)]=s&&s[l(1813)]||null}}class Il extends dr{constructor(r,s){let l=t,h={dJPRM:function(g,y){return g(y)}};if(e[l(1262)](e.TUGwA,l(1541)))return function(...g){let y=l;return _0x36f6f8[y(662)](SnkRfP.dJPRM(_0x4b736b,this),g),_0x27fc06(_0x44be9d[y(493)](this))};super(r),this[l(749)]=s&&s[l(749)]||null,this[l(993)]=s&&s[l(993)]||0,this[l(1392)]=s&&s[l(1392)]||"",this[l(576)]=s&&s.lineno||0,this.message=s&&s[l(1813)]||"",this.code=s&&s[l(655)]||5001}}class Al extends dr{constructor(r,s){let l=t,h=(l(1320)+"0")[l(1432)]("|"),g=0;for(;;){switch(h[g++]){case"0":this[l(1800)+l(964)]=s&&s["willReco"+l(964)]||!1;continue;case"1":super(r);continue;case"2":this[l(1653)]=s&&s[l(1653)]||"";continue;case"3":this[l(655)]=s&&s[l(655)]||0;continue;case"4":this.wasClean=s&&s[l(552)]||!1;continue}break}}}class kl extends dr{constructor(r,s){let l=t;super(r),this.data=s&&s[l(1838)]||null}}class Tl extends kl{constructor(r,s){let l=t;super(r),this[l(1838)]=s&&s.data||null,this.message=s&&s[l(1813)]||null}}class Cl extends dr{constructor(r,s){let l=t;super(r),this[l(1838)]=s&&s[l(1838)]||null}}function ht(c,{message:r,code:s,error:l}){return new Il(c,{message:r,code:s,error:l})}function bt(c,{code:r,reason:s,wasClean:l,willReconnect:h}){return new Al(c,{code:r,reason:s,wasClean:l,willReconnect:h})}function Rl(c,{data:r,message:s}){return new Tl(c,{data:r,message:s})}function Pl(c,{data:r}){let s=t;if(e.IqwYF(e[s(1087)],"zGqDx"))return new Cl(c,{data:r});for(var l in _0x55b8b8)_0x12d8b8.o(_0x4de335,l)&&!_0x4175c1.o(_0xe1f9d,l)&&_0x5b8c4e[s(1512)+s(933)](_0x505a67,l,{enumerable:!0,get:_0x572e48[l]})}function Pa(c,{message:r}){return new Sl(c,{message:r})}class Dl{constructor(r,s){let l=t;this.endpoints=r,this[l(1370)+"es"]=s,this.currentIndex=0,this[l(1245)+"ndpointT"+l(665)+"t"]=0}[t(458)+"pointConfig"](){let r=t;if(e.Qbtrd(e.FEVCf,"XAsPM"))this["currentI"+r(990)]=0,this[r(1245)+r(1704)+r(665)+"t"]=0;else{let s={XUdjV:function(l,h,g){return e[r(1382)](l,h,g)}};return new _0x43db50(l=>{let h=r;s.XUdjV(_0x3d62ea,l,this[h(1398)+"rvalValue"](_0x41854c))})}}resetTries(){let r=t;this[r(1245)+r(1704)+"riesCount"]=0}[t(791)+t(1498)+"nt"](){let r=t,s={BbXGK:function(l,h){return e[B(1426)](l,h)}};if(e.NCaMf("XzBTN",e[r(1343)]))return this.endpoints[this[r(1077)+r(990)]];{let l=this[r(1531)][r(1728)+r(1782)](this[r(842)]),h=_0x1c541b[r(477)](s[r(687)](l,"{}"));return h[_0x49908e||_0x213111[this[r(1711)]]]=_0x449ce7,this._qosDB[r(1694)+r(1782)](this._prefix,_0x3cce83[r(1499)+"y"](h)),_0x5be200||_0x1a1db5[this[r(1711)]]}}[t(791)+"ntEndpointTriesC"+t(1152)](){let r=t;return this[r(1245)+"ndpointT"+r(665)+"t"]}checkReachMaxTries(){let r=t;return!!(e[r(679)](this[r(1077)+"ndex"],this[r(1044)+"s"][r(1407)])||e[r(969)](this[r(1077)+"ndex"],e[r(1324)](this[r(1044)+"s"].length,1))&&e[r(1271)](this[r(1245)+r(1704)+"riesCount"],this[r(1370)+"es"]))}[t(1887)+t(1460)+"ointReac"+t(1315)+t(1296)](){let r=t;return e[r(1213)](this["currentI"+r(990)],this.endpoints[r(1407)])?!0:this[r(1245)+"ndpointT"+r(665)+"t"]>this[r(1370)+"es"]}[t(1424)+t(1230)+t(1068)+t(1375)+"unt"](){let r=t;return this[r(1245)+r(1704)+r(665)+"t"]=1,this[r(1077)+r(990)]++,this[r(1044)+"s"][this["currentI"+r(990)]]}[t(791)+t(1498)+t(843)+"ateCount"](){let r=t;return this[r(1245)+r(1704)+"riesCount"]++,this[r(791)+r(1498)+"nt"]()}}let lr=(e[t(1713)](e[t(1363)],typeof globalThis)&&e.noBLq===globalThis[t(1696)+"tor"][t(1588)]||e[t(1363)]!=typeof window&&e[t(1777)]("Window",window.constructor.name))&&e[t(1713)](e[t(1363)],typeof document),Ln=e[t(1713)](e[t(1363)],typeof globalThis)&&(e[t(1212)](t(520),globalThis[t(1696)+t(1084)][t(1588)])||e[t(1358)](e[t(402)],globalThis[t(1696)+t(1084)][t(1588)]))&&e[t(837)](e[t(1363)],typeof tt),ci=(e[t(837)](t(1434)+"d",typeof globalThis)&&e.TMMNx(e[t(733)],globalThis[t(1696)+t(1084)][t(1588)])||e[t(884)](e.ErXbE,typeof globalThis)||e[t(1713)](e[t(1363)],typeof globalThis)&&!!globalThis[t(1733)+"Bridge"])&&e[t(1101)](e[t(1363)],typeof wx),di=e[t(1363)]!=typeof globalThis&&(e[t(402)]===globalThis[t(1696)+t(1084)][t(1588)]||e.SlLdb(e[t(1542)],globalThis["construc"+t(1084)].name)||e[t(712)](e[t(1494)],globalThis[t(1696)+t(1084)][t(1588)]))&&e.ErXbE!=typeof self,_g=e[t(654)](e[t(1363)],typeof globalThis)&&e[t(1433)](e[t(733)],globalThis[t(1696)+t(1084)].name)&&e[t(1363)]!=typeof global&&e[t(1219)](e.zhjJN,global["construc"+t(1084)][t(1588)])&&e[t(1713)](e[t(1363)],typeof process)&&!!process.version;class Da{constructor(){let r=t;this[r(1806)+"rs"]={}}[t(1700)](r,...s){let l=t,h=this[l(1806)+"rs"][r];if(h)h[l(1116)]()[l(920)](g=>g.fn.apply(g.ctx,s));else if(e.uhqTk(e[l(1579)],r)&&!this[l(425)]){let g=s.length&&s[0];if(e[l(1355)](g,Error))throw g;let y=new Error(e.HytZq(e[l(1260)],g?e.MRxFw(" ("+g[l(1813)],")"):""));throw y[l(1073)]=g,g}return this}[t(1397)](r,s){let l=t;if(e[l(1338)](void 0,r))this._listeners={};else if(e[l(1828)](void 0,s))this[l(1806)+"rs"][r]=null;else{let h=this._listeners[r];if(h)for(let g=0;g<h[l(1407)];)e[l(1742)](h[g].fn,s)?h[l(1590)](g,1):++g}return this}on(r,s,l){let h=t;return e.fZaKL(e[h(1380)],e[h(1380)])?{frameType:_0x42e49c,headers:[{key:e[h(1003)],value:e[h(1014)]}],payload:void 0}:((this[h(1806)+"rs"][r]||(this._listeners[r]=[]))[h(489)]({fn:s,ctx:l||this}),this)}}class yg extends Da{[t(1351)+t(1258)+t(1527)](r){let s=t;return r[s(1121)]||r[s(1441)]?(s(559)+" "+(r[s(1121)]||"")+" code: "+(r[s(1441)]||""))[s(1362)]():JSON[s(1499)+"y"](r)}constructor(r,s,l){let h=t;super(),this[h(1168)]=null,ci&&wx[h(932)+"ocket"]&&(this[h(1168)]=wx["connectS"+h(1052)]({url:r,protocols:s,header:l,fail:this["_createS"+h(1285)+h(1191)].bind(this),success:this[h(897)+"ocketSuc"+h(1690)+h(497)][h(1072)](this)})),Ln&&tt[h(932)+h(1052)]&&(this[h(1168)]=tt[h(932)+h(1052)]({url:r,protocols:s,header:l,fail:this[h(897)+h(1285)+h(1191)].bind(this),success:this[h(897)+h(543)+h(1690)+h(497)][h(1072)](this)}))}["_createS"+t(543)+t(1690)+t(497)](){let r=t;Promise[r(1819)]()[r(1663)](()=>{this["_addWsLi"+r(1831)]()})}[t(897)+t(1285)+t(1191)](r){let s=t,l={OMiXh:function(h,g,y){return e[B(1522)](h,g,y)},kDlzO:s(749),sMuGR:function(h,g,y){return e.HgBVq(h,g,y)},xMkHN:s(438)};Promise.resolve().then(()=>{let h=s,g=l[h(1313)](ht,h(749),{message:this[h(1351)+"rrorMess"+h(1527)](r)});this.emit(l.kDlzO,g);let y=l[h(432)](bt,l[h(1232)],{reason:this[h(1351)+h(1258)+h(1527)](r)});this[h(1700)](l[h(1232)],y)})}[t(553)+"steners"](){let r=t,s={EonNe:e[r(721)],dgjbY:function(l,h,g){return e[r(941)](l,h,g)}};this[r(1168)][r(891)](l=>{let h=r;this[h(1700)](h(1430),e[h(1090)](Pl,e[h(1071)],{...l,data:l.errMsg||""}))}),this._socket[r(486)](l=>{let h=r;this.emit(e[h(1274)],e[h(397)](bt,e[h(1274)],{...l}))}),this._socket.onMessage(l=>{let h=r;this.emit(s[h(863)],s[h(1027)](Rl,h(1813),{...l}))}),this[r(1168)].onError(l=>{let h=r;this[h(1700)](e[h(1579)],ht(h(749),{...l,message:l.errMsg||""}))})}[t(1383)](r){let s=t,l={zRPZN:e.Zddjg,PYdef:function(h,g,y){return e.qNahp(h,g,y)}};if(e.wHrpe(r,Uint8Array)){let h=r.buffer[s(1116)](r[s(1851)+"et"],e.teXqB(r.byteLength,r[s(1851)+"et"]));this._socket&&this._socket.send({data:h,fail:g=>{let y=s;this[y(1700)](e[y(1579)],e[y(1880)](ht,y(749),{message:this["_formatE"+y(1258)+y(1527)](g)}))}})}else this[s(1168)]&&this[s(1168)].send({data:r,fail:h=>{let g=s;this[g(1700)](l.zRPZN,l.PYdef(ht,l.zRPZN,{message:this[g(1351)+g(1258)+"age"](h)}))}})}[t(438)](r,s){let l=t;this[l(1168)]&&this[l(1168)][l(438)]({code:r,reason:s})}addEventListener(r,s){this.on(r,s)}[t(1550)+t(1436)+"ner"](r,s){this[t(1397)](r,s)}get[t(743)+"te"](){let r=t;return this._socket[r(743)+"te"]}get[t(763)+"pe"](){let r=t;return this[r(1168)][r(763)+"pe"]}set binaryType(r){}get[t(645)](){let r=t;return this[r(1168)][r(645)]}get[t(1612)](){return this[t(1168)].protocol}get[t(909)+"ns"](){let r=t;return this[r(1168)][r(909)+"ns"]}get[t(423)+t(490)](){return 0}}function bg(c,r){let s=t;if(r)return new r(c[s(645)],c[s(1612)]);if(e[s(1095)](ci,Ln))return new yg(c[s(645)],c[s(1612)],c.headers);if(e[s(1426)](lr,di)&&e[s(837)](e[s(1363)],typeof WebSocket)&&WebSocket)return new WebSocket(c[s(645)],c[s(1612)+"s"])}function Eg(c){let r=t;if(e.HGAQl===r(1618)){let s=(r(1474)+"3")[r(1432)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(c)return!0;continue;case"1":if(Ln&&tt.connectSocket)return!0;continue;case"2":if(ci&&wx[r(932)+r(1052)])return!0;continue;case"3":return!1;case"4":if(e[r(625)](lr,di)&&e[r(837)](e[r(1363)],typeof WebSocket)&&WebSocket)return!0;continue}break}}else e[r(1167)](_0xd2854d,this,_0x20f63e,[_0x437552,_0x57def6,_0x1444dc])}function Ol(c,r,s){let l=t,h={KCAtv:function(k,w){return e.yfcxy(k,w)},FiikT:e[l(938)],fEarO:function(k,w){return e[l(1742)](k,w)}},g=-1;async function y(k){let w=l;return h[w(1129)](k,g)?Promise[w(844)](new Error(h[w(748)])):(g=k,h.fEarO(k,s.length)?Promise[w(1819)]():s[k][w(1072)](c)(r,y.bind(null,k+1)))}e.GZyFw(y,0)}function Ll(c){let r=t;if(e.MJkpx(e[r(1632)],e[r(455)])){let s=0,l=0;for(let h=0;e[r(1794)](h,c[r(1407)]);++h)r(440)===e.DLdgm?(_0x425a00=e[r(1864)](e[r(571)](7&_0x219adf,18)|e.hgdFX(e[r(577)](63,_0x1171f7),12),e[r(1670)](63&_0x3bc31a,6))|e[r(824)](63,_0x29d6c9),_0x39105b<65536||_0x45f12f>1114111?_0x16df61+=_0x252e24:(_0x38b97c-=65536,_0x29d048+=_0x7cd82b(e[r(1391)](_0x4867aa>>10,55296),e[r(862)](e.UlpqP(1023,_0x15c798),56320)),_0x248c98+=3)):(l=c[r(1431)+"At"](h),e[r(549)](l,128)?s+=1:e[r(1505)](l,2048)?s+=2:e[r(405)](e[r(1784)](64512,l),55296)&&e[r(632)](e[r(1816)](64512,c[r(1431)+"At"](e.BCaNT(h,1))),56320)?(++h,s+=4):s+=3);return s}else{let s=e[r(664)].split("|"),l=0;for(;;){switch(s[l++]){case"0":if(_0x1bfa41.utf8Write)return _0x465c73.utf8Write(_0x250916,_0x38e4f9)+_0x450fc6;continue;case"1":if(e.xWpYk(_0x26a604[r(1407)],40))return e[r(406)](_0x47526e(_0x4b7cca,_0x2ddeb6,_0x494afb),_0x213f89);continue;case"2":return e[r(1202)](e[r(1167)](_0x196c71,_0x3e381c,_0xcce51,_0x518a57),_0x1cc203);case"3":if(!_0xc8f61a)return _0xb3dc06;continue;case"4":if(_0x158523[r(1114)])return e[r(560)](_0x33e1fa[r(1114)](_0x1763f1,_0x30c28a),_0x42dbf1);continue}break}}}function Nl(c,r,s){let l=t;if(e.wovgs(e[l(1862)](s,r),1))return"";let h="";for(let g=r;e.kNkKk(g,s);){let y=c[g++];if(e.gYacW(y,127))h+=String["fromChar"+l(1738)](y);else if(y>=192&&y<224)h+=String[l(940)+l(1738)](e[l(683)](e[l(807)](e.IYqAm(31,y),6),e[l(1082)](63,c[g++])));else if(e[l(1194)](y,224)&&e[l(472)](y,240))h+=String[l(940)+"Code"](e[l(435)](e[l(914)](e[l(1826)](e.ibnZy(15,y),12),e[l(1395)](e.Furgk(63,c[g++]),6)),e[l(587)](63,c[g++])));else if(e[l(1802)](y,240)){let k=e[l(1324)](e.SRgLn(e[l(1400)](e[l(1092)](e.mWcQm(7,y),18)|e[l(855)](e.uZLlF(63,c[g++]),12),e[l(555)](63&c[g++],6)),63&c[g++]),65536);h+=String[l(940)+l(1738)](e[l(1709)](55296,k>>10)),h+=String[l(940)+l(1738)](e[l(622)](56320,e[l(978)](1023,k)))}}return h}function Oa(c,r,s){let l=t,h=s,g,y;for(let k=0;k<c[l(1407)];++k)if(g=c[l(1431)+"At"](k),e[l(1468)](g,128))r[s++]=g;else if(e[l(1839)](g,2048))if(e.cjsFB!==e.nAqAo)r[s++]=e[l(1595)](g>>6,192),r[s++]=e[l(1050)](63&g,128);else return _0x1413b5[l(548)](_0x2c3a07),!1;else if(e.evmsz(e.FyIeE(64512,g),55296)&&e.twYlI(e[l(1036)](64512,y=c[l(1431)+"At"](e[l(1830)](k,1))),56320)){let w=e[l(678)][l(1432)]("|"),O=0;for(;;){switch(w[O++]){case"0":r[s++]=g>>18|240;continue;case"1":r[s++]=e[l(727)](e[l(534)](g,12)&63,128);continue;case"2":r[s++]=e[l(1755)](e[l(1040)](63,g),128);continue;case"3":++k;continue;case"4":r[s++]=e[l(731)](e[l(565)](g,6),63)|128;continue;case"5":g=e[l(692)](e[l(537)](65536,e[l(555)](e[l(1387)](1023,g),10)),e.Furgk(1023,y));continue}break}}else r[s++]=e[l(1423)](g,12)|224,r[s++]=e[l(663)](g,6)&63|128,r[s++]=e[l(1164)](e[l(825)](63,g),128);return e.EJYqL(s,h)}async function Ml(c){let r=t,s={ZNeme:function(l,h,g){return l(h,g)},RMZvH:function(l,h){return e[B(1727)](l,h)}};if(e[r(1858)]===e[r(1858)]){if(e.lACtz(e[r(1465)],typeof c))if(e[r(1183)](e.VJYKv,"cftGA")){for(_0x3fa474>>>=0;_0x24d25f>=128;)mLVwSw.ZNeme(_0x2514b8,_0x5ed0f9,mLVwSw[r(556)](127&_0x5310bb,128)),_0x112a87>>>=7;_0x1212b8(_0x2cd89e,_0x58e966)}else{let l=new Uint8Array(e[r(799)](Ll,c));return e[r(1301)](Oa,c,l,0),l}return e[r(1355)](c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c[r(834)],c[r(1851)+"et"],c.byteLength)}else this[r(1530)+"mise"]=null}function vg(c){let r=t,s={JSjUu:function(l,h){return l===h},pbkdh:function(l,h){return l!==h},idsXD:function(l,h,g){return e[B(1605)](l,h,g)}};try{return e[r(837)]("string",typeof c)&&(c instanceof ArrayBuffer||c.buffer&&c.buffer instanceof ArrayBuffer)||e[r(1713)](e.NzOeh,typeof c)?"":(JSON.parse(c),r(525)+r(1100))}catch{if(e.pjEby(e[r(1429)],e[r(858)]))return e[r(1422)](e[r(1465)],typeof c)?e.cDYQe:"";if(this[r(1594)]&&s.JSjUu(this[r(1594)][r(743)+"te"],this.CONNECTING)){this[r(1846)+r(1547)](),this[r(944)+r(1801)+"Id"]=_0x413834(this[r(1264)][r(1072)](this),this[r(979)][r(1418)+r(419)]);return}if(!this[r(1594)]||s[r(1206)](this[r(1594)][r(743)+"te"],this.OPEN))return void this[r(788)+r(1459)]();this[r(1594)]&&this._ws[r(1383)]("hi"),this[r(716)+"ctTimeou"+r(596)]=s[r(1634)](_0x1d3b28,this[r(788)+r(1459)+r(921)][r(1072)](this),this[r(979)][r(414)+"outInter"+r(1650)])}}let Sg=(c,r)=>{let s=t;if(e[s(771)](e[s(1282)],e.xqZBy))Ce[s(1118)+s(473)]=_0x2b4a68,Ce._ws&&(Ce._ws[s(763)+"pe"]=_0x4cb719);else switch(c){case e.JXPag:case e[s(1853)]:return{["x-use-"+c]:1,"x-tt-env":r};default:return{}}};class Ig{constructor(r){let s=t;this["maxLossC"+s(1152)]=r,this[s(1450)]=0}[t(1872)](){this.count++}[t(1654)+t(1229)+"nt"](){let r=t;if(e[r(1183)](e[r(1330)],e.ZZsAo)){let s=this[r(1531)]["getStora"+r(1782)](this[r(842)]);return _0x321480[r(477)](e.JxZoK(s,"{}"))[_0x31317d]}else return e[r(1228)](this[r(1450)],this[r(1639)+r(1152)])}[t(463)+"nter"](r=0){let s=t;this[s(1639)+s(1152)]=r,this[s(1450)]=0}}async function Ag(c){let r={KDJsQ:function(s,l){return e[B(1447)](s,l)},GRVpM:function(s){return s()},SgyyV:function(s,l,h){return e[B(1569)](s,l,h)},AVAJh:function(s,l){return e[B(1248)](s,l)}};return new Promise(s=>{let l=B;if(!lr)return e[l(1714)](s,e[l(1807)]);try{let h=document[l(1444)+l(854)](e[l(680)]);window[l(471)+l(1514)]=g=>{let y=l;document[y(1753)][y(1808)+y(1772)](h),window[y(471)+y(1514)]=void 0,r.KDJsQ(s,g&&g[y(1060)]||"unknown "+y(1653))},h.type=e[l(551)],h.src=e[l(540)](c.replace(/^ws/,e[l(1390)]),e[l(1154)]);try{document[l(1753)][l(509)+l(1772)](h)}catch{if(l(1047)===e[l(1523)])document.body[l(1808)+l(1772)](h);else{let g=mscmMg[l(1210)](_0x31c4d3);return mscmMg.SgyyV(_0x4983af,_0x237087,g),mscmMg.AVAJh(_0x5a5573,g)}}}catch{window[l(471)+"JSONP"]=void 0,e[l(1820)](s,e[l(1807)])}})}function un(c,r,s){let l=t;return!!c?.[l(1457)](h=>h[l(1484)]===r&&h[l(715)]===s)}function ur(c,r){let s=t;return c?.[s(1457)](l=>l[s(1484)]===r)?.[s(715)]}let La=null;async function kg(){let c=t;return La||(La=Promise[c(1819)]()[c(1663)](Gt.bind(Gt,e.GCstk))),La}class Tg extends Da{constructor(r,s){let l=t;super(),this[l(611)]=r,this[l(536)]=s,this[l(1531)]=void 0,this._initPromise=null}async[t(709)](){await this._init()}async[t(618)](){let r=t,s={TwHgV:function(l){return l()},iXhNh:function(l,h,g,y){return e[B(636)](l,h,g,y)}};if(!this[r(1531)]){if(this[r(1530)+r(1085)])return this[r(1530)+r(1085)];try{let l=this[r(611)],h=this[r(536)];this[r(1530)+r(1085)]=(async()=>{let g=r,{openDB:y}=await s.TwHgV(kg);this[g(1531)]=await s[g(1117)](y,g(471)+"_"+l,1,{upgrade(k){let w=g;k[w(1298)+w(1010)+"e"](l,{keyPath:h})}})})(),await this["_initPro"+r(1085)]}catch(l){console[r(548)](l)}finally{if(e[r(498)](r(1785),e[r(1043)])){let l=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(737)](_0x3d1101),h=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(737)](_0x3d881d);return l?e.hNVGY(_0x55f71b,_0x4a78a9):h?e.msNLd(_0x10977d,_0x4bf4dd):e[r(670)]}else this[r(1530)+r(1085)]=null}}}async get(r){let s=t;if(e[s(915)]===s(1780))return this[s(1594)]?this._ws[s(645)]:this[s(1321)];try{return await this._init(),this[s(1531)]?.get(this[s(611)],r)}catch(l){console[s(548)](l)}}async[t(598)](r,s){let l=t;return await this._init(),this[l(1531)]?.put(this[l(611)],r)}async[t(1425)](r){let s=t;try{return await this[s(618)](),this[s(1531)]?.delete(this._dbName,r)}catch(l){console[s(548)](l)}}async[t(831)](){let r=t;if(e[r(671)](e.PsdSO,r(601)))this.emit(e.Zddjg,_0x333131(e[r(1579)],{message:this[r(1351)+r(1258)+"age"](_0x4c1327)}));else try{return e[r(1788)](e[r(1170)],e[r(1170)])?(await this[r(618)](),this._qosDB?.[r(831)](this[r(611)])):new _0x3ba308(_0x28ba59)}catch(s){console[r(548)](s)}}async keys(){let r=t;return e[r(1568)]!==e.GWshr?(_0xa0a847&&(_0x457e49=(0,_0x3733b9[_0x26dc45(_0x542b25)[0]])(_0x242876=0)),_0x18c22b):(await this[r(618)](),this[r(1531)]?.[r(1452)+"ys"](this._dbName))}async[t(446)](){let r=t;return await this._init(),this._qosDB?.getAll(this[r(611)])}async[t(1501)](){let r=t;try{this._qosDB?.close(),this[r(1531)]=void 0}catch(s){console[r(548)](s)}}get[t(603)](){let r=t;try{return!!this[r(1531)]}catch(s){return console[r(548)](s),!1}}}class Cg{constructor(r,s){let l=t;this[l(816)]=r,this[l(1711)]=s,this[l(1531)]=localStorage}async[t(709)](){}get[t(842)](){let r=t,s={JVTka:function(l,h){return l-h}};if(e[r(1841)](e[r(896)],e[r(896)])){let l=_0xf03b95.substring(0,OymWwD[r(411)](4,_0x32c57e[_0x388779][r(1407)])),h=l.concat(_0x18b7c1);_0x580992=_0x5c08cc[r(803)](h)}else return r(471)+"_"+this[r(816)]}async[t(493)](r){let s=t;if(e[s(1262)](s(1616),e[s(1259)])){let l=this[s(1531)][s(1254)](this[s(842)]);return JSON[s(477)](e.Rtltm(l,"{}"))[r]}else _0x50b8c4[s(548)](_0x33adb9)}async[t(598)](r,s){let l=t,h=this._qosDB[l(1254)](this[l(842)]),g=JSON[l(477)](e[l(1479)](h,"{}"));return g[s||r[this[l(1711)]]]=r,this[l(1531)][l(1688)](this[l(842)],JSON[l(1499)+"y"](g)),s||r[this[l(1711)]]}async[t(1425)](r){let s=t,l=this[s(1531)][s(1254)](this[s(842)]),h=JSON[s(477)](e[s(1479)](l,"{}"));return h[r]=void 0,this[s(1531)].setItem(this[s(842)],JSON[s(1499)+"y"](h))}async[t(831)](){let r=t,s={hpGQK:function(l,h,g,y){return l(h,g,y)},jNvTP:function(l,h,g){return e[B(699)](l,h,g)},zjtCe:e.Zddjg};if(e[r(1598)](r(1439),e[r(1045)]))return this._qosDB[r(831)]();try{s[r(641)](_0x48612e,this,_0x52438d,[_0x10c1c5,_0x4cdab2,_0x37e211])}catch(l){let h=s[r(561)](_0x596a88,s[r(1347)],{message:l.message,code:_0x143502[r(1877)+"OR"],error:l});this[r(1255)+"hErrorEv"+r(741)](h)}}async[t(991)](){let r=t,s=this._qosDB[r(1254)](this._prefix),l=JSON[r(477)](e.Rtltm(s,"{}"));return Object[r(991)](l)}async[t(446)](){let r=t,s=this[r(1531)].getItem(this._prefix),l=JSON.parse(e[r(625)](s,"{}"));return Object[r(1490)](l)}[t(1501)](){return Promise[t(1819)]()}get[t(603)](){return!!this[t(1531)]}}class Rg{constructor(r,s){let l=t;this._DBName=r,this._pathKey=s,this[l(1531)]=Ln?tt:ci?wx:null}async[t(709)](){}get[t(842)](){let r=t;return r(471)+"_"+this[r(816)]}async get(r){let s=t,l=this[s(1531)][s(1728)+s(1782)](this[s(842)]);return JSON[s(477)](l||"{}")[r]}async[t(598)](r,s){let l=t,h=this[l(1531)][l(1728)+l(1782)](this[l(842)]),g=JSON.parse(e.Cwrij(h,"{}"));return g[s||r[this[l(1711)]]]=r,this._qosDB[l(1694)+l(1782)](this[l(842)],JSON.stringify(g)),s||r[this._pathKey]}async del(r){let s=t;if(e[s(1136)](e[s(1702)],s(1587)))this._messageQueue.shift(),this[s(1478)+s(475)].push(_0x545067);else{let l=this[s(1531)].getStorageSync(this[s(842)]),h=JSON[s(477)](e[s(1015)](l,"{}"));return h[r]=void 0,this._qosDB[s(1694)+s(1782)](this._prefix,JSON.stringify(h))}}async[t(831)](){let r=t;return this[r(1531)][r(1741)+r(957)]()}async[t(991)](){let r=t,s=this._qosDB[r(1728)+r(1489)+"nc"](this[r(842)]),l=JSON[r(477)](e[r(666)](s,"{}"));return Object.keys(l)}async[t(446)](){let r=t;if(e[r(396)]===e[r(396)]){let s=this[r(1531)][r(1728)+r(1489)+"nc"](this[r(842)]),l=JSON.parse(s||"{}");return Object[r(1490)](l)}else _0x3d9e38[r(1753)][r(1808)+"ild"](_0x2b50db)}[t(1501)](){return Promise.resolve()}get[t(603)](){return!!this._qosDB}}function Bl(c,r){let s=t;if(Ln||Ln)return new Rg(c,r);if(e[s(1438)](lr,di)&&e[s(837)](e[s(1363)],typeof indexedDB))return new Tg(c,r);if(e[s(1479)](lr,di)&&e[s(837)](s(1434)+"d",typeof localStorage))return new Cg(c,r);throw new Error(e[s(1469)])}class Pg{constructor(){let r=t;if(e.nvxMo(e[r(1524)],"hEDYm"))this[r(1091)+r(1196)+"Id"]=null,this[r(1091)+"l"]=36e5,this._qosDB=e[r(1090)](Bl,e[r(1035)],e[r(1065)]);else return this[r(1531)][r(831)]()}async["_interva"+t(431)](){let r=t;e.scgeX(clearInterval,this["_interva"+r(1196)+"Id"]),this[r(1091)+"lTimeoutId"]=e[r(1382)](setInterval,()=>{this.flushExpired()},this[r(1091)+"l"])}async[t(709)](){let r=t;await this[r(1531)][r(709)]().then(()=>{this["_interva"+r(431)]()})}async["flushExp"+t(1025)](){let r=t;(await this[r(1531)]?.getAll()||[]).filter(({timestamp:h})=>h<Date[r(427)]())[r(920)](h=>{let g=r;this[g(1531)]?.[g(1425)](h[g(1137)+"id"])})}async[t(1425)](r){let s=t;return this[s(1531)]?.[s(1425)](r)}async set(r,s){return this[t(1531)]?.set({message_id:r,timestamp:s})}async[t(493)](r){let s=t;if(e.dzoXI(e.CMHPA,e[s(760)]))return this._qosDB?.[s(493)](r);try{this[s(1594)]&&this[s(1594)][s(438)](_0x23205d,_0x44ca3a)}catch{}}async[t(1501)](){let r=t;e.msNLd(clearInterval,this[r(1091)+r(1196)+"Id"]),await this[r(1531)]?.[r(1501)]()}get[t(603)](){let r=t;return this[r(1531)]?.[r(603)]}}function Na(c){let r=t;if(e[r(1841)]("EBsqa",e[r(468)])){let s=!!this[r(979)][r(759)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(1301)](un,c.message[r(967)],r(545)+r(1112),"2"),h=l&&e[r(1167)](un,c.message[r(967)],e[r(1454)],"1"),g=l&&e[r(1167)](un,c[r(1813)][r(967)],e[r(1496)],"1"),y=g?ur(c[r(1813)][r(967)],e[r(442)])?.split(",")[r(1305)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:g,ackMsgIds:y}}else{let s=_0x83b5d0[r(1431)+"At"](_0x545d84);e[r(866)](s,55296)&&e[r(1708)](s,56319)&&e.GyzJh(_0x3942e7+1,_0x1936ba)&&(s=e[r(1102)](e[r(1e3)](e[r(451)](s,10),_0x1c93b6[r(1431)+"At"](++_0x33c3ab)),56613888)),_0x2aad91+=e[r(1286)](s,128)?1:s<2048?2:e[r(547)](s,65536)?3:4}}async function Fl(){let c=t;return this[c(1011)+c(950)]||(this[c(1011)+c(950)]=new Pg),this[c(1011)+c(950)].isReady||await this[c(1011)+c(950)][c(709)](),this[c(1011)+c(950)]}async function Dg(c,r){let s=t,{enableAutoAck:l}=this[s(979)],h=e[s(636)](un,c.message[s(967)],s(629),"1"),g=e[s(1167)](un,c[s(1813)][s(967)],e[s(746)],"1"),y=Na.call(this,c);if(l&&h){let{SeqID:k,LogID:w,service:O,LogIDNew:H,method:F}=c[s(1813)];this[s(518)]({SeqID:k,LogID:w,LogIDNew:H,service:O,method:F,headers:[{key:e[s(746)],value:"1"},{key:e.BHJok,value:e[s(1845)](H,"")},{key:e[s(977)],value:"0"}]})}g&&!y.isQoSAck&&this[s(1255)+s(1309)+s(1288)](c),e[s(682)](r)}async function Og(c,r){let s=t,l={qIWyj:function(h,g){return h(g)},fkhoN:function(h,g,y){return e.rTGvF(h,g,y)}};if(e[s(1644)](e[s(1146)],"cXtyn"))return(hTSIjg.qIWyj(_0x53841d,8).join("0")+hTSIjg.fkhoN(_0x194576,_0x5e9683,10).toString(2))[s(1116)](-8);this._debug(e[s(1601)],c.message),e.TABTV(r)}async function Lg(c,r){let s=t,l=e.iZVZq(cn,await e[s(1253)](Ml,c[s(1838)]));try{if(e[s(1355)](l[s(1627)],Uint8Array)){let h=e[s(1355)](this[s(979)]["payloadE"+s(767)],Object)?{force:!!this[s(979)][s(700)+s(767)][s(1238)],encoding:this[s(979)][s(700)+s(767)].encoding?this[s(979)][s(700)+s(767)][s(1442)][s(893)](/\s/g,"")[s(974)+s(1693)]():""}:{force:!1,encoding:this._options[s(700)+s(767)]?this[s(979)]["payloadE"+s(767)].replace(/\s/g,"")["toLowerC"+s(1693)]():""},g=l[s(700)+s(767)]?l[s(700)+s(767)][s(893)](/\s/g,"")[s(974)+s(1693)]():"",y=e[s(1619)](this[s(979)][s(480)+"ype"],Object)?{force:!!this[s(979)]["payloadT"+s(473)][s(1238)],type:this._options[s(480)+"ype"][s(573)]?this._options[s(480)+"ype"][s(573)][s(893)](/\s/g,"").toLowerCase():""}:{force:!1,type:this[s(979)][s(480)+s(473)]?this[s(979)][s(480)+"ype"].replace(/\s/g,"")[s(974)+"ase"]():""},k=l[s(480)+"ype"]?l[s(480)+s(473)].replace(/\s/g,"")[s(974)+"ase"]():"",w=y[s(1238)]?y[s(573)]:k||y[s(573)],O=h[s(1238)]?h[s(1442)]:g||h[s(1442)],H=[s(580)+s(888)+"et=utf-8",e[s(1735)],e[s(412)],e[s(1465)]],F=[e[s(1797)],s(1081)];this._options[s(926)+"ansformTextPayload"]&&H.includes(w)&&(!O||F[s(1645)](O))?l["textPayl"+s(869)]=e.HFIom(Nl,l[s(1627)],0,l[s(1627)].byteLength):l[s(637)+s(869)]=""}else l[s(637)+"oad"]=""}catch(h){l["textPayl"+s(869)]="",console[s(548)](h)}c[s(1813)]=l,e[s(1835)](r)}function Ng(c,r,s){let l=t,h={lhqwD:function(g,y){return e.pNsGs(g,y)},wOQYs:function(g,y){return g>y},vVQCc:function(g,y){return e[B(1119)](g,y)},cwBmH:function(g,y){return e.eDOft(g,y)},GyxFs:function(g,y){return e.CcKGP(g,y)},oAdXj:function(g,y){return e[B(435)](g,y)}};if(e[l(1771)](l(1171),e.xiKAG))_0x4c86e7=e[l(1364)](_0x3559ec,_0x27859c),e.uUFYK(_0x2e9e0b,32)&&(_0x2c0658|=e[l(1172)](127,_0x5552b0)<<_0x2703e8),_0x2b610b+=7;else{let g=e.PsykK(s,8192),y=e.BkHJe(g,1),k=null,w=g;return function(O){let H=l;if(h[H(1374)](O,1)||h[H(1066)](O,y))return c(O);h[H(1066)](h[H(1057)](w,O),g)&&(k=h.cwBmH(c,g),w=0);let F=r[H(444)](k,w,w+=O);return h[H(1283)](7,w)&&(w=h[H(719)](7,w)+1),F}}}let Mg=4294967295;function Bg(c,r,s){let l=t;if(e[l(961)](e[l(1520)],l(1786)))return e[l(1628)](RangeError,e[l(851)](e[l(851)](e.DJAhk(e[l(622)](e[l(1765)],c)+e.eOZqX,r||1),e[l(1222)]),s));this[l(1397)](_0xf8acb3,_0x255f63)}function Fg(c,r,s){let l=t;if(e[l(1836)](s,Mg))throw new Error(e[l(453)]);let h=3;for(;e[l(1267)](h,0);){let g=255&s;e[l(1184)](Ba,g,c,r+h),s>>>=8,h--}return e[l(1709)](r,4)}function zg(c,r){let s=t,l=0,h=r,g=r+4;for(;h<g;){let{value:y,offset:k}=e[s(1630)](Ma,c,h);h=k,l=e.BndxZ(e[s(1551)](l,8),0),l+=y}return{value:l,offset:g}}function Ug(c,r,s){let l=t,h=e.tRPVW.split("|"),g=0;for(;;){switch(h[g++]){case"0":return e.lJUVe(Oa(c,r,s),s);case"1":if(!c)return s;continue;case"2":if(r[l(1114)])return e.fLQRr(r[l(1114)](c,s),s);continue;case"3":if(r[l(965)+"e"])return r.utf8Write(c,s)+s;continue;case"4":if(e[l(1322)](c[l(1407)],40))return e.hyYdv(Oa(c,r,s),s);continue}break}}function Hg(c,r){let s=t;if(e[s(1841)](e[s(1815)],e.gFNPW))return _0x487607[s(1698)](_0x1cdc7f)||(_0x1f1e4a=_0x364ec4[s(1223)+"er"](_0x4bd9cf)),this[s(690)]!==_0x176ea6[s(690)]&&e[s(1243)](this[s(1256)],31)===1&&e.CtaBY(e[s(1013)](_0x3c77f2.high,31),1)?!1:this[s(1256)]===_0x241357[s(1256)]&&this[s(1668)]===_0x30afc1[s(1668)];{let l=new xe(e[s(789)](e[s(456)](e[s(1299)](c[e.bQcAU(r,4)]<<24,e[s(807)](c[r+5],16)),e[s(575)](c[r+6],8)),c[e.eltMo(r,7)]),e[s(1307)](e[s(1666)](c[r+0],24)|e[s(890)](c[e[s(537)](r,1)],16)|e[s(976)](c[e[s(1214)](r,2)],8),c[r+3]),!0);return r+=8,{value:l,offset:e.gJuNk(r,8)}}}function Gg(c,r,s){let l=t;if(e[l(671)](e[l(1615)],e[l(1615)]))e[l(980)](_0x15bc00,e[l(462)]),this[l(1397)](e[l(484)],_0x36a9b7),this[l(1397)](e[l(649)],_0x1e8b1b);else{let h=c.low,g=c[l(1256)];return r[s]=e[l(1093)](g,24),r[e[l(511)](s,1)]=e.wGFXx(e.dsExu(g,16),255),r[e.DJAhk(s,2)]=e.rTVJl(g>>>8,255),r[e.ywFIM(s,3)]=255&g,r[e[l(802)](s,4)]=h>>>24,r[s+5]=h>>>16&255,r[e[l(558)](s,6)]=e.wfEzj(h>>>8,255),r[e.emrgh(s,7)]=e[l(1292)](255,h),s+=8,s}}function Ma(c,r){let s=t,l={lWjlp:function(h,g){return e[B(424)](h,g)},DLZsm:function(h,g){return e[B(675)](h,g)},Qfroq:function(h,g){return h|g},uqMjb:function(h,g){return e[B(1339)](h,g)},iNfOZ:function(h,g){return e[B(648)](h,g)},TpmkS:function(h,g){return e[B(1040)](h,g)},DJOXW:function(h,g){return e[B(1187)](h,g)},AusNF:function(h,g){return e[B(1372)](h,g)},MXYwx:function(h,g){return e[B(534)](h,g)},iXbLy:function(h,g){return e[B(1153)](h,g)},LCZnb:function(h,g){return e[B(927)](h,g)}};if(e[s(1681)](s(1083),s(1842))){let h=vArNIx[s(628)](vArNIx.DLZsm(vArNIx[s(695)](vArNIx[s(962)](vArNIx[s(1055)](7,_0x1fdd1f),18),(63&_0x580804[_0x47ae56++])<<12)|vArNIx.uqMjb(vArNIx[s(718)](63,_0x4243ab[_0x212bb6++]),6),vArNIx[s(838)](63,_0x561349[_0x4b68e0++])),65536);_0x252d91+=_0x375c14[s(940)+s(1738)](vArNIx[s(452)](55296,vArNIx[s(623)](h,10))),_0x5135a2+=_0x3c8b09[s(940)+"Code"](vArNIx[s(1774)](56320,vArNIx[s(918)](1023,h)))}else return c[s(1486)+"8"]?{value:c[s(1486)+"8"](r),offset:e[s(928)](r,1)}:{value:e[s(1604)](255,c[r]),offset:e.pRLAj(r,1)}}function Ba(c,r,s){let l=t;if(e[l(1549)]!==l(1592)){let h=_0x52040f[l(1484)];h!==void 0&&(e[l(999)](_0x3980bc,_0x601ba9,10),e.vQEMW(_0x3aaf02,_0x155e72,h));let g=_0x18f36d[l(715)];e[l(1162)](void 0,g)&&(e[l(457)](_0x410bf9,_0x179e07,18),e[l(1268)](_0x9ddace,_0x1002d9,g))}else return r[l(1103)+"t8"]?r[l(1103)+"t8"](c,s):r[s]=255&c,e[l(697)](s,1)}let qg=function(c){return new Uint8Array(c)},jg=e[t(1101)](e[t(1363)],typeof Buffer)?Buffer["allocUns"+t(1061)]:e[t(1617)](Ng,qg,Uint8Array[t(875)+"e"].subarray);(()=>{let c=t,r={cGDuz:function(l,h){return e[B(1153)](l,h)},Igvpv:function(l,h){return e[B(1270)](l,h)},jTPSi:function(l,h){return l&h},ZhhBy:function(l,h){return l<h},UesVI:function(l,h){return e[B(905)](l,h)},MlWGV:function(l,h){return l<<h},PbLbz:function(l,h){return l&h},lgSfC:function(l,h){return e[B(727)](l,h)},OeKet:function(l,h){return e.xmNwi(l,h)},zcciW:function(l,h){return e[B(1322)](l,h)},HVBum:function(l,h){return e[B(890)](l,h)},sdZgR:function(l,h){return e[B(1396)](l,h)},bpXGX:function(l,h){return l>>>h},HPIgr:function(l,h){return e[B(1096)](l,h)},NiYXD:function(l,h){return e[B(1307)](l,h)},GbmWz:function(l,h){return e[B(1401)](l,h)},mzpUB:c(1658),ZBYQr:function(l,h,g,y){return e.wopcm(l,h,g,y)}},s=4294967295;return function(l,h,g=!0){let y=c,k={cdvBY:function(w,O){return r.cGDuz(w,O)}};if(s=r[y(1548)](r.jTPSi(127,l[h]),0),r[y(1659)](l[h++],128))return{value:g?s:0|s,offset:h};if(s=r[y(1208)](s|r.MlWGV(r.PbLbz(127,l[h]),7),0),r.ZhhBy(l[h++],128))return{value:g?s:r.lgSfC(0,s),offset:h};if(s=r.OeKet(r.lgSfC(s,r[y(1381)](127&l[h],14)),0),r[y(747)](l[h++],128))return{value:g?s:0|s,offset:h};if(s=r[y(1276)](r[y(530)](s,r[y(1346)](r[y(1614)](127,l[h]),21)),0),r.sdZgR(l[h++],128))return{value:g?s:r[y(530)](0,s),offset:h};if(s=r.bpXGX(r[y(826)](s,r[y(1346)](15&l[h],28)),0),l[h++]<128)return{value:g?s:r.NiYXD(0,s),offset:h};if(r[y(946)](h+=5,l[y(1407)])){if(r[y(885)]==="rsuYp")throw h=l.length,r.ZBYQr(Bg,h,10,l[y(1407)]);return tJTEsJ.cdvBY(1e4*_0x434d2f.now(),_0xbeb0df[y(1779)](1e4*_0x1f52b0[y(956)]()))}return{value:g?s:0|s,offset:h}}})();let Wg=16,Fa=32;function Kg(c){let r=t,s=0,l={};for(let h=0;e[r(1585)](h,c[r(1407)]);h++)l[c[h][r(464)+r(830)]]=Ll(c[h]["cursor_n"+r(830)]),s+=14+l[c[h][r(464)+r(830)]];return[s,l]}function zl(c,r,s){let l=t,[h,g]=Kg(c),y=e[l(1855)](jg,h),k=0;return c[l(920)](w=>{let O=l;console.log(e[O(1227)],w,w[O(935)]),k=e[O(1205)](Ba,0,y,k),console.log("header",k),k=e[O(1822)](Fg,y,k,w[O(935)]||0),console[O(548)](e[O(1599)],k),k=e[O(878)](Ba,g[w[O(464)+O(830)]],y,k),console[O(548)](O(1403)+O(1588),k),k=Ug(w[O(464)+O(830)],y,k),console[O(548)](O(1588),k),k=e[O(1157)](Gg,xe[O(1223)+"er"](w[O(514)]||r),y,k),console.log(e[O(1139)],k)}),{frameType:Fa,headers:[{key:"cursor_f"+l(1687),value:s}],payload:y}}function $g(c){let r=t;if(e[r(542)](r(879),e[r(408)])){this[r(1467)+"WebSocket"]();let s=e[r(1723)](_0x1f3fac,e[r(593)],{message:e.DPxmm});this["onStopIm"+r(541)+r(1130)+"ct"]&&this[r(1482)+r(541)+r(1130)+"ct"](s)}else{let s=0,l=[];for(;e[r(472)](s,c[r(1366)+"th"]);){let{offset:h}=e[r(1181)](Ma,c,s);s=h;let g={cursor_name:"",cursor:0,service:0},{value:y,offset:k}=zg(c,s);g[r(935)]=y,s=k;let{value:w,offset:O}=Ma(c,s);s=O,g[r(464)+r(830)]=Nl(c,s,e[r(589)](s,w)),s+=w;let{value:H,offset:F}=e[r(1250)](Hg,c,s);g[r(514)]=H[r(1656)](),s=F,l[r(489)](g)}return l}}function Vg(){let c=t;return{frameType:Fa,headers:[{key:e.nQGgB,value:e[c(1014)]}],payload:void 0}}class Zg{constructor(r,s,l){let h=t;this["_cursorN"+h(959)]=r,this[h(899)+"ileName"]=s,this["_message"+h(1147)]=l,this[h(1531)]=e[h(1268)](Bl,this[h(1386)+h(959)],h(464)+h(830))}async openDB(){let r=t;await this[r(1531)][r(709)]()}async[t(1333)+"rs"](){let r=t;if(!this[r(1531)][r(603)])return;let s=this[r(1478)+"Strategy"],l=await this[r(1531)][r(446)]();switch(console[r(548)]("allCurso"+r(1557),l),s){case e.pKcSO:return l&&l[r(1407)]?e[r(1661)](zl,l,0,this["_cursorF"+r(861)]):void 0;case"INSTANT":return;case e[r(1463)]:return l&&l[r(1407)]?e[r(1695)](zl,l,0,this[r(899)+"ileName"]):e.TABTV(Vg)}}async[t(598)](r,s,l){let h=t;return console[h(548)](e.dQvBu,r,s,l),this[h(1531)][h(598)]({cursor_name:r,cursor:s,service:l})}async[t(667)+"rs"](r){let s=t,l=e[s(1220)]($g,r);for(let h of l)console[s(548)](e.CrBNH,l),await this._qosDB[s(598)](h)}async[t(493)](r){let s=t;return(await this._qosDB[s(493)](r))?.[s(514)]}async[t(1501)](){let r=t;await this._qosDB[r(1501)]()}[t(1416)+t(1451)+t(1748)](r){let s=t;e[s(449)](e[s(634)],e.CdIya)?(this._isInit=!0,this[s(892)]()):this[s(899)+s(861)]=r}get[t(603)](){return this._qosDB.isReady}}let Jg=e.ijupe;async function Ul(c){let r=t;if(e[r(413)](e[r(1646)],e[r(1500)]))this[r(934)+r(1247)+r(502)]=_0x4dae93,_0x252fa1?this[r(887)+r(1345)]():this["_handleO"+r(708)]();else{if(!this[r(979)].enableQoS)return null;let{aID:s,fpID:l,messageStrategy:h}=this[r(979)],g=e[r(1120)](c,Jg);try{return this[r(1719)+r(407)]?c&&this[r(1719)+"anager"][r(1416)+r(1451)+r(1748)](c):this[r(1719)+"anager"]=new Zg(l+"_"+s+"_"+g,g,h),this[r(1719)+"anager"][r(603)]||await this[r(1719)+r(407)][r(709)](),this["_cursorM"+r(407)]}catch{return null}}}async function Yg(c,r){let s=t,l={fszkh:e[s(984)],cLmmj:e[s(649)],ZCEjo:function(K,ce){return e[s(943)](K,ce)},kMTfJ:s(948)+s(557)+"s",snxfx:function(K,ce,be){return K(ce,be)}},h=e[s(1184)](un,c[s(1813)][s(967)],s(655),"-1"),g=e.QCcRV(un,c[s(1813)].headers,e[s(746)],"1"),y=ur(c[s(1813)][s(967)],e[s(996)]),k=e[s(1503)](Number,ur(c.message[s(967)],e.qFRzS))||0,w=Na[s(444)](this,c),O=e[s(1665)](un,c[s(1813)][s(967)],e[s(650)],"2"),H=e.ZjuIe(ur,c[s(1813)][s(967)],s(953)+s(460)+"e"),F=e.UoHBI(Number,e[s(1886)](ur,c.message[s(967)],s(953)+s(1860)+"ue"));if(w[s(1412)])return e[s(1516)](r);let W=w[s(1492)+s(1509)]?await Fl[s(444)](this):null;if(e[s(1850)](c.message[s(935)],0)&&g&&!h||e[s(1217)](c[s(1813)][s(935)],0)){if(y&&w[s(1492)+s(1509)]&&W){if(e[s(1331)]===e[s(1331)])return!!!await W[s(493)](y)&&(this[s(1255)+"hMessage"+s(1367)](c),await W[s(598)](y,e[s(1108)](Date[s(427)](),k))),e[s(479)](r);{let K={USdqy:function(ge,Ge){return l[s(600)](ge,Ge)},UKGfh:l[s(1446)],Zrfrc:s(948)+"e_timeout"};this._clearPingTimer(),this["_pingPon"+s(1801)+"Id"]=l.snxfx(_0x435589,this[s(1264)][s(1072)](this),this[s(979)][s(1418)+s(419)]);let ce=()=>{let ge=s;K[ge(738)](_0xa66bb3,ge(443)),this[ge(1397)](K[ge(1111)],ce),this[ge(1397)](K.Zrfrc,be)},be=()=>{let ge=s;_0x217c37(l.fszkh),this.off(ge(948)+ge(557)+"s",ce),this.off(l[ge(1640)],be)};this.on(l.kMTfJ,ce),this.on(l[s(1640)],be),this[s(1264)]()}}if(O){let K=await Ul[s(444)](this);if(!K)return this[s(1255)+s(1799)+s(1367)](c),e[s(1682)](r);let ce=await K.get(H)??-1;if(e[s(1001)](ce,F))this["_dispatc"+s(1799)+"Event"](c),K[s(598)](H,F,c[s(1813)][s(935)]);else throw new Error("recevied"+s(676)+s(1607)+F+(s(1577)+s(958)+"al cursor ")+ce);return r()}return this[s(1255)+s(1799)+s(1367)](c),e[s(1703)](r)}}async function Xg(c,r){let s=t,l=Na.call(this,c);if(!l[s(1492)+s(1509)])return e[s(1303)](r);let h=await Fl[s(444)](this);if(l[s(481)+s(922)+s(1527)]&&l[s(1790)+"s"].length)for(let g of l[s(1790)+"s"])await h[s(1425)](g);e[s(1278)](r)}async function Qg(c,r){let s=t,l=e[s(1136)](c.message.frameType,Wg),h=e[s(436)](c.message.frameType,Fa);if(!l&&!h)return e.TABTV(r);let g=ur(c[s(1813)][s(967)],e[s(1003)]);if(!g)return e[s(1776)](r);let y=await Ul[s(444)](this,g);if(!y)return e[s(1870)](r);if(l){let k=await y[s(1333)+"rs"](),w={frameType:k?.[s(616)+"e"],SeqID:xe.fromNumber(this[s(1252)]++),LogID:xe.fromNumber(this[s(979)][s(1686)+s(517)]()),service:9e3,method:5,headers:k?.[s(967)],payload:k?.[s(1627)]},O=e.ErWap(v,w);this[s(1594)]&&this[s(1594)][s(743)+"te"]&&this[s(1594)].send(O)}if(h){let k=c[s(1813)][s(1627)];k&&y.setCursors(k)}}let em=async function(c,r){let s=t;this._isInit=!1,e[s(1253)](clearTimeout,this["_connect"+s(1235)+s(1706)]),e.CzfAX(r)},tm=async function(c,r){let s=t,l={yNbOM:e[s(1570)]};if(!this[s(1594)]||e[s(671)](this[s(1594)][s(743)+"te"],this.OPEN))return r();let{pingInterval:h}=this._options;this._endpointManager?.["resetEnd"+s(653)+s(1560)]();for(let y=0;y<this["_message"+s(475)][s(1407)];y++)if(e[s(643)](s(1080),e[s(672)])){let k=this["_message"+s(475)][y];if(e[s(1335)](this._ws[s(743)+"te"],this[s(1122)])&&e[s(1477)](null,k))this[s(1594)]&&this[s(1594)].send(k),this[s(1478)+"Queue"][y]=null;else break}else!_0x45d8ec[s(1233)+"d"]&&(this[s(1576)+"er"]&&_0x17fb43[s(1550)+s(1436)+s(871)](l[s(1678)],this[s(491)+s(1155)]),this[s(1576)+"er"]&&_0x29bfcd["removeEv"+s(1436)+"ner"]("pageshow",this[s(491)+s(786)]),this[s(438)]()),this[s(1576)+"er"]&&_0x37d957[s(1550)+s(1436)+s(871)](s(1413),this[s(887)+s(1345)]),this._isBrowser&&_0x1e6d39[s(1550)+s(1436)+s(871)](s(659),this[s(887)+s(708)]);this["_message"+s(475)]=this[s(1478)+"Queue"][s(1305)](y=>!!y),this["_pingPon"+s(1801)+"Id"]=e[s(1244)](setTimeout,()=>this[s(1264)](),h),this[s(1255)+"hOpenEvent"](c),this._isBrowser&&this[s(1594)]&&(this[s(1594)].binaryType=this["_binaryT"+s(473)]);let g=this[s(1655)+"tManager"]?.[s(791)+s(1498)+"nt"]();this[s(810)](s(1610)+g+s(1074)),e[s(626)](r)},nm=async function(c,r){let s=t,l=this["_endpoin"+s(1225)]?.[s(791)+"ntEndpoint"]();this[s(810)](s(1610)+l),e[s(1835)](r)};class rm extends Da{constructor(r){let s=t,l={Trqwo:e[s(1064)],lpPQv:function(h,g){return e[s(495)](h,g)},TkYJf:e[s(808)],ckBkj:function(h,g,y){return h(g,y)},cuKZz:"error",CNnuv:function(h,g){return h===g},hlxOp:function(h,g){return e.TzZed(h,g)},QsYWm:e.DWErH,dYUtV:e[s(1302)],lBqjh:function(h,g){return e[s(1337)](h,g)},rIldn:e[s(461)],KUWLv:function(h,g){return e.rPzTJ(h,g)},JiLFq:function(h,g){return e.czlad(h,g)},reBXX:s(1798),ODUoD:s(691),dVzTZ:function(h,g,y){return e.WnOwU(h,g,y)},vvvwI:e.mLApU,qWIdv:e[s(1567)],mIShr:function(h,g){return h!==g},efwgO:function(h,g){return e[s(997)](h,g)},GXkqB:function(h,g,y){return e[s(397)](h,g,y)}};if(e[s(643)](e.DRmLz,e.fFWNW)){let h=_0x119e48.deleteDatabase(_0x47c97f);return _0x813b28&&h[s(1323)+s(1810)](hjOfrn[s(1868)],()=>_0x216b61()),_0x375144(h).then(()=>{})}else{super(),this[s(934)+s(1247)+"line"]=!0,this[s(1576)+"er"]=lr,this[s(1359)]=_g,this[s(1636)+"T"]=Ln,this._isMiniWX=ci,this[s(585)+"r"]=di,this[s(1478)+"Queue"]=[],this[s(1655)+s(1225)]=null,this[s(1178)+s(686)]=!1,this[s(1118)+s(473)]=e[s(1385)],this["_connect"+s(836)]=!1,this[s(892)+s(1235)+s(1706)]=null,this[s(716)+s(647)+"tId"]=null,this[s(944)+"gTimeoutId"]=null,this[s(1252)]=0,this[s(522)]=!1,this[s(1321)]="",this[s(1011)+s(950)]=null,this[s(1719)+"anager"]=null,this[s(1638)+s(1770)]=null,this[s(740)+"ls"]=e.EJUeP,this.CLOSED=3,this.CONNECTING=0,this[s(1122)]=1,this.CLOSING=2,this[s(1342)]=k=>{let w=s;try{if(l[w(1866)](l.TkYJf,l.TkYJf))Ol(this,k,[em,tm,nm]);else return{bytes:_0x4d3692,offset:0,limit:_0x2fdc7b[w(1407)]}}catch(O){let H=l[w(829)](ht,l[w(1273)],{message:O[w(1813)],code:ln.OPEN_ERROR,error:O});this[w(1255)+w(1699)+w(741)](H)}},this[s(1796)+"ge"]=async k=>{let w=s,{pingInterval:O,pingFrequency:H}=this[w(979)];if((l.CNnuv("hi",k.data)&&l[w(521)](l[w(1226)],H)||l.dYUtV===H)&&(this[w(1846)+w(1547)](),this[w(1700)](w(948)+w(557)+"s",w(443)),this[w(944)+w(1801)+"Id"]=l[w(829)](setTimeout,this[w(1264)].bind(this),O)),!l[w(521)]("hi",k.data))try{Ol(this,k,[Lg,Dg,Xg,Qg,Yg,Og])}catch(F){let W=ht(l.cuKZz,{message:F.message,code:ln[w(968)+w(459)],error:F});this[w(1255)+w(1699)+"ent"](W)}},this[s(657)]=k=>{let w=s,O=this[w(1655)+w(1225)]?.[w(1654)+w(1201)+"es"](),H=this[w(1655)+w(1225)]?.[w(791)+w(1498)+"nt"]();if(O&&!k[w(1813)]){let F=w(1824)+H+(w(1791)+w(1856)+w(1133)+"ed");this[w(1255)+w(1699)+w(741)](e[w(512)](ht,e[w(1579)],{message:F,code:ln[w(1018)+"IES_ERROR"],error:k}));return}this[w(1594)]&&e.bENXa(this[w(1594)][w(743)+"te"],this[w(1122)])&&this[w(1453)+w(1572)](),this[w(1255)+w(1699)+w(741)](e[w(1660)](ht,e[w(1579)],{message:k[w(1813)],code:ln[w(1151)+w(801)],error:k}))},this[s(881)]=async k=>{let w=s,O={zscDK:function(F,W){return F+W},RHXxn:function(F,W){return F+W},AxExY:function(F,W){return l[B(1573)](F,W)},gRckc:function(F,W){return l[B(1573)](F,W)},OLHau:l[w(931)],yLcay:function(F,W){return l.KUWLv(F,W)},IfqDI:w(1804)};this._clearTimer(),this[w(1846)+w(1547)](),this[w(1737)+w(739)+"rs"](),this._ws=null,this[w(892)+w(836)]=!1;let H=this[w(1655)+"tManager"]?.[w(1654)+w(1201)+"es"]();if(!H&&this[w(987)+w(430)]()&&!this["_readyCl"+w(686)])if(l.JiLFq(l.reBXX,l[w(1882)])){let F=this[w(1655)+w(1225)]?.[w(791)+"ntEndpoint"](),W=this[w(979)][w(1624)+w(873)+w(669)](k[w(655)],k.reason);this[w(1255)+w(856)+"ent"](l.dVzTZ(bt,l[w(574)],{code:1006,reason:k[w(1653)]||w(1538)+w(859)+w(857)+w(487)+w(433)+w(1417)+F,willReconnect:W})),W&&this[w(892)]();return}else return _0xf86b4f(Ogkwxi[w(685)](Ogkwxi[w(1676)](Ogkwxi[w(1239)](Ogkwxi[w(1361)]("index ou"+w(1781)+w(550),_0x4f74b2),Ogkwxi[w(1415)]),Ogkwxi[w(937)](_0x28001c,1))+Ogkwxi[w(568)],_0x45e454));if(l[w(1266)](1e3,k[w(655)])&&this[w(1178)+w(686)]){this[w(1255)+w(856)+"ent"](l.dVzTZ(bt,l.vvvwI,{code:1e3,reason:l[w(1004)]})),this[w(1655)+"tManager"]?.["resetEnd"+w(653)+w(1560)](),this._pingLossCounter?.[w(463)+"nter"]();return}if(l[w(395)](1e3,k.code)&&H){let F=this[w(1655)+"tManager"]?.[w(791)+w(1498)+"nt"](),W=k[w(1653)];W||(W=await l.efwgO(Ag,this[w(1321)])),W=w(1538)+w(859)+"d, "+W+(w(448)+w(1546))+F+(", max re"+w(1825)+w(1368)),this[w(1255)+w(856)+w(741)](bt(l.vvvwI,{code:k.code,reason:W}));let K=w(1824)+F+(w(1791)+w(1856)+"es reached");this[w(1255)+w(1699)+"ent"](l.GXkqB(ht,l[w(1273)],{message:K,code:ln[w(1018)+w(401)+"R"]})),this[w(1655)+w(1225)]?.[w(458)+w(653)+w(1560)](),this[w(1638)+"sCounter"]?.[w(463)+w(1593)]();return}if(l[w(1266)](1e3,k[w(655)])&&!k[w(1653)]){let F=this["_endpoin"+w(1225)]?.[w(791)+w(1498)+"nt"]();this["_dispatc"+w(856)+w(741)](l[w(652)](bt,l[w(574)],{code:k.code,reason:w(1538)+w(859)+w(857)+"wn reaso"+w(433)+w(1417)+F})),this[w(1655)+w(1225)]?.["resetEnd"+w(653)+w(1560)](),this[w(1638)+w(1770)]?.resetCounter();return}this[w(1255)+w(856)+w(741)](k),this._endpointManager?.[w(458)+w(653)+w(1560)](),this[w(1638)+w(1770)]?.[w(463)+w(1593)]()},this[s(1818)]=null,this[s(425)]=null,this[s(1629)+"e"]=null,this[s(507)]=null,this["onStartR"+s(1459)]=null,this[s(1852)+s(1378)]=null,this[s(1482)+s(541)+s(1130)+"ct"]=null,this[s(887)+"nLine"]=this[s(887)+s(1345)][s(1072)](this),this[s(887)+s(708)]=this["_handleO"+s(708)][s(1072)](this),this["_handleP"+s(1155)]=this[s(491)+s(1155)].bind(this),this[s(491)+s(786)]=this[s(491)+s(786)][s(1072)](this),this[s(979)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1566)](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.oMMsi,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1463)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:g}=r,y=Array[s(1613)](h)?h:e[s(1465)]==typeof h?[h]:[];if(!y||e[s(1079)](0,y[s(1407)]))throw new Error(s(1652)+s(792)+s(1041));if(!e[s(1059)](Eg,g))throw new Error(e.syOCI);Object.assign(this[s(979)],r),this[s(1655)+s(1225)]=new Dl(y,this[s(979)][s(1370)+"es"]),this[s(1638)+s(1770)]=new Ig(this._options[s(1023)+s(1651)]),this[s(979)].automaticOpen&&(this[s(522)]=!0,this[s(892)]()),this._options["listenNe"+s(726)+s(1332)]&&(this[s(1636)+"T"]||this._isMiniWX?this._onPageNetWorkChange():this._isBrowser&&this[s(775)+s(470)+"Listener"]())}}["_handleO"+t(1345)](){let r=t;if(e[r(1162)](e[r(1789)],e[r(1789)])){if(this[r(1846)+r(1547)](),this[r(1318)+r(1795)](),this._removeWsListeners(),this["_wsInsta"+r(870)](1e3,_0x4be65f),this[r(892)+r(836)]=!1,_0x375f4e&&this[r(987)+r(430)]()&&!this[r(1178)+r(686)]){if(this[r(1655)+r(1225)]?.[r(1654)+r(1201)+"es"]()){let l=this[r(1655)+r(1225)]?.[r(791)+r(1498)+"nt"]();this["_dispatc"+r(856)+r(741)](e.bFlAN(_0x5d2bd9,e[r(1274)],{code:1006,reason:r(1824)+l+(" timeout"+r(1156)+r(1825)+r(1368)),wasClean:!0}))}else{let l=this[r(979)]["reconnec"+r(873)+r(669)](_0x41c93a,_0xf347a3);this[r(1255)+r(856)+r(741)](e.uKofr(_0x1d7115,r(438),{code:_0x497149,reason:_0x1969d7,wasClean:!0,willReconnect:l})),l&&this[r(892)]()}return}this[r(987)+r(430)]()||this[r(1178)+r(686)]?this[r(1255)+r(856)+"ent"](e[r(519)](_0x5990bb,r(438),{code:_0x141b38,reason:r(630)})):this[r(1255)+r(856)+r(741)](e[r(1049)](_0x3b4067,e[r(1274)],{code:1006,reason:e[r(1732)]})),this[r(1594)]=null,this["_endpoin"+r(1225)]?.[r(458)+"pointCon"+r(1560)](),this[r(1638)+r(1770)]?.[r(463)+r(1593)]()}else{if(this[r(979)][r(1125)+r(1473)+r(1558)]||this[r(1178)+r(686)])return;this[r(788)+r(1459)]()}}[t(887)+t(708)](){let r=t;this[r(1467)+r(1532)+"t"]();let s=e[r(1038)](Pa,e[r(593)],{message:e[r(420)]});this[r(1482)+r(541)+"yReconnect"]&&this[r(1482)+"mediatel"+r(1130)+"ct"](s)}["_initGlo"+t(470)+t(1810)](){let r=t;this[r(1576)+"er"]&&window[r(1323)+"Listener"](e[r(610)],this["_handleO"+r(1345)]),this[r(1576)+"er"]&&window[r(1323)+r(1810)](e[r(1352)],this["_handleO"+r(708)]),this[r(1576)+"er"]&&window[r(1323)+r(1810)](e[r(1570)],this[r(491)+r(1155)]),this[r(1576)+"er"]&&window[r(1323)+r(1810)](e.EnGZn,this._handlePageShow)}[t(704)+"balEvent"+t(1810)](){let r=t;if(e[r(1873)]!==r(949)){let s=_0x3d74b2.pop();return s?(s[r(1344)]=s[r(1840)]=0,s):{bytes:new _0x17e3a2(64),offset:0,limit:0}}else this[r(1576)+"er"]&&window[r(1550)+r(1436)+r(871)](e[r(610)],this[r(887)+r(1345)]),this[r(1576)+"er"]&&window[r(1550)+r(1436)+r(871)](r(659),this[r(887)+r(708)]),this._isBrowser&&window["removeEv"+r(1436)+r(871)](e[r(1570)],this[r(491)+r(1155)]),this._isBrowser&&window[r(1550)+r(1436)+r(871)](r(447),this[r(491)+r(786)])}[t(491)+t(1155)](r){let s=t;!r[s(1233)+"d"]&&(this._isBrowser&&window["removeEv"+s(1436)+s(871)](e[s(1570)],this[s(491)+s(1155)]),this[s(1576)+"er"]&&window[s(1550)+"entListe"+s(871)](e[s(1675)],this[s(491)+"ageShow"]),this[s(438)]()),this._isBrowser&&window["removeEv"+s(1436)+"ner"](s(1413),this[s(887)+s(1345)]),this[s(1576)+"er"]&&window[s(1550)+s(1436)+s(871)](s(659),this[s(887)+s(708)])}[t(491)+t(786)](r){let s=t;r[s(1233)+"d"]&&(this[s(987)+s(430)]()&&(!this[s(1594)]||e[s(1042)](this[s(1594)][s(743)+"te"],this.OPEN)||e[s(614)](this[s(1594)][s(743)+"te"],this.CONNECTING))&&this[s(887)+s(1345)](),this[s(1576)+"er"]&&window[s(1323)+s(1810)]("online",this[s(887)+s(1345)]),this[s(1576)+"er"]&&window[s(1323)+"Listener"](s(659),this[s(887)+s(708)]))}async[t(1483)+t(1778)](r){let s=t,{fpID:l,deviceID:h,bddID:g,ttwID:y,accessKey:k,aID:w,customParams:O={},enableAutoAck:H,enableQoS:F,QoSLevel:W,env:K}=this[s(979)],ce,be,ge;this._isBrowser||this[s(955)+"X"]||this[s(1636)+"T"]?(ce=location&&e[s(1422)](e[s(1289)],location[s(1612)])?e.UlwdF:s(846),be=r[s(893)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),ge=/^wss(.*:\/\/)/.test(r)?r:""+ce+be):(ce=e.UlwdF,be=r[s(893)](/(^http)((?:[s]*:\/\/))/,""),ge=/(^ws)((?:[s]*:\/\/))/[s(737)](be)?be:""+ce+be);let Ge=g?e.zGPVt:y?s(1533):e[s(1552)],_s=g||y||h;if(e[s(1095)](!_s,!Ge))throw new Error(e[s(426)]);let im=e[s(1325)](s(1115),typeof O)?await e[s(1406)](O):O,sm=K?Sg(K[s(1399)],K.xTTEnv):{},za=Object[s(730)]({device_platform:s(1261),version_code:e[s(504)],access_key:k,fpid:l,aid:w,[Ge]:_s,xsack:H?1:0,xaack:H?1:0,xsqos:F?1:0,qos_level:F?W:void 0,qos_sdk_version:2,...sm},im),om=Object[s(991)](za)[s(1449)]((Ua,Ha)=>za[Ha]!==void 0?""+Ua+(Ua?"&":"?")+Ha+"="+za[Ha]:Ua,"");return ge+s(756)+om}async _connect(){let r=t;if(!(this["_connect"+r(836)]||this._readyClosed)){this[r(892)+r(836)]=!0;try{let s=this._endpointManager?.[r(1887)+r(1460)+"ointReac"+r(1315)+r(1296)](),{timeoutInterval:l}=this._options;if(s){let g=this[r(1655)+r(1225)]?.[r(791)+r(1498)+"nt"](),y=this[r(1655)+r(1225)]?.[r(1424)+r(1230)+r(1068)+"UpdateCo"+r(769)](),k=this[r(1655)+"tManager"]?.[r(791)+"ntEndpointTriesC"+r(1152)]();if(y){let w=r(1824)+g+(r(1691)+r(1156)+"tries re"+r(1176)+r(569)+"backup e"+r(661))+y+" to retry",O=e.xWQTf(ht,e[r(1579)],{message:w,code:ln[r(1018)+"IES_ERROR"]});this[r(810)](w),this[r(1255)+"hErrorEv"+r(741)](O),this[r(1321)]=await this._generateUrl(y),this[r(810)]("connect "+y+" "+k+r(988)),this[r(1737)+r(739)+"rs"]()}else{let w="connect "+g+(r(1691)+r(1156)+r(1825)+r(1368));this[r(810)](w),this[r(1255)+r(1699)+"ent"](e[r(1561)](ht,r(749),{message:w,code:ln["MAX_RETR"+r(401)+"R"]}));return}}else{let g=this[r(1655)+r(1225)]?.[r(791)+r(1498)+r(843)+r(698)](),y=this[r(1655)+"tManager"]?.["getCurre"+r(1498)+r(833)+r(1152)]();this[r(1321)]=await this[r(1483)+r(1778)](e.lWJEl(g,"")),this._debug(r(1824)+g+" "+y+r(988)),this[r(1737)+"sListeners"]()}if(this[r(522)])this[r(522)]=!1;else{let g=e[r(1504)](Pa,e[r(593)],{message:e[r(1756)]});this.onStartReconnect&&this["onStartR"+r(1459)](g)}let h=this[r(1655)+"tManager"]?.["getCurrentEndpoi"+r(833)+r(1152)]()||0;e.EwMTo(h,1)&&await this[r(1017)](h-1),this._debug(r(1538)+"ng url: "+this[r(1321)]+(r(1354)+"ls: ")+this[r(740)+"ls"]),this[r(1594)]=e[r(1088)](bg,{url:this[r(1321)],protocols:[this[r(740)+"ls"]],headers:this[r(979)][r(755)+r(1294)+"s"]["customHt"+r(782)]},this[r(979)].ws),(this[r(1576)+"er"]||this[r(585)+"r"])&&this[r(1594)]&&(this[r(1594)].binaryType=this[r(1118)+r(473)]),this["_addWsLi"+r(1831)](),this["_connect"+r(1235)+"utId"]=setTimeout(this[r(644)+"ut"][r(1072)](this),l)}catch(s){if(e[r(1534)](e[r(840)],e[r(840)]))return this[r(1044)+"s"][this[r(1077)+r(990)]];throw this[r(892)+r(836)]=!1,s}}}[t(1318)+t(1795)](){let r=t;if(e[r(693)](e[r(1874)],r(867)))e[r(943)](clearTimeout,this["_connect"+r(1235)+r(1706)]),this[r(892)+r(1235)+"utId"]=null;else return _0xc197bd[_0x3496c4]=_0x47f5c1,!0}[t(1846)+t(1547)](){let r=t;clearTimeout(this._pingPongTimeoutId),e[r(1820)](clearTimeout,this[r(716)+r(647)+r(596)]),this[r(944)+r(1801)+"Id"]=null,this[r(716)+r(647)+r(596)]=null}_debug(...r){let s=t;this._options.debug&&console.log[s(662)](console,[e[s(735)],...r])}["_getInte"+t(535)+"e"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:g}=this[s(979)],y=e[s(1792)](l,Math.pow(g,e[s(424)](r,1)));return e.XThjh(y,h)?h:y}[t(1264)](){let r=t;if(this._ws&&this[r(1594)][r(743)+"te"]===this[r(1075)+"NG"]){this[r(1846)+r(1547)](),this[r(944)+"gTimeoutId"]=e.BXfZS(setTimeout,this._ping[r(1072)](this),this[r(979)][r(1418)+r(419)]);return}if(!this[r(1594)]||this[r(1594)].readyState!==this.OPEN)return void this[r(788)+"econnect"]();this[r(1594)]&&this[r(1594)][r(1383)]("hi"),this[r(716)+r(647)+r(596)]=e[r(450)](setTimeout,this[r(788)+r(1459)+r(921)][r(1072)](this),this[r(979)]["pingTime"+r(1725)+r(1650)])}[t(788)+"econnect"+t(921)](){let r=t;this[r(1638)+"sCounter"]?.addCount(),this[r(1700)](e[r(649)],r(1692)),this[r(1638)+r(1770)]?.["checkRea"+r(1229)+"nt"]()?this[r(788)+r(1459)]():this[r(1264)]()}[t(987)+t(430)](){let r=t;return this[r(1636)+"T"]||this[r(955)+"X"]?this[r(934)+r(1247)+r(502)]:(this[r(1576)+"er"]||this[r(585)+"r"])&&this._options[r(1721)+r(726)+r(1332)]?navigator[r(785)]:!0}[t(788)+t(1459)](){let r=t;!this[r(987)+r(430)]()||this[r(1178)+r(686)]||(this[r(1655)+r(1225)]?.[r(458)+r(653)+"fig"](),this._pingLossCounter?.[r(463)+r(1593)](),this[r(1594)]?this[r(1453)+r(1572)](1001,e.tJUZA,!0):this._connect())}["_onPageN"+t(1319)+t(845)](){let r=t;this[r(1636)+"T"]?tt["onNetwor"+r(753)+r(1769)](({isConnected:s})=>{let l=r;this[l(934)+l(1247)+l(502)]=s,s?this[l(887)+l(1345)]():this[l(887)+l(708)]()}):this[r(955)+"X"]&&wx[r(809)+"kStatusC"+r(1769)](({isConnected:s})=>{let l=r;this[l(934)+l(1247)+l(502)]=s,s?this[l(887)+l(1345)]():this[l(887)+l(708)]()})}[t(1017)](r){let s=t,l={lhYWs:function(h,g,y){return e.ZjuIe(h,g,y)}};if(e.LIDwa(s(1773),e[s(1419)]))return new Promise(h=>{let g=s;setTimeout(h,this[g(1398)+g(535)+"e"](r))});_0x5ecdb7(_0x103fcc,8),vrviNF.lhYWs(_0x29d623,_0xf76027,_0xdc9584)}["_disconn"+t(1572)](r=1e3,s="",l=!1){let h=t;this[h(1594)]&&this[h(1467)+h(1532)+"t"](r,s,l)}_onTimeout(){let r=t,s=this[r(1655)+r(1225)]?.[r(791)+"ntEndpoint"]();this._debug(r(1824)+s+r(1691)),this[r(1453)+r(1572)](1001,e[r(757)],!0)}_sendAck(r){let s=t,l=e[s(997)](jt,r);this[s(1594)]&&e[s(1878)](this[s(1594)][s(743)+"te"],this[s(1122)])&&(this._ws&&this[s(1594)][s(1383)](l),this._debug(e.UzHlg,r))}["_removeW"+t(739)+"rs"](){let r=t,s=e[r(1127)].split("|"),l=0;for(;;){switch(s[l++]){case"0":this._ws[r(1550)+"entListe"+r(871)](e[r(1071)],this[r(1342)]);continue;case"1":this[r(1594)][r(1550)+"entListe"+r(871)](e[r(1274)],this[r(881)]);continue;case"2":this._ws["removeEv"+r(1436)+r(871)](e[r(721)],this[r(1796)+"ge"]);continue;case"3":if(!this[r(1594)])return;continue;case"4":this[r(1594)][r(1550)+r(1436)+r(871)](r(749),this[r(657)]);continue}break}}["_addWsLi"+t(1831)](){let r=t,s=e.rykxa.split("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[r(1594)])return;continue;case"1":this[r(1594)][r(1323)+"Listener"](e[r(1579)],this[r(657)]);continue;case"2":this[r(1594)][r(1323)+r(1810)](e.oLoki,this._onOpen);continue;case"3":this[r(1594)][r(1323)+r(1810)](e.JYpKb,this[r(1796)+"ge"]);continue;case"4":this[r(1594)]["addEvent"+r(1810)](r(438),this[r(881)]);continue}break}}[t(1536)+t(870)](r=1e3,s=""){let l=t;try{this[l(1594)]&&this[l(1594)].close(r,s)}catch{}}[t(1467)+t(1532)+"t"](r=1e3,s="",l=!1){let h=t;if(this[h(1846)+"ngTimer"](),this["_clearTi"+h(1795)](),this[h(1737)+h(739)+"rs"](),this[h(1536)+"nceClose"](1e3,s),this[h(892)+"Lock"]=!1,l&&this[h(987)+"orOnline"]()&&!this[h(1178)+h(686)]){if(this[h(1655)+"tManager"]?.["checkRea"+h(1201)+"es"]()){let y=this["_endpoin"+h(1225)]?.[h(791)+h(1498)+"nt"]();this["_dispatc"+h(856)+h(741)](e[h(403)](bt,h(438),{code:1006,reason:h(1824)+y+(h(1691)+h(1156)+h(1825)+h(1368)),wasClean:!0}))}else{let y=this[h(979)][h(1624)+h(873)+"ptor"](r,s);this["_dispatc"+h(856)+h(741)](e[h(528)](bt,e[h(1274)],{code:r,reason:s,wasClean:!0,willReconnect:y})),y&&this[h(892)]()}return}this["_navigat"+h(430)]()||this[h(1178)+"osed"]?this[h(1255)+h(856)+h(741)](e[h(989)](bt,e[h(1274)],{code:r,reason:e.kyDiC})):this[h(1255)+h(856)+h(741)](e[h(482)](bt,e[h(1274)],{code:1006,reason:e.PeObR})),this[h(1594)]=null,this[h(1655)+h(1225)]?.["resetEnd"+h(653)+"fig"](),this[h(1638)+"sCounter"]?.["resetCou"+h(1593)]()}[t(1255)+t(656)+"nt"](r){let s=t;this.emit(e[s(1071)],r),this.onopen&&this.onopen(r)}["_dispatc"+t(1799)+t(1367)](r){let s=t;this[s(1700)](s(1813),r),this[s(1629)+"e"]&&this[s(1629)+"e"](r)}[t(1255)+t(1309)+t(1288)](r){let s=t;this.emit(s(783),r),this.onReceiveAck&&this["onReceiv"+s(1378)](r)}["_dispatc"+t(1699)+t(741)](r){let s=t;this[s(1700)](s(749),r),this[s(425)]&&this.onerror(r)}["_dispatc"+t(856)+t(741)](r){let s=t;this[s(1700)](e[s(1274)],r),this[s(1818)]&&this[s(1818)](r)}get[t(763)+"pe"](){let r=t;if(e[r(1608)](e.gNBUF,e[r(1360)])){let s=this[r(1531)].getStorageSync(this[r(842)]),l=_0x3c8d41[r(477)](s||"{}");return l[_0x5dbd84]=void 0,this[r(1531)]["setStora"+r(1782)](this[r(842)],_0x32cf51[r(1499)+"y"](l))}else return this[r(1594)]?this[r(1594)][r(763)+"pe"]:this["_binaryT"+r(473)]}set[t(763)+"pe"](r){let s=t;this[s(1118)+s(473)]=r,this._ws&&(this._ws.binaryType=r)}get[t(1394)+"nt"](){let r=t;return this[r(1655)+r(1225)]?.[r(791)+"ntEndpointTriesC"+r(1152)]()||0}get[t(423)+t(490)](){let r=t,s=this[r(1478)+"Queue"][r(1449)]((l,h)=>(l+=h&&h[r(1366)+"th"]||0,l),0);return e[r(1684)](s,this._ws?this._ws[r(423)+"Amount"]:0)}get[t(909)+"ns"](){let r=t,s={CVOUd:r(1813),ZvYdm:function(l,h,g){return e[r(422)](l,h,g)}};if(e[r(1712)](e.kracM,e[r(1166)]))return this[r(1594)]?this[r(1594)][r(909)+"ns"]:"";this[r(1700)](fTCCHT.CVOUd,fTCCHT[r(1409)](_0x300313,fTCCHT[r(516)],{..._0x3b7244}))}get[t(1612)](){let r=t;return this[r(1594)]?this[r(1594)][r(1612)]:""}get[t(743)+"te"](){let r=t;return this._ws?this._ws[r(743)+"te"]:this._options[r(800)+r(1583)]?this[r(1075)+"NG"]:this.CLOSED}get[t(645)](){let r=t;return this[r(1594)]?this[r(1594)][r(645)]:this[r(1321)]}close(r=1e3,s){let l=t,h=(l(1762)+l(1142)).split("|"),g=0;for(;;){switch(h[g++]){case"0":this[l(1467)+l(1532)+"t"](r,s);continue;case"1":if(e.nqrZx(this[l(1594)].readyState,this[l(1812)])||e[l(643)](this[l(1594)][l(743)+"te"],this[l(793)]))return void this._debug(e.OzVQB);continue;case"2":if(!this[l(1594)])return void this._debug(e.QVauF);continue;case"3":this[l(1846)+"ngTimer"]();continue;case"4":this["_dropGlo"+l(470)+l(1810)]();continue;case"5":this[l(1178)+l(686)]=!0;continue;case"6":this[l(1011)+l(950)]?.[l(1501)]();continue;case"7":this[l(1318)+"mer"]();continue}break}}async[t(1383)](r,s){let l=t,h={AJXUM:function(g,y){return e[B(524)](g,y)},olkwV:function(g,y){return g<y}};if(e[l(1740)](e.NdkfR,e[l(1067)]))_0x22a647=qlVDlI.AJXUM(31,_0x5ece81)<<6|qlVDlI.AJXUM(63,_0x4b6318),qlVDlI[l(1510)](_0x533279,128)?_0x1375f9+=_0x1e8087:(_0x4f7988+=_0x2b7514(_0x119b63),_0x1f6200++);else{if(e[l(1281)](null,r))throw new Error(e[l(936)]);e[l(884)]("number",typeof r)&&(r=JSON[l(1499)+"y"](r)),e.AvusI(e[l(1465)],typeof r)&&!(r instanceof ArrayBuffer)&&!(r[l(834)]&&r[l(834)]instanceof ArrayBuffer)&&(r=JSON[l(1499)+"y"](r));let g=await e[l(1508)](Ml,r),y=e.GZyFw(vg,r),{method:k=0,service:w=this[l(979)][l(935)],logID:O=this[l(979)][l(1686)+"erator"](),headers:H=this[l(979)][l(967)],payloadEncoding:F=this._options[l(700)+l(767)],payloadType:W=this[l(979)]["payloadT"+l(473)],logIDNew:K=this[l(979)][l(1440)+l(469)][l(615)+l(880)+"teLogIDNew"]?e.OksLq(i,this[l(979)][l(1440)+l(469)][l(1626)]):""}=e[l(617)](s,{});if(!w)throw new Error(l(1652)+l(1752)+l(651)+"ervice");let ce={SeqID:xe.fromNumber(this[l(1252)]++),LogID:xe[l(1223)+"er"](O),service:w,method:k,headers:H,payloadEncoding:F instanceof Object?F.encoding?F[l(1442)]:"":F,payloadType:e[l(1619)](W,Object)?W.type?W.type:y:W||y,payload:g,LogIDNew:K},be=e.UoHBI(jt,ce);return this[l(1594)]&&e[l(1219)](this[l(1594)].readyState,this[l(1122)])?(this[l(1594)]&&this[l(1594)][l(1383)](be),this[l(810)](l(554),ce)):e[l(1046)](this["_message"+l(475)].length,this[l(979)][l(1443)+"geQueueLength"])?(this[l(1478)+l(475)][l(489)](be),this[l(810)](e[l(1625)],ce)):(this[l(1478)+l(475)].shift(),this["_message"+l(475)].push(be)),{seqID:this._seqId,logID:O,logIDNew:K}}}async[t(1624)+"t"](r){let s=t,l={XRZmK:function(y,k){return e[B(992)](y,k)},FkzeA:e[s(610)],awviC:e[s(1352)]},{url:h}=r||{},g=Array[s(1613)](h)?h:e[s(1466)](e[s(1465)],typeof h)?[h]:[];r&&Object[s(730)](this[s(979)],r),g&&g.length?this._endpointManager=new Dl(g,this._options.maxRetries):this["_endpoin"+s(1225)]?.["resetEnd"+s(653)+s(1560)](),this[s(1638)+"sCounter"]?.[s(463)+s(1593)](this._options["pingLoss"+s(1651)]),this[s(1178)+s(686)]=!1,this._ws&&this._ws[s(743)+"te"]!==this[s(1812)]?this[s(1453)+"ect"](1e3,e[s(745)],!0):e[s(1534)](e.uPMRZ,e[s(822)])?_0x431455[s(1233)+"d"]&&(this["_navigat"+s(430)]()&&(!this[s(1594)]||FjEtGj[s(1231)](this[s(1594)][s(743)+"te"],this[s(1122)])||this._ws[s(743)+"te"]!==this[s(1075)+"NG"])&&this["_handleO"+s(1345)](),this[s(1576)+"er"]&&_0x3295f[s(1323)+s(1810)](FjEtGj.FkzeA,this[s(887)+s(1345)]),this[s(1576)+"er"]&&_0x4d998f[s(1323)+"Listener"](FjEtGj.awviC,this[s(887)+"ffLine"])):(this[s(522)]=!0,this[s(892)]())}async[t(570)](){let r=t;if(!this[r(892)+r(836)])if(e[r(1350)]===e.grhwC){let s=e.XDrzg[r(1432)]("|"),l=0;for(;;){switch(s[l++]){case"0":_0x484e24=e[r(924)](_0x30bd9e,_0x3b2f15[_0x58835b["cursor_n"+r(830)]],_0x438ba6,_0x3cf784);continue;case"1":_0x5e5f31[r(548)](e[r(925)],_0xe89570);continue;case"2":_0x42929f=e[r(882)](_0x59aa67,_0x22432d,_0x1c0337,_0x16642a[r(935)]||0);continue;case"3":_0x4f5155=_0xfb48fd(_0x3face8[r(464)+r(830)],_0x2b4f62,_0x308e61);continue;case"4":_0x19bdde[r(548)](e[r(658)],_0x5412c4);continue;case"5":_0x43050c[r(548)](e.HVsiL,_0xae951);continue;case"6":_0x1cc001[r(548)](e.vtDkr,_0x1d622d);continue;case"7":_0x557cd4=_0x3bd4a5(0,_0x1ddbc9,_0x323c72);continue;case"8":_0xb9d87c[r(548)](e[r(994)],_0x278dfe);continue;case"9":_0x11be48[r(548)](e.jsDFi,_0x4e784b,_0x3dc3a9[r(935)]);continue;case"10":_0x40bcb8=e[r(766)](_0x4e3ddb,_0x2099d9[r(1223)+"er"](_0x4ae779[r(514)]||_0x36c335),_0x42e34f,_0x2706b4);continue}break}}else{let s=(r(1349)+"1")[r(1432)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1178)+r(686)]=!1;continue;case"1":this[r(892)]();continue;case"2":this["_endpoin"+r(1225)]?.[r(458)+r(653)+r(1560)]();continue;case"3":this[r(522)]=!0;continue;case"4":this[r(1638)+r(1770)]?.resetCounter();continue}break}}}[t(1323)+t(1810)](r,s){this.on(r,s)}[t(847)+"Event"](r){let{type:s}=r;this.emit(s,r)}["removeEv"+t(1436)+t(871)](r,s){let l=t;e[l(599)](e[l(1730)],e[l(1657)])?e[l(1301)](_0x3063ac,this,_0x197c2b,[_0x1935c5,_0x5191e3,_0x3173a5,_0xa363d5,_0x7f815f,_0x556fdb]):this.off(r,s)}[t(592)](){let r=t,s={bdcRU:function(l,h){return e.OksLq(l,h)},eviSJ:function(l,h,g,y){return e[B(636)](l,h,g,y)},JLGtf:function(l,h){return e[B(1712)](l,h)},smhip:e.TJCDe,OmZJu:e[r(1062)],vLBui:r(1692),EMsMN:e[r(649)]};return new Promise((l,h)=>{let g=r,y={gzmRm:function(O,H){return O(H)},LvHEP:e[g(462)],APmmn:g(948)+g(557)+"s",dDcON:g(948)+"e_timeout"};this[g(1846)+g(1547)](),this[g(944)+g(1801)+"Id"]=e[g(1643)](setTimeout,this[g(1264)].bind(this),this[g(979)]["pingInte"+g(419)]);let k=()=>{let O=g;y[O(1875)](l,y.LvHEP),this[O(1397)](y[O(421)],k),this[O(1397)](y[O(916)],w)},w=()=>{let O=g,H={TFcAJ:function(F,W){return s[B(684)](F,W)},XUyhW:function(F,W,K,ce){return s[B(1275)](F,W,K,ce)}};if(s[O(439)](s[O(1314)],s[O(1485)]))s[O(684)](h,s[O(410)]),this[O(1397)](O(948)+O(557)+"s",k),this[O(1397)](s.EMsMN,w);else{let F=new _0x5c9ba5(cGbeAe.TFcAJ(_0x3217c8,_0x50ad5a));return cGbeAe[O(761)](_0x15d061,_0x5d8aaa,F,0),F}};this.on(e[g(484)],k),this.on(e[g(649)],w),this._ping()})}}})(),Ce[L(1677)+L(724)]=Ne[L(1677)+L(724)],Ce[L(418)+L(1158)]=Ne[L(418)+"rorEvent"],Ce.ErrorCode=Ne[L(911)+"e"],Ce[L(1367)]=Ne.Event,Ce[L(1113)]=Ne[L(1113)],Ce["Frontier"+L(1683)+L(1763)]=Ne[L(1759)+L(1683)+L(1763)],Ce["MessageE"+L(1763)]=Ne[L(1683)+L(1763)],Ce[L(841)+"t"]=Ne[L(841)+"t"],Ce[L(428)+L(823)]=Ne[L(428)+L(823)],Ce[L(705)+"oseEvent"]=Ne[L(705)+"oseEvent"],Ce[L(1207)+L(1158)]=Ne["createEr"+L(1158)],Ce[L(1300)+L(998)+"nt"]=Ne["createMe"+L(998)+"nt"],Ce[L(494)+"enEvent"]=Ne[L(494)+L(814)],Ce[L(1069)+"connectE"+L(1763)]=Ne[L(1069)+L(1480)+L(1763)],Ce[L(1384)+L(398)]=Ne[L(1384)+L(398)],Ce[L(595)+"ame"]=Ne[L(595)+"ame"];for(ca in Ne)[L(1677)+L(724),L(418)+L(1158),L(911)+"e","Event",L(1113),L(1759)+L(1683)+"vent","MessageE"+L(1763),L(841)+"t",L(428)+L(823),L(705)+"oseEvent",L(1207)+L(1158),"createMessageEvent",L(494)+L(814),"createRe"+L(1480)+"vent",L(1384)+L(398),L(595)+"ame"].indexOf(ca)===-1&&(Ce[ca]=Ne[ca]);var ca;Object[L(1512)+L(933)](Ce,L(1718)+"le",{value:!0})});import{existsSync as Y1,openSync as X1}from"node:fs";import{mkdir as Q1}from"node:fs/promises";import{dirname as eI}from"node:path";import{fileURLToPath as tI}from"node:url";function rI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function ll(t=Z()){return Y1(t.libEntry)?t.libEntry:tI(new URL("../index.ts",import.meta.url))}async function Rp(t={}){let e=t.paths??Z(),n=t.entryOverride??ll(e),i=rI(e,process.env.COZE_BRIDGE_LOG_MODE);await Q1(eI(i),{recursive:!0});let o=X1(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=at(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[xs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return nI.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var nI,xs,_a=it(()=>{"use strict";en();te();Pe();nI=G("spawn-daemon"),xs="COZE_BRIDGE_DAEMON"});import{spawn as eA}from"node:child_process";import{mkdir as tA,unlink as nA,writeFile as rA}from"node:fs/promises";import{dirname as iA,join as sA}from"node:path";function si(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function oA(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${si(n)}</key>
|
|
21
|
+
<string>${si(i)}</string>`).join(`
|
|
22
22
|
`);return e?`
|
|
23
23
|
<key>EnvironmentVariables</key>
|
|
24
24
|
<dict>
|
|
25
25
|
${e}
|
|
26
|
-
</dict>`:""}function
|
|
26
|
+
</dict>`:""}function aA(t,e){return new Promise((n,i)=>{let o=eA(t,e,{stdio:["ignore","pipe","pipe"]}),a="";o.stderr?.on("data",d=>{a+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var ii,ms,Ia,_l,Qp=it(()=>{"use strict";te();ii=G("supervisor.launchd"),ms="ai.coze.bridge",Ia=aA,_l={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
27
27
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
28
28
|
<plist version="1.0">
|
|
29
29
|
<dict>
|
|
30
30
|
<key>Label</key>
|
|
31
|
-
<string>${
|
|
31
|
+
<string>${ms}</string>
|
|
32
32
|
<key>ProgramArguments</key>
|
|
33
33
|
<array>
|
|
34
|
-
<string>${
|
|
35
|
-
<string>${
|
|
34
|
+
<string>${si(t.nodeBin)}</string>
|
|
35
|
+
<string>${si(t.entry)}</string>
|
|
36
36
|
<string>--daemon</string>
|
|
37
37
|
</array>
|
|
38
38
|
<key>RunAtLoad</key>
|
|
@@ -42,13 +42,13 @@ ${e}
|
|
|
42
42
|
<key>ThrottleInterval</key>
|
|
43
43
|
<integer>10</integer>
|
|
44
44
|
<key>StandardOutPath</key>
|
|
45
|
-
<string>${
|
|
45
|
+
<string>${si(t.logFile)}</string>
|
|
46
46
|
<key>StandardErrorPath</key>
|
|
47
|
-
<string>${
|
|
47
|
+
<string>${si(t.logFile)}</string>${oA(t.env)}
|
|
48
48
|
</dict>
|
|
49
49
|
</plist>
|
|
50
|
-
`},configPath(t){return
|
|
51
|
-
`):""}function
|
|
50
|
+
`},configPath(t){return sA(t.homeDir,"Library","LaunchAgents",`${ms}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await tA(iA(i),{recursive:!0}),await rA(i,this.renderConfig(t),"utf8"),ii.info("plist written",{plistPath:i,activate:n}),!n)return;await Ia("launchctl",["unload","-w",i]).catch(a=>ii.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await Ia("launchctl",["load","-w",i]),ii.info("launchd job loaded",{label:ms});let o=process.getuid?.()??0;await Ia("launchctl",["kickstart","-k",`gui/${o}/${ms}`]),ii.info("launchd job kickstarted",{label:ms,uid:o})},async uninstall(t){let e=this.configPath(t);await Ia("launchctl",["unload","-w",e]).catch(n=>ii.warn("launchctl unload failed (ignored)",{err:String(n)})),await nA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),ii.info("launchd job removed",{plistPath:e})}}});import{spawn as cA}from"node:child_process";import{mkdir as dA,unlink as lA,writeFile as uA}from"node:fs/promises";import{dirname as fA,join as eg}from"node:path";function ka(t,e){return t.isRoot?e:["--user",...e]}function xA(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
|
|
51
|
+
`):""}function Ta(t,e){return new Promise((n,i)=>{let o=cA(t,e,{stdio:["ignore","pipe","pipe"]}),a="";o.stderr?.on("data",d=>{a+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var Aa,oi,hA,yl,tg=it(()=>{"use strict";te();Aa=G("supervisor.systemd"),oi="coze-bridge.service",hA="/etc/systemd/system";yl={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
|
-
${
|
|
62
|
+
${xA(t.env)}
|
|
63
63
|
[Install]
|
|
64
64
|
WantedBy=${e}
|
|
65
|
-
`},configPath(t){return t.isRoot?eg(
|
|
65
|
+
`},configPath(t){return t.isRoot?eg(hA,oi):eg(t.homeDir,".config","systemd","user",oi)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await dA(fA(i),{recursive:!0}),await uA(i,this.renderConfig(t),"utf8"),Aa.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await Ta("systemctl",ka(t,["daemon-reload"])),await Ta("systemctl",ka(t,n?["enable","--now",oi]:["enable",oi])),Aa.info("systemd unit enabled",{unitName:oi,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await Ta("systemctl",ka(t,["disable","--now",oi])).catch(n=>Aa.warn("systemctl disable failed (ignored)",{err:String(n)})),await lA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Ta("systemctl",ka(t,["daemon-reload"])).catch(()=>{}),Aa.info("systemd unit removed",{unitPath:e})}}});import{spawn as pA}from"node:child_process";import{join as gA}from"node:path";function ng(t,e){return new Promise((n,i)=>{let o=pA(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),a="";o.stderr?.on("data",d=>{a+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var bl,Ca,El,rg=it(()=>{"use strict";te();bl=G("supervisor.taskscheduler"),Ca="CozeBridge",El={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,64 +86,65 @@ WantedBy=${e}
|
|
|
86
86
|
</Exec>
|
|
87
87
|
</Actions>
|
|
88
88
|
</Task>
|
|
89
|
-
`},configPath(t){return g2(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 ng("schtasks",["/Create","/SC","ONLOGON","/TN",Aa,"/TR",n,"/RU",t.userName,"/F"]),_l.info("task scheduler entry created",{task:Aa,logFile:t.logFile})},async uninstall(t){await ng("schtasks",["/Delete","/TN",Aa,"/F"]).catch(e=>_l.warn("schtasks /Delete failed (ignored)",{err:String(e)})),_l.info("task scheduler entry removed",{task:Aa})}}});var ig={};Ha(ig,{buildContext:()=>E2,getSupervisor:()=>_2,launchdSupervisor:()=>ml,systemdSupervisor:()=>wl,taskSchedulerSupervisor:()=>yl});import{homedir as m2,userInfo as w2}from"node:os";function _2(t=process.platform){switch(t){case"darwin":return ml;case"linux":return wl;case"win32":return yl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function b2(){let t={};for(let e of y2){let n=process.env[e];n&&(t[e]=n)}return t}function E2(){let t=V();return{nodeBin:process.execPath,entry:cl(t),logFile:t.logFile,homeDir:m2(),userName:w2().username,isRoot:process.getuid?.()===0,env:b2()}}var y2,sg=nt(()=>{"use strict";Ae();ma();Qp();tg();rg();y2=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();un();var Xl=U("acp-installer-warmup"),Om=["claude-code","codex"];async function Ql(t={}){let e=t.ensure??pr,i=(await Promise.allSettled(Om.map(async o=>{let a=await e(o);Xl.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&Xl.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))})}jt();te();import{readdir as Jm}from"node:fs/promises";import{mkdir as ru,readFile as $m,writeFile as iu}from"node:fs/promises";import{join as Va}from"node:path";var Vm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function gr(t,e,n){await ru(t,{recursive:!0});let i=Vm[e],o=Va(t,i);return await iu(o,n??"","utf8"),o}async function Ja(t,e,n){let i=Va(t,".claude");await ru(i,{recursive:!0});let o=Va(i,"settings.local.json"),a={};try{let u=await $m(o,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(a=h)}catch{}let d=typeof a.permissions=="object"&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",a.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return a.permissions=d,await iu(o,JSON.stringify(a,null,2),"utf8"),o}var Xe=U("agent-detail-sync"),Zm=6e4,Ym=5*6e4,Ts=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await Jm(n)}catch(o){Xe.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}Xe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let a=await Ee(o,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){Xe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,a)}catch(d){Xe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Xe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&n.push(i);if(n.length!==0){Xe.info("retrying pending detail syncs",{count:n.length});for(let i of n)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,n){let i=n??await Ee(e,this.opts.paths);if(!i){Xe.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(h){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),g=x?Math.min(x.currentDelay*2,Ym):Zm;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 a=!1,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,a=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,a=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,a=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Xe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):o.deployType&&Xe.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){Xe.debug("detail sync: no diff",{agentId:e});return}await He(i,this.opts.paths),Xe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Xe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await gr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Ed=Gt(Bu(),1);import{createHash as Hy}from"node:crypto";import{lstat as xd,mkdir as pd,readFile as So,readdir as P0,rm as gd,stat as yd,writeFile as md}from"node:fs/promises";import{homedir as Gy}from"node:os";import{basename as A0,dirname as qy,join as ue,normalize as jy,relative as bd,resolve as wd,sep as R0}from"node:path";import{Readable as D0}from"node:stream";import{pipeline as O0}from"node:stream/promises";import _w from"events";import it from"fs";import{EventEmitter as Jc}from"node:events";import yf from"node:stream";import{StringDecoder as yw}from"node:string_decoder";import vf from"node:path";import Tr from"node:fs";import{dirname as Ow,parse as Nw}from"path";import{EventEmitter as Gw}from"events";import Pc from"assert";import{Buffer as Wn}from"buffer";import*as Gu from"zlib";import qw from"zlib";import{posix as br}from"node:path";import{basename as m_}from"node:path";import oo from"fs";import Dt from"fs";import Zu from"path";import{win32 as P_}from"node:path";import rf from"path";import Ff from"node:fs";import $_ from"node:assert";import{randomBytes as zf}from"node:crypto";import oe from"node:fs";import Fe from"node:path";import Uf from"fs";import go from"node:fs";import Oi from"node:path";import ct from"node:fs";import ey from"node:fs/promises";import lo from"node:path";import{join as Yf}from"node:path";import at from"node:fs";import e0 from"node:path";var mw=Object.defineProperty,ww=(t,e)=>{for(var n in e)mw(t,n,{get:e[n],enumerable:!0})},Fu=typeof process=="object"&&process?process:{stdout:null,stderr:null},bw=t=>!!t&&typeof t=="object"&&(t instanceof Vn||t instanceof yf||Ew(t)||vw(t)),Ew=t=>!!t&&typeof t=="object"&&t instanceof Jc&&typeof t.pipe=="function"&&t.pipe!==yf.Writable.prototype.pipe,vw=t=>!!t&&typeof t=="object"&&t instanceof Jc&&typeof t.write=="function"&&typeof t.end=="function",Wt=Symbol("EOF"),Kt=Symbol("maybeEmitEnd"),pn=Symbol("emittedEnd"),Os=Symbol("emittingEnd"),pi=Symbol("emittedError"),Ns=Symbol("closed"),zu=Symbol("read"),Ls=Symbol("flush"),Uu=Symbol("flushChunk"),yt=Symbol("encoding"),yr=Symbol("decoder"),Ge=Symbol("flowing"),gi=Symbol("paused"),Ir=Symbol("resume"),qe=Symbol("buffer"),Qe=Symbol("pipes"),je=Symbol("bufferLength"),tc=Symbol("bufferPush"),Ms=Symbol("bufferShift"),Ye=Symbol("objectMode"),Te=Symbol("destroyed"),nc=Symbol("error"),rc=Symbol("emitData"),Hu=Symbol("emitEnd"),ic=Symbol("emitEnd2"),Tt=Symbol("async"),sc=Symbol("abort"),Bs=Symbol("aborted"),mi=Symbol("signal"),Mn=Symbol("dataListeners"),ot=Symbol("discarded"),wi=t=>Promise.resolve().then(t),Sw=t=>t(),Iw=t=>t==="end"||t==="finish"||t==="prefinish",kw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Aw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),bf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Ir](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Tw=class extends bf{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)}},Cw=t=>!!t.objectMode,Pw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Vn=class extends Jc{[Ge]=!1;[gi]=!1;[Qe]=[];[qe]=[];[Ye];[yt];[Tt];[yr];[Wt]=!1;[pn]=!1;[Os]=!1;[Ns]=!1;[pi]=null;[je]=0;[Te]=!1;[mi];[Bs]=!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");Cw(e)?(this[Ye]=!0,this[yt]=null):Pw(e)?(this[yt]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[yt]=null),this[Tt]=!!e.async,this[yr]=this[yt]?new yw(this[yt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[qe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:n}=e;n&&(this[mi]=n,n.aborted?this[sc]():n.addEventListener("abort",()=>this[sc]()))}get bufferLength(){return this[je]}get encoding(){return this[yt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Tt]}set async(t){this[Tt]=this[Tt]||!!t}[sc](){this[Bs]=!0,this.emit("abort",this[mi]?.reason),this.destroy(this[mi]?.reason)}get aborted(){return this[Bs]}set aborted(t){}write(t,e,n){if(this[Bs])return!1;if(this[Wt])throw new Error("write after end");if(this[Te])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[Tt]?wi:Sw;if(!this[Ye]&&!Buffer.isBuffer(t)){if(Aw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(kw(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[Ge]&&this[je]!==0&&this[Ls](!0),this[Ge]?this.emit("data",t):this[tc](t),this[je]!==0&&this.emit("readable"),n&&i(n),this[Ge]):t.length?(typeof t=="string"&&!(e===this[yt]&&!this[yr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[yt]&&(t=this[yr].write(t)),this[Ge]&&this[je]!==0&&this[Ls](!0),this[Ge]?this.emit("data",t):this[tc](t),this[je]!==0&&this.emit("readable"),n&&i(n),this[Ge]):(this[je]!==0&&this.emit("readable"),n&&i(n),this[Ge])}read(t){if(this[Te])return null;if(this[ot]=!1,this[je]===0||t===0||t&&t>this[je])return this[Kt](),null;this[Ye]&&(t=null),this[qe].length>1&&!this[Ye]&&(this[qe]=[this[yt]?this[qe].join(""):Buffer.concat(this[qe],this[je])]);let e=this[zu](t||null,this[qe][0]);return this[Kt](),e}[zu](t,e){if(this[Ye])this[Ms]();else{let n=e;t===n.length||t===null?this[Ms]():typeof n=="string"?(this[qe][0]=n.slice(t),e=n.slice(0,t),this[je]-=t):(this[qe][0]=n.subarray(t),e=n.subarray(0,t),this[je]-=t)}return this.emit("data",e),!this[qe].length&&!this[Wt]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[Wt]=!0,this.writable=!1,(this[Ge]||!this[gi])&&this[Kt](),this}[Ir](){this[Te]||(!this[Mn]&&!this[Qe].length&&(this[ot]=!0),this[gi]=!1,this[Ge]=!0,this.emit("resume"),this[qe].length?this[Ls]():this[Wt]?this[Kt]():this.emit("drain"))}resume(){return this[Ir]()}pause(){this[Ge]=!1,this[gi]=!0,this[ot]=!1}get destroyed(){return this[Te]}get flowing(){return this[Ge]}get paused(){return this[gi]}[tc](t){this[Ye]?this[je]+=1:this[je]+=t.length,this[qe].push(t)}[Ms](){return this[Ye]?this[je]-=1:this[je]-=this[qe][0].length,this[qe].shift()}[Ls](t=!1){do;while(this[Uu](this[Ms]())&&this[qe].length);!t&&!this[qe].length&&!this[Wt]&&this.emit("drain")}[Uu](t){return this.emit("data",t),this[Ge]}pipe(t,e){if(this[Te])return t;this[ot]=!1;let n=this[pn];return e=e||{},t===Fu.stdout||t===Fu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[Qe].push(e.proxyErrors?new Tw(this,t,e):new bf(this,t,e)),this[Tt]?wi(()=>this[Ir]()):this[Ir]()),t}unpipe(t){let e=this[Qe].find(n=>n.dest===t);e&&(this[Qe].length===1?(this[Ge]&&this[Mn]===0&&(this[Ge]=!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 n=super.on(t,e);if(t==="data")this[ot]=!1,this[Mn]++,!this[Qe].length&&!this[Ge]&&this[Ir]();else if(t==="readable"&&this[je]!==0)super.emit("readable");else if(Iw(t)&&this[pn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[pi]){let i=e;this[Tt]?wi(()=>i.call(this,this[pi])):i.call(this,this[pi])}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[Qe].length&&(this[Ge]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Mn]=0,!this[ot]&&!this[Qe].length&&(this[Ge]=!1)),e}get emittedEnd(){return this[pn]}[Kt](){!this[Os]&&!this[pn]&&!this[Te]&&this[qe].length===0&&this[Wt]&&(this[Os]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ns]&&this.emit("close"),this[Os]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Te&&this[Te])return!1;if(t==="data")return!this[Ye]&&!n?!1:this[Tt]?(wi(()=>this[rc](n)),!0):this[rc](n);if(t==="end")return this[Hu]();if(t==="close"){if(this[Ns]=!0,!this[pn]&&!this[Te])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[pi]=n,super.emit(nc,n);let o=!this[mi]||this.listeners("error").length?super.emit("error",n):!1;return this[Kt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Kt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[Kt](),i}[rc](t){for(let n of this[Qe])n.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[Kt](),e}[Hu](){return this[pn]?!1:(this[pn]=!0,this.readable=!1,this[Tt]?(wi(()=>this[ic]()),!0):this[ic]())}[ic](){if(this[yr]){let e=this[yr].end();if(e){for(let n of this[Qe])n.dest.write(e);this[ot]||super.emit("data",e)}}for(let e of this[Qe])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ye]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Ye]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Ye])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[yt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Te,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ot]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[Wt])return e();let i,o,a=x=>{this.off("data",d),this.off("end",u),this.off(Te,h),e(),o(x)},d=x=>{this.off("error",a),this.off("end",u),this.off(Te,h),this.pause(),i({value:x,done:!!this[Wt]})},u=()=>{this.off("error",a),this.off("data",d),this.off(Te,h),e(),i({done:!0,value:void 0})},h=()=>a(new Error("stream destroyed"));return new Promise((x,g)=>{o=g,i=x,this.once(Te,h),this.once("error",a),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(nc,e),this.off(Te,e),this.off("end",e),t=!0,{done:!0,value:void 0}),n=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(nc,e),this.once(Te,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Te])return t?this.emit("error",t):this.emit(Te),this;this[Te]=!0,this[ot]=!0,this[qe].length=0,this[je]=0;let e=this;return typeof e.close=="function"&&!this[Ns]&&e.close(),t?this.emit("error",t):this.emit(Te),this}static get isStream(){return bw}},Rw=it.writev,Sn=Symbol("_autoClose"),St=Symbol("_close"),_i=Symbol("_ended"),le=Symbol("_fd"),oc=Symbol("_finished"),Zt=Symbol("_flags"),ac=Symbol("_flush"),Tc=Symbol("_handleChunk"),Cc=Symbol("_makeBuf"),Ri=Symbol("_mode"),Fs=Symbol("_needDrain"),Pr=Symbol("_onerror"),Rr=Symbol("_onopen"),cc=Symbol("_onread"),kr=Symbol("_onwrite"),In=Symbol("_open"),vt=Symbol("_path"),_n=Symbol("_pos"),Ct=Symbol("_queue"),Ar=Symbol("_read"),dc=Symbol("_readSize"),Jt=Symbol("_reading"),yi=Symbol("_remain"),lc=Symbol("_size"),Vs=Symbol("_write"),Bn=Symbol("_writing"),Js=Symbol("_defaultFlag"),jn=Symbol("_errored"),Zc=class extends Vn{[jn]=!1;[le];[vt];[dc];[Jt]=!1;[lc];[yi];[Sn];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[jn]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[vt]=t,this[dc]=e.readSize||16*1024*1024,this[Jt]=!1,this[lc]=typeof e.size=="number"?e.size:1/0,this[yi]=this[lc],this[Sn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[Ar]():this[In]()}get fd(){return this[le]}get path(){return this[vt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[In](){it.open(this[vt],"r",(t,e)=>this[Rr](t,e))}[Rr](t,e){t?this[Pr](t):(this[le]=e,this.emit("open",e),this[Ar]())}[Cc](){return Buffer.allocUnsafe(Math.min(this[dc],this[yi]))}[Ar](){if(!this[Jt]){this[Jt]=!0;let t=this[Cc]();if(t.length===0)return process.nextTick(()=>this[cc](null,0,t));it.read(this[le],t,0,t.length,null,(e,n,i)=>this[cc](e,n,i))}}[cc](t,e,n){this[Jt]=!1,t?this[Pr](t):this[Tc](e,n)&&this[Ar]()}[St](){if(this[Sn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Pr](t){this[Jt]=!0,this[St](),this.emit("error",t)}[Tc](t,e){let n=!1;return this[yi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[yi]<=0)&&(n=!1,this[St](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[Ar](),!1;case"error":return this[jn]?!1:(this[jn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Dw=class extends Zc{[In](){let t=!0;try{this[Rr](null,it.openSync(this[vt],"r")),t=!1}finally{t&&this[St]()}}[Ar](){let t=!0;try{if(!this[Jt]){this[Jt]=!0;do{let e=this[Cc](),n=e.length===0?0:it.readSync(this[le],e,0,e.length,null);if(!this[Tc](n,e))break}while(!0);this[Jt]=!1}t=!1}finally{t&&this[St]()}}[St](){if(this[Sn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}},uo=class extends _w{readable=!1;writable=!0;[jn]=!1;[Bn]=!1;[_i]=!1;[Ct]=[];[Fs]=!1;[vt];[Ri];[Sn];[le];[Js];[Zt];[oc]=!1;[_n];constructor(t,e){e=e||{},super(e),this[vt]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Ri]=e.mode===void 0?438:e.mode,this[_n]=typeof e.start=="number"?e.start:void 0,this[Sn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[_n]!==void 0?"r+":"w";this[Js]=e.flags===void 0,this[Zt]=e.flags===void 0?n:e.flags,this[le]===void 0&&this[In]()}emit(t,...e){if(t==="error"){if(this[jn])return!1;this[jn]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[vt]}[Pr](t){this[St](),this[Bn]=!0,this.emit("error",t)}[In](){it.open(this[vt],this[Zt],this[Ri],(t,e)=>this[Rr](t,e))}[Rr](t,e){this[Js]&&this[Zt]==="r+"&&t&&t.code==="ENOENT"?(this[Zt]="w",this[In]()):t?this[Pr](t):(this[le]=e,this.emit("open",e),this[Bn]||this[ac]())}end(t,e){return t&&this.write(t,e),this[_i]=!0,!this[Bn]&&!this[Ct].length&&typeof this[le]=="number"&&this[kr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[_i]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[Bn]||this[Ct].length?(this[Ct].push(t),this[Fs]=!0,!1):(this[Bn]=!0,this[Vs](t),!0)}[Vs](t){it.write(this[le],t,0,t.length,this[_n],(e,n)=>this[kr](e,n))}[kr](t,e){t?this[Pr](t):(this[_n]!==void 0&&typeof e=="number"&&(this[_n]+=e),this[Ct].length?this[ac]():(this[Bn]=!1,this[_i]&&!this[oc]?(this[oc]=!0,this[St](),this.emit("finish")):this[Fs]&&(this[Fs]=!1,this.emit("drain"))))}[ac](){if(this[Ct].length===0)this[_i]&&this[kr](null,0);else if(this[Ct].length===1)this[Vs](this[Ct].pop());else{let t=this[Ct];this[Ct]=[],Rw(this[le],t,this[_n],(e,n)=>this[kr](e,n))}}[St](){if(this[Sn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Ef=class extends uo{[In](){let t;if(this[Js]&&this[Zt]==="r+")try{t=it.openSync(this[vt],this[Zt],this[Ri])}catch(e){if(e?.code==="ENOENT")return this[Zt]="w",this[In]();throw e}else t=it.openSync(this[vt],this[Zt],this[Ri]);this[Rr](null,t)}[St](){if(this[Sn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}[Vs](t){let e=!0;try{this[kr](null,it.writeSync(this[le],t,0,t.length,this[_n])),e=!1}finally{if(e)try{this[St]()}catch{}}}},Lw=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"]]),Mw=t=>!!t.sync&&!!t.file,Bw=t=>!t.sync&&!!t.file,Fw=t=>!!t.sync&&!t.file,zw=t=>!t.sync&&!t.file,Uw=t=>!!t.file,Hw=t=>Lw.get(t)||t,Yc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=Hw(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Ui=(t,e,n,i,o)=>Object.assign((a=[],d,u)=>{Array.isArray(a)&&(d=a,a={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let h=Yc(a);if(o?.(h,d),Mw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(Bw(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(Fw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(h,d)}else if(zw(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:o}),jw=qw.constants||{ZLIB_VERNUM:4736},Nt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},jw)),Ww=Wn.concat,qu=Object.getOwnPropertyDescriptor(Wn,"concat"),Kw=t=>t,uc=qu?.writable===!0||qu?.set!==void 0?t=>{Wn.concat=t?Kw:Ww}:t=>{},Kn=Symbol("_superWrite"),zs=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},fc=Symbol("flushFlag"),Xc=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 Gu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Gu[e](t)}catch(n){throw new zs(n,this.constructor)}this.#o=n=>{this.#e||(this.#e=!0,this.close(),this.emit("error",n))},this.#t?.on("error",n=>this.#o(new zs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Pc(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),{[fc]: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;Pc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},uc(!0);let d;try{let h=typeof t[fc]=="number"?t[fc]:this.#r;d=this.#t._processChunk(t,h),uc(!1)}catch(h){uc(!1),this.#o(new zs(h,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=a,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",h=>this.#o(new zs(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}},Sf=class extends Xc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Nt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Nt.Z_FINISH,t.fullFlushFlag=Nt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Nt.Z_SYNC_FLUSH),Pc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},$w=class extends Sf{#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)}},Vw=class extends Sf{constructor(t){super(t,"Unzip")}},If=class extends Xc{constructor(t,e){t=t||{},t.flush=t.flush||Nt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Nt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Nt.BROTLI_OPERATION_FLUSH,super(t,e)}},Jw=class extends If{constructor(t){super(t,"BrotliCompress")}},Zw=class extends If{constructor(t){super(t,"BrotliDecompress")}},kf=class extends Xc{constructor(t,e){t=t||{},t.flush=t.flush||Nt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Nt.ZSTD_e_end,t.fullFlushFlag=Nt.ZSTD_e_flush,super(t,e)}},Yw=class extends kf{constructor(t){super(t,"ZstdCompress")}},Xw=class extends kf{constructor(t){super(t,"ZstdDecompress")}},Qw=(t,e)=>{if(Number.isSafeInteger(t))t<0?t_(t,e):e_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},e_=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},t_=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),n?e[i-1]=Af(o):o===0?e[i-1]=0:(n=!0,e[i-1]=Tf(o))}},n_=t=>{let e=t[0],n=e===128?i_(t.subarray(1,t.length)):e===255?r_(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},r_=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var a=Number(t[o]),d;i?d=Af(a):a===0?d=a:(i=!0,d=Tf(a)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},i_=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(n+=o*Math.pow(256,e-i-1))}return n},Af=t=>(255^t)&255,Tf=t=>(255^t)+1&255,s_={};ww(s_,{code:()=>Qc,isCode:()=>Zs,isName:()=>o_,name:()=>fo,normalFsTypes:()=>Cf});var Zs=t=>fo.has(t),o_=t=>Qc.has(t),Cf=new Set(["0","","1","2","3","4","5","6","7","D"]),fo=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Qc=new Map(Array.from(fo).map(t=>[t[1],t[0]])),a_=t=>t===void 0||t<0?void 0:t,$n=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=Fn(t,e+156,1),a=Cf.has(o),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??Fn(t,e,100),this.mode=d?.mode??u?.mode??yn(t,e+100,8),this.uid=d?.uid??u?.uid??yn(t,e+108,8),this.gid=d?.gid??u?.gid??yn(t,e+116,8),this.size=a_(d?.size??u?.size??yn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??hc(t,e+136,12),this.cksum=yn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Zs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Fn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Fn(t,e+265,32),this.gname=d?.gname??u?.gname??Fn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??yn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??yn(t,e+337,8)??0,t[e+475]!==0){let x=Fn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Fn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??hc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??hc(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==="size"&&Number(i)<0||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,i=c_(this.path||"",n),o=i[0],a=i[1];this.needPax=!!i[2],this.needPax=zn(t,e,100,o)||this.needPax,this.needPax=bn(t,e+100,8,this.mode)||this.needPax,this.needPax=bn(t,e+108,8,this.uid)||this.needPax,this.needPax=bn(t,e+116,8,this.gid)||this.needPax,this.needPax=bn(t,e+124,12,this.size)||this.needPax,this.needPax=xc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=zn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=zn(t,e+265,32,this.uname)||this.needPax,this.needPax=zn(t,e+297,32,this.gname)||this.needPax,this.needPax=bn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=bn(t,e+337,8,this.devmin)||this.needPax,this.needPax=zn(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=zn(t,e+345,155,a)||this.needPax:(this.needPax=zn(t,e+345,130,a)||this.needPax,this.needPax=xc(t,e+476,12,this.atime)||this.needPax,this.needPax=xc(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,bn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:fo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Qc.get(t));if(Zs(e)||e==="Unsupported")this.#e=e;else if(Zs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},c_=(t,e)=>{let n=t,i="",o,a=br.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=br.dirname(n),n=br.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?o=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?o=[n.slice(0,99),i,!0]:(n=br.join(br.basename(i),n),i=br.dirname(i));while(i!==a&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Fn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),hc=(t,e,n)=>d_(yn(t,e,n)),d_=t=>t===void 0?void 0:new Date(t*1e3),yn=(t,e,n)=>Number(t[e])&128?n_(t.subarray(e,e+n)):u_(t,e,n),l_=t=>isNaN(t)?void 0:t,u_=(t,e,n)=>l_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),f_={12:8589934591,8:2097151},bn=(t,e,n,i)=>i===void 0?!1:i>f_[n]||i<0?(Qw(i,t.subarray(e,e+n)),!0):(h_(t,e,n,i),!1),h_=(t,e,n,i)=>t.write(x_(i,n),e,n,"ascii"),x_=(t,e)=>p_(Math.floor(t).toString(8),e),p_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",xc=(t,e,n,i)=>i===void 0?!1:bn(t,e,n,i.getTime()/1e3),g_=new Array(156).join("\0"),zn=(t,e,n,i)=>i===void 0?!1:(t.write(i+g_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),so=class Pf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),o=Buffer.allocUnsafe(i);for(let a=0;a<512;a++)o[a]=0;new $n({path:("PaxHeader/"+m_(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,n,"utf8");for(let a=n+512;a<o.length;a++)o[a]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let n=this[e],i=n instanceof Date?n.getTime()/1e3:n,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
|
|
90
|
-
`,a=Buffer.byteLength(o),d=Math.floor(Math.log(a)/Math.log(10))+1;return a+d>=Math.pow(10,d)&&(d+=1),d+a+o}static parse(e,n,i=!1){return new
|
|
91
|
-
`).reduce(y_,Object.create(null)),y_=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let a=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(a){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[a]=d;break;case"ctime":case"atime":case"mtime":t[a]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[a]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[a]=+d;break}return t},b_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=b_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),E_=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=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),n&&this.#e(n,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let n=this.remain,i=this.blockRemain;return this.remain=Math.max(0,n-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:n>=e?super.write(t):super.write(t.subarray(0,n))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},ho=(t,e,n,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=n instanceof Error&&n.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(n instanceof Error&&(i=Object.assign(n,i),n=n.message),t.emit("warn",e,n,i)):n instanceof Error?t.emit("error",Object.assign(n,i)):t.emit("error",Object.assign(new Error(`${e}: ${n}`),i))},v_=1024*1024,Rc=Buffer.from([31,139]),Dc=Buffer.from([40,181,47,253]),S_=Math.max(Rc.length,Dc.length),ft=Symbol("state"),Un=Symbol("writeEntry"),$t=Symbol("readEntry"),pc=Symbol("nextEntry"),ju=Symbol("processEntry"),Pt=Symbol("extendedHeader"),bi=Symbol("globalExtendedHeader"),gn=Symbol("meta"),Wu=Symbol("emitMeta"),ge=Symbol("buffer"),Vt=Symbol("queue"),mn=Symbol("ended"),gc=Symbol("emittedEnd"),Hn=Symbol("emit"),Ie=Symbol("unzip"),Us=Symbol("consumeChunk"),Hs=Symbol("consumeChunkSub"),mc=Symbol("consumeBody"),Ku=Symbol("consumeMeta"),$u=Symbol("consumeHeader"),Ei=Symbol("consuming"),wc=Symbol("bufferConcat"),Gs=Symbol("maybeEnd"),Er=Symbol("writing"),Rt=Symbol("aborted"),qs=Symbol("onDone"),Gn=Symbol("sawValidEntry"),js=Symbol("sawNullBlock"),Ws=Symbol("sawEOF"),Vu=Symbol("closeStream"),I_=1e3,vi=Symbol("compressedBytesRead"),_c=Symbol("decompressedBytesRead"),Ju=Symbol("checkDecompressionRatio"),k_=()=>!0,zi=class extends Gw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[Vt]=[];[ge];[$t];[Un];[ft]="begin";[gn]="";[Pt];[bi];[mn]=!1;[Ie];[Rt]=!1;[Gn];[js]=!1;[Ws]=!1;[Er]=!1;[Ei]=!1;[gc]=!1;[vi]=0;[_c]=0;constructor(t={}){super(),this.file=t.file||"",this.on(qs,()=>{(this[ft]==="begin"||this[Gn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(qs,t.ondone):this.on(qs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:I_,this.maxMetaEntrySize=t.maxMetaEntrySize||v_,this.filter=typeof t.filter=="function"?t.filter:k_;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[Vu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){ho(this,t,e,n)}[$u](t,e){this[Gn]===void 0&&(this[Gn]=!1);let n;try{n=new $n(t,e,this[Pt],this[bi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[js]?(this[Ws]=!0,this[ft]==="begin"&&(this[ft]="header"),this[Hn]("eof")):(this[js]=!0,this[Hn]("nullBlock"));else if(this[js]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let o=this[Un]=new E_(n,this[Pt],this[bi]);if(!this[Gn])if(o.remain){let a=()=>{o.invalid||(this[Gn]=!0)};o.on("end",a)}else this[Gn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Hn]("ignoredEntry",o),this[ft]="ignore",o.resume()):o.size>0&&(this[gn]="",o.on("data",a=>this[gn]+=a),this[ft]="meta"):(this[Pt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Hn]("ignoredEntry",o),this[ft]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ft]="body":(this[ft]="header",o.end()),this[$t]?this[Vt].push(o):(this[Vt].push(o),this[pc]())))}}}[Vu](){queueMicrotask(()=>this.emit("close"))}[ju](t){let e=!0;if(!t)this[$t]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[$t]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[pc]()),e=!1);return e}[pc](){do;while(this[ju](this[Vt].shift()));if(this[Vt].length===0){let t=this[$t];!t||t.flowing||t.size===t.remain?this[Er]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[mc](t,e){let n=this[Un];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(o),n.blockRemain||(this[ft]="header",this[Un]=void 0,n.end()),o.length}[Ku](t,e){let n=this[Un],i=this[mc](t,e);return!this[Un]&&n&&this[Wu](n),i}[Hn](t,e,n){this[Vt].length===0&&!this[$t]?this.emit(t,e,n):this[Vt].push([t,e,n])}[Wu](t){switch(this[Hn]("meta",this[gn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Pt]=so.parse(this[gn],this[Pt],!1);break;case"GlobalExtendedHeader":this[bi]=so.parse(this[gn],this[bi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Pt]??Object.create(null);this[Pt]=e,e.path=this[gn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Pt]||Object.create(null);this[Pt]=e,e.linkpath=this[gn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Rt]){if(this[Ie]){let e=this[Ie];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Rt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[Ju](t){this[_c]+=t.length;let e=this[_c]/this[vi];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[Rt])return n?.(),!1;if((this[Ie]===void 0||this.brotli===void 0&&this[Ie]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<S_)return this[ge]=t,n?.(),!0;for(let d=0;this[Ie]===void 0&&d<Rc.length;d++)t[d]!==Rc[d]&&(this[Ie]=!1);let o=!1;if(this[Ie]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Dc.length;d++)if(t[d]!==Dc[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[Ie]===!1&&a)if(t.length<512)if(this[mn])this.brotli=!0;else return this[ge]=t,n?.(),!0;else try{new $n(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ie]===void 0||this[Ie]===!1&&(this.brotli||o)){let d=this[mn];this[mn]=!1,this[Ie]=this[Ie]===void 0?new Vw({}):o?new Xw({}):new Zw({}),this[Ie].on("data",h=>{this[Ju](h)&&this[Us](h)}),this[Ie].on("error",h=>{this[Rt]||this.abort(h)}),this[Ie].on("end",()=>{this[mn]=!0,this[Us]()}),this[Er]=!0,this[vi]+=t.length;let u=!!this[Ie][d?"end":"write"](t);return this[Er]=!1,n?.(),u}}this[Er]=!0,this[Ie]?(this[vi]+=t.length,this[Ie].write(t)):this[Us](t),this[Er]=!1;let i=this[Vt].length>0?!1:this[$t]?this[$t].flowing:!0;return!i&&this[Vt].length===0&&this[$t]?.once("drain",()=>this.emit("drain")),n?.(),i}[wc](t){t&&!this[Rt]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[Gs](){if(this[mn]&&!this[gc]&&!this[Rt]&&!this[Ei]){this[gc]=!0;let t=this[Un];if(t?.blockRemain){let e=this[ge]?this[ge].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ge]&&t.write(this[ge]),t.end()}this[Hn](qs)}}[Us](t){if(this[Ei]&&t)this[wc](t);else if(!t&&!this[ge])this[Gs]();else if(t){if(this[Ei]=!0,this[ge]){this[wc](t);let e=this[ge];this[ge]=void 0,this[Hs](e)}else this[Hs](t);for(;this[ge]&&this[ge]?.length>=512&&!this[Rt]&&!this[Ws];){let e=this[ge];this[ge]=void 0,this[Hs](e)}this[Ei]=!1}(!this[ge]||this[mn])&&this[Gs]()}[Hs](t){let e=0,n=t.length;for(;e+512<=n&&!this[Rt]&&!this[Ws];)switch(this[ft]){case"begin":case"header":this[$u](t,e),e+=512;break;case"ignore":case"body":e+=this[mc](t,e);break;case"meta":e+=this[Ku](t,e);break;default:throw new Error("invalid state: "+this[ft])}e<n&&(this[ge]=this[ge]?Buffer.concat([t.subarray(e),this[ge]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[Rt]||(this[Ie]?(t&&(this[vi]+=t.length,this[Ie].write(t)),this[Ie].end()):(this[mn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Gs]())),this}},Di=t=>{let e=t.length-1,n=-1;for(;e>-1&&t.charAt(e)==="/";)n=e,e--;return n===-1?t:t.slice(0,n)},A_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Rf=(t,e)=>{let n=new Map(e.map(d=>[Di(d),!0])),i=t.filter,o=100,a=(d,u="",h=0)=>{if(h>=o)return n.set(d,!1),!1;let x=u||Nw(d).root||".",g;if(d===x)g=!1;else{let m=n.get(d);g=m!==void 0?m:a(Ow(d),x,h+1)}return n.set(d,g),g};t.filter=i?(d,u)=>i(d,u)&&a(Di(d)):d=>a(Di(d))},T_=t=>{let e=new zi(t),n=t.file,i;try{i=Tr.openSync(n,"r");let o=Tr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),u=Tr.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(a);for(;d<o.size;){let h=Tr.readSync(i,u,0,a,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Tr.closeSync(i)}catch{}}},C_=(t,e)=>{let n=new zi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Tr.stat(o,(u,h)=>{if(u)d(u);else{let x=new Zc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Dr=Ui(T_,C_,t=>new zi(t),t=>new zi(t),(t,e)=>{e?.length&&Rf(t,e),t.noResume||A_(t)}),Df=(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:R_,parse:Yu}=P_,ed=t=>{let e="",n=Yu(t);for(;R_(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Yu(t)}return[e,t]},xo=["|","<",">","?",":"],td=xo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),D_=new Map(xo.map((t,e)=>[t,td[e]])),O_=new Map(td.map((t,e)=>[t,xo[e]])),Xu=t=>xo.reduce((e,n)=>e.split(n).join(D_.get(n)),t),N_=t=>td.reduce((e,n)=>e.split(n).join(O_.get(n)),t),Of=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Di(e)+"/"+t):Q(t),L_=16*1024*1024,Qu=Symbol("process"),ef=Symbol("file"),tf=Symbol("directory"),Oc=Symbol("symlink"),nf=Symbol("hardlink"),Si=Symbol("header"),Ys=Symbol("read"),Nc=Symbol("lstat"),Xs=Symbol("onlstat"),Lc=Symbol("onread"),Mc=Symbol("onreadlink"),Bc=Symbol("openfile"),Fc=Symbol("onopenfile"),En=Symbol("close"),ao=Symbol("mode"),zc=Symbol("awaitDrain"),yc=Symbol("ondrain"),Ot=Symbol("prefix"),Nf=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=Yc(e);super(),this.path=Q(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||L_,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=Q(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?Q(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[a,d]=ed(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=N_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(n.absolute||Zu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[Xs](o):this[Nc]()}warn(t,e,n={}){return ho(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Nc](){Dt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Xs](e)})}[Xs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=F_(t),this.emit("stat",t),this[Qu]()}[Qu](){switch(this.type){case"File":return this[ef]();case"Directory":return this[tf]();case"SymbolicLink":return this[Oc]();default:return this.end()}}[ao](t){return Df(t,this.type==="Directory",this.portable)}[Ot](t){return Of(t,this.prefix)}[Si](){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[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](this.linkpath):this.linkpath,mode:this[ao](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new so({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[tf](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Si](),this.end()}[Oc](){Dt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Mc](e)})}[Mc](t){this.linkpath=Q(t),this[Si](),this.end()}[nf](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Zu.relative(this.cwd,t)),this.stat.size=0,this[Si](),this.end()}[ef](){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[nf](e);this.linkCache.set(t,this.absolute)}if(this[Si](),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[Fc](e)})}[Fc](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[Ys]()}[Ys](){let{fd:t,buf:e,offset:n,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Dt.read(t,e,n,i,o,(a,d)=>{if(a)return this[En](()=>this.emit("error",a));this[Lc](d)})}[En](t=()=>{}){this.fd!==void 0&&Dt.close(this.fd,t)}[Lc](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[En](()=>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[En](()=>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[yc]():this[zc](()=>this[yc]())}[zc](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)}[yc](){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[Ys]()}},M_=class extends Nf{sync=!0;[Nc](){this[Xs](Dt.lstatSync(this.absolute))}[Oc](){this[Mc](Dt.readlinkSync(this.absolute))}[Bc](){this[Fc](Dt.openSync(this.absolute,"r"))}[Ys](){let t=!0;try{let{fd:e,buf:n,offset:i,length:o,pos:a}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let d=Dt.readSync(e,n,i,o,a);this[Lc](d),t=!1}finally{if(t)try{this[En](()=>{})}catch{}}}[zc](t){t()}[En](t=()=>{}){this.fd!==void 0&&Dt.closeSync(this.fd),t()}},B_=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 ho(this,t,e,n)}constructor(t,e={}){let n=Yc(e);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=n.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[ao](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:n.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=ed(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new $n({path:this[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new so({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let a=this.header?.block;if(!a)throw new Error("failed to encode header");super.write(a),t.pipe(this)}[Ot](t){return Of(t,this.prefix)}[ao](t){return Df(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}},F_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",z_=class Cr{tail;head;length=0;static create(e=[]){return new Cr(e)}constructor(e=[]){for(let n of e)this.push(n)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let n=e.next,i=e.prev;return n&&(n.prev=i),i&&(i.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,i=e.length;n<i;n++)H_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)G_(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,o=0;i;o++)e.call(n,i.value,o,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(n,i.value,o,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Cr;for(let o=this.head;o;)i.push(e.call(n,o.value,this)),o=o.next;return i}mapReverse(e,n){n=n||this;var i=new Cr;for(let o=this.tail;o;)i.push(e.call(n,o.value,this)),o=o.prev;return i}reduce(e,n){let i,o=this.head;if(arguments.length>1)i=n;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var a=0;o;a++)i=e(i,o.value,a),o=o.next;return i}reduceReverse(e,n){let i,o=this.tail;if(arguments.length>1)i=n;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let a=this.length-1;o;a--)i=e(i,o.value,a),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Cr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.head,a=0;for(a=0;o&&a<e;a++)o=o.next;for(;o&&a<n;a++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Cr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.length,a=this.tail;for(;a&&o>n;o--)a=a.prev;for(;a&&o>e;o--,a=a.prev)i.push(a.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let d=0;o&&d<e;d++)o=o.next;let a=[];for(let d=0;o&&d<n;d++)a.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=U_(this,o,d);return a}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=n,this.tail=e,this}};function U_(t,e,n){let i=e,o=e?e.next:t.head,a=new nd(n,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function H_(t,e){t.tail=new nd(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function G_(t,e){t.head=new nd(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var nd=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}},sf=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},of=Buffer.alloc(1024),Qs=Symbol("onStat"),Ii=Symbol("ended"),bt=Symbol("queue"),ki=Symbol("pendingLinks"),wn=Symbol("current"),qn=Symbol("process"),Ai=Symbol("processing"),Ks=Symbol("processJob"),Et=Symbol("jobs"),bc=Symbol("jobDone"),eo=Symbol("addFSEntry"),af=Symbol("addTarEntry"),Uc=Symbol("stat"),Hc=Symbol("readdir"),to=Symbol("onreaddir"),no=Symbol("pipe"),cf=Symbol("entry"),Ec=Symbol("entryOpt"),ro=Symbol("writeEntryClass"),Lf=Symbol("write"),vc=Symbol("ondrain"),po=class extends Vn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ro];onWriteEntry;[bt];[ki]=new Map;[Et]=0;[Ai]=!1;[Ii]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[ro]=Nf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new $w(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Jw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Yw(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[vc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[vc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[bt]=new z_,this[Et]=0,this.jobs=Number(t.jobs)||4,this[Ai]=!1,this[Ii]=!1}[Lf](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[Ii]=!0,this[qn](),n&&n(),this}write(t){if(this[Ii])throw new Error("write after end");return typeof t=="string"?this[eo](t):this[af](t),this.flowing}[af](t){let e=Q(rf.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new sf(t.path,e);n.entry=new B_(t,this[Ec](n)),n.entry.on("end",()=>this[bc](n)),this[Et]+=1,this[bt].push(n)}this[qn]()}[eo](t){let e=Q(rf.resolve(this.cwd,t));this[bt].push(new sf(t,e)),this[qn]()}[Uc](t){t.pending=!0,this[Et]+=1;let e=this.follow?"stat":"lstat";oo[e](t.absolute,(n,i)=>{t.pending=!1,this[Et]-=1,n?this.emit("error",n):this[Qs](t,i)})}[Qs](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[wn])this[Ks](t);else{let n=`${e.dev}:${e.ino}`,i=this[ki].get(n);i?i.push(t):this[ki].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[qn]()}[Hc](t){t.pending=!0,this[Et]+=1,oo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[Et]-=1,e)return this.emit("error",e);this[to](t,n)})}[to](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[qn]()}[qn](){if(!this[Ai]){this[Ai]=!0;for(let t=this[bt].head;t&&this[Et]<this.jobs;t=t.next)if(this[Ks](t.value),t.value.ignore){let e=t.next;this[bt].removeNode(t),t.next=e}this[Ai]=!1,this[Ii]&&this[bt].length===0&&this[Et]===0&&(this.zip?this.zip.end(of):(super.write(of),super.end()))}}get[wn](){return this[bt]&&this[bt].head&&this[bt].head.value}[bc](t){this[bt].shift(),this[Et]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[ki].get(n);if(i){this[ki].delete(n);for(let o of i)o.pending=!1,this[Ks](o)}}this[qn]()}[Ks](t){if(t.pending&&t.pendingLink&&t===this[wn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[wn]&&!t.piped&&this[no](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Qs](t,e):this[Uc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[to](t,e):this[Hc](t),!t.readdir)return}if(t.entry=this[cf](t),!t.entry){t.ignore=!0;return}t===this[wn]&&!t.piped&&this[no](t)}}}[Ec](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}}[cf](t){this[Et]+=1;try{return new this[ro](t.path,this[Ec](t)).on("end",()=>this[bc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[vc](){this[wn]&&this[wn].entry&&this[wn].entry.resume()}[no](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[eo](a+i)});let e=t.entry,n=this.zip;if(!e)throw new Error("cannot pipe without source");n?e.on("data",i=>{n.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,n={}){ho(this,t,e,n)}},rd=class extends po{sync=!0;constructor(t){super(t),this[ro]=M_}pause(){}resume(){}[Uc](t){let e=this.follow?"statSync":"lstatSync";this[Qs](t,oo[e](t.absolute))}[Hc](t){this[to](t,oo.readdirSync(t.absolute))}[no](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[eo](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Lf](i)})}},q_=(t,e)=>{let n=new rd(t),i=new Ef(t.file,{mode:t.mode||438});n.pipe(i),Mf(n,e)},j_=(t,e)=>{let n=new po(t),i=new uo(t.file,{mode:t.mode||438});n.pipe(i);let o=new Promise((a,d)=>{i.on("error",d),i.on("close",a),n.on("error",d)});return Bf(n,e).catch(a=>n.emit("error",a)),o},Mf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Dr({file:vf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Bf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Dr({file:vf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},W_=(t,e)=>{let n=new rd(t);return Mf(n,e),n},K_=(t,e)=>{let n=new po(t);return Bf(n,e).catch(i=>n.emit("error",i)),n},iA=Ui(q_,j_,W_,K_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),V_=process.env.__FAKE_PLATFORM__||process.platform,Hf=V_==="win32",{O_CREAT:Gf,O_NOFOLLOW:df,O_TRUNC:qf,O_WRONLY:jf}=Uf.constants,Wf=Number(process.env.__FAKE_FS_O_FILENAME__)||Uf.constants.UV_FS_O_FILEMAP||0,J_=Hf&&!!Wf,Z_=512*1024,Y_=Wf|qf|Gf|jf,lf=!Hf&&typeof df=="number"?df|qf|Gf|jf:null,Kf=lf!==null?()=>lf:J_?t=>t<Z_?Y_:"w":()=>"w",Gc=(t,e,n)=>{try{return go.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},co=(t,e,n,i)=>{go.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},X_=(t,e,n,i,o)=>{if(e.isDirectory())$f(Oi.resolve(t,e.name),n,i,a=>{if(a)return o(a);let d=Oi.resolve(t,e.name);co(d,n,i,o)});else{let a=Oi.resolve(t,e.name);co(a,n,i,o)}},$f=(t,e,n,i)=>{go.readdir(t,{withFileTypes:!0},(o,a)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!a.length)return co(t,e,n,i);let d=a.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return co(t,e,n,i)}};for(let x of a)X_(t,x,e,n,h)})},Q_=(t,e,n,i)=>{e.isDirectory()&&Vf(Oi.resolve(t,e.name),n,i),Gc(Oi.resolve(t,e.name),n,i)},Vf=(t,e,n)=>{let i;try{i=go.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Gc(t,e,n);throw a}for(let o of i)Q_(t,o,e,n);return Gc(t,e,n)},Jf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},mo=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},ty=(t,e)=>{ct.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new Jf(t,n?.code||"ENOTDIR")),e(n)})},ny=(t,e,n)=>{t=Q(t);let i=e.umask??18,o=e.mode|448,a=(o&i)!==0,d=e.uid,u=e.gid,h=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,g=e.unlink,m=Q(e.cwd),S=(v,I)=>{v?n(v):I&&h?$f(I,d,u,k=>S(k)):a?ct.chmod(t,o,n):n()};if(t===m)return ty(t,S);if(x)return ey.mkdir(t,{mode:o,recursive:!0}).then(v=>S(null,v??void 0),S);let _=Q(lo.relative(m,t)).split("/");qc(m,_,o,g,m,void 0,S)},qc=(t,e,n,i,o,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),h=Q(lo.resolve(t+"/"+u));ct.mkdir(h,n,Zf(h,e,n,i,o,a,d))},Zf=(t,e,n,i,o,a,d)=>u=>{u?ct.lstat(t,(h,x)=>{if(h)h.path=h.path&&Q(h.path),d(h);else if(x.isDirectory())qc(t,e,n,i,o,a,d);else if(i)ct.unlink(t,g=>{if(g)return d(g);ct.mkdir(t,n,Zf(t,e,n,i,o,a,d))});else{if(x.isSymbolicLink())return d(new mo(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,qc(t,e,n,i,o,a,d))},ry=t=>{let e=!1,n;try{e=ct.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new Jf(t,n??"ENOTDIR")}},iy=(t,e)=>{t=Q(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==0,a=e.uid,d=e.gid,u=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),h=e.preserve,x=e.unlink,g=Q(e.cwd),m=v=>{v&&u&&Vf(v,a,d),o&&ct.chmodSync(t,i)};if(t===g)return ry(g),m();if(h)return m(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(lo.relative(g,t)).split("/"),_;for(let v=S.shift(),I=g;v&&(I+="/"+v);v=S.shift()){I=Q(lo.resolve(I));try{ct.mkdirSync(I,i),_=_||I}catch{let k=ct.lstatSync(I);if(k.isDirectory())continue;if(x){ct.unlinkSync(I),ct.mkdirSync(I,i),_=_||I;continue}else if(k.isSymbolicLink())return new mo(I,I+"/"+S.join("/"))}}return m(_)},Sc=Object.create(null),uf=1e4,vr=new Set,sy=t=>{vr.has(t)?vr.delete(t):Sc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),vr.add(t);let e=Sc[t],n=vr.size-uf;if(n>uf/10){for(let i of vr)if(vr.delete(i),delete Sc[i],--n<=0)break}return e},oy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ay=oy==="win32",cy=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Yf(i,n)),e.push(n||"/"),e},[]),dy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=ay?["win32 parallelization disabled"]:t.map(i=>Di(Yf(sy(i))));let n=new Set(t.map(i=>cy(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of n){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let a=o.at(-1);a instanceof Set?a.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:i}=e,o=new Set;for(let a of n){let d=this.#e.get(a);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(a);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let h of u)o.add(h)}for(let a of i){let d=this.#e.get(a),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(a);continue}else if(u.size===1){d.shift();let h=d[0];typeof h=="function"&&o.add(h)}else u.delete(t)}return this.#r.delete(t),o.forEach(a=>this.#i(a)),!0}},ly=()=>process.umask(),ff=Symbol("onEntry"),jc=Symbol("checkFs"),hf=Symbol("checkFs2"),Wc=Symbol("isReusable"),ht=Symbol("makeFs"),Kc=Symbol("file"),$c=Symbol("directory"),io=Symbol("link"),xf=Symbol("symlink"),pf=Symbol("hardlink"),Pi=Symbol("ensureNoSymlink"),gf=Symbol("unsupported"),mf=Symbol("checkPath"),Ic=Symbol("stripAbsolutePath"),vn=Symbol("mkdir"),We=Symbol("onError"),$s=Symbol("pending"),wf=Symbol("pend"),Sr=Symbol("unpend"),kc=Symbol("ended"),Ac=Symbol("maybeClose"),Vc=Symbol("skip"),Ni=Symbol("doChown"),Li=Symbol("uid"),Mi=Symbol("gid"),Bi=Symbol("checkedCwd"),uy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Fi=uy==="win32",fy=1024,hy=(t,e)=>{if(!Fi)return oe.unlink(t,e);let n=t+".DELETE."+zf(16).toString("hex");oe.rename(t,n,i=>{if(i)return e(i);oe.unlink(n,e)})},xy=t=>{if(!Fi)return oe.unlinkSync(t);let e=t+".DELETE."+zf(16).toString("hex");oe.renameSync(t,e),oe.unlinkSync(e)},_f=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,id=class extends zi{[kc]=!1;[Bi]=!1;[$s]=0;reservations=new dy;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[kc]=!0,this[Ac]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:fy,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Fi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Fe.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:ly():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[ff](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Ac](){this[kc]&&this[$s]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Ic](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,a]=ed(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Fi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=Fe.posix.dirname(t.path),h=Fe.posix.normalize(Fe.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 o&&(t[e]=String(a),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:n})),!0}[mf](t){let e=Q(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=Q(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}n.splice(0,this.strip),t.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[Ic](t,"path")||!this[Ic](t,"linkpath"))return!1;if(t.absolute=Fe.isAbsolute(t.path)?Q(Fe.resolve(t.path)):Q(Fe.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Q(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Fe.win32.parse(String(t.absolute));t.absolute=i+Xu(String(t.absolute).slice(i.length));let{root:o}=Fe.win32.parse(t.path);t.path=o+Xu(t.path.slice(o.length))}return!0}[ff](t){if(!this[mf](t))return t.resume();switch($_.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[jc](t);default:return this[gf](t)}}[We](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Sr](),e.resume())}[vn](t,e,n){ny(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},n)}[Ni](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Li](t){return _f(this.uid,t.uid,this.processUid)}[Mi](t){return _f(this.gid,t.gid,this.processGid)}[Kc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new uo(String(t.absolute),{flags:Kf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&oe.close(i.fd,()=>{}),i.write=()=>!0,this[We](u,t),e()});let o=1,a=u=>{if(u){i.fd&&oe.close(i.fd,()=>{}),this[We](u,t),e();return}--o===0&&i.fd!==void 0&&oe.close(i.fd,h=>{h?this[We](h,t):this[Sr](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,g=t.mtime;oe.futimes(h,x,g,m=>m?oe.utimes(u,x,g,S=>a(S&&m)):a())}if(typeof h=="number"&&this[Ni](t)){o++;let x=this[Li](t),g=this[Mi](t);typeof x=="number"&&typeof g=="number"&&oe.fchown(h,x,g,m=>m?oe.chown(u,x,g,S=>a(S&&m)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[We](u,t),e()}),t.pipe(d)),d.pipe(i)}[$c](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[vn](String(t.absolute),n,i=>{if(i){this[We](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[Sr](),t.resume())};t.mtime&&!this.noMtime&&(o++,oe.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Ni](t)&&(o++,oe.chown(String(t.absolute),Number(this[Li](t)),Number(this[Mi](t)),a)),a()})}[gf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[xf](t,e){let n=Q(Fe.relative(this.cwd,Fe.resolve(Fe.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Pi](t,this.cwd,n,()=>this[io](t,String(t.linkpath),"symlink",e),i=>{this[We](i,t),e()})}[pf](t,e){let n=Q(Fe.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Pi](t,this.cwd,i,()=>this[io](t,n,"link",e),o=>{this[We](o,t),e()})}[Pi](t,e,n,i,o){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Fe.resolve(e,a);oe.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new mo(d,Fe.resolve(d,n.join("/"))));this[Pi](t,d,n,i,o)})}[wf](){this[$s]++}[Sr](){this[$s]--,this[Ac]()}[Vc](t){this[Sr](),t.resume()}[Wc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Fi}[jc](t){this[wf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[hf](t,n))}[hf](t,e){let n=d=>{e(d)},i=()=>{this[vn](this.cwd,this.dmode,d=>{if(d){this[We](d,t),n();return}this[Bi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Fe.dirname(String(t.absolute)));if(d!==this.cwd)return this[vn](d,this.dmode,u=>{if(u){this[We](u,t),n();return}a()})}a()},a=()=>{oe.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Vc](t),n();return}if(d||this[Wc](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=g=>this[ht](g??null,t,n);return h?oe.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return oe.rmdir(String(t.absolute),h=>this[ht](h??null,t,n))}if(t.absolute===this.cwd)return this[ht](null,t,n);hy(String(t.absolute),h=>this[ht](h??null,t,n))})};this[Bi]?o():i()}[ht](t,e,n){if(t){this[We](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Kc](e,n);case"Link":return this[pf](e,n);case"SymbolicLink":return this[xf](e,n);case"Directory":case"GNUDumpDir":return this[$c](e,n)}}[io](t,e,n,i){oe[n](e,String(t.absolute),o=>{o?this[We](o,t):(this[Sr](),t.resume()),i()})}},Ti=t=>{try{return[null,t()]}catch(e){return[e,null]}},Xf=class extends id{sync=!0;[ht](t,e){return super[ht](t,e,()=>{})}[jc](t){if(!this[Bi]){let o=this[vn](this.cwd,this.dmode);if(o)return this[We](o,t);this[Bi]=!0}if(t.absolute!==this.cwd){let o=Q(Fe.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[vn](o,this.dmode);if(a)return this[We](a,t)}}let[e,n]=Ti(()=>oe.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Vc](t);if(e||this[Wc](t,n))return this[ht](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Ti(()=>{oe.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ht](d,t)}let[o]=Ti(()=>oe.rmdirSync(String(t.absolute)));this[ht](o,t)}let[i]=t.absolute===this.cwd?[]:Ti(()=>xy(String(t.absolute)));this[ht](i,t)}[Kc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{oe.closeSync(o)}catch(h){u=h}(d||u)&&this[We](d||u,t),e()},o;try{o=oe.openSync(String(t.absolute),Kf(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[We](d,t)),t.pipe(a)),a.on("data",d=>{try{oe.writeSync(o,d,0,d.length)}catch(u){i(u)}}),a.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{oe.futimesSync(o,u,h)}catch(x){try{oe.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[Ni](t)){let u=this[Li](t),h=this[Mi](t);try{oe.fchownSync(o,Number(u),Number(h))}catch(x){try{oe.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[$c](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[vn](String(t.absolute),n);if(i){this[We](i,t),e();return}if(t.mtime&&!this.noMtime)try{oe.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ni](t))try{oe.chownSync(String(t.absolute),Number(this[Li](t)),Number(this[Mi](t)))}catch{}e(),t.resume()}[vn](t,e){try{return iy(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(n){return n}}[Pi](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=Fe.resolve(a,d);let[u,h]=Ti(()=>oe.lstatSync(a));if(u)return i();if(h.isSymbolicLink())return o(new mo(a,Fe.resolve(e,n.join("/"))))}i()}[io](t,e,n,i){let o=`${n}Sync`;try{oe[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[We](a,t)}}},py=t=>{let e=new Xf(t),n=t.file,i=Ff.statSync(n),o=t.maxReadSize||16*1024*1024;new Dw(n,{readSize:o,size:i.size}).pipe(e)},gy=(t,e)=>{let n=new id(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Ff.stat(o,(u,h)=>{if(u)d(u);else{let x=new Zc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Qf=Ui(py,gy,t=>new Xf(t),t=>new id(t),(t,e)=>{e?.length&&Rf(t,e)}),my=(t,e)=>{let n=new rd(t),i=!0,o,a;try{try{o=at.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=at.openSync(t.file,"w+");else throw h}let d=at.fstatSync(o),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let g=0,m=0;g<512;g+=m){if(m=at.readSync(o,u,g,u.length-g,a+g),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!m)break e}let h=new $n(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,wy(t,n,a,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},wy=(t,e,n,i,o)=>{let a=new Ef(t.file,{fd:i,start:n});e.pipe(a),yy(e,o)},_y=(t,e)=>{e=Array.from(e);let n=new po(t),i=(o,a,d)=>{let u=(S,_)=>{S?at.close(o,v=>d(S)):d(null,_)},h=0;if(a===0)return u(null,0);let x=0,g=Buffer.alloc(512),m=(S,_)=>{if(S||_===void 0)return u(S);if(x+=_,x<512&&_)return at.read(o,g,x,g.length-x,h+x,m);if(h===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let v=new $n(g);if(!v.cksumValid)return u(null,h);let I=512*Math.ceil((v.size??0)/512);if(h+I+512>a||(h+=I+512,h>=a))return u(null,h);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,at.read(o,g,0,512,h,m)};at.read(o,g,0,512,h,m)};return new Promise((o,a)=>{n.on("error",a);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 a(h);at.fstat(x,(g,m)=>{if(g)return at.close(x,()=>a(g));i(x,m.size,(S,_)=>{if(S)return a(S);let v=new uo(t.file,{fd:x,start:_});n.pipe(v),v.on("error",a),v.on("close",o),by(n,e)})})};at.open(t.file,d,u)})},yy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Dr({file:e0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},by=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Dr({file:e0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Ci=Ui(my,_y,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Uw(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")}),_A=Ui(Ci.syncFile,Ci.asyncFile,Ci.syncNoFile,Ci.asyncNoFile,(t,e=[])=>{Ci.validate?.(t,e),Ey(t)}),Ey=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))};jt();var xt={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function wo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function t0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function _o(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function n0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function r0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function i0(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}Yt();Ve();te();Ae();Ve();function Or(t,e){if(wo(t)!=="cloud")throw new A("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Hi(t){return t.startsWith("http://")||t.startsWith("https://")}function Nr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as lT}from"node:fs";import{dirname as fT,join as hT}from"node:path";import{fileURLToPath as pT}from"node:url";var Lt="0.3.1-beta.1";import{mkdir as zy,rm as E0}from"node:fs/promises";import{join as Wi}from"node:path";qt();import{readFileSync as Py}from"node:fs";var Ry=384;async function sd(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await hn(t.agentEnvFile,n,{mode:Ry})}function Zn(t){try{let e=JSON.parse(Py(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function yo(t,e,n={},i=o=>o){return{...i({...t,...Zn(e)}),...n}}qt();function Gi(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(Dy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
|
|
89
|
+
`},configPath(t){return gA(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 ng("schtasks",["/Create","/SC","ONLOGON","/TN",Ca,"/TR",n,"/RU",t.userName,"/F"]),bl.info("task scheduler entry created",{task:Ca,logFile:t.logFile})},async uninstall(t){await ng("schtasks",["/Delete","/TN",Ca,"/F"]).catch(e=>bl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),bl.info("task scheduler entry removed",{task:Ca})}}});var ig={};qa(ig,{buildContext:()=>EA,getSupervisor:()=>_A,launchdSupervisor:()=>_l,systemdSupervisor:()=>yl,taskSchedulerSupervisor:()=>El});import{homedir as mA,userInfo as wA}from"node:os";function _A(t=process.platform){switch(t){case"darwin":return _l;case"linux":return yl;case"win32":return El;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function bA(){let t={};for(let e of yA){let n=process.env[e];n&&(t[e]=n)}return t}function EA(){let t=Z();return{nodeBin:process.execPath,entry:ll(t),logFile:t.logFile,homeDir:mA(),userName:wA().username,isRoot:process.getuid?.()===0,env:bA()}}var yA,sg=it(()=>{"use strict";Pe();_a();Qp();tg();rg();yA=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();fn();var Xl=G("acp-installer-warmup"),Om=["claude-code","codex"];async function Ql(t={}){let e=t.ensure??gr,i=(await Promise.allSettled(Om.map(async o=>{let a=await e(o);Xl.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&Xl.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))})}$t();te();import{readdir as Zm}from"node:fs/promises";import{mkdir as ru,readFile as $m,writeFile as iu}from"node:fs/promises";import{join as Ja}from"node:path";var Vm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function mr(t,e,n){await ru(t,{recursive:!0});let i=Vm[e],o=Ja(t,i);return await iu(o,n??"","utf8"),o}async function Ya(t,e,n){let i=Ja(t,".claude");await ru(i,{recursive:!0});let o=Ja(i,"settings.local.json"),a={};try{let u=await $m(o,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(a=f)}catch{}let d=typeof a.permissions=="object"&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",a.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return a.permissions=d,await iu(o,JSON.stringify(a,null,2),"utf8"),o}var et=G("agent-detail-sync"),Jm=6e4,Ym=5*6e4,Rs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await Zm(n)}catch(o){et.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}et.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let a=await Ie(o,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){et.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,a)}catch(d){et.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),et.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&n.push(i);if(n.length!==0){et.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){et.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await Ie(e,this.opts.paths);if(!i){et.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){et.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,Ym):Jm;this.retryQueue.set(e,{dueAt:Date.now()+p,currentDelay:p});return}if(o.agentId&&o.agentId!==e){et.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let a=!1,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,a=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,a=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,a=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(et.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):o.deployType&&et.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){et.debug("detail sync: no diff",{agentId:e});return}await qe(i,this.opts.paths),et.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}),et.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await mr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Sd=Wt(Bu(),1);import{createHash as Hy}from"node:crypto";import{lstat as gd,mkdir as md,readFile as Ao,readdir as R0,rm as wd,stat as Ed,writeFile as _d}from"node:fs/promises";import{homedir as Gy}from"node:os";import{basename as k0,dirname as qy,join as fe,normalize as jy,relative as vd,resolve as yd,sep as P0}from"node:path";import{Readable as D0}from"node:stream";import{pipeline as O0}from"node:stream/promises";import _w from"events";import ot from"fs";import{EventEmitter as Yc}from"node:events";import yf from"node:stream";import{StringDecoder as yw}from"node:string_decoder";import vf from"node:path";import Cr from"node:fs";import{dirname as Ow,parse as Lw}from"path";import{EventEmitter as Gw}from"events";import Dc from"assert";import{Buffer as Kn}from"buffer";import*as Gu from"zlib";import qw from"zlib";import{posix as Er}from"node:path";import{basename as m_}from"node:path";import co from"fs";import Lt from"fs";import Ju from"path";import{win32 as R_}from"node:path";import rf from"path";import Ff from"node:fs";import $_ from"node:assert";import{randomBytes as zf}from"node:crypto";import oe from"node:fs";import Ue from"node:path";import Uf from"fs";import wo from"node:fs";import Li from"node:path";import ut from"node:fs";import ey from"node:fs/promises";import fo from"node:path";import{join as Yf}from"node:path";import lt from"node:fs";import e0 from"node:path";var mw=Object.defineProperty,ww=(t,e)=>{for(var n in e)mw(t,n,{get:e[n],enumerable:!0})},Fu=typeof process=="object"&&process?process:{stdout:null,stderr:null},bw=t=>!!t&&typeof t=="object"&&(t instanceof Zn||t instanceof yf||Ew(t)||vw(t)),Ew=t=>!!t&&typeof t=="object"&&t instanceof Yc&&typeof t.pipe=="function"&&t.pipe!==yf.Writable.prototype.pipe,vw=t=>!!t&&typeof t=="object"&&t instanceof Yc&&typeof t.write=="function"&&typeof t.end=="function",Vt=Symbol("EOF"),Zt=Symbol("maybeEmitEnd"),gn=Symbol("emittedEnd"),Ns=Symbol("emittingEnd"),gi=Symbol("emittedError"),Ms=Symbol("closed"),zu=Symbol("read"),Bs=Symbol("flush"),Uu=Symbol("flushChunk"),Et=Symbol("encoding"),br=Symbol("decoder"),je=Symbol("flowing"),mi=Symbol("paused"),Ar=Symbol("resume"),We=Symbol("buffer"),nt=Symbol("pipes"),Ke=Symbol("bufferLength"),rc=Symbol("bufferPush"),Fs=Symbol("bufferShift"),Qe=Symbol("objectMode"),De=Symbol("destroyed"),ic=Symbol("error"),sc=Symbol("emitData"),Hu=Symbol("emitEnd"),oc=Symbol("emitEnd2"),Rt=Symbol("async"),ac=Symbol("abort"),zs=Symbol("aborted"),wi=Symbol("signal"),Bn=Symbol("dataListeners"),dt=Symbol("discarded"),_i=t=>Promise.resolve().then(t),Sw=t=>t(),Iw=t=>t==="end"||t==="finish"||t==="prefinish",Aw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,kw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),bf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Ar](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Tw=class extends bf{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)}},Cw=t=>!!t.objectMode,Rw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Zn=class extends Yc{[je]=!1;[mi]=!1;[nt]=[];[We]=[];[Qe];[Et];[Rt];[br];[Vt]=!1;[gn]=!1;[Ns]=!1;[Ms]=!1;[gi]=null;[Ke]=0;[De]=!1;[wi];[zs]=!1;[Bn]=0;[dt]=!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");Cw(e)?(this[Qe]=!0,this[Et]=null):Rw(e)?(this[Et]=e.encoding,this[Qe]=!1):(this[Qe]=!1,this[Et]=null),this[Rt]=!!e.async,this[br]=this[Et]?new yw(this[Et]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[We]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[nt]});let{signal:n}=e;n&&(this[wi]=n,n.aborted?this[ac]():n.addEventListener("abort",()=>this[ac]()))}get bufferLength(){return this[Ke]}get encoding(){return this[Et]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Qe]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Rt]}set async(t){this[Rt]=this[Rt]||!!t}[ac](){this[zs]=!0,this.emit("abort",this[wi]?.reason),this.destroy(this[wi]?.reason)}get aborted(){return this[zs]}set aborted(t){}write(t,e,n){if(this[zs])return!1;if(this[Vt])throw new Error("write after end");if(this[De])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[Rt]?_i:Sw;if(!this[Qe]&&!Buffer.isBuffer(t)){if(kw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Aw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Qe]?(this[je]&&this[Ke]!==0&&this[Bs](!0),this[je]?this.emit("data",t):this[rc](t),this[Ke]!==0&&this.emit("readable"),n&&i(n),this[je]):t.length?(typeof t=="string"&&!(e===this[Et]&&!this[br]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Et]&&(t=this[br].write(t)),this[je]&&this[Ke]!==0&&this[Bs](!0),this[je]?this.emit("data",t):this[rc](t),this[Ke]!==0&&this.emit("readable"),n&&i(n),this[je]):(this[Ke]!==0&&this.emit("readable"),n&&i(n),this[je])}read(t){if(this[De])return null;if(this[dt]=!1,this[Ke]===0||t===0||t&&t>this[Ke])return this[Zt](),null;this[Qe]&&(t=null),this[We].length>1&&!this[Qe]&&(this[We]=[this[Et]?this[We].join(""):Buffer.concat(this[We],this[Ke])]);let e=this[zu](t||null,this[We][0]);return this[Zt](),e}[zu](t,e){if(this[Qe])this[Fs]();else{let n=e;t===n.length||t===null?this[Fs]():typeof n=="string"?(this[We][0]=n.slice(t),e=n.slice(0,t),this[Ke]-=t):(this[We][0]=n.subarray(t),e=n.subarray(0,t),this[Ke]-=t)}return this.emit("data",e),!this[We].length&&!this[Vt]&&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[Vt]=!0,this.writable=!1,(this[je]||!this[mi])&&this[Zt](),this}[Ar](){this[De]||(!this[Bn]&&!this[nt].length&&(this[dt]=!0),this[mi]=!1,this[je]=!0,this.emit("resume"),this[We].length?this[Bs]():this[Vt]?this[Zt]():this.emit("drain"))}resume(){return this[Ar]()}pause(){this[je]=!1,this[mi]=!0,this[dt]=!1}get destroyed(){return this[De]}get flowing(){return this[je]}get paused(){return this[mi]}[rc](t){this[Qe]?this[Ke]+=1:this[Ke]+=t.length,this[We].push(t)}[Fs](){return this[Qe]?this[Ke]-=1:this[Ke]-=this[We][0].length,this[We].shift()}[Bs](t=!1){do;while(this[Uu](this[Fs]())&&this[We].length);!t&&!this[We].length&&!this[Vt]&&this.emit("drain")}[Uu](t){return this.emit("data",t),this[je]}pipe(t,e){if(this[De])return t;this[dt]=!1;let n=this[gn];return e=e||{},t===Fu.stdout||t===Fu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[nt].push(e.proxyErrors?new Tw(this,t,e):new bf(this,t,e)),this[Rt]?_i(()=>this[Ar]()):this[Ar]()),t}unpipe(t){let e=this[nt].find(n=>n.dest===t);e&&(this[nt].length===1?(this[je]&&this[Bn]===0&&(this[je]=!1),this[nt]=[]):this[nt].splice(this[nt].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[dt]=!1,this[Bn]++,!this[nt].length&&!this[je]&&this[Ar]();else if(t==="readable"&&this[Ke]!==0)super.emit("readable");else if(Iw(t)&&this[gn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[gi]){let i=e;this[Rt]?_i(()=>i.call(this,this[gi])):i.call(this,this[gi])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Bn]=this.listeners("data").length,this[Bn]===0&&!this[dt]&&!this[nt].length&&(this[je]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Bn]=0,!this[dt]&&!this[nt].length&&(this[je]=!1)),e}get emittedEnd(){return this[gn]}[Zt](){!this[Ns]&&!this[gn]&&!this[De]&&this[We].length===0&&this[Vt]&&(this[Ns]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ms]&&this.emit("close"),this[Ns]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==De&&this[De])return!1;if(t==="data")return!this[Qe]&&!n?!1:this[Rt]?(_i(()=>this[sc](n)),!0):this[sc](n);if(t==="end")return this[Hu]();if(t==="close"){if(this[Ms]=!0,!this[gn]&&!this[De])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[gi]=n,super.emit(ic,n);let o=!this[wi]||this.listeners("error").length?super.emit("error",n):!1;return this[Zt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Zt](),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[Zt](),i}[sc](t){for(let n of this[nt])n.dest.write(t)===!1&&this.pause();let e=this[dt]?!1:super.emit("data",t);return this[Zt](),e}[Hu](){return this[gn]?!1:(this[gn]=!0,this.readable=!1,this[Rt]?(_i(()=>this[oc]()),!0):this[oc]())}[oc](){if(this[br]){let e=this[br].end();if(e){for(let n of this[nt])n.dest.write(e);this[dt]||super.emit("data",e)}}for(let e of this[nt])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Qe]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Qe]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Qe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Et]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(De,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[dt]=!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[Vt])return e();let i,o,a=x=>{this.off("data",d),this.off("end",u),this.off(De,f),e(),o(x)},d=x=>{this.off("error",a),this.off("end",u),this.off(De,f),this.pause(),i({value:x,done:!!this[Vt]})},u=()=>{this.off("error",a),this.off("data",d),this.off(De,f),e(),i({done:!0,value:void 0})},f=()=>a(new Error("stream destroyed"));return new Promise((x,p)=>{o=p,i=x,this.once(De,f),this.once("error",a),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[dt]=!1;let t=!1,e=()=>(this.pause(),this.off(ic,e),this.off(De,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(ic,e),this.once(De,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[De])return t?this.emit("error",t):this.emit(De),this;this[De]=!0,this[dt]=!0,this[We].length=0,this[Ke]=0;let e=this;return typeof e.close=="function"&&!this[Ms]&&e.close(),t?this.emit("error",t):this.emit(De),this}static get isStream(){return bw}},Pw=ot.writev,In=Symbol("_autoClose"),At=Symbol("_close"),yi=Symbol("_ended"),ue=Symbol("_fd"),cc=Symbol("_finished"),Qt=Symbol("_flags"),dc=Symbol("_flush"),Rc=Symbol("_handleChunk"),Pc=Symbol("_makeBuf"),Di=Symbol("_mode"),Us=Symbol("_needDrain"),Pr=Symbol("_onerror"),Dr=Symbol("_onopen"),lc=Symbol("_onread"),kr=Symbol("_onwrite"),An=Symbol("_open"),It=Symbol("_path"),yn=Symbol("_pos"),Pt=Symbol("_queue"),Tr=Symbol("_read"),uc=Symbol("_readSize"),Xt=Symbol("_reading"),bi=Symbol("_remain"),fc=Symbol("_size"),Js=Symbol("_write"),Fn=Symbol("_writing"),Ys=Symbol("_defaultFlag"),Wn=Symbol("_errored"),Xc=class extends Zn{[Wn]=!1;[ue];[It];[uc];[Xt]=!1;[fc];[bi];[In];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[Wn]=!1,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[It]=t,this[uc]=e.readSize||16*1024*1024,this[Xt]=!1,this[fc]=typeof e.size=="number"?e.size:1/0,this[bi]=this[fc],this[In]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[ue]=="number"?this[Tr]():this[An]()}get fd(){return this[ue]}get path(){return this[It]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[An](){ot.open(this[It],"r",(t,e)=>this[Dr](t,e))}[Dr](t,e){t?this[Pr](t):(this[ue]=e,this.emit("open",e),this[Tr]())}[Pc](){return Buffer.allocUnsafe(Math.min(this[uc],this[bi]))}[Tr](){if(!this[Xt]){this[Xt]=!0;let t=this[Pc]();if(t.length===0)return process.nextTick(()=>this[lc](null,0,t));ot.read(this[ue],t,0,t.length,null,(e,n,i)=>this[lc](e,n,i))}}[lc](t,e,n){this[Xt]=!1,t?this[Pr](t):this[Rc](e,n)&&this[Tr]()}[At](){if(this[In]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Pr](t){this[Xt]=!0,this[At](),this.emit("error",t)}[Rc](t,e){let n=!1;return this[bi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[bi]<=0)&&(n=!1,this[At](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[ue]=="number"&&this[Tr](),!1;case"error":return this[Wn]?!1:(this[Wn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Dw=class extends Xc{[An](){let t=!0;try{this[Dr](null,ot.openSync(this[It],"r")),t=!1}finally{t&&this[At]()}}[Tr](){let t=!0;try{if(!this[Xt]){this[Xt]=!0;do{let e=this[Pc](),n=e.length===0?0:ot.readSync(this[ue],e,0,e.length,null);if(!this[Rc](n,e))break}while(!0);this[Xt]=!1}t=!1}finally{t&&this[At]()}}[At](){if(this[In]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,ot.closeSync(t),this.emit("close")}}},ho=class extends _w{readable=!1;writable=!0;[Wn]=!1;[Fn]=!1;[yi]=!1;[Pt]=[];[Us]=!1;[It];[Di];[In];[ue];[Ys];[Qt];[cc]=!1;[yn];constructor(t,e){e=e||{},super(e),this[It]=t,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[Di]=e.mode===void 0?438:e.mode,this[yn]=typeof e.start=="number"?e.start:void 0,this[In]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[yn]!==void 0?"r+":"w";this[Ys]=e.flags===void 0,this[Qt]=e.flags===void 0?n:e.flags,this[ue]===void 0&&this[An]()}emit(t,...e){if(t==="error"){if(this[Wn])return!1;this[Wn]=!0}return super.emit(t,...e)}get fd(){return this[ue]}get path(){return this[It]}[Pr](t){this[At](),this[Fn]=!0,this.emit("error",t)}[An](){ot.open(this[It],this[Qt],this[Di],(t,e)=>this[Dr](t,e))}[Dr](t,e){this[Ys]&&this[Qt]==="r+"&&t&&t.code==="ENOENT"?(this[Qt]="w",this[An]()):t?this[Pr](t):(this[ue]=e,this.emit("open",e),this[Fn]||this[dc]())}end(t,e){return t&&this.write(t,e),this[yi]=!0,!this[Fn]&&!this[Pt].length&&typeof this[ue]=="number"&&this[kr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[yi]?(this.emit("error",new Error("write() after end()")),!1):this[ue]===void 0||this[Fn]||this[Pt].length?(this[Pt].push(t),this[Us]=!0,!1):(this[Fn]=!0,this[Js](t),!0)}[Js](t){ot.write(this[ue],t,0,t.length,this[yn],(e,n)=>this[kr](e,n))}[kr](t,e){t?this[Pr](t):(this[yn]!==void 0&&typeof e=="number"&&(this[yn]+=e),this[Pt].length?this[dc]():(this[Fn]=!1,this[yi]&&!this[cc]?(this[cc]=!0,this[At](),this.emit("finish")):this[Us]&&(this[Us]=!1,this.emit("drain"))))}[dc](){if(this[Pt].length===0)this[yi]&&this[kr](null,0);else if(this[Pt].length===1)this[Js](this[Pt].pop());else{let t=this[Pt];this[Pt]=[],Pw(this[ue],t,this[yn],(e,n)=>this[kr](e,n))}}[At](){if(this[In]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Ef=class extends ho{[An](){let t;if(this[Ys]&&this[Qt]==="r+")try{t=ot.openSync(this[It],this[Qt],this[Di])}catch(e){if(e?.code==="ENOENT")return this[Qt]="w",this[An]();throw e}else t=ot.openSync(this[It],this[Qt],this[Di]);this[Dr](null,t)}[At](){if(this[In]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,ot.closeSync(t),this.emit("close")}}[Js](t){let e=!0;try{this[kr](null,ot.writeSync(this[ue],t,0,t.length,this[yn])),e=!1}finally{if(e)try{this[At]()}catch{}}}},Nw=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"]]),Mw=t=>!!t.sync&&!!t.file,Bw=t=>!t.sync&&!!t.file,Fw=t=>!!t.sync&&!t.file,zw=t=>!t.sync&&!t.file,Uw=t=>!!t.file,Hw=t=>Nw.get(t)||t,Qc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=Hw(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Hi=(t,e,n,i,o)=>Object.assign((a=[],d,u)=>{Array.isArray(a)&&(d=a,a={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let f=Qc(a);if(o?.(f,d),Mw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(Bw(f)){let x=e(f,d);return u?x.then(()=>u(),u):x}else if(Fw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(f,d)}else if(zw(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:o}),jw=qw.constants||{ZLIB_VERNUM:4736},Mt=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},jw)),Ww=Kn.concat,qu=Object.getOwnPropertyDescriptor(Kn,"concat"),Kw=t=>t,hc=qu?.writable===!0||qu?.set!==void 0?t=>{Kn.concat=t?Kw:Ww}:t=>{},$n=Symbol("_superWrite"),Hs=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"}},xc=Symbol("flushFlag"),ed=class extends Zn{#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 Gu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Gu[e](t)}catch(n){throw new Hs(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 Hs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Dc(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),{[xc]: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}[$n](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Kn.from(t,e)),this.#e)return;Dc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},hc(!0);let d;try{let f=typeof t[xc]=="number"?t[xc]:this.#r;d=this.#t._processChunk(t,f),hc(!1)}catch(f){hc(!1),this.#o(new Hs(f,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=a,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",f=>this.#o(new Hs(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[$n](Kn.from(f));for(let x=1;x<d.length;x++)u=this[$n](d[x])}else u=this[$n](Kn.from(d));return n&&n(),u}},Sf=class extends ed{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Mt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Mt.Z_FINISH,t.fullFlushFlag=Mt.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(Mt.Z_SYNC_FLUSH),Dc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},$w=class extends Sf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[$n](t){return this.#e?(this.#e=!1,t[9]=255,super[$n](t)):super[$n](t)}},Vw=class extends Sf{constructor(t){super(t,"Unzip")}},If=class extends ed{constructor(t,e){t=t||{},t.flush=t.flush||Mt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Mt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Mt.BROTLI_OPERATION_FLUSH,super(t,e)}},Zw=class extends If{constructor(t){super(t,"BrotliCompress")}},Jw=class extends If{constructor(t){super(t,"BrotliDecompress")}},Af=class extends ed{constructor(t,e){t=t||{},t.flush=t.flush||Mt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Mt.ZSTD_e_end,t.fullFlushFlag=Mt.ZSTD_e_flush,super(t,e)}},Yw=class extends Af{constructor(t){super(t,"ZstdCompress")}},Xw=class extends Af{constructor(t){super(t,"ZstdDecompress")}},Qw=(t,e)=>{if(Number.isSafeInteger(t))t<0?t_(t,e):e_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},e_=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},t_=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),n?e[i-1]=kf(o):o===0?e[i-1]=0:(n=!0,e[i-1]=Tf(o))}},n_=t=>{let e=t[0],n=e===128?i_(t.subarray(1,t.length)):e===255?r_(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},r_=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var a=Number(t[o]),d;i?d=kf(a):a===0?d=a:(i=!0,d=Tf(a)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},i_=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(n+=o*Math.pow(256,e-i-1))}return n},kf=t=>(255^t)&255,Tf=t=>(255^t)+1&255,s_={};ww(s_,{code:()=>td,isCode:()=>Xs,isName:()=>o_,name:()=>xo,normalFsTypes:()=>Cf});var Xs=t=>xo.has(t),o_=t=>td.has(t),Cf=new Set(["0","","1","2","3","4","5","6","7","D"]),xo=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"]]),td=new Map(Array.from(xo).map(t=>[t[1],t[0]])),a_=t=>t===void 0||t<0?void 0:t,Vn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=zn(t,e+156,1),a=Cf.has(o),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??zn(t,e,100),this.mode=d?.mode??u?.mode??bn(t,e+100,8),this.uid=d?.uid??u?.uid??bn(t,e+108,8),this.gid=d?.gid??u?.gid??bn(t,e+116,8),this.size=a_(d?.size??u?.size??bn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??pc(t,e+136,12),this.cksum=bn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Xs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=zn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??zn(t,e+265,32),this.gname=d?.gname??u?.gname??zn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??bn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??bn(t,e+337,8)??0,t[e+475]!==0){let x=zn(t,e+345,155);this.path=x+"/"+this.path}else{let x=zn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??pc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??pc(t,e+488,12)}let f=256;for(let x=e;x<e+148;x++)f+=t[x];for(let x=e+156;x<e+512;x++)f+=t[x];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="size"&&Number(i)<0||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,i=c_(this.path||"",n),o=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Un(t,e,100,o)||this.needPax,this.needPax=En(t,e+100,8,this.mode)||this.needPax,this.needPax=En(t,e+108,8,this.uid)||this.needPax,this.needPax=En(t,e+116,8,this.gid)||this.needPax,this.needPax=En(t,e+124,12,this.size)||this.needPax,this.needPax=gc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Un(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Un(t,e+265,32,this.uname)||this.needPax,this.needPax=Un(t,e+297,32,this.gname)||this.needPax,this.needPax=En(t,e+329,8,this.devmaj)||this.needPax,this.needPax=En(t,e+337,8,this.devmin)||this.needPax,this.needPax=Un(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=Un(t,e+345,155,a)||this.needPax:(this.needPax=Un(t,e+345,130,a)||this.needPax,this.needPax=gc(t,e+476,12,this.atime)||this.needPax,this.needPax=gc(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,En(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:xo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(td.get(t));if(Xs(e)||e==="Unsupported")this.#e=e;else if(Xs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},c_=(t,e)=>{let n=t,i="",o,a=Er.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=Er.dirname(n),n=Er.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?o=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?o=[n.slice(0,99),i,!0]:(n=Er.join(Er.basename(i),n),i=Er.dirname(i));while(i!==a&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},zn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),pc=(t,e,n)=>d_(bn(t,e,n)),d_=t=>t===void 0?void 0:new Date(t*1e3),bn=(t,e,n)=>Number(t[e])&128?n_(t.subarray(e,e+n)):u_(t,e,n),l_=t=>isNaN(t)?void 0:t,u_=(t,e,n)=>l_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),f_={12:8589934591,8:2097151},En=(t,e,n,i)=>i===void 0?!1:i>f_[n]||i<0?(Qw(i,t.subarray(e,e+n)),!0):(h_(t,e,n,i),!1),h_=(t,e,n,i)=>t.write(x_(i,n),e,n,"ascii"),x_=(t,e)=>p_(Math.floor(t).toString(8),e),p_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",gc=(t,e,n,i)=>i===void 0?!1:En(t,e,n,i.getTime()/1e3),g_=new Array(156).join("\0"),Un=(t,e,n,i)=>i===void 0?!1:(t.write(i+g_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),ao=class Rf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),o=Buffer.allocUnsafe(i);for(let a=0;a<512;a++)o[a]=0;new Vn({path:("PaxHeader/"+m_(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,n,"utf8");for(let a=n+512;a<o.length;a++)o[a]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let n=this[e],i=n instanceof Date?n.getTime()/1e3:n,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
|
|
90
|
+
`,a=Buffer.byteLength(o),d=Math.floor(Math.log(a)/Math.log(10))+1;return a+d>=Math.pow(10,d)&&(d+=1),d+a+o}static parse(e,n,i=!1){return new Rf(w_(__(e),n),i)}},w_=(t,e)=>e?Object.assign({},e,t):t,__=t=>t.replace(/\n$/,"").split(`
|
|
91
|
+
`).reduce(y_,Object.create(null)),y_=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let a=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(a){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[a]=d;break;case"ctime":case"atime":case"mtime":t[a]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[a]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[a]=+d;break}return t},b_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=b_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),E_=class extends Zn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,n){switch(super({}),this.pause(),this.extended=e,this.globalExtended=n,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),n&&this.#e(n,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let n=this.remain,i=this.blockRemain;return this.remain=Math.max(0,n-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:n>=e?super.write(t):super.write(t.subarray(0,n))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},po=(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))},v_=1024*1024,Oc=Buffer.from([31,139]),Lc=Buffer.from([40,181,47,253]),S_=Math.max(Oc.length,Lc.length),xt=Symbol("state"),Hn=Symbol("writeEntry"),Jt=Symbol("readEntry"),mc=Symbol("nextEntry"),ju=Symbol("processEntry"),Dt=Symbol("extendedHeader"),Ei=Symbol("globalExtendedHeader"),mn=Symbol("meta"),Wu=Symbol("emitMeta"),we=Symbol("buffer"),Yt=Symbol("queue"),wn=Symbol("ended"),wc=Symbol("emittedEnd"),Gn=Symbol("emit"),Te=Symbol("unzip"),Gs=Symbol("consumeChunk"),qs=Symbol("consumeChunkSub"),_c=Symbol("consumeBody"),Ku=Symbol("consumeMeta"),$u=Symbol("consumeHeader"),vi=Symbol("consuming"),yc=Symbol("bufferConcat"),js=Symbol("maybeEnd"),vr=Symbol("writing"),Ot=Symbol("aborted"),Ws=Symbol("onDone"),qn=Symbol("sawValidEntry"),Ks=Symbol("sawNullBlock"),$s=Symbol("sawEOF"),Vu=Symbol("closeStream"),I_=1e3,Si=Symbol("compressedBytesRead"),bc=Symbol("decompressedBytesRead"),Zu=Symbol("checkDecompressionRatio"),A_=()=>!0,Ui=class extends Gw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[Yt]=[];[we];[Jt];[Hn];[xt]="begin";[mn]="";[Dt];[Ei];[wn]=!1;[Te];[Ot]=!1;[qn];[Ks]=!1;[$s]=!1;[vr]=!1;[vi]=!1;[wc]=!1;[Si]=0;[bc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Ws,()=>{(this[xt]==="begin"||this[qn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ws,t.ondone):this.on(Ws,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:I_,this.maxMetaEntrySize=t.maxMetaEntrySize||v_,this.filter=typeof t.filter=="function"?t.filter:A_;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let n=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:n?!0:void 0,this.on("end",()=>this[Vu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){po(this,t,e,n)}[$u](t,e){this[qn]===void 0&&(this[qn]=!1);let n;try{n=new Vn(t,e,this[Dt],this[Ei])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Ks]?(this[$s]=!0,this[xt]==="begin"&&(this[xt]="header"),this[Gn]("eof")):(this[Ks]=!0,this[Gn]("nullBlock"));else if(this[Ks]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let o=this[Hn]=new E_(n,this[Dt],this[Ei]);if(!this[qn])if(o.remain){let a=()=>{o.invalid||(this[qn]=!0)};o.on("end",a)}else this[qn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Gn]("ignoredEntry",o),this[xt]="ignore",o.resume()):o.size>0&&(this[mn]="",o.on("data",a=>this[mn]+=a),this[xt]="meta"):(this[Dt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Gn]("ignoredEntry",o),this[xt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[xt]="body":(this[xt]="header",o.end()),this[Jt]?this[Yt].push(o):(this[Yt].push(o),this[mc]())))}}}[Vu](){queueMicrotask(()=>this.emit("close"))}[ju](t){let e=!0;if(!t)this[Jt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Jt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[mc]()),e=!1);return e}[mc](){do;while(this[ju](this[Yt].shift()));if(this[Yt].length===0){let t=this[Jt];!t||t.flowing||t.size===t.remain?this[vr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[_c](t,e){let n=this[Hn];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(o),n.blockRemain||(this[xt]="header",this[Hn]=void 0,n.end()),o.length}[Ku](t,e){let n=this[Hn],i=this[_c](t,e);return!this[Hn]&&n&&this[Wu](n),i}[Gn](t,e,n){this[Yt].length===0&&!this[Jt]?this.emit(t,e,n):this[Yt].push([t,e,n])}[Wu](t){switch(this[Gn]("meta",this[mn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Dt]=ao.parse(this[mn],this[Dt],!1);break;case"GlobalExtendedHeader":this[Ei]=ao.parse(this[mn],this[Ei],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Dt]??Object.create(null);this[Dt]=e,e.path=this[mn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Dt]||Object.create(null);this[Dt]=e,e.linkpath=this[mn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Ot]){if(this[Te]){let e=this[Te];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Ot]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[Zu](t){this[bc]+=t.length;let e=this[bc]/this[Si];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[Ot])return n?.(),!1;if((this[Te]===void 0||this.brotli===void 0&&this[Te]===!1)&&t){if(this[we]&&(t=Buffer.concat([this[we],t]),this[we]=void 0),t.length<S_)return this[we]=t,n?.(),!0;for(let d=0;this[Te]===void 0&&d<Oc.length;d++)t[d]!==Oc[d]&&(this[Te]=!1);let o=!1;if(this[Te]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Lc.length;d++)if(t[d]!==Lc[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[Te]===!1&&a)if(t.length<512)if(this[wn])this.brotli=!0;else return this[we]=t,n?.(),!0;else try{new Vn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Te]===void 0||this[Te]===!1&&(this.brotli||o)){let d=this[wn];this[wn]=!1,this[Te]=this[Te]===void 0?new Vw({}):o?new Xw({}):new Jw({}),this[Te].on("data",f=>{this[Zu](f)&&this[Gs](f)}),this[Te].on("error",f=>{this[Ot]||this.abort(f)}),this[Te].on("end",()=>{this[wn]=!0,this[Gs]()}),this[vr]=!0,this[Si]+=t.length;let u=!!this[Te][d?"end":"write"](t);return this[vr]=!1,n?.(),u}}this[vr]=!0,this[Te]?(this[Si]+=t.length,this[Te].write(t)):this[Gs](t),this[vr]=!1;let i=this[Yt].length>0?!1:this[Jt]?this[Jt].flowing:!0;return!i&&this[Yt].length===0&&this[Jt]?.once("drain",()=>this.emit("drain")),n?.(),i}[yc](t){t&&!this[Ot]&&(this[we]=this[we]?Buffer.concat([this[we],t]):t)}[js](){if(this[wn]&&!this[wc]&&!this[Ot]&&!this[vi]){this[wc]=!0;let t=this[Hn];if(t?.blockRemain){let e=this[we]?this[we].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[we]&&t.write(this[we]),t.end()}this[Gn](Ws)}}[Gs](t){if(this[vi]&&t)this[yc](t);else if(!t&&!this[we])this[js]();else if(t){if(this[vi]=!0,this[we]){this[yc](t);let e=this[we];this[we]=void 0,this[qs](e)}else this[qs](t);for(;this[we]&&this[we]?.length>=512&&!this[Ot]&&!this[$s];){let e=this[we];this[we]=void 0,this[qs](e)}this[vi]=!1}(!this[we]||this[wn])&&this[js]()}[qs](t){let e=0,n=t.length;for(;e+512<=n&&!this[Ot]&&!this[$s];)switch(this[xt]){case"begin":case"header":this[$u](t,e),e+=512;break;case"ignore":case"body":e+=this[_c](t,e);break;case"meta":e+=this[Ku](t,e);break;default:throw new Error("invalid state: "+this[xt])}e<n&&(this[we]=this[we]?Buffer.concat([t.subarray(e),this[we]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[Ot]||(this[Te]?(t&&(this[Si]+=t.length,this[Te].write(t)),this[Te].end()):(this[wn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[js]())),this}},Oi=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)},k_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Pf=(t,e)=>{let n=new Map(e.map(a=>[Oi(a),!0])),i=t.filter,o=(a,d="")=>{let u=d||Lw(a).root||".",f;if(a===u)f=!1;else{let x=n.get(a);f=x!==void 0?x:o(Ow(a),u)}return n.set(a,f),f};t.filter=i?(a,d)=>i(a,d)&&o(Oi(a)):a=>o(Oi(a))},T_=t=>{let e=new Ui(t),n=t.file,i;try{i=Cr.openSync(n,"r");let o=Cr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),u=Cr.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(a);for(;d<o.size;){let f=Cr.readSync(i,u,0,a,d);if(f===0)break;d+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Cr.closeSync(i)}catch{}}},C_=(t,e)=>{let n=new Ui(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Cr.stat(o,(u,f)=>{if(u)d(u);else{let x=new Xc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},Or=Hi(T_,C_,t=>new Ui(t),t=>new Ui(t),(t,e)=>{e?.length&&Pf(t,e),t.noResume||k_(t)}),Df=(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:P_,parse:Yu}=R_,nd=t=>{let e="",n=Yu(t);for(;P_(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Yu(t)}return[e,t]},go=["|","<",">","?",":"],rd=go.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),D_=new Map(go.map((t,e)=>[t,rd[e]])),O_=new Map(rd.map((t,e)=>[t,go[e]])),Xu=t=>go.reduce((e,n)=>e.split(n).join(D_.get(n)),t),L_=t=>rd.reduce((e,n)=>e.split(n).join(O_.get(n)),t),Of=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Oi(e)+"/"+t):Q(t),N_=16*1024*1024,Qu=Symbol("process"),ef=Symbol("file"),tf=Symbol("directory"),Nc=Symbol("symlink"),nf=Symbol("hardlink"),Ii=Symbol("header"),Qs=Symbol("read"),Mc=Symbol("lstat"),eo=Symbol("onlstat"),Bc=Symbol("onread"),Fc=Symbol("onreadlink"),zc=Symbol("openfile"),Uc=Symbol("onopenfile"),vn=Symbol("close"),lo=Symbol("mode"),Hc=Symbol("awaitDrain"),Ec=Symbol("ondrain"),Nt=Symbol("prefix"),Lf=class extends Zn{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=Qc(e);super(),this.path=Q(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||N_,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=Q(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?Q(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[a,d]=nd(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=L_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(n.absolute||Ju.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[eo](o):this[Mc]()}warn(t,e,n={}){return po(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Mc](){Lt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[eo](e)})}[eo](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=F_(t),this.emit("stat",t),this[Qu]()}[Qu](){switch(this.type){case"File":return this[ef]();case"Directory":return this[tf]();case"SymbolicLink":return this[Nc]();default:return this.end()}}[lo](t){return Df(t,this.type==="Directory",this.portable)}[Nt](t){return Of(t,this.prefix)}[Ii](){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 Vn({path:this[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](this.linkpath):this.linkpath,mode:this[lo](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 ao({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[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](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)}[tf](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ii](),this.end()}[Nc](){Lt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Fc](e)})}[Fc](t){this.linkpath=Q(t),this[Ii](),this.end()}[nf](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Ju.relative(this.cwd,t)),this.stat.size=0,this[Ii](),this.end()}[ef](){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[nf](e);this.linkCache.set(t,this.absolute)}if(this[Ii](),this.stat.size===0)return this.end();this[zc]()}[zc](){Lt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Uc](e)})}[Uc](t){if(this.fd=t,this.#e)return this[vn]();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:n,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Lt.read(t,e,n,i,o,(a,d)=>{if(a)return this[vn](()=>this.emit("error",a));this[Bc](d)})}[vn](t=()=>{}){this.fd!==void 0&&Lt.close(this.fd,t)}[Bc](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[vn](()=>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[vn](()=>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[Ec]():this[Hc](()=>this[Ec]())}[Hc](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)}[Ec](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[vn](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]()}},M_=class extends Lf{sync=!0;[Mc](){this[eo](Lt.lstatSync(this.absolute))}[Nc](){this[Fc](Lt.readlinkSync(this.absolute))}[zc](){this[Uc](Lt.openSync(this.absolute,"r"))}[Qs](){let t=!0;try{let{fd:e,buf:n,offset:i,length:o,pos:a}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let d=Lt.readSync(e,n,i,o,a);this[Bc](d),t=!1}finally{if(t)try{this[vn](()=>{})}catch{}}}[Hc](t){t()}[vn](t=()=>{}){this.fd!==void 0&&Lt.closeSync(this.fd),t()}},B_=class extends Zn{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 po(this,t,e,n)}constructor(t,e={}){let n=Qc(e);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=n.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[lo](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:n.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=nd(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Vn({path:this[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](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 ao({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[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](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 a=this.header?.block;if(!a)throw new Error("failed to encode header");super.write(a),t.pipe(this)}[Nt](t){return Of(t,this.prefix)}[lo](t){return Df(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}},F_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",z_=class Rr{tail;head;length=0;static create(e=[]){return new Rr(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++)H_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)G_(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,o=0;i;o++)e.call(n,i.value,o,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(n,i.value,o,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Rr;for(let o=this.head;o;)i.push(e.call(n,o.value,this)),o=o.next;return i}mapReverse(e,n){n=n||this;var i=new Rr;for(let o=this.tail;o;)i.push(e.call(n,o.value,this)),o=o.prev;return i}reduce(e,n){let i,o=this.head;if(arguments.length>1)i=n;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var a=0;o;a++)i=e(i,o.value,a),o=o.next;return i}reduceReverse(e,n){let i,o=this.tail;if(arguments.length>1)i=n;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let a=this.length-1;o;a--)i=e(i,o.value,a),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Rr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.head,a=0;for(a=0;o&&a<e;a++)o=o.next;for(;o&&a<n;a++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Rr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.length,a=this.tail;for(;a&&o>n;o--)a=a.prev;for(;a&&o>e;o--,a=a.prev)i.push(a.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let d=0;o&&d<e;d++)o=o.next;let a=[];for(let d=0;o&&d<n;d++)a.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=U_(this,o,d);return a}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=n,this.tail=e,this}};function U_(t,e,n){let i=e,o=e?e.next:t.head,a=new id(n,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function H_(t,e){t.tail=new id(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function G_(t,e){t.head=new id(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var id=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}},sf=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},of=Buffer.alloc(1024),to=Symbol("onStat"),Ai=Symbol("ended"),vt=Symbol("queue"),ki=Symbol("pendingLinks"),_n=Symbol("current"),jn=Symbol("process"),Ti=Symbol("processing"),Vs=Symbol("processJob"),St=Symbol("jobs"),vc=Symbol("jobDone"),no=Symbol("addFSEntry"),af=Symbol("addTarEntry"),Gc=Symbol("stat"),qc=Symbol("readdir"),ro=Symbol("onreaddir"),io=Symbol("pipe"),cf=Symbol("entry"),Sc=Symbol("entryOpt"),so=Symbol("writeEntryClass"),Nf=Symbol("write"),Ic=Symbol("ondrain"),mo=class extends Zn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[so];onWriteEntry;[vt];[ki]=new Map;[St]=0;[Ti]=!1;[Ai]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[so]=Lf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new $w(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Zw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Yw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[Ic]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Ic]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[vt]=new z_,this[St]=0,this.jobs=Number(t.jobs)||4,this[Ti]=!1,this[Ai]=!1}[Nf](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[Ai]=!0,this[jn](),n&&n(),this}write(t){if(this[Ai])throw new Error("write after end");return typeof t=="string"?this[no](t):this[af](t),this.flowing}[af](t){let e=Q(rf.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new sf(t.path,e);n.entry=new B_(t,this[Sc](n)),n.entry.on("end",()=>this[vc](n)),this[St]+=1,this[vt].push(n)}this[jn]()}[no](t){let e=Q(rf.resolve(this.cwd,t));this[vt].push(new sf(t,e)),this[jn]()}[Gc](t){t.pending=!0,this[St]+=1;let e=this.follow?"stat":"lstat";co[e](t.absolute,(n,i)=>{t.pending=!1,this[St]-=1,n?this.emit("error",n):this[to](t,i)})}[to](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[_n])this[Vs](t);else{let n=`${e.dev}:${e.ino}`,i=this[ki].get(n);i?i.push(t):this[ki].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[jn]()}[qc](t){t.pending=!0,this[St]+=1,co.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[St]-=1,e)return this.emit("error",e);this[ro](t,n)})}[ro](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[jn]()}[jn](){if(!this[Ti]){this[Ti]=!0;for(let t=this[vt].head;t&&this[St]<this.jobs;t=t.next)if(this[Vs](t.value),t.value.ignore){let e=t.next;this[vt].removeNode(t),t.next=e}this[Ti]=!1,this[Ai]&&this[vt].length===0&&this[St]===0&&(this.zip?this.zip.end(of):(super.write(of),super.end()))}}get[_n](){return this[vt]&&this[vt].head&&this[vt].head.value}[vc](t){this[vt].shift(),this[St]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[ki].get(n);if(i){this[ki].delete(n);for(let o of i)o.pending=!1,this[Vs](o)}}this[jn]()}[Vs](t){if(t.pending&&t.pendingLink&&t===this[_n]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[_n]&&!t.piped&&this[io](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[to](t,e):this[Gc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[ro](t,e):this[qc](t),!t.readdir)return}if(t.entry=this[cf](t),!t.entry){t.ignore=!0;return}t===this[_n]&&!t.piped&&this[io](t)}}}[Sc](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}}[cf](t){this[St]+=1;try{return new this[so](t.path,this[Sc](t)).on("end",()=>this[vc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Ic](){this[_n]&&this[_n].entry&&this[_n].entry.resume()}[io](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[no](a+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={}){po(this,t,e,n)}},sd=class extends mo{sync=!0;constructor(t){super(t),this[so]=M_}pause(){}resume(){}[Gc](t){let e=this.follow?"statSync":"lstatSync";this[to](t,co[e](t.absolute))}[qc](t){this[ro](t,co.readdirSync(t.absolute))}[io](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[no](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Nf](i)})}},q_=(t,e)=>{let n=new sd(t),i=new Ef(t.file,{mode:t.mode||438});n.pipe(i),Mf(n,e)},j_=(t,e)=>{let n=new mo(t),i=new ho(t.file,{mode:t.mode||438});n.pipe(i);let o=new Promise((a,d)=>{i.on("error",d),i.on("close",a),n.on("error",d)});return Bf(n,e).catch(a=>n.emit("error",a)),o},Mf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Or({file:vf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Bf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Or({file:vf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},W_=(t,e)=>{let n=new sd(t);return Mf(n,e),n},K_=(t,e)=>{let n=new mo(t);return Bf(n,e).catch(i=>n.emit("error",i)),n},ik=Hi(q_,j_,W_,K_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),V_=process.env.__FAKE_PLATFORM__||process.platform,Hf=V_==="win32",{O_CREAT:Gf,O_NOFOLLOW:df,O_TRUNC:qf,O_WRONLY:jf}=Uf.constants,Wf=Number(process.env.__FAKE_FS_O_FILENAME__)||Uf.constants.UV_FS_O_FILEMAP||0,Z_=Hf&&!!Wf,J_=512*1024,Y_=Wf|qf|Gf|jf,lf=!Hf&&typeof df=="number"?df|qf|Gf|jf:null,Kf=lf!==null?()=>lf:Z_?t=>t<J_?Y_:"w":()=>"w",jc=(t,e,n)=>{try{return wo.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},uo=(t,e,n,i)=>{wo.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},X_=(t,e,n,i,o)=>{if(e.isDirectory())$f(Li.resolve(t,e.name),n,i,a=>{if(a)return o(a);let d=Li.resolve(t,e.name);uo(d,n,i,o)});else{let a=Li.resolve(t,e.name);uo(a,n,i,o)}},$f=(t,e,n,i)=>{wo.readdir(t,{withFileTypes:!0},(o,a)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!a.length)return uo(t,e,n,i);let d=a.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--d===0)return uo(t,e,n,i)}};for(let x of a)X_(t,x,e,n,f)})},Q_=(t,e,n,i)=>{e.isDirectory()&&Vf(Li.resolve(t,e.name),n,i),jc(Li.resolve(t,e.name),n,i)},Vf=(t,e,n)=>{let i;try{i=wo.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return jc(t,e,n);throw a}for(let o of i)Q_(t,o,e,n);return jc(t,e,n)},Zf=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"}},_o=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"}},ty=(t,e)=>{ut.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new Zf(t,n?.code||"ENOTDIR")),e(n)})},ny=(t,e,n)=>{t=Q(t);let i=e.umask??18,o=e.mode|448,a=(o&i)!==0,d=e.uid,u=e.gid,f=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,p=e.unlink,m=Q(e.cwd),v=(b,S)=>{b?n(b):S&&f?$f(S,d,u,I=>v(I)):a?ut.chmod(t,o,n):n()};if(t===m)return ty(t,v);if(x)return ey.mkdir(t,{mode:o,recursive:!0}).then(b=>v(null,b??void 0),v);let _=Q(fo.relative(m,t)).split("/");Wc(m,_,o,p,m,void 0,v)},Wc=(t,e,n,i,o,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),f=Q(fo.resolve(t+"/"+u));ut.mkdir(f,n,Jf(f,e,n,i,o,a,d))},Jf=(t,e,n,i,o,a,d)=>u=>{u?ut.lstat(t,(f,x)=>{if(f)f.path=f.path&&Q(f.path),d(f);else if(x.isDirectory())Wc(t,e,n,i,o,a,d);else if(i)ut.unlink(t,p=>{if(p)return d(p);ut.mkdir(t,n,Jf(t,e,n,i,o,a,d))});else{if(x.isSymbolicLink())return d(new _o(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,Wc(t,e,n,i,o,a,d))},ry=t=>{let e=!1,n;try{e=ut.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new Zf(t,n??"ENOTDIR")}},iy=(t,e)=>{t=Q(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==0,a=e.uid,d=e.gid,u=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),f=e.preserve,x=e.unlink,p=Q(e.cwd),m=b=>{b&&u&&Vf(b,a,d),o&&ut.chmodSync(t,i)};if(t===p)return ry(p),m();if(f)return m(ut.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=Q(fo.relative(p,t)).split("/"),_;for(let b=v.shift(),S=p;b&&(S+="/"+b);b=v.shift()){S=Q(fo.resolve(S));try{ut.mkdirSync(S,i),_=_||S}catch{let I=ut.lstatSync(S);if(I.isDirectory())continue;if(x){ut.unlinkSync(S),ut.mkdirSync(S,i),_=_||S;continue}else if(I.isSymbolicLink())return new _o(S,S+"/"+v.join("/"))}}return m(_)},Ac=Object.create(null),uf=1e4,Sr=new Set,sy=t=>{Sr.has(t)?Sr.delete(t):Ac[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Sr.add(t);let e=Ac[t],n=Sr.size-uf;if(n>uf/10){for(let i of Sr)if(Sr.delete(i),delete Ac[i],--n<=0)break}return e},oy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ay=oy==="win32",cy=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Yf(i,n)),e.push(n||"/"),e},[]),dy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=ay?["win32 parallelization disabled"]:t.map(i=>Oi(Yf(sy(i))));let n=new Set(t.map(i=>cy(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of n){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let a=o.at(-1);a instanceof Set?a.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:i}=e,o=new Set;for(let a of n){let d=this.#e.get(a);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(a);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let f of u)o.add(f)}for(let a of i){let d=this.#e.get(a),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(a);continue}else if(u.size===1){d.shift();let f=d[0];typeof f=="function"&&o.add(f)}else u.delete(t)}return this.#r.delete(t),o.forEach(a=>this.#i(a)),!0}},ly=()=>process.umask(),ff=Symbol("onEntry"),Kc=Symbol("checkFs"),hf=Symbol("checkFs2"),$c=Symbol("isReusable"),pt=Symbol("makeFs"),Vc=Symbol("file"),Zc=Symbol("directory"),oo=Symbol("link"),xf=Symbol("symlink"),pf=Symbol("hardlink"),Pi=Symbol("ensureNoSymlink"),gf=Symbol("unsupported"),mf=Symbol("checkPath"),kc=Symbol("stripAbsolutePath"),Sn=Symbol("mkdir"),$e=Symbol("onError"),Zs=Symbol("pending"),wf=Symbol("pend"),Ir=Symbol("unpend"),Tc=Symbol("ended"),Cc=Symbol("maybeClose"),Jc=Symbol("skip"),Ni=Symbol("doChown"),Mi=Symbol("uid"),Bi=Symbol("gid"),Fi=Symbol("checkedCwd"),uy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,zi=uy==="win32",fy=1024,hy=(t,e)=>{if(!zi)return oe.unlink(t,e);let n=t+".DELETE."+zf(16).toString("hex");oe.rename(t,n,i=>{if(i)return e(i);oe.unlink(n,e)})},xy=t=>{if(!zi)return oe.unlinkSync(t);let e=t+".DELETE."+zf(16).toString("hex");oe.renameSync(t,e),oe.unlinkSync(e)},_f=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,od=class extends Ui{[Tc]=!1;[Fi]=!1;[Zs]=0;reservations=new dy;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[Tc]=!0,this[Cc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===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:fy,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||zi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Ue.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:ly():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[ff](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Cc](){this[Tc]&&this[Zs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[kc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,a]=nd(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||zi&&/^[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=Ue.posix.dirname(t.path),f=Ue.posix.normalize(Ue.posix.join(u,d.join("/")));if(f.startsWith("../")||f==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return o&&(t[e]=String(a),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:n})),!0}[mf](t){let e=Q(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=Q(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}n.splice(0,this.strip),t.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[kc](t,"path")||!this[kc](t,"linkpath"))return!1;if(t.absolute=Ue.isAbsolute(t.path)?Q(Ue.resolve(t.path)):Q(Ue.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Q(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Ue.win32.parse(String(t.absolute));t.absolute=i+Xu(String(t.absolute).slice(i.length));let{root:o}=Ue.win32.parse(t.path);t.path=o+Xu(t.path.slice(o.length))}return!0}[ff](t){if(!this[mf](t))return t.resume();switch($_.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[gf](t)}}[$e](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Ir](),e.resume())}[Sn](t,e,n){ny(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},n)}[Ni](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}[Mi](t){return _f(this.uid,t.uid,this.processUid)}[Bi](t){return _f(this.gid,t.gid,this.processGid)}[Vc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new ho(String(t.absolute),{flags:Kf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&oe.close(i.fd,()=>{}),i.write=()=>!0,this[$e](u,t),e()});let o=1,a=u=>{if(u){i.fd&&oe.close(i.fd,()=>{}),this[$e](u,t),e();return}--o===0&&i.fd!==void 0&&oe.close(i.fd,f=>{f?this[$e](f,t):this[Ir](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,p=t.mtime;oe.futimes(f,x,p,m=>m?oe.utimes(u,x,p,v=>a(v&&m)):a())}if(typeof f=="number"&&this[Ni](t)){o++;let x=this[Mi](t),p=this[Bi](t);typeof x=="number"&&typeof p=="number"&&oe.fchown(f,x,p,m=>m?oe.chown(u,x,p,v=>a(v&&m)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[$e](u,t),e()}),t.pipe(d)),d.pipe(i)}[Zc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Sn](String(t.absolute),n,i=>{if(i){this[$e](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[Ir](),t.resume())};t.mtime&&!this.noMtime&&(o++,oe.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Ni](t)&&(o++,oe.chown(String(t.absolute),Number(this[Mi](t)),Number(this[Bi](t)),a)),a()})}[gf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[xf](t,e){let n=Q(Ue.relative(this.cwd,Ue.resolve(Ue.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Pi](t,this.cwd,n,()=>this[oo](t,String(t.linkpath),"symlink",e),i=>{this[$e](i,t),e()})}[pf](t,e){let n=Q(Ue.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Pi](t,this.cwd,i,()=>this[oo](t,n,"link",e),o=>{this[$e](o,t),e()})}[Pi](t,e,n,i,o){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Ue.resolve(e,a);oe.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new _o(d,Ue.resolve(d,n.join("/"))));this[Pi](t,d,n,i,o)})}[wf](){this[Zs]++}[Ir](){this[Zs]--,this[Cc]()}[Jc](t){this[Ir](),t.resume()}[$c](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!zi}[Kc](t){this[wf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[hf](t,n))}[hf](t,e){let n=d=>{e(d)},i=()=>{this[Sn](this.cwd,this.dmode,d=>{if(d){this[$e](d,t),n();return}this[Fi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Ue.dirname(String(t.absolute)));if(d!==this.cwd)return this[Sn](d,this.dmode,u=>{if(u){this[$e](u,t),n();return}a()})}a()},a=()=>{oe.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Jc](t),n();return}if(d||this[$c](t,u))return this[pt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=p=>this[pt](p??null,t,n);return f?oe.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return oe.rmdir(String(t.absolute),f=>this[pt](f??null,t,n))}if(t.absolute===this.cwd)return this[pt](null,t,n);hy(String(t.absolute),f=>this[pt](f??null,t,n))})};this[Fi]?o():i()}[pt](t,e,n){if(t){this[$e](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Vc](e,n);case"Link":return this[pf](e,n);case"SymbolicLink":return this[xf](e,n);case"Directory":case"GNUDumpDir":return this[Zc](e,n)}}[oo](t,e,n,i){oe[n](e,String(t.absolute),o=>{o?this[$e](o,t):(this[Ir](),t.resume()),i()})}},Ci=t=>{try{return[null,t()]}catch(e){return[e,null]}},Xf=class extends od{sync=!0;[pt](t,e){return super[pt](t,e,()=>{})}[Kc](t){if(!this[Fi]){let o=this[Sn](this.cwd,this.dmode);if(o)return this[$e](o,t);this[Fi]=!0}if(t.absolute!==this.cwd){let o=Q(Ue.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[Sn](o,this.dmode);if(a)return this[$e](a,t)}}let[e,n]=Ci(()=>oe.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Jc](t);if(e||this[$c](t,n))return this[pt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Ci(()=>{oe.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[pt](d,t)}let[o]=Ci(()=>oe.rmdirSync(String(t.absolute)));this[pt](o,t)}let[i]=t.absolute===this.cwd?[]:Ci(()=>xy(String(t.absolute)));this[pt](i,t)}[Vc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{oe.closeSync(o)}catch(f){u=f}(d||u)&&this[$e](d||u,t),e()},o;try{o=oe.openSync(String(t.absolute),Kf(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[$e](d,t)),t.pipe(a)),a.on("data",d=>{try{oe.writeSync(o,d,0,d.length)}catch(u){i(u)}}),a.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{oe.futimesSync(o,u,f)}catch(x){try{oe.utimesSync(String(t.absolute),u,f)}catch{d=x}}}if(this[Ni](t)){let u=this[Mi](t),f=this[Bi](t);try{oe.fchownSync(o,Number(u),Number(f))}catch(x){try{oe.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||x}}}i(d)})}[Zc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Sn](String(t.absolute),n);if(i){this[$e](i,t),e();return}if(t.mtime&&!this.noMtime)try{oe.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ni](t))try{oe.chownSync(String(t.absolute),Number(this[Mi](t)),Number(this[Bi](t)))}catch{}e(),t.resume()}[Sn](t,e){try{return iy(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(n){return n}}[Pi](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=Ue.resolve(a,d);let[u,f]=Ci(()=>oe.lstatSync(a));if(u)return i();if(f.isSymbolicLink())return o(new _o(a,Ue.resolve(e,n.join("/"))))}i()}[oo](t,e,n,i){let o=`${n}Sync`;try{oe[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[$e](a,t)}}},py=t=>{let e=new Xf(t),n=t.file,i=Ff.statSync(n),o=t.maxReadSize||16*1024*1024;new Dw(n,{readSize:o,size:i.size}).pipe(e)},gy=(t,e)=>{let n=new od(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Ff.stat(o,(u,f)=>{if(u)d(u);else{let x=new Xc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},Qf=Hi(py,gy,t=>new Xf(t),t=>new od(t),(t,e)=>{e?.length&&Pf(t,e)}),my=(t,e)=>{let n=new sd(t),i=!0,o,a;try{try{o=lt.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=lt.openSync(t.file,"w+");else throw f}let d=lt.fstatSync(o),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let p=0,m=0;p<512;p+=m){if(m=lt.readSync(o,u,p,u.length-p,a+p),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!m)break e}let f=new Vn(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,wy(t,n,a,o,e)}finally{if(i)try{lt.closeSync(o)}catch{}}},wy=(t,e,n,i,o)=>{let a=new Ef(t.file,{fd:i,start:n});e.pipe(a),yy(e,o)},_y=(t,e)=>{e=Array.from(e);let n=new mo(t),i=(o,a,d)=>{let u=(v,_)=>{v?lt.close(o,b=>d(v)):d(null,_)},f=0;if(a===0)return u(null,0);let x=0,p=Buffer.alloc(512),m=(v,_)=>{if(v||_===void 0)return u(v);if(x+=_,x<512&&_)return lt.read(o,p,x,p.length-x,f+x,m);if(f===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let b=new Vn(p);if(!b.cksumValid)return u(null,f);let S=512*Math.ceil((b.size??0)/512);if(f+S+512>a||(f+=S+512,f>=a))return u(null,f);t.mtimeCache&&b.mtime&&t.mtimeCache.set(String(b.path),b.mtime),x=0,lt.read(o,p,0,512,f,m)};lt.read(o,p,0,512,f,m)};return new Promise((o,a)=>{n.on("error",a);let d="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",lt.open(t.file,d,u);if(f||!x)return a(f);lt.fstat(x,(p,m)=>{if(p)return lt.close(x,()=>a(p));i(x,m.size,(v,_)=>{if(v)return a(v);let b=new ho(t.file,{fd:x,start:_});n.pipe(b),b.on("error",a),b.on("close",o),by(n,e)})})};lt.open(t.file,d,u)})},yy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Or({file:e0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},by=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Or({file:e0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Ri=Hi(my,_y,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Uw(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")}),_k=Hi(Ri.syncFile,Ri.asyncFile,Ri.syncNoFile,Ri.asyncNoFile,(t,e=[])=>{Ri.validate?.(t,e),Ey(t)}),Ey=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))};$t();var gt={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 yo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function t0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function bo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function n0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function r0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function i0(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}en();Je();te();Pe();Je();function Lr(t,e){if(yo(t)!=="cloud")throw new A("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Gi(t){return t.startsWith("http://")||t.startsWith("https://")}function Nr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as lT}from"node:fs";import{dirname as fT,join as hT}from"node:path";import{fileURLToPath as pT}from"node:url";var Bt="0.3.2-alpha.1";import{mkdir as zy,rm as E0}from"node:fs/promises";import{join as Ki}from"node:path";Kt();import{readFileSync as Ry}from"node:fs";var Py=384;async function ad(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await xn(t.agentEnvFile,n,{mode:Py})}function Yn(t){try{let e=JSON.parse(Ry(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Eo(t,e,n={},i=o=>o){return{...i({...t,...Yn(e)}),...n}}Kt();function qi(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(Dy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
|
|
92
92
|
`)}
|
|
93
93
|
`}function Dy(t){if(t.includes(`
|
|
94
|
-
`)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}te();
|
|
95
|
-
`)}}function
|
|
94
|
+
`)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}te();Pe();import{homedir as Ny}from"node:os";import{join as My}from"node:path";Je();te();var vo="1008033",c0="1289";var d0="pbbp2",l0="https://www.coze.cn",u0="/api/coze_claw/resource/get_frontier_key",Oy="https://www.coze.cn",Ly="wss://frontier.coze.cn";function Mr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??Oy}function f0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Ly}function kn(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 Wi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var ji=G("handshake");async function cd(t){let e=Mr(t.endpoint),n=t.timeoutMs??1e4,i=`${Nr(e)}${u0}?aid=${encodeURIComponent(vo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...kn(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),n);ji.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:a.signal}),f=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let b=await u.text().catch(()=>"");throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${b.slice(0,200)}`)}let p=await u.json();if(p.code!==void 0&&p.code!==0)throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${p.code} msg=${p.msg??"-"} logid=${f}`);let m=p.data??{},v=typeof m.access_key=="string"&&m.access_key||typeof m.accessKey=="string"&&m.accessKey||void 0,_=typeof m.device_id=="string"&&m.device_id||typeof m.deviceId=="string"&&m.deviceId||void 0;if(!v||!_){let b=JSON.stringify(p).slice(0,500);throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${b}`)}return ji.info("handshake ok",{remoteDeviceId:_,logid:f,traceId:x}),{accessKey:v,deviceId:_}}catch(u){if(u instanceof A)throw ji.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw ji.warn("handshake timeout",{base:e,timeoutMs:n}),new A("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let f=u.cause;throw ji.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 A("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var So=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",kt="auto",dd=19e4,h0=32e3;function p0(t){return{model:ld(t.model)??kt,...t.modelToken?{modelToken:t.modelToken}:{}}}function g0(t){return!t||t===kt}var By=new Set(["auto","\u81EA\u52A8"]);function ld(t){let e=t?.trim();if(e)return By.has(e.toLowerCase())?kt:e}function m0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=So,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||kt;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=n,e.ANTHROPIC_DEFAULT_OPUS_MODEL=n,e.ANTHROPIC_DEFAULT_SONNET_MODEL=n,e.CLAUDE_CODE_SUBAGENT_MODEL=n,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else g0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function w0(t,e,n,i){let o={};if(t.modelToken?o.model=t.model||kt:g0(t.model)||(o.model=t.model),t.modelToken){let a={name:"coze",base_url:`${So}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=Io(e,n,i);Object.keys(d).length>0&&(a.http_headers=d),o.model_providers={coze:a},o.model_context_window=t.modelInfo?.contextWindow??dd}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function _0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Io(t,e,n){let{ttEnv:i,usePpe:o}=Wi(t),a={};return i&&(a["x-tt-env"]=i),o&&(a["x-use-ppe"]=o),e&&(a["x-mock-scenario"]=e),n&&(a["x-coze-request-scene"]=n),a}function y0(t,e,n,i){if(!t.modelToken)return{};let o=Io(e,n,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,u])=>`${d}:${u}`).join(`
|
|
95
|
+
`)}}function ud(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function fd(t){return t.model||kt}function x0(t,e,n,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:i,api:"openai-completions"}}function b0(t,e,n,i,o){if(!t.modelToken)return null;let a=fd(t),d=Io(e,n,o),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let f=[x0(a,u,t.modelInfo?.contextWindow??dd,t.modelInfo?.maxOutput??h0)],x=new Set([a]);for(let m of i??[])!m||x.has(m)||(x.add(m),f.push(x0(m,["text"],dd,h0)));let p={baseUrl:`${So}/v1`,api:"openai-completions",apiKey:t.modelToken,models:f};return Object.keys(d).length>0&&(p.headers=d),p}function Fy(t){if(t!==void 0)return t?"auto":"text"}function hd(t,e,n){let i=Io(e,n),o=t.model||kt,a=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${So}/v1`];if(t.modelInfo?.contextWindow&&a.push(` context_length: ${t.modelInfo.contextWindow}`),t.modelInfo?.maxOutput&&a.push(` max_tokens: ${t.modelInfo.maxOutput}`),t.modelToken&&a.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){a.push(" default_headers:");for(let[u,f]of Object.entries(i))a.push(` ${u}: ${JSON.stringify(f)}`)}a.push("compression:"),a.push(" threshold: 0.8"),a.push("approvals:"),a.push(` mode: ${JSON.stringify("off")}`),a.push(` cron_mode: ${JSON.stringify("approve")}`);let d=Fy(t.modelInfo?.capabilities?.image);return d&&(a.push("agent:"),a.push(` image_input_mode: ${JSON.stringify(d)}`)),a.push("skills:"),a.push(" external_dirs:"),a.push(` - ${My(Ny(),".hermes","skills")}`),`${a.join(`
|
|
96
96
|
`)}
|
|
97
|
-
`}var
|
|
98
|
-
`).slice(1,6).join(" | ")}),await E0(n,{force:!0}).catch(a=>
|
|
99
|
-
`).slice(1,6).join(" | ")}),await E0(n,{recursive:!0,force:!0}).catch(i=>
|
|
100
|
-
`).slice(1,6).join(" | ")});let i=await
|
|
97
|
+
`}var Xn=G("hermes-config"),v0="dont_ask",S0="default";function Qn(t,e){return Ki(Re(t,e).root,"hermes-home")}async function Uy(t){let e=Qn(t.agentId,t.paths);await zy(e,{recursive:!0,mode:448});let n=qi({...process.env,...Yn(t.paths.agentEnvFile)});await ct(Ki(e,".env"),n,{mode:384});let i=hd(t.modelConfig,t.cozeEnv,t.mockScenario);await ct(Ki(e,"config.yaml"),i,{mode:384}),Xn.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function I0(t){let e=Qn(t.agentId,t.paths),n=Ki(e,"state.db"),i=Ki(e,"config.yaml");Xn.warn("[AUDIT] ABOUT TO RM hermes state.db (resetHermesHome)",{src:"hermes-config.resetHermesHome",agentId:t.agentId,home:e,stateDb:n,callerStack:new Error("resetHermesHome-caller").stack?.split(`
|
|
98
|
+
`).slice(1,6).join(" | ")}),await E0(n,{force:!0}).catch(a=>Xn.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let o=hd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await ct(i,o,{mode:384}).catch(a=>Xn.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(a)})),Xn.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function pd(t,e){let n=Qn(t,e);Xn.warn("[AUDIT] ABOUT TO RM hermes-home (cleanupHermesHome)",{src:"hermes-config.cleanupHermesHome",agentId:t,home:n,callerStack:new Error("cleanupHermesHome-caller").stack?.split(`
|
|
99
|
+
`).slice(1,6).join(" | ")}),await E0(n,{recursive:!0,force:!0}).catch(i=>Xn.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var xd=new Map;function A0(t){let e=xd.get(t.agentId);if(e)return e;let n=Uy(t).finally(()=>xd.delete(t.agentId));return xd.set(t.agentId,n),n}var ie=G("agent-handlers"),T0=5*1024*1024,Wy=1,Ky=6,$y=new Set(["node_modules",".git",".coze","dist","build",".next"]),Vy=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Zy=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Jy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Yy(t){let e=t?.trim();return e?Jy.test(e)||Zy.test(e)?e:(ie.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Xy(t){return new Promise((e,n)=>{let i=at("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,a=d=>{o||(o=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),a()}),i.once("error",d=>a(d))})}function Qy(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var ko=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??Z()}async listSkills(e){e._meta;let n=Jn(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Re(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Fr(a,n,o,this.paths),f=[],x=new Set;for(let m of d){let v=fe(u,m.relPath,"SKILL.md");await Ed(v).then(b=>b.isFile()).catch(()=>!1)&&(f.push(ib(m)),x.add(m.relPath))}if(e.scanLocal){let m=await z0(n,o,a,this.paths),v=await U0(n,a);for(let _ of[...m,...v])x.has(_.relPath)||(x.add(_.relPath),f.push(_.skill))}return{skills:a==="hermes"?f.filter(m=>m.skillName!=="yuanbao"):f}}async addSkills(e){e._meta;let n=Jn(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await To({agentId:n,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});Co(a,d,x),u.push(f)}return await xi(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=Jn(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:u}=Fr(i.framework,n,i.workspace,this.paths);for(let f of a){if(!o.has(f.skillId)){d.push(f);continue}let x=fe(u,f.relPath);ie.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:f.skillId,relPath:f.relPath,skillBase:u,absDir:x}),await wd(x,{recursive:!0,force:!0}),ie.info("skill removed",{agentId:n,skillId:f.skillId,relPath:f.relPath})}return await xi(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=Jn(e._meta);if(!e.skillName)throw new A("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");ie.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),o=i?.workspace??Re(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,u=await tb(n,o,a,e.skillName,d,this.paths);if(!u){let R=d?"global":"workspace";throw new A("SKILL_NOT_FOUND",`skill not found in ${R}: ${e.skillName}`)}let{absDir:f,relPath:x,dirName:p}=u,m=fe(f,"SKILL.md"),v=new Sd.default;v.addLocalFolder(f,p);let _=v.toBuffer();if(_.length>C0)throw new A("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${C0}`);let b=await Ao(m,{encoding:"utf8"}).then(R=>B0(R).description).catch(()=>{}),S={};this.opts.publishSkillToMarketplace?S=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...b?{description:b}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):ie.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let I=S.version??"v1.0",T=S.skillId??e.skillId??M0(n,x);if(i&&!d){let R=i.skills??[],E=R.find(P=>P.relPath===x);E?(E.version=I,E.skillId=T):R.push({skillId:T,skillName:e.skillName,relPath:x,version:I,installedAt:Date.now(),...b?{description:b}:{}}),await xi(n,R)}return ie.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:T,version:I}),{ok:!0,skillId:T,version:I}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[o,a]of i.sessions){if(!a.downstream)continue;let d=a.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(a)){a.reloadAfterTurn=!0,ie.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let f=a.downstream;a.downstream=void 0,ie.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(n).catch(x=>ie.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return ie.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await Ie(n);if(!i)throw new A("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return ie.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await mr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw ie.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(o)}),new A("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await qe(i),ie.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 A("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Ie(n))throw new A("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&Gi(e.registry)&&o.push(`--registry=${e.registry}`);let a=Yy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&Vy.test(d)&&o.push("--env",d);let u=await Xy(o);return ie.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:u,targetVersion:a,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 A("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Ie(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await qe(i),ie.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}):(ie.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new A("IPC_BAD_REQUEST",`${gt.DELETE}: missing agentId`);ie.warn("[AUDIT] deleteAgent handler entry",{agentId:n,reason:e.reason??"",forceParamDeployType:e.deployType,metaDeployType:e._meta?.cozeDeployType,callerStack:new Error("deleteAgent-caller").stack?.split(`
|
|
100
|
+
`).slice(1,6).join(" | ")});let i=await Ie(n),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,a=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let d=Re(n);return a==="cloud"?(ie.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:n,path:d.root,deployType:a,reason:e.reason??""}),await wd(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await qe(i)),ie.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(Lr(e._meta,"_agent/switchModel"),!e.agentId)throw new A("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=ld(e.model)??kt,i=await Ie(e.agentId);if(!i)throw new A("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await qe(i),ie.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return ie.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let a=o.model,d=o.modelInfo;o.model=n,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,a).catch(x=>ie.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=o.framework==="hermes"&&Qy(d,o.modelInfo);if(o.framework==="hermes"&&!u){let x=[];for(let[p,m]of o.allSessionQueues())x.push(m.enqueue(async()=>{let v=o.sessions.get(p);if(!(!v?.downstream||!v.acpSessionId))try{await v.downstream.setSessionModel?.({sessionId:v.acpSessionId,modelId:n})}catch(_){ie.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:p,acpId:v.acpSessionId,err:String(_)})}}));return await Promise.all(x),ie.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:x.length}),{ok:!0}}let f=[];for(let[x,p]of o.allSessionQueues())f.push(p.enqueue(async()=>{let m=o.sessions.get(x);m?.downstream&&(await m.downstream.stop(`switchModel: ${n}`).catch(()=>{}),m.downstream=void 0)}));return await Promise.all(f),ie.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:f.length}),{ok:!0}}async resetAgent(e){if(Lr(e._meta,gt.RESET),!e.agentId)throw new A("IPC_BAD_REQUEST",`${gt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,gt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>ie.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,gt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),ie.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(n);for(let a of i.sessions.values())a.acpSessionId=void 0,a.replySeq=0,a.loadingSession=!1,a.spawnFailCount=void 0,a.spawnFailedAt=void 0;let o=new Map;for(let[a,d]of i.sessions)o.set(a,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt,permissionMode:d.permissionMode,cozeGroupId:d.cozeGroupId});await hi(e,o)}async clearPersistedAcpSessionIds(e){let n=await Ie(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let o of Object.values(n.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await qe(n)}async repairAgent(e){if(Lr(e._meta,gt.REPAIR),!e.agentId)throw new A("IPC_BAD_REQUEST",`${gt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new A("IPC_BAD_REQUEST",`${gt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){ie.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,gt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){ie.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){ie.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Lr(e._meta,"_agent/getFileTree");let n=e._meta,i=Jn(n),o=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(o,a),u=await gd(d).catch(()=>null);if(!u)throw new A("IPC_BAD_REQUEST",`path not found: ${a}`);if(u.isSymbolicLink())throw new A("IPC_BAD_REQUEST",`symlink not allowed: ${a}`);if(!await fi(d,o))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let f=gb(e.depth);return u.isDirectory()?{tree:await pb(o,d,a,f)}:{tree:[{name:mb(a),path:q0(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Lr(e._meta,"_agent/getFileContent");let n=Jn(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new A("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),a=await gd(o).catch(()=>null);if(!a||!a.isFile())throw new A("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(a.isSymbolicLink())throw new A("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await fi(o,i))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>T0)throw new A("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${T0})`);let d=await Ao(o);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:a.size}:{content:d.toString("utf8"),encoding:"utf-8",size:a.size}}async resolveWorkspace(e){let n=this.opts.agents.get(e);return n?n.workspace:(await Ie(e).catch(()=>null))?.workspace??Re(e).workspace}safeJoin(e,n){let i=yd(e,n||"."),o=vd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${P0}`))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return Ie(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new A("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function L0(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new A("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new A("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function Fr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:fe(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:fe(".agents","skills")};case"hermes":return{base:Qn(e,i??Z()),subdir:"skills"}}}function N0(t){let e=Gy();if(t==="claude-code")return[fe(e,".claude","skills")];if(t==="codex")return[fe(e,".agents","skills"),fe(e,".codex","skills")];if(t==="openclaw")return[fe(e,".agents","skills"),fe(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||fe(e,"AppData","Local");return[fe(n,"hermes","skills"),fe(e,".hermes","skills")]}return[fe(e,".hermes","skills")]}return[]}async function eb(t,e,n,i,o,a){let d=async u=>Ed(fe(u,"SKILL.md")).then(f=>f.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:f}=Fr(n,t,e,a),x=fe(f,i),p=fe(u,x);return await d(p)?{absDir:p,relPath:x}:null}for(let u of N0(n)){let f=fe(u,i);if(await d(f))return{absDir:f,relPath:f}}return null}async function tb(t,e,n,i,o,a){let d=L0(i),u=await eb(t,e,n,d,o,a);if(u)return{...u,dirName:d};let x=(o?await U0(t,n):await z0(t,e,n,a)).filter(v=>v.skill.skillName===i);if(x.length>1)throw new A("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${x.map(v=>k0(v.relPath)).join(", ")} \u2014 rename or remove duplicates`);let p=x[0];return p?{absDir:o?p.relPath:fe(e,p.relPath),relPath:p.relPath,dirName:k0(p.relPath)}:null}function M0(t,e){return(Hy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function B0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
|
|
101
101
|
---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let o of n.split(`
|
|
102
|
-
`)){let a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!a||!a[2])continue;let d=a[1],u=a[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function F0(t,e,n,i){let o=await P0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let a=[];for(let d of o){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await yd(ue(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=d.name,x=ue(n,h),g=ue(e,h,"SKILL.md"),m=await So(g,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let S=B0(m);a.push({relPath:x,skill:{skillId:M0(t,x),skillName:S.name||h,...S.description?{description:S.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function z0(t,e,n,i){let{base:o,subdir:a}=Br(n,t,e,i);return F0(t,ue(o,a),a,!1)}async function U0(t,e){let n=[],i=new Set;for(let o of L0(e)){let a=await F0(t,o,o,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var nb=3e4,rb=50*1024*1024,C0=10*1024*1024,Mr=3e4;async function ko(t){let{agentId:e,workspace:n,framework:i,skill:o,paths:a}=t;if(!o.skillName)throw new A("IPC_BAD_REQUEST","skill missing skillName");let d=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!d&&!u)throw new A("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let h=N0(o.skillName),{base:x,subdir:g}=Br(i,e,n,a),m=ue(g,h),S=ue(x,m);if(await pd(S,{recursive:!0}),d){let v=Buffer.from(o.content,"utf8");Ki(v.length),await md(ue(S,"SKILL.md"),v,"utf8")}else{let v=await ob(o.downloadUrl);cb(v)?await fb(v,S):db(v)?await lb(v,S):await md(ue(S,"SKILL.md"),v.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:m,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return ie.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:m,source:d?"content":"downloadUrl"}),_}function Ao(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 ib(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 sb(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 H0(t,e){let n=await Ee(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Lt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await He(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((m,S)=>[m.skillId,S])),u=a.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await He(n,e),{status:"noop",count:0};let h=0,x=0,{base:g}=Br(n.framework,t,n.workspace,e);ie.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:g,builtinCount:u.length,builtinRelPaths:u.map(m=>m.relPath)});for(let m of u)try{let S=ue(g,m.relPath);ie.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:m.skillId,relPath:m.relPath,rmTarget:S}),await gd(S,{recursive:!0,force:!0});let _=await ko({agentId:t,workspace:n.workspace,framework:n.framework,skill:sb(m),...e?{paths:e}:{}});Ao(a,d,_),h+=1}catch(S){x+=1,ie.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(S)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await He(n,e),ie.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function ob(t){if(!t)throw new A("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ki(e);let n=ab(t);return Ki(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await So(e);return Ki(n.length),n}if(Hi(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),nb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new A("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Ki(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new A("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Ki(t){if(t>rb)throw new A("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function ab(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new A("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 cb(t){return t.length>=2&&t[0]===31&&t[1]===139}function db(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 _d(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function lb(t,e){let n,i;try{n=new Ed.default(t),i=n.getEntries()}catch(d){throw new A("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||_d(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new A("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new A("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new A("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=ub(i),a=wd(e);for(let d of i){if(_d(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=wd(e,u),x=bd(a,h);if(x.startsWith("..")||x==="..")throw new A("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await pd(h,{recursive:!0});continue}await pd(qy(h),{recursive:!0});let g;try{g=d.getData()}catch(m){throw new A("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${m.message}`,{cause:m})}await md(h,g)}}function ub(t){let e;for(let n of t){let i=n.entryName;if(!i||_d(i))continue;let o=i.indexOf("/");if(o<=0)return;let a=i.slice(0,o+1);if(e===void 0)e=a;else if(e!==a)return}return e}async function fb(t,e){await hb(t);let n=Qf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new A("IPC_BAD_REQUEST",`tar extract timeout (${Mr}ms)`))},Mr);try{await O0(D0.from(t),n)}catch(a){throw a instanceof A?a:i?new A("IPC_BAD_REQUEST",`tar extract timeout (${Mr}ms)`):new A("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function hb(t){let e=[],n=Dr({onReadEntry:a=>{let d=a.path,u=a.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new A("IPC_BAD_REQUEST",`tar list timeout (${Mr}ms)`))},Mr);try{await O0(D0.from(t),n)}catch(a){throw i?new A("IPC_BAD_REQUEST",`tar list timeout (${Mr}ms)`):new A("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}if(e.length>0)throw new A("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var xb=5e3;async function pb(t,e,n,i){return G0(t,e,n,i,{count:0})}async function G0(t,e,n,i,o){if(i<=0)return[];let a;try{a=await P0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if($y.has(u.name)||u.isSymbolicLink())continue;if(o.count>=xb){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=ue(e,u.name),x=jy(ue(n,u.name)),g=null;try{g=await xd(h)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let m={name:u.name,path:q0(bd(t,h)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(m.children=await G0(t,h,x,i-1,o)),d.push(m)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function gb(t){return!t||t<=0?Wy:Math.min(t,Ky)}function mb(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function q0(t){return t.split(R0).join("/")}te();var An=U("agent-health-reporter"),wb=1e4,_b=3,$i=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??wb,this.livenessFailureThreshold=e.livenessFailureThreshold??_b}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=yb(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:Lt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,An.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=o?.authFailures;if(a&&a.length>0&&(An.warn("heartbeat received authFailures from cloud",{count:a.length,agentIds:a.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(a)}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 yb(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}jt();import{copyFile as BE,cp as FE,mkdir as zo,readFile as zE,rm as UE,stat as Pd,writeFile as HE}from"node:fs/promises";import{homedir as kh}from"node:os";import{basename as GE,join as Qt}from"node:path";un();import{existsSync as Rb}from"node:fs";import{release as Db}from"node:os";import{basename as Ob,isAbsolute as Nb}from"node:path";function Vi(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Fr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function zr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Tn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ve();var To=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Y={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function j0(t){return"method"in t&&"id"in t&&t.id!==void 0}function W0(t){return"method"in t&&!("id"in t)}function Co(t){return!("method"in t)&&"id"in t}var bb={AGENT_NOT_FOUND:Y.AGENT_NOT_FOUND,AGENT_BUSY:Y.AGENT_BUSY,AGENT_DISCONNECTED:Y.AGENT_DISCONNECTED,AGENT_TIMEOUT:Y.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Y.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Y.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Y.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Y.INTERNAL_ERROR,BRIDGE_INTERNAL:Y.INTERNAL_ERROR,IPC_AUTH_FAILED:Y.INTERNAL_ERROR,IPC_BAD_REQUEST:Y.INVALID_REQUEST,METHOD_NOT_FOUND:Y.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Y.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Y.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Y.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Y.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Y.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Y.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Y.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Y.FILE_TOO_LARGE,UNSUPPORTED_MIME:Y.UNSUPPORTED_MIME,UPLOAD_FAILED:Y.UPLOAD_FAILED,UPSTREAM_NOT_READY:Y.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Y.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Y.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Y.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Y.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Y.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Y.SKILL_ZIP_TOO_LARGE};function Eb(t){if(t!=null)return t instanceof Error?{name:t.name,message:Ji(t.message)}:typeof t=="string"?Ji(t):typeof t=="object"?Sb(t):t}var vb=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Ji(t){let e=t;for(let[n,i]of vb)e=e.replace(n,i);return e}function Sb(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Ji(i):e[n]=i;return e}function Zi(t){if(t instanceof A){let e=Eb(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(n.reason=e.reason),{code:bb[t.code]??Y.INTERNAL_ERROR,message:Ji(t.message),data:n}}return{code:Y.INTERNAL_ERROR,message:Ji(t instanceof Error?t.message:String(t))}}function K0(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,a=t.data;if(i&&e){let{message:d,...u}=e;a=u}return new A(n,o,{retriable:e?.retriable??!1,cause:a})}function V0(t){return`${JSON.stringify(t)}
|
|
103
|
-
`}var $0=10*1024*1024,
|
|
104
|
-
`);this.buffer=n.pop()??"";let i=[];for(let o of n){let a=o.replace(/\r$/,"").trim();if(a)try{i.push(JSON.parse(a))}catch(d){this.onError?.({line:a,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
|
|
105
|
-
`).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function th(t,e){if(t.length===0)return;let n=e?.killFn??Xi,i=e?.isAliveFn??Yi,o=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),a=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<a&&t.some(h=>i(h));u+=d)await o(Math.min(d,a-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var Pb=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]codex-acp/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function nh(t,e){if(!e)return null;for(let n of Pb)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function rh(t,e){return nh(t,e)}function ih(t,e){return nh(t,e)}function Gr(t,e,n){return!e&&n.firstUpdateMs>0&&t<n.firstUpdateMs?Math.max(1,n.firstUpdateMs-t):t<n.phase2GateMs?Math.max(1,n.phase2GateMs-t):Math.max(1,n.livenessWindowMs)}function sh(t,e,n){let o=n-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,g=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Gr(g,t.firstFrameSeen,e)}}let a=n-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return a>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?a<e.phase2GateMs?{action:"continue",rearmMs:Gr(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Gr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Gr(a,!1,e)}}var oh=Ze("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Lb=200,Mb=40,Bb=Ze("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Fb=Ze("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),zb=Ze("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Ub=Ze("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Hb=Ze("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Gb=Ze("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),ah=500;function qb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=ah?t:`${e.slice(0,ah)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function jb(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 ch(t){try{return Rb(t)}catch{return}}function Wb(t,e){return{platform:process.platform,osRelease:Db(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Nb(e.command)?ch(e.command):void 0,cwd:e.cwd,cwdExists:ch(e.cwd),envKeys:e.envKeys}}function Kb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Ob(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var pt=class{constructor(e){this.opts=e;this.log=U(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Po({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Ur;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new A("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=yo(process.env,this.opts.agentEnvFile??V().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=st(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,Y0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let a of this.decoder.push(o))this.dispatch(a)}catch(a){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(a)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let a=o.trimEnd();this.stderrRing.push(a),this.stderrRing.length>Lb&&this.stderrRing.shift(),this.log.debug("stderr",{text:a})}),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,a)=>{this.stopped=!0,X0(i.pid),(o!==0||a!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:a,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,a));for(let u of this.exitHandlers)u(o,a)}),i.on("error",o=>{let a=o,d=Wb(a,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new A("AGENT_SPAWN_FAILED",Kb(a,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(a=>n.once("exit",()=>a()));Xi(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||Xi(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:Hb,phase2GateMs:Bb,livenessWindowMs:Fb,absoluteMaxMs:zb,approvalMaxMs:Gb,suspendThresholdMs:Ub,...n};return this.call("session/prompt",e,oh,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Fr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(zr(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=oh,o){if(!this.child||this.stopped)return Promise.reject(new A("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=Vi(a,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let h=n.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let g={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(o){let m=this.now(),S={cfg:o,startedAt:m,lastActivityAt:m,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:m,expectedIntervalMs:Gr(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(),k=sh(v,S.cfg,I),T=P=>{S.armedAt=I,S.expectedIntervalMs=P,g.timer=setTimeout(_,P)};if(k.action==="suspend"){S.suspendedMs+=k.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:k.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),T(k.rearmMs);return}if(k.action==="continue"){T(k.rearmMs);return}this.pending.delete(a),k.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:k.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),x(k.awaitingApproval?new A("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new A("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new A("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(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),x(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,g);try{this.writeFrame(d)}catch(m){g.timer&&clearTimeout(g.timer),this.pending.delete(a),x(m)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new A("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(V0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(Co(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 A("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:qb(e.result)}),n.resolve(e.result));return}if(W0(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(j0(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let a=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!a)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(a):u&&e.activeToolCalls.delete(a)}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,Zi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=K0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=ih(this.framework,jb(e));return i?new A(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 A("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(Mb).join(`
|
|
106
|
-
`),o=rh(this.framework,i);return o?new A(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:n,stderrTail:i}}):new A("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 $b(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
|
|
107
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function pE(t){let e={};for(let n of t.split(/\r?\n/)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.startsWith("export ")?i.slice(7).trimStart():i,a=o.indexOf("=");if(a<=0)continue;let d=o.slice(0,a).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=xE(o.slice(a+1)))}return e}function gE(t){let e=
|
|
108
|
-
`)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{tE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function wE(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=fh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}te();var _E=U("hermes-downstream"),No=class extends pt{framework="hermes";modelId;constructor(e){let n={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(n),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(n){_E.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}};Ve();var yE=3e4,jr=class extends pt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},yE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};qt();Ve();te();Ae();function Td(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}un();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 Lo=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)Wr(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 Wr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Xt(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Yt();te();import{constants as gh}from"node:fs";import{access as bE,readFile as EE}from"node:fs/promises";import{delimiter as vE,dirname as SE,join as mh}from"node:path";var et=U("framework-detector"),wh={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},IE=[".exe",".cmd",".bat",".ps1"],Qn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??st,access:e.access??bE,readFile:e.readFile??EE}}async detect(e){let n=wh[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return et.debug("framework binary not found",{framework:e,bin:n}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[a,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:a};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(wh).map(async i=>[i,await this.detect(i)])),n={};for(let[i,o]of e)o&&(n[i]=o);return n}async which(e){let n=this.env.pathEnv.split(vE).filter(Boolean),i=this.env.platform==="win32"?["",...IE]:[""];for(let o of n)for(let a of i){let d=mh(o,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?gh.F_OK:gh.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let n;try{n=await this.env.readFile(e,"utf8")}catch(d){return et.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let o=n.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return et.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=mh(SE(o),"hermes-acp");return await this.isExecutable(a)?(et.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(et.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:a}),null)}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return et.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return et.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 et.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return et.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let a=o.find(d=>d?.isDefault===!0);return a?!a.id||!a.workspace?(et.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!a.id,hasWorkspace:!!a.workspace}),null):{id:a.id,workspace:a.workspace}:(et.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return et.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return et.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||et.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let o={reachable:i},a=n.stdout.match(/\{[\s\S]*\}/);if(a)try{let d=JSON.parse(a[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){et.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(AE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let o="",a=!1,d,u=h=>{a||(a=!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=>{o+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},kE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function AE(t){return t.replace(kE,"")}import{homedir as yh}from"node:os";import{join as Bo}from"node:path";qt();Yt();ur();Ve();te();async function bh(){let t=Bo(yh(),".openclaw/openclaw.json");return fn(t)}async function Eh(){return(await bh())?.gateway?.auth?.token??""}var er=U("openclaw.config"),TE=[0,5e3,5e3],CE=Ze("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),_h="models.providers.",Mo="agents.defaults.models",PE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function Kr(t,e){let n=Array.isArray(t)?[...t]:[],i=new Set(n);for(let o of e)i.has(o)||(i.add(o),n.push(o));return n}var Fo=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Cn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??TE,this.cliTimeoutMs=e.cliTimeoutMs??CE,this.openclawDir=e.openclawDir??Bo(yh(),".openclaw")}async withRetry(e,n){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let a=this.retryDelaysMs[o]??0;a>0&&await new Promise(d=>setTimeout(d,a));try{return await n()}catch(d){i=d,er.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new A("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=st(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=x=>{d||(d=!0,clearTimeout(h),x())};o.stderr?.on("data",x=>{a+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${a.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let o=String(i);if(n.some(a=>o.includes(a)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",n],["Config path not found","Nothing was changed"])))}catch(i){er.warn(`${e} failed (best-effort)`,{configPath:n,err:String(i)})}}ensureProvider(e,n){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${_h}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${_h}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Mo}[${e}]`,()=>this.runCli(["config","set",Mo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Mo}[${e}]`,`${Mo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await bh())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,a=[];for(let d of Object.keys(i))d.startsWith(o)&&a.push(d.slice(o.length));return a}ensureAgent(e,n,i){let o=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}ensureAcpDeviceScopes(){return this.queue.enqueue(()=>this.ensureAcpDeviceScopesUnlocked())}async ensureAcpDeviceScopesUnlocked(){try{let e=Bo(this.openclawDir,"identity","device.json"),i=(await fn(e))?.deviceId?.trim();if(!i)return er.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Bo(this.openclawDir,"devices","paired.json"),a=await fn(o),d=a?.[i];if(!a||!d)return er.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,h=Kr(Kr(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(v=>v.startsWith("operator.")),x=Kr([...PE],h),g=Kr(d.scopes,x),m=Kr(d.approvedScopes,x),S=u?Kr(u.scopes,x):void 0;return g.length!==(d.scopes?.length??0)||m.length!==(d.approvedScopes?.length??0)||u!==void 0&&S?.length!==(u.scopes?.length??0)?(d.scopes=g,d.approvedScopes=m,u&&S&&(u.scopes=S),await hn(o,a,{mode:384}),er.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(er.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return er.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};import{readFile as RE,writeFile as DE}from"node:fs/promises";import{join as OE}from"node:path";var NE=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
|
|
109
|
-
`),
|
|
102
|
+
`)){let a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!a||!a[2])continue;let d=a[1],u=a[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function F0(t,e,n,i){let o=await R0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let a=[];for(let d of o){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await Ed(fe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,x=fe(n,f),p=fe(e,f,"SKILL.md"),m=await Ao(p,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let v=B0(m);a.push({relPath:x,skill:{skillId:M0(t,x),skillName:v.name||f,...v.description?{description:v.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function z0(t,e,n,i){let{base:o,subdir:a}=Fr(n,t,e,i);return F0(t,fe(o,a),a,!1)}async function U0(t,e){let n=[],i=new Set;for(let o of N0(e)){let a=await F0(t,o,o,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var nb=3e4,rb=50*1024*1024,C0=10*1024*1024,Br=3e4;async function To(t){let{agentId:e,workspace:n,framework:i,skill:o,paths:a}=t;if(!o.skillName)throw new A("IPC_BAD_REQUEST","skill missing skillName");let d=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!d&&!u)throw new A("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let f=L0(o.skillName),{base:x,subdir:p}=Fr(i,e,n,a),m=fe(p,f),v=fe(x,m);if(await md(v,{recursive:!0}),d){let b=Buffer.from(o.content,"utf8");$i(b.length),await _d(fe(v,"SKILL.md"),b,"utf8")}else{let b=await ob(o.downloadUrl);cb(b)?await fb(b,v):db(b)?await lb(b,v):await _d(fe(v,"SKILL.md"),b.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:m,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return ie.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:m,source:d?"content":"downloadUrl"}),_}function Co(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 ib(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 sb(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 H0(t,e){let n=await Ie(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Bt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await qe(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((m,v)=>[m.skillId,v])),u=a.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await qe(n,e),{status:"noop",count:0};let f=0,x=0,{base:p}=Fr(n.framework,t,n.workspace,e);ie.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:p,builtinCount:u.length,builtinRelPaths:u.map(m=>m.relPath)});for(let m of u)try{let v=fe(p,m.relPath);ie.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:m.skillId,relPath:m.relPath,rmTarget:v}),await wd(v,{recursive:!0,force:!0});let _=await To({agentId:t,workspace:n.workspace,framework:n.framework,skill:sb(m),...e?{paths:e}:{}});Co(a,d,_),f+=1}catch(v){x+=1,ie.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(v)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await qe(n,e),ie.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function ob(t){if(!t)throw new A("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);$i(e);let n=ab(t);return $i(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Ao(e);return $i(n.length),n}if(Gi(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),nb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new A("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return $i(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new A("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function $i(t){if(t>rb)throw new A("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function ab(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new A("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 cb(t){return t.length>=2&&t[0]===31&&t[1]===139}function db(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 bd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function lb(t,e){let n,i;try{n=new Sd.default(t),i=n.getEntries()}catch(d){throw new A("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||bd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new A("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new A("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new A("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=ub(i),a=yd(e);for(let d of i){if(bd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=yd(e,u),x=vd(a,f);if(x.startsWith("..")||x==="..")throw new A("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await md(f,{recursive:!0});continue}await md(qy(f),{recursive:!0});let p;try{p=d.getData()}catch(m){throw new A("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${m.message}`,{cause:m})}await _d(f,p)}}function ub(t){let e;for(let n of t){let i=n.entryName;if(!i||bd(i))continue;let o=i.indexOf("/");if(o<=0)return;let a=i.slice(0,o+1);if(e===void 0)e=a;else if(e!==a)return}return e}async function fb(t,e){await hb(t);let n=Qf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new A("IPC_BAD_REQUEST",`tar extract timeout (${Br}ms)`))},Br);try{await O0(D0.from(t),n)}catch(a){throw a instanceof A?a:i?new A("IPC_BAD_REQUEST",`tar extract timeout (${Br}ms)`):new A("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function hb(t){let e=[],n=Or({onReadEntry:a=>{let d=a.path,u=a.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new A("IPC_BAD_REQUEST",`tar list timeout (${Br}ms)`))},Br);try{await O0(D0.from(t),n)}catch(a){throw i?new A("IPC_BAD_REQUEST",`tar list timeout (${Br}ms)`):new A("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}if(e.length>0)throw new A("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var xb=5e3;async function pb(t,e,n,i){return G0(t,e,n,i,{count:0})}async function G0(t,e,n,i,o){if(i<=0)return[];let a;try{a=await R0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if($y.has(u.name)||u.isSymbolicLink())continue;if(o.count>=xb){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=fe(e,u.name),x=jy(fe(n,u.name)),p=null;try{p=await gd(f)}catch{continue}if(p.isSymbolicLink())continue;o.count++;let m={name:u.name,path:q0(vd(t,f)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(m.children=await G0(t,f,x,i-1,o)),d.push(m)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function gb(t){return!t||t<=0?Wy:Math.min(t,Ky)}function mb(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function q0(t){return t.split(P0).join("/")}te();var Tn=G("agent-health-reporter"),wb=1e4,_b=3,Vi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??wb,this.livenessFailureThreshold=e.livenessFailureThreshold??_b}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()}),Tn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Tn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Tn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Tn.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=yb(d);if(!u)continue;let f={agentId:d.agentId,status:u};d.patToken&&(f.patToken=d.patToken),d.accountId&&(f.accountId=d.accountId),n.push(f)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Bt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Tn.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=o?.authFailures;if(a&&a.length>0&&(Tn.warn("heartbeat received authFailures from cloud",{count:a.length,agentIds:a.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(a)}catch(d){Tn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Tn.warn("onTickEnd hook failed",{err:String(n)})}}};function yb(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}$t();import{copyFile as BE,cp as FE,mkdir as Ho,readFile as zE,rm as UE,stat as Dd,writeFile as HE}from"node:fs/promises";import{homedir as Ah}from"node:os";import{basename as GE,join as zt}from"node:path";fn();import{existsSync as Pb}from"node:fs";import{release as Db}from"node:os";import{basename as Ob,isAbsolute as Lb}from"node:path";function Zi(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function zr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Ur(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Cn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Je();var Ro=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Y={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function j0(t){return"method"in t&&"id"in t&&t.id!==void 0}function W0(t){return"method"in t&&!("id"in t)}function Po(t){return!("method"in t)&&"id"in t}var bb={AGENT_NOT_FOUND:Y.AGENT_NOT_FOUND,AGENT_BUSY:Y.AGENT_BUSY,AGENT_DISCONNECTED:Y.AGENT_DISCONNECTED,AGENT_TIMEOUT:Y.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Y.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Y.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Y.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Y.INTERNAL_ERROR,BRIDGE_INTERNAL:Y.INTERNAL_ERROR,IPC_AUTH_FAILED:Y.INTERNAL_ERROR,IPC_BAD_REQUEST:Y.INVALID_REQUEST,METHOD_NOT_FOUND:Y.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Y.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Y.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Y.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Y.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Y.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Y.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Y.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Y.FILE_TOO_LARGE,UNSUPPORTED_MIME:Y.UNSUPPORTED_MIME,UPLOAD_FAILED:Y.UPLOAD_FAILED,UPSTREAM_NOT_READY:Y.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Y.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Y.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Y.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Y.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Y.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Y.SKILL_ZIP_TOO_LARGE};function Eb(t){if(t!=null)return t instanceof Error?{name:t.name,message:Ji(t.message)}:typeof t=="string"?Ji(t):typeof t=="object"?Sb(t):t}var vb=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Ji(t){let e=t;for(let[n,i]of vb)e=e.replace(n,i);return e}function Sb(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Ji(i):e[n]=i;return e}function Yi(t){if(t instanceof A){let e=Eb(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(n.reason=e.reason),{code:bb[t.code]??Y.INTERNAL_ERROR,message:Ji(t.message),data:n}}return{code:Y.INTERNAL_ERROR,message:Ji(t instanceof Error?t.message:String(t))}}function K0(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,a=t.data;if(i&&e){let{message:d,...u}=e;a=u}return new A(n,o,{retriable:e?.retriable??!1,cause:a})}function V0(t){return`${JSON.stringify(t)}
|
|
103
|
+
`}var $0=10*1024*1024,Do=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>$0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${$0} bytes`)}),[]}let n=this.buffer.split(`
|
|
104
|
+
`);this.buffer=n.pop()??"";let i=[];for(let o of n){let a=o.replace(/\r$/,"").trim();if(a)try{i.push(JSON.parse(a))}catch(d){this.onError?.({line:a,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 J0={"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"},gC=Object.fromEntries(Object.entries(J0).map(([t,e])=>[e,t])),Ib={"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:[]},Hr=class{seq=0;next(e,n){this.seq+=1;let i=J0[e]??Ab(e),o=Ib[i]??[],a=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>Z0(n?.[f]??"")),u=kb(d).join(":");u&&a.push(u)}else n&&Object.values(n).some(d=>d)&&a.push(Object.values(n).filter(Boolean).map(d=>Z0(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function Ab(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Z0(t){return t.replace(/[:_\s]+/g,"-")}function kb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}en();fr();Je();te();Pe();import{execFileSync as Tb,spawnSync as Cb}from"node:child_process";function Xi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Qi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),Cb("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var Id=new Set;function Y0(t){typeof t=="number"&&t>0&&Id.add(t)}function X0(t){typeof t=="number"&&Id.delete(t)}function Q0(){for(let t of Id)Qi(t,"SIGKILL")}var Gr="coze-bridge-daemon";function eh(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return Tb("pgrep",["-U",String(o),"-f",Gr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
|
|
105
|
+
`).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function th(t,e){if(t.length===0)return;let n=e?.killFn??Qi,i=e?.isAliveFn??Xi,o=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),a=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<a&&t.some(f=>i(f));u+=d)await o(Math.min(d,a-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var Rb=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]codex-acp/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function nh(t,e){if(!e)return null;for(let n of Rb)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function rh(t,e){return nh(t,e)}function ih(t,e){return nh(t,e)}function qr(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 sh(t,e,n){let o=n-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,p=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:qr(p,t.firstFrameSeen,e)}}let a=n-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return a>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?a<e.phase2GateMs?{action:"continue",rearmMs:qr(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:qr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:qr(a,!1,e)}}var oh=Xe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Nb=200,Mb=40,Bb=Xe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Fb=Xe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),zb=Xe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Ub=Xe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Hb=Xe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Gb=Xe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),ah=500;function qb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=ah?t:`${e.slice(0,ah)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function jb(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 ch(t){try{return Pb(t)}catch{return}}function Wb(t,e){return{platform:process.platform,osRelease:Db(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Lb(e.command)?ch(e.command):void 0,cwd:e.cwd,cwdExists:ch(e.cwd),envKeys:e.envKeys}}function Kb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Ob(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var mt=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Do({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Hr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new A("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=Eo(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=at(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,Y0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let a of this.decoder.push(o))this.dispatch(a)}catch(a){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(a)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let a=o.trimEnd();this.stderrRing.push(a),this.stderrRing.length>Nb&&this.stderrRing.shift(),this.log.debug("stderr",{text:a})}),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,a)=>{this.stopped=!0,X0(i.pid),(o!==0||a!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:a,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,a));for(let u of this.exitHandlers)u(o,a)}),i.on("error",o=>{let a=o,d=Wb(a,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new A("AGENT_SPAWN_FAILED",Kb(a,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(a=>n.once("exit",()=>a()));Qi(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||Qi(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:Hb,phase2GateMs:Bb,livenessWindowMs:Fb,absoluteMaxMs:zb,approvalMaxMs:Gb,suspendThresholdMs:Ub,...n};return this.call("session/prompt",e,oh,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(zr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Ur(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(Cn(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=oh,o){if(!this.child||this.stopped)return Promise.reject(new A("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=Zi(a,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let f=n.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,x)=>{let p={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let m=this.now(),v={cfg:o,startedAt:m,lastActivityAt:m,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:m,expectedIntervalMs:qr(0,!1,o),sessionId:u};p.promptTimeout=v;let _=()=>{let b={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},S=this.now(),I=sh(b,v.cfg,S),T=R=>{v.armedAt=S,v.expectedIntervalMs=R,p.timer=setTimeout(_,R)};if(I.action==="suspend"){v.suspendedMs+=I.suspendedDeltaMs,v.lastActivityAt=S,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:I.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),T(I.rearmMs);return}if(I.action==="continue"){T(I.rearmMs);return}this.pending.delete(a),I.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:I.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),x(I.awaitingApproval?new A("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new A("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new A("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(_,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(p.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),x(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,p);try{this.writeFrame(d)}catch(m){p.timer&&clearTimeout(p.timer),this.pending.delete(a),x(m)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new A("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(V0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(Po(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new A("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:qb(e.result)}),n.resolve(e.result));return}if(W0(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(j0(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let a=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!a)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(a):u&&e.activeToolCalls.delete(a)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Cn(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(Cn(e.id,Yi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=K0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=ih(this.framework,jb(e));return i?new A(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 A("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(Mb).join(`
|
|
106
|
+
`),o=rh(this.framework,i);return o?new A(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:n,stderrTail:i}}):new A("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 $b(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 Oo=class extends mt{framework="claude-code";constructor(e){let{command:n,args:i}=ui("claude-code",e.command,e.args??[]),o={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return $b(e)}};fn();import{spawn as Vb}from"node:child_process";import{closeSync as Zb,existsSync as Td,mkdirSync as Jb,mkdtempSync as Yb,openSync as Xb,readFileSync as ph,readSync as Qb,readdirSync as eE,rmSync as tE,statSync as nE}from"node:fs";import{homedir as rE,tmpdir as iE}from"node:os";import{join as jr}from"node:path";var dh=["default","acceptEdits","plan","auto","bypassPermissions"],lh=["read-only","auto","full-access"];var uh=["default","accept_edits","dont_ask"];function Ft(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return dh.includes(e);case"codex":return lh.includes(e);case"hermes":return uh.includes(e);case"openclaw":return!1}}function Lo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function fh(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function Ad(t){switch(t){case"claude-code":return dh.join("/");case"codex":return lh.join("/");case"hermes":return uh.join("/");case"openclaw":return""}}Pe();var Cd=9e4,sE=64*1024,oE=100;function aE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Cd:Math.max(1,Math.floor(e*1e3))}function cE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Cd:Math.max(1,Math.floor(e))}function dE(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n]=i);return Object.keys(e).length>0?e:void 0}function hh(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:Cd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let n=typeof e.command=="string"?e.command.trim():"";if(!n)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,o=dE(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?aE(e.timeout):cE(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function kd(t){if(Array.isArray(t))return t.flatMap(i=>kd(i));if(!t||typeof t!="object"){let i=hh(t);return i?[i]:[]}let e=t;if(e.hooks)return kd(e.hooks);let n=hh(e);return n?[n]:[]}function lE(t){let e=jr(t,"hooks.json");if(!Td(e))return[];let n=JSON.parse(ph(e,"utf8")),o=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return kd(o.Stop??o.stop)}function uE(t,e){let n=jr(t,"sessions");if(!Td(n))return;let i=[],o=a=>{let d;try{d=eE(a,{withFileTypes:!0})}catch{return}for(let u of d){let f=jr(a,u.name);if(u.isDirectory())o(f);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:f,mtimeMs:nE(f).mtimeMs})}catch{}}};o(n),i.sort((a,d)=>d.mtimeMs-a.mtimeMs);for(let a of i.slice(0,oE))if(fE(a.path,e))return a.path}function fE(t,e){let n;try{n=Xb(t,"r");let i=Buffer.alloc(sE),o=Qb(n,i,0,i.length,0),a=i.subarray(0,o).toString("utf8");return a.includes(JSON.stringify(e))||a.includes(e)}catch{return!1}finally{if(n!==void 0)try{Zb(n)}catch{}}}function hE(t){return Yn(t??Z().agentEnvFile)}function xE(t){let e=t.trim();if(e.length>=2){let n=e[0];if((n==='"'||n==="'")&&e.endsWith(n)){let i=e.slice(1,-1);return n==='"'?i.replace(/\\n/g,`
|
|
107
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function pE(t){let e={};for(let n of t.split(/\r?\n/)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.startsWith("export ")?i.slice(7).trimStart():i,a=o.indexOf("=");if(a<=0)continue;let d=o.slice(0,a).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=xE(o.slice(a+1)))}return e}function gE(t){let e=jr(t,"cozeloop.env");return Td(e)?pE(ph(e,"utf8")):{}}function xh(t){let e=t?.trim();return e||void 0}function mE(t){let e=hE(t.agentEnvFile),n=xh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=xh(t.env?.HOME??e.HOME??process.env.HOME)??rE();return jr(i,".codex")}var No=class extends mt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:a}=ui("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Yb(jr(iE(),"coze-bridge-codex-home-")):mE(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&Jb(d,{recursive:!0});let f=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:o,args:a,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...f?{env:f}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=d,this.cleanupCodexHomeDir=u}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async sessionPrompt(e){let n=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),n}setSessionMode(e){let n=Ft("codex",e.modeId)?Lo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(wE(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=lE(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let o=uE(n,e),a=JSON.stringify({hook_event_name:"Stop",session_id:e,...o?{transcript_path:o}:{},trigger:"coze-bridge"});await Promise.all(i.map(async d=>{try{await this.runHookCommand(d,a)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:n,command:d.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,n){return new Promise((i,o)=>{let a=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=a?gE(a):{},u=Eo(process.env,this.opts.agentEnvFile??Z().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}});this.opts.env?.COZELAB_ONBOARD_CLOUD==="true"&&u.COZE_API_TOKEN&&(u.COZELOOP_API_TOKEN=u.COZE_API_TOKEN);let f=Vb(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",p=setTimeout(()=>{f.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);f.stderr?.setEncoding("utf8"),f.stderr?.on("data",m=>{x+=m,x.length>4e3&&(x=x.slice(-4e3))}),f.on("error",m=>{clearTimeout(p),o(m)}),f.on("close",(m,v)=>{if(clearTimeout(p),m===0){i();return}o(new Error(`hook exited code=${m} signal=${v} stderr=${x.slice(-1e3)}`))}),f.stdin.end(`${n}
|
|
108
|
+
`)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{tE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function wE(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=fh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}te();var _E=G("hermes-downstream"),Mo=class extends mt{framework="hermes";modelId;constructor(e){let n={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(n),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(n){_E.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}};Je();var yE=3e4,Wr=class extends mt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},yE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Kt();Je();te();Pe();function Rd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}fn();var Rn=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 Bo=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 Rn,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)Kr(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 Kr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function tn(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}en();te();import{constants as gh}from"node:fs";import{access as bE,readFile as EE}from"node:fs/promises";import{delimiter as vE,dirname as SE,join as mh}from"node:path";var rt=G("framework-detector"),wh={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},IE=[".exe",".cmd",".bat",".ps1"],er=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??at,access:e.access??bE,readFile:e.readFile??EE}}async detect(e){let n=wh[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return rt.debug("framework binary not found",{framework:e,bin:n}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[a,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:a};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(wh).map(async i=>[i,await this.detect(i)])),n={};for(let[i,o]of e)o&&(n[i]=o);return n}async which(e){let n=this.env.pathEnv.split(vE).filter(Boolean),i=this.env.platform==="win32"?["",...IE]:[""];for(let o of n)for(let a of i){let d=mh(o,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?gh.F_OK:gh.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let n;try{n=await this.env.readFile(e,"utf8")}catch(d){return rt.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let o=n.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return rt.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=mh(SE(o),"hermes-acp");return await this.isExecutable(a)?(rt.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(rt.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:a}),null)}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return rt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return rt.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return rt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return rt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let a=o.find(d=>d?.isDefault===!0);return a?!a.id||!a.workspace?(rt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!a.id,hasWorkspace:!!a.workspace}),null):{id:a.id,workspace:a.workspace}:(rt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return rt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return rt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||rt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let o={reachable:i},a=n.stdout.match(/\{[\s\S]*\}/);if(a)try{let d=JSON.parse(a[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){rt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(kE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let o="",a=!1,d,u=f=>{a||(a=!0,d&&clearTimeout(d),i(f))};try{let f=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{o+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},AE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function kE(t){return t.replace(AE,"")}import{homedir as yh}from"node:os";import{join as zo}from"node:path";Kt();en();fr();Je();te();async function bh(){let t=zo(yh(),".openclaw/openclaw.json");return hn(t)}async function Eh(){return(await bh())?.gateway?.auth?.token??""}var tr=G("openclaw.config"),TE=[0,5e3,5e3],CE=Xe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),_h="models.providers.",Fo="agents.defaults.models",RE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function $r(t,e){let n=Array.isArray(t)?[...t]:[],i=new Set(n);for(let o of e)i.has(o)||(i.add(o),n.push(o));return n}var Uo=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Rn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??TE,this.cliTimeoutMs=e.cliTimeoutMs??CE,this.openclawDir=e.openclawDir??zo(yh(),".openclaw")}async withRetry(e,n){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let a=this.retryDelaysMs[o]??0;a>0&&await new Promise(d=>setTimeout(d,a));try{return await n()}catch(d){i=d,tr.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new A("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=at(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=x=>{d||(d=!0,clearTimeout(f),x())};o.stderr?.on("data",x=>{a+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${a.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let o=String(i);if(n.some(a=>o.includes(a)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",n],["Config path not found","Nothing was changed"])))}catch(i){tr.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",`${_h}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${_h}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Fo}[${e}]`,()=>this.runCli(["config","set",Fo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Fo}[${e}]`,`${Fo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await bh())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,a=[];for(let d of Object.keys(i))d.startsWith(o)&&a.push(d.slice(o.length));return a}ensureAgent(e,n,i){let o=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}ensureAcpDeviceScopes(){return this.queue.enqueue(()=>this.ensureAcpDeviceScopesUnlocked())}async ensureAcpDeviceScopesUnlocked(){try{let e=zo(this.openclawDir,"identity","device.json"),i=(await hn(e))?.deviceId?.trim();if(!i)return tr.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=zo(this.openclawDir,"devices","paired.json"),a=await hn(o),d=a?.[i];if(!a||!d)return tr.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,f=$r($r(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(b=>b.startsWith("operator.")),x=$r([...RE],f),p=$r(d.scopes,x),m=$r(d.approvedScopes,x),v=u?$r(u.scopes,x):void 0;return p.length!==(d.scopes?.length??0)||m.length!==(d.approvedScopes?.length??0)||u!==void 0&&v?.length!==(u.scopes?.length??0)?(d.scopes=p,d.approvedScopes=m,u&&v&&(u.scopes=v),await xn(o,a,{mode:384}),tr.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(tr.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return tr.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};import{readFile as PE,writeFile as DE}from"node:fs/promises";import{join as OE}from"node:path";var LE=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
|
|
109
|
+
`),NE=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
|
|
110
110
|
`);function ME(t){return t.length===0?t:`${(t.endsWith(`
|
|
111
111
|
`)?t.slice(0,-1):t).split(`
|
|
112
112
|
`).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
|
|
113
113
|
`)}
|
|
114
|
-
`}async function vh(t){let e=OE(t,"HEARTBEAT.md"),n=await
|
|
115
|
-
`);await HE(d,h,{mode:384})}else await BE(a,d);ne.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ne.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var Rd="acceptEdits",Ah="full-access",Th="read-only";function KE(t){return{INITIAL_AGENT_MODE:Do(t)}}var $E=(t,e,n,i,o,a,d,u,h,x,g,m)=>{switch(t){case"claude-code":{let S={...o?{...m0(o),...y0(o,d,u,m)}:{},...h??{},IS_SANDBOX:"1"};return new Ro({cwd:n,env:S,agentId:i})}case"codex":{let S=Ah;x!==void 0&&(Mt("codex",x)?S=x:ne.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _={...o?{..._0(o),...w0(o,d,u,m)}:{},...KE(S),...o?{NO_BROWSER:"1"}:{},...h??{},...o?{COZELAB_ONBOARD_CLOUD:"true"}:{}},v=!!o;return new Oo({cwd:n,agentId:i,...Object.keys(_).length>0?{env:_}:{},...v?{authMethodId:"api-key",isolateCodexHome:!0,...g?{codexHomeDir:g}:{}}:{}})}case"openclaw":return new jr({command:e,cwd:n,agentId:i,...a?{sessionName:Td(a)}:{}});case"hermes":return new No({command:e,cwd:n,agentId:i,...h&&Object.keys(h).length>0?{env:{...h}}:{},...o?.model?{modelId:o.model}:{}})}};function Cd(t){return t==="claude-code"||t==="codex"}var VE={path:"",version:"cloud-deployed"},Sh="openclaw_gateway_unavailable",JE="openclaw_default_agent_missing";function Ih(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 ZE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},YE=6e4,Uo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Map;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??$E,this.createTimeoutMs=e.createTimeoutMs??YE,this.detectorFactory=e.detectorFactory??(()=>new Qn),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Fo({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??Qt(kh(),".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 A("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=>{ne.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=Qt(e,".env");if(await Pd(n).then(a=>a.isFile()).catch(()=>!1)){ne.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=Gi({...process.env,...Zn(this.paths.agentEnvFile)});await ut(n,o,{mode:384}),ne.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ne.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){if(!e.agentId)throw new A("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new A("IPC_BAD_REQUEST","framework required");let i=await Ee(e.agentId,this.paths).catch(()=>null),o=wo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new A("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")ne.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(T=>ne.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&a.deployType!=="cloud")ne.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(T=>ne.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){ne.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let T=await Ee(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await He(T,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){ne.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let T=await Ee(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await He(T,this.paths))}return ne.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework]){let P=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new A("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${P}`)}let u=De(e.agentId,this.paths),h=o?"cloud":"local",x=e.framework==="openclaw"&&h==="local",g;x&&!n?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let m=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??m??u.workspace,_=new AbortController,v=setTimeout(()=>_.abort(new A("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,k=!1;try{o&&Cd(e.framework)&&await pr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new A("AGENT_TIMEOUT","_agent/create aborted")};await zo(u.root,{recursive:!0}),await zo(S,{recursive:!0}),await zo(u.logs,{recursive:!0}),T(),x||await gr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await Ja(S,"cloud"):await Ja(S,"local",Rd)),T();let P=i,E=p0({model:e.model??P?.model}),R=t0(e._meta)??P?.accountId,D=e.patToken??P?.patToken,M=h==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new Lo({agentId:e.agentId,framework:e.framework,workspace:S,model:E.model??It,deployType:h,...R?{accountId:R}:{},...D?{patToken:D}:{},...M?{modelInfo:M}:{}}),I.status="ok",P?.sessions){let K=e.framework==="hermes"||h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,re]of Object.entries(P.sessions)){let ae={acpSessionId:re.acpSessionId,modelToken:re.modelToken,tokenGeneratedAt:re.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};K?re.permissionMode===void 0?(ae.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",ne.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:ae.permissionMode})):Mt(e.framework,re.permissionMode)?ae.permissionMode=re.permissionMode:ne.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:re.permissionMode}):re.permissionMode!==void 0&&ne.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:h}),re.cozeGroupId&&(ae.cozeGroupId=re.cozeGroupId),re.tokenGroupId&&(ae.tokenGroupId=re.tokenGroupId),re.requestScene&&(ae.requestScene=re.requestScene),I.sessions.set(X,ae)}let se=Object.keys(P.sessions).length;se>0&&ne.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:se})}this.registry.register(I),k=!0;let N={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:E.model};if(h==="cloud"&&(N.deployType="cloud"),R&&(N.accountId=R),D&&(N.patToken=D),M&&(N.modelInfo=M),P?.skills&&(N.skills=P.skills),P?.agentName&&(N.agentName=P.agentName),P?.description&&(N.description=P.description),N.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&h==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):ne.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await vh(S)&&ne.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:S})}catch(K){ne.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:S,err:String(K)})}}let J=e.initialSkills??[];if(J.length>0){let K=[...N.skills??[]],se=new Map(K.map((ae,C)=>[ae.skillId,C])),X=await Promise.allSettled(J.map(ae=>ko({agentId:e.agentId,workspace:S,framework:e.framework,skill:ae,paths:this.paths}))),re=0;for(let[ae,C]of X.entries()){let F=J[ae];F&&(C.status==="fulfilled"?(Ao(K,se,C.value),re++):ne.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:F.skillId,skillName:F.skillName,err:String(C.reason)}))}re>0&&(N.skills=K,ne.info("initialSkills installed",{agentId:e.agentId,installed:re,requested:J.length}))}return await He(N,this.paths),ne.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(T){throw ne.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),k&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),ne.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:n?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await UE(u.root,{recursive:!0,force:!0}).catch(P=>ne.warn("rm agent dir failed (ignored)",{err:String(P)})),T instanceof A?T:new A("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,n,i,o,a,d){let h=this.config.frameworksCache?.[e.framework];if(!h)if(e.deployType==="cloud"&&Cd(e.framework))h=VE;else throw e.framework==="hermes"?new A("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new A("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Cd(e.framework)&&!Ss(e.framework)&&(ne.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await pr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,g;if(e.framework==="openclaw")g=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:a,requestScene:d,command:h.path});else if(e.framework==="hermes"){let m={...this.buildBinShimPathEnv()};x&&(await k0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:o,mockScenario:a}),m.HERMES_HOME=Xn(e.agentId,this.paths)),g=this.factory(e.framework,h.path,e.workspace,e.agentId,x,i,o,a,m)}else{let m=e.sessions.get(i),S=Xt(e)?m?.permissionMode??Ah:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await WE(e.agentId,this.paths),g=this.factory(e.framework,h.path,e.workspace,e.agentId,x,i,o,a,this.buildBinShimPathEnv(),S,e.framework==="codex"&&e.deployType==="cloud"?Qt(De(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await g.start(),await g.initialize(ZE),g}catch(m){let S=g instanceof pt?g.getStderrTail():[];throw S.length>0&&ne.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof A?m.code:"unknown",recentStderr:S}),await g.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,h.path,m)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let o=await this.detectorFactory().probeOpenclawGateway(n);if(!o.reachable)return new A("AGENT_ENV_NOT_READY",Ih(o),{cause:{reason:Sh}})}catch(o){ne.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof A?i:new A("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};ne.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 ne.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 A("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:JE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new A("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new A("AGENT_ENV_NOT_READY",Ih(n),{cause:{reason:Sh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,requestScene:u,command:h}=e,x=Td(o);if(n.deployType==="local"){let S=await this.ensureOpenclawDefaultAgent();return new jr({command:h,cwd:S.workspace,agentId:S.id,sessionName:x})}let g=await Eh();try{let S=this.getOpenclawConfig();await S.ensureAcpDeviceScopes()&&await S.restartGateway()}catch(S){ne.warn("acp device scope ensure failed (ignored)",{err:String(S)})}let m;if(i?.modelToken){let S=dd(o),_=ld(i),v=`${S}/${_}`,I=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(v)!==I){let k=this.getOpenclawConfig(),T=await k.getAllowlistModelsForProvider(S),P=b0(i,a,d,T,u);P&&(await k.ensureProvider(S,P),await k.addModelToAllowlist(v),this.ensuredProviders.set(v,I))}m=v}return new jr({command:h,cwd:n.workspace,agentId:n.agentId,sessionName:x,...g?{gatewayToken:g}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=n??e.model;for(let a of e.sessions.keys()){let d=dd(a),u=`${d}/${o}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,ne.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,ne.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as Oh}from"node:crypto";import{promises as iv}from"node:fs";import{basename as Nh}from"node:path";Ve();te();import{promises as XE}from"node:fs";import{basename as QE}from"node:path";var Ch=U("file-upload"),ev="/api/coze_claw/file/agent_upload",tv=6e4;async function Ph(t,e={}){let i=`${Nr(Lr(e.handshakeBase))}${ev}`,o=e.timeoutMs??tv,a=await XE.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([a],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),o);Ch.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let g=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),m=g.headers.get("x-tt-logid")??"";if(!g.ok){let v=await g.text().catch(()=>"");throw new A("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${m}: ${v.slice(0,200)}`)}let S=await g.json();if(S.code!==void 0&&S.code!==0)throw new A("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${m}`);let _=S.data?.file?.file_url;if(!_)throw new A("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${m}: ${JSON.stringify(S).slice(0,200)}`);return Ch.info("file upload ok",{uri:_,logid:m}),{uri:_}}catch(g){throw g instanceof A?g:g.name==="AbortError"?new A("UPLOAD_FAILED",`upload timeout (${o}ms) for ${QE(t.path)}`):new A("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}Ve();te();import{extname as nv}from"node:path";var rv={".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 Rh(t){let e=nv(t).toLowerCase();return rv[e]??"application/octet-stream"}Ae();var Ho=U("agent-send"),Dh=50*1024*1024;function Lh(t,e,n){let i=t.get(e);if(!i)throw new A("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new A("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(n);if(!o)throw new A("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function Mh(t,e,n,i,o,a){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,n,i,o);return}catch(x){u=x,h<2&&(Ho.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(g=>setTimeout(g,5e3)))}throw new A("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function Bh(t,e){let{session:n,runtime:i}=Lh(e.core,t.agentId,t.sessionId);if(!await ui(t.path,n.workspace))throw new A("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await iv.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new A("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>Dh)throw new A("FILE_TOO_LARGE",`${o.size} bytes > limit ${Dh}`);let a=await Rh(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new A("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??Nh(t.path),u;try{u=await Ph({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:a,name:d,sizeBytes:o.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Ho.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:a,code:x instanceof A?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:Oh(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:a,name:d,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Mh(e,n,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Ho.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:a,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:a,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Fh(t,e){let{session:n,runtime:i}=Lh(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new A("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??Nh(t.path),a={sessionUpdate:"group_file",messageId:Oh(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Mh(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),Ho.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 zh(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(n.length,i.length);for(let a=0;a<o;a++){let d=n[a]??0,u=i[a]??0;if(d<u)return!0;if(d>u)return!1}return!1}Yt();te();un();var Bt=U("coze-cli-installer"),Uh="@coze/cli@latest",sv="coze",Hh="0.1.8",ov=5e3,av=5e3,cv=9e4,Gh=1e4,Qi=null,Go=!1;async function Od(t,e={}){if(Go)return;if(Qi)return Qi;let n=e.exec??a0;return Qi=(async()=>{try{let i=await dv(sv,n),o=!1;if(i){let d=await lv(n);if(d===void 0)Bt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(zh(d,Hh))Bt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:Hh}),o=!0;else{Bt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Go=!0;return}}let a=o?"upgrade-only":"full";Bt.info("coze-cli install start",{package:Uh,mode:a});try{await n("npm",["i","-g","--prefer-online",Uh],{timeout:cv,maxBuffer:10*1024*1024}),Bt.info("coze-cli install ok")}catch(d){Bt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Go=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:Gh}),Bt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Bt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:Gh}),Bt.info("coze auth login ok")}catch(d){Bt.warn("coze auth login failed",{err:String(d)});return}Go=!0}finally{Qi=null}})(),Qi}async function dv(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:ov});return $a(i)}catch{return}}async function lv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:av});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}jt();qt();Ae();var uv=10*6e4;function qh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?uv:e}function qo(t){return fn(t??V().configFile)}function es(t,e){return hn(e??V().configFile,t)}import{randomBytes as Rv}from"node:crypto";ur();Ve();te();import{createReadStream as fv}from"node:fs";import{mkdir as hv,readFile as xv,realpath as pv,stat as gv,writeFile as mv}from"node:fs/promises";import{basename as wv,dirname as Nd,isAbsolute as _v,join as yv,relative as bv,resolve as jh,sep as Ev}from"node:path";import{createInterface as vv}from"node:readline";var Kh=U("fs-rpc"),ts=Ze("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function $h(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>ts)throw new A("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${ts} bytes`);let i=await Jh(t.path,e);return await hv(Nd(i),{recursive:!0}),await mv(i,t.content,"utf8"),Kh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Vh(t,e){let n=await Jh(t.path,e),i=await gv(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>ts&&!o)throw new A("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${ts} bytes`);let a;if(o&&i.size>ts)a=await Sv(n,t.line??1,t.limit);else{let d=await xv(n,"utf8");if(o){let u=d.split(`
|
|
116
|
-
`),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;a=u.slice(h,x).join(`
|
|
117
|
-
`)
|
|
118
|
-
`)}async function Jh(t,e){if(typeof t!="string"||t.length===0)throw new A("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([Wh(jh(e)),Wh(jh(t))]),o=bv(n,i);if(Iv(o,Ev,_v(o)))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Iv(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Wh(t){let e=[],n=t;for(;n!==Nd(n);)try{let i=await pv(n);return e.length?yv(i,...e.reverse()):i}catch{e.push(wv(n)),n=Nd(n)}return t}te();var Zh=U("prompt-multimodal"),Yh=10*1024*1024,kv=15e3,Av=6;async function Xh(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let a=n++,d=t[a];d!==void 0&&(e[a]=await Tv(d))}}let o=Array.from({length:Math.min(Av,t.length)},()=>i());return await Promise.all(o),e}function Qh(t){return t.some(e=>e.type==="image")}async function Tv(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Hi(e.uri))return t;try{let{buf:n,contentType:i}=await Pv(e.uri),o=e.mimeType||Cv(i)||"application/octet-stream";return Zh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:o}),{type:"image",data:n.toString("base64"),mimeType:o}}catch(n){return Zh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Cv(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function Pv(t){let e=new AbortController,n=setTimeout(()=>e.abort(),kv);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>Yh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Yh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}jt();Ve();te();var W=U("core"),Dv=3e4,Ov=/^(boe|ppe)_[A-Za-z0-9_-]+$/,Nv="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",Lv="\u5BA1\u6279\u5DF2\u8D85\u65F6",Mv=3e4,jo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Ur;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=qh(e.bridgeConfig)}registerExtension(e,n){this.extensions[e]=n}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}getRequestSceneForSession(e){return this.requestSceneBySession.get(e)}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(n=>n.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of n)await this.agents.get(i)?.killAllRuntimes("reload");return n}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,i){let o=i.downstream;o&&(o.onUpdate(a=>{i.loadingSession||this.forwardUpdate(e,a)}),o.onAgentRequest(a=>{this.handleAgentRequest(e,o,a)}),o.onExit((a,d)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),Wr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[o,a]of this.pendingUpstream)a.downstream===e&&i.push(o);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let o of i){let a=this.pendingUpstream.get(o);if(a){this.pendingUpstream.delete(o),this.upstream.send(Tn(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>W.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:Y.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:Y.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new A("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Co(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&&Ov.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,a=n0(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);a&&u!==a?(this.requestSceneBySession.set(d,a),W.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),W.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){n!==null?await this.sendError(n,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let h=await u(e,this);n!==null&&await this.upstream.send(zr(n,h));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(zr(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(zr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(u){W.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Tn(n,Zi(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new A("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new A("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new A("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new A("AGENT_NOT_FOUND",`agent not found: ${i}`);let a=typeof n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!a)return this.dispatchSessionCall(o,e.method,n);if(e.method==="session/prompt"){let h=o.sessions.get(a);if(h?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,g=_o(n._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,h,a,Nv,x,g)}}let d=Date.now(),u=!1;try{let h=await o.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return u=!0,h}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=i0(i);switch(n){case"session/new":{let a=Bv();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=o;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:a.sessionId}),{}}case"session/prompt":{let a=o,d=a.sessionId;if(!d)throw new A("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Xt(e)?r0(i._meta):void 0;if(u!==void 0&&!Mt(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Sd(e.framework)}`);let h=_o(i._meta),x=this.requestSceneBySession.get(d),g=await this.ensureRuntime(e,d,h,x);if(u!==void 0&&g.permissionMode===void 0&&(g.permissionMode=u,await this.persistSessionMapping(e)),g.replySeq=0,await this.ensureDownstream(e,d,g),!g.downstream||!g.acpSessionId)throw new A("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&g.permissionMode!==void 0&&g.permissionMode!==u){let _=g.permissionMode;g.permissionMode=u,await this.persistSessionMapping(e);try{await g.downstream.setSessionMode({sessionId:g.acpSessionId,modeId:u})}catch(v){throw g.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),v}}let m=i._meta?.cozeTriggerMsgId;if(m?e.activeTriggers.set(g.acpSessionId,m):e.activeTriggers.delete(g.acpSessionId),h?e.activeGroupIds.set(g.acpSessionId,h):e.activeGroupIds.delete(g.acpSessionId),h&&g.cozeGroupId!==h&&(g.cozeGroupId=h,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Qh(a.prompt))throw new A("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let S=await Xh(a.prompt);try{let _=await g.downstream.sessionPrompt({...a,sessionId:g.acpSessionId,prompt:S});return g.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof A&&_.code==="AGENT_APPROVAL_TIMEOUT"){let v=g.pendingPermission;v&&(v.downstream.respondAgentRequest(v.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(v.upstreamId),g.pendingPermission=void 0);let I=g.acpSessionId,k=I?e.activeTriggers.get(I):void 0,T=I?e.activeGroupIds.get(I):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,g,d,Lv,k,T)}throw _}finally{if(e.activeTriggers.delete(g.acpSessionId),e.activeGroupIds.delete(g.acpSessionId),g.pendingPermission=void 0,g.reloadAfterTurn){g.reloadAfterTurn=!1;let _=g.downstream;_&&(g.downstream=void 0,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:g.acpSessionId}),_.stop("reload-after-turn").catch(v=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(v)})))}else g.downstream?.isAlive()&&this.armIdleTimer(e,d,g)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new A("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 A("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 a=o,d=a.sessionId,u=a.modeId,h=_o(i._meta);if(!d)throw new A("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Xt(e))throw e.framework==="openclaw"?new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new A("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Mt(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Sd(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let g=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(m){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),m}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 A("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let d of o){let u=d.runtime.downstream,h=d.runtime.acpSessionId;u?.isAlive()&&h&&a.push({downstream:u,acpSessionId:h,oldMode:d.oldMode,runtime:d.runtime})}for(let d of a)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let h of o)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n,i,o){let a=e.sessions.get(n);if(a){let h=a.cozeGroupId!==i,x=e.deployType==="cloud"&&a.tokenGroupId!==i,g=a.requestScene!==o;if(x&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),x||g){Wr(a);let m=a.downstream;a.downstream=void 0,m&&await m.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=o,(h||x||g)&&await this.persistSessionMapping(e),a}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...o?{requestScene:o}:{}};return Xt(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?v0:S0:u.permissionMode=e.framework==="claude-code"?Rd:Th),e.sessions.set(n,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,n,i){let o={sessionId:n,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let a=await this.sendRequest(xt.GEN_MODEL_TOKEN,o,Mv);if(!a?.modelToken)throw new A("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return a.modelToken}catch(a){throw a instanceof A&&a.code==="MODEL_TOKEN_GEN_FAILED"?a:new A("MODEL_TOKEN_GEN_FAILED",a instanceof Error?a.message:String(a),{cause:a})}}async ensureDownstream(e,n,i){if(Wr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new A("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<a)throw new A("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((a-(Date.now()-u))/1e3)}s`);let h;try{let x=this.requestSceneBySession.get(n);x&&W.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),h=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=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 g=await h.sessionNew({cwd:e.workspace});i.acpSessionId=g.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw 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),Xt(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(Wr(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(a=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(a)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,o){let a={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(a.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(a.cozeGroupId=u)}await this.upstream.send(Fr("session/update",{sessionId:i,update:o,_meta:a}))}async synthesizePromptReply(e,n,i,o,a,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return a&&(u.cozeTriggerMsgId=a),d&&(u.cozeGroupId=d),await this.upstream.send(Fr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(h=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,o=this.reverseSessionId(e,i);if(!o){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(o);if(!a){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(Uv(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"&&Xt(e)){let g=d.currentModeId;Mt(e.framework,g)&&a.permissionMode!==g?(a.permissionMode=g,this.persistSessionMapping(e).catch(m=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(m)}))):typeof g=="string"&&!Mt(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:++a.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Fr("session/update",{...n,sessionId:o,_meta:u})).catch(g=>W.warn("forward update failed",{agentId:e.agentId,err:String(g)}))}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:Y.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let a=i.params??{},d=await $h(a,o);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await Vh(a,o);n.respondAgentRequest(i.id,d)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,Zi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let o=this.upstreamIds.next("session/request_permission"),a=i.params??{},u=a.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let g=u?e.activeGroupIds.get(u):void 0;g&&(x.cozeGroupId=g);let m=u?this.reverseSessionId(e,u):void 0,S=m?e.sessions.get(m):void 0;S&&(S.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...a,...m?{sessionId:m}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:m}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:m,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(Vi(o,"session/request_permission",_)).catch(v=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),n.respondAgentRequestError(i.id,{code:Y.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 o=n.value;this.clearPendingPermissionFor(o),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&Fv(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 To(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let o=e.get(n);if(o)return{value:o,key:n};if(typeof n=="number"){let a=String(n),d=e.get(a);if(d)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=Dv){let o=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(Vi(o,e,n)).catch(h=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(h)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,o]of e.sessions){let a={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(a.acpSessionId=o.acpSessionId),o.permissionMode&&Xt(e)&&(a.permissionMode=o.permissionMode),o.cozeGroupId&&(a.cozeGroupId=o.cozeGroupId),o.tokenGroupId&&(a.tokenGroupId=o.tokenGroupId),o.requestScene&&(a.requestScene=o.requestScene),n.set(i,a)}await fi(e.agentId,n,this.paths)}catch(n){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Tn(e,{code:n,message:i,data:{bridgeVersion:Lt}}))}};function Bv(){return Rv(16).toString("hex")}function Fv(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 a=i.outcome;(typeof a!="string"||a!=="selected"&&a!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var zv=["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."],ex="Warning: ";function Uv(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let o=i.text.startsWith(ex)?i.text.slice(ex.length):i.text;return zv.some(a=>o.startsWith(a))}qt();te();Ae();import{randomBytes as Hv}from"node:crypto";import{createServer as Gv}from"node:http";var qv=1e6,tx=U("ipc"),Wo=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??V()}async start(){this.token=Hv(32).toString("hex");let e=Gv((i,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),tx.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(o=>o?i(o):n())}),this.server=null)}async persistAuthFiles(){await ut(this.paths.portFile,String(this.port)),await ut(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){ns(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){ns(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await jv(e)}catch(u){ns(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);ns(n,200,u??{ok:!0})}catch(u){tx.error("IPC handler failed",{key:o,err:String(u)}),ns(n,500,{error:u instanceof Error?u.message:String(u)})}}};function ns(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function jv(t){let e=[],n=0;for await(let o of t){let a=o;if(n+=a.length,n>qv)throw new Error("body too large");e.push(a)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var l1=Gt(Yx(),1),u1=Gt(ea(),1),f1=Gt(Jr(),1),h1=Gt(Wd(),1),x1=Gt(Vd(),1),p1=Gt(el(),1),op=Gt(ia(),1),g1=Gt(sp(),1);var ap=op.default;Ve();te();var{FWS:D1}=wp(),Ne=U("upstream.frontier"),yp="application/json",bp="none",O1=15e3;function N1(t){class e extends ap{constructor(i){super(i,d0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Ne.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(Wl("debug"))try{let a;typeof i=="string"?a=Buffer.from(i,"utf8"):i instanceof Buffer?a=i:i instanceof ArrayBuffer?a=new Uint8Array(i):ArrayBuffer.isView(i)?a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):a=new Uint8Array(0);let d=Buffer.from(a.slice(0,128)).toString("hex");Ne.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Ne.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...o)}}return e}var us=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){Ne.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:l0,...kn(this.opts.ppeOverride)},n=N1(e),i=f0(this.opts.urlOverride),o={url:i,ws:n,fpID:c0,aID:bo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:yp,force:!0},payloadEncoding:{encoding:bp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new D1(o),d=!1,u=null,h,x,g=new Promise((_,v)=>{h=_,x=v}),m=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?x(_):h())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Ne.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&m();for(let v of this.connectHandlers)Promise.resolve(v({initial:_})).catch(I=>Ne.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=_=>{this.opened=!1,Ne.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},a.onerror=_=>{Ne.warn("frontier error",{code:_.code,msg:_.message}),m(new A("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},a.onmessage=_=>this.handleMessage(_),this.fws=a;let S=this.opts.openTimeoutMs??O1;u=setTimeout(()=>{m(new A("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await a.connect();try{await g}catch(_){try{a.close(1e3,"open failed")}catch(v){Ne.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Ne.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Ne.warn("frontier send refused: upstream not started",{method:i}),new A("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Ne.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 A("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),a=e;Ep(a)||Ne.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:yp,payloadEncoding:bp})}catch(u){throw Ne.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(u)}),new A("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=n(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Ne.debug("drop non-adapter frontier frame",{service:n});return}let i=B1(e);if(!i){Ne.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Ne.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Ne.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=o;Ep(a)||Ne.info("frontier frame in",{logid:M1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:L1(i)}),Promise.resolve(this.handler(o)).catch(d=>Ne.warn("frontier frame handler threw",{err:String(d)}))}};function Ep(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var vp=2e3;function L1(t){return t.length<=vp?t:`${t.slice(0,vp)}...<truncated, total ${t.length} chars>`}function M1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function B1(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}Ve();te();var il=U("skill-publish"),F1="/api/marketplace/product/skill/publish_with_assets",z1=15e4;async function Sp(t,e={}){let i=`${Nr(Lr(e.handshakeBase))}${F1}`,o=e.timeoutMs??z1,a=new FormData;a.append("skill_id",t.skillId??""),a.append("skill_name",t.skillName),a.append("skill_description",t.description??""),a.append("agent_id",t.agentId),a.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",...kn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),o);il.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:a,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new A("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${_.slice(0,200)}`)}let m=await x.json();if(il.info("skill publish response",{logid:g,httpStatus:x.status,code:m.code,msg:m.msg,dataSkillId:m.data?.skill_id??"",dataVersion:m.data?.version??""}),m.code!==void 0&&m.code!==0)throw new A("UPLOAD_FAILED",`skill publish code=${m.code} msg=${m.msg??"-"} logid=${g}`);let S={};return m.data?.skill_id!==void 0&&m.data.skill_id!==""&&(S.skillId=String(m.data.skill_id)),m.data?.version&&(S.version=m.data.version),il.info("skill publish ok",{logid:g,skillId:S.skillId??"",version:S.version??""}),S}catch(x){throw x instanceof A?x:x.name==="AbortError"?new A("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new A("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}te();var sl=U("upstream.switchable"),ha=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;sl.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw sl.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>sl.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};te();var ol=U("upstream"),ti=class{handler=null;async start(){ol.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){ol.info("NoopUpstream stopped",{reason:e})}async send(e){ol.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Ve();te();qt();te();Ae();import{promises as U1}from"node:fs";var Ip=U("pat-token-store");async function xa(t=V()){try{let n=(await U1.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Ip.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"&&Ip.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function fs(t,e=V()){if(!t)throw new Error("writePatToken: empty patToken");await ut(e.patTokenFile,t,{mode:384})}Ae();Ae();import{promises as pa}from"node:fs";import{join as H1}from"node:path";function G1(t,e){return`#!/bin/sh
|
|
114
|
+
`}async function vh(t){let e=OE(t,"HEARTBEAT.md"),n=await PE(e,"utf8");return ME(n)!==LE?!1:(await DE(e,NE),!0)}var ne=G("agent-manager"),qE=["hooks.json","cozeloop.env"],jE=["hooks"];async function WE(t,e){let n=zt(Re(t,e).root,"codex-home"),i=zt(Ah(),".codex");if(n!==i){await Ho(n,{recursive:!0});for(let o of jE){let a=zt(i,o),d=zt(n,o);try{await Dd(d);continue}catch{}try{await FE(a,d,{recursive:!0,errorOnExist:!0,filter:u=>{let f=GE(u);return!f.endsWith(".log")&&!f.includes(".bak")}}),ne.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ne.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}for(let o of qE){let a=zt(i,o),d=zt(n,o);try{await Dd(d);continue}catch{}try{if(o==="cozeloop.env"){let f=(await zE(a,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
|
|
115
|
+
`);await HE(d,f,{mode:384})}else await BE(a,d);ne.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ne.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var Od="acceptEdits",kh="full-access",Th="read-only";function KE(t){return{INITIAL_AGENT_MODE:Lo(t)}}var $E=(t,e,n,i,o,a,d,u,f,x,p,m)=>{switch(t){case"claude-code":{let v={...o?{...m0(o),...y0(o,d,u,m)}:{},...f??{},IS_SANDBOX:"1"};return new Oo({cwd:n,env:v,agentId:i})}case"codex":{let v=kh;x!==void 0&&(Ft("codex",x)?v=x:ne.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _={...o?{..._0(o),...w0(o,d,u,m)}:{},...KE(v),...o?{NO_BROWSER:"1"}:{},...f??{},...o?{COZELAB_ONBOARD_CLOUD:"true"}:{}},b=!!o;return new No({cwd:n,agentId:i,...Object.keys(_).length>0?{env:_}:{},...b?{authMethodId:"api-key",isolateCodexHome:!0,...p?{codexHomeDir:p}:{}}:{}})}case"openclaw":return new Wr({command:e,cwd:n,agentId:i,...a?{sessionName:Rd(a)}:{}});case"hermes":return new Mo({command:e,cwd:n,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{},...o?.model?{modelId:o.model}:{}})}};function Pd(t){return t==="claude-code"||t==="codex"}var VE={path:"",version:"cloud-deployed"},Sh="openclaw_gateway_unavailable",ZE="openclaw_default_agent_missing";function Ih(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 JE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},YE=6e4,Go=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Map;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??$E,this.createTimeoutMs=e.createTimeoutMs??YE,this.detectorFactory=e.detectorFactory??(()=>new er),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Uo({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??zt(Ah(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}async buildAgentToolEnv(e,n){let i=this.buildBinShimPathEnv();if(e.deployType!=="cloud")return i;let o=zt(Re(e.agentId,this.paths).root,"coze-cli-config.json");return await ct(o,`${JSON.stringify({xTTEnv:n??""},null,2)}
|
|
116
|
+
`,{mode:384}),i.COZE_CONFIG_FILE=o,i}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new A("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=>{ne.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=zt(e,".env");if(await Dd(n).then(a=>a.isFile()).catch(()=>!1)){ne.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=qi({...process.env,...Yn(this.paths.agentEnvFile)});await ct(n,o,{mode:384}),ne.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ne.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){if(!e.agentId)throw new A("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new A("IPC_BAD_REQUEST","framework required");let i=await Ie(e.agentId,this.paths).catch(()=>null),o=yo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new A("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")ne.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(T=>ne.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&a.deployType!=="cloud")ne.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(T=>ne.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){ne.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let T=await Ie(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await qe(T,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){ne.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let T=await Ie(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await qe(T,this.paths))}return ne.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework]){let R=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new A("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${R}`)}let u=Re(e.agentId,this.paths),f=o?"cloud":"local",x=e.framework==="openclaw"&&f==="local",p;x&&!n?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let m=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??m??u.workspace,_=new AbortController,b=setTimeout(()=>_.abort(new A("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),S,I=!1;try{o&&Pd(e.framework)&&await gr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new A("AGENT_TIMEOUT","_agent/create aborted")};await Ho(u.root,{recursive:!0}),await Ho(v,{recursive:!0}),await Ho(u.logs,{recursive:!0}),T(),x||await mr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Ya(v,"cloud"):await Ya(v,"local",Od)),T();let R=i,E=p0({model:e.model??R?.model}),P=t0(e._meta)??R?.accountId,D=e.patToken??R?.patToken,M=f==="cloud"?e.modelInfo??R?.modelInfo:void 0;if(S=new Bo({agentId:e.agentId,framework:e.framework,workspace:v,model:E.model??kt,deployType:f,...P?{accountId:P}:{},...D?{patToken:D}:{},...M?{modelInfo:M}:{}}),S.status="ok",R?.sessions){let V=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,re]of Object.entries(R.sessions)){let ae={acpSessionId:re.acpSessionId,modelToken:re.modelToken,tokenGeneratedAt:re.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?re.permissionMode===void 0?(ae.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",ne.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:ae.permissionMode})):Ft(e.framework,re.permissionMode)?ae.permissionMode=re.permissionMode:ne.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:re.permissionMode}):re.permissionMode!==void 0&&ne.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:f}),re.cozeGroupId&&(ae.cozeGroupId=re.cozeGroupId),re.tokenGroupId&&(ae.tokenGroupId=re.tokenGroupId),re.requestScene&&(ae.requestScene=re.requestScene),S.sessions.set(X,ae)}let se=Object.keys(R.sessions).length;se>0&&ne.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:se})}this.registry.register(S),I=!0;let N={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:R?.createdAt??Date.now(),sessions:R?.sessions??{},model:E.model};if(f==="cloud"&&(N.deployType="cloud"),P&&(N.accountId=P),D&&(N.patToken=D),M&&(N.modelInfo=M),R?.skills&&(N.skills=R.skills),R?.agentName&&(N.agentName=R.agentName),R?.description&&(N.description=R.description),N.skillsRefreshedForVersion=R?.skillsRefreshedForVersion??Bt,e.framework==="openclaw"&&f==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):ne.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await vh(v)&&ne.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:v})}catch(V){ne.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:v,err:String(V)})}}let J=e.initialSkills??[];if(J.length>0){let V=[...N.skills??[]],se=new Map(V.map((ae,C)=>[ae.skillId,C])),X=await Promise.allSettled(J.map(ae=>To({agentId:e.agentId,workspace:v,framework:e.framework,skill:ae,paths:this.paths}))),re=0;for(let[ae,C]of X.entries()){let z=J[ae];z&&(C.status==="fulfilled"?(Co(V,se,C.value),re++):ne.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:z.skillId,skillName:z.skillName,err:String(C.reason)}))}re>0&&(N.skills=V,ne.info("initialSkills installed",{agentId:e.agentId,installed:re,requested:J.length}))}return await qe(N,this.paths),ne.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(T){throw ne.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),I&&S&&(await S.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),ne.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:n?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await UE(u.root,{recursive:!0,force:!0}).catch(R=>ne.warn("rm agent dir failed (ignored)",{err:String(R)})),T instanceof A?T:new A("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(b)}}async spawnSessionDownstream(e,n,i,o,a,d){let f=this.config.frameworksCache?.[e.framework];if(!f)if(e.deployType==="cloud"&&Pd(e.framework))f=VE;else throw e.framework==="hermes"?new A("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new A("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Pd(e.framework)&&!As(e.framework)&&(ne.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await gr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,p=await this.buildAgentToolEnv(e,o),m;if(e.framework==="openclaw")m=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:a,requestScene:d,command:f.path});else if(e.framework==="hermes"){let v={...p};x&&(await A0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:o,mockScenario:a}),v.HERMES_HOME=Qn(e.agentId,this.paths)),m=this.factory(e.framework,f.path,e.workspace,e.agentId,x,i,o,a,v)}else{let v=e.sessions.get(i),_=tn(e)?v?.permissionMode??kh:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await WE(e.agentId,this.paths),m=this.factory(e.framework,f.path,e.workspace,e.agentId,x,i,o,a,p,_,e.framework==="codex"&&e.deployType==="cloud"?zt(Re(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await m.start(),await m.initialize(JE),m}catch(v){let _=m instanceof mt?m.getStderrTail():[];throw _.length>0&&ne.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:v instanceof A?v.code:"unknown",recentStderr:_}),await m.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,f.path,v)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let o=await this.detectorFactory().probeOpenclawGateway(n);if(!o.reachable)return new A("AGENT_ENV_NOT_READY",Ih(o),{cause:{reason:Sh}})}catch(o){ne.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof A?i:new A("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};ne.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 ne.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 A("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:ZE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new A("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new A("AGENT_ENV_NOT_READY",Ih(n),{cause:{reason:Sh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,requestScene:u,command:f}=e,x=Rd(o);if(n.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new Wr({command:f,cwd:v.workspace,agentId:v.id,sessionName:x})}let p=await Eh();try{let v=this.getOpenclawConfig();await v.ensureAcpDeviceScopes()&&await v.restartGateway()}catch(v){ne.warn("acp device scope ensure failed (ignored)",{err:String(v)})}let m;if(i?.modelToken){let v=ud(o),_=fd(i),b=`${v}/${_}`,S=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(b)!==S){let I=this.getOpenclawConfig(),T=await I.getAllowlistModelsForProvider(v),R=b0(i,a,d,T,u);R&&(await I.ensureProvider(v,R),await I.addModelToAllowlist(b),this.ensuredProviders.set(b,S))}m=b}return new Wr({command:f,cwd:n.workspace,agentId:n.agentId,sessionName:x,...p?{gatewayToken:p}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=n??e.model;for(let a of e.sessions.keys()){let d=ud(a),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(x){f=!1,ne.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){f=!1,ne.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as Oh}from"node:crypto";import{promises as iv}from"node:fs";import{basename as Lh}from"node:path";Je();te();import{promises as XE}from"node:fs";import{basename as QE}from"node:path";var Ch=G("file-upload"),ev="/api/coze_claw/file/agent_upload",tv=6e4;async function Rh(t,e={}){let i=`${Nr(Mr(e.handshakeBase))}${ev}`,o=e.timeoutMs??tv,a=await XE.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([a],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);Ch.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let p=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),m=p.headers.get("x-tt-logid")??"";if(!p.ok){let b=await p.text().catch(()=>"");throw new A("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${m}: ${b.slice(0,200)}`)}let v=await p.json();if(v.code!==void 0&&v.code!==0)throw new A("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${m}`);let _=v.data?.file?.file_url;if(!_)throw new A("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${m}: ${JSON.stringify(v).slice(0,200)}`);return Ch.info("file upload ok",{uri:_,logid:m}),{uri:_}}catch(p){throw p instanceof A?p:p.name==="AbortError"?new A("UPLOAD_FAILED",`upload timeout (${o}ms) for ${QE(t.path)}`):new A("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}Je();te();import{extname as nv}from"node:path";var rv={".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 Ph(t){let e=nv(t).toLowerCase();return rv[e]??"application/octet-stream"}Pe();var qo=G("agent-send"),Dh=50*1024*1024;function Nh(t,e,n){let i=t.get(e);if(!i)throw new A("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new A("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(n);if(!o)throw new A("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function Mh(t,e,n,i,o,a){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,n,i,o);return}catch(x){u=x,f<2&&(qo.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new A("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function Bh(t,e){let{session:n,runtime:i}=Nh(e.core,t.agentId,t.sessionId);if(!await fi(t.path,n.workspace))throw new A("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await iv.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new A("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>Dh)throw new A("FILE_TOO_LARGE",`${o.size} bytes > limit ${Dh}`);let a=await Ph(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new A("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??Lh(t.path),u;try{u=await Rh({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:a,name:d,sizeBytes:o.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw qo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:a,code:x instanceof A?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let f={sessionUpdate:"agent_file",messageId:Oh(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:a,name:d,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Mh(e,n,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),qo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:a,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:a,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Fh(t,e){let{session:n,runtime:i}=Nh(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new A("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??Lh(t.path),a={sessionUpdate:"group_file",messageId:Oh(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Mh(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),qo.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 zh(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(n.length,i.length);for(let a=0;a<o;a++){let d=n[a]??0,u=i[a]??0;if(d<u)return!0;if(d>u)return!1}return!1}en();te();fn();var Ut=G("coze-cli-installer"),Uh="@coze/cli@latest",sv="coze",Hh="0.1.8",ov=5e3,av=5e3,cv=9e4,Gh=1e4,es=null,jo=!1;async function Nd(t,e={}){if(jo)return;if(es)return es;let n=e.exec??a0;return es=(async()=>{try{let i=await dv(sv,n),o=!1;if(i){let d=await lv(n);if(d===void 0)Ut.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(zh(d,Hh))Ut.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:Hh}),o=!0;else{Ut.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),jo=!0;return}}let a=o?"upgrade-only":"full";Ut.info("coze-cli install start",{package:Uh,mode:a});try{await n("npm",["i","-g","--prefer-online",Uh],{timeout:cv,maxBuffer:10*1024*1024}),Ut.info("coze-cli install ok")}catch(d){Ut.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){jo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:Gh}),Ut.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Ut.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:Gh}),Ut.info("coze auth login ok")}catch(d){Ut.warn("coze auth login failed",{err:String(d)});return}jo=!0}finally{es=null}})(),es}async function dv(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:ov});return Za(i)}catch{return}}async function lv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:av});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}$t();Kt();Pe();var uv=10*6e4;function qh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?uv:e}function Wo(t){return hn(t??Z().configFile)}function ts(t,e){return xn(e??Z().configFile,t)}import{randomBytes as Pv}from"node:crypto";fr();Je();te();import{createReadStream as fv}from"node:fs";import{mkdir as hv,readFile as xv,realpath as pv,stat as gv,writeFile as mv}from"node:fs/promises";import{basename as wv,dirname as Md,isAbsolute as _v,join as yv,relative as bv,resolve as jh,sep as Ev}from"node:path";import{createInterface as vv}from"node:readline";var Kh=G("fs-rpc"),ns=Xe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function $h(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>ns)throw new A("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${ns} bytes`);let i=await Zh(t.path,e);return await hv(Md(i),{recursive:!0}),await mv(i,t.content,"utf8"),Kh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Vh(t,e){let n=await Zh(t.path,e),i=await gv(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>ns&&!o)throw new A("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${ns} bytes`);let a;if(o&&i.size>ns)a=await Sv(n,t.line??1,t.limit);else{let d=await xv(n,"utf8");if(o){let u=d.split(`
|
|
117
|
+
`),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;a=u.slice(f,x).join(`
|
|
118
|
+
`)}else a=d}return Kh.info("fs/read_text_file ok",{path:n,size:a.length}),{content:a}}async function Sv(t,e,n){let i=vv({input:fv(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),a=typeof n=="number"?o+n:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let f of i)if(u>=o&&u<a&&d.push(f),u++,u>=a)break}finally{i.close()}return d.join(`
|
|
119
|
+
`)}async function Zh(t,e){if(typeof t!="string"||t.length===0)throw new A("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([Wh(jh(e)),Wh(jh(t))]),o=bv(n,i);if(Iv(o,Ev,_v(o)))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Iv(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Wh(t){let e=[],n=t;for(;n!==Md(n);)try{let i=await pv(n);return e.length?yv(i,...e.reverse()):i}catch{e.push(wv(n)),n=Md(n)}return t}te();var Jh=G("prompt-multimodal"),Yh=10*1024*1024,Av=15e3,kv=6;async function Xh(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let a=n++,d=t[a];d!==void 0&&(e[a]=await Tv(d))}}let o=Array.from({length:Math.min(kv,t.length)},()=>i());return await Promise.all(o),e}function Qh(t){return t.some(e=>e.type==="image")}async function Tv(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Gi(e.uri))return t;try{let{buf:n,contentType:i}=await Rv(e.uri),o=e.mimeType||Cv(i)||"application/octet-stream";return Jh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:o}),{type:"image",data:n.toString("base64"),mimeType:o}}catch(n){return Jh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Cv(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function Rv(t){let e=new AbortController,n=setTimeout(()=>e.abort(),Av);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>Yh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Yh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}$t();Je();te();var $=G("core"),Dv=3e4,Ov=/^(boe|ppe)_[A-Za-z0-9_-]+$/,Lv="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",Nv="\u5BA1\u6279\u5DF2\u8D85\u65F6",Mv=3e4,Ko=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Hr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=qh(e.bridgeConfig)}registerExtension(e,n){this.extensions[e]=n}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}getRequestSceneForSession(e){return this.requestSceneBySession.get(e)}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(n=>n.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of n)await this.agents.get(i)?.killAllRuntimes("reload");return n}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){$.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&$.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,i){let o=i.downstream;o&&(o.onUpdate(a=>{i.loadingSession||this.forwardUpdate(e,a)}),o.onAgentRequest(a=>{this.handleAgentRequest(e,o,a)}),o.onExit((a,d)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),Kr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[o,a]of this.pendingUpstream)a.downstream===e&&i.push(o);if(i.length!==0){$.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let o of i){let a=this.pendingUpstream.get(o);if(a){this.pendingUpstream.delete(o),this.upstream.send(Cn(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>$.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:Y.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){$.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Y.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new A("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Po(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&Ov.test(i)?this.currentCozeEnv=i:i&&$.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,a=n0(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);a&&u!==a?(this.requestSceneBySession.set(d,a),$.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),$.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){n!==null?await this.sendError(n,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let f=await u(e,this);n!==null&&await this.upstream.send(Ur(n,f));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Ur(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Ur(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(u){$.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Cn(n,Yi(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new A("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new A("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new A("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new A("AGENT_NOT_FOUND",`agent not found: ${i}`);let a=typeof n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!a)return this.dispatchSessionCall(o,e.method,n);if(e.method==="session/prompt"){let f=o.sessions.get(a);if(f?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,p=bo(n._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,f,a,Lv,x,p)}}let d=Date.now(),u=!1;try{let f=await o.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return u=!0,f}finally{$.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=i0(i);switch(n){case"session/new":{let a=Bv();return $.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=o;return $.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:a.sessionId}),{}}case"session/prompt":{let a=o,d=a.sessionId;if(!d)throw new A("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=tn(e)?r0(i._meta):void 0;if(u!==void 0&&!Ft(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Ad(e.framework)}`);let f=bo(i._meta),x=this.requestSceneBySession.get(d),p=await this.ensureRuntime(e,d,f,x);if(u!==void 0&&p.permissionMode===void 0&&(p.permissionMode=u,await this.persistSessionMapping(e)),p.replySeq=0,await this.ensureDownstream(e,d,p),!p.downstream||!p.acpSessionId)throw new A("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&p.permissionMode!==void 0&&p.permissionMode!==u){let _=p.permissionMode;p.permissionMode=u,await this.persistSessionMapping(e);try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(b){throw p.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),b}}let m=i._meta?.cozeTriggerMsgId;if(m?e.activeTriggers.set(p.acpSessionId,m):e.activeTriggers.delete(p.acpSessionId),f?e.activeGroupIds.set(p.acpSessionId,f):e.activeGroupIds.delete(p.acpSessionId),f&&p.cozeGroupId!==f&&(p.cozeGroupId=f,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Qh(a.prompt))throw new A("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let v=await Xh(a.prompt);try{let _=await p.downstream.sessionPrompt({...a,sessionId:p.acpSessionId,prompt:v});return p.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof A&&_.code==="AGENT_APPROVAL_TIMEOUT"){let b=p.pendingPermission;b&&(b.downstream.respondAgentRequest(b.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(b.upstreamId),p.pendingPermission=void 0);let S=p.acpSessionId,I=S?e.activeTriggers.get(S):void 0,T=S?e.activeGroupIds.get(S):void 0;return $.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,p,d,Nv,I,T)}throw _}finally{if(e.activeTriggers.delete(p.acpSessionId),e.activeGroupIds.delete(p.acpSessionId),p.pendingPermission=void 0,p.reloadAfterTurn){p.reloadAfterTurn=!1;let _=p.downstream;_&&(p.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:p.acpSessionId}),_.stop("reload-after-turn").catch(b=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(b)})))}else p.downstream?.isAlive()&&this.armIdleTimer(e,d,p)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new A("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let f=e.getSessionQueue(d);f.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:f.size}),f.dispose(new A("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 a=o,d=a.sessionId,u=a.modeId,f=bo(i._meta);if(!d)throw new A("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!tn(e))throw e.framework==="openclaw"?new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new A("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Ft(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Ad(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let p=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(m){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),m}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new A("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};$.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let d of o){let u=d.runtime.downstream,f=d.runtime.acpSessionId;u?.isAlive()&&f&&a.push({downstream:u,acpSessionId:f,oldMode:d.oldMode,runtime:d.runtime})}for(let d of a)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let f of o)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n,i,o){let a=e.sessions.get(n);if(a){let f=a.cozeGroupId!==i,x=e.deployType==="cloud"&&a.tokenGroupId!==i,p=a.requestScene!==o;if(x&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),x||p){Kr(a);let m=a.downstream;a.downstream=void 0,m&&await m.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=o,(f||x||p)&&await this.persistSessionMapping(e),a}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...o?{requestScene:o}:{}};return tn(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?v0:S0:u.permissionMode=e.framework==="claude-code"?Od:Th),e.sessions.set(n,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,n,i){let o={sessionId:n,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let a=await this.sendRequest(gt.GEN_MODEL_TOKEN,o,Mv);if(!a?.modelToken)throw new A("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return a.modelToken}catch(a){throw a instanceof A&&a.code==="MODEL_TOKEN_GEN_FAILED"?a:new A("MODEL_TOKEN_GEN_FAILED",a instanceof Error?a.message:String(a),{cause:a})}}async ensureDownstream(e,n,i){if(Kr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new A("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<a)throw new A("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((a-(Date.now()-u))/1e3)}s`);let f;try{let x=this.requestSceneBySession.get(n);x&&$.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),f=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&($.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),$.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),tn(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){$.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(Kr(i),this.isRuntimeBusy(e,i)){$.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}$.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(a=>$.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(a)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,o){let a={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(a.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(a.cozeGroupId=u)}await this.upstream.send(zr("session/update",{sessionId:i,update:o,_meta:a}))}async synthesizePromptReply(e,n,i,o,a,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return a&&(u.cozeTriggerMsgId=a),d&&(u.cozeGroupId=d),await this.upstream.send(zr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>$.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,o=this.reverseSessionId(e,i);if(!o){$.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(o);if(!a){$.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(Uv(n)){$.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&tn(e)){let p=d.currentModeId;Ft(e.framework,p)&&a.permissionMode!==p?(a.permissionMode=p,this.persistSessionMapping(e).catch(m=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(m)}))):typeof p=="string"&&!Ft(e.framework,p)&&$.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:p})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(zr("session/update",{...n,sessionId:o,_meta:u})).catch(p=>$.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}$.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:Y.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let a=i.params??{},d=await $h(a,o);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await Vh(a,o);n.respondAgentRequest(i.id,d)}}catch(o){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,Yi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let o=this.upstreamIds.next("session/request_permission"),a=i.params??{},u=a.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let p=u?e.activeGroupIds.get(u):void 0;p&&(x.cozeGroupId=p);let m=u?this.reverseSessionId(e,u):void 0,v=m?e.sessions.get(m):void 0;v&&(v.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...a,...m?{sessionId:m}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:m}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:m,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(b=>({optionId:b.optionId,kind:b.kind,name:b.name}))}),this.upstream.send(Zi(o,"session/request_permission",_)).catch(b=>{this.pendingUpstream.delete(o),$.error("forward permission request failed",{agentId:e.agentId,err:String(b)}),n.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(b)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let o=n.value;this.clearPendingPermissionFor(o),e.error?($.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"&&Fv(e.result,o),$.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new Ro(e.error)):i.value.resolve(e.result);return}$.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let o=e.get(n);if(o)return{value:o,key:n};if(typeof n=="number"){let a=String(n),d=e.get(a);if(d)return $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=Dv){let o=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(Zi(o,e,n)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(f)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,o]of e.sessions){let a={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(a.acpSessionId=o.acpSessionId),o.permissionMode&&tn(e)&&(a.permissionMode=o.permissionMode),o.cozeGroupId&&(a.cozeGroupId=o.cozeGroupId),o.tokenGroupId&&(a.tokenGroupId=o.tokenGroupId),o.requestScene&&(a.requestScene=o.requestScene),n.set(i,a)}await hi(e.agentId,n,this.paths)}catch(n){$.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Cn(e,{code:n,message:i,data:{bridgeVersion:Bt}}))}};function Bv(){return Pv(16).toString("hex")}function Fv(t,e){if(!t||typeof t!="object"){$.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){$.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=n.outcome;if(!i||typeof i!="object"){$.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let a=i.outcome;(typeof a!="string"||a!=="selected"&&a!=="cancelled")&&$.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var zv=["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."],ex="Warning: ";function Uv(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let o=i.text.startsWith(ex)?i.text.slice(ex.length):i.text;return zv.some(a=>o.startsWith(a))}Kt();te();Pe();import{randomBytes as Hv}from"node:crypto";import{createServer as Gv}from"node:http";var qv=1e6,tx=G("ipc"),$o=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??Z()}async start(){this.token=Hv(32).toString("hex");let e=Gv((i,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),tx.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(o=>o?i(o):n())}),this.server=null)}async persistAuthFiles(){await ct(this.paths.portFile,String(this.port)),await ct(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){rs(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){rs(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await jv(e)}catch(u){rs(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);rs(n,200,u??{ok:!0})}catch(u){tx.error("IPC handler failed",{key:o,err:String(u)}),rs(n,500,{error:u instanceof Error?u.message:String(u)})}}};function rs(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function jv(t){let e=[],n=0;for await(let o of t){let a=o;if(n+=a.length,n>qv)throw new Error("body too large");e.push(a)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var l1=Wt(Yx(),1),u1=Wt(na(),1),f1=Wt(Jr(),1),h1=Wt($d(),1),x1=Wt(Jd(),1),p1=Wt(nl(),1),op=Wt(oa(),1),g1=Wt(sp(),1);var ap=op.default;Je();te();var{FWS:D1}=wp(),Me=G("upstream.frontier"),yp="application/json",bp="none",O1=15e3;function L1(t){class e extends ap{constructor(i){super(i,d0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Me.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(Wl("debug"))try{let a;typeof i=="string"?a=Buffer.from(i,"utf8"):i instanceof Buffer?a=i:i instanceof ArrayBuffer?a=new Uint8Array(i):ArrayBuffer.isView(i)?a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):a=new Uint8Array(0);let d=Buffer.from(a.slice(0,128)).toString("hex");Me.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Me.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...o)}}return e}var fs=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){Me.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:l0,...kn(this.opts.ppeOverride)},n=L1(e),i=f0(this.opts.urlOverride),o={url:i,ws:n,fpID:c0,aID:vo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:yp,force:!0},payloadEncoding:{encoding:bp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new D1(o),d=!1,u=null,f,x,p=new Promise((_,b)=>{f=_,x=b}),m=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?x(_):f())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Me.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&m();for(let b of this.connectHandlers)Promise.resolve(b({initial:_})).catch(S=>Me.warn("onConnect handler threw (ignored)",{err:String(S)}))},a.onclose=_=>{this.opened=!1,Me.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},a.onerror=_=>{Me.warn("frontier error",{code:_.code,msg:_.message}),m(new A("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},a.onmessage=_=>this.handleMessage(_),this.fws=a;let v=this.opts.openTimeoutMs??O1;u=setTimeout(()=>{m(new A("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await a.connect();try{await p}catch(_){try{a.close(1e3,"open failed")}catch(b){Me.warn("fws close during start failure threw (ignored)",{err:String(b)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Me.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Me.warn("frontier send refused: upstream not started",{method:i}),new A("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Me.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 A("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),a=e;Ep(a)||Me.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:yp,payloadEncoding:bp})}catch(u){throw Me.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(u)}),new A("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=n(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Me.debug("drop non-adapter frontier frame",{service:n});return}let i=B1(e);if(!i){Me.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Me.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Me.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=o;Ep(a)||Me.info("frontier frame in",{logid:M1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:N1(i)}),Promise.resolve(this.handler(o)).catch(d=>Me.warn("frontier frame handler threw",{err:String(d)}))}};function Ep(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var vp=2e3;function N1(t){return t.length<=vp?t:`${t.slice(0,vp)}...<truncated, total ${t.length} chars>`}function M1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function B1(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}Je();te();var ol=G("skill-publish"),F1="/api/marketplace/product/skill/publish_with_assets",z1=15e4;async function Sp(t,e={}){let i=`${Nr(Mr(e.handshakeBase))}${F1}`,o=e.timeoutMs??z1,a=new FormData;a.append("skill_id",t.skillId??""),a.append("skill_name",t.skillName),a.append("skill_description",t.description??""),a.append("agent_id",t.agentId),a.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",...kn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);ol.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:a,signal:u.signal}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new A("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${_.slice(0,200)}`)}let m=await x.json();if(ol.info("skill publish response",{logid:p,httpStatus:x.status,code:m.code,msg:m.msg,dataSkillId:m.data?.skill_id??"",dataVersion:m.data?.version??""}),m.code!==void 0&&m.code!==0)throw new A("UPLOAD_FAILED",`skill publish code=${m.code} msg=${m.msg??"-"} logid=${p}`);let v={};return m.data?.skill_id!==void 0&&m.data.skill_id!==""&&(v.skillId=String(m.data.skill_id)),m.data?.version&&(v.version=m.data.version),ol.info("skill publish ok",{logid:p,skillId:v.skillId??"",version:v.version??""}),v}catch(x){throw x instanceof A?x:x.name==="AbortError"?new A("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new A("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(f)}}te();var al=G("upstream.switchable"),pa=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;al.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw al.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>al.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};te();var cl=G("upstream"),ni=class{handler=null;async start(){cl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){cl.info("NoopUpstream stopped",{reason:e})}async send(e){cl.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Je();te();Kt();te();Pe();import{promises as U1}from"node:fs";var Ip=G("pat-token-store");async function ga(t=Z()){try{let n=(await U1.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Ip.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"&&Ip.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function hs(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await ct(e.patTokenFile,t,{mode:384})}Pe();Pe();import{promises as ma}from"node:fs";import{join as H1}from"node:path";function G1(t,e){return`#!/bin/sh
|
|
119
120
|
exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
|
|
120
121
|
`}function q1(t,e){return`@echo off\r
|
|
121
122
|
"${e}" "${t}" %*\r
|
|
122
|
-
`}async function
|
|
123
|
+
`}async function Ap(t,e=Z()){let n=e.binDir;await ma.mkdir(n,{recursive:!0});let i=H1(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,a=process.platform==="win32"?q1(t,o):G1(t,o);return await ma.readFile(i,"utf8").catch(()=>null)===a||(await ma.writeFile(i,a,"utf8"),process.platform!=="win32"&&await ma.chmod(i,493)),n}te();Pe();import{execSync as kp}from"node:child_process";import{readFileSync as Tp,unlinkSync as j1}from"node:fs";import{mkdir as W1,open as K1,readFile as Cp,unlink as dl,writeFile as $1}from"node:fs/promises";import{dirname as V1}from"node:path";var Z1=G("single-instance"),J1=t=>new Promise(e=>setTimeout(e,t)),wa=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Z().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Xi(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&&Z1.warn("removing stale pid file",{stalePid:i}),await $1(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 Cp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await dl(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 Cp(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 W1(V1(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await K1(n,"wx")}catch(a){if(a.code!=="EEXIST")throw a;let d=await this.readPidFrom(n);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await J1(this.claimLockIntervalMs);continue}await dl(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await dl(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=Tp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Gr)||n.includes("lib/index.js"))}catch{}try{let n=kp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Gr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=kp(`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{Tp(this.pidFile,"utf8").trim()===String(this.selfPid)&&j1(this.pidFile)}catch{}})}};_a();te();var ar=G("daemon.upstream-watchdog"),iI=12e4,sI=9e5,oI=3e4;function ul(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ya=class{constructor(e){this.opts=e;this.softMs=e.softMs??ul("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",iI),this.hardMs=e.hardMs??ul("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",sI),this.intervalMs=e.intervalMs??ul("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",oI),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?.(),ar.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&&ar.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&&ar.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,ar.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){ar.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,ar.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>ar.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=G("daemon");async function Dp(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){ql({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>Re(C,t).logs,listAgentIds:()=>ks(t)});try{let{writeFileSync:C}=await import("node:fs");C(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
|
|
123
124
|
\u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
|
|
124
125
|
\u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
|
|
125
|
-
`)}catch{}}let e=new ga({processTitle:Hr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await qo(),o=i??{};bs({pid:process.pid}),G.info(i?"loaded bridge config":"initialized bridge config");let a=new ha(new ti),d=null,u=new jo({upstream:a,paths:t,bridgeConfig:o,sessionSpawner:async(C,F,H,ee,Ue,fe)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(C,F,H,ee,Ue,fe)}}),h=new Uo({paths:t,config:o,registry:u});d=h;let x,g,m=null,S={},_,v=null,I=null,k=null,T=new Cn;function P(C,F){return T.enqueue(()=>R(C,F))}function E(){I||(I=new wa({isConnected:()=>a.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>k?P(k,{force:!0}):void 0,onFatal:C=>{if(process.env[hs]==="1"){G.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}G.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),I.start()}async function R(C,F){let H=C,ee=H?.privatecode;if(!ee)throw new A("IPC_BAD_REQUEST","/connect requires privatecode");let Ue=ji(H.env),fe=H.handshake_url,pe=H.frontier_url,At=Rp(H.env,fe,pe);if(k=H,!F?.force&&x===ee&&g===At){let we=await aI(t);return u.agents.size===0&&we?(G.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ya(t,h).catch(Ce=>G.warn("connect-noop auto-revive error (ignored)",{err:String(Ce)}))):G.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let wt=!!x&&x!==ee,on=g!==void 0&&g!==At,Ht=wt||on,an=await od({privatecode:ee,...fe?{endpoint:fe}:{},ppeOverride:Ue});if(Ht){G.warn("connect config switched, resetting agents",{pcChanged:wt,envChanged:on,previousPc:x?_a(x):"",nextPc:_a(ee)});for(let we of[...u.agents.values()])await we.dispose("connect config switch").catch(()=>{}),u.agents.delete(we.agentId);u.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ti,"connect switch").catch(()=>{})}m=an.deviceId,bs({deviceId:m,pid:process.pid}),Od({patToken:ee,env:H.env}).catch(we=>G.warn("coze-cli setup error (ignored)",{err:String(we)}));let oi=new us({handshake:an,privatecode:ee,...pe?{urlOverride:pe}:{},ppeOverride:Ue,getPatTokenForAgent:we=>u.agents.get(we)?.patToken});return await a.swap(oi,"connect"),x=ee,g=At,S=Ue,_=fe,H.mock_scenario!==void 0&&(u.setMockScenario(H.mock_scenario),G.info("mock scenario set",{scenario:H.mock_scenario})),v||(v=new $i({core:u,getDeviceId:()=>m??"",onTickEnd:()=>N.retryPending().catch(we=>G.warn("detailSync.retryPending failed (ignored)",{err:String(we)})),onAuthFailures:J})),v.start(),E(),Ht&&ya(t,h).catch(we=>G.warn("post-connect-switch auto-revive error (ignored)",{err:String(we)})),fs(ee,t).catch(we=>G.warn("writePatToken after /connect failed (ignored)",{err:String(we)})),G.info("/connect: WS established",{deviceId:m}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async C=>h.createAgent(C.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let D={},M=new Io({agents:u.agents,paths:t,publishSkillToMarketplace:async C=>{let F=u.agents.get(C.agentId)?.patToken??x;if(!F)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Sp({patToken:F,zip:C.zip,...C.skillId?{skillId:C.skillId}:{},skillName:C.skillName,...C.description?{description:C.description}:{},agentId:C.agentId,...C.accountId?{accountId:C.accountId}:{}},{handshakeBase:_,ppeOverride:S})},disposeAndMarkDisconnected:async(C,F)=>{let H=u.agents.get(C);if(H){await h.cleanupOpenclawSessionProviders(H).catch(Ue=>G.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(Ue)})),H.framework==="hermes"&&H.deployType==="cloud"&&await hd(C,t).catch(Ue=>G.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(Ue)}));let ee=!0;try{await H.dispose(`disconnect: ${F}`)}catch(Ue){ee=!1,G.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(Ue)}),H.status="error"}ee&&(H.status="disconnected",u.unregister(C),u.disconnectedAgents.add(C))}else u.disconnectedAgents.add(C)},disposeForDelete:async(C,F)=>{let H=u.agents.get(C);H&&(await h.cleanupOpenclawSessionProviders(H).catch(ee=>G.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(ee)})),H.framework==="hermes"&&H.deployType==="cloud"&&await hd(C,t).catch(ee=>G.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(ee)})),await H.dispose(`delete: ${F}`).catch(ee=>G.warn("dispose during delete failed (ignored)",{agentId:C,err:String(ee)})),u.unregister(C)),u.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!D.ref)throw new Error("agent-detail-sync not initialized yet");await D.ref.syncOne(C)},cleanupOpenclawProviders:async(C,F)=>{await h.cleanupOpenclawSessionProviders(C,F)},openclawRepair:async(C,F)=>{await h.openclawRepair(C,F)},hermesReset:async(C,F)=>{let H=await Ee(C).catch(()=>null);!H||H.framework!=="hermes"||H.deployType!=="cloud"||await I0({paths:t,agentId:C,model:H.model,modelInfo:H.modelInfo,cozeEnv:F,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:C=>u.hasPendingPermissionFor(C)});u.registerExtension("_agent/listSkills",C=>M.listSkills(C.params)),u.registerExtension("_agent/addSkills",C=>M.addSkills(C.params)),u.registerExtension("_agent/removeSkills",C=>M.removeSkills(C.params)),u.registerExtension("_agent/publishSkill",C=>M.publishSkill(C.params)),u.registerExtension("_agent/getFileTree",C=>M.getFileTree(C.params)),u.registerExtension("_agent/getFileContent",C=>M.getFileContent(C.params)),u.registerExtension("_agent/update",C=>M.updateAgent(C.params)),u.registerExtension("_agent/disconnect",C=>M.disconnectAgent(C.params)),u.registerExtension("_agent/switchModel",C=>M.switchModel(C.params)),u.registerExtension("_agent/reset",C=>M.resetAgent(C.params)),u.registerExtension("_agent/repair",C=>M.repairAgent(C.params)),u.registerExtension("_agent/delete",C=>M.deleteAgent(C.params)),u.registerExtension("_agent/upgrade",C=>M.upgradeBridge(C.params));let N=new Ts({paths:t,handlers:M,agentManager:h,sendDetail:C=>u.sendRequest("_agent/detail",C)});D.ref=N;let J=async C=>{await Promise.allSettled(C.map(async F=>{try{await M.disconnectAgent({agentId:F.agentId,reason:`auth_failure: code=${F.code} ${F.message}`}),G.info("agent disconnected due to auth failure from heartbeat response",{agentId:F.agentId,code:F.code,message:F.message})}catch(H){G.warn("disconnect during authFailure handling failed (ignored)",{agentId:F.agentId,err:String(H)})}}))};a.onConnect(({initial:C})=>{G.info("frontier upstream connected, triggering detail sync",{initial:C}),N.syncAll(C?"initial-connect":"reconnect").catch(F=>G.warn("detail sync top-level error (ignored)",{err:String(F)}))});let K=new Wo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[hs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:m??"",frameworksCache:o.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let F=C,H=F?.privatecode,ee=F?.pairing_code;if(!H||!ee)throw new A("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ue=ji(F.env),fe=F.handshake_url,pe=F.frontier_url,At=Rp(F.env,fe,pe),wt=!!x&&x!==H,on=g!==void 0&&g!==At,Ht=wt||on,an=await od({privatecode:H,...fe?{endpoint:fe}:{},ppeOverride:Ue});if(Ht){G.warn("pair config switched, resetting agents",{pcChanged:wt,envChanged:on,previousPc:x?_a(x):"",nextPc:_a(H),previousEnvKey:g??"",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&&(G.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ti,"pair switch").catch(()=>{})}m=an.deviceId,bs({deviceId:m,pid:process.pid}),Od({patToken:H,env:F.env}).catch(Ce=>G.warn("coze-cli setup error (ignored)",{err:String(Ce)}));let oi=new us({handshake:an,privatecode:H,...pe?{urlOverride:pe}:{},ppeOverride:Ue,getPatTokenForAgent:Ce=>u.agents.get(Ce)?.patToken});await a.swap(oi,"pair");try{let Ce=new Qn;o.frameworksCache=await Ce.detectAll(),await es(o),G.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ce){G.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ce)})}let we=Object.keys(o.frameworksCache??{});try{let Ce=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:H,frameworks:we,_meta:{cozeDeviceId:m}});G.info("_agent/pair ok",{pairResult:Ce}),x=H,g=At,S=Ue,_=fe,F.mock_scenario!==void 0&&(u.setMockScenario(F.mock_scenario),G.info("mock scenario set",{scenario:F.mock_scenario})),fs(H,t).catch(Me=>G.warn("writePatToken after /pair failed (ignored)",{err:String(Me)})),v||(v=new $i({core:u,getDeviceId:()=>m??"",onTickEnd:()=>N.retryPending().catch(Me=>G.warn("detailSync.retryPending failed (ignored)",{err:String(Me)})),onAuthFailures:J})),v.start(),E(),Ht&&ya(t,h).catch(Me=>G.warn("post-pair-switch auto-revive error (ignored)",{err:String(Me)}));let ar;return F.agent_id&&(ar=await dI(F.agent_id,t,h,Me=>u.sendRequest("_agent/detail",Me),H).catch(Me=>(G.error("--agent-id ensureAgent failed",{agentId:F.agent_id,err:String(Me)}),{ok:!1,agentId:F.agent_id??"",note:String(Me)}))),{ok:!0,note:"paired with cloud",...ar?{agent:ar}:{}}}catch(Ce){return G.error("_agent/pair failed",{err:String(Ce)}),{ok:!1,note:`pair failed: ${String(Ce)}`}}}},{method:"POST",path:"/connect",handler:C=>P(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let F=C;return{ok:!0,result:await h.createAgent(F)}}},{method:"POST",path:"/agent/send",handler:async C=>{let F=C;if(!F?.agentId||!F?.sessionId||!F?.kind||!F?.path)throw new A("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let H=F;return await(H.groupFile?Fh:Bh)(H,{core:u,patToken:x,handshakeBase:_,ppeOverride:S})}catch(H){if(H instanceof A)return{ok:!1,code:H.code,message:H.message};throw H}}},{method:"POST",path:"/reload",handler:async C=>{let F=C?.agent_id,H=await u.reloadAgents(F);return G.info("IPC /reload: recycled agent subprocesses",{agentId:F??"(all)",recycled:H}),{ok:!0,recycled:H}}},{method:"POST",path:"/shutdown",handler:async()=>(G.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:se,token:X}=await K.start();try{await kp(t.libEntry,t)}catch(C){G.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await u.start(),lI({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new Qn().detectAll(),await es(o),o.frameworksCache)}).catch(C=>G.warn("startup warmup error (ignored)",{err:String(C)})),Ql().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(un(),Yl));for(let F of["claude-code","codex"]){let H=await C(F);H&&G.info("acp wrapper version",{framework:F,version:H})}}).catch(C=>G.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let re=null,ae={port:se,token:X,core:u,ipc:K,shutdown(C){return re||(G.info("daemon shutdown",{reason:C}),re=(async()=>{v?.stop(),I?.stop(),await u.stop(C),await K.stop(),await e.release()})(),re)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{ae.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>Q0()),process.on("unhandledRejection",C=>{G.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{G.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
|
|
126
|
-
`)}catch{}process.exit(1)}),
|
|
127
|
-
`)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function _I(){let t=(process.env.SHELL??"").trim()||(Mp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return gI.has(e)?t:null}function yI(t){return new Promise(e=>{let n=`printf '%s' '${
|
|
128
|
-
`;await
|
|
129
|
-
`).filter(d=>d.length>0).filter(d=>
|
|
130
|
-
`)}async function Yp(t,e){let n=e.paths??
|
|
131
|
-
`),1;for(let x of
|
|
126
|
+
`)}catch{}}let e=new wa({processTitle:Gr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Wo(),o=i??{};vs({pid:process.pid}),j.info(i?"loaded bridge config":"initialized bridge config");let a=new pa(new ni),d=null,u=new Ko({upstream:a,paths:t,bridgeConfig:o,sessionSpawner:async(C,z,q,ee,He,he)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(C,z,q,ee,He,he)}}),f=new Go({paths:t,config:o,registry:u});d=f;let x,p,m=null,v={},_,b=null,S=null,I=null,T=new Rn;function R(C,z){return T.enqueue(()=>P(C,z))}function E(){S||(S=new ya({isConnected:()=>a.isConnected()&&!(b?.isLivenessLost()??!1),forceReconnect:()=>I?R(I,{force:!0}):void 0,onFatal:C=>{if(process.env[xs]==="1"){j.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}j.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),S.start()}async function P(C,z){let q=C,ee=q?.privatecode;if(!ee)throw new A("IPC_BAD_REQUEST","/connect requires privatecode");let He=Wi(q.env),he=q.handshake_url,me=q.frontier_url,Ct=Pp(q.env,he,me);if(I=q,!z?.force&&x===ee&&p===Ct){let ye=await aI(t);return u.agents.size===0&&ye?(j.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ea(t,f).catch(Oe=>j.warn("connect-noop auto-revive error (ignored)",{err:String(Oe)}))):j.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let yt=!!x&&x!==ee,cn=p!==void 0&&p!==Ct,jt=yt||cn,dn=await cd({privatecode:ee,...he?{endpoint:he}:{},ppeOverride:He});if(jt){j.warn("connect config switched, resetting agents",{pcChanged:yt,envChanged:cn,previousPc:x?ba(x):"",nextPc:ba(ee)});for(let ye of[...u.agents.values()])await ye.dispose("connect config switch").catch(()=>{}),u.agents.delete(ye.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ni,"connect switch").catch(()=>{})}m=dn.deviceId,vs({deviceId:m,pid:process.pid}),Nd({patToken:ee,env:q.env}).catch(ye=>j.warn("coze-cli setup error (ignored)",{err:String(ye)}));let ai=new fs({handshake:dn,privatecode:ee,...me?{urlOverride:me}:{},ppeOverride:He,getPatTokenForAgent:ye=>u.agents.get(ye)?.patToken});return await a.swap(ai,"connect"),x=ee,p=Ct,v=He,_=he,q.mock_scenario!==void 0&&(u.setMockScenario(q.mock_scenario),j.info("mock scenario set",{scenario:q.mock_scenario})),b||(b=new Vi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>N.retryPending().catch(ye=>j.warn("detailSync.retryPending failed (ignored)",{err:String(ye)})),onAuthFailures:J})),b.start(),E(),jt&&Ea(t,f).catch(ye=>j.warn("post-connect-switch auto-revive error (ignored)",{err:String(ye)})),hs(ee,t).catch(ye=>j.warn("writePatToken after /connect failed (ignored)",{err:String(ye)})),j.info("/connect: WS established",{deviceId:m}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async C=>f.createAgent(C.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let D={},M=new ko({agents:u.agents,paths:t,publishSkillToMarketplace:async C=>{let z=u.agents.get(C.agentId)?.patToken??x;if(!z)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Sp({patToken:z,zip:C.zip,...C.skillId?{skillId:C.skillId}:{},skillName:C.skillName,...C.description?{description:C.description}:{},agentId:C.agentId,...C.accountId?{accountId:C.accountId}:{}},{handshakeBase:_,ppeOverride:v})},disposeAndMarkDisconnected:async(C,z)=>{let q=u.agents.get(C);if(q){await f.cleanupOpenclawSessionProviders(q).catch(He=>j.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(He)})),q.framework==="hermes"&&q.deployType==="cloud"&&await pd(C,t).catch(He=>j.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(He)}));let ee=!0;try{await q.dispose(`disconnect: ${z}`)}catch(He){ee=!1,j.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(He)}),q.status="error"}ee&&(q.status="disconnected",u.unregister(C),u.disconnectedAgents.add(C))}else u.disconnectedAgents.add(C)},disposeForDelete:async(C,z)=>{let q=u.agents.get(C);q&&(await f.cleanupOpenclawSessionProviders(q).catch(ee=>j.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(ee)})),q.framework==="hermes"&&q.deployType==="cloud"&&await pd(C,t).catch(ee=>j.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(ee)})),await q.dispose(`delete: ${z}`).catch(ee=>j.warn("dispose during delete failed (ignored)",{agentId:C,err:String(ee)})),u.unregister(C)),u.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!D.ref)throw new Error("agent-detail-sync not initialized yet");await D.ref.syncOne(C)},cleanupOpenclawProviders:async(C,z)=>{await f.cleanupOpenclawSessionProviders(C,z)},openclawRepair:async(C,z)=>{await f.openclawRepair(C,z)},hermesReset:async(C,z)=>{let q=await Ie(C).catch(()=>null);!q||q.framework!=="hermes"||q.deployType!=="cloud"||await I0({paths:t,agentId:C,model:q.model,modelInfo:q.modelInfo,cozeEnv:z,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:C=>u.hasPendingPermissionFor(C)});u.registerExtension("_agent/listSkills",C=>M.listSkills(C.params)),u.registerExtension("_agent/addSkills",C=>M.addSkills(C.params)),u.registerExtension("_agent/removeSkills",C=>M.removeSkills(C.params)),u.registerExtension("_agent/publishSkill",C=>M.publishSkill(C.params)),u.registerExtension("_agent/getFileTree",C=>M.getFileTree(C.params)),u.registerExtension("_agent/getFileContent",C=>M.getFileContent(C.params)),u.registerExtension("_agent/update",C=>M.updateAgent(C.params)),u.registerExtension("_agent/disconnect",C=>M.disconnectAgent(C.params)),u.registerExtension("_agent/switchModel",C=>M.switchModel(C.params)),u.registerExtension("_agent/reset",C=>M.resetAgent(C.params)),u.registerExtension("_agent/repair",C=>M.repairAgent(C.params)),u.registerExtension("_agent/delete",C=>M.deleteAgent(C.params)),u.registerExtension("_agent/upgrade",C=>M.upgradeBridge(C.params));let N=new Rs({paths:t,handlers:M,agentManager:f,sendDetail:C=>u.sendRequest("_agent/detail",C)});D.ref=N;let J=async C=>{await Promise.allSettled(C.map(async z=>{try{await M.disconnectAgent({agentId:z.agentId,reason:`auth_failure: code=${z.code} ${z.message}`}),j.info("agent disconnected due to auth failure from heartbeat response",{agentId:z.agentId,code:z.code,message:z.message})}catch(q){j.warn("disconnect during authFailure handling failed (ignored)",{agentId:z.agentId,err:String(q)})}}))};a.onConnect(({initial:C})=>{j.info("frontier upstream connected, triggering detail sync",{initial:C}),N.syncAll(C?"initial-connect":"reconnect").catch(z=>j.warn("detail sync top-level error (ignored)",{err:String(z)}))});let V=new $o({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[xs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:m??"",frameworksCache:o.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let z=C,q=z?.privatecode,ee=z?.pairing_code;if(!q||!ee)throw new A("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let He=Wi(z.env),he=z.handshake_url,me=z.frontier_url,Ct=Pp(z.env,he,me),yt=!!x&&x!==q,cn=p!==void 0&&p!==Ct,jt=yt||cn,dn=await cd({privatecode:q,...he?{endpoint:he}:{},ppeOverride:He});if(jt){j.warn("pair config switched, resetting agents",{pcChanged:yt,envChanged:cn,previousPc:x?ba(x):"",nextPc:ba(q),previousEnvKey:p??"",nextEnvKey:Ct});for(let Oe of[...u.agents.values()])await Oe.dispose("pair config switch").catch(()=>{}),u.agents.delete(Oe.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ni,"pair switch").catch(()=>{})}m=dn.deviceId,vs({deviceId:m,pid:process.pid}),Nd({patToken:q,env:z.env}).catch(Oe=>j.warn("coze-cli setup error (ignored)",{err:String(Oe)}));let ai=new fs({handshake:dn,privatecode:q,...me?{urlOverride:me}:{},ppeOverride:He,getPatTokenForAgent:Oe=>u.agents.get(Oe)?.patToken});await a.swap(ai,"pair");try{let Oe=new er;o.frameworksCache=await Oe.detectAll(),await ts(o),j.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Oe){j.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Oe)})}let ye=Object.keys(o.frameworksCache??{});try{let Oe=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:q,frameworks:ye,_meta:{cozeDeviceId:m}});j.info("_agent/pair ok",{pairResult:Oe}),x=q,p=Ct,v=He,_=he,z.mock_scenario!==void 0&&(u.setMockScenario(z.mock_scenario),j.info("mock scenario set",{scenario:z.mock_scenario})),hs(q,t).catch(Fe=>j.warn("writePatToken after /pair failed (ignored)",{err:String(Fe)})),b||(b=new Vi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>N.retryPending().catch(Fe=>j.warn("detailSync.retryPending failed (ignored)",{err:String(Fe)})),onAuthFailures:J})),b.start(),E(),jt&&Ea(t,f).catch(Fe=>j.warn("post-pair-switch auto-revive error (ignored)",{err:String(Fe)}));let cr;return z.agent_id&&(cr=await dI(z.agent_id,t,f,Fe=>u.sendRequest("_agent/detail",Fe),q).catch(Fe=>(j.error("--agent-id ensureAgent failed",{agentId:z.agent_id,err:String(Fe)}),{ok:!1,agentId:z.agent_id??"",note:String(Fe)}))),{ok:!0,note:"paired with cloud",...cr?{agent:cr}:{}}}catch(Oe){return j.error("_agent/pair failed",{err:String(Oe)}),{ok:!1,note:`pair failed: ${String(Oe)}`}}}},{method:"POST",path:"/connect",handler:C=>R(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let z=C;return{ok:!0,result:await f.createAgent(z)}}},{method:"POST",path:"/agent/send",handler:async C=>{let z=C;if(!z?.agentId||!z?.sessionId||!z?.kind||!z?.path)throw new A("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let q=z;return await(q.groupFile?Fh:Bh)(q,{core:u,patToken:x,handshakeBase:_,ppeOverride:v})}catch(q){if(q instanceof A)return{ok:!1,code:q.code,message:q.message};throw q}}},{method:"POST",path:"/reload",handler:async C=>{let z=C?.agent_id,q=await u.reloadAgents(z);return j.info("IPC /reload: recycled agent subprocesses",{agentId:z??"(all)",recycled:q}),{ok:!0,recycled:q}}},{method:"POST",path:"/shutdown",handler:async()=>(j.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:se,token:X}=await V.start();try{await Ap(t.libEntry,t)}catch(C){j.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await u.start(),lI({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new er().detectAll(),await ts(o),o.frameworksCache)}).catch(C=>j.warn("startup warmup error (ignored)",{err:String(C)})),Ql().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(fn(),Yl));for(let z of["claude-code","codex"]){let q=await C(z);q&&j.info("acp wrapper version",{framework:z,version:q})}}).catch(C=>j.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let re=null,ae={port:se,token:X,core:u,ipc:V,shutdown(C){return re||(j.info("daemon shutdown",{reason:C}),re=(async()=>{b?.stop(),S?.stop(),await u.stop(C),await V.stop(),await e.release()})(),re)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{ae.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>Q0()),process.on("unhandledRejection",C=>{j.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{j.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
|
|
127
|
+
`)}catch{}process.exit(1)}),j.info("daemon ready",{port:se,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),fI({cliSpawned:process.env[xs]==="1",readPatToken:()=>ga(t),connect:R}).catch(C=>j.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),ae}async function aI(t){return ks(t).length>0}function ba(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Pp(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function cI(t,e){let n=ks(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>($t(),Cs));for(let a of n){await o(a,t).catch(d=>j.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),j.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),j.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){j.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(d)})}}}async function dI(t,e,n,i,o){let{loadAgentConfig:a}=await Promise.resolve().then(()=>($t(),Cs)),d=await a(t,e);if(d){if(d.deletedAt)throw new A("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);j.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let p=Op(d),m={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...p?{_meta:p}:{}};return await n.createAgent(m),{ok:!0,agentId:t,note:d.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 A("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await n.createAgent(f);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function lI(t){let e=t.logger??j;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 cI(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await Ea(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await uI(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function Ea(t,e){let{readdir:n}=await import("node:fs/promises"),i;try{i=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>($t(),Cs));j.info("auto-revive: scanning local agents on startup",{count:i.length});let a=0,d=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)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){j.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){j.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{j.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=Op(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}),a+=1}catch(x){j.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),d+=1}}return j.info("auto-revive: done",{revived:a,skipped:d,total:i.length}),{revived:a,skipped:d,total:i.length}}async function uI(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let o of n)try{(await H0(o,t)).status==="refreshed"&&(i+=1)}catch(a){j.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(a)})}return i>0&&j.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function fI(t){let e=t.logger??j;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 Op(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}_a();Pe();import{readFile as Lp}from"node:fs/promises";var an=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let n=await va(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:xI(i)}}}async request(e){let n=await va(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let i=n.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let a=new AbortController,d=setTimeout(()=>a.abort(),n.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:o,body:i?JSON.stringify(n.body):void 0,signal:a.signal}),f=await u.text();return{status:u.status,body:hI(f)}}finally{clearTimeout(d)}}};async function va(t){try{let[e,n]=await Promise.all([Lp(t.portFile,"utf8"),Lp(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=n.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function hI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function xI(t){return t instanceof Error?t.message:String(t)}en();te();fr();import{spawn as pI}from"node:child_process";import{userInfo as Mp}from"node:os";var fl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",gI=new Set(["bash","zsh","sh","dash","ksh"]),Np=Xe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),mI=2e3;function wI(t,e=fl){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let o=t.slice(n+e.length,i),a={};for(let d of o.split(`
|
|
128
|
+
`)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function _I(){let t=(process.env.SHELL??"").trim()||(Mp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return gI.has(e)?t:null}function yI(t){return new Promise(e=>{let n=`printf '%s' '${fl}'; env; printf '%s' '${fl}'`,i;try{i=pI(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Mp().homedir}})}catch{e(null);return}let o="",a=!1,d=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},u=p=>{a||(a=!0,clearTimeout(f),clearTimeout(x),e(p))};i.stdout?.on("data",p=>{o+=p.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>d("SIGTERM"),Np),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},Np+mI)})}async function hl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=_I();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??yI)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=wI(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Pe();function On(t,...e){let n=[],i;for(let o=0;o<t.length;o++){let a=t[o],d=!1;for(let u of e){if(a===u){i=t[o+1],o+=1,d=!0;break}if(a.startsWith(`${u}=`)){i=a.slice(u.length+1),d=!0;break}}d||n.push(a)}return{value:i,rest:n}}fn();import{chmod as bI,copyFile as Bp,mkdir as zp,readFile as gs,rename as Fp,rm as gl,stat as Up,writeFile as EI}from"node:fs/promises";import{homedir as aO}from"node:os";import{dirname as vI,join as Be,resolve as ml,sep as ps}from"node:path";import{fileURLToPath as SI}from"node:url";en();te();Pe();function ri(t,e,n,i){st(t.bridgeLogsDir,e,"dist-install",n,i)}function Hp(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function II(){return{darwin:{arm64:Be("vendor","aarch64-apple-darwin","bin","codex"),x64:Be("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Be("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Be("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Be("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Be("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function AI(t){let e=SI(t),n=vI(e),i=`${ps}src${ps}`;if(n.includes(i)||n.endsWith(`${ps}src${ps}cli`))return null;let o=ml(n,"index.js"),a=ml(n,"..","package.json");return{dist:o,pkgJson:a}}async function wl(t={}){let e=t.paths??Z(),n=AI(import.meta.url),i=t.sourceDist??n?.dist,o=t.sourcePackageJson??n?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let a,d;try{let b=JSON.parse(await gs(o,"utf8"));a=b.version??"unknown",d=b.dependencies??{}}catch(b){throw ri(e,"error","cannot read source package.json",{err:String(b)}),new Error(`cannot read source package.json: ${String(b)}`,{cause:b})}let u=Is.map(b=>({name:b,spec:d[b]??"latest"})),f=u.map(({name:b,spec:S})=>`${b}@${S}`),x=await Wo(e.configFile)??{},p=x.libVersion,m=await gs(e.libEntry).then(()=>!0).catch(()=>!1),v=p===a,_=await Gp(e,u);if(v&&m&&_)return{kind:"already-current",libVersion:a};if(!v||!m){await zp(e.libDir,{recursive:!0}),await Bp(i,e.libEntry),await Bp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let b=ml(e.libDir,"package.json"),S=`${JSON.stringify({type:"module"},null,2)}
|
|
129
|
+
`;await gs(b,"utf8").catch(()=>null)!==S&&await EI(b,S)}return _||(t.installWrappers?await t.installWrappers(e,f):await CI(e,f,u)),x.libVersion=a,await ts(x,e.configFile),ri(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:p,toVersion:a}),v&&m?{kind:"already-current",libVersion:a}:p?{kind:"version-changed",fromVersion:p,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function Gp(t,e){for(let n of e){let i=Be(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await gs(i,"utf8"))}catch(d){return ri(t,"debug","wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(d)}),!1}let a=o.version;if(!a)return ri(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!kI(a,n.spec))return ri(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!!await qp(Be(t.libDir,"node_modules"))}function kI(t,e){let n=xl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=xl(i.slice(1));if(!a)return!0;if(pl(n,a)<0)return!1;let d=TI(a);return pl(n,d)<0}let o=xl(i);return o?pl(n,o)===0:!0}function TI(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function xl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function pl(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 CI(t,e,n){await DI(t.installLock,async()=>{if(await Gp(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${ps}.staging-${process.pid}-${i}`,a=Be(o,"node_modules"),d=Be(t.libDir,"node_modules");try{await zp(o,{recursive:!0}),await RI(e,o),await PI(a);let u=`${d}.trash-${i}`;await Fp(d,u).catch(()=>{}),await Fp(a,d),await gl(u,{recursive:!0,force:!0}).catch(()=>{}),ri(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await gl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function RI(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let a=at("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";a.stderr?.on("data",f=>{d.length<8192&&(d+=f.toString("utf8"))});let u=setTimeout(()=>a.kill("SIGKILL"),18e4);a.once("error",f=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(f)}`))}),a.once("close",f=>{clearTimeout(u),f===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${d.trim().slice(0,2e3)}`))})})}async function PI(t){for(let e of Is){let n=Be(t,...e.split("/")),i=JSON.parse(await gs(Be(n,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let a=Be(t,".bin",o),d=await Up(a);process.platform!=="win32"&&!(d.mode&73)&&await bI(a,d.mode|73).catch(()=>{})}if(!await qp(t)){let e=Hp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function qp(t){let e=Hp(),n=II();if(!e||!n)return!0;let i=Be(t,"@openai","codex"),o=Be(t,...e.split("/")),a=[Be(i,"package.json"),Be(i,"bin","codex.js"),Be(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Be(o,"package.json"),Be(o,n)];return(await Promise.all(a.map(u=>Up(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function DI(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(a=>setTimeout(a,500))}try{return await e()}finally{i&&await gl(t,{force:!0}).catch(()=>{})}}Wa();te();Pe();import{closeSync as Wp,fstatSync as Kp,openSync as $p,readFileSync as OI,readSync as LI,readdirSync as NI,statSync as MI}from"node:fs";import{join as Sa}from"node:path";var BI=new Set(["debug","info","warn","error"]);function Vp(t){let e=t,n=On(e,"--agent-id");e=n.rest;let i=On(e,"--date");e=i.rest;let o=On(e,"-n","--lines");e=o.rest;let a=On(e,"--level");e=a.rest;let d=On(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,x=a.value&&BI.has(a.value)?a.value:void 0,p={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(p.agentId=n.value),i.value&&(p.date=i.value),x&&(p.level=x),d.value&&(p.grep=d.value),p}function FI(t,e){return t.agentId?Sa(Re(t.agentId,e).logs,hr("agent",t.date)):Sa(e.bridgeLogsDir,hr("bridge",t.date))}function zI(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function UI(t,e){let n;try{n=NI(t)}catch{return[]}let i=[];for(let o of n){let a=ja(o,e);if(!a)continue;let d=0;try{d=MI(Sa(t,o)).size}catch{}i.push({file:Sa(t,o),date:a,size:d})}return i.sort((o,a)=>a.date.localeCompare(o.date)),i}function Zp(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"&&!Kl(n,e.level))return!1}return!0}var jp={debug:"90",info:"36",warn:"33",error:"31"},HI=new Set(["ts","level","module","msg"]);function GI(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Jp(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=GI(n.ts),o=typeof n.level=="string"?n.level:"",a=o.toUpperCase().padEnd(5);e.color&&jp[o]&&(a=`\x1B[${jp[o]}m${a}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",f=Object.entries(n).filter(([x])=>!HI.has(x)).map(([x,p])=>` ${x}=${typeof p=="string"?p:JSON.stringify(p)}`).join("");return`${i} ${a} ${d} ${u}${f}`}function qI(t,e,n){let a=OI(t,"utf8").split(`
|
|
130
|
+
`).filter(d=>d.length>0).filter(d=>Zp(d,{level:e.level,grep:e.grep}));for(let d of zI(a,e.lines))process.stdout.write(`${Jp(d,{raw:e.raw,color:n})}
|
|
131
|
+
`)}async function Yp(t,e){let n=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Re(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=UI(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
|
|
132
|
+
`),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
|
|
132
133
|
`);return 0}let o=t.date??Nn(new Date),a=FI({agentId:t.agentId,date:o},n);try{qI(a,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${a}
|
|
133
134
|
\u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
|
|
134
135
|
(legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
|
|
135
|
-
`),1}return t.follow&&await KI(a,t,i),0}var jI=500;function WI(t){try{let e=$p(t,"r");try{return Kp(e).size}finally{Wp(e)}}catch{return 0}}async function KI(t,e,n){let i=WI(t),o="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let u="";try{let
|
|
136
|
-
`);o=
|
|
137
|
-
`)}await new Promise(
|
|
136
|
+
`),1}return t.follow&&await KI(a,t,i),0}var jI=500;function WI(t){try{let e=$p(t,"r");try{return Kp(e).size}finally{Wp(e)}}catch{return 0}}async function KI(t,e,n){let i=WI(t),o="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let u="";try{let f=$p(t,"r");try{let x=Kp(f).size;if(x>i){let p=Buffer.allocUnsafe(x-i),m=LI(f,p,0,p.length,i);u=p.subarray(0,m).toString("utf8"),i+=m}}finally{Wp(f)}}catch{}if(u){let f=(o+u).split(`
|
|
137
|
+
`);o=f.pop()??"";for(let x of f)x.length>0&&Zp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Jp(x,{raw:e.raw,color:n})}
|
|
138
|
+
`)}await new Promise(f=>setTimeout(f,jI))}}finally{process.off("SIGINT",d)}}import{basename as $I,resolve as VI}from"node:path";Pe();var ZI=9e4,JI={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 YI(t){return JI[t]??1}async function Xp(t,e={}){let n=e.paths??Z();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>
|
|
138
139
|
`),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.
|
|
139
|
-
`),3;let i=await
|
|
140
|
-
`),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:VI(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},a;try{a=await XI(i,"/agent/send",o,
|
|
140
|
+
`),3;let i=await va(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.
|
|
141
|
+
`),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:VI(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},a;try{a=await XI(i,"/agent/send",o,ZI)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
|
|
141
142
|
`),4}if(!a.ok)return process.stderr.write(`Error: ${a.code}: ${a.message}
|
|
142
143
|
`),YI(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
|
|
143
144
|
`);else{let d=t.name??$I(o.path);if(t.groupFile){let u=a.uri.length>60?`${a.uri.slice(0,57)}...`:a.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
|
|
144
145
|
`)}else process.stdout.write(`Sent ${t.kind} ${d} (${QI(a.bytes)})
|
|
145
|
-
`)}return 0}async function XI(t,e,n,i){let o=new AbortController,a=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:o.signal}),u=await d.text(),
|
|
146
|
-
`)}function
|
|
146
|
+
`)}return 0}async function XI(t,e,n,i){let o=new AbortController,a=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:o.signal}),u=await d.text(),f=u?JSON.parse(u):null;return f&&typeof f=="object"&&"ok"in f?f:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(a)}}function QI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var cg=G("cli");function Ze(t,e){let{value:n,rest:i}=On(t,e);return{value:n,rest:i}}function Ra(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
|
|
147
|
+
`)}function vA(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:R}=Ze(e.slice(1),"--agent-id");return R?{mode:"reload",agentId:R}:{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 SA(e.slice(1));if(e[0]==="log")return{mode:"log",...Vp(e.slice(1))};if(e[0]==="connect")return IA(e.slice(1));if(e.includes("--status"))return Ra("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ra("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ra("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ra("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:i,rest:o}=Ze(n,"--pat-token");n=o;let{value:a,rest:d}=Ze(n,"--pair-code");n=d;let{value:u,rest:f}=Ze(n,"--env");n=f;let{value:x,rest:p}=Ze(n,"--handshake-url");n=p;let{value:m,rest:v}=Ze(n,"--frontier-url");n=v;let{value:_,rest:b}=Ze(n,"--mock-scenario");n=b;let{value:S}=Ze(n,"--agent-id"),I=n.includes("--skip-rebuild-env");if(!i||!a)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:a};return u&&(T.env=u),x&&(T.handshakeUrl=x),m&&(T.frontierUrl=m),_&&(T.mockScenario=_),S&&(T.agentId=S),I&&(T.skipRebuildEnv=!0),T}function SA(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:a}=Ze(i,"--caption");i=a;let{value:d,rest:u}=Ze(i,"--name");i=u;let{value:f,rest:x}=Ze(i,"--agent-id");i=x;let{value:p,rest:m}=Ze(i,"--session-id");i=m;let{value:v,rest:_}=Ze(i,"--mime");i=_;let b=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let S=i.includes("--json"),I={mode:"send",kind:e,path:n,json:S};return o&&(I.caption=o),d&&(I.name=d),f&&(I.agentId=f),p&&(I.sessionId=p),b&&(I.groupFile=!0),v&&(I.mimeType=v),I}function IA(t){let e=t,{value:n,rest:i}=Ze(e,"--pat-token");e=i;let{value:o,rest:a}=Ze(e,"--env");e=a;let{value:d,rest:u}=Ze(e,"--handshake-url");e=u;let{value:f,rest:x}=Ze(e,"--frontier-url");e=x;let{value:p,rest:m}=Ze(e,"--mock-scenario");e=m;let v=e.includes("--skip-rebuild-env"),_={mode:"connect"};return n&&(_.privatecode=n),o&&(_.env=o),d&&(_.handshakeUrl=d),f&&(_.frontierUrl=f),p&&(_.mockScenario=p),v&&(_.skipRebuildEnv=!0),_}var AA=`
|
|
147
148
|
coze-bridge - local bridge daemon for cloud Agent Service
|
|
148
149
|
|
|
149
150
|
Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
|
|
@@ -224,52 +225,52 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
|
|
|
224
225
|
|
|
225
226
|
Internal:
|
|
226
227
|
<node> <entry> --daemon daemon mode (OS supervisor only)
|
|
227
|
-
`.trimStart();async function dg(t=process.argv,e={}){let n=
|
|
228
|
-
`),0;case"daemon":{try{await Dp()}catch(i){return cg.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return
|
|
228
|
+
`.trimStart();async function dg(t=process.argv,e={}){let n=vA(t);switch(n.mode){case"help":return process.stdout.write(AA),0;case"version":return process.stdout.write(`${Bt}
|
|
229
|
+
`),0;case"daemon":{try{await Dp()}catch(i){return cg.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return kA(e);case"stop":return ug(e);case"reload":return RA(n.agentId,e);case"log":return Yp(n,e);case"update":return TA(e);case"purge":return DA(e);case"service-install":return OA(e);case"service-uninstall":return LA(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),NA(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),MA(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return Xp({kind:n.kind,path:n.path,...n.agentId?{agentId:n.agentId}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.caption?{caption:n.caption}:{},...n.name?{name:n.name}:{},...n.groupFile?{groupFile:!0}:{},...n.mimeType?{mimeType:n.mimeType}:{},json:n.json},e)}}async function lg(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 kA(t){let e=t.paths??Z(),n=new an(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
229
230
|
`),1;if(i.kind==="stale")return await lg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
230
231
|
`),1;let o=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
|
|
231
232
|
${JSON.stringify(o.body,null,2)}
|
|
232
|
-
`),0}async function ug(t){let e=t.paths??
|
|
233
|
+
`),0}async function ug(t){let e=t.paths??Z(),n=new an(e),i=t.daemonSweep??(async()=>{let f=eh();return await th(f),f}),o=async()=>{t.skipProcessKill||await i(e)},a=await ws(t),d=!1;if(a)try{await a.uninstall(),d=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
|
|
233
234
|
`)}let u=await n.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
|
|
234
235
|
`:`coze-bridge: not running
|
|
235
236
|
`),0;if(u.kind==="stale")return await lg(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
236
237
|
`),0;try{return await n.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
|
|
237
|
-
`),0}catch(
|
|
238
|
-
`),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(
|
|
239
|
-
`),1)}}async function
|
|
240
|
-
`),e(1)})})}async function
|
|
238
|
+
`),0}catch(f){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
|
|
239
|
+
`),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
|
|
240
|
+
`),1)}}async function TA(t){return await ug(t),(t.spawnNpx??CA)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function CA(t){return new Promise(e=>{let n=at("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
|
|
241
|
+
`),e(1)})})}async function RA(t,e){let n=new an(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
|
|
241
242
|
`),1;try{let o=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let a=o.body.recycled??[];return t&&a.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
|
|
242
243
|
`):process.stdout.write(`coze-bridge: reloaded ${a.length} agent(s): ${a.join(", ")||"(none)"}
|
|
243
244
|
`),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
|
|
244
245
|
`),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
|
|
245
|
-
`),1}}async function
|
|
246
|
+
`),1}}async function ws(t){if(t.supervisor){let a=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:a.platform,install:u=>a.install(d,u),uninstall:()=>a.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(sg(),ig)),i=e(),o=n();return{platform:i.platform,install:a=>i.install(o,a),uninstall:()=>i.uninstall(o)}}async function fg(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??BA,a=t.paths??Z();if(n.kind==="connected"){if(!PA(n.body))return n;st(a.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:n.body}),await e.request({method:"POST",path:"/shutdown"}).catch(f=>st(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await ag(a.pidFile,o)}let d=t.spawnDaemon??Rp,u=await ws(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await og(e,i,o);if(f.kind==="connected")return f;st(a.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(f){st(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}st(a.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 ag(a.pidFile,o)}else u&&await u.install({activate:!1}).catch(f=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(f)}
|
|
246
247
|
`));return process.stdout.write(`coze-bridge: starting daemon...
|
|
247
|
-
`),await d({paths:t.paths}),og(e,i,o)}function
|
|
248
|
+
`),await d({paths:t.paths}),og(e,i,o)}function PA(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 DA(t){let e=new an(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
|
|
248
249
|
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
|
|
249
|
-
`)}await new Promise(d=>setTimeout(d,500))}let i=await
|
|
250
|
+
`)}await new Promise(d=>setTimeout(d,500))}let i=await ws(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
|
|
250
251
|
`)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
|
|
251
|
-
`)}let o=t.paths??
|
|
252
|
+
`)}let o=t.paths??Z(),{rm:a}=await import("node:fs/promises");try{await a(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
|
|
252
253
|
`)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
|
|
253
254
|
`),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
|
|
254
|
-
`),0}async function
|
|
255
|
+
`),0}async function OA(t){let e=await ws(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
|
|
255
256
|
`),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
|
|
256
257
|
`),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
|
|
257
|
-
`),1}}async function
|
|
258
|
+
`),1}}async function LA(t){let e=await ws(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
|
|
258
259
|
`),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
|
|
259
|
-
`),1}}async function hg(t,e,n){if(e)return
|
|
260
|
-
`),
|
|
260
|
+
`),1}}async function hg(t,e,n){if(e)return st(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(st(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(st(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
|
|
261
|
+
`),st(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function NA(t,e,n,i={},o,a){let d=new an(n.paths),u=n.paths??Z(),f=await hg(u,a,n.reconstructEnv??hl);if(await ad(u,f).catch(m=>st(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!n.skipDistInstall){let m=await wl({paths:n.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
|
|
261
262
|
`),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
|
|
262
263
|
`)}let x=await fg(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
|
|
263
|
-
`),1;let
|
|
264
|
+
`),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),o&&(p.agent_id=o);try{let m=await d.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});if(m.status===200&&m.body?.ok){let v=m.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
|
|
264
265
|
`),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"
|
|
265
266
|
`),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(m.body)}
|
|
266
267
|
`),1}catch(m){return process.stderr.write(`coze-bridge: pair failed: ${String(m)}
|
|
267
|
-
`),1}}async function
|
|
268
|
-
`),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(
|
|
269
|
-
`)}let
|
|
270
|
-
`),1;let x={privatecode:a};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
|
|
271
|
-
`),t!==void 0&&await
|
|
272
|
-
`),1)}catch(
|
|
273
|
-
`),1}}async function og(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await n(200)}return t.probe(500)}async function ag(t,e,n=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let a=0;a<n;a++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!
|
|
268
|
+
`),1}}async function MA(t,e,n={},i){let o=e.paths??Z(),a=t??await ga(o);if(!a)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 an(e.paths),u=await hg(o,i,e.reconstructEnv??hl);if(await ad(o,u).catch(p=>st(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(p)})),!e.skipDistInstall){let p=await wl({paths:e.paths});p.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${p.fromVersion} \u2192 ${p.toVersion}
|
|
269
|
+
`),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):p.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${p.libVersion}
|
|
270
|
+
`)}let f=await fg(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
|
|
271
|
+
`),1;let x={privatecode:a};n.env&&(x.env=n.env),n.handshakeUrl&&(x.handshake_url=n.handshakeUrl),n.frontierUrl&&(x.frontier_url=n.frontierUrl),n.mockScenario&&(x.mock_scenario=n.mockScenario);try{let p=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return p.status===200&&p.body?.ok?(process.stdout.write(`coze-bridge: connected (${p.body.note??"ok"})
|
|
272
|
+
`),t!==void 0&&await hs(a,o).catch(m=>cg.warn("writePatToken after connect failed (ignored)",{err:String(m)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(p.body)}
|
|
273
|
+
`),1)}catch(p){return process.stderr.write(`coze-bridge: connect failed: ${String(p)}
|
|
274
|
+
`),1}}async function og(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await n(200)}return t.probe(500)}async function ag(t,e,n=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let a=0;a<n;a++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Xi(u))return;await e(i)}}function BA(t){return new Promise(e=>setTimeout(e,t))}te();function FA(t){let e=/^v?(\d+)/.exec(t.trim());return e&&Number(e[1])<22?"fatal":"ok"}function xg(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){if(FA(t)==="ok")return;let o=t.replace(/^v/,"");e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v22.0.0)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
|
|
274
275
|
`),n(1)}xg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&jl("warn");dg(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
|
|
275
276
|
`),process.exit(1)});
|