coze-bridge 0.3.2-alpha.106 → 0.3.2-alpha.107
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 +87 -87
- 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 Mm=Object.create;var
|
|
8
|
+
var Mm=Object.create;var tc=Object.defineProperty;var Nm=Object.getOwnPropertyDescriptor;var Fm=Object.getOwnPropertyNames;var Bm=Object.getPrototypeOf,zm=Object.prototype.hasOwnProperty;var we=(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 lt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ue=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),nc=(t,e)=>{for(var n in e)tc(t,n,{get:e[n],enumerable:!0})},Um=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fm(e))!zm.call(t,o)&&o!==n&&tc(t,o,{get:()=>e[o],enumerable:!(i=Nm(e,o))||i.enumerable});return t};var on=(t,e,n)=>(n=t!=null?Mm(Bm(t)):{},Um(e||!t||!t.__esModule?tc(n,"default",{value:t,enumerable:!0}):n,t));function Xe(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var Ar=lt(()=>{"use strict"});import{createWriteStream as Hm,mkdirSync as Gm,readdirSync as qm,unlinkSync as jm}from"node:fs";import{join as nu}from"node:path";function Vn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function kr(t,e){return`${t}-${e}.log`}function rc(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Wm(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 Ls(t,e,n,i){let o;try{o=qm(t)}catch{return}for(let a of o){let d=rc(a,e);if(d&&Wm(d,n,i))try{jm(nu(t,a))}catch{}}}var Si,ic=lt(()=>{"use strict";Si=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Vn(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{Gm(this.dir,{recursive:!0});let n=Hm(nu(this.dir,kr(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}),Km(Vm(t,
|
|
12
|
-
`;if(
|
|
13
|
-
`),{cause:a})}}async function iw(t){let e=
|
|
14
|
-
`,n)}var Ct=ot(()=>{"use strict"});import{promises as pf,readdirSync as pw}from"node:fs";import{homedir as gw}from"node:os";import{sep as mw,join as Re,resolve as gf}from"node:path";function Z(t){let e=t??gw(),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"),modelCacheFile:Re(i,"model-cache.json"),agentsRoot:Re(n,"agents")}}function Oe(t,e=Z()){let n=Re(e.agentsRoot,t);return{root:n,config:Re(n,"config.json"),workspace:Re(n,"workspace"),logs:Re(n,"logs")}}function Bs(t=Z()){try{return pw(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function vi(t,e){let n=await pf.realpath(gf(t)).catch(()=>null);if(!n)return!1;let i=await pf.realpath(gf(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+mw)}var Pe=ot(()=>{"use strict"});var Us={};tc(Us,{AGENT_CONFIG_FILE_MODE:()=>zs,enforceAgentConfigMode:()=>yw,loadAgentConfig:()=>we,persistAgentSessions:()=>Si,persistAgentSkills:()=>Ii,saveAgentConfig:()=>Le});import{chmod as ww,stat as _w}from"node:fs/promises";function we(t,e){return Ye(Oe(t,e).config)}function Le(t,e){return ut(Oe(t.agentId,e).config,t,{mode:zs})}async function yw(t,e){if(process.platform==="win32")return;let n=Oe(t,e).config;try{let i=await _w(n);if(!i.isFile())return;let o=i.mode&511;o!==zs&&(await ww(n,zs),mf.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;mf.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function Si(t,e,n){let i=await we(t,n);i&&(i.sessions=Object.fromEntries(e),await Le(i,n))}async function Ii(t,e,n){let i=await we(t,n);i&&(i.skills=e,await Le(i,n))}var mf,zs,tn=ot(()=>{"use strict";Ct();ne();Pe();mf=q("agent-config"),zs=384});var lc=fe((cT,yf)=>{yf.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 qs=fe(bf=>{var Ef={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 Aw(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(Ef))bf[t]=Aw(Ef[t])});var kf=fe((lT,Af)=>{var kw=ge("fs"),ze=ge("path"),vf=lc(),Tw=qs(),Cw=typeof process=="object"&&process.platform==="win32",Sf=t=>typeof t=="object"&&t!==null,If=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 ke(t){this.sep=ze.sep,this.fs=kw,Sf(t)&&Sf(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Af.exports=ke;ke.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(f){if(f.message&&f.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw f}if(d&&d.isFile())throw Tw.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};ke.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 f;try{f=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),f=o.fs.openSync(t,"w",438)}if(f)try{o.fs.writeSync(f,e,0,e.length,0)}finally{o.fs.closeSync(f)}return o.fs.chmodSync(t,i||438),!0};ke.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(f,u){if(d&&u.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(w,b){w?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)})})})})}):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)})})}):a.fs.chmod(t,i||438,function(){o(!0)})})})})})};ke.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(f){let u=ze.join(i,f),x=e.fs.statSync(u);(!o||o.test(u))&&d.push(ze.normalize(u)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(d=d.concat(n(u,o,a)))}),d}return n(t,void 0,!0)};ke.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(f){f=ze.join(t,f),n.fs.stat(f,function(u,x){if(u)return e(u);x&&(i.push(ze.normalize(f)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(f,function(p,w){if(p)return e(p);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};ke.prototype.getAttributes=function(){};ke.prototype.setAttributes=function(){};ke.crc32update=function(t,e){return If[(t^e)&255]^t>>>8};ke.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=ke.crc32update(n,t[i++]);return~n>>>0};ke.methodToString=function(t){switch(t){case vf.STORED:return"STORED ("+t+")";case vf.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ke.canonical=function(t){if(!t)return"";let e=ze.posix.normalize("/"+t.split("\\").join("/"));return ze.join(".",e)};ke.zipnamefix=function(t){if(!t)return"";let e=ze.posix.normalize("/"+t.split("\\").join("/"));return ze.posix.join(".",e)};ke.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]};ke.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)))};ke.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};ke.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};ke.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)};ke.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};ke.isWin=Cw;ke.crcTable=If});var Cf=fe((fT,Tf)=>{var Rw=ge("path");Tf.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=Rw.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 Pf=fe((uT,Rf)=>{Rf.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var Rr=fe((hT,Cr)=>{Cr.exports=kf();Cr.exports.Constants=lc();Cr.exports.Errors=qs();Cr.exports.FileAttr=Cf();Cr.exports.decoder=Pf()});var Of=fe((xT,Df)=>{var Sn=Rr(),z=Sn.Constants;Df.exports=function(){var t=20,e=10,n=0,i=0,o=0,a=0,d=0,f=0,u=0,x=0,p=0,w=0,b=0,_=0,v=0;t|=Sn.isWin?2560:768,n|=z.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,R=E=>Math.max(0,E)&255;return o=Sn.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 Sn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=Sn.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=A(E)},get timeHighByte(){return R(o>>>8)},get crc(){return a},set crc(E){a=A(E)},get compressedSize(){return d},set compressedSize(E){d=A(E)},get size(){return f},set size(E){f=A(E)},get fileNameLength(){return u},set fileNameLength(E){u=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return p},set commentLength(E){p=E},get diskNumStart(){return w},set diskNumStart(E){w=A(E)},get inAttr(){return b},set inAttr(E){b=A(E)},get attr(){return _},set attr(E){_=A(E)},get fileAttr(){return(_||0)>>16&4095},get offset(){return v},set offset(E){v=A(E)},get encrypted(){return(n&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+u+x+p},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var P=E.slice(v,v+z.LOCHDR);if(P.readUInt32LE(0)!==z.LOCSIG)throw Sn.Errors.INVALID_LOC();I.version=P.readUInt16LE(z.LOCVER),I.flags=P.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=P.readUInt16LE(z.LOCHOW),I.time=P.readUInt32LE(z.LOCTIM),I.crc=P.readUInt32LE(z.LOCCRC),I.compressedSize=P.readUInt32LE(z.LOCSIZ),I.size=P.readUInt32LE(z.LOCLEN),I.fnameLen=P.readUInt16LE(z.LOCNAM),I.extraLen=P.readUInt16LE(z.LOCEXT);let D=v+z.LOCHDR+I.fnameLen,U=D+I.extraLen;return E.slice(D,U)},loadFromBinary:function(E){if(E.length!==z.CENHDR||E.readUInt32LE(0)!==z.CENSIG)throw Sn.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),f=E.readUInt32LE(z.CENLEN),u=E.readUInt16LE(z.CENNAM),x=E.readUInt16LE(z.CENEXT),p=E.readUInt16LE(z.CENCOM),w=E.readUInt16LE(z.CENDSK),b=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(f,z.LOCLEN),E.writeUInt16LE(u,z.LOCNAM),E.writeUInt16LE(I.extraLen,z.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(z.CENHDR+u+x+p);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(f,z.CENLEN),E.writeUInt16LE(u,z.CENNAM),E.writeUInt16LE(x,z.CENEXT),E.writeUInt16LE(p,z.CENCOM),E.writeUInt16LE(w,z.CENDSK),E.writeUInt16LE(b,z.CENATT),E.writeUInt32LE(_,z.CENATX),E.writeUInt32LE(v,z.CENOFF),E},toJSON:function(){let E=function(P){return P+" bytes"};return{made:t,version:e,flags:n,method:Sn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:E(d),size:E(f),fileNameLength:E(u),extraLength:E(x),commentLength:E(p),diskNumStart:w,inAttr:b,attr:_,offset:v,centralHeaderSize:E(z.CENHDR+u+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Mf=fe((pT,Lf)=>{var Pr=Rr(),ve=Pr.Constants;Lf.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 ve.ENDHDR+o},loadFromBinary:function(a){if((a.length!==ve.ENDHDR||a.readUInt32LE(0)!==ve.ENDSIG)&&(a.length<ve.ZIP64HDR||a.readUInt32LE(0)!==ve.ZIP64SIG))throw Pr.Errors.INVALID_END();a.readUInt32LE(0)===ve.ENDSIG?(t=a.readUInt16LE(ve.ENDSUB),e=a.readUInt16LE(ve.ENDTOT),n=a.readUInt32LE(ve.ENDSIZ),i=a.readUInt32LE(ve.ENDOFF),o=a.readUInt16LE(ve.ENDCOM)):(t=Pr.readBigUInt64LE(a,ve.ZIP64SUB),e=Pr.readBigUInt64LE(a,ve.ZIP64TOT),n=Pr.readBigUInt64LE(a,ve.ZIP64SIZE),i=Pr.readBigUInt64LE(a,ve.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(ve.ENDHDR+o);return a.writeUInt32LE(ve.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,ve.ENDSUB),a.writeUInt16LE(e,ve.ENDTOT),a.writeUInt32LE(n,ve.ENDSIZ),a.writeUInt32LE(i,ve.ENDOFF),a.writeUInt16LE(o,ve.ENDCOM),a.fill(" ",ve.ENDHDR),a},toJSON:function(){let a=function(d,f){let u=d.toString(16).toUpperCase();for(;u.length<f;)u="0"+u;return"0x"+u};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:a(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var uc=fe(fc=>{fc.EntryHeader=Of();fc.MainHeader=Mf()});var Ff=fe((mT,Nf)=>{Nf.exports=function(t){var e=ge("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(f){a.push(f),d+=f.length}),o.on("end",function(){var f=Buffer.alloc(d),u=0;f.fill(0);for(var x=0;x<a.length;x++){var p=a[x];p.copy(f,u),u+=p.length}i&&i(f)}),o.end(t)}}}});var zf=fe((wT,Bf)=>{var Pw=+(process.versions?process.versions.node:"").split(".")[0]||0;Bf.exports=function(t,e){var n=ge("zlib");let i=Pw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var a=n.createInflateRaw(i),d=[],f=0;a.on("data",function(u){d.push(u),f+=u.length}),a.on("end",function(){var u=Buffer.alloc(f),x=0;u.fill(0);for(var p=0;p<d.length;p++){var w=d[p];w.copy(u,x),x+=w.length}o&&o(u)}),a.end(t)}}}});var jf=fe((_T,Gf)=>{"use strict";var{randomFillSync:Uf}=ge("crypto"),Dw=qs(),Ow=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}),qf=(t,e)=>Math.imul(t,e)>>>0,Hf=(t,e)=>Ow[(t^e)&255]^t>>>8,Ai=()=>typeof Uf=="function"?Uf(Buffer.alloc(12)):Ai.node();Ai.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 Gs={genSalt:Ai};function js(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])}js.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Hf(e[0],t),e[1]+=e[0]&255,e[1]=qf(e[1],134775813)+1,e[2]=Hf(e[2],e[1]>>>24),t};js.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return qf(t,t^1)>>8&255};function Lw(t){let e=new js(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 Mw(t){let e=new js(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 Nw(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Lw(n),o=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==a)throw Dw.WRONG_PASSWORD();return i(t.slice(12))}function Fw(t){Buffer.isBuffer(t)&&t.length>=12?Gs.genSalt=function(){return t.slice(0,12)}:t==="node"?Gs.genSalt=Ai.node:Gs.genSalt=Ai}function Bw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Mw(n),a=Gs.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)}Gf.exports={decrypt:Nw,encrypt:Bw,_salter:Fw}});var Wf=fe(Ws=>{Ws.Deflater=Ff();Ws.Inflater=zf();Ws.ZipCrypto=jf()});var xc=fe((ET,Kf)=>{var ue=Rr(),zw=uc(),Te=ue.Constants,hc=Wf();Kf.exports=function(t,e){var n=new zw.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,d=null,f=Buffer.alloc(0),u=Buffer.alloc(0),x=!0;let p=t,w=typeof p.decoder=="object"?p.decoder:ue.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function b(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(u=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(ue.crc32(E)!==n.localHeader.crc)return!1}else{let P={},D=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(D)==Te.LOCSIG||e.readUInt32LE(D)==Te.CENSIG)throw ue.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==Te.EXTSIG)P.crc=e.readUInt32LE(D+Te.EXTCRC),P.compressedSize=e.readUInt32LE(D+Te.EXTSIZ),P.size=e.readUInt32LE(D+Te.EXTLEN);else if(e.readUInt16LE(D+12)===19280)P.crc=e.readUInt32LE(D+Te.EXTCRC-4),P.compressedSize=e.readUInt32LE(D+Te.EXTSIZ-4),P.size=e.readUInt32LE(D+Te.EXTLEN-4);else throw ue.Errors.DESCRIPTOR_UNKNOWN();if(P.compressedSize!==n.compressedSize||P.size!==n.size||P.crc!==n.crc)throw ue.Errors.DESCRIPTOR_FAULTY();if(ue.crc32(E)!==P.crc)return!1}return!0}function v(E,P,D){if(typeof P>"u"&&typeof E=="string"&&(D=E,E=void 0),a)return E&&P&&P(Buffer.alloc(0),ue.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var U=b();if(U.length===0)return E&&P&&P(U),U;if(n.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw ue.Errors.INVALID_PASS_PARAM();U=hc.ZipCrypto.decrypt(U,n,D)}var N=Buffer.alloc(n.size);switch(n.method){case ue.Constants.STORED:if(U.copy(N),_(N))return E&&P&&P(N),N;throw E&&P&&P(N,ue.Errors.BAD_CRC()),ue.Errors.BAD_CRC();case ue.Constants.DEFLATED:var K=new hc.Inflater(U,n.size);if(E)K.inflateAsync(function(J){J.copy(J,0),P&&(_(J)?P(J):P(J,ue.Errors.BAD_CRC()))});else{if(K.inflate(N).copy(N,0),!_(N))throw ue.Errors.BAD_CRC(`"${w.decode(i)}"`);return N}break;default:throw E&&P&&P(Buffer.alloc(0),ue.Errors.UNKNOWN_METHOD()),ue.Errors.UNKNOWN_METHOD()}}function I(E,P){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&P&&P(b()),b();if(d.length&&!a){var D;switch(n.method){case ue.Constants.STORED:return n.compressedSize=n.size,D=Buffer.alloc(d.length),d.copy(D),E&&P&&P(D),D;default:case ue.Constants.DEFLATED:var U=new hc.Deflater(d);if(E)U.deflateAsync(function(K){D=Buffer.alloc(K.length),n.compressedSize=K.length,K.copy(D),P&&P(D)});else{var N=U.deflate();return n.compressedSize=N.length,N}U=null;break}}else if(E&&P)P(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,P){return ue.readBigUInt64LE(E,P)}function T(E){try{for(var P=0,D,U,N;P+4<E.length;)D=E.readUInt16LE(P),P+=2,U=E.readUInt16LE(P),P+=2,N=E.slice(P,P+U),P+=U,Te.ID_ZIP64===D&&R(N)}catch{throw ue.Errors.EXTRA_FIELD_PARSE_ERROR()}}function R(E){var P,D,U,N;E.length>=Te.EF_ZIP64_SCOMP&&(P=A(E,Te.EF_ZIP64_SUNCOMP),n.size===Te.EF_ZIP64_OR_32&&(n.size=P)),E.length>=Te.EF_ZIP64_RHO&&(D=A(E,Te.EF_ZIP64_SCOMP),n.compressedSize===Te.EF_ZIP64_OR_32&&(n.compressedSize=D)),E.length>=Te.EF_ZIP64_DSN&&(U=A(E,Te.EF_ZIP64_RHO),n.offset===Te.EF_ZIP64_OR_32&&(n.offset=U)),E.length>=Te.EF_ZIP64_DSN+4&&(N=E.readUInt32LE(Te.EF_ZIP64_DSN),n.diskNumStart===Te.EF_ZIP64_OR_16&&(n.diskNumStart=N))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(E){i=ue.toBuffer(E,w.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 f},set extra(E){f=E,n.extraLength=E.length,T(E)},get comment(){return w.decode(o)},set comment(E){if(o=ue.toBuffer(E,w.encode),n.commentLength=o.length,o.length>65535)throw ue.Errors.COMMENT_TOO_LONG()},get name(){var E=w.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=ue.toBuffer(E,ue.decoder.encode),!a&&d.length?(n.size=d.length,n.method=ue.Constants.DEFLATED,n.crc=ue.crc32(E),n.changed=!0):n.method=ue.Constants.STORED},getData:function(E){return n.changed?d:v(!1,null,E)},getDataAsync:function(E,P){n.changed?E(d):v(!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=f.length;var E=n.centralHeaderToBinary(),P=ue.Constants.CENHDR;return i.copy(E,P),P+=i.length,f.copy(E,P),P+=n.extraLength,o.copy(E,P),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=u.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,u.copy(D,E),E+=u.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 Jf=fe((bT,Vf)=>{var $f=xc(),Uw=uc(),Xe=Rr();Vf.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),a=new Uw.MainHeader,d=!1,f=null;let u=new Set,x=e,{noSort:p,decoder:w}=x;t?v(x.readEntries):d=!0;function b(){let A=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("/")+"/";A.add(P)}}for(let T of A)if(!(T in i)){let R=new $f(x);R.entryName=T,R.attr=16,R.temporary=!0,n.push(R),i[R.entryName]=R,u.add(R)}}function _(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Xe.Constants.CENHDR)throw Xe.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var A=a.offset,T=0;T<n.length;T++){var R=A,E=new $f(x,t);E.header=t.slice(R,R+=Xe.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)),A+=E.header.centralHeaderSize,n[T]=E,i[E.entryName]=E}u.clear(),b()}function v(A){var T=t.length-Xe.Constants.ENDHDR,R=Math.max(0,T-65535),E=R,P=t.length,D=-1,U=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(R=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===Xe.Constants.ENDSIG){D=T,U=T,P=T+Xe.Constants.ENDHDR,E=T-Xe.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Xe.Constants.END64SIG){E=R;continue}if(t.readUInt32LE(T)===Xe.Constants.ZIP64SIG){D=T,P=T+Xe.readBigUInt64LE(t,T+Xe.Constants.ZIP64SIZE)+Xe.Constants.ZIP64LEAD;break}}if(D==-1)throw Xe.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(D,P)),a.commentLength&&(o=t.slice(U+Xe.Constants.ENDHDR)),A&&_()}function I(){n.length>1&&!p&&n.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(A=>!u.has(A))},get comment(){return w.decode(o)},set comment(A){o=Xe.toBuffer(A,w.encode),a.commentLength=o.length},getEntryCount:function(){return d?n.length:a.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||_(),i[A]||null},setEntry:function(A){d||_(),n.push(A),i[A.entryName]=A,a.totalEntries=n.length},deleteFile:function(A,T=!0){d||_();let R=i[A];this.getEntryChildren(R,T).map(P=>P.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||_();let T=i[A],R=n.indexOf(T);R>=0&&(n.splice(R,1),delete i[A],a.totalEntries=n.length)},getEntryChildren:function(A,T=!0){if(d||_(),typeof A=="object")if(A.isDirectory&&T){let R=[],E=A.entryName;for(let P of n)P.entryName.startsWith(E)&&R.push(P);return R}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){d||_(),I();let A=[],T=[],R=0,E=0;a.size=0,a.offset=0;let P=0;for(let N of this.entries){let K=N.getCompressedData();N.header.offset=E;let J=N.packLocalHeader(),ie=J.length+K.length;E+=ie,A.push(J),A.push(K);let Y=N.packCentralHeader();T.push(Y),a.size+=Y.length,R+=ie+Y.length,P++}R+=a.mainHeaderSize,a.offset=E,a.totalEntries=P,E=0;let D=Buffer.alloc(R);for(let N of A)N.copy(D,E),E+=N.length;for(let N of T)N.copy(D,E),E+=N.length;let U=a.toBinary();return o&&o.copy(U,Xe.Constants.ENDHDR),U.copy(D,E),t=D,d=!1,D},toAsyncBuffer:function(A,T,R,E){try{d||_(),I();let P=[],D=[],U=0,N=0,K=0;a.size=0,a.offset=0;let J=function(ie){if(ie.length>0){let Y=ie.shift(),oe=Y.entryName+Y.extra.toString();R&&R(oe),Y.getCompressedDataAsync(function(le){E&&E(oe),Y.header.offset=N;let Ee=Y.packLocalHeader(),qe=Ee.length+le.length;N+=qe,P.push(Ee),P.push(le);let C=Y.packCentralHeader();D.push(C),a.size+=C.length,U+=qe+C.length,K++,J(ie)})}else{U+=a.mainHeaderSize,a.offset=N,a.totalEntries=K,N=0;let Y=Buffer.alloc(U);P.forEach(function(le){le.copy(Y,N),N+=le.length}),D.forEach(function(le){le.copy(Y,N),N+=le.length});let oe=a.toBinary();o&&o.copy(oe,Xe.Constants.ENDHDR),oe.copy(Y,N),t=Y,d=!1,A(Y)}};J(Array.from(this.entries))}catch(P){T(P)}}}}});var Yf=fe((vT,Xf)=>{var Ie=Rr(),Se=ge("path"),Hw=xc(),qw=Jf(),Wn=(...t)=>Ie.findLast(t,e=>typeof e=="boolean"),Zf=(...t)=>Ie.findLast(t,e=>typeof e=="string"),Gw=(...t)=>Ie.findLast(t,e=>typeof e=="function"),jw={noSort:!1,readEntries:!1,method:Ie.Constants.NONE,fs:null};Xf.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),jw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=Ie.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Ie(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ie.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Ie.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw Ie.Errors.INVALID_FILENAME();let a=new qw(n,i),{canonical:d,sanitize:f,zipnamefix:u}=Ie;function x(_){if(_&&a){var v;if(typeof _=="string"&&(v=a.getEntry(Se.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(v=a.getEntry(_.entryName)),v)return v}return null}function p(_){let{join:v,normalize:I,sep:A}=Se.posix;return v(Se.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function w(_){return _ instanceof RegExp?(function(v){return function(I){return v.test(I)}})(_):typeof _!="function"?()=>!0:_}let b=(_,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",Se.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 A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(_,v,I){var A=x(_);A?A.getDataAsync(function(T,R){if(R){v(T,R);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,A){if(o.fs.existsSync(_)){v=v?p(v):"";let T=Se.win32.basename(Se.win32.normalize(_));v+=I||T;let R=o.fs.statSync(_),E=R.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);R.isDirectory()&&(v+=o.sep),this.addFile(v,E,A,R)}else throw Ie.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,v){_=typeof _=="object"?_:{localPath:_};let I=Se.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:R}=_,E=this;o.fs.stat(I,function(P,D){if(P)return v(P,!1);T=T?p(T):"";let U=Se.win32.basename(Se.win32.normalize(I));if(T+=R||U,D.isFile())o.fs.readFile(I,function(N,K){return N?v(N,!1):(E.addFile(T,K,A,D),setImmediate(v,void 0,!0))});else if(D.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),A,D),setImmediate(v,void 0,!0)})},addLocalFolder:function(_,v,I){if(I=w(I),v=v?p(v):"",_=Se.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),T=this;if(A.length)for(let R of A){let E=Se.join(v,b(_,R));I(E)&&T.addLocalFile(R,Se.dirname(E))}}else throw Ie.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,v,I,A){A=w(A),I=I?p(I):"",_=Se.normalize(_);var T=this;o.fs.open(_,"r",function(R){if(R&&R.code==="ENOENT")v(void 0,Ie.Errors.FILE_NOT_FOUND(_));else if(R)v(void 0,R);else{var E=o.findFiles(_),P=-1,D=function(){if(P+=1,P<E.length){var U=E[P],N=b(_,U).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(N)?o.fs.stat(U,function(K,J){K&&v(void 0,K),J.isFile()?o.fs.readFile(U,function(ie,Y){ie?v(void 0,ie):(T.addFile(I+N,Y,"",J),D())}):(T.addFile(I+N+"/",Buffer.alloc(0),"",J),D())}):process.nextTick(()=>{D()})}else v(!0,void 0)};D()}})},addLocalFolderAsync2:function(_,v){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=Se.resolve(p(_.localPath));let{zipPath:A,filter:T,namefix:R}=_;T instanceof RegExp?T=(function(D){return function(U){return D.test(U)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?p(A):"",R=="latin1"&&(R=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof R!="function"&&(R=D=>D);let E=D=>Se.join(A,R(b(localPath,D))),P=D=>Se.win32.basename(Se.win32.normalize(R(D)));o.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?v(void 0,Ie.Errors.FILE_NOT_FOUND(localPath)):D?v(void 0,D):o.findFilesAsync(localPath,function(U,N){if(U)return v(U);N=N.filter(K=>T(E(K))),N.length||v(void 0,!1),setImmediate(N.reverse().reduce(function(K,J){return function(ie,Y){if(ie||Y===!1)return setImmediate(K,ie,!1);I.addLocalFileAsync({localPath:J,zipPath:Se.dirname(E(J)),zipName:P(J)},K)}},v))})})},addLocalFolderPromise:function(_,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},v),(T,R)=>{T&&A(T),R&&I(this)})})},addFile:function(_,v,I,A){_=u(_);let T=x(_),R=T!=null;R||(T=new Hw(i),T.entryName=_),T.comment=I||"";let E=typeof A=="object"&&A instanceof o.fs.Stats;E&&(T.header.time=A.mtime);var P=T.isDirectory?16:0;let D=T.isDirectory?16384:32768;return E?D|=4095&A.mode:typeof A=="number"?D|=4095&A:D|=T.isDirectory?493:420,P=(P|D<<16)>>>0,T.attr=P,T.setData(v),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(_,v,I,A,T,R){A=Wn(!1,A),T=Wn(!1,T),I=Wn(!0,I),R=Zf(T,R);var E=x(_);if(!E)throw Ie.Errors.NO_ENTRY();var P=d(E.entryName),D=f(v,R&&!E.isDirectory?R:I?P:Se.basename(P));if(E.isDirectory){var U=a.getEntryChildren(E);return U.forEach(function(J){if(J.isDirectory)return;var ie=J.getData();if(!ie)throw Ie.Errors.CANT_EXTRACT_FILE();var Y=d(J.entryName),oe=f(v,I?Y:Se.basename(Y));let le=T?J.header.fileAttr:void 0;o.writeFileTo(oe,ie,A,le)}),!0}var N=E.getData(a.password);if(!N)throw Ie.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(D)&&!A)throw Ie.Errors.CANT_OVERRIDE();let K=T?_.header.fileAttr:void 0;return o.writeFileTo(D,N,A,K),!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,A){if(I=Wn(!1,I),A=Zf(I,A),v=Wn(!1,v),!a)throw Ie.Errors.NO_ZIP();a.entries.forEach(function(T){var R=f(_,d(T.entryName));if(T.isDirectory){o.makeDir(R);return}var E=T.getData(A);if(!E)throw Ie.Errors.CANT_EXTRACT_FILE();let P=I?T.header.fileAttr:void 0;o.writeFileTo(R,E,v,P);try{o.fs.utimesSync(R,T.header.time,T.header.time)}catch{throw Ie.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,v,I,A){if(A=Gw(v,I,A),I=Wn(!1,I),v=Wn(!1,v),!A)return new Promise((D,U)=>{this.extractAllToAsync(_,v,I,function(N){N?U(N):D(this)})});if(!a){A(Ie.Errors.NO_ZIP());return}_=Se.resolve(_);let T=D=>f(_,Se.normalize(d(D.entryName))),R=(D,U)=>new Error(D+': "'+U+'"'),E=[],P=[];a.entries.forEach(D=>{D.isDirectory?E.push(D):P.push(D)});for(let D of E){let U=T(D),N=I?D.header.fileAttr:void 0;try{o.makeDir(U),N&&o.fs.chmodSync(U,N),o.fs.utimesSync(U,D.header.time,D.header.time)}catch{A(R("Unable to create folder",U))}}P.reverse().reduce(function(D,U){return function(N){if(N)D(N);else{let K=Se.normalize(d(U.entryName)),J=f(_,K);U.getDataAsync(function(ie,Y){if(Y)D(Y);else if(!ie)D(Ie.Errors.CANT_EXTRACT_FILE());else{let oe=I?U.header.fileAttr:void 0;o.writeFileToAsync(J,ie,v,oe,function(le){le||D(R("Unable to write file",J)),o.fs.utimes(J,U.header.time,U.header.time,function(Ee){Ee?D(R("Unable to set times",J)):D()})})}})}}},A)()},writeZip:function(_,v){if(arguments.length===1&&typeof _=="function"&&(v=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=a.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((T,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,I,A,P)},R)})},toBufferPromise:function(){return new Promise((_,v)=>{a.toAsyncBuffer(_,v)})},toBuffer:function(_,v,I,A){return typeof _=="function"?(a.toAsyncBuffer(_,v,I,A),null):a.compressToBuffer()}}}});import{execFile as Qy,spawn as eE,spawnSync as WC}from"node:child_process";import{promisify as tE}from"node:util";function rE(t){if(process.platform!=="win32")return!1;if(A0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(A0,"").toLowerCase();return nE.has(n)}function k0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return rE(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function dt(t,e=[],n={}){return eE(t,e,k0(t,n))}function Oo(t,e=[],n={}){return iE(t,e,k0(t,n))}var nE,A0,iE,Wt=ot(()=>{"use strict";nE=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),A0=/\.(cmd|bat|ps1)$/i;iE=tE(Qy)});var un=fe((wO,Lx)=>{"use strict";var Dx=["nodebuffer","arraybuffer","fragments"],Ox=typeof Blob<"u";Ox&&Dx.push("blob");Lx.exports={BINARY_TYPES:Dx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ox,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var gs=fe((_O,aa)=>{"use strict";var{EMPTY_BUFFER:RS}=un(),Yd=Buffer[Symbol.species];function PS(t,e){if(t.length===0)return RS;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 Yd(n.buffer,n.byteOffset,i):n}function Mx(t,e,n,i,o){for(let a=0;a<o;a++)n[i+a]=t[a]^e[a&3]}function Nx(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function DS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Qd(t){if(Qd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Yd(t):ArrayBuffer.isView(t)?e=new Yd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Qd.readOnly=!1),e}aa.exports={concat:PS,mask:Mx,toArrayBuffer:DS,toBuffer:Qd,unmask:Nx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ge("bufferutil");aa.exports.mask=function(e,n,i,o,a){a<48?Mx(e,n,i,o,a):t.mask(e,n,i,o,a)},aa.exports.unmask=function(e,n){e.length<32?Nx(e,n):t.unmask(e,n)}}catch{}});var zx=fe((yO,Bx)=>{"use strict";var Fx=Symbol("kDone"),el=Symbol("kRun"),tl=class{constructor(e){this[Fx]=()=>{this.pending--,this[el]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[el]()}[el](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Fx])}}};Bx.exports=tl});var ai=fe((EO,Gx)=>{"use strict";var ms=ge("zlib"),Ux=gs(),OS=zx(),{kStatusCode:Hx}=un(),LS=Buffer[Symbol.species],MS=Buffer.from([0,0,255,255]),da=Symbol("permessage-deflate"),hn=Symbol("total-length"),si=Symbol("callback"),zn=Symbol("buffers"),oi=Symbol("error"),ca,nl=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,!ca){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ca=new OS(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[si];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){ca.add(o=>{this._decompress(e,n,(a,d)=>{o(),i(a,d)})})}compress(e,n,i){ca.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"?ms.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=ms.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[da]=this,this._inflate[hn]=0,this._inflate[zn]=[],this._inflate.on("error",FS),this._inflate.on("data",qx)}this._inflate[si]=i,this._inflate.write(e),n&&this._inflate.write(MS),this._inflate.flush(()=>{let a=this._inflate[oi];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=Ux.concat(this._inflate[zn],this._inflate[hn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[hn]=0,this._inflate[zn]=[],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"?ms.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=ms.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[hn]=0,this._deflate[zn]=[],this._deflate.on("data",NS)}this._deflate[si]=i,this._deflate.write(e),this._deflate.flush(ms.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=Ux.concat(this._deflate[zn],this._deflate[hn]);n&&(a=new LS(a.buffer,a.byteOffset,a.length-4)),this._deflate[si]=null,this._deflate[hn]=0,this._deflate[zn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};Gx.exports=nl;function NS(t){this[zn].push(t),this[hn]+=t.length}function qx(t){if(this[hn]+=t.length,this[da]._maxPayload<1||this[hn]<=this[da]._maxPayload){this[zn].push(t);return}this[oi]=new RangeError("Max payload size exceeded"),this[oi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[oi][Hx]=1009,this.removeListener("data",qx),this.reset()}function FS(t){if(this[da]._inflate=null,this[oi]){this[si](this[oi]);return}t[Hx]=1007,this[si](t)}});var ci=fe((bO,la)=>{"use strict";var{isUtf8:jx}=ge("buffer"),{hasBlob:BS}=un(),zS=[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 US(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function rl(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 HS(t){return BS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}la.exports={isBlob:HS,isValidStatusCode:US,isValidUTF8:rl,tokenChars:zS};if(jx)la.exports.isValidUTF8=function(t){return t.length<24?rl(t):jx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ge("utf-8-validate");la.exports.isValidUTF8=function(e){return e.length<32?rl(e):t(e)}}catch{}});var cl=fe((vO,Xx)=>{"use strict";var{Writable:qS}=ge("stream"),Wx=ai(),{BINARY_TYPES:GS,EMPTY_BUFFER:Kx,kStatusCode:jS,kWebSocket:WS}=un(),{concat:il,toArrayBuffer:KS,unmask:$S}=gs(),{isValidStatusCode:VS,isValidUTF8:$x}=ci(),fa=Buffer[Symbol.species],It=0,Vx=1,Jx=2,Zx=3,sl=4,ol=5,ua=6,al=class extends qS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||GS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[WS]=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=It}_write(e,n,i){if(this._opcode===8&&this._state==It)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 fa(i.buffer,i.byteOffset+e,i.length-e),new fa(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 fa(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 It:this.getInfo(e);break;case Vx:this.getPayloadLength16(e);break;case Jx:this.getPayloadLength64(e);break;case Zx:this.getMask();break;case sl:this.getData(e);break;case ol:case ua: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[Wx.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=Vx:this._payloadLength===127?this._state=Jx: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=Zx:this._state=sl}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=sl}getData(e){let n=Kx;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&&$S(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=ol,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Wx.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===It&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=It;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=il(i,n):this._binaryType==="arraybuffer"?o=KS(il(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=It):(this._state=ua,setImmediate(()=>{this.emit("message",o,!0),this._state=It,this.startLoop(e)}))}else{let o=il(i,n);if(!this._skipUTF8Validation&&!$x(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===ol||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=It):(this._state=ua,setImmediate(()=>{this.emit("message",o,!1),this._state=It,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Kx),this.end();else{let i=e.readUInt16BE(0);if(!VS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let o=new fa(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$x(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=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=ua,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,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[jS]=o,d}};Xx.exports=al});var fl=fe((IO,ep)=>{"use strict";var{Duplex:SO}=ge("stream"),{randomFillSync:JS}=ge("crypto"),Yx=ai(),{EMPTY_BUFFER:ZS,kWebSocket:XS,NOOP:YS}=un(),{isBlob:di,isValidStatusCode:QS}=ci(),{mask:Qx,toBuffer:ur}=gs(),At=Symbol("kByteLength"),e1=Buffer.alloc(4),ha=8*1024,hr,li=ha,Nt=0,t1=1,n1=2,dl=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=Nt,this.onerror=YS,this[XS]=void 0}static frame(e,n){let i,o=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||e1,n.generateMask?n.generateMask(i):(li===ha&&(hr===void 0&&(hr=Buffer.alloc(ha)),JS(hr,0,ha),li=0),i[0]=hr[li++],i[1]=hr[li++],i[2]=hr[li++],i[3]=hr[li++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let f;typeof e=="string"?(!n.mask||d)&&n[At]!==void 0?f=n[At]:(e=Buffer.from(e),f=e.length):(f=e.length,o=n.mask&&n.readOnly&&!d);let u=f;f>=65536?(a+=8,u=127):f>125&&(a+=2,u=126);let x=Buffer.allocUnsafe(o?f+a:a);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=u,u===126?x.writeUInt16BE(f,2):u===127&&(x[2]=x[3]=0,x.writeUIntBE(f,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?(Qx(e,i,x,a,f),[x]):(Qx(e,i,e,0,f),[x,e])):[x,e]}close(e,n,i,o){let a;if(e===void 0)a=ZS;else{if(typeof e!="number"||!QS(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 f=Buffer.byteLength(n);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");a=Buffer.allocUnsafe(2+f),a.writeUInt16BE(e,0),typeof n=="string"?a.write(n,2):a.set(n,2)}}let d={[At]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Nt?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):di(e)?(o=e.size,a=!1):(e=ur(e),o=e.length,a=ur.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[At]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};di(e)?this._state!==Nt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Nt?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):di(e)?(o=e.size,a=!1):(e=ur(e),o=e.length,a=ur.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[At]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};di(e)?this._state!==Nt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Nt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[Yx.extensionName],a=n.binary?2:1,d=n.compress,f,u;typeof e=="string"?(f=Buffer.byteLength(e),u=!1):di(e)?(f=e.size,u=!1):(e=ur(e),f=e.length,u=ur.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=f>=o._threshold),this._compress=d):(d=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[At]:f,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:u,rsv1:d};di(e)?this._state!==Nt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Nt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[At],this._state=n1,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(ll,this,f,o);return}this._bufferedBytes-=i[At];let d=ur(a);n?this.dispatch(d,n,i,o):(this._state=Nt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(a=>{process.nextTick(r1,this,a,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let a=this._extensions[Yx.extensionName];this._bufferedBytes+=i[At],this._state=t1,a.compress(e,i.fin,(d,f)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");ll(this,u,o);return}this._bufferedBytes-=i[At],this._state=Nt,i.readOnly=!1,this.sendFrame(t.frame(f,i),o),this.dequeue()})}dequeue(){for(;this._state===Nt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][At],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][At],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)}};ep.exports=dl;function ll(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 r1(t,e,n){ll(t,e,n),t.onerror(e)}});var dp=fe((AO,cp)=>{"use strict";var{kForOnEventAttribute:ws,kListener:ul}=un(),tp=Symbol("kCode"),np=Symbol("kData"),rp=Symbol("kError"),ip=Symbol("kMessage"),sp=Symbol("kReason"),fi=Symbol("kTarget"),op=Symbol("kType"),ap=Symbol("kWasClean"),xn=class{constructor(e){this[fi]=null,this[op]=e}get target(){return this[fi]}get type(){return this[op]}};Object.defineProperty(xn.prototype,"target",{enumerable:!0});Object.defineProperty(xn.prototype,"type",{enumerable:!0});var xr=class extends xn{constructor(e,n={}){super(e),this[tp]=n.code===void 0?0:n.code,this[sp]=n.reason===void 0?"":n.reason,this[ap]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[tp]}get reason(){return this[sp]}get wasClean(){return this[ap]}};Object.defineProperty(xr.prototype,"code",{enumerable:!0});Object.defineProperty(xr.prototype,"reason",{enumerable:!0});Object.defineProperty(xr.prototype,"wasClean",{enumerable:!0});var ui=class extends xn{constructor(e,n={}){super(e),this[rp]=n.error===void 0?null:n.error,this[ip]=n.message===void 0?"":n.message}get error(){return this[rp]}get message(){return this[ip]}};Object.defineProperty(ui.prototype,"error",{enumerable:!0});Object.defineProperty(ui.prototype,"message",{enumerable:!0});var _s=class extends xn{constructor(e,n={}){super(e),this[np]=n.data===void 0?null:n.data}get data(){return this[np]}};Object.defineProperty(_s.prototype,"data",{enumerable:!0});var i1={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[ws]&&o[ul]===e&&!o[ws])return;let i;if(t==="message")i=function(a,d){let f=new _s("message",{data:d?a:a.toString()});f[fi]=this,xa(e,this,f)};else if(t==="close")i=function(a,d){let f=new xr("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[fi]=this,xa(e,this,f)};else if(t==="error")i=function(a){let d=new ui("error",{error:a,message:a.message});d[fi]=this,xa(e,this,d)};else if(t==="open")i=function(){let a=new xn("open");a[fi]=this,xa(e,this,a)};else return;i[ws]=!!n[ws],i[ul]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ul]===e&&!n[ws]){this.removeListener(t,n);break}}};cp.exports={CloseEvent:xr,ErrorEvent:ui,Event:xn,EventTarget:i1,MessageEvent:_s};function xa(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var pa=fe((kO,lp)=>{"use strict";var{tokenChars:ys}=ci();function Zt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function s1(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,a=!1,d,f,u=-1,x=-1,p=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(p===-1&&ys[x]===1)u===-1&&(u=w);else if(w!==0&&(x===32||x===9))p===-1&&u!==-1&&(p=w);else if(x===59||x===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w);let _=t.slice(u,p);x===44?(Zt(e,_,n),n=Object.create(null)):d=_,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(f===void 0)if(p===-1&&ys[x]===1)u===-1&&(u=w);else if(x===32||x===9)p===-1&&u!==-1&&(p=w);else if(x===59||x===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w),Zt(n,t.slice(u,p),!0),x===44&&(Zt(e,d,n),n=Object.create(null),d=void 0),u=p=-1}else if(x===61&&u!==-1&&p===-1)f=t.slice(u,w),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(ys[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);u===-1?u=w:i||(i=!0),o=!1}else if(a)if(ys[x]===1)u===-1&&(u=w);else if(x===34&&u!==-1)a=!1,p=w;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)a=!0;else if(p===-1&&ys[x]===1)u===-1&&(u=w);else if(u!==-1&&(x===32||x===9))p===-1&&(p=w);else if(x===59||x===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w);let _=t.slice(u,p);i&&(_=_.replace(/\\/g,""),i=!1),Zt(n,f,_),x===44&&(Zt(e,d,n),n=Object.create(null),d=void 0),f=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(u===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=w);let b=t.slice(u,p);return d===void 0?Zt(e,b,n):(f===void 0?Zt(n,b,!0):i?Zt(n,f,b.replace(/\\/g,"")):Zt(n,f,b),Zt(e,d,n)),e}function o1(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(", ")}lp.exports={format:o1,parse:s1}});var _a=fe((RO,bp)=>{"use strict";var a1=ge("events"),c1=ge("https"),d1=ge("http"),hp=ge("net"),l1=ge("tls"),{randomBytes:f1,createHash:u1}=ge("crypto"),{Duplex:TO,Readable:CO}=ge("stream"),{URL:hl}=ge("url"),Un=ai(),h1=cl(),x1=fl(),{isBlob:p1}=ci(),{BINARY_TYPES:fp,CLOSE_TIMEOUT:g1,EMPTY_BUFFER:ga,GUID:m1,kForOnEventAttribute:xl,kListener:w1,kStatusCode:_1,kWebSocket:$e,NOOP:xp}=un(),{EventTarget:{addEventListener:y1,removeEventListener:E1}}=dp(),{format:b1,parse:v1}=pa(),{toBuffer:S1}=gs(),pp=Symbol("kAborted"),pl=[8,13],pn=["CONNECTING","OPEN","CLOSING","CLOSED"],I1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ye=class t extends a1{constructor(e,n,i){super(),this._binaryType=fp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ga,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]),gp(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){fp.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 h1({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new x1(e,this._extensions,i.generateMask);this._receiver=o,this._sender=a,this._socket=e,o[$e]=this,a[$e]=this,e[$e]=this,o.on("conclude",T1),o.on("drain",C1),o.on("error",R1),o.on("message",P1),o.on("ping",D1),o.on("pong",O1),a.onerror=L1,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",_p),e.on("data",wa),e.on("end",yp),e.on("error",Ep),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[Un.extensionName]&&this._extensions[Un.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){gt(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())}),wp(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){gl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ga,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){gl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ga,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){gl(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Un.extensionName]||(o.compress=!1),this._sender.send(e||ga,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){gt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ye,"CONNECTING",{enumerable:!0,value:pn.indexOf("CONNECTING")});Object.defineProperty(ye.prototype,"CONNECTING",{enumerable:!0,value:pn.indexOf("CONNECTING")});Object.defineProperty(ye,"OPEN",{enumerable:!0,value:pn.indexOf("OPEN")});Object.defineProperty(ye.prototype,"OPEN",{enumerable:!0,value:pn.indexOf("OPEN")});Object.defineProperty(ye,"CLOSING",{enumerable:!0,value:pn.indexOf("CLOSING")});Object.defineProperty(ye.prototype,"CLOSING",{enumerable:!0,value:pn.indexOf("CLOSING")});Object.defineProperty(ye,"CLOSED",{enumerable:!0,value:pn.indexOf("CLOSED")});Object.defineProperty(ye.prototype,"CLOSED",{enumerable:!0,value:pn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ye.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ye.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[xl])return e[w1];return null},set(e){for(let n of this.listeners(t))if(n[xl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[xl]:!0})}})});ye.prototype.addEventListener=y1;ye.prototype.removeEventListener=E1;bp.exports=ye;function gp(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:g1,protocolVersion:pl[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,!pl.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${pl.join(", ")})`);let a;if(e instanceof hl)a=e;else try{a=new hl(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:",f=a.protocol==="ws+unix:",u;if(a.protocol!=="ws:"&&!d&&!f?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!a.pathname?u="The URL's pathname is empty":a.hash&&(u="The URL contains a fragment identifier"),u){let I=new SyntaxError(u);if(t._redirects===0)throw I;ma(t,I);return}let x=d?443:80,p=f1(16).toString("base64"),w=d?c1.request:d1.request,b=new Set,_;if(o.createConnection=o.createConnection||(d?k1:A1),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 Un({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=b1({[Un.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!I1.test(I)||b.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.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}`),f){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=f,t._originalSecure=d,t._originalHostOrSocketPath=f?o.socketPath:a.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,T]of Object.entries(I))i.headers[A.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=f?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=w(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=w(o);o.timeout&&v.on("timeout",()=>{gt(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[pp]||(v=t._req=null,ma(t,I))}),v.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){gt(t,v,"Maximum redirects exceeded");return}v.abort();let R;try{R=new hl(A,e)}catch{let P=new SyntaxError(`Invalid URL: ${A}`);ma(t,P);return}gp(t,R,n,i)}else t.emit("unexpected-response",v,I)||gt(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==ye.CONNECTING)return;v=t._req=null;let R=I.headers.upgrade;if(R===void 0||R.toLowerCase()!=="websocket"){gt(t,A,"Invalid Upgrade header");return}let E=u1("sha1").update(p+m1).digest("base64");if(I.headers["sec-websocket-accept"]!==E){gt(t,A,"Invalid Sec-WebSocket-Accept header");return}let P=I.headers["sec-websocket-protocol"],D;if(P!==void 0?b.size?b.has(P)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":b.size&&(D="Server sent no subprotocol"),D){gt(t,A,D);return}P&&(t._protocol=P);let U=I.headers["sec-websocket-extensions"];if(U!==void 0){if(!_){gt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=v1(U)}catch{gt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let K=Object.keys(N);if(K.length!==1||K[0]!==Un.extensionName){gt(t,A,"Server indicated an extension that was not requested");return}try{_.accept(N[Un.extensionName])}catch{gt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Un.extensionName]=_}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(v,t):v.end()}function ma(t,e){t._readyState=ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function A1(t){return t.path=t.socketPath,hp.connect(t)}function k1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hp.isIP(t.host)?"":t.host),l1.connect(t)}function gt(t,e,n){t._readyState=ye.CLOSING;let i=new Error(n);Error.captureStackTrace(i,gt),e.setHeader?(e[pp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ma,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function gl(t,e,n){if(e){let i=p1(e)?e.size:S1(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${pn[t.readyState]})`);process.nextTick(n,i)}}function T1(t,e){let n=this[$e];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[$e]!==void 0&&(n._socket.removeListener("data",wa),process.nextTick(mp,n._socket),t===1005?n.close():n.close(t,e))}function C1(){let t=this[$e];t.isPaused||t._socket.resume()}function R1(t){let e=this[$e];e._socket[$e]!==void 0&&(e._socket.removeListener("data",wa),process.nextTick(mp,e._socket),e.close(t[_1])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function up(){this[$e].emitClose()}function P1(t,e){this[$e].emit("message",t,e)}function D1(t){let e=this[$e];e._autoPong&&e.pong(t,!this._isServer,xp),e.emit("ping",t)}function O1(t){this[$e].emit("pong",t)}function mp(t){t.resume()}function L1(t){let e=this[$e];e.readyState!==ye.CLOSED&&(e.readyState===ye.OPEN&&(e._readyState=ye.CLOSING,wp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function wp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function _p(){let t=this[$e];if(this.removeListener("close",_p),this.removeListener("data",wa),this.removeListener("end",yp),t._readyState=ye.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[$e]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",up),t._receiver.on("finish",up))}function wa(t){this[$e]._receiver.write(t)||this.pause()}function yp(){let t=this[$e];t._readyState=ye.CLOSING,t._receiver.end(),this.end()}function Ep(){let t=this[$e];this.removeListener("error",Ep),this.on("error",xp),t&&(t._readyState=ye.CLOSING,this.destroy())}});var Ap=fe((DO,Ip)=>{"use strict";var PO=_a(),{Duplex:M1}=ge("stream");function vp(t){t.emit("close")}function N1(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Sp(t){this.removeListener("error",Sp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function F1(t,e){let n=!0,i=new M1({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,d){let f=!d&&i._readableState.objectMode?a.toString():a;i.push(f)||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(vp,i);return}let d=!1;t.once("error",function(u){d=!0,a(u)}),t.once("close",function(){d||a(o),process.nextTick(vp,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",N1),i.on("error",Sp),i}Ip.exports=F1});var ml=fe((OO,kp)=>{"use strict";var{tokenChars:B1}=ci();function z1(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&&B1[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 f=t.slice(n,i);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),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}kp.exports={parse:z1}});var Lp=fe((MO,Op)=>{"use strict";var U1=ge("events"),ya=ge("http"),{Duplex:LO}=ge("stream"),{createHash:H1}=ge("crypto"),Tp=pa(),pr=ai(),q1=ml(),G1=_a(),{CLOSE_TIMEOUT:j1,GUID:W1,kWebSocket:K1}=un(),$1=/^[+/0-9A-Za-z]{22}==$/,Cp=0,Rp=1,Dp=2,wl=class extends U1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:j1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:G1,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ya.createServer((i,o)=>{let a=ya.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=V1(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=Cp}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===Dp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Es,this);return}if(e&&this.once("close",e),this._state!==Rp)if(this._state=Rp,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(Es,this):process.nextTick(Es,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Es(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",Pp);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){gr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){gr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!$1.test(a)){gr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){gr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){bs(n,400);return}let u=e.headers["sec-websocket-protocol"],x=new Set;if(u!==void 0)try{x=q1.parse(u)}catch{gr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&p!==void 0){let b=new pr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Tp.parse(p);_[pr.extensionName]&&(b.accept(_[pr.extensionName]),w[pr.extensionName]=b)}catch{gr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(_,v,I,A)=>{if(!_)return bs(n,v||401,I,A);this.completeUpgrade(w,a,x,e,n,i,o)});return}if(!this.options.verifyClient(b))return bs(n,401)}this.completeUpgrade(w,a,x,e,n,i,o)}completeUpgrade(e,n,i,o,a,d,f){if(!a.readable||!a.writable)return a.destroy();if(a[K1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Cp)return bs(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${H1("sha1").update(n+W1).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),p._protocol=w)}if(e[pr.extensionName]){let w=e[pr.extensionName].params,b=Tp.format({[pr.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${b}`),p._extensions=e}this.emit("headers",x,o),a.write(x.concat(`\r
|
|
10
|
+
`),this.stream=void 0;return}this.currentDate!==void 0&&Ls(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 Km,mkdirSync as $m}from"node:fs";import{join as Vm}from"node:path";function iu(t){let e=t.retentionDays??Ym,n=t.clock??(()=>Vn(new Date));Ns={bridgeSink:new Si(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new Si(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();Ls(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])Ls(t.agentLogsDir(o),"agent",i,e)}function Xm(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function su(t){sc=t}function ou(t){return Cr[sc]<=Cr[t]}function au(t,e){let n=Cr[t];return n===void 0?!0:n>=Cr[e]}function Fs(t){ru={...t}}function cu(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`${Vn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function ut(t,e,n,i,o){try{let a=`${JSON.stringify({ts:cu(new Date),level:e,module:n,msg:i,...o})}
|
|
11
|
+
`;$m(t,{recursive:!0}),Km(Vm(t,kr("bridge",Vn(new Date))),a)}catch{}}function Qm(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function Ms(t,e,n,i,o){if(Cr[t]<Cr[sc])return;let a=`${JSON.stringify({ts:cu(new Date),level:t,module:e,msg:n,...ru,...i})}
|
|
12
|
+
`;if(Ns){let d=Qm(o,i),u=d?Xm(Ns,d):Ns.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?Zm.write(a):Jm.write(a)}function H(t,e){return{debug:(n,i)=>Ms("debug",t,n,i,e),info:(n,i)=>Ms("info",t,n,i,e),warn:(n,i)=>Ms("warn",t,n,i,e),error:(n,i)=>Ms("error",t,n,i,e),child:n=>H(`${t}.${n}`,e),forAgent:n=>H(t,n)}}var Cr,sc,Jm,Zm,ru,Ym,Ns,re=lt(()=>{"use strict";Ar();ic();Cr={debug:10,info:20,warn:30,error:40},sc=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Jm=process.stdout,Zm=process.stderr,ru={},Ym=Xe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Ns=null});var k,Qe=lt(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,n,i){super(n),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var fu={};nc(fu,{ACP_WRAPPER_NPM_PACKAGES:()=>zs,_resetAcpInstallerForTests:()=>sw,_setBinaryPathCacheForTests:()=>ow,buildAcpSpawn:()=>Ii,ensureAcpInstalled:()=>Pr,getAcpBinaryPath:()=>Us,pickWhichLine:()=>cc,probeAcpVersion:()=>iw,resolveAcpCommand:()=>uu});import{readFileSync as du}from"node:fs";import{createRequire as ew}from"node:module";import{dirname as tw,resolve as nw}from"node:path";function ac(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function cc(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 rw(t){let e=lu.resolve(`${t.npmPackage}/package.json`),n=tw(e),i=JSON.parse(du(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 nw(n,o)}async function Pr(t,e){let n=oc[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=Tr.get(t);if(i)return i;let o=ac(t);if(o)return Tr.set(t,o),Bs.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let a=rw(n);return Tr.set(t,a),Bs.info("acp wrapper resolved",{framework:t,binary:n.binary,path:a}),a}catch(a){throw Bs.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 k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${n.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
|
|
13
|
+
`),{cause:a})}}async function iw(t){let e=oc[t];if(e)try{let n=lu.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(du(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Bs.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function Us(t){return Tr.get(t)}function uu(t,e){if(e)return e;let n=ac(t);if(n)return n;let i=Us(t);if(!i)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function Ii(t,e,n){if(e)return{command:e,args:[...n]};let i=ac(t);if(i)return{command:i,args:[...n]};let o=uu(t);return{command:process.execPath,args:[o,...n]}}function sw(){Tr.clear()}function ow(t,e){Tr.set(t,e)}var Bs,oc,zs,lu,Tr,In=lt(()=>{"use strict";Qe();re();Bs=H("agents.acp-installer"),oc={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},zs=Object.values(oc).filter(t=>t!==void 0).map(t=>t.npmPackage),lu=ew(import.meta.url),Tr=new Map});import{chmod as cw,mkdir as dw,readFile as lw,rename as uw,rm as fw,writeFile as hw}from"node:fs/promises";import{dirname as pw}from"node:path";async function rt(t){try{let e=await lw(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function vt(t,e,n){await dw(pw(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await hw(i,e,{encoding:"utf8",mode:n?.mode}),await uw(i,t),n?.mode!==void 0&&await cw(t,n.mode)}catch(o){throw await fw(i,{force:!0}).catch(()=>{}),o}}async function gt(t,e,n){await vt(t,`${JSON.stringify(e,null,2)}
|
|
14
|
+
`,n)}var Dt=lt(()=>{"use strict"});import{promises as xu,readdirSync as xw}from"node:fs";import{homedir as gw}from"node:os";import{sep as mw,join as Re,resolve as gu}from"node:path";function Z(t){let e=t??gw(),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"),modelCacheFile:Re(i,"model-cache.json"),agentsRoot:Re(n,"agents")}}function Ne(t,e=Z()){let n=Re(e.agentsRoot,t);return{root:n,config:Re(n,"config.json"),workspace:Re(n,"workspace"),logs:Re(n,"logs")}}function Hs(t=Z()){try{return xw(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function Ai(t,e){let n=await xu.realpath(gu(t)).catch(()=>null);if(!n)return!1;let i=await xu.realpath(gu(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+mw)}var De=lt(()=>{"use strict"});var qs={};nc(qs,{AGENT_CONFIG_FILE_MODE:()=>Gs,enforceAgentConfigMode:()=>yw,loadAgentConfig:()=>ye,persistAgentSessions:()=>ki,persistAgentSkills:()=>Ci,saveAgentConfig:()=>Oe});import{chmod as ww,stat as _w}from"node:fs/promises";function ye(t,e){return rt(Ne(t,e).config)}function Oe(t,e){return gt(Ne(t.agentId,e).config,t,{mode:Gs})}async function yw(t,e){if(process.platform==="win32")return;let n=Ne(t,e).config;try{let i=await _w(n);if(!i.isFile())return;let o=i.mode&511;o!==Gs&&(await ww(n,Gs),mu.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;mu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function ki(t,e,n){let i=await ye(t,n);i&&(i.sessions=Object.fromEntries(e),await Oe(i,n))}async function Ci(t,e,n){let i=await ye(t,n);i&&(i.skills=e,await Oe(i,n))}var mu,Gs,an=lt(()=>{"use strict";Dt();re();De();mu=H("agent-config"),Gs=384});var uc=ue((cC,yu)=>{yu.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Ws=ue(Eu=>{var bu={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 Aw(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(bu))Eu[t]=Aw(bu[t])});var ku=ue((lC,Au)=>{var kw=we("fs"),He=we("path"),vu=uc(),Cw=Ws(),Tw=typeof process=="object"&&process.platform==="win32",Su=t=>typeof t=="object"&&t!==null,Iu=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 Ce(t){this.sep=He.sep,this.fs=kw,Su(t)&&Su(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Au.exports=Ce;Ce.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 Cw.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};Ce.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=He.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};Ce.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 p=He.dirname(t);a.fs.exists(p,function(x){x||a.makeDir(p),a.fs.open(t,"w",438,function(g,v){g?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(w,E){a.fs.write(E,e,0,e.length,0,function(){a.fs.close(E,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)})})})})})};Ce.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=He.join(i,u),p=e.fs.statSync(f);(!o||o.test(f))&&d.push(He.normalize(f)+(p.isDirectory()?e.sep:"")),p.isDirectory()&&a&&(d=d.concat(n(f,o,a)))}),d}return n(t,void 0,!0)};Ce.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=He.join(t,u),n.fs.stat(u,function(f,p){if(f)return e(f);p&&(i.push(He.normalize(u)+(p.isDirectory()?n.sep:"")),p.isDirectory()?n.findFilesAsync(u,function(x,g){if(x)return e(x);i=i.concat(g),--d||e(null,i)}):--d||e(null,i))})})})};Ce.prototype.getAttributes=function(){};Ce.prototype.setAttributes=function(){};Ce.crc32update=function(t,e){return Iu[(t^e)&255]^t>>>8};Ce.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Ce.crc32update(n,t[i++]);return~n>>>0};Ce.methodToString=function(t){switch(t){case vu.STORED:return"STORED ("+t+")";case vu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ce.canonical=function(t){if(!t)return"";let e=He.posix.normalize("/"+t.split("\\").join("/"));return He.join(".",e)};Ce.zipnamefix=function(t){if(!t)return"";let e=He.posix.normalize("/"+t.split("\\").join("/"));return He.posix.join(".",e)};Ce.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]};Ce.sanitize=function(t,e){t=He.resolve(He.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var a=He.normalize(He.join(t,n.slice(i,o).join(He.sep)));if(a.indexOf(t)===0)return a}return He.normalize(He.join(t,He.basename(e)))};Ce.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Ce.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Ce.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)};Ce.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};Ce.isWin=Tw;Ce.crcTable=Iu});var Tu=ue((uC,Cu)=>{var Pw=we("path");Cu.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=Pw.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 Ru=ue((fC,Pu)=>{Pu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var Or=ue((hC,Dr)=>{Dr.exports=ku();Dr.exports.Constants=uc();Dr.exports.Errors=Ws();Dr.exports.FileAttr=Tu();Dr.exports.decoder=Ru()});var Ou=ue((pC,Du)=>{var An=Or(),B=An.Constants;Du.exports=function(){var t=20,e=10,n=0,i=0,o=0,a=0,d=0,u=0,f=0,p=0,x=0,g=0,v=0,w=0,E=0;t|=An.isWin?2560:768,n|=B.FLG_EFS;let S={extraLen:0},A=y=>Math.max(0,y)>>>0,C=y=>Math.max(0,y)&65535,P=y=>Math.max(0,y)&255;return o=An.fromDate2DOS(new Date),{get made(){return t},set made(y){t=y},get version(){return e},set version(y){e=y},get flags(){return n},set flags(y){n=y},get flags_efs(){return(n&B.FLG_EFS)>0},set flags_efs(y){y?n|=B.FLG_EFS:n&=~B.FLG_EFS},get flags_desc(){return(n&B.FLG_DESC)>0},set flags_desc(y){y?n|=B.FLG_DESC:n&=~B.FLG_DESC},get method(){return i},set method(y){switch(y){case B.STORED:this.version=10;case B.DEFLATED:default:this.version=20}i=y},get time(){return An.fromDOS2Date(this.timeval)},set time(y){y=new Date(y),this.timeval=An.fromDate2DOS(y)},get timeval(){return o},set timeval(y){o=A(y)},get timeHighByte(){return P(o>>>8)},get crc(){return a},set crc(y){a=A(y)},get compressedSize(){return d},set compressedSize(y){d=A(y)},get size(){return u},set size(y){u=A(y)},get fileNameLength(){return f},set fileNameLength(y){f=y},get extraLength(){return p},set extraLength(y){p=y},get extraLocalLength(){return S.extraLen},set extraLocalLength(y){S.extraLen=y},get commentLength(){return x},set commentLength(y){x=y},get diskNumStart(){return g},set diskNumStart(y){g=A(y)},get inAttr(){return v},set inAttr(y){v=A(y)},get attr(){return w},set attr(y){w=A(y)},get fileAttr(){return(w||0)>>16&4095},get offset(){return E},set offset(y){E=A(y)},get encrypted(){return(n&B.FLG_ENC)===B.FLG_ENC},get centralHeaderSize(){return B.CENHDR+f+p+x},get realDataOffset(){return E+B.LOCHDR+S.fnameLen+S.extraLen},get localHeader(){return S},loadLocalHeaderFromBinary:function(y){var R=y.slice(E,E+B.LOCHDR);if(R.readUInt32LE(0)!==B.LOCSIG)throw An.Errors.INVALID_LOC();S.version=R.readUInt16LE(B.LOCVER),S.flags=R.readUInt16LE(B.LOCFLG),S.flags_desc=(S.flags&B.FLG_DESC)>0,S.method=R.readUInt16LE(B.LOCHOW),S.time=R.readUInt32LE(B.LOCTIM),S.crc=R.readUInt32LE(B.LOCCRC),S.compressedSize=R.readUInt32LE(B.LOCSIZ),S.size=R.readUInt32LE(B.LOCLEN),S.fnameLen=R.readUInt16LE(B.LOCNAM),S.extraLen=R.readUInt16LE(B.LOCEXT);let D=E+B.LOCHDR+S.fnameLen,z=D+S.extraLen;return y.slice(D,z)},loadFromBinary:function(y){if(y.length!==B.CENHDR||y.readUInt32LE(0)!==B.CENSIG)throw An.Errors.INVALID_CEN();t=y.readUInt16LE(B.CENVEM),e=y.readUInt16LE(B.CENVER),n=y.readUInt16LE(B.CENFLG),i=y.readUInt16LE(B.CENHOW),o=y.readUInt32LE(B.CENTIM),a=y.readUInt32LE(B.CENCRC),d=y.readUInt32LE(B.CENSIZ),u=y.readUInt32LE(B.CENLEN),f=y.readUInt16LE(B.CENNAM),p=y.readUInt16LE(B.CENEXT),x=y.readUInt16LE(B.CENCOM),g=y.readUInt16LE(B.CENDSK),v=y.readUInt16LE(B.CENATT),w=y.readUInt32LE(B.CENATX),E=y.readUInt32LE(B.CENOFF)},localHeaderToBinary:function(){var y=Buffer.alloc(B.LOCHDR);return y.writeUInt32LE(B.LOCSIG,0),y.writeUInt16LE(e,B.LOCVER),y.writeUInt16LE(n,B.LOCFLG),y.writeUInt16LE(i,B.LOCHOW),y.writeUInt32LE(o,B.LOCTIM),y.writeUInt32LE(a,B.LOCCRC),y.writeUInt32LE(d,B.LOCSIZ),y.writeUInt32LE(u,B.LOCLEN),y.writeUInt16LE(f,B.LOCNAM),y.writeUInt16LE(S.extraLen,B.LOCEXT),y},centralHeaderToBinary:function(){var y=Buffer.alloc(B.CENHDR+f+p+x);return y.writeUInt32LE(B.CENSIG,0),y.writeUInt16LE(t,B.CENVEM),y.writeUInt16LE(e,B.CENVER),y.writeUInt16LE(n,B.CENFLG),y.writeUInt16LE(i,B.CENHOW),y.writeUInt32LE(o,B.CENTIM),y.writeUInt32LE(a,B.CENCRC),y.writeUInt32LE(d,B.CENSIZ),y.writeUInt32LE(u,B.CENLEN),y.writeUInt16LE(f,B.CENNAM),y.writeUInt16LE(p,B.CENEXT),y.writeUInt16LE(x,B.CENCOM),y.writeUInt16LE(g,B.CENDSK),y.writeUInt16LE(v,B.CENATT),y.writeUInt32LE(w,B.CENATX),y.writeUInt32LE(E,B.CENOFF),y},toJSON:function(){let y=function(R){return R+" bytes"};return{made:t,version:e,flags:n,method:An.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:y(d),size:y(u),fileNameLength:y(f),extraLength:y(p),commentLength:y(x),diskNumStart:g,inAttr:v,attr:w,offset:E,centralHeaderSize:y(B.CENHDR+f+p+x)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Mu=ue((xC,Lu)=>{var Lr=Or(),Ie=Lr.Constants;Lu.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 Ie.ENDHDR+o},loadFromBinary:function(a){if((a.length!==Ie.ENDHDR||a.readUInt32LE(0)!==Ie.ENDSIG)&&(a.length<Ie.ZIP64HDR||a.readUInt32LE(0)!==Ie.ZIP64SIG))throw Lr.Errors.INVALID_END();a.readUInt32LE(0)===Ie.ENDSIG?(t=a.readUInt16LE(Ie.ENDSUB),e=a.readUInt16LE(Ie.ENDTOT),n=a.readUInt32LE(Ie.ENDSIZ),i=a.readUInt32LE(Ie.ENDOFF),o=a.readUInt16LE(Ie.ENDCOM)):(t=Lr.readBigUInt64LE(a,Ie.ZIP64SUB),e=Lr.readBigUInt64LE(a,Ie.ZIP64TOT),n=Lr.readBigUInt64LE(a,Ie.ZIP64SIZE),i=Lr.readBigUInt64LE(a,Ie.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(Ie.ENDHDR+o);return a.writeUInt32LE(Ie.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,Ie.ENDSUB),a.writeUInt16LE(e,Ie.ENDTOT),a.writeUInt32LE(n,Ie.ENDSIZ),a.writeUInt32LE(i,Ie.ENDOFF),a.writeUInt16LE(o,Ie.ENDCOM),a.fill(" ",Ie.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 hc=ue(fc=>{fc.EntryHeader=Ou();fc.MainHeader=Mu()});var Fu=ue((mC,Nu)=>{Nu.exports=function(t){var e=we("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 p=0;p<a.length;p++){var x=a[p];x.copy(u,f),f+=x.length}i&&i(u)}),o.end(t)}}}});var zu=ue((wC,Bu)=>{var Rw=+(process.versions?process.versions.node:"").split(".")[0]||0;Bu.exports=function(t,e){var n=we("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),p=0;f.fill(0);for(var x=0;x<d.length;x++){var g=d[x];g.copy(f,p),p+=g.length}o&&o(f)}),a.end(t)}}}});var ju=ue((_C,qu)=>{"use strict";var{randomFillSync:Uu}=we("crypto"),Dw=Ws(),Ow=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Gu=(t,e)=>Math.imul(t,e)>>>0,Hu=(t,e)=>Ow[(t^e)&255]^t>>>8,Ti=()=>typeof Uu=="function"?Uu(Buffer.alloc(12)):Ti.node();Ti.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 Ks={genSalt:Ti};function $s(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])}$s.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Hu(e[0],t),e[1]+=e[0]&255,e[1]=Gu(e[1],134775813)+1,e[2]=Hu(e[2],e[1]>>>24),t};$s.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Gu(t,t^1)>>8&255};function Lw(t){let e=new $s(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 Mw(t){let e=new $s(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 Nw(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Lw(n),o=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==a)throw Dw.WRONG_PASSWORD();return i(t.slice(12))}function Fw(t){Buffer.isBuffer(t)&&t.length>=12?Ks.genSalt=function(){return t.slice(0,12)}:t==="node"?Ks.genSalt=Ti.node:Ks.genSalt=Ti}function Bw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Mw(n),a=Ks.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)}qu.exports={decrypt:Nw,encrypt:Bw,_salter:Fw}});var Wu=ue(Vs=>{Vs.Deflater=Fu();Vs.Inflater=zu();Vs.ZipCrypto=ju()});var xc=ue((bC,Ku)=>{var fe=Or(),zw=hc(),Te=fe.Constants,pc=Wu();Ku.exports=function(t,e){var n=new zw.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),p=!0;let x=t,g=typeof x.decoder=="object"?x.decoder:fe.decoder;p=g.hasOwnProperty("efs")?g.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 w(y){if(!n.flags_desc&&!n.localHeader.flags_desc){if(fe.crc32(y)!==n.localHeader.crc)return!1}else{let R={},D=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(D)==Te.LOCSIG||e.readUInt32LE(D)==Te.CENSIG)throw fe.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==Te.EXTSIG)R.crc=e.readUInt32LE(D+Te.EXTCRC),R.compressedSize=e.readUInt32LE(D+Te.EXTSIZ),R.size=e.readUInt32LE(D+Te.EXTLEN);else if(e.readUInt16LE(D+12)===19280)R.crc=e.readUInt32LE(D+Te.EXTCRC-4),R.compressedSize=e.readUInt32LE(D+Te.EXTSIZ-4),R.size=e.readUInt32LE(D+Te.EXTLEN-4);else throw fe.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==n.compressedSize||R.size!==n.size||R.crc!==n.crc)throw fe.Errors.DESCRIPTOR_FAULTY();if(fe.crc32(y)!==R.crc)return!1}return!0}function E(y,R,D){if(typeof R>"u"&&typeof y=="string"&&(D=y,y=void 0),a)return y&&R&&R(Buffer.alloc(0),fe.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var z=v();if(z.length===0)return y&&R&&R(z),z;if(n.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw fe.Errors.INVALID_PASS_PARAM();z=pc.ZipCrypto.decrypt(z,n,D)}var M=Buffer.alloc(n.size);switch(n.method){case fe.Constants.STORED:if(z.copy(M),w(M))return y&&R&&R(M),M;throw y&&R&&R(M,fe.Errors.BAD_CRC()),fe.Errors.BAD_CRC();case fe.Constants.DEFLATED:var W=new pc.Inflater(z,n.size);if(y)W.inflateAsync(function(K){K.copy(K,0),R&&(w(K)?R(K):R(K,fe.Errors.BAD_CRC()))});else{if(W.inflate(M).copy(M,0),!w(M))throw fe.Errors.BAD_CRC(`"${g.decode(i)}"`);return M}break;default:throw y&&R&&R(Buffer.alloc(0),fe.Errors.UNKNOWN_METHOD()),fe.Errors.UNKNOWN_METHOD()}}function S(y,R){if((!d||!d.length)&&Buffer.isBuffer(e))return y&&R&&R(v()),v();if(d.length&&!a){var D;switch(n.method){case fe.Constants.STORED:return n.compressedSize=n.size,D=Buffer.alloc(d.length),d.copy(D),y&&R&&R(D),D;default:case fe.Constants.DEFLATED:var z=new pc.Deflater(d);if(y)z.deflateAsync(function(W){D=Buffer.alloc(W.length),n.compressedSize=W.length,W.copy(D),R&&R(D)});else{var M=z.deflate();return n.compressedSize=M.length,M}z=null;break}}else if(y&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(y,R){return fe.readBigUInt64LE(y,R)}function C(y){try{for(var R=0,D,z,M;R+4<y.length;)D=y.readUInt16LE(R),R+=2,z=y.readUInt16LE(R),R+=2,M=y.slice(R,R+z),R+=z,Te.ID_ZIP64===D&&P(M)}catch{throw fe.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(y){var R,D,z,M;y.length>=Te.EF_ZIP64_SCOMP&&(R=A(y,Te.EF_ZIP64_SUNCOMP),n.size===Te.EF_ZIP64_OR_32&&(n.size=R)),y.length>=Te.EF_ZIP64_RHO&&(D=A(y,Te.EF_ZIP64_SCOMP),n.compressedSize===Te.EF_ZIP64_OR_32&&(n.compressedSize=D)),y.length>=Te.EF_ZIP64_DSN&&(z=A(y,Te.EF_ZIP64_RHO),n.offset===Te.EF_ZIP64_OR_32&&(n.offset=z)),y.length>=Te.EF_ZIP64_DSN+4&&(M=y.readUInt32LE(Te.EF_ZIP64_DSN),n.diskNumStart===Te.EF_ZIP64_OR_16&&(n.diskNumStart=M))}return{get entryName(){return g.decode(i)},get rawEntryName(){return i},set entryName(y){i=fe.toBuffer(y,g.encode);var R=i[i.length-1];a=R===47||R===92,n.fileNameLength=i.length},get efs(){return typeof p=="function"?p(this.entryName):p},get extra(){return u},set extra(y){u=y,n.extraLength=y.length,C(y)},get comment(){return g.decode(o)},set comment(y){if(o=fe.toBuffer(y,g.encode),n.commentLength=o.length,o.length>65535)throw fe.Errors.COMMENT_TOO_LONG()},get name(){var y=g.decode(i);return a?y.substr(y.length-1).split("/").pop():y.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return S(!1,null)},getCompressedDataAsync:function(y){S(!0,y)},setData:function(y){d=fe.toBuffer(y,fe.decoder.encode),!a&&d.length?(n.size=d.length,n.method=fe.Constants.DEFLATED,n.crc=fe.crc32(y),n.changed=!0):n.method=fe.Constants.STORED},getData:function(y){return n.changed?d:E(!1,null,y)},getDataAsync:function(y,R){n.changed?y(d):E(!0,y,R)},set attr(y){n.attr=y},get attr(){return n.attr},set header(y){n.loadFromBinary(y)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var y=n.centralHeaderToBinary(),R=fe.Constants.CENHDR;return i.copy(y,R),R+=i.length,u.copy(y,R),R+=n.extraLength,o.copy(y,R),y},packLocalHeader:function(){let y=0;n.flags_efs=this.efs,n.extraLocalLength=f.length;let R=n.localHeaderToBinary(),D=Buffer.alloc(R.length+i.length+n.extraLocalLength);return R.copy(D,y),y+=R.length,i.copy(D,y),y+=i.length,f.copy(D,y),y+=f.length,D},toJSON:function(){let y=function(R){return"<"+(R&&R.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:y(e),data:y(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ju=ue((EC,Vu)=>{var $u=xc(),Uw=hc(),et=Or();Vu.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),a=new Uw.MainHeader,d=!1,u=null;let f=new Set,p=e,{noSort:x,decoder:g}=p;t?E(p.readEntries):d=!0;function v(){let A=new Set;for(let C of Object.keys(i)){let P=C.split("/");if(P.pop(),!!P.length)for(let y=0;y<P.length;y++){let R=P.slice(0,y+1).join("/")+"/";A.add(R)}}for(let C of A)if(!(C in i)){let P=new $u(p);P.entryName=C,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,f.add(P)}}function w(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/et.Constants.CENHDR)throw et.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var A=a.offset,C=0;C<n.length;C++){var P=A,y=new $u(p,t);y.header=t.slice(P,P+=et.Constants.CENHDR),y.entryName=t.slice(P,P+=y.header.fileNameLength),y.header.extraLength&&(y.extra=t.slice(P,P+=y.header.extraLength)),y.header.commentLength&&(y.comment=t.slice(P,P+y.header.commentLength)),A+=y.header.centralHeaderSize,n[C]=y,i[y.entryName]=y}f.clear(),v()}function E(A){var C=t.length-et.Constants.ENDHDR,P=Math.max(0,C-65535),y=P,R=t.length,D=-1,z=0;for(typeof p.trailingSpace=="boolean"&&p.trailingSpace&&(P=0),C;C>=y;C--)if(t[C]===80){if(t.readUInt32LE(C)===et.Constants.ENDSIG){D=C,z=C,R=C+et.Constants.ENDHDR,y=C-et.Constants.END64HDR;continue}if(t.readUInt32LE(C)===et.Constants.END64SIG){y=P;continue}if(t.readUInt32LE(C)===et.Constants.ZIP64SIG){D=C,R=C+et.readBigUInt64LE(t,C+et.Constants.ZIP64SIZE)+et.Constants.ZIP64LEAD;break}}if(D==-1)throw et.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(D,R)),a.commentLength&&(o=t.slice(z+et.Constants.ENDHDR)),A&&w()}function S(){n.length>1&&!x&&n.sort((A,C)=>A.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return d||w(),n.filter(A=>!f.has(A))},get comment(){return g.decode(o)},set comment(A){o=et.toBuffer(A,g.encode),a.commentLength=o.length},getEntryCount:function(){return d?n.length:a.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||w(),i[A]||null},setEntry:function(A){d||w(),n.push(A),i[A.entryName]=A,a.totalEntries=n.length},deleteFile:function(A,C=!0){d||w();let P=i[A];this.getEntryChildren(P,C).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||w();let C=i[A],P=n.indexOf(C);P>=0&&(n.splice(P,1),delete i[A],a.totalEntries=n.length)},getEntryChildren:function(A,C=!0){if(d||w(),typeof A=="object")if(A.isDirectory&&C){let P=[],y=A.entryName;for(let R of n)R.entryName.startsWith(y)&&P.push(R);return P}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let C=this.getEntryChildren(A);return C.includes(A)?C.length-1:C.length}return 0},compressToBuffer:function(){d||w(),S();let A=[],C=[],P=0,y=0;a.size=0,a.offset=0;let R=0;for(let M of this.entries){let W=M.getCompressedData();M.header.offset=y;let K=M.packLocalHeader(),se=K.length+W.length;y+=se,A.push(K),A.push(W);let Q=M.packCentralHeader();C.push(Q),a.size+=Q.length,P+=se+Q.length,R++}P+=a.mainHeaderSize,a.offset=y,a.totalEntries=R,y=0;let D=Buffer.alloc(P);for(let M of A)M.copy(D,y),y+=M.length;for(let M of C)M.copy(D,y),y+=M.length;let z=a.toBinary();return o&&o.copy(z,et.Constants.ENDHDR),z.copy(D,y),t=D,d=!1,D},toAsyncBuffer:function(A,C,P,y){try{d||w(),S();let R=[],D=[],z=0,M=0,W=0;a.size=0,a.offset=0;let K=function(se){if(se.length>0){let Q=se.shift(),ae=Q.entryName+Q.extra.toString();P&&P(ae),Q.getCompressedDataAsync(function(le){y&&y(ae),Q.header.offset=M;let Se=Q.packLocalHeader(),je=Se.length+le.length;M+=je,R.push(Se),R.push(le);let T=Q.packCentralHeader();D.push(T),a.size+=T.length,z+=je+T.length,W++,K(se)})}else{z+=a.mainHeaderSize,a.offset=M,a.totalEntries=W,M=0;let Q=Buffer.alloc(z);R.forEach(function(le){le.copy(Q,M),M+=le.length}),D.forEach(function(le){le.copy(Q,M),M+=le.length});let ae=a.toBinary();o&&o.copy(ae,et.Constants.ENDHDR),ae.copy(Q,M),t=Q,d=!1,A(Q)}};K(Array.from(this.entries))}catch(R){C(R)}}}}});var Xu=ue((vC,Yu)=>{var ke=Or(),Ae=we("path"),Hw=xc(),Gw=Ju(),Jn=(...t)=>ke.findLast(t,e=>typeof e=="boolean"),Zu=(...t)=>ke.findLast(t,e=>typeof e=="string"),qw=(...t)=>ke.findLast(t,e=>typeof e=="function"),jw={noSort:!1,readEntries:!1,method:ke.Constants.NONE,fs:null};Yu.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),jw);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=ke.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new ke(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=ke.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=ke.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw ke.Errors.INVALID_FILENAME();let a=new Gw(n,i),{canonical:d,sanitize:u,zipnamefix:f}=ke;function p(w){if(w&&a){var E;if(typeof w=="string"&&(E=a.getEntry(Ae.posix.normalize(w))),typeof w=="object"&&typeof w.entryName<"u"&&typeof w.header<"u"&&(E=a.getEntry(w.entryName)),E)return E}return null}function x(w){let{join:E,normalize:S,sep:A}=Ae.posix;return E(Ae.isAbsolute(w)?"/":".",S(A+w.split("\\").join(A)+A))}function g(w){return w instanceof RegExp?(function(E){return function(S){return E.test(S)}})(w):typeof w!="function"?()=>!0:w}let v=(w,E)=>{let S=E.slice(-1);return S=S===o.sep?o.sep:"",Ae.relative(w,E)+S};return{readFile:function(w,E){var S=p(w);return S&&S.getData(E)||null},childCount:function(w){let E=p(w);if(E)return a.getChildCount(E)},readFileAsync:function(w,E){var S=p(w);S?S.getDataAsync(E):E(null,"getEntry failed for:"+w)},readAsText:function(w,E){var S=p(w);if(S){var A=S.getData();if(A&&A.length)return A.toString(E||"utf8")}return""},readAsTextAsync:function(w,E,S){var A=p(w);A?A.getDataAsync(function(C,P){if(P){E(C,P);return}C&&C.length?E(C.toString(S||"utf8")):E("")}):E("")},deleteFile:function(w,E=!0){var S=p(w);S&&a.deleteFile(S.entryName,E)},deleteEntry:function(w){var E=p(w);E&&a.deleteEntry(E.entryName)},addZipComment:function(w){a.comment=w},getZipComment:function(){return a.comment||""},addZipEntryComment:function(w,E){var S=p(w);S&&(S.comment=E)},getZipEntryComment:function(w){var E=p(w);return E&&E.comment||""},updateFile:function(w,E){var S=p(w);S&&S.setData(E)},addLocalFile:function(w,E,S,A){if(o.fs.existsSync(w)){E=E?x(E):"";let C=Ae.win32.basename(Ae.win32.normalize(w));E+=S||C;let P=o.fs.statSync(w),y=P.isFile()?o.fs.readFileSync(w):Buffer.alloc(0);P.isDirectory()&&(E+=o.sep),this.addFile(E,y,A,P)}else throw ke.Errors.FILE_NOT_FOUND(w)},addLocalFileAsync:function(w,E){w=typeof w=="object"?w:{localPath:w};let S=Ae.resolve(w.localPath),{comment:A}=w,{zipPath:C,zipName:P}=w,y=this;o.fs.stat(S,function(R,D){if(R)return E(R,!1);C=C?x(C):"";let z=Ae.win32.basename(Ae.win32.normalize(S));if(C+=P||z,D.isFile())o.fs.readFile(S,function(M,W){return M?E(M,!1):(y.addFile(C,W,A,D),setImmediate(E,void 0,!0))});else if(D.isDirectory())return C+=o.sep,y.addFile(C,Buffer.alloc(0),A,D),setImmediate(E,void 0,!0)})},addLocalFolder:function(w,E,S){if(S=g(S),E=E?x(E):"",w=Ae.normalize(w),o.fs.existsSync(w)){let A=o.findFiles(w),C=this;if(A.length)for(let P of A){let y=Ae.join(E,v(w,P));S(y)&&C.addLocalFile(P,Ae.dirname(y))}}else throw ke.Errors.FILE_NOT_FOUND(w)},addLocalFolderAsync:function(w,E,S,A){A=g(A),S=S?x(S):"",w=Ae.normalize(w);var C=this;o.fs.open(w,"r",function(P){if(P&&P.code==="ENOENT")E(void 0,ke.Errors.FILE_NOT_FOUND(w));else if(P)E(void 0,P);else{var y=o.findFiles(w),R=-1,D=function(){if(R+=1,R<y.length){var z=y[R],M=v(w,z).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?o.fs.stat(z,function(W,K){W&&E(void 0,W),K.isFile()?o.fs.readFile(z,function(se,Q){se?E(void 0,se):(C.addFile(S+M,Q,"",K),D())}):(C.addFile(S+M+"/",Buffer.alloc(0),"",K),D())}):process.nextTick(()=>{D()})}else E(!0,void 0)};D()}})},addLocalFolderAsync2:function(w,E){let S=this;w=typeof w=="object"?w:{localPath:w},localPath=Ae.resolve(x(w.localPath));let{zipPath:A,filter:C,namefix:P}=w;C instanceof RegExp?C=(function(D){return function(z){return D.test(z)}})(C):typeof C!="function"&&(C=function(){return!0}),A=A?x(A):"",P=="latin1"&&(P=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=D=>D);let y=D=>Ae.join(A,P(v(localPath,D))),R=D=>Ae.win32.basename(Ae.win32.normalize(P(D)));o.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?E(void 0,ke.Errors.FILE_NOT_FOUND(localPath)):D?E(void 0,D):o.findFilesAsync(localPath,function(z,M){if(z)return E(z);M=M.filter(W=>C(y(W))),M.length||E(void 0,!1),setImmediate(M.reverse().reduce(function(W,K){return function(se,Q){if(se||Q===!1)return setImmediate(W,se,!1);S.addLocalFileAsync({localPath:K,zipPath:Ae.dirname(y(K)),zipName:R(K)},W)}},E))})})},addLocalFolderPromise:function(w,E){return new Promise((S,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:w},E),(C,P)=>{C&&A(C),P&&S(this)})})},addFile:function(w,E,S,A){w=f(w);let C=p(w),P=C!=null;P||(C=new Hw(i),C.entryName=w),C.comment=S||"";let y=typeof A=="object"&&A instanceof o.fs.Stats;y&&(C.header.time=A.mtime);var R=C.isDirectory?16:0;let D=C.isDirectory?16384:32768;return y?D|=4095&A.mode:typeof A=="number"?D|=4095&A:D|=C.isDirectory?493:420,R=(R|D<<16)>>>0,C.attr=R,C.setData(E),P||a.setEntry(C),C},getEntries:function(w){return a.password=w,a?a.entries:[]},getEntry:function(w){return p(w)},getEntryCount:function(){return a.getEntryCount()},forEach:function(w){return a.forEach(w)},extractEntryTo:function(w,E,S,A,C,P){A=Jn(!1,A),C=Jn(!1,C),S=Jn(!0,S),P=Zu(C,P);var y=p(w);if(!y)throw ke.Errors.NO_ENTRY();var R=d(y.entryName),D=u(E,P&&!y.isDirectory?P:S?R:Ae.basename(R));if(y.isDirectory){var z=a.getEntryChildren(y);return z.forEach(function(K){if(K.isDirectory)return;var se=K.getData();if(!se)throw ke.Errors.CANT_EXTRACT_FILE();var Q=d(K.entryName),ae=u(E,S?Q:Ae.basename(Q));let le=C?K.header.fileAttr:void 0;o.writeFileTo(ae,se,A,le)}),!0}var M=y.getData(a.password);if(!M)throw ke.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(D)&&!A)throw ke.Errors.CANT_OVERRIDE();let W=C?w.header.fileAttr:void 0;return o.writeFileTo(D,M,A,W),!0},test:function(w){if(!a)return!1;for(var E in a.entries)try{if(E.isDirectory)continue;var S=a.entries[E].getData(w);if(!S)return!1}catch{return!1}return!0},extractAllTo:function(w,E,S,A){if(S=Jn(!1,S),A=Zu(S,A),E=Jn(!1,E),!a)throw ke.Errors.NO_ZIP();a.entries.forEach(function(C){var P=u(w,d(C.entryName));if(C.isDirectory){o.makeDir(P);return}var y=C.getData(A);if(!y)throw ke.Errors.CANT_EXTRACT_FILE();let R=S?C.header.fileAttr:void 0;o.writeFileTo(P,y,E,R);try{o.fs.utimesSync(P,C.header.time,C.header.time)}catch{throw ke.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(w,E,S,A){if(A=qw(E,S,A),S=Jn(!1,S),E=Jn(!1,E),!A)return new Promise((D,z)=>{this.extractAllToAsync(w,E,S,function(M){M?z(M):D(this)})});if(!a){A(ke.Errors.NO_ZIP());return}w=Ae.resolve(w);let C=D=>u(w,Ae.normalize(d(D.entryName))),P=(D,z)=>new Error(D+': "'+z+'"'),y=[],R=[];a.entries.forEach(D=>{D.isDirectory?y.push(D):R.push(D)});for(let D of y){let z=C(D),M=S?D.header.fileAttr:void 0;try{o.makeDir(z),M&&o.fs.chmodSync(z,M),o.fs.utimesSync(z,D.header.time,D.header.time)}catch{A(P("Unable to create folder",z))}}R.reverse().reduce(function(D,z){return function(M){if(M)D(M);else{let W=Ae.normalize(d(z.entryName)),K=u(w,W);z.getDataAsync(function(se,Q){if(Q)D(Q);else if(!se)D(ke.Errors.CANT_EXTRACT_FILE());else{let ae=S?z.header.fileAttr:void 0;o.writeFileToAsync(K,se,E,ae,function(le){le||D(P("Unable to write file",K)),o.fs.utimes(K,z.header.time,z.header.time,function(Se){Se?D(P("Unable to set times",K)):D()})})}})}}},A)()},writeZip:function(w,E){if(arguments.length===1&&typeof w=="function"&&(E=w,w=""),!w&&i.filename&&(w=i.filename),!!w){var S=a.compressToBuffer();if(S){var A=o.writeFileTo(w,S,!0);typeof E=="function"&&E(A?null:new Error("failed"),"")}}},writeZipPromise:function(w,E){let{overwrite:S,perm:A}=Object.assign({overwrite:!0},E);return new Promise((C,P)=>{!w&&i.filename&&(w=i.filename),w||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(y=>{let R=D=>D?C(D):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(w,y,S,A,R)},P)})},toBufferPromise:function(){return new Promise((w,E)=>{a.toAsyncBuffer(w,E)})},toBuffer:function(w,E,S,A){return typeof w=="function"?(a.toAsyncBuffer(w,E,S,A),null):a.compressToBuffer()}}}});import{execFile as Qy,spawn as eb,spawnSync as WT}from"node:child_process";import{promisify as tb}from"node:util";function rb(t){if(process.platform!=="win32")return!1;if(k0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(k0,"").toLowerCase();return nb.has(n)}function C0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return rb(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function ht(t,e=[],n={}){return eb(t,e,C0(t,n))}function No(t,e=[],n={}){return ib(t,e,C0(t,n))}var nb,k0,ib,Vt=lt(()=>{"use strict";nb=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),k0=/\.(cmd|bat|ps1)$/i;ib=tb(Qy)});var mn=ue((wO,Lp)=>{"use strict";var Dp=["nodebuffer","arraybuffer","fragments"],Op=typeof Blob<"u";Op&&Dp.push("blob");Lp.exports={BINARY_TYPES:Dp,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Op,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var _s=ue((_O,la)=>{"use strict";var{EMPTY_BUFFER:PS}=mn(),Qd=Buffer[Symbol.species];function RS(t,e){if(t.length===0)return PS;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 Qd(n.buffer,n.byteOffset,i):n}function Mp(t,e,n,i,o){for(let a=0;a<o;a++)n[i+a]=t[a]^e[a&3]}function Np(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function DS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function el(t){if(el.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Qd(t):ArrayBuffer.isView(t)?e=new Qd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),el.readOnly=!1),e}la.exports={concat:RS,mask:Mp,toArrayBuffer:DS,toBuffer:el,unmask:Np};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=we("bufferutil");la.exports.mask=function(e,n,i,o,a){a<48?Mp(e,n,i,o,a):t.mask(e,n,i,o,a)},la.exports.unmask=function(e,n){e.length<32?Np(e,n):t.unmask(e,n)}}catch{}});var zp=ue((yO,Bp)=>{"use strict";var Fp=Symbol("kDone"),tl=Symbol("kRun"),nl=class{constructor(e){this[Fp]=()=>{this.pending--,this[tl]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[tl]()}[tl](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Fp])}}};Bp.exports=nl});var li=ue((bO,qp)=>{"use strict";var ys=we("zlib"),Up=_s(),OS=zp(),{kStatusCode:Hp}=mn(),LS=Buffer[Symbol.species],MS=Buffer.from([0,0,255,255]),fa=Symbol("permessage-deflate"),wn=Symbol("total-length"),ci=Symbol("callback"),Hn=Symbol("buffers"),di=Symbol("error"),ua,rl=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,!ua){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ua=new OS(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[ci];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){ua.add(o=>{this._decompress(e,n,(a,d)=>{o(),i(a,d)})})}compress(e,n,i){ua.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"?ys.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=ys.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[fa]=this,this._inflate[wn]=0,this._inflate[Hn]=[],this._inflate.on("error",FS),this._inflate.on("data",Gp)}this._inflate[ci]=i,this._inflate.write(e),n&&this._inflate.write(MS),this._inflate.flush(()=>{let a=this._inflate[di];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=Up.concat(this._inflate[Hn],this._inflate[wn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[wn]=0,this._inflate[Hn]=[],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"?ys.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=ys.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[wn]=0,this._deflate[Hn]=[],this._deflate.on("data",NS)}this._deflate[ci]=i,this._deflate.write(e),this._deflate.flush(ys.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=Up.concat(this._deflate[Hn],this._deflate[wn]);n&&(a=new LS(a.buffer,a.byteOffset,a.length-4)),this._deflate[ci]=null,this._deflate[wn]=0,this._deflate[Hn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};qp.exports=rl;function NS(t){this[Hn].push(t),this[wn]+=t.length}function Gp(t){if(this[wn]+=t.length,this[fa]._maxPayload<1||this[wn]<=this[fa]._maxPayload){this[Hn].push(t);return}this[di]=new RangeError("Max payload size exceeded"),this[di].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[di][Hp]=1009,this.removeListener("data",Gp),this.reset()}function FS(t){if(this[fa]._inflate=null,this[di]){this[ci](this[di]);return}t[Hp]=1007,this[ci](t)}});var ui=ue((EO,ha)=>{"use strict";var{isUtf8:jp}=we("buffer"),{hasBlob:BS}=mn(),zS=[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 US(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function il(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 HS(t){return BS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ha.exports={isBlob:HS,isValidStatusCode:US,isValidUTF8:il,tokenChars:zS};if(jp)ha.exports.isValidUTF8=function(t){return t.length<24?il(t):jp(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=we("utf-8-validate");ha.exports.isValidUTF8=function(e){return e.length<32?il(e):t(e)}}catch{}});var dl=ue((vO,Yp)=>{"use strict";var{Writable:GS}=we("stream"),Wp=li(),{BINARY_TYPES:qS,EMPTY_BUFFER:Kp,kStatusCode:jS,kWebSocket:WS}=mn(),{concat:sl,toArrayBuffer:KS,unmask:$S}=_s(),{isValidStatusCode:VS,isValidUTF8:$p}=ui(),pa=Buffer[Symbol.species],Tt=0,Vp=1,Jp=2,Zp=3,ol=4,al=5,xa=6,cl=class extends GS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||qS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[WS]=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=Tt}_write(e,n,i){if(this._opcode===8&&this._state==Tt)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 pa(i.buffer,i.byteOffset+e,i.length-e),new pa(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 pa(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 Tt:this.getInfo(e);break;case Vp:this.getPayloadLength16(e);break;case Jp:this.getPayloadLength64(e);break;case Zp:this.getMask();break;case ol:this.getData(e);break;case al:case xa: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[Wp.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=Vp:this._payloadLength===127?this._state=Jp: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=Zp:this._state=ol}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ol}getData(e){let n=Kp;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&&$S(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=al,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Wp.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===Tt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Tt;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=sl(i,n):this._binaryType==="arraybuffer"?o=KS(sl(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Tt):(this._state=xa,setImmediate(()=>{this.emit("message",o,!0),this._state=Tt,this.startLoop(e)}))}else{let o=sl(i,n);if(!this._skipUTF8Validation&&!$p(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===al||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Tt):(this._state=xa,setImmediate(()=>{this.emit("message",o,!1),this._state=Tt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Kp),this.end();else{let i=e.readUInt16BE(0);if(!VS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let o=new pa(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$p(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=Tt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Tt):(this._state=xa,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Tt,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[jS]=o,d}};Yp.exports=cl});var fl=ue((IO,ex)=>{"use strict";var{Duplex:SO}=we("stream"),{randomFillSync:JS}=we("crypto"),Xp=li(),{EMPTY_BUFFER:ZS,kWebSocket:YS,NOOP:XS}=mn(),{isBlob:fi,isValidStatusCode:QS}=ui(),{mask:Qp,toBuffer:gr}=_s(),Pt=Symbol("kByteLength"),e1=Buffer.alloc(4),ga=8*1024,mr,hi=ga,zt=0,t1=1,n1=2,ll=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=zt,this.onerror=XS,this[YS]=void 0}static frame(e,n){let i,o=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||e1,n.generateMask?n.generateMask(i):(hi===ga&&(mr===void 0&&(mr=Buffer.alloc(ga)),JS(mr,0,ga),hi=0),i[0]=mr[hi++],i[1]=mr[hi++],i[2]=mr[hi++],i[3]=mr[hi++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[Pt]!==void 0?u=n[Pt]:(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 p=Buffer.allocUnsafe(o?u+a:a);return p[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(p[0]|=64),p[1]=f,f===126?p.writeUInt16BE(u,2):f===127&&(p[2]=p[3]=0,p.writeUIntBE(u,4,6)),n.mask?(p[1]|=128,p[a-4]=i[0],p[a-3]=i[1],p[a-2]=i[2],p[a-1]=i[3],d?[p,e]:o?(Qp(e,i,p,a,u),[p]):(Qp(e,i,e,0,u),[p,e])):[p,e]}close(e,n,i,o){let a;if(e===void 0)a=ZS;else{if(typeof e!="number"||!QS(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={[Pt]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==zt?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):fi(e)?(o=e.size,a=!1):(e=gr(e),o=e.length,a=gr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[Pt]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};fi(e)?this._state!==zt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==zt?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):fi(e)?(o=e.size,a=!1):(e=gr(e),o=e.length,a=gr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[Pt]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};fi(e)?this._state!==zt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==zt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[Xp.extensionName],a=n.binary?2:1,d=n.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):fi(e)?(u=e.size,f=!1):(e=gr(e),u=e.length,f=gr.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 p={[Pt]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:f,rsv1:d};fi(e)?this._state!==zt?this.enqueue([this.getBlobData,e,this._compress,p,i]):this.getBlobData(e,this._compress,p,i):this._state!==zt?this.enqueue([this.dispatch,e,this._compress,p,i]):this.dispatch(e,this._compress,p,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[Pt],this._state=n1,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(ul,this,u,o);return}this._bufferedBytes-=i[Pt];let d=gr(a);n?this.dispatch(d,n,i,o):(this._state=zt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(a=>{process.nextTick(r1,this,a,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let a=this._extensions[Xp.extensionName];this._bufferedBytes+=i[Pt],this._state=t1,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");ul(this,f,o);return}this._bufferedBytes-=i[Pt],this._state=zt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===zt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Pt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Pt],this._queue.push(e)}sendFrame(e,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)}};ex.exports=ll;function ul(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 r1(t,e,n){ul(t,e,n),t.onerror(e)}});var dx=ue((AO,cx)=>{"use strict";var{kForOnEventAttribute:bs,kListener:hl}=mn(),tx=Symbol("kCode"),nx=Symbol("kData"),rx=Symbol("kError"),ix=Symbol("kMessage"),sx=Symbol("kReason"),pi=Symbol("kTarget"),ox=Symbol("kType"),ax=Symbol("kWasClean"),_n=class{constructor(e){this[pi]=null,this[ox]=e}get target(){return this[pi]}get type(){return this[ox]}};Object.defineProperty(_n.prototype,"target",{enumerable:!0});Object.defineProperty(_n.prototype,"type",{enumerable:!0});var wr=class extends _n{constructor(e,n={}){super(e),this[tx]=n.code===void 0?0:n.code,this[sx]=n.reason===void 0?"":n.reason,this[ax]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[tx]}get reason(){return this[sx]}get wasClean(){return this[ax]}};Object.defineProperty(wr.prototype,"code",{enumerable:!0});Object.defineProperty(wr.prototype,"reason",{enumerable:!0});Object.defineProperty(wr.prototype,"wasClean",{enumerable:!0});var xi=class extends _n{constructor(e,n={}){super(e),this[rx]=n.error===void 0?null:n.error,this[ix]=n.message===void 0?"":n.message}get error(){return this[rx]}get message(){return this[ix]}};Object.defineProperty(xi.prototype,"error",{enumerable:!0});Object.defineProperty(xi.prototype,"message",{enumerable:!0});var Es=class extends _n{constructor(e,n={}){super(e),this[nx]=n.data===void 0?null:n.data}get data(){return this[nx]}};Object.defineProperty(Es.prototype,"data",{enumerable:!0});var i1={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[bs]&&o[hl]===e&&!o[bs])return;let i;if(t==="message")i=function(a,d){let u=new Es("message",{data:d?a:a.toString()});u[pi]=this,ma(e,this,u)};else if(t==="close")i=function(a,d){let u=new wr("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[pi]=this,ma(e,this,u)};else if(t==="error")i=function(a){let d=new xi("error",{error:a,message:a.message});d[pi]=this,ma(e,this,d)};else if(t==="open")i=function(){let a=new _n("open");a[pi]=this,ma(e,this,a)};else return;i[bs]=!!n[bs],i[hl]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[hl]===e&&!n[bs]){this.removeListener(t,n);break}}};cx.exports={CloseEvent:wr,ErrorEvent:xi,Event:_n,EventTarget:i1,MessageEvent:Es};function ma(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var wa=ue((kO,lx)=>{"use strict";var{tokenChars:vs}=ui();function Qt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function s1(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,a=!1,d,u,f=-1,p=-1,x=-1,g=0;for(;g<t.length;g++)if(p=t.charCodeAt(g),d===void 0)if(x===-1&&vs[p]===1)f===-1&&(f=g);else if(g!==0&&(p===32||p===9))x===-1&&f!==-1&&(x=g);else if(p===59||p===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);x===-1&&(x=g);let w=t.slice(f,x);p===44?(Qt(e,w,n),n=Object.create(null)):d=w,f=x=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);else if(u===void 0)if(x===-1&&vs[p]===1)f===-1&&(f=g);else if(p===32||p===9)x===-1&&f!==-1&&(x=g);else if(p===59||p===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);x===-1&&(x=g),Qt(n,t.slice(f,x),!0),p===44&&(Qt(e,d,n),n=Object.create(null),d=void 0),f=x=-1}else if(p===61&&f!==-1&&x===-1)u=t.slice(f,g),f=x=-1;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(o){if(vs[p]!==1)throw new SyntaxError(`Unexpected character at index ${g}`);f===-1?f=g:i||(i=!0),o=!1}else if(a)if(vs[p]===1)f===-1&&(f=g);else if(p===34&&f!==-1)a=!1,x=g;else if(p===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(p===34&&t.charCodeAt(g-1)===61)a=!0;else if(x===-1&&vs[p]===1)f===-1&&(f=g);else if(f!==-1&&(p===32||p===9))x===-1&&(x=g);else if(p===59||p===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);x===-1&&(x=g);let w=t.slice(f,x);i&&(w=w.replace(/\\/g,""),i=!1),Qt(n,u,w),p===44&&(Qt(e,d,n),n=Object.create(null),d=void 0),u=void 0,f=x=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);if(f===-1||a||p===32||p===9)throw new SyntaxError("Unexpected end of input");x===-1&&(x=g);let v=t.slice(f,x);return d===void 0?Qt(e,v,n):(u===void 0?Qt(n,v,!0):i?Qt(n,u,v.replace(/\\/g,"")):Qt(n,u,v),Qt(e,d,n)),e}function o1(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:o1,parse:s1}});var Ea=ue((PO,vx)=>{"use strict";var a1=we("events"),c1=we("https"),d1=we("http"),hx=we("net"),l1=we("tls"),{randomBytes:u1,createHash:f1}=we("crypto"),{Duplex:CO,Readable:TO}=we("stream"),{URL:pl}=we("url"),Gn=li(),h1=dl(),p1=fl(),{isBlob:x1}=ui(),{BINARY_TYPES:ux,CLOSE_TIMEOUT:g1,EMPTY_BUFFER:_a,GUID:m1,kForOnEventAttribute:xl,kListener:w1,kStatusCode:_1,kWebSocket:Je,NOOP:px}=mn(),{EventTarget:{addEventListener:y1,removeEventListener:b1}}=dx(),{format:E1,parse:v1}=wa(),{toBuffer:S1}=_s(),xx=Symbol("kAborted"),gl=[8,13],yn=["CONNECTING","OPEN","CLOSING","CLOSED"],I1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ve=class t extends a1{constructor(e,n,i){super(),this._binaryType=ux[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_a,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]),gx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ux.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let o=new h1({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new p1(e,this._extensions,i.generateMask);this._receiver=o,this._sender=a,this._socket=e,o[Je]=this,a[Je]=this,e[Je]=this,o.on("conclude",C1),o.on("drain",T1),o.on("error",P1),o.on("message",R1),o.on("ping",D1),o.on("pong",O1),a.onerror=L1,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",yx),e.on("data",ba),e.on("end",bx),e.on("error",Ex),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Gn.extensionName]&&this._extensions[Gn.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){yt(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())}),_x(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){ml(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||_a,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){ml(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||_a,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){ml(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Gn.extensionName]||(o.compress=!1),this._sender.send(e||_a,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){yt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ve,"CONNECTING",{enumerable:!0,value:yn.indexOf("CONNECTING")});Object.defineProperty(ve.prototype,"CONNECTING",{enumerable:!0,value:yn.indexOf("CONNECTING")});Object.defineProperty(ve,"OPEN",{enumerable:!0,value:yn.indexOf("OPEN")});Object.defineProperty(ve.prototype,"OPEN",{enumerable:!0,value:yn.indexOf("OPEN")});Object.defineProperty(ve,"CLOSING",{enumerable:!0,value:yn.indexOf("CLOSING")});Object.defineProperty(ve.prototype,"CLOSING",{enumerable:!0,value:yn.indexOf("CLOSING")});Object.defineProperty(ve,"CLOSED",{enumerable:!0,value:yn.indexOf("CLOSED")});Object.defineProperty(ve.prototype,"CLOSED",{enumerable:!0,value:yn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ve.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ve.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[xl])return e[w1];return null},set(e){for(let n of this.listeners(t))if(n[xl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[xl]:!0})}})});ve.prototype.addEventListener=y1;ve.prototype.removeEventListener=b1;vx.exports=ve;function gx(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:g1,protocolVersion:gl[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,!gl.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${gl.join(", ")})`);let a;if(e instanceof pl)a=e;else try{a=new pl(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;ya(t,S);return}let p=d?443:80,x=u1(16).toString("base64"),g=d?c1.request:d1.request,v=new Set,w;if(o.createConnection=o.createConnection||(d?k1:A1),o.defaultPort=o.defaultPort||p,o.port=a.port||p,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":x,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(w=new Gn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=E1({[Gn.extensionName]:w.offer()})),n.length){for(let S of n){if(typeof S!="string"||!I1.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 E;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[A,C]of Object.entries(S))i.headers[A.toLowerCase()]=C}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")),E=t._req=g(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=g(o);o.timeout&&E.on("timeout",()=>{yt(t,E,"Opening handshake has timed out")}),E.on("error",S=>{E===null||E[xx]||(E=t._req=null,ya(t,S))}),E.on("response",S=>{let A=S.headers.location,C=S.statusCode;if(A&&o.followRedirects&&C>=300&&C<400){if(++t._redirects>o.maxRedirects){yt(t,E,"Maximum redirects exceeded");return}E.abort();let P;try{P=new pl(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);ya(t,R);return}gx(t,P,n,i)}else t.emit("unexpected-response",E,S)||yt(t,E,`Unexpected server response: ${S.statusCode}`)}),E.on("upgrade",(S,A,C)=>{if(t.emit("upgrade",S),t.readyState!==ve.CONNECTING)return;E=t._req=null;let P=S.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){yt(t,A,"Invalid Upgrade header");return}let y=f1("sha1").update(x+m1).digest("base64");if(S.headers["sec-websocket-accept"]!==y){yt(t,A,"Invalid Sec-WebSocket-Accept header");return}let R=S.headers["sec-websocket-protocol"],D;if(R!==void 0?v.size?v.has(R)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":v.size&&(D="Server sent no subprotocol"),D){yt(t,A,D);return}R&&(t._protocol=R);let z=S.headers["sec-websocket-extensions"];if(z!==void 0){if(!w){yt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=v1(z)}catch{yt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(M);if(W.length!==1||W[0]!==Gn.extensionName){yt(t,A,"Server indicated an extension that was not requested");return}try{w.accept(M[Gn.extensionName])}catch{yt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Gn.extensionName]=w}t.setSocket(A,C,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,t):E.end()}function ya(t,e){t._readyState=ve.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function A1(t){return t.path=t.socketPath,hx.connect(t)}function k1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hx.isIP(t.host)?"":t.host),l1.connect(t)}function yt(t,e,n){t._readyState=ve.CLOSING;let i=new Error(n);Error.captureStackTrace(i,yt),e.setHeader?(e[xx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ya,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ml(t,e,n){if(e){let i=x1(e)?e.size:S1(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${yn[t.readyState]})`);process.nextTick(n,i)}}function C1(t,e){let n=this[Je];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Je]!==void 0&&(n._socket.removeListener("data",ba),process.nextTick(mx,n._socket),t===1005?n.close():n.close(t,e))}function T1(){let t=this[Je];t.isPaused||t._socket.resume()}function P1(t){let e=this[Je];e._socket[Je]!==void 0&&(e._socket.removeListener("data",ba),process.nextTick(mx,e._socket),e.close(t[_1])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function fx(){this[Je].emitClose()}function R1(t,e){this[Je].emit("message",t,e)}function D1(t){let e=this[Je];e._autoPong&&e.pong(t,!this._isServer,px),e.emit("ping",t)}function O1(t){this[Je].emit("pong",t)}function mx(t){t.resume()}function L1(t){let e=this[Je];e.readyState!==ve.CLOSED&&(e.readyState===ve.OPEN&&(e._readyState=ve.CLOSING,_x(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function _x(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function yx(){let t=this[Je];if(this.removeListener("close",yx),this.removeListener("data",ba),this.removeListener("end",bx),t._readyState=ve.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",fx),t._receiver.on("finish",fx))}function ba(t){this[Je]._receiver.write(t)||this.pause()}function bx(){let t=this[Je];t._readyState=ve.CLOSING,t._receiver.end(),this.end()}function Ex(){let t=this[Je];this.removeListener("error",Ex),this.on("error",px),t&&(t._readyState=ve.CLOSING,this.destroy())}});var kx=ue((DO,Ax)=>{"use strict";var RO=Ea(),{Duplex:M1}=we("stream");function Sx(t){t.emit("close")}function N1(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ix(t){this.removeListener("error",Ix),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function F1(t,e){let n=!0,i=new M1({...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(Sx,i);return}let d=!1;t.once("error",function(f){d=!0,a(f)}),t.once("close",function(){d||a(o),process.nextTick(Sx,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",N1),i.on("error",Ix),i}Ax.exports=F1});var wl=ue((OO,Cx)=>{"use strict";var{tokenChars:B1}=ui();function z1(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&&B1[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}Cx.exports={parse:z1}});var Mx=ue((MO,Lx)=>{"use strict";var U1=we("events"),va=we("http"),{Duplex:LO}=we("stream"),{createHash:H1}=we("crypto"),Tx=wa(),_r=li(),G1=wl(),q1=Ea(),{CLOSE_TIMEOUT:j1,GUID:W1,kWebSocket:K1}=mn(),$1=/^[+/0-9A-Za-z]{22}==$/,Px=0,Rx=1,Ox=2,_l=class extends U1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:j1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:q1,...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=va.createServer((i,o)=>{let a=va.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=V1(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=Px}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Ox){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ss,this);return}if(e&&this.once("close",e),this._state!==Rx)if(this._state=Rx,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(Ss,this):process.nextTick(Ss,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Ss(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",Dx);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){yr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){yr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!$1.test(a)){yr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){yr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Is(n,400);return}let f=e.headers["sec-websocket-protocol"],p=new Set;if(f!==void 0)try{p=G1.parse(f)}catch{yr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let x=e.headers["sec-websocket-extensions"],g={};if(this.options.perMessageDeflate&&x!==void 0){let v=new _r({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Tx.parse(x);w[_r.extensionName]&&(v.accept(w[_r.extensionName]),g[_r.extensionName]=v)}catch{yr(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,(w,E,S,A)=>{if(!w)return Is(n,E||401,S,A);this.completeUpgrade(g,a,p,e,n,i,o)});return}if(!this.options.verifyClient(v))return Is(n,401)}this.completeUpgrade(g,a,p,e,n,i,o)}completeUpgrade(e,n,i,o,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[K1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Px)return Is(a,503);let p=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${H1("sha1").update(n+W1).digest("base64")}`],x=new this.options.WebSocket(null,void 0,this.options);if(i.size){let g=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;g&&(p.push(`Sec-WebSocket-Protocol: ${g}`),x._protocol=g)}if(e[_r.extensionName]){let g=e[_r.extensionName].params,v=Tx.format({[_r.extensionName]:[g]});p.push(`Sec-WebSocket-Extensions: ${v}`),x._extensions=e}this.emit("headers",p,o),a.write(p.concat(`\r
|
|
15
15
|
`).join(`\r
|
|
16
|
-
`)),a.removeListener("error",
|
|
16
|
+
`)),a.removeListener("error",Dx),x.setSocket(a,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(x),x.on("close",()=>{this.clients.delete(x),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ss,this)})),u(x,o)}};Lx.exports=_l;function V1(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 Ss(t){t._state=Ox,t.emit("close")}function Dx(){this.destroy()}function Is(t,e,n,i){n=n||va.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} ${va.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 gr(t,e,n,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,gr),t.emit("wsClientError",d,n,e)}else bs(n,i,o,a)}});var $p=fe(He=>{"use strict";var M=V;(function(t,e){let n=V,i=t();for(;;)try{if(parseInt(n(1289))/1+parseInt(n(764))/2+parseInt(n(1585))/3*(parseInt(n(1098))/4)+parseInt(n(380))/5+-parseInt(n(1089))/6+parseInt(n(477))/7+-parseInt(n(523))/8*(parseInt(n(1727))/9)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ka,163224);var nI=Object["definePr"+M(1266)],rI=Object[M(937)+"opertyNa"+M(1110)],qp=(t,e)=>function(){return t&&(e=(0,t[{maphO:function(o,a){return o(a)}}.maphO(rI,t)[0]])(t=0)),e},iI=(t,e)=>{let n=M,i={oSpBI:function(a,d,f,u){return a(d,f,u)}};for(var o in e)i[n(818)](nI,t,o,{get:e[o],enumerable:!0})};function sI(){return Fp||(Fp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function oI(){let t=M;return Bp||(Bp=[IDBCursor.prototype[t(1749)],IDBCursor[t(501)+"e"][t(1678)],IDBCursor[t(501)+"e"][t(1678)+t(368)+"ey"]])}function aI(t){let e=M,n={HYlJb:function(o,a){return o(a)},liXeu:function(o){return o()},NVxXl:e(468),vKtIA:function(o,a){return o instanceof a}},i=new Promise((o,a)=>{let d=e,f={WfXZD:d(1746),gspET:function(w,b){return n.HYlJb(w,b)},zEOEo:function(w){return n.liXeu(w)}},u=()=>{let w=d;t[w(963)+w(1331)+w(441)](w(468),x),t[w(963)+"entListe"+w(441)](f[w(1605)],p)},x=()=>{let w=d;f[w(1257)](o,f[w(1257)](Yt,t[w(836)])),f.zEOEo(u)},p=()=>{f[d(1257)](a,t.error),u()};t[d(1107)+d(984)](n[d(418)],x),t[d(1107)+"Listener"](d(1746),p)});return i[e(1094)](o=>{let a=e;n[a(349)](o,IDBCursor)&&yl[a(1753)](o,t)})[e(765)](()=>{}),Ia[e(1753)](i,t),i}function cI(t){let e=M,n={gGERD:function(o){return o()},wMlKq:"QKyGT",azswV:e(452),gpHJU:e(1699),QUVlH:e(1746),PvivS:e(1108)+"or",IZlEF:e(1479)};if(Sa[e(1197)](t))return;let i=new Promise((o,a)=>{let d=e,f={lIJLY:function(w,b){return w!==b},EMveZ:n.wMlKq,sxgaJ:n[d(1676)],kdwZB:n[d(922)],cfyzT:n[d(1831)],nlpEg:"abort",zPqEk:n[d(420)]},u=()=>{let w=d;if(f.lIJLY(f.EMveZ,f[w(1796)]))t[w(963)+w(1331)+w(441)](f[w(787)],x),t[w(963)+w(1331)+w(441)](f[w(979)],p),t[w(963)+w(1331)+w(441)](f[w(1590)],p);else return!!_0x588837?.[w(526)](b=>b[w(1683)]===_0x19510b&&b[w(1595)]===_0x36bae7)},x=()=>{n[d(1647)](o),n.gGERD(u)},p=()=>{let w=d;a(t[w(1746)]||new DOMException(f[w(709)],f[w(709)])),u()};t[d(1107)+d(984)](n.gpHJU,x),t[d(1107)+"Listener"](n.QUVlH,p),t[d(1107)+d(984)](n[d(944)],p)});Sa.set(t,i)}function dI(t){Aa={QBjDQ:function(n,i){return n(i)}}.QBjDQ(t,Aa)}function lI(t){let e=M,n={Hhjnw:function(i,o,a){return i(o,a)},EMemT:function(i,o){return i===o},DJEXt:e(467),zyDfv:function(i,o){return i(o)},EuCQI:e(583),WzZvL:"ArkMC",ENpqi:function(i,o){return i(o)},emFDR:function(i,o){return i in o},WxXzD:e(891)+"oreNames",KaIUn:function(i){return i()}};return n.EMemT(t,IDBDatabase[e(501)+"e"]["transact"+e(817)])&&!n.emFDR(n[e(1083)],IDBTransaction[e(501)+"e"])?function(i,...o){let a=e,d={NPXfw:function(f,u,x){return n[V(1443)](f,u,x)},QMvEx:function(f,u,x){return n[V(1443)](f,u,x)}};if(n[a(713)](a(467),n[a(1147)])){let f=t[a(1603)](vs(this),i,...o);return _l[a(1753)](f,i.sort?i[a(1645)]():[i]),n[a(1521)](Yt,f)}else d[a(1180)](_0x24c5f7,_0x4cdff8,50),d[a(600)](_0x2a43c8,_0x375ace,_0x4b438c)}:n[e(1743)](oI)[e(632)](t)?function(...i){let o=e;return t[o(939)](vs(this),i),n[o(1521)](Yt,yl.get(this))}:function(...i){let o=e,a={OYuOv:n[o(1119)]};return o(885)===n[o(481)]?n[o(1521)](Yt,t[o(939)](n[o(996)](vs,this),i)):(_0x1e7d27||(_0x4d0ad9=_0x18e339.resolve()[o(1094)](_0x5d80fd[o(1305)](_0x3f0e8c,a[o(1003)]))),_0x1b99cf)}}function fI(t){let e=M,n={DUlgE:function(i,o){return i===o},nIOMi:"function",Oikns:function(i,o){return i(o)},pwbxt:function(i,o){return i instanceof o},VWFpM:function(i,o){return i(o)},eCPyQ:function(i,o,a){return i(o,a)}};return n.DUlgE(typeof t,n[e(1084)])?n[e(373)](lI,t):(n[e(1335)](t,IDBTransaction)&&n[e(1546)](cI,t),n.eCPyQ(Gp,t,sI())?new Proxy(t,Aa):t)}function Yt(t){let e=M,n={peSWA:function(o,a){return o instanceof a},Yfwwk:function(o,a){return o(a)},VviPc:function(o,a){return o!==a}};if(n[e(1349)](t,IDBRequest))return aI(t);if(ba[e(1197)](t))return ba[e(1326)](t);let i=n[e(639)](fI,t);return n.VviPc(i,t)&&(ba[e(1753)](t,i),Ia.set(i,t)),i}var Gp,Fp,Bp,yl,Sa,_l,ba,Ia,Aa,vs,zp=qp({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={MsnoL:function(n){return n()},Hojii:function(n,i,o){return n(i,o)},qLAnA:function(n,i){return n(i)},hhcLG:function(n,i){return n instanceof i},ylXXD:function(n,i){return n!==i},xOMCu:"uMOBR",xhXNi:"OSfHo",jgxHX:"done",dKNCA:function(n,i){return n===i},mpvaX:t(365),ypvDK:function(n,i){return n===i},TRrWz:t(320),IVoYd:function(n,i){return n|i},hoBln:function(n,i){return n&i},TuuTh:function(n,i){return n>>i},TuhRI:function(n,i){return n|i},sFrlv:t(1659),qmjTb:function(n,i){return n in i}};Gp=(n,i)=>i[t(1181)](o=>n instanceof o),yl=new WeakMap,Sa=new WeakMap,_l=new WeakMap,ba=new WeakMap,Ia=new WeakMap,Aa={get(n,i,o){let a=t;if(e.hhcLG(n,IDBTransaction))if(e[a(840)](e[a(434)],e[a(656)])){if(i===e.jgxHX)return Sa[a(1326)](n);if(e[a(1324)](i,a(891)+a(329)))return e[a(1199)]===e[a(1199)]?n["objectSt"+a(329)]||_l[a(1326)](n):this[a(1167)+a(758)+a(610)+"t"];if(e.ypvDK(i,e[a(775)]))return o[a(891)+a(329)][1]?void 0:o[a(891)+a(538)](o["objectSt"+a(329)][0])}else{let d=e[a(1376)](_0x2832a5);return e[a(1509)](_0x4c2e05,_0x58f72f,d),e[a(1264)](_0x2f5cff,d)}return e.qLAnA(Yt,n[i])},set(n,i,o){let a=t;if(e[a(840)](e[a(563)],e[a(563)]))_0x27b80f[_0x423817++]=e[a(611)](e[a(1451)](e.TuuTh(_0x22585e,18),7),240),_0x1a9bec[_0x18f3f5++]=e[a(459)](e[a(1451)](e[a(748)](_0x2fc6a6,12),63),128);else return n[i]=o,!0},has(n,i){let o=t;return e[o(569)](n,IDBTransaction)&&(i===e.jgxHX||i===e[o(775)])?!0:e.qmjTb(i,n)}},vs=n=>Ia[t(1326)](n)}}),jp={};iI(jp,{deleteDB:()=>hI,openDB:()=>uI,unwrap:()=>vs,wrap:()=>Yt});function uI(t,e,{blocked:n,upgrade:i,blocking:o,terminated:a}={}){let d=M,f={oEdBa:function(p,w,b,_,v){return p(w,b,_,v)},CjvAI:function(p,w){return p(w)},mrTeT:d(1175),ltmhD:d(1639)+d(1824),AqNjD:"upgraden"+d(487),rLJhx:"blocked"},u=indexedDB[d(841)](t,e),x=Yt(u);return i&&u["addEvent"+d(984)](f.AqNjD,p=>{let w=d;f.oEdBa(i,f[w(874)](Yt,u[w(836)]),p[w(1610)+"on"],p[w(1420)+"on"],f[w(874)](Yt,u[w(1567)+w(817)]))}),n&&u[d(1107)+d(984)](f.rLJhx,()=>n()),x[d(1094)](p=>{let w=d;a&&p[w(1107)+w(984)](f.mrTeT,()=>a()),o&&p[w(1107)+w(984)](f[w(1310)],()=>o())})[d(765)](()=>{}),x}function hI(t,{blocked:e}={}){let n=M,i={sENnQ:n(1754)},o=indexedDB[n(808)+n(628)](t);return e&&o[n(1107)+n(984)](i[n(1170)],()=>e()),Yt(o).then(()=>{})}function Up(t,e){let n=M,i={WMjOJ:n(1658)+"e",HAIfk:n(1436),BBFcO:function(u,x){return u instanceof x},IbDgY:function(u,x){return u in x},ShSdI:function(u,x){return u===x}};if(!(i[n(1100)](t,IDBDatabase)&&!i[n(321)](e,t)&&i[n(1508)](typeof e,n(1397))))return;if(va[n(1326)](e))return va[n(1326)](e);let o=e[n(1631)](/FromIndex$/,""),a=e!==o,d=Kp.includes(o);if(!(o in(a?IDBIndex:IDBObjectStore).prototype)||!(d||Wp.includes(o)))return;let f=async function(u,...x){let p=n,w=this[p(1567)+p(817)](u,d?i[p(1762)]:i[p(1265)]),b=w[p(320)];return a&&(b=b[p(794)](x[p(1031)]())),(await Promise[p(499)]([b[o](...x),d&&w[p(579)]]))[0]};return va[n(1753)](e,f),f}var Wp,Kp,va,xI=qp({"node_modules/idb/build/index.js"(){let t=M,e={yahke:function(n){return n()},mtHAB:t(915),RYLEA:t(1302),vgsSI:t(1434),PMWAS:t(1686),bNsPO:t(1433),eaqxO:function(n,i){return n(i)}};e[t(1092)](zp),e[t(1092)](zp),Wp=[t(1326),e[t(785)],e[t(1262)],t(693)+"ys",t(1215)],Kp=[e.vgsSI,e.PMWAS,t(1258),e[t(1126)]],va=new Map,e[t(822)](dI,n=>({...n,get:(i,o,a)=>Up(i,o)||n.get(i,o,a),has:(i,o)=>!!Up(i,o)||n[t(1197)](i,o)}))}}),pI={idb:function(t){let e=M;t.exports=Promise[e(1078)]()[e(1094)](()=>(xI(),jp))[e(1094)](function(n){return n})}},Hp={};function Xt(t){let e=M,n={ekBmv:function(a,d){return a!==d}};var i=Hp[t];if(n[e(1696)](void 0,i))return i[e(1468)];var o=Hp[t]={exports:{}};return pI[t](o,o[e(1468)],Xt),o[e(1468)]}function V(t,e){t=t-319;let n=ka(),i=n[t];if(V.KXTQAw===void 0){var o=function(u){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",w="";for(let b=0,_,v,I=0;v=u.charAt(I++);~v&&(_=b%4?_*64+v:v,b++%4)?p+=String.fromCharCode(255&_>>(-2*b&6)):0)v=x.indexOf(v);for(let b=0,_=p.length;b<_;b++)w+="%"+("00"+p.charCodeAt(b).toString(16)).slice(-2);return decodeURIComponent(w)};V.yptjtC=o,V.reXAuj={},V.KXTQAw=!0}let a=n[0],d=t+a,f=V.reXAuj[d];return f?i=f:(i=V.yptjtC(i),V.reXAuj[d]=i),i}Xt.d=(t,e)=>{let n=V;for(var i in e)Xt.o(e,i)&&!Xt.o(t,i)&&Object["definePr"+n(1266)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Xt.o=(e,n)=>Object.prototype[t(1062)+t(1266)][t(1603)](e,n)})(),(()=>{let t=M,e={APSxH:t(1583)+"d",eKwOg:t(605)};Xt.r=n=>{let i=t;e[i(1562)]!=typeof Symbol&&Symbol["toString"+i(800)]&&Object[i(824)+i(1266)](n,Symbol[i(1518)+"Tag"],{value:e[i(527)]}),Object[i(824)+"operty"](n,"__esModule",{value:!0})}})();var Me={};(()=>{let t=M,e={LPvCo:function(c,r){return c(r)},UXOZa:function(c,r){return c+r},tbDLh:function(c,r){return c+r},hFeZC:function(c,r){return c*r},iyqHg:function(c,r){return c(r)},SfwGr:function(c,r){return c+r},HFhKP:function(c,r){return c(r)},KXfEh:function(c,r,s){return c(r,s)},qZggh:t(998),iFcQf:"ffff",JICGu:function(c,r){return c===r},DWnGD:t(1105),YxvtE:function(c,r){return c(r)},MkepB:function(c,r){return c>r},uiZPl:function(c,r){return c>r},HaQGH:function(c,r){return c<r},ybSjd:function(c,r){return c!==r},LnUec:t(1704),YVNva:t(544),ODaRh:function(c,r){return c-r},uMtbh:function(c,r){return c!==r},qYROV:function(c,r){return c<r},IVxdh:function(c,r){return c-r},SyMKf:function(c,r){return c-r},nUGWb:function(c,r,s){return c(r,s)},hDEwf:function(c,r,s){return c(r,s)},ccHtF:function(c,r){return c!==r},zbvlG:function(c,r){return c(r)},htkdE:function(c,r,s){return c(r,s)},EBahx:function(c,r){return c&r},FGZNe:function(c,r){return c===r},uAUVH:t(1179)+t(1786)+" field: value",tSYcb:function(c){return c()},Xazae:function(c,r,s){return c(r,s)},pfiIB:function(c,r){return c(r)},CXvNh:function(c,r){return c>r},fZkSw:function(c,r){return c!==r},UYXhv:function(c,r,s){return c(r,s)},jOVsr:function(c,r,s){return c(r,s)},reSpa:function(c,r,s){return c(r,s)},pTAjl:function(c,r){return c(r)},RpXMX:function(c,r){return c(r)},wUrVY:function(c,r){return c===r},AVZCR:t(404),fIpuk:t(697),mZHKQ:function(c,r,s){return c(r,s)},aSqEL:function(c,r,s){return c(r,s)},mtimn:function(c,r){return c!==r},qSZMp:function(c,r,s){return c(r,s)},vpgrz:t(1782),GnLHy:t(848),GQAYm:function(c,r,s){return c(r,s)},aQJUJ:function(c,r){return c!==r},uDFIW:function(c,r,s){return c(r,s)},RByfH:function(c,r,s){return c(r,s)},obKTT:t(1685),hRrEk:t(506),nDjWd:function(c,r){return c!==r},FOtsu:t(1675),DcDqz:function(c,r,s){return c(r,s)},kHBbT:"VrvRQ",gkRfF:"XChDr",hvNku:function(c,r){return c(r)},MeyjV:function(c,r){return c===r},mjEeL:t(1561),FifNC:t(631),XQjHw:function(c,r){return c>>>r},uBSld:function(c,r){return c(r)},IFczQ:function(c,r){return c(r)},CSQlY:function(c,r){return c!==r},yWgrQ:t(1805),uekSd:t(529),SoKKJ:function(c,r,s){return c(r,s)},lDoRT:function(c,r,s){return c(r,s)},RjUBh:function(c,r){return c(r)},tBZps:function(c,r,s){return c(r,s)},BRtiA:function(c,r,s){return c(r,s)},NeXAE:function(c,r){return c&r},ghIyt:function(c,r){return c===r},IgWvq:t(1179)+t(1786)+" field: SeqID",edMXh:t(1179)+t(1786)+t(432)+t(1572),NShpV:t(1179)+t(1786)+" field: method",ObIhR:function(c,r){return c(r)},BXkla:function(c,r){return c&r},firXH:function(c,r){return c(r)},ALmfR:function(c,r){return c+r},QKeKZ:function(c,r,s){return c(r,s)},HKAeK:function(c,r){return c!==r},SKOGT:t(1840),VbfrB:function(c,r){return c>>r},OupQH:function(c,r){return c>=r},puFDu:function(c,r){return c>r},PIMlJ:t(430)+"t limit",uVZFl:function(c,r){return c>=r},pqIbI:t(1565),jSOyi:function(c,r){return c+r},VddIs:"QiAmZ",kIEVC:"Read pas"+t(723),bCqgi:function(c,r){return c===r},jkUDy:t(579),xoSnC:function(c,r){return c!==r},oOocw:function(c,r,s){return c(r,s)},xSJog:t(797),wEMxT:"AZPSJ",iMJdb:function(c,r){return c instanceof r},ANiey:function(c,r){return c instanceof r},IINBX:t(1296)+t(688)+"et=utf-8",WNtXc:"applicat"+t(825)+t(856)+t(1472),RFBpU:"none_none",hLcdr:t(1184),ypDeM:function(c,r){return c<r},ZmcXn:function(c,r){return c&r},kTNMC:function(c,r){return c(r)},YRPIf:function(c,r){return c+r},UTKnG:function(c,r){return c!==r},urxkp:function(c,r){return c<<r},qGgWn:function(c,r){return c&r},cnwRh:function(c,r){return c<r},uKIGa:function(c,r){return c==r},IEavZ:function(c,r){return c===r},xdgAw:t(1384),TSmQg:t(650),HMRdw:function(c,r){return c+r},clNsE:function(c,r){return c&r},TKGXF:function(c,r){return c|r},cZBQv:function(c,r){return c<<r},xZlPS:function(c,r){return c|r},awMeu:function(c,r){return c<<r},ecfzz:function(c,r){return c&r},HBfZW:function(c,r){return c<<r},AaQJw:function(c,r){return c&r},fPTkz:function(c,r){return c<=r},ENfEl:function(c,r){return c>=r},cStor:function(c,r){return c+r},jSBfW:function(c,r){return c+r},dRgYR:function(c,r){return c&r},cDAcE:function(c,r){return c|r},QMcMz:function(c,r){return c+r},BxCRp:function(c,r){return c+r},mDZJz:function(c,r){return c&r},EnZVE:function(c,r){return c||r},SyYEb:function(c,r){return c>=r},JUfqC:function(c,r){return c-r},IrpXn:function(c,r){return c<<r},ZoWKd:function(c,r){return c<=r},iwKBp:function(c,r){return c<r},hIiDm:function(c,r){return c+r},BGRKN:function(c,r){return c+r},gPivP:function(c,r){return c<r},ldEuw:t(1235),APwVZ:t(770),qGCiM:function(c,r){return c<r},ulYvQ:function(c,r){return c|r},KHPpx:function(c,r){return c&r},otUCf:function(c,r){return c>>r},OwNfn:function(c,r){return c===r},CHzol:t(346),GyEXa:t(1149),ZCmLY:function(c,r){return c|r},sjxuT:function(c,r){return c&r},lnOeP:function(c,r){return c|r},wBBmq:function(c,r){return c>>r},CxfYQ:function(c,r){return c&r},abEYg:function(c,r){return c&r},pfCzD:function(c,r){return c<r},LvBPT:"KfUss",NHRCb:function(c,r,s){return c(r,s)},sXprw:function(c,r){return c&r},sGjLB:function(c,r){return c===r},Synht:"vzRuu",bHdRg:t(1717),EqYRJ:function(c,r){return c(r)},qIsnR:function(c,r){return c&r},xcJfo:function(c,r){return c(r)},Xftyi:function(c,r){return c<<r},yXoON:function(c,r){return c&r},RZXXc:function(c,r){return c(r)},Jsauq:function(c,r){return c&r},hVyiC:function(c,r){return c&r},jkiXd:function(c,r){return c(r)},TTirx:function(c,r){return c(r)},IaERq:function(c,r){return c(r)},IWAan:function(c,r){return c&r},czqRE:function(c,r){return c|r},WXLtp:function(c,r){return c|r},waoSH:function(c,r){return c>>>r},JDGGU:function(c,r){return c<<r},zniFR:function(c,r){return c>>>r},hOaLv:function(c,r){return c===r},ZJJwH:function(c,r){return c===r},UWHGU:function(c,r){return c<r},ipMUz:function(c,r){return c<r},tdcEO:function(c,r){return c<r},IiTmi:function(c,r){return c<r},FgaKH:function(c,r){return c>>>r},yPora:function(c,r){return c+r},XeLaC:function(c,r){return c!==r},OPwUG:function(c,r){return c|r},yGMSe:function(c,r){return c&r},eLLLF:function(c,r){return c+r},lDZRu:function(c,r){return c&r},fleJX:function(c,r){return c>>>r},ZEXca:function(c,r){return c|r},kekIR:function(c,r){return c>>>r},BDmaw:function(c,r){return c>>>r},XbkgK:function(c,r){return c!==r},tKumJ:function(c,r){return c|r},uElUM:function(c,r){return c>>>r},PIaED:function(c,r){return c&r},ZvImf:function(c,r){return c>>>r},gBucD:function(c,r){return c|r},VuncQ:function(c,r){return c!==r},yhJDA:function(c,r){return c&r},Vjjsk:function(c,r){return c>>>r},nITFW:function(c,r){return c|r},Gwofq:function(c,r){return c|r},IVVrd:function(c,r){return c&r},NCAuK:function(c,r){return c!==r},fpTuR:function(c,r){return c|r},Ssmzl:function(c,r){return c&r},lxdOh:function(c,r){return c(r)},OkVrb:function(c,r){return c|r},pDVOj:function(c,r){return c<<r},gLuWV:function(c,r){return c|r},ENaxR:function(c,r){return c<<r},hbGtG:function(c,r){return c|r},MPhQo:function(c,r){return c|r},pniNM:function(c,r){return c&r},iEXSA:function(c,r){return c&r},sJbui:function(c,r){return c>>>r},UqQLu:function(c,r){return c&r},Pwdjm:function(c,r){return c>>>r},SxMVL:function(c,r){return c!==r},nuNLl:t(1815),bGoDa:function(c,r){return c>>>r},gRbMG:function(c,r){return c|r},uAMER:function(c,r){return c<<r},Vzlwk:function(c,r){return c|r},griOq:function(c,r){return c<<r},rHhXt:function(c,r){return c&r},tOQNb:function(c,r){return c>>>r},wJEgy:function(c,r){return c|r},LMIed:function(c,r){return c/r},BgnZN:function(c,r){return c+r},PRBhl:function(c,r){return c+r},cSMQK:function(c,r){return c===r},nwxWX:function(c,r){return c>>>r},vxJQr:function(c,r){return c&r},UiUPE:function(c,r){return c&r},xEKip:function(c,r){return c+r},JrReb:function(c,r){return c+r},LMqGY:function(c,r){return c>>>r},qdrnM:function(c,r){return c>>>r},uiNRC:function(c,r){return c|r},hTOUG:function(c,r){return c<<r},vjLEp:function(c,r){return c|r},UGVYx:function(c,r){return c>>>r},VaWtC:function(c,r){return c===r},BXlgB:function(c,r){return c<r},KvTlD:function(c,r){return c===r},ZipmR:t(1352),SLRQL:function(c,r){return c===r},UvVBc:function(c,r){return c+r},fzvGv:function(c,r){return c&r},DMCFY:function(c,r){return c&r},aketg:function(c,r){return c>>>r},aGkTb:function(c,r){return c>>>r},qNQiQ:function(c,r){return c>>>r},Zmogx:function(c,r){return c>>>r},DKbIF:function(c,r){return c&r},nEaBd:function(c,r){return c>>>r},MQXbh:function(c,r){return c>>>r},xWvlE:function(c,r){return c>>>r},vlODd:function(c,r){return c&r},TMByS:function(c,r){return c|r},axwih:function(c,r){return c&r},HmcsJ:function(c,r){return c!==r},RZqQB:t(1131),EevvV:t(586)+"4|5",Uzihf:t(1601)+t(1336),VYhdC:"CONNECTI"+t(1804),ZuxTy:t(618)+t(943)+"R",PFjqB:t(1157)+"OR",gCHaQ:t(1564)+"0",TiDMR:function(c,r){return c>=r},xdLxY:function(c,r){return c===r},CHovI:function(c,r){return c-r},yeRMM:function(c,r){return c==r},MrTce:"send_ack",wOaIZ:t(468),edSbv:function(c,r,s){return c(r,s)},sxYnD:t(1369)+t(590)+"t",DALlo:function(c,r){return c===r},qfPuA:t(712),zyGMJ:t(1734),wMPJr:t(678),Cwbqv:t(1247),IrlNJ:function(c,r){return c!==r},iJnNQ:t(1203),pazKF:t(1746),DeTlc:t(1175),VIJsT:function(c,r,s){return c(r,s)},PLgri:"open",bkQCK:function(c,r){return c===r},JUOVw:function(c,r){return c+r},JNAsE:t(1581),yfDjV:t(1500),egadl:t(645),gixvg:function(c,r,s){return c(r,s)},OzFfV:function(c,r){return c+r},ynElw:function(c,r){return c>>r},zMIqq:function(c,r){return c|r},VaERx:function(c,r){return c|r},FOBQB:function(c,r){return c&r},bighX:function(c,r){return c instanceof r},yBWqB:"LaGrg",FIkfE:function(c,r){return c!=r},xLJTq:function(c,r){return c*r},dFARF:function(c,r){return c===r},mIbZJ:"mfrUh",gGmpV:t(1144),nxLRQ:t(1583)+"d",ngdnO:"qNsXT",LnzFc:t(486)+t(1503)+t(1703)+"imes in "+t(905),VMbur:function(c,r){return c+r},dgoKi:function(c,r){return c(r)},ovTiG:function(c,r){return c&r},XcZNa:function(c,r){return c&r},Elxhy:function(c,r){return c(r)},egNtn:function(c,r){return c&r},ccCjK:function(c,r){return c(r)},NPvhv:"MDCFf",jFcQl:function(c,r){return c<r},MODao:function(c,r){return c===r},WFkpQ:function(c,r){return c===r},Dhzkc:function(c,r){return c<r},OvEYn:function(c,r){return c<=r},schMr:function(c,r){return c>=r},Nkfpa:function(c,r){return c<r},xUelg:function(c,r){return c|r},rfMEp:function(c,r){return c<<r},szUCA:function(c,r){return c&r},PPIxN:function(c,r){return c|r},XALOa:function(c,r){return c|r},jqZyi:function(c,r){return c<<r},CPIcI:function(c,r){return c<<r},WIdyY:function(c,r){return c!==r},AgbFU:t(725),Vcgjt:function(c,r){return c-r},JWsTb:function(c,r){return c|r},SetiF:function(c,r){return c&r},YRuqz:function(c,r){return c+r},MKKDS:function(c,r){return c<r},mkzVT:function(c,r){return c|r},NjnpC:function(c,r){return c&r},jhpkX:function(c,r){return c===r},EQclM:function(c,r){return c&r},EjuLn:function(c,r){return c+r},YVLJW:function(c,r){return c&r},bVmHI:function(c,r){return c&r},QeBbx:function(c,r){return c|r},TrIjw:function(c,r){return c&r},pdCHD:function(c,r){return c&r},XLJxZ:function(c,r){return c|r},cJnSv:function(c,r){return c&r},vzBdG:function(c,r){return c&r},MsLAa:function(c,r){return c|r},lduSY:function(c,r){return c>>r},GiWmN:t(1784),ASApT:t(1397),cuGjB:function(c,r){return c(r)},VKzqk:function(c,r,s,l){return c(r,s,l)},lGVbw:function(c,r){return c!=r},AzmRU:t(776)+t(825),QTJgX:function(c,r){return c==r},FHpqL:"boe",XPKUN:t(1439),bdOQn:t(1277)+t(828),ViKxF:"script",CeMFI:t(1140)+t(993),laxJv:function(c,r){return c+r},IEGri:t(1271),egbjM:"&jscallback=fron"+t(551)+"P",UbmQq:t(460),GtxHI:function(c,r){return c<r},mOxQP:function(c,r){return c<<r},SRwwl:function(c,r){return c|r},UdMDy:"idb",mRvCT:t(1404),JUACX:t(1643)+t(327),YdQtf:"dyExr",omHpa:"uwVnD",bMDnI:t(1623),oELRj:t(1814),NUNyj:t(1785),aaIje:"zeLoe",hKtLi:function(c,r,s){return c(r,s)},daRcd:t(895),HmCoA:function(c,r){return c||r},WLLRf:t(1517),gIryo:function(c,r){return c||r},tEWcg:function(c,r){return c||r},SDuRP:"BbDdF",padRW:function(c,r){return c||r},VvGXy:function(c,r){return c||r},rBMDR:function(c,r){return c||r},SnGYO:t(1432)+"00000000"+t(1432)+"00000000",skSGO:function(c,r){return c||r},gOHhp:"LfNMH",UdVIl:t(1672),VimIj:function(c,r){return c||r},Vvtxe:t(1735)+t(1374)+"d",AFKFm:t(348),kAbRc:t(1256)+"id",ngBzC:function(c,r,s){return c(r,s)},SmoTz:function(c,r,s,l){return c(r,s,l)},LXvWr:t(1693),AJVvN:function(c,r){return c(r)},LijqS:function(c,r,s){return c(r,s)},QcgRi:function(c,r){return c==r},JXdVP:function(c,r){return c instanceof r},MEiBH:t(742),WLdec:function(c,r){return c===r},supaQ:t(372),ZrPcf:t(1744),PcNBr:"ack",DTQJg:function(c,r){return c===r},gaXLT:t(1413),kHaAc:t(509),rNeKC:t(959),CofPZ:t(395)+t(987),ACLQQ:function(c,r,s,l){return c(r,s,l)},HlPae:t(395)+t(774)+"ck",XrhJk:t(395)+t(453)+"k",WUTJW:"x_fronti"+t(1530)+t(791),UuOgF:"suQiy",EKTmn:function(c,r,s,l){return c(r,s,l)},voTct:"need_ack",FWGWC:t(1809),CVVES:function(c,r){return c&&r},RzhKT:t(1669),ncPPo:"ack_id",FfUDv:function(c,r){return c||r},aQdkH:function(c){return c()},ZWZKD:function(c,r,s){return c(r,s)},ieOUx:function(c,r){return c+r},zEfIu:function(c,r,s){return c(r,s)},edzYj:t(657),eOmtB:function(c,r){return c(r)},jiEsO:function(c,r){return c===r},PauFv:"esBCQ",xOBLA:function(c,r){return c instanceof r},flmWo:function(c,r,s,l){return c(r,s,l)},MfaCw:function(c,r){return c(r)},UTJqU:function(c,r){return c|r},TuXgN:function(c,r){return c(r)},FMWGd:function(c,r){return c+r},rTWdU:function(c,r){return c+r},LMZwy:function(c,r){return c+r},LkhjI:t(615)+t(1315)+"ge: ",cWkYQ:t(762),VADBX:t(1388),dmfrG:function(c,r){return c>r},MDPaz:t(601)+t(720)+"e",ceEhE:"JbPKx",usXGM:function(c,r,s){return c(r,s)},hvOvH:function(c,r){return c>>>r},DhPED:function(c,r){return c===r},sLBZO:t(320),QztgY:function(c,r){return c in r},nSevT:t(507),zWrXo:t(1619)+"2",xqoNt:function(c,r){return c+r},ILrrY:function(c,r){return c+r},FCwpF:function(c,r,s,l){return c(r,s,l)},Cihvs:function(c,r){return c<<r},ikhDv:function(c,r){return c+r},HEuSu:function(c,r){return c<<r},lgdtF:function(c,r){return c+r},Ecwql:function(c,r){return c+r},MQJDw:function(c,r){return c+r},pbCPw:function(c,r){return c<<r},SRiHe:function(c,r){return c+r},gFMeO:function(c,r){return c+r},eFLOU:function(c,r){return c&r},eKtDn:function(c,r){return c+r},BylQA:function(c,r){return c>>>r},WwKRq:function(c,r){return c+r},EspTs:function(c,r){return c&r},fAQHQ:function(c,r){return c>>>r},iOHud:function(c,r){return c&r},rVUdT:function(c,r){return c>>>r},yTcwZ:function(c,r){return c&r},tCpuN:function(c,r){return c&r},YyAiR:function(c,r){return c+r},UNifh:function(c,r){return c&r},vcIsH:function(c,r){return c===r},DfwrG:"Akpxx",wlgXc:function(c,r){return c<r},IQbps:function(c,r){return c|r},EEotC:function(c,r){return c<<r},cpSFh:function(c,r){return c&r},FWKfk:function(c,r){return c|r},EqqCe:function(c,r){return c&r},YKaod:function(c,r){return c<r},UuWrS:function(c,r){return c|r},DnAeq:function(c,r){return c>>>r},FdEWL:function(c,r){return c&r},AhgAt:function(c,r){return c&r},QHeKQ:function(c,r){return c<r},fNyci:function(c,r){return c+r},wbtkf:t(438)+"10|1|2|7"+t(515),yqqcI:t(338)+t(732),FHRtK:t(1341)+t(913),lNlby:"curvalue",TSHAC:t(1768),kzhSy:t(798),lrWPe:t(655),nDDfB:t(540)+t(323),nRpNk:function(c,r){return c(r)},QKRIm:"JIfIU",KnNkR:t(1495),luFvg:function(c,r,s){return c(r,s)},DGvif:function(c,r){return c+r},qRysC:function(c,r,s){return c(r,s)},mOdIZ:t(719)+t(389),ACPmy:t(1195)+"ame",GDHuG:t(603)+t(1543),cpQsh:"ALL",nKCfx:"INSTANT",xitIL:t(1200),rXLsW:function(c,r,s,l){return c(r,s,l)},LiLzM:function(c,r){return c(r)},cTIqg:t(1116),mBORv:function(c,r){return c+r},eUPLx:function(c,r){return c!==r},BVghF:"MBljr",KNIvX:t(1467),ofBTp:function(c,r){return c||r},NFuAF:t(1026),PDhRO:function(c,r){return c(r)},aJMIi:t(1373),dbaUo:function(c,r,s,l){return c(r,s,l)},yaLav:t(395)+"er_msgid",fiTkl:function(c,r){return c(r)},bDHVP:t(395)+"er_ttl",wjLwu:t(741)+"s",tOhov:t(613)+t(938)+"e",ZdFoq:function(c,r){return c(r)},qFKHW:function(c,r,s){return c(r,s)},oikLk:function(c,r){return c!==r},clZiP:"ctyRi",fQUyr:function(c){return c()},GeOuU:function(c){return c()},zqbvw:function(c,r){return c===r},rEana:function(c,r,s){return c(r,s)},kmfPm:function(c){return c()},zXDtY:"bNzJC",hNkNI:function(c){return c()},eJBZN:function(c,r,s){return c(r,s)},Feiad:function(c){return c()},XTtTI:function(c,r){return c===r},WlEHi:t(1726),nNtHA:t(682),TpZho:function(c){return c()},Xyluw:t(1479),jJIcQ:function(c,r,s){return c(r,s)},ptHrL:t(1060),JiDue:function(c,r,s){return c(r,s)},IGHCk:function(c,r){return c===r},kisAL:function(c,r){return c+r},oAKsi:"always",FxbwE:t(1405),WTImg:function(c,r){return c!=r},ReTLj:function(c,r){return c!==r},meUqJ:"jvFQr",tJgdU:function(c,r,s){return c(r,s)},jnZgE:t(1347)+t(606),ZjLQp:t(1791),SmJQk:function(c,r){return c===r},PRGUR:t(1117)+"rovide v"+t(1794),ktHWA:function(c,r){return c(r)},fARMf:t(1117)+t(761)+"s params"+t(1114)+"ket cons"+t(749)+"is undef"+t(619),KAeGC:t(528)+"t",LuXys:t(958)+t(371)+" reconnect",ftcVx:"online",ZaINm:t(1783),GhpYy:"pagehide",zJaqZ:t(1206),eUZAL:function(c,r,s){return c(r,s)},uPgKP:t(921),HgcUd:function(c,r){return c!==r},PBygh:function(c,r,s,l){return c(r,s,l)},oGnoo:"upgraden"+t(487),WRxwo:t(1819),gnYEn:function(c,r){return c==r},TTzgF:t(1828),gkUJF:t(648),pJCFh:function(c,r){return c!==r},sXDQp:t(989),eTWbD:t(425),LlISD:t(608),AnzQz:function(c,r){return c||r},xfvFF:t(1117)+t(1802)+t(1835)+t(1666)+t(1268),UGXQj:t(379),kPZuz:t(1807),uudAd:t(510)+"0",pgsay:function(c,r){return c-r},aDwfu:t(630),RNVgr:t(753),mNOFk:"QKHsg",gMuio:function(c,r){return c!==r},IzCIt:t(595),QiwoG:function(c,r){return c||r},AZVUy:function(c,r,s){return c(r,s)},NMTMV:function(c,r,s){return c(r,s)},StfKX:function(c,r){return c(r)},BNEka:function(c,r){return c(r)},meoqG:"FRONTIER>",KGxEv:function(c,r){return c*r},LtVoq:function(c,r){return c>r},Fxhsi:function(c,r,s){return c(r,s)},dgiod:function(c,r,s){return c(r,s)},YVPrM:t(1118),Apcma:t(907)+t(1021)+t(528)+t(1731)+t(1682),DkfbC:function(c,r,s){return c(r,s)},RvpVR:t(1632),SjVsf:t(582),HzFyM:function(c,r){return c!==r},RXiyq:"gZTWT",TActL:t(1254)+t(1636)+"onnecting",gPLnk:"0|2|4|3|1",wuacK:t(1718)+"2",UfIYd:function(c,r,s){return c(r,s)},fdnQD:t(1586),vpgoQ:function(c,r){return c!==r},Bmlca:t(951),vwwCX:t(661),gNFKQ:t(1176),cWFrJ:t(621)+t(1469),Tuxuc:t(581)+t(1677)+t(1811),cURCE:t(1117)+t(403)+t(1395)+t(1017)+t(356)+t(1093)+t(1526)+t(1137)+t(1476),bLRCO:function(c,r){return c==r},bqjMm:t(1343),RGVlw:function(c,r){return c!=r},GXwHe:function(c,r){return c instanceof r},OXKYj:function(c,r){return c instanceof r},idfbv:function(c,r){return c(r)},fOAvy:function(c,r){return c(r)},gaSTq:function(c,r){return c||r},hftLs:"please provide a"+t(1101)+t(732),VmRqW:function(c,r){return c instanceof r},QWrVf:function(c,r){return c instanceof r},TNdrO:function(c,r){return c(r)},rVzia:t(1091),nqIDv:t(482),BszbC:function(c,r){return c==r},lMOgL:t(1450)+t(1260)+t(1287),ccgKL:function(c,r){return c===r},Xnkpa:t(1096),ynFJz:t(1369)+t(1150)+"s",ZRomp:t(1151),QHHNE:function(c,r){return c/r},ZASEl:function(c,r){return c!=r},IljXo:t(1837),EjswH:function(c,r){return c!=r},CHkCM:function(c,r){return c===r},QaVPB:t(1243)+t(1024)+t(638)+"pe",zXzlD:function(c,r){return c===r},PLcqJ:"Object",mQZTm:function(c,r){return c!=r},zPlny:function(c,r){return c!=r},OmClq:t(1043)+t(1556)+t(1366),kJiwF:function(c,r){return c===r},OIggd:t(1591)+t(1438)+t(422),ThcbG:function(c,r){return c!=r},hjJcw:t(573)+t(1334)};Xt.r(Me),Xt.d(Me,{FWS:()=>Dm,CustomErrorEvent:()=>zl,createCloseEvent:()=>kt,ReconnectEvent:()=>Bl,createErrorEvent:()=>wt,decodedFrame:()=>Ft,createOpenEvent:()=>Wl,CustomCloseEvent:()=>Ul,createReconnectEvent:()=>ja,FrontierMessageEvent:()=>ql,encodeFrame:()=>Qt,createMessageEvent:()=>jl,OpenEvent:()=>Gl,ErrorCode:()=>wn,Event:()=>_r,MessageEvent:()=>Hl});let n="";function i(c=""){let r=t,s="02",l=""+Date[r(559)](),h=n||(n=e[r(347)](u,c)),m=Math[r(1e3)]()[r(1518)](16)[r(899)](-6);return e.UXOZa(e.UXOZa(e[r(680)](s,l),h),m)}function o(){let c=t;return e.tbDLh(e[c(1463)](1e4,Date[c(559)]()),Math[c(1280)](1e4*Math.random()))}function a(c){let r=t;return(e[r(795)](Array,8)[r(1770)]("0")+parseInt(c,10)[r(1518)](2))[r(899)](-8)}function d(c){let r=t;return e[r(635)](e[r(367)](Array,4)[r(1770)]("0"),e[r(564)](parseInt,c,2)[r(1518)](16)).slice(-4)}function f(c){let r=t,s=c[r(1622)](/\./)[r(424)](m=>a(m)),l=[];return l[0]=e[r(367)](d,s[0]+s[1]),l[1]=e[r(795)](d,e[r(635)](s[2],s[3])),[e[r(990)],e[r(990)],e.qZggh,e.qZggh,e[r(990)],e[r(336)],l[0],l[1]][r(1770)]("")}function u(c){let r=t;if(e[r(330)](e.DWnGD,e[r(448)])){let s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.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]))/.test(c);return s?e[r(347)](f,c):l?e[r(1637)](x,c):r(1432)+r(1432)+r(1432)+r(1432)}else this[r(1776)]=!1,_0x17b20c(this[r(1378)+"ionTimeo"+r(1051)]),_0x1a01c3()}function x(c){let r=t,s="",l=[],h=0,m=0,y=!0,S=e[r(990)];if(e[r(1004)](c[r(1611)]("::"),-1)){let g=c.split("::");for(let O=0;O<g.length;O++){let B=g[O];if(e.uiZPl(B[r(1611)](":"),0)){let F=B[r(1622)](":");y&&(h=F[r(1511)]),m+=F[r(1511)];for(let $=0;e[r(1435)]($,F.length);$++)if(e[r(1654)](4,F[$][r(1511)])){if(e[r(330)](e[r(1713)],e[r(1494)]))return this._qosDB[r(1599)];{let pe=S.substring(0,e[r(1263)](4,F[$].length)),de=pe[r(1408)](F[$]);l[r(567)](de)}}else l[r(567)](F[$]);y=!1}else{if(e[r(624)](4,B.length)){let F=S.substring(0,e.ODaRh(4,B[r(1511)])),$=F.concat(B);l[r(567)]($)}else l[r(567)](B);y&&(h+=1),m+=1,y=!1}}let L="";for(let O=0;e.qYROV(O,e.IVxdh(8,m));O++)L=L[r(1408)](S);for(let O=0;O<l[r(1511)];O++)e.JICGu(O,h)&&(s=s[r(1408)](L)),s=s.concat(l[O]);return s}{let g=c[r(1622)](":");for(let L=0;L<g[r(1511)];L++){let O=g[L];if(e[r(624)](4,g[L][r(1511)])){let B=S.substring(0,e[r(1723)](4,g[L][r(1511)])),F=B[r(1408)](O);s=s[r(1408)](F)}else s=s.concat(O)}return s}}function p(c,r){let s=t,l=c.key;e[s(1654)](void 0,l)&&(e[s(1161)](ae,r,10),e[s(1226)](qe,r,l));let h=c[s(1595)];e[s(470)](void 0,h)&&(ae(r,18),qe(r,h))}function w(c){let r=t,s={};e:for(;!e[r(795)](J,c);){let l=e[r(367)](ee,c);switch(l>>>3){case 0:break e;case 1:s[r(1683)]=e[r(564)](Ee,c,e[r(842)](ee,c));break;case 2:s[r(1595)]=e[r(1161)](Ee,c,e[r(842)](ee,c));break;default:e[r(1833)](T,c,e[r(677)](7,l))}}if(e.JICGu(void 0,s[r(1683)]))throw new Error("Missing "+r(1786)+" field: key");if(e[r(1460)](void 0,s[r(1595)]))throw new Error(e[r(1068)]);return s}function b(c){let r=t,s=e[r(1148)](P);return e[r(1515)](_,c,s),N(s)}function _(c,r){let s=t,l={gtaBJ:function(be,Ae){return be+Ae},QVXba:function(be,Ae){return e[V(1020)](be,Ae)},iKBwQ:function(be,Ae){return be*Ae},XafaC:function(be,Ae){return e[V(1039)](be,Ae)}},h=c[s(812)];e.fZkSw(void 0,h)&&(ae(r,8),e[s(1132)](lt,r,h));let m=c[s(1572)];m!==void 0&&(e.jOVsr(ae,r,16),lt(r,m));let y=c.service;e[s(1654)](void 0,y)&&(e[s(970)](ae,r,24),e[s(1515)](lt,r,e[s(1214)](R,y)));let S=c.method;e[s(1654)](void 0,S)&&(e[s(1833)](ae,r,32),e[s(970)](lt,r,e.RpXMX(R,S)));let g=c[s(497)];if(g!==void 0)for(let be of g){if(e[s(1174)](e.AVZCR,e.fIpuk))return _0x41223d?this.toBytesLE():this[s(1320)+"E"]();{e[s(1461)](ae,r,42);let Ae=e.tSYcb(P);e[s(1358)](p,be,Ae),e.aSqEL(ae,r,Ae.limit),C(r,Ae),e.LPvCo(D,Ae)}}let L=c[s(391)+"ncoding"];e.mtimn(void 0,L)&&(e[s(1461)](ae,r,50),e[s(1229)](qe,r,L));let O=c.payloadType;if(O!==void 0)if(e[s(330)](e[s(851)],e.GnLHy)){let be=_0x4862de.bytes,Ae=_0x1faf9a[s(417)],yn=_0x397529[s(975)],Tt=l[s(1308)](Ae,_0x3bfefa);if(l[s(1456)](Tt,be[s(1511)])){let br=new _0x27debe(l[s(332)](2,Tt));br[s(1753)](be),_0x13bd3f[s(604)]=br}return _0x36d75e.offset=Tt,l[s(385)](Tt,yn)&&(_0x1ffc93[s(975)]=Tt),Ae}else e[s(652)](ae,r,58),e.KXfEh(qe,r,O);let B=c[s(1177)];e[s(810)](void 0,B)&&(e[s(1080)](ae,r,66),e[s(1461)](ae,r,B[s(1511)]),e[s(1391)](le,r,B));let F=c[s(1325)];if(F!==void 0)if(e.FGZNe(e[s(1580)],e[s(690)])){if(this._options[s(767)+"utoRecon"+s(378)]||this[s(402)+s(554)])return;this["_handleR"+s(1260)]()}else e[s(1358)](ae,r,74),e[s(1833)](qe,r,F);let $=c[s(1410)+s(433)];e[s(1654)](void 0,$)&&(e[s(652)](ae,r,82),e[s(1226)](qe,r,$));let pe=c[s(701)];if(e[s(1654)](void 0,pe)){if(e[s(1633)](e[s(617)],e[s(617)]))return rxVpOu[s(1568)](_0x48992f,_0x576712[s(939)](rxVpOu[s(795)](_0x2385d3,this),_0xf252d3));e[s(1833)](ae,r,90),qe(r,pe)}let de=c[s(1205)+"e"];de!==void 0&&(e[s(1524)](ae,r,96),lt(r,e[s(1568)](R,de)))}function v(c){let r=t,s={IFjPG:function(l,h,m){return l(h,m)}};if(e[r(1174)](e.kHBbT,e[r(633)]))CKRkbC.IFjPG(_0x40468e,_0x42ad3a,90),CKRkbC[r(1001)](_0x150b4a,_0x48815a,_0x4cd33e);else return e[r(795)](I,e[r(1836)](U,c))}function I(c){let r=t,s={JQmob:function(l,h,m){return l(h,m)}};if(e[r(1050)](e[r(1038)],e[r(1702)]))JmHaBN[r(985)](_0x2851eb,_0x3309f5,96),JmHaBN[r(985)](_0x536310,_0x5326c3,_0xf93d1(_0x39bd62));else{let l={};e:for(;!e[r(1214)](J,c);){let h=e[r(842)](ee,c);switch(e[r(589)](h,3)){case 0:break e;case 1:l.SeqID=st(c,!0);break;case 2:l[r(1572)]=e.Xazae(st,c,!0);break;case 3:l.service=e[r(1330)](ee,c);break;case 4:l[r(1803)]=e[r(409)](ee,c);break;case 5:if(e.CSQlY(e[r(512)],e[r(1592)])){let m=A(c);(l[r(497)]||(l.headers=[]))[r(567)](w(c)),c[r(975)]=m;break}else _0x36ca07(_0x49b9be,16),_0x120504(_0x11d255,_0x14bf70);case 6:l[r(391)+r(1143)]=e[r(1515)](Ee,c,ee(c));break;case 7:l["payloadT"+r(1624)]=Ee(c,e.iyqHg(ee,c));break;case 8:l[r(1177)]=e[r(322)](oe,c,e[r(1637)](ee,c));break;case 9:l[r(1325)]=e[r(1348)](Ee,c,e[r(731)](ee,c));break;case 10:l.serverTiming=e[r(872)](Ee,c,ee(c));break;case 11:l[r(701)]=e.tBZps(Ee,c,ee(c));break;case 12:l[r(1205)+"e"]=e[r(409)](ee,c);break;default:e[r(1764)](T,c,e[r(1766)](7,h))}}if(e[r(1300)](void 0,l[r(812)]))throw new Error(e[r(692)]);if(e[r(330)](void 0,l[r(1572)]))throw new Error(e.edMXh);if(e[r(1460)](void 0,l[r(1566)]))throw new Error("Missing "+r(1786)+r(432)+r(1566));if(l[r(1803)]===void 0)throw new Error(e[r(698)]);return l}}function A(c){let r=t,s=e.ObIhR(ee,c),l=c.limit;return c[r(975)]=e.tbDLh(c[r(417)],s),l}function T(c,r){let s=t;switch(r){case 0:for(;e[s(489)](128,e.iyqHg(H,c)););break;case 2:e[s(1348)](K,c,e[s(1286)](ee,c));break;case 5:e[s(970)](K,c,4);break;case 1:e[s(383)](K,c,8);break;default:throw new Error(e[s(1798)](s(597)+s(1232)+s(629),r))}}function R(c){let r=t,s={WtmFg:function(l,h,m){return e[V(399)](l,h,m)},qiavG:function(l){return l()},YLbKr:function(l,h,m){return e[V(1461)](l,h,m)},wCjYP:function(l,h){return l(h)}};if(e[r(881)](e.SKOGT,"fUdav")){oQvkUu[r(1383)](_0xdf6368,_0x4ad20d,42);let l=oQvkUu[r(1485)](_0x39343c);_0x387e7e(_0x4cdca7,l),_0x1b3fc7(_0x5025e5,l.limit),oQvkUu[r(1569)](_0x57738a,_0x48f022,l),oQvkUu[r(1559)](_0xdc5804,l)}else return c|=0,{low:c,high:e[r(1075)](c,31),unsigned:e[r(1412)](c,0)}}let E=[];function P(){let c=t,r=E[c(1523)]();return r?(r[c(417)]=r[c(975)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(c){E[t(567)](c)}function U(c){return{bytes:c,offset:0,limit:c[t(1511)]}}function N(c){let r=t,s=c[r(604)],l=c[r(975)];return s[r(1511)]===l?s:s[r(1104)](0,l)}function K(c,r){let s=t;if(e[s(1380)](c[s(417)]+r,c[s(975)]))throw new Error(e[s(335)]);c[s(417)]+=r}function J(c){let r=t;return e[r(923)](c[r(417)],c[r(975)])}function ie(c,r){let s=t;if(e[s(624)](e.pqIbI,e[s(591)]))this[s(845)]=_0x4c4093,this[s(884)]=_0x4a57c9,this._qosDB=_0x86cfe4;else{let l=c[s(604)],h=c[s(417)],m=c.limit,y=e[s(1602)](h,r);if(e[s(1004)](y,l[s(1511)])){let S=new Uint8Array(e.hFeZC(2,y));S[s(1753)](l),c[s(604)]=S}return c[s(417)]=y,e[s(1004)](y,m)&&(c[s(975)]=y),h}}function Y(c,r){let s=t;if(e[s(1337)]!==s(1710)){let l=c.offset;if(e[s(1004)](e[s(680)](l,r),c[s(975)]))throw new Error(e[s(1548)]);return c[s(417)]+=r,l}else _0x2b1cb1.d=(l,h)=>{for(var m in h)_0x45601f.o(h,m)&&!_0x4ab0a6.o(l,m)&&_0x2a1aec.defineProperty(l,m,{enumerable:!0,get:h[m]})}}function oe(c,r){let s=t,l={VOjYV:function(h,m){return e[V(803)](h,m)},EAHzh:e[s(908)],opRTe:s(891)+s(329),IAbRL:function(h,m){return e[s(330)](h,m)},upubn:s(320)};if(e[s(1053)](s(1571),"aSQxW")){if(KHeKeU[s(466)](_0x382fd6,KHeKeU.EAHzh))return _0x45688c.get(_0x5b4226);if(KHeKeU[s(466)](_0x12fddd,KHeKeU[s(1066)]))return _0x5d521b[s(891)+"oreNames"]||_0x1f1ca4[s(1326)](_0x5dcb47);if(KHeKeU[s(1491)](_0x480044,KHeKeU[s(928)]))return _0x55ffef["objectSt"+s(329)][1]?void 0:_0x5da4f2[s(891)+s(538)](_0x316120[s(891)+s(329)][0])}else{let h=e.oOocw(Y,c,r);return c[s(604)][s(1104)](h,e[s(1602)](h,r))}}function le(c,r){let s=t;if(e[s(852)]===e[s(953)])this["maxLossC"+s(883)]=_0x17846f,this[s(1215)]=0;else{let l=e[s(1764)](ie,c,r[s(1511)]);c[s(604)][s(1753)](r,l)}}function Ee(c,r){let s=t,l=e[s(1764)](Y,c,r),h=String[s(339)+s(710)],m=c[s(604)],y="\uFFFD",S="";for(let g=0;e[s(1319)](g,r);g++){let L=m[e[s(680)](g,l)],O,B,F,$;if(e[s(1377)](128,L)===0)S+=e.kTNMC(h,L);else if(e[s(330)](e.EBahx(224,L),192))e.OupQH(e[s(1602)](g,1),r)?S+=y:(O=m[e[s(1191)](e.UXOZa(g,l),1)],e.UTKnG(e[s(677)](192,O),128)?S+=y:($=e[s(1019)](e[s(489)](31,L),6)|e[s(1823)](63,O),e.cnwRh($,128)?S+=y:(S+=h($),g++)));else if(e[s(916)](240&L,224))if(g+2>=r)S+=y;else if(e[s(771)](e.xdgAw,e[s(525)]))if(e[s(1537)](_0x1ec4e1[s(1177)],_0x386f2b)){let pe=this[s(415)][s(391)+"ncoding"]instanceof _0x51fc3d?{force:!!this[s(415)].payloadEncoding.force,encoding:this._options[s(391)+s(1143)].encoding?this[s(415)][s(391)+s(1143)][s(806)][s(1631)](/\s/g,"")[s(850)+s(1774)]():""}:{force:!1,encoding:this._options[s(391)+s(1143)]?this[s(415)][s(391)+"ncoding"][s(1631)](/\s/g,"")[s(850)+s(1774)]():""},de=_0x307c17[s(391)+s(1143)]?_0x235a02["payloadE"+s(1143)][s(1631)](/\s/g,"")[s(850)+"ase"]():"",be=e[s(779)](this[s(415)]["payloadT"+s(1624)],_0x15628e)?{force:!!this[s(415)][s(1009)+s(1624)][s(831)],type:this[s(415)][s(1009)+s(1624)][s(1097)]?this[s(415)][s(1009)+"ype"][s(1097)].replace(/\s/g,"")[s(850)+s(1774)]():""}:{force:!1,type:this[s(415)][s(1009)+"ype"]?this[s(415)][s(1009)+s(1624)].replace(/\s/g,"").toLowerCase():""},Ae=_0x51c374[s(1009)+s(1624)]?_0x40a75a["payloadT"+s(1624)].replace(/\s/g,"")[s(850)+s(1774)]():"",yn=be[s(831)]?be[s(1097)]:Ae||be[s(1097)],Tt=pe.force?pe[s(806)]:de||pe[s(806)],br=[e[s(1291)],s(776)+s(825),e[s(1788)],"string"],Ya=[e[s(1489)],e.hLcdr];this._options["enableTr"+s(707)+s(1156)+"ad"]&&br[s(632)](yn)&&(!Tt||Ya[s(632)](Tt))?_0x13b99c[s(1234)+"oad"]=_0x47fe1b(_0x1be1f2[s(1177)],0,_0x4fbd3d[s(1177)][s(1826)+"th"]):_0x371a64[s(1234)+s(789)]=""}else _0x40b856[s(1234)+"oad"]="";else O=m[e[s(1191)](e[s(1602)](g,l),1)],B=m[e[s(786)](g+l,2)],e[s(624)](e[s(1490)](e.TKGXF(O,e.cZBQv(B,8)),49344),32896)?S+=y:($=e.xZlPS(e[s(479)](e.awMeu(e[s(666)](15,L),12),e[s(733)](63&O,6)),e[s(735)](63,B)),e.ypDeM($,2048)||e[s(923)]($,55296)&&e[s(696)]($,57343)?S+=y:(S+=h($),g+=2));else e.uKIGa(248&L,240)?e[s(1416)](e[s(1626)](g,3),r)?S+=y:(O=m[e[s(1346)](g+l,1)],B=m[e[s(635)](g,l)+2],F=m[e.YRPIf(e[s(1602)](g,l),3)],e.dRgYR(e[s(1241)](e[s(1241)](O,B<<8),e[s(1129)](F,16)),12632256)!==8421504?S+=y:($=e[s(1241)](e[s(479)](e[s(677)](7,L)<<18,(63&O)<<12),e[s(733)](63&B,6))|e.NeXAE(63,F),e[s(1319)]($,65536)||e[s(1020)]($,1114111)?S+=y:($-=65536,S+=e[s(1080)](h,e[s(1125)](e.VbfrB($,10),55296),e.BxCRp(e.mDZJz(1023,$),56320)),g+=3))):S+=y}return S}function qe(c,r){let s=t,l=r[s(1511)],h=0;for(let S=0;e.qYROV(S,l);S++){let g=r[s(1535)+"At"](S);e[s(1152)](g,55296)&&e[s(696)](g,56319)&&e.cnwRh(S+1,l)&&(g=e[s(1217)](e[s(1125)](e[s(394)](g,10),r[s(1535)+"At"](++S)),56613888)),h+=e[s(1435)](g,128)?1:e[s(503)](g,2048)?2:e[s(1435)](g,65536)?3:4}e[s(1229)](ae,c,h);let m=e[s(1358)](ie,c,h),y=c.bytes;for(let S=0;e[s(503)](S,l);S++){let g=r[s(1535)+"At"](S);if(e[s(1416)](g,55296)&&e[s(1839)](g,56319)&&e.iwKBp(e[s(406)](S,1),l)&&(g=e.SyMKf(e[s(1208)](e.cZBQv(g,10),r.charCodeAt(++S)),56613888)),e[s(1253)](g,128))y[m++]=g;else if(e.bCqgi(e.ldEuw,e[s(1621)])){let L=this[s(1022)][s(1598)](this[s(1142)]),O=_0x58319d.parse(e[s(903)](L,"{}"));return _0x499996[s(440)](O)}else{if(e[s(1529)](g,2048))y[m++]=e[s(1279)](e.KHPpx(e[s(1421)](g,6),31),192);else{if(e[s(930)](e[s(858)],e[s(524)]))return!0;g<65536?y[m++]=e[s(508)](e.sjxuT(e.VbfrB(g,12),15),224):(y[m++]=e.lnOeP(e.wBBmq(g,18)&7,240),y[m++]=e[s(1241)](e[s(1789)](g,12)&63,128)),y[m++]=e.CxfYQ(e.wBBmq(g,6),63)|128}y[m++]=e[s(1071)](e[s(1488)](63,g),128)}}}function C(c,r){let s=t,l=ie(c,r[s(975)]),h=c.bytes,m=r[s(604)];for(let y=0,S=r[s(975)];e[s(813)](y,S);y++)h[e[s(1626)](y,l)]=m[y]}function H(c){let r=t;if(e[r(330)](r(668),e[r(350)]))this["_miniNavigatorOn"+r(1769)]=_0x209f4c,_0x5f0f5c?this[r(1582)+r(870)]():this[r(1582)+"ffLine"]();else return c[r(604)][e[r(1161)](Y,c,1)]}function j(c,r){let s=t,l=e.hDEwf(ie,c,1);c[s(604)][l]=r}function ee(c){let r=t;if(e.sGjLB(e[r(426)],e.bHdRg))_0x54a07d-=65536,_0x36a2cc+=e[r(1239)](_0x13d3d8,e[r(1789)](_0x4c80e6,10)+55296,e[r(1346)](e.sXprw(1023,_0x8cbe10),56320)),_0x40bd6b+=3;else{let s=0,l=0,h;do h=e[r(556)](H,c),e.gPivP(s,32)&&(l|=e[r(1019)](127&h,s)),s+=7;while(e[r(1377)](128,h));return l}}function ae(c,r){let s=t;for(r>>>=0;e[s(1152)](r,128);)j(c,e[s(666)](127,r)|128),r>>>=7;e[s(1515)](j,c,r)}function st(c,r){let s=t,l=0,h=0,m=0,y;return y=e[s(1637)](H,c),l=e[s(550)](127,y),128&y&&(y=e[s(1273)](H,c),l|=e[s(1019)](e.mDZJz(127,y),7),128&y&&(y=H(c),l|=e[s(1578)](e[s(363)](127,y),14),128&y&&(y=e[s(974)](H,c),l|=e[s(733)](e[s(1377)](127,y),21),128&y&&(y=e[s(842)](H,c),h=e[s(1484)](127,y),128&y&&(y=H(c),h|=e[s(866)](127,y)<<7,e.KHPpx(128,y)&&(y=e[s(782)](H,c),h|=e[s(1129)](127&y,14),e.AaQJw(128,y)&&(y=e.TTirx(H,c),h|=e.ecfzz(127,y)<<21,e.mDZJz(128,y)&&(y=H(c),m=127&y,128&y&&(y=e[s(1058)](H,c),m|=e[s(1578)](e[s(995)](127,y),7)))))))))),{low:e.czqRE(l,h<<28),high:e[s(479)](e[s(589)](h,4),m<<24),unsigned:r}}function lt(c,r){let s=t,l=r[s(1272)]>>>0,h=e[s(361)](e[s(1482)](r[s(1272)],28),e.JDGGU(r.high,4))>>>0,m=e[s(537)](r[s(837)],24),y=e[s(1670)](0,m)?e[s(1544)](0,h)?e[s(1687)](l,16384)?e[s(756)](l,128)?1:2:e[s(1426)](l,2097152)?3:4:e[s(1529)](h,16384)?e[s(813)](h,128)?5:6:e[s(1202)](h,2097152)?7:8:e[s(1202)](m,128)?9:10,S=e[s(1391)](ie,c,y),g=c[s(604)];switch(y){case 10:g[S+9]=e[s(1766)](e[s(1146)](m,7),1);case 9:g[e[s(495)](S,8)]=e[s(868)](9,y)?e[s(936)](128,m):e[s(1228)](127,m);case 8:g[e[s(1223)](S,7)]=e[s(1633)](8,y)?e[s(1241)](e[s(1482)](h,21),128):e[s(1415)](e.fleJX(h,21),127);case 7:g[e[s(786)](S,6)]=e.mtimn(7,y)?e.ZEXca(e[s(1011)](h,14),128):e[s(667)](h,14)&127;case 6:g[e[s(1486)](S,5)]=e[s(683)](6,y)?e[s(416)](e[s(412)](h,7),128):e[s(1285)](e.ZvImf(h,7),127);case 5:g[S+4]=y!==5?e[s(558)](128,h):e[s(671)](127,h);case 4:g[e[s(635)](S,3)]=e[s(1574)](4,y)?e.OPwUG(l>>>21,128):e[s(511)](e.Vjjsk(l,21),127);case 3:g[e[s(1486)](S,2)]=y!==3?e[s(778)](l>>>14,128):l>>>14&127;case 2:g[e.SfwGr(S,1)]=e[s(1053)](2,y)?e[s(1240)](l>>>7,128):e.IVVrd(l>>>7,127);case 1:g[S]=e.NCAuK(1,y)?e[s(410)](128,l):e[s(1742)](127,l)}}function Ft(c){return e[t(842)](v,c)}function Qt(c){return e[t(1589)](b,c)}let mn=65536,qn=e[t(463)],mt=e.xLJTq(mn,mn),wr=e.xLJTq(mt,mt),Be=e[t(1311)](wr,2),me=String[t(501)+"e"][t(1535)+"At"];class ce{constructor(r,s,l){let h=t;this[h(413)]=!0,this[h(1272)]=e[h(746)](0,r),this[h(837)]=0|s,this[h(340)]=!!l}static[t(413)](r){return r&&e[t(930)](!0,r.isLong)}static[t(1015)](r,s,l){return new ce(r,s,l)}static[t(1138)+"s"](r,s,l){let h=t;return l?ce[h(1138)+h(909)](r,s):ce[h(1138)+h(1122)](r,s)}static[t(1138)+t(909)](r,s){let l=t;return new ce(e[l(479)](e[l(461)](e[l(1241)](r[0],e[l(1284)](r[1],8)),r[2]<<16),r[3]<<24),e[l(746)](e[l(557)](r[4],r[5]<<8),r[6]<<16)|e[l(1082)](r[7],24),s)}static[t(1138)+t(1122)](r,s){let l=t;return new ce(e[l(479)](e.hbGtG(e[l(1042)](r[4]<<24,e[l(1082)](r[5],16)),e[l(1129)](r[6],8)),r[7]),e[l(410)](e[l(1042)](e[l(508)](r[0]<<24,r[1]<<16),e[l(1284)](r[2],8)),r[3]),s)}static[t(860)](r){let s=t;if(e[s(1398)]("XEJOA",e[s(892)])){let l=this[s(837)],h=this[s(1272)];return[e[s(550)](255,h),e.pniNM(e[s(537)](h,8),255),e[s(708)](h>>>16,255),h>>>24,e[s(677)](255,l),e[s(443)](e.sJbui(l,8),255),e[s(1063)](e.Pwdjm(l,16),255),l>>>24]}else return r===qn?ft:new ce(e.bGoDa(e[s(1073)](e[s(1240)](e[s(361)](me[s(1603)](r,0),e.Xftyi(me[s(1603)](r,1),8)),e[s(1019)](me[s(1603)](r,2),16)),e[s(1016)](me[s(1603)](r,3),24)),0),(e[s(747)](me[s(1603)](r,4),e[s(672)](me.call(r,5),8))|e[s(1792)](me.call(r,6),16)|e[s(1578)](me.call(r,7),24))>>>0,!0)}[t(480)](){let r=t;return String[r(339)+"Code"](e[r(549)](255,this[r(1272)]),e[r(912)](e[r(412)](this[r(1272)],8),255),e.PIaED(e[r(1482)](this[r(1272)],16),255),e[r(689)](this[r(1272)],24),255&this[r(837)],e[r(783)](this[r(837)],8)&255,this.high>>>16&255,e[r(783)](this[r(837)],24))}static[t(686)+"er"](r,s=!0){let l=t;if(e[l(1058)](isNaN,r))return s?jg:ft;if(s){if(e[l(1416)](r,wr))return Kg}else{if(e.ZoWKd(r,-Be))return $g;if(e.BxCRp(r,1)>=Be)return Wg}return ce.fromBits(r%mt|0,e[l(716)](e[l(1186)](r,mt),0),s)}[t(1691)](){let r=t;return this[r(340)]?e[r(934)](e[r(1778)](this[r(837)],0)*mt,e.tOQNb(this.low,0)):e[r(1644)](this.high*mt,this[r(1272)]>>>0)}[t(1692)](){let r=t;return e[r(1475)](0,this[r(837)])&&e[r(771)](0,this[r(1272)])}add(r){let s=t;ce[s(413)](r)||(r=ce.fromNumber(r));let l=this.high>>>16,h=e[s(780)](65535,this[s(837)]),m=e[s(1816)](this[s(1272)],16),y=e[s(978)](65535,this[s(1272)]),S=e[s(1011)](r.high,16),g=65535&r[s(837)],L=e[s(997)](r[s(1272)],16),O=e.UiUPE(65535,r.low),B=0,F=0,$=0,pe=0;return pe+=e[s(1779)](y,O),$+=pe>>>16,pe&=65535,$+=e.JrReb(m,L),F+=e[s(1034)]($,16),$&=65535,F+=e[s(495)](h,g),B+=e.qdrnM(F,16),F&=65535,B+=l+S,B&=65535,ce.fromBits(e[s(1560)](e[s(370)]($,16),pe),e.vjLEp(B<<16,F),this[s(340)])}[t(1655)](r){let s=t;return ce[s(413)](r)||(r=ce[s(686)+"er"](r)),e[s(1633)](this.unsigned,r[s(340)])&&e[s(1174)](e[s(659)](this[s(837)],31),1)&&e[s(412)](r[s(837)],31)===1?!1:e[s(803)](this[s(837)],r.high)&&e[s(596)](this[s(1272)],r[s(1272)])}[t(1671)](){let r=t;if(e.KvTlD(e[r(1759)],e[r(1759)]))return e.SLRQL(-1,this[r(1272)])&&this[r(837)]===-1?ce.fromBits(0,0,this.unsigned):e.bCqgi(-1,this[r(1272)])?ce[r(1015)](0,e[r(1159)](this[r(837)],1),this.unsigned):ce[r(1015)](this[r(1272)]+1,this[r(837)],this[r(340)]);{let s=0,l={};for(let h=0;e[r(1573)](h,_0x365f04[r(1511)]);h++)l[_0x4d6abe[h][r(1195)+r(887)]]=e[r(1589)](_0x5b1a57,_0x30dfa1[h][r(1195)+r(887)]),s+=e[r(1208)](14,l[_0x2135ef[h]["cursor_n"+r(887)]]);return[s,l]}}[t(1386)](r){return r?this.toBytesLE():this.toBytesBE()}toBytesLE(){let r=t,s=this.high,l=this.low;return[e.rHhXt(255,l),e.fzvGv(l>>>8,255),e[r(1231)](e[r(1213)](l,16),255),l>>>24,e[r(1823)](255,s),e[r(511)](e[r(344)](s,8),255),e[r(1742)](e.qNQiQ(s,16),255),e[r(412)](s,24)]}[t(1320)+"E"](){let r=t,s=this[r(837)],l=this[r(1272)];return[e[r(562)](s,24),e[r(1414)](e[r(726)](s,16),255),e[r(735)](e.MQXbh(s,8),255),e[r(1056)](255,s),e[r(886)](l,24),e[r(838)](e[r(997)](l,16),255),e[r(667)](l,8)&255,e.vlODd(255,l)]}}let ft=new ce(0,0,!1),jg=new ce(0,0,!0),Wg=ce[t(1015)](-1,2147483647,!1),Kg=ce[t(1015)](-1,-1,!0),$g=ce[t(1015)](0,-2147483648,!1);var wn=(function(c){let r=t;if(e[r(1606)](e[r(861)],e[r(861)]))_0x38704a[_0x3fed59++]=e[r(1531)](_0x10b85d>>12,224),_0x235d79[_0x5b3c08++]=e[r(1241)](e.axwih(_0x103138>>6,63),128),_0x35176f[_0x85af31++]=e[r(778)](e.vlODd(63,_0x4d950e),128);else{let s=e[r(1364)][r(1622)]("|"),l=0;for(;;){switch(s[l++]){case"0":c[c[r(1643)+r(327)]=5004]=r(1643)+r(327);continue;case"1":c[c[e.Uzihf]=5001]=e[r(1498)];continue;case"2":c[c[e[r(1629)]]=5002]=e.VYhdC;continue;case"3":c[c[e.ZuxTy]=5003]=r(618)+r(943)+"R";continue;case"4":c[c[e.PFjqB]=5005]=e[r(914)];continue;case"5":return c}break}}})({});class _r{constructor(r){let s=t;this.type=r,this[s(1055)]=null}}class Bl extends _r{constructor(r,s){let l=t;super(r),this[l(1500)]=s&&s.message||null}}class zl extends _r{constructor(r,s){let l=t;super(r),this.error=s&&s[l(1746)]||null,this[l(988)]=s&&s.colno||0,this[l(829)]=s&&s.filename||"",this[l(965)]=s&&s[l(965)]||0,this[l(1500)]=s&&s[l(1500)]||"",this[l(1373)]=s&&s[l(1373)]||5001}}class Ul extends _r{constructor(r,s){let l=t,h=e[l(1356)][l(1622)]("|"),m=0;for(;;){switch(h[m++]){case"0":this[l(1061)+l(1755)]=s&&s[l(1061)+l(1755)]||!1;continue;case"1":this[l(828)]=s&&s.reason||"";continue;case"2":this[l(1373)]=s&&s[l(1373)]||0;continue;case"3":this[l(375)]=s&&s[l(375)]||!1;continue;case"4":super(r);continue}break}}}class Hl extends _r{constructor(r,s){let l=t;super(r),this[l(960)]=s&&s.data||null}}class ql extends Hl{constructor(r,s){let l=t;super(r),this.data=s&&s[l(960)]||null,this[l(1500)]=s&&s[l(1500)]||null}}class Gl extends _r{constructor(r,s){let l=t;super(r),this[l(960)]=s&&s[l(960)]||null}}function wt(c,{message:r,code:s,error:l}){return new zl(c,{message:r,code:s,error:l})}function kt(c,{code:r,reason:s,wasClean:l,willReconnect:h}){return new Ul(c,{code:r,reason:s,wasClean:l,willReconnect:h})}function jl(c,{data:r,message:s}){return new ql(c,{data:r,message:s})}function Wl(c,{data:r}){return new Gl(c,{data:r})}function ja(c,{message:r}){return new Bl(c,{message:r})}class Kl{constructor(r,s){let l=t;this[l(1155)+"s"]=r,this.maxRetries=s,this[l(1736)+l(901)]=0,this[l(1167)+l(758)+l(610)+"t"]=0}[t(1248)+t(902)+"fig"](){let r=t;this[r(1736)+r(901)]=0,this[r(1167)+r(758)+r(610)+"t"]=0}resetTries(){let r=t;this[r(1167)+r(758)+r(610)+"t"]=0}[t(478)+t(1025)+"nt"](){let r=t;return this[r(1155)+"s"][this[r(1736)+r(901)]]}[t(478)+t(1025)+t(1134)+t(883)](){let r=t;return this[r(1167)+r(758)+r(610)+"t"]}[t(882)+"chMaxTries"](){let r=t;return!!(e.TiDMR(this[r(1736)+r(901)],this[r(1155)+"s"][r(1511)])||e[r(1563)](this[r(1736)+r(901)],e[r(1219)](this.endpoints[r(1511)],1))&&this[r(1167)+r(758)+r(610)+"t"]===this[r(1634)+"es"])}[t(1594)+t(750)+t(401)+t(1550)+t(1664)](){let r=t;return e[r(1371)](this[r(1736)+r(901)],this[r(1155)+"s"][r(1511)])?!0:this[r(1167)+"ndpointT"+r(610)+"t"]>this[r(1634)+"es"]}[t(641)+t(1607)+"pointAnd"+t(1838)+t(502)](){let r=t;return this["currentE"+r(758)+"riesCount"]=1,this[r(1736)+r(901)]++,this[r(1155)+"s"][this["currentI"+r(901)]]}[t(478)+t(1025)+t(1697)+"ateCount"](){let r=t;if(r(1103)!==r(1365))return this[r(1167)+r(758)+r(610)+"t"]++,this[r(478)+r(1025)+"nt"]();{let s=e.TTirx(_0x17d6b8,_0x23e9de);this[r(1545)]&&e[r(596)](this[r(1545)][r(1558)+"te"],this[r(1547)])&&(this[r(1545)]&&this[r(1545)].send(s),this[r(1270)](e[r(1318)],_0x228564))}}}let yr=(e.lGVbw(e.nxLRQ,typeof globalThis)&&e.vcIsH(t(1837),globalThis[t(1447)+t(1628)][t(913)])||e[t(547)](t(1583)+"d",typeof window)&&e[t(1740)]===window[t(1447)+t(1628)][t(913)])&&e[t(777)](e[t(1733)],typeof document),Gn=e.nxLRQ!=typeof globalThis&&(e[t(1393)](t(1189),globalThis[t(1447)+"tor"].name)||e[t(1690)](e.QaVPB,globalThis.constructor[t(913)]))&&e[t(1342)](e[t(1733)],typeof tt),wi=(t(1583)+"d"!=typeof globalThis&&e.zXzlD(e.PLcqJ,globalThis[t(1447)+"tor"][t(913)])||e[t(916)](e.nxLRQ,typeof globalThis)||e[t(1367)](e[t(1733)],typeof globalThis)&&!!globalThis[t(387)+t(1787)])&&e.WTImg(e.nxLRQ,typeof wx),_i=e.zPlny("undefined",typeof globalThis)&&(e[t(1359)](t(1243)+t(1024)+"lobalScope",globalThis["construc"+t(1628)][t(913)])||e[t(857)](e.OmClq,globalThis[t(1447)+t(1628)][t(913)])||e.kJiwF(e.OIggd,globalThis["construc"+t(1628)].name))&&e[t(494)]("undefined",typeof self),Vg=e[t(1342)]("undefined",typeof globalThis)&&t(1189)===globalThis[t(1447)+"tor"][t(913)]&&e[t(679)](e.nxLRQ,typeof global)&&e.PLcqJ===global[t(1447)+t(1628)][t(913)]&&e[t(547)](e[t(1733)],typeof process)&&!!process[t(1465)];class Wa{constructor(){let r=t;this[r(833)+"rs"]={}}[t(910)](r,...s){let l=t;if(l(429)!==l(429)){let{type:h}=_0x44bcc1;this.emit(h,_0x593336)}else{let h=this._listeners[r];if(h)h[l(899)]().forEach(m=>m.fn[l(939)](m[l(1362)],s));else if(e[l(1054)]("error",r)&&!this[l(1577)])if(e[l(1606)](e[l(1812)],e[l(580)])){let m=s.length&&s[0];if(e[l(1537)](m,Error))throw m;let y=new Error(e[l(1722)](l(1282)+"d error.",m?e[l(811)](" ("+m.message,")"):""));throw y[l(1190)]=m,m}else{let m={wzNPW:e[l(1178)],owxYM:l(1369)+l(1150)+"s",GHasV:l(1118),ATNal:function(y,S,g){return e[l(1182)](y,S,g)},LCHzt:e[l(390)]};return new _0x2e25c5((y,S)=>{let g=l,L={nmOZq:function(F,$){return F($)},cMTHW:m[g(634)],KuSzW:m.owxYM,FpKup:function(F,$){return F($)},vhUWf:m[g(1005)]};this[g(1400)+g(490)](),this[g(435)+g(1576)+"Id"]=m[g(942)](_0x3b905f,this._ping[g(1305)](this),this[g(415)][g(1106)+g(859)]);let O=()=>{let F=g;L[F(1662)](y,L.cMTHW),this[F(670)](L[F(932)],O),this[F(670)](F(1369)+F(590)+"t",B)},B=()=>{let F=g;L[F(1737)](S,L.vhUWf),this[F(670)](L[F(932)],O),this.off("ping_onc"+F(590)+"t",B)};this.on(g(1369)+g(1150)+"s",O),this.on(m[g(627)],B),this[g(669)]()})}return this}}[t(670)](r,s){let l=t;if(e[l(1300)](e[l(1725)],e[l(1725)])){if(e[l(1174)](void 0,r))this._listeners={};else if(s===void 0)this[l(833)+"rs"][r]=null;else{let h=this._listeners[r];if(h)for(let m=0;e[l(1435)](m,h[l(1511)]);)e.VaWtC(h[m].fn,s)?h[l(1625)](m,1):++m}return this}else{this[l(1775)+l(1613)+l(927)](e.lDoRT(_0x5796a1,l(1175),{code:1e3,reason:e[l(948)]})),this._endpointManager?.[l(1248)+l(902)+l(1822)](),this[l(1252)+l(815)]?.["resetCou"+l(585)]();return}}on(r,s,l){let h=t;return(this[h(833)+"rs"][r]||(this[h(833)+"rs"][r]=[]))[h(567)]({fn:s,ctx:l||this}),this}}class Jg extends Wa{["_formatE"+t(1801)+"age"](r){let s=t;return e[s(1719)](e[s(1185)],"xuGkU")?r[s(843)]||r[s(1233)]?(s(578)+" "+(r[s(843)]||"")+s(644)+(r.errNo||""))[s(906)]():JSON[s(1353)+"y"](r):(this["currentE"+s(758)+s(610)+"t"]=1,this["currentI"+s(901)]++,this[s(1155)+"s"][this[s(1736)+s(901)]])}constructor(r,s,l){let h=t;super(),this[h(1227)]=null,wi&&wx[h(637)+h(358)]&&(this[h(1227)]=wx[h(637)+"ocket"]({url:r,protocols:s,header:l,fail:this["_createS"+h(1706)+"lHandler"][h(1305)](this),success:this[h(1721)+h(1506)+h(587)+h(1618)][h(1305)](this)})),Gn&&tt["connectS"+h(358)]&&(this._socket=tt[h(637)+h(358)]({url:r,protocols:s,header:l,fail:this[h(1721)+"ocketFailHandler"][h(1305)](this),success:this[h(1721)+h(1506)+h(587)+"ler"][h(1305)](this)}))}[t(1721)+t(1506)+"cessHand"+t(1618)](){let r=t;Promise.resolve()[r(1094)](()=>{this["_addWsLi"+r(956)]()})}[t(1721)+t(1706)+t(1165)](r){let s=t;Promise[s(1078)]()[s(1094)](()=>{let l=s,h=e[l(1239)](wt,e[l(360)],{message:this[l(1483)+l(1801)+l(568)](r)});this[l(910)](e[l(360)],h);let m=e.mZHKQ(kt,e.DeTlc,{reason:this[l(1483)+l(1801)+l(568)](r)});this.emit(l(1175),m)})}[t(1781)+"steners"](){let r=t,s={GsTDS:function(l,h){return l<=h},fZswD:function(l,h){return e[V(457)](l,h)},xrOaY:function(l,h){return e.JUOVw(l,h)},kfKgY:e.JNAsE,dLdfS:e.DeTlc,BsCAt:e.yfDjV,hEATR:function(l,h,m){return e[V(522)](l,h,m)},zxKzn:e[r(360)]};this._socket.onOpen(l=>{let h=r;this[h(910)](h(841),e[h(1444)](Wl,e[h(408)],{...l,data:l.errMsg||""}))}),this[r(1227)][r(744)](l=>{let h=r;if(s.kfKgY==="oEUiQ")this.emit(s.dLdfS,kt(s[h(642)],{...l}));else return s.GsTDS(_0x59f953,_0x1bbdda)?_0x2ee25e[h(869)](new _0x41ee08("next() c"+h(1503)+h(1703)+h(1555)+h(905))):(_0x45b7b9=_0x3e668d,s[h(1070)](_0x25beeb,_0x5391fd.length)?_0x51f014[h(1078)]():_0x558947[_0x4dcb14].bind(_0x17e55a)(_0x22fc59,_0x4f8244.bind(null,s[h(986)](_0xa751b7,1))))}),this[r(1227)][r(946)+"e"](l=>{let h=r;this.emit(s[h(1086)],s[h(1411)](jl,s[h(1086)],{...l}))}),this[r(1227)][r(1584)](l=>{let h=r;this.emit(s[h(969)],wt(s.zxKzn,{...l,message:l[h(843)]||""}))})}[t(933)](r){let s=t,l={JDMna:e[s(1653)],POTFw:s(458),gdaAr:e[s(360)],aybEv:function(h,m,y){return e[s(1035)](h,m,y)},TlmLd:function(h,m){return e[s(1573)](h,m)},EHnLh:function(h,m){return h|m},rUJpQ:function(h,m){return e.VbfrB(h,m)},aeVKd:function(h,m){return h===m},IaWyF:function(h,m){return e.OzFfV(h,m)},oHUFP:function(h,m){return e[s(1082)](h,m)},uJJBO:function(h,m){return h&m},rALTW:function(h,m){return h&m},AzMtb:function(h,m){return e.ynElw(h,m)},UuKad:function(h,m){return e[s(1303)](h,m)},fXknd:function(h,m){return h&m},Qfmvb:function(h,m){return e[s(890)](h,m)},jZJXE:function(h,m){return e.VaERx(h,m)},ATfyj:function(h,m){return h&m},jFOyg:function(h,m){return h>>m},JdXpZ:function(h,m){return e[s(354)](h,m)}};if(e[s(334)](r,Uint8Array))if(e.wUrVY(e[s(1502)],s(643))){let h=r.buffer[s(899)](r[s(1748)+"et"],r.byteLength+r.byteOffset);this[s(1227)]&&this._socket[s(933)]({data:h,fail:m=>{let y=s;if(l[y(1250)]===l[y(1158)])return{bytes:_0x32ab50,offset:0,limit:_0x43f017[y(1511)]};this[y(910)](l[y(471)],l[y(1557)](wt,l.gdaAr,{message:this[y(1483)+"rrorMess"+y(568)](m)}))}})}else _0x4fe2df=_0x1477b7[s(1535)+"At"](_0x51cf39),l[s(781)](_0x2af273,128)?_0x5eb70f[_0x47f4b4++]=_0x2739b4:l[s(781)](_0x16e4c1,2048)?(_0x4c3a78[_0x28c95e++]=l[s(423)](l[s(877)](_0x108776,6),192),_0x28242e[_0x5d4dd0++]=l.EHnLh(63&_0xd427a5,128)):(64512&_0x1cf26d)===55296&&l[s(436)](64512&(_0x3be645=_0x8ea60a.charCodeAt(_0x4329fc+1)),56320)?(_0x5138e0=l[s(730)](l[s(730)](65536,l.oHUFP(l[s(1701)](1023,_0x170401),10)),l.rALTW(1023,_0x161c85)),++_0x3cc4f2,_0x1a29c9[_0x2644e0++]=l[s(423)](l[s(520)](_0x5eae49,18),240),_0x15db48[_0x5df08e++]=l[s(1218)](l[s(475)](l.Qfmvb(_0x3008ca,12),63),128),_0xbd6d14[_0x4aa281++]=l[s(423)](_0x3781a4>>6&63,128),_0x36fa9d[_0x2a70e5++]=l[s(1612)](l[s(1040)](63,_0x42799f),128)):(_0x3e770d[_0x4edc39++]=l[s(1612)](l[s(520)](_0x13c91c,12),224),_0x5a8d91[_0x18b52a++]=l.UuKad(l[s(1673)](_0x58b497,6)&63,128),_0x48bdc8[_0x552ab1++]=l.JdXpZ(63,_0x157857)|128);else this[s(1227)]&&this[s(1227)][s(933)]({data:r,fail:h=>{let m=s;this[m(910)](e[m(360)],wt(e.pazKF,{message:this[m(1483)+"rrorMess"+m(568)](h)}))}})}close(r,s){let l=t;this[l(1227)]&&this[l(1227)][l(1175)]({code:r,reason:s})}[t(1107)+t(984)](r,s){this.on(r,s)}["removeEv"+t(1331)+t(441)](r,s){this[t(670)](r,s)}get[t(1558)+"te"](){return this[t(1227)].readyState}get[t(572)+"pe"](){return this._socket.binaryType}set[t(572)+"pe"](r){}get[t(397)](){return this._socket.url}get protocol(){let r=t;return this._socket[r(1449)]}get[t(521)+"ns"](){let r=t;return this._socket[r(521)+"ns"]}get[t(1648)+t(736)](){return 0}}function Zg(c,r){let s=t;if(r)return new r(c[s(397)],c[s(1449)]);if(wi||Gn)return new Jg(c[s(397)],c[s(1449)],c[s(497)]);if((yr||_i)&&e.FIkfE(s(1583)+"d",typeof WebSocket)&&WebSocket)return new WebSocket(c[s(397)],c[s(1449)+"s"])}function Xg(c){let r=t;if(e.dFARF(e.mIbZJ,e[r(1799)])){let s=new _0x310de8(e[r(1139)](2,_0x442f49));s[r(1753)](_0x48e846),_0x26ae06.bytes=s}else return!!(c||wi&&wx[r(637)+r(358)]||Gn&&tt["connectS"+r(358)]||e.EnZVE(yr,_i)&&e[r(1733)]!=typeof WebSocket&&WebSocket)}function $l(c,r,s){let l={SJSYV:function(y,S){return e[V(457)](y,S)},hGVaP:e.ngdnO,twkOH:e.LnzFc,VvSlR:function(y,S){return e[V(1663)](y,S)}},h=-1;async function m(y){let S=V;return l.SJSYV(S(855),l.hGVaP)?!!this._qosDB:y<=h?Promise[S(869)](new Error(l[S(518)])):(h=y,l.SJSYV(y,s[S(1511)])?Promise[S(1078)]():s[y].bind(c)(r,m[S(1305)](null,l.VvSlR(y,1))))}m(0)}function Vl(c){let r=t;if(r(1609)===e[r(660)]){let s=0,l=0;for(let h=0;e[r(1529)](h,c[r(1511)]);++h)l=c[r(1535)+"At"](h),e[r(879)](l,128)?s+=1:l<2048?s+=2:e.MODao(e[r(1231)](64512,l),55296)&&e.WFkpQ(e[r(1488)](64512,c[r(1535)+"At"](e[r(1159)](h,1))),56320)?(++h,s+=4):s+=3;return s}else _0x38e1ca=e[r(351)](_0x3e3ebd,_0x17902c),_0x23bca6|=e[r(888)](127,_0xc6fde9)<<14,e[r(1821)](128,_0x347a26)&&(_0x18b12b=e.Elxhy(_0x464767,_0x54aaf2),_0x20bb1f|=(127&_0x4802a9)<<21,e[r(728)](128,_0x48ea73)&&(_0x36d727=e[r(1273)](_0xba2b28,_0x45af46),_0x1aa475=127&_0x210b54,e[r(489)](128,_0x54632d)&&(_0x5b29ae=e[r(1072)](_0x44be48,_0x296c8d),_0x70c934|=e[r(505)](127,_0x3a17fc)<<7)))}function Jl(c,r,s){let l=t,h={HVyXr:function(y,S,g){return y(S,g)},CbIoi:function(y,S,g){return e.UYXhv(y,S,g)},LJxTM:function(y,S){return y(S)}};if(e[l(1198)](s-r,1))return"";let m="";for(let y=r;y<s;){let S=c[y++];if(e[l(1396)](S,127))m+=String[l(339)+l(710)](S);else if(e[l(1616)](S,192)&&e[l(343)](S,224))m+=String["fromChar"+l(710)](e[l(1192)](e.rfMEp(e[l(489)](31,S),6),e[l(1808)](63,c[y++])));else if(e[l(1616)](S,224)&&S<240)m+=String[l(339)+l(710)](e[l(1049)](e.XALOa(e[l(760)](15&S,12),e.CPIcI(63&c[y++],6)),e[l(354)](63,c[y++])));else if(S>=240)if(e[l(398)]("aNphJ",e.AgbFU))lznxOx[l(1187)](_0x16674d,_0x161740,24),lznxOx[l(388)](_0x29eb9f,_0x2695d2,lznxOx[l(1288)](_0x27ddbb,_0x5de5dd));else{let g=e[l(1650)](e[l(1560)](e.JWsTb(e.xZlPS(e[l(1284)](e[l(1488)](7,S),18),e[l(718)](63,c[y++])<<12),e.IrpXn(e.IWAan(63,c[y++]),6)),e[l(456)](63,c[y++])),65536);m+=String[l(339)+l(710)](e[l(1720)](55296,e[l(890)](g,10))),m+=String[l(339)+"Code"](56320+e[l(549)](1023,g))}}return m}function Ka(c,r,s){let l=t,h=s,m,y;for(let S=0;e[l(1573)](S,c[l(1511)]);++S)m=c[l(1535)+"At"](S),e[l(1435)](m,128)?r[s++]=m:e.MKKDS(m,2048)?(r[s++]=e[l(1042)](e[l(1075)](m,6),192),r[s++]=e[l(1314)](63&m,128)):e[l(1032)](64512,m)===55296&&e.jhpkX(e.EQclM(64512,y=c.charCodeAt(e[l(1159)](S,1))),56320)?(m=e.BGRKN(e.EjuLn(65536,e[l(1048)](e[l(1488)](1023,m),10)),e[l(1228)](1023,y)),++S,r[s++]=m>>18|240,r[s++]=e[l(361)](e[l(1075)](m,12)&63,128),r[s++]=e.Vzlwk(e[l(444)](e[l(1075)](m,6),63),128),r[s++]=e.bVmHI(63,m)|128):(r[s++]=e.tKumJ(e[l(1789)](m,12),224),r[s++]=e[l(1193)](e[l(366)](e[l(1075)](m,6),63),128),r[s++]=e[l(671)](63,m)|128);return s-h}async function Zl(c){let r=t;if(e[r(1054)](e[r(445)],e[r(445)])){if(e.uKIGa(e.ASApT,typeof c)){let s=new Uint8Array(e[r(1522)](Vl,c));return e[r(957)](Ka,c,s,0),s}return e.bighX(c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c.buffer,c[r(1748)+"et"],c[r(1826)+"th"])}else _0x16dba9<65536?_0x107b68[_0x2615f0++]=e[r(1160)](_0x1f224e>>12,15)|224:(_0x68d290[_0x954a47++]=e.XLJxZ(e.cJnSv(e[r(890)](_0x4e440f,18),7),240),_0x31f896[_0x2e03de++]=e[r(647)](_0x39a276>>12,63)|128),_0x33b8d2[_0x170a67++]=e[r(651)](e.yGMSe(e[r(1834)](_0x25f1bc,6),63),128)}function Yg(c){let r=t;try{return e[r(1473)](e.ASApT,typeof c)&&(e[r(779)](c,ArrayBuffer)||c[r(476)]&&c.buffer instanceof ArrayBuffer)||e[r(1473)](e[r(1533)],typeof c)?"":(JSON[r(1471)](c),e[r(570)])}catch{return e.QTJgX("string",typeof c)?e[r(1291)]:""}}let Qg=(c,r)=>{let s=t;switch(c){case e[s(699)]:case e[s(823)]:return{[s(1306)+c]:1,"x-tt-env":r};default:return{}}};class em{constructor(r){let s=t;this[s(941)+s(883)]=r,this[s(1215)]=0}addCount(){let r=t;this[r(1215)]++}["checkRea"+t(328)+"nt"](){let r=t;return this[r(1215)]>=this[r(941)+"ount"]}[t(553)+t(585)](r=0){let s=t;this[s(941)+s(883)]=r,this[s(1215)]=0}}async function tm(c){let r={mJZvu:function(s,l){return s>=l},OQioa:function(s,l){return e[V(1396)](s,l)},rWLTm:function(s,l){return e[V(900)](s,l)},MenhZ:function(s,l){return e[V(1705)](s,l)},fMogO:function(s,l){return e[V(1219)](s,l)},sZwMi:function(s,l){return e[V(1316)](s,l)},ckYAX:function(s,l){return e[V(1071)](s,l)},kInzc:function(s,l){return s&l},QgZwb:function(s,l){return s>>l},fgznZ:function(s,l){return e[V(508)](s,l)},KAMeV:function(s,l){return e.DKbIF(s,l)},qxgOO:function(s,l){return e[V(1635)](s,l)},PLRLe:function(s,l){return s&l},SQNXi:function(s,l){return e[V(1049)](s,l)},wdWHz:function(s,l){return e[V(888)](s,l)},gXDDE:function(s,l){return e.YVLJW(s,l)}};return new Promise(s=>{let l=V,h={bwzUQ:function(m,y){return e[V(485)](m,y)}};if(!yr)return e.RZXXc(s,e[l(1497)]);try{let m=document[l(1067)+"ement"](e[l(1076)]);window["frontier"+l(1712)]=y=>{let S=l;document[S(1660)].removeChild(m),window["frontier"+S(1712)]=void 0,h[S(449)](s,y&&y[S(1641)]||S(1277)+"reason")},m[l(1097)]=e[l(926)],m[l(1153)]=e.laxJv(c.replace(/^ws/,e[l(1640)]),e[l(925)]);try{if(e.MeyjV(e[l(854)],"bHYzT"))document.body[l(729)+"ild"](m);else{let y=_0x1f2955[l(1535)+"At"](_0x278f08);TqTFFQ[l(1679)](y,55296)&&TqTFFQ.OQioa(y,56319)&&TqTFFQ[l(1446)](TqTFFQ[l(904)](_0x682e95,1),_0x5a5274)&&(y=TqTFFQ[l(1210)](TqTFFQ.MenhZ(TqTFFQ[l(1327)](y,10),_0x41cc27.charCodeAt(++_0x10cba1)),56613888)),TqTFFQ.rWLTm(y,128)?_0x30d876[_0x30625c++]=y:(y<2048?_0x443941[_0x562237++]=TqTFFQ[l(740)](TqTFFQ[l(1269)](TqTFFQ[l(1088)](y,6),31),192):(TqTFFQ[l(1446)](y,65536)?_0x25b65f[_0x5175c2++]=TqTFFQ[l(929)](TqTFFQ[l(1246)](y>>12,15),224):(_0x400884[_0x3faa2f++]=TqTFFQ[l(1328)](TqTFFQ[l(1422)](TqTFFQ[l(1088)](y,18),7),240),_0x3b9130[_0x5b49ed++]=TqTFFQ[l(1237)](TqTFFQ[l(807)](y>>12,63),128)),_0x1da705[_0x5c170e++]=TqTFFQ[l(807)](y>>6,63)|128),_0x260f50[_0x1ff680++]=TqTFFQ[l(1328)](TqTFFQ[l(594)](63,y),128))}}catch{document.body[l(966)+"ild"](m)}}catch{window[l(757)+l(1712)]=void 0,e[l(1286)](s,l(1277)+"reason")}})}function _n(c,r,s){let l=t;return!!c?.[l(526)](h=>h[l(1683)]===r&&h[l(1595)]===s)}function Er(c,r){let s=t;return c?.find(l=>l[s(1683)]===r)?.value}let $a=null;async function nm(){let c=t;return $a||($a=Promise[c(1078)]()[c(1094)](Xt[c(1305)](Xt,e[c(607)]))),$a}class rm extends Wa{constructor(r,s){let l=t;super(),this._dbName=r,this[l(973)]=s,this[l(1022)]=void 0,this[l(1688)+"mise"]=null}async[t(876)](){await this[t(534)]()}async _init(){let r=t,s={xVdmo:e[r(1527)],lDhIq:function(l){return l()},Ldpte:e[r(1372)],iSbno:e[r(1498)],iLiCb:r(1135)+"NG_ERROR",gUFBs:e[r(914)],RYELQ:e.JUACX};if(e[r(868)](e.YdQtf,e[r(1099)])){if(this[r(1022)])return;if(this[r(1688)+r(991)])return this["_initPro"+r(991)];try{let l=this[r(1667)],h=this[r(973)];this[r(1688)+r(991)]=(async()=>{let m=r;if(s[m(864)]===m(1404)){let{openDB:y}=await s[m(1538)](nm);this[m(1022)]=await y(m(757)+"_"+l,1,{upgrade(S){let g=m;S[g(1112)+g(565)+"e"](l,{keyPath:h})}})}else this._ws&&this[m(1545)][m(1175)](_0x4c41d3,_0x2fe200)})(),await this._initPromise}catch(l){console[r(1492)](l)}finally{this[r(1688)+r(991)]=null}}else{let l=(r(1698)+r(345))[r(1622)]("|"),h=0;for(;;){switch(l[h++]){case"0":_0x546ee8[_0xd36d6b["MAX_RETR"+r(943)+"R"]=5003]=MYploE[r(1171)];continue;case"1":_0xcb43d5[_0x217cb9[MYploE[r(1322)]]=5001]=MYploE[r(1322)];continue;case"2":return _0x371d54;case"3":_0x460208[_0x8ab6b[r(1135)+"NG_ERROR"]=5002]=MYploE.iLiCb;continue;case"4":_0xb0317e[_0x3d4b07.OPEN_ERROR=5005]=MYploE.gUFBs;continue;case"5":_0x8a2d3a[_0x4d34ed[MYploE[r(820)]]=5004]=MYploE[r(820)];continue}break}}}async get(r){let s=t;if(e[s(1354)]!==e[s(439)])try{return await this._init(),this[s(1022)]?.get(this[s(1667)],r)}catch(l){console.log(l)}else{let l=s(1079)+_0x3d89f6+(s(1059)+s(1597)+s(1399)+s(455));this[s(1270)](l),this["_dispatc"+s(863)+s(927)](e[s(383)](_0x587d2e,e[s(360)],{message:l,code:_0x3af225[s(618)+s(943)+"R"]}));return}}async[t(1753)](r,s){let l=t;return await this._init(),this[l(1022)]?.[l(1434)](this._dbName,r)}async[t(714)](r){let s=t,l={PtiBS:s(1369)+s(1150)+"s",zVEFc:e[s(1178)],qvHMD:function(h,m,y){return e[s(1348)](h,m,y)}};if(e[s(1145)]!==e[s(1363)])try{return await this[s(534)](),this[s(1022)]?.[s(1258)](this._dbName,r)}catch(h){console[s(1492)](h)}else this["_clearPi"+s(490)](),this[s(910)](l[s(419)],l[s(920)]),this[s(435)+"gTimeoutId"]=l.qvHMD(_0x4d0f5c,this._ping[s(1305)](this),_0x58ba6f)}async[t(1433)](){let r=t;try{return await this[r(534)](),this[r(1022)]?.[r(1433)](this[r(1667)])}catch(s){console.log(s)}}async[t(440)](){let r=t;return await this[r(534)](),this[r(1022)]?.[r(693)+"ys"](this[r(1667)])}async[t(1302)](){let r=t;return await this[r(534)](),this[r(1022)]?.[r(1302)](this[r(1667)])}async[t(796)](){let r=t;try{this[r(1022)]?.[r(1175)](),this[r(1022)]=void 0}catch(s){console[r(1492)](s)}}get[t(1599)](){let r=t;try{return!!this[r(1022)]}catch(s){return console[r(1492)](s),!1}}}class im{constructor(r,s){let l=t;this[l(845)]=r,this[l(884)]=s,this._qosDB=localStorage}async openDB(){}get[t(1142)](){return"frontier_"+this[t(845)]}async get(r){let s=t;if(e.DALlo(s(1409),e[s(623)])){let l=_0x4acdd1(e[s(360)],{message:this[s(1483)+s(1801)+"age"](_0x2ba7d)});this[s(910)](e[s(360)],l);let h=e.hKtLi(_0x5d3bc7,e.DeTlc,{reason:this[s(1483)+s(1801)+s(568)](_0x3bf29b)});this[s(910)](e[s(1455)],h)}else{let l=this[s(1022)][s(1598)](this[s(1142)]);return JSON[s(1471)](e[s(609)](l,"{}"))[r]}}async[t(1753)](r,s){let l=t,h={zBSsg:l(648)};if(l(1517)===e.WLLRf){let m=this[l(1022)][l(1598)](this[l(1142)]),y=JSON[l(1471)](e[l(331)](m,"{}"));return y[s||r[this._pathKey]]=r,this[l(1022)][l(1057)](this[l(1142)],JSON[l(1353)+"y"](y)),s||r[this[l(884)]]}else _0xbd4868=h[l(1646)],_0x386045=_0x2a294a[l(1631)](/(^http)((?:[s]*:\/\/))/,""),_0x536254=/(^ws)((?:[s]*:\/\/))/.test(_0x52e7da)?_0x4fe21f:""+_0x270088+_0x12ecaf}async del(r){let s=t,l=this[s(1022)][s(1598)](this[s(1142)]),h=JSON[s(1471)](e.tEWcg(l,"{}"));return h[r]=void 0,this._qosDB.setItem(this[s(1142)],JSON.stringify(h))}async[t(1433)](){let r=t;return this._qosDB[r(1433)]()}async keys(){let r=t;if(e[r(330)](e.SDuRP,e[r(752)])){let s=this[r(1022)].getItem(this[r(1142)]),l=JSON[r(1471)](e[r(331)](s,"{}"));return Object[r(440)](l)}else return}async[t(1302)](){let r=t,s=this._qosDB[r(1598)](this[r(1142)]),l=JSON.parse(e.padRW(s,"{}"));return Object.values(l)}[t(796)](){return Promise[t(1078)]()}get[t(1599)](){return!!this._qosDB}}class sm{constructor(r,s){let l=t;this[l(845)]=r,this[l(884)]=s,this[l(1022)]=Gn?tt:wi?wx:null}async[t(876)](){}get[t(1142)](){let r=t;return r(757)+"_"+this[r(845)]}async[t(1326)](r){let s=t,l=this[s(1022)][s(1299)+s(1714)](this[s(1142)]);return JSON[s(1471)](e[s(428)](l,"{}"))[r]}async[t(1753)](r,s){let l=t,h=this[l(1022)][l(1299)+"geSync"](this[l(1142)]),m=JSON[l(1471)](e[l(1620)](h,"{}"));return m[s||r[this[l(884)]]]=r,this._qosDB[l(1230)+l(1714)](this[l(1142)],JSON[l(1353)+"y"](m)),s||r[this[l(884)]]}async[t(714)](r){let s=t,l=this[s(1022)][s(1299)+s(1714)](this[s(1142)]),h=JSON[s(1471)](l||"{}");return h[r]=void 0,this[s(1022)][s(1230)+s(1714)](this[s(1142)],JSON[s(1353)+"y"](h))}async[t(1433)](){let r=t,s={ygkmD:function(l,h){return e[V(1836)](l,h)},AEWum:e[r(1820)]};if(r(1758)!=="UnrlV"){let l=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(_0x31c03e),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(945)](_0x36daf5);return l?_0x1dc900(_0x372b8d):h?uBoESo[r(536)](_0x4ab117,_0x2f9040):uBoESo.AEWum}else return this[r(1022)][r(935)+r(751)]()}async[t(440)](){let r=t,s=this[r(1022)][r(1299)+r(1006)+"nc"](this[r(1142)]),l=JSON.parse(e[r(1832)](s,"{}"));return Object[r(440)](l)}async getAll(){let r=t,s=this[r(1022)][r(1299)+r(1006)+"nc"](this[r(1142)]),l=JSON[r(1471)](e[r(1046)](s,"{}"));return Object[r(1290)](l)}[t(796)](){return Promise[t(1078)]()}get[t(1599)](){return!!this[t(1022)]}}function Xl(c,r){let s=t;if(e[s(950)]!==e[s(532)]){if(Gn||Gn)return new sm(c,r);if(e[s(1201)](yr,_i)&&e[s(1473)](s(1583)+"d",typeof indexedDB))return new rm(c,r);if(e[s(428)](yr,_i)&&e[s(679)](e[s(1733)],typeof localStorage))return new im(c,r);throw new Error(e.Vvtxe)}else this.on(_0x473c04,_0x42bc72)}class om{constructor(){let r=t;this._intervalTimeoutId=null,this[r(616)+"l"]=36e5,this[r(1022)]=e[r(1226)](Xl,e[r(1487)],e[r(1452)])}async[t(616)+t(1115)](){let r=t,s={xVHgw:function(l,h,m){return e[V(1695)](l,h,m)},idtwm:function(l,h,m){return e[V(1695)](l,h,m)},YzqwA:function(l,h,m,y){return e[V(576)](l,h,m,y)},GDFNd:function(l,h){return e[V(1602)](l,h)}};if(e[r(1606)](e.LXvWr,r(516)))e.AJVvN(clearInterval,this[r(616)+r(700)+"Id"]),this["_interva"+r(700)+"Id"]=e[r(1507)](setInterval,()=>{let l=r;this[l(1283)+l(1387)]()},this[r(616)+"l"]);else{let{offset:l}=s[r(814)](_0x4e8ad0,_0x39a30d,_0xac8aed);_0x4df0af=l;let h={cursor_name:"",cursor:0,service:0},{value:m,offset:y}=s[r(675)](_0x13ad97,_0x5b8ed2,_0x5203ff);h[r(1566)]=m,_0x1a4e88=y;let{value:S,offset:g}=s[r(675)](_0x470926,_0x8a44ef,_0x9f3fdf);_0x2dc62b=g,h[r(1195)+r(887)]=s[r(454)](_0x1dbf53,_0x4e3f46,_0x57f090,s.GDFNd(_0x1548f5,S)),_0x32cf8e+=S;let{value:L,offset:O}=_0x3dbd49(_0x4c9a06,_0x4b58e5);h[r(658)]=L[r(1691)](),_0x4515fa=O,_0x398797[r(567)](h)}}async openDB(){let r=t;e[r(1222)](e[r(1760)],e.ZrPcf)?this[r(833)+"rs"]={}:await this[r(1022)][r(876)]()[r(1094)](()=>{let s=r,l={eZeuu:function(h,m){return e.QcgRi(h,m)},KIjee:e[s(1533)],ILnOl:function(h,m,y,S){return e[s(957)](h,m,y,S)},WcrtB:function(h,m){return e[s(1757)](h,m)}};if(e[s(1670)](e[s(1739)],e[s(1739)]))this._intervalFlush();else{if(QJCZyb.eZeuu(QJCZyb[s(1018)],typeof _0xde2df4)){let h=new _0x326d1d(_0x55f16d(_0x17f6aa));return QJCZyb.ILnOl(_0x2e8b1d,_0x4e1899,h,0),h}return QJCZyb[s(1166)](_0x571b87,_0x598132)?new _0x432e2e(_0x439d8b):new _0x3e6611(_0x55d736[s(476)],_0x10da62[s(1748)+"et"],_0x18d314.byteLength)}})}async[t(1283)+t(1387)](){let r=t;(await this[r(1022)]?.getAll()||[])[r(653)](({timestamp:h})=>h<Date[r(559)]()).forEach(h=>{let m=r,y={ptRaH:e[m(835)]};e[m(1593)](e[m(1344)],e[m(1344)])?this[m(1022)]?.del(h[m(1256)+"id"]):(this[m(910)](y.ptRaH,_0x3456c1),this[m(1716)+"eAck"]&&this[m(1716)+m(1827)](_0xbe19d0))})}async[t(714)](r){let s=t;return this._qosDB?.[s(714)](r)}async[t(1753)](r,s){let l=t;return this[l(1022)]?.[l(1753)]({message_id:r,timestamp:s})}async[t(1326)](r){let s=t;return e.kHaAc===s(1298)?this._ws?this[s(1545)].extensions:"":this[s(1022)]?.get(r)}async[t(796)](){let r=t;e.RZXXc(clearInterval,this[r(616)+"lTimeoutId"]),await this[r(1022)]?.[r(796)]()}get[t(1599)](){let r=t;return this[r(1022)]?.[r(1599)]}}function Va(c){let r=t;if(e[r(622)]===r(959)){let s=!!this[r(415)][r(396)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(957)](_n,c[r(1500)][r(497)],e.CofPZ,"2"),h=l&&e[r(1445)](_n,c[r(1500)][r(497)],e[r(759)],"1"),m=l&&e[r(957)](_n,c[r(1500)].headers,e.XrhJk,"1"),y=m?Er(c[r(1500)][r(497)],e.WUTJW)?.[r(1622)](",")[r(653)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:m,ackMsgIds:y}}else this[r(1545)]&&this[r(1545)][r(933)](_0x523bc9),this._debug(e.MrTce,_0x489cdc)}async function Yl(){let c=t,r={FsMkz:function(s,l){return e.pfiIB(s,l)},DrmLe:function(s){return e[V(1148)](s)}};if(e.ybSjd(e[c(681)],e[c(681)]))aVAvti[c(702)](_0x48e337,_0x2c146f[c(1746)]),aVAvti[c(737)](_0x4d5bc4);else return this[c(1793)+"ger"]||(this[c(1793)+c(1128)]=new om),this[c(1793)+c(1128)][c(1599)]||await this[c(1793)+c(1128)].openDB(),this["_QoSMana"+c(1128)]}async function am(c,r){let s=t,{enableAutoAck:l}=this._options,h=e.EKTmn(_n,c[s(1500)][s(497)],e.voTct,"1"),m=e[s(576)](_n,c[s(1500)][s(497)],e[s(755)],"1"),y=Va[s(1603)](this,c);if(e[s(981)](l,h))if(s(1669)===e.RzhKT){let{SeqID:S,LogID:g,service:L,LogIDNew:O,method:B}=c.message;this[s(1220)]({SeqID:S,LogID:g,LogIDNew:O,service:L,method:B,headers:[{key:e[s(755)],value:"1"},{key:e[s(1608)],value:e[s(1747)](O,"")},{key:s(873),value:"0"}]})}else{let S=_0x47aef1[s(1523)]();return S?(S[s(417)]=S[s(975)]=0,S):{bytes:new _0x4667d6(64),offset:0,limit:0}}m&&!y[s(734)]&&this["_dispatc"+s(382)+s(1570)](c),e[s(1505)](r)}async function cm(c,r){let s=t;this._debug(s(717),c.message),r()}async function dm(c,r){let s=t,l={tUqhy:function(h,m){return h!=m},JAACJ:e[s(1733)],Ydrnp:function(h,m,y){return e.ZWZKD(h,m,y)},xjpIn:function(h,m,y,S){return h(m,y,S)},UQpDW:function(h,m){return e.ieOUx(h,m)},jvixC:function(h,m,y){return e[s(571)](h,m,y)}};if(s(722)!==e[s(1249)]){let h=e[s(1023)](Ft,await e.eOmtB(Zl,c[s(960)]));try{if(e[s(983)](s(809),e[s(1281)]))return!!(_0xa96d34||_0x40ecc2&&_0x3d9ecb[s(637)+"ocket"]||_0x4b7bed&&_0x1be3ef[s(637)+s(358)]||(_0x3d93f0||_0x5044b5)&&mzKLzw[s(1464)](mzKLzw[s(1711)],typeof _0x57866e)&&_0x176384);if(e[s(334)](h[s(1177)],Uint8Array)){let m=e.bighX(this[s(415)][s(391)+s(1143)],Object)?{force:!!this[s(415)][s(391)+s(1143)][s(831)],encoding:this[s(415)].payloadEncoding[s(806)]?this[s(415)][s(391)+s(1143)][s(806)][s(1631)](/\s/g,"")[s(850)+"ase"]():""}:{force:!1,encoding:this[s(415)][s(391)+s(1143)]?this._options[s(391)+s(1143)][s(1631)](/\s/g,"")[s(850)+s(1774)]():""},y=h[s(391)+s(1143)]?h[s(391)+s(1143)][s(1631)](/\s/g,"").toLowerCase():"",S=e[s(1767)](this[s(415)][s(1009)+"ype"],Object)?{force:!!this._options[s(1009)+"ype"][s(831)],type:this[s(415)][s(1009)+s(1624)].type?this[s(415)].payloadType[s(1097)][s(1631)](/\s/g,"")[s(850)+s(1774)]():""}:{force:!1,type:this[s(415)]["payloadT"+s(1624)]?this[s(415)][s(1009)+s(1624)][s(1631)](/\s/g,"")[s(850)+"ase"]():""},g=h["payloadT"+s(1624)]?h[s(1009)+"ype"][s(1631)](/\s/g,"")[s(850)+s(1774)]():"",L=S[s(831)]?S[s(1097)]:g||S.type,O=m.force?m[s(806)]:y||m[s(806)],B=[e.IINBX,e[s(570)],s(776)+s(825)+s(856)+s(1472),e[s(1533)]],F=[s(784)+"e",e[s(1014)]];this[s(415)][s(1470)+s(707)+s(1156)+"ad"]&&B.includes(L)&&(!O||F.includes(O))?h.textPayload=e[s(1292)](Jl,h[s(1177)],0,h.payload[s(1826)+"th"]):h["textPayl"+s(789)]=""}else h[s(1234)+s(789)]=""}catch(m){h[s(1234)+s(789)]="",console.log(m)}c[s(1500)]=h,e.tSYcb(r)}else{let h=0,m=[];for(;h<_0x332b8c[s(1826)+"th"];){let{offset:y}=l.Ydrnp(_0x5f5929,_0x4b0e86,h);h=y;let S={cursor_name:"",cursor:0,service:0},{value:g,offset:L}=l.Ydrnp(_0x3d69c5,_0x572638,h);S[s(1566)]=g,h=L;let{value:O,offset:B}=_0x283911(_0x182db4,h);h=B,S[s(1195)+s(887)]=l[s(1136)](_0x5848d1,_0x313fc1,h,l[s(1501)](h,O)),h+=O;let{value:F,offset:$}=l[s(1301)](_0x67eb11,_0x114f5c,h);S.cursor=F[s(1691)](),h=$,m[s(567)](S)}return m}}function lm(c,r,s){let l=t,h=e[l(889)](s,8192),m=h>>>1,y=null,S=h;return function(g){let L=l;if(e[L(900)](g,1)||e[L(1020)](g,m))return e[L(1428)](c,g);e[L(1779)](S,g)>h&&(y=c(h),S=0);let O=r.call(y,S,S+=g);return 7&S&&(S=e[L(1528)](7,S)+1),O}}let fm=4294967295;function um(c,r,s){let l=t;return e[l(1674)](RangeError,e[l(1403)](e[l(1705)](e[l(769)](e.LMZwy(e.LkhjI,c),e[l(1806)]),r||1)+e[l(862)],s))}function hm(c,r,s){let l=t;if(e[l(1493)](s,fm))throw new Error(e[l(972)]);let h=3;for(;e[l(1616)](h,0);){let m=e[l(1415)](255,s);Za(m,c,e.LMZwy(r,h)),s>>>=8,h--}return e[l(1779)](r,4)}function xm(c,r){let s=t;if(e[s(546)]!=="JbPKx")this[s(1022)]?.[s(714)](_0x33538c[s(1256)+"id"]);else{let l=0,h=r,m=r+4;for(;e[s(1198)](h,m);){let{value:y,offset:S}=e[s(1553)](Ja,c,h);h=S,l=e[s(319)](e[s(733)](l,8),0),l+=y}return{value:l,offset:m}}}function pm(c,r,s){let l=t;if(e[l(1728)](e[l(353)],e[l(353)]))return _0x54d960 instanceof _0x4dad0e&&(rxVpOu[l(1221)](_0x4923c0,rxVpOu[l(908)])||rxVpOu[l(596)](_0x41545d,rxVpOu[l(1293)]))?!0:rxVpOu.QztgY(_0x290eee,_0x428517);{let h=e[l(739)][l(1622)]("|"),m=0;for(;;){switch(h[m++]){case"0":if(!c)return s;continue;case"1":if(r[l(326)+"e"])return e[l(1297)](r[l(326)+"e"](c,s),s);continue;case"2":return e.ILrrY(e[l(612)](Ka,c,r,s),s);case"3":if(c.length<40)return e.hIiDm(Ka(c,r,s),s);continue;case"4":if(r[l(1684)])return r[l(1684)](c,s)+s;continue}break}}}function gm(c,r){let s=t,l=new ce(e[s(1314)](e[s(1279)](e[s(804)](c[e[s(743)](r,4)],24),e.HEuSu(c[e[s(961)](r,5)],16))|c[r+6]<<8,c[e.Ecwql(r,7)]),e[s(1560)](e.QeBbx(e.mkzVT(e[s(1316)](c[e[s(1602)](r,0)],24),e[s(1316)](c[e[s(1045)](r,1)],16)),e[s(1477)](c[e[s(1681)](r,2)],8)),c[r+3]),!0);return r+=8,{value:l,offset:e.gFMeO(r,8)}}function mm(c,r,s){let l=t,h=c[l(1272)],m=c.high;return r[s]=m>>>24,r[e[l(1779)](s,1)]=e[l(706)](m>>>16,255),r[e.eKtDn(s,2)]=e[l(1228)](e[l(374)](m,8),255),r[e[l(1212)](s,3)]=e[l(846)](255,m),r[e[l(1602)](s,4)]=e.BDmaw(h,24),r[e[l(1705)](s,5)]=e[l(1638)](h,16)&255,r[e[l(1163)](s,6)]=e[l(962)](e[l(1211)](h,8),255),r[s+7]=e.yTcwZ(255,h),s+=8,s}function Ja(c,r){let s=t;return c[s(1162)+"8"]?{value:c.readUInt8(r),offset:e[s(1761)](r,1)}:{value:e.tCpuN(255,c[r]),offset:e[s(1164)](r,1)}}function Za(c,r,s){let l=t;return r[l(1111)+"t8"]?r[l(1111)+"t8"](c,s):r[s]=e.UNifh(255,c),s+1}let wm=function(c){return new Uint8Array(c)},_m=e[t(1733)]!=typeof Buffer?Buffer["allocUns"+t(407)]:lm(wm,Uint8Array[t(501)+"e"][t(1104)]),ym=16,Xa=32;function Em(c){let r=t,s=0,l={};for(let h=0;e[r(1417)](h,c[r(1511)]);h++)l[c[h][r(1195)+r(887)]]=Vl(c[h][r(1195)+"ame"]),s+=e[r(552)](14,l[c[h][r(1195)+r(887)]]);return[s,l]}function Ql(c,r,s){let l=t,h={HRsQI:e[l(427)],PAtfQ:e[l(1554)],pSQeG:function(m,y,S,g){return m(y,S,g)},neBaR:e[l(437)],voCKf:l(913),GvkqQ:e.lNlby,ZKqtc:e.TSHAC};if(e[l(894)]===e.lrWPe){let m=this[l(1022)][l(1299)+l(1006)+"nc"](this[l(1142)]),y=_0x5ac3e1.parse(e.VvGXy(m,"{}"));return _0x2872c2.values(y)}else{let[m,y]=Em(c),S=e[l(842)](_m,m),g=0;return c[l(1588)](L=>{let O=l,B=h[O(893)][O(1622)]("|"),F=0;for(;;){switch(B[F++]){case"0":console.log(h[O(1274)],L,L.service);continue;case"1":g=h.pSQeG(Za,y[L[O(1195)+O(887)]],S,g);continue;case"2":console.log(h[O(462)],g);continue;case"3":g=h[O(772)](mm,ce[O(686)+"er"](L[O(658)]||r),S,g);continue;case"4":console.log(h.voCKf,g);continue;case"5":console[O(1492)](h[O(1357)],g);continue;case"6":g=h[O(772)](hm,S,g,L.service||0);continue;case"7":g=pm(L["cursor_n"+O(887)],S,g);continue;case"8":console.log(h[O(362)],g);continue;case"9":g=h[O(772)](Za,0,S,g);continue;case"10":console[O(1492)](O(1566),g);continue}break}}),{frameType:Xa,headers:[{key:e[l(1430)],value:s}],payload:S}}}function bm(c){let r=t,s=0,l=[];for(;e[r(1417)](s,c[r(1826)+"th"]);)if(e[r(1813)]!==e[r(1772)]){let{offset:h}=e[r(1810)](Ja,c,s);s=h;let m={cursor_name:"",cursor:0,service:0},{value:y,offset:S}=xm(c,s);m[r(1566)]=y,s=S;let{value:g,offset:L}=e.luFvg(Ja,c,s);s=L,m["cursor_n"+r(887)]=e.EKTmn(Jl,c,s,e[r(1028)](s,g)),s+=g;let{value:O,offset:B}=e[r(805)](gm,c,s);m.cursor=O[r(1691)](),s=B,l.push(m)}else return _0x2bcd06&&(_0x570b26=(0,_0x39cf7e[rxVpOu[r(1141)](_0x3cf1ac,_0x8e5d16)[0]])(_0x388e2a=0)),_0x479401;return l}function vm(){let c=t;return{frameType:Xa,headers:[{key:c(540)+c(323),value:e.mOdIZ}],payload:void 0}}class Sm{constructor(r,s,l){let h=t;this[h(1037)+h(1236)]=r,this[h(1536)+h(1169)]=s,this[h(602)+h(1209)]=l,this._qosDB=Xl(this["_cursorN"+h(1236)],e[h(663)])}async[t(876)](){await this._qosDB.openDB()}async[t(830)+"rs"](){let r=t;if(!this[r(1022)][r(1599)])return;let s=this[r(602)+r(1209)],l=await this[r(1022)].getAll();switch(console.log(e.GDHuG,l),s){case e[r(788)]:return l&&l[r(1511)]?e[r(576)](Ql,l,0,this[r(1536)+r(1169)]):void 0;case e[r(614)]:return;case e[r(1715)]:return l&&l[r(1511)]?e[r(1401)](Ql,l,0,this["_cursorF"+r(1169)]):e[r(1505)](vm)}}async[t(1753)](r,s,l){let h=t,m={inMYO:function(y,S){return e[V(1007)](y,S)},YLxef:e[h(1497)]};if(e[h(421)]!==h(1587))return console[h(1492)](h(1586),r,s,l),this._qosDB[h(1753)]({cursor_name:r,cursor:s,service:l});_0x11fd62[h(757)+h(1712)]=void 0,qbmKIG[h(474)](_0x2dd225,qbmKIG[h(1127)])}async[t(1029)+"rs"](r){let s=t,l=bm(r);for(let h of l)console[s(1492)](s(1738)+"r",l),await this[s(1022)][s(1753)](h)}async[t(1326)](r){let s=t;if(e[s(1010)](s(799),e[s(1830)]))return(await this._qosDB[s(1326)](r))?.cursor;{let l=255&_0x4122bb;e[s(612)](_0x2f88ea,l,_0x533e99,e.mBORv(_0x459da2,_0x32304b)),_0xd41034>>>=8,_0x3eca66--}}async closeDB(){await this[t(1022)].closeDB()}["updateCu"+t(1085)+"Name"](r){let s=t,l={jtJns:function(h,m){return e.KvTlD(h,m)},qERGt:function(h,m){return h+m},mQCrd:s(1282)+"d error."};if(e[s(1238)]===e.KNIvX)this["_cursorF"+s(1169)]=r;else{let h=this[s(833)+"rs"][_0x102b8d];if(h)h.slice()[s(1588)](m=>m.fn[s(939)](m[s(1362)],_0x222127));else if(JcFKTi[s(1694)](s(1746),_0xbfe14b)&&!this.onerror){let m=_0x175b4c.length&&_0x5962c0[0];if(m instanceof _0xd0d47a)throw m;let y=new _0x1d3def(JcFKTi[s(1385)](JcFKTi[s(1441)],m?JcFKTi[s(1385)](" ("+m[s(1500)],")"):""));throw y[s(1190)]=m,m}return this}}get[t(1599)](){let r=t;return this._qosDB[r(1599)]}}let Im=e.hjJcw;async function ef(c){let r=t;if(!this._options[r(396)+"S"])return null;let{aID:s,fpID:l,messageStrategy:h}=this[r(415)],m=e[r(584)](c,Im);try{return this[r(1329)+r(665)]?c&&this[r(1329)+r(665)][r(865)+r(1085)+"Name"](c):this[r(1329)+r(665)]=new Sm(l+"_"+s+"_"+m,m,h),this[r(1329)+r(665)].isReady||await this._cursorManager[r(876)](),this[r(1329)+r(665)]}catch{if(e[r(1460)](r(1026),e[r(968)]))return null;_0x17f593[r(1492)](_0x423e32)}}async function Am(c,r){let s=t,l=e.VKzqk(_n,c[s(1500)].headers,e[s(1242)],"-1"),h=e[s(1204)](_n,c[s(1500)].headers,e.FWGWC,"1"),m=e[s(1239)](Er,c.message[s(497)],e.yaLav),y=e.fiTkl(Number,e[s(1226)](Er,c[s(1500)].headers,e[s(839)]))||0,S=Va[s(1603)](this,c),g=e[s(576)](_n,c[s(1500)][s(497)],e[s(1225)],"2"),L=e[s(1358)](Er,c[s(1500)].headers,e.tOhov),O=e.ZdFoq(Number,e[s(801)](Er,c[s(1500)][s(497)],"x-msg-cu"+s(364)+"ue"));if(S.isQoSAck)return e.tSYcb(r);let B=S[s(1173)+s(500)]?await Yl.call(this):null;if(c[s(1500)].service>0&&h&&!l||e[s(1380)](c[s(1500)][s(1566)],0))if(e[s(1575)](e.clZiP,s(1276))){let F=_0x38a62c[s(1603)](rxVpOu[s(974)](_0x551ee3,this),_0xa72b2b,..._0x2aa8d1);return _0x3ab1ce.set(F,_0x584c71[s(1645)]?_0x5947f8.sort():[_0x4ff645]),rxVpOu.PDhRO(_0x3c1725,F)}else{if(m&&S[s(1173)+s(500)]&&B)return!!!await B[s(1326)](m)&&(this[s(1775)+"hMessage"+s(1474)](c),await B[s(1753)](m,Date.now()+y)),r();if(g){let F=await ef[s(1603)](this);if(!F)return this[s(1775)+s(738)+s(1474)](c),e[s(1505)](r);let $=await F[s(1326)](L)??-1;if($<O)this[s(1775)+"hMessageEvent"](c),F[s(1753)](L,O,c[s(1500)][s(1566)]);else throw new Error(s(496)+s(1360)+s(1532)+O+(" larger "+s(1752)+"al cursor ")+$);return e[s(1407)](r)}return this["_dispatc"+s(738)+s(1474)](c),e.GeOuU(r)}}async function km(c,r){let s=t,l=Va[s(1603)](this,c);if(!l[s(1173)+"sage"])return r();let h=await Yl[s(1603)](this);if(l[s(1665)+s(871)+"age"]&&l[s(405)+"s"][s(1511)])for(let m of l[s(405)+"s"])await h.del(m);e[s(1148)](r)}async function Tm(c,r){let s=t,l=e.zqbvw(c[s(1500)][s(1205)+"e"],ym),h=e[s(488)](c[s(1500)].frameType,Xa);if(e[s(981)](!l,!h))return e.fQUyr(r);let m=e[s(1382)](Er,c[s(1500)][s(497)],e.nDDfB);if(!m)return e[s(1370)](r);let y=await ef[s(1603)](this,m);if(!y)return r();if(l)if(e[s(384)](e[s(1431)],s(1534))){let S=_0x131700.split(":");_0x13e149&&(_0x309d25=S.length),_0x47c3bd+=S[s(1511)];for(let g=0;g<S[s(1511)];g++)if(S[g][s(1511)]!==4){let L=_0x2357da[s(994)+"g"](0,4-S[g].length),O=L[s(1408)](S[g]);_0x3c3209[s(567)](O)}else _0xe6bc5a[s(567)](S[g]);_0x1aafb0=!1}else{let S=await y[s(830)+"rs"](),g={frameType:S?.[s(1205)+"e"],SeqID:ce[s(686)+"er"](this._seqId++),LogID:ce[s(686)+"er"](this[s(415)][s(1745)+s(1339)]()),service:9e3,method:5,headers:S?.headers,payload:S?.payload},L=e[s(1007)](b,g);this._ws&&this[s(1545)][s(1558)+"te"]&&this[s(1545)][s(933)](L)}if(h){let S=c[s(1500)][s(1177)];S&&y[s(1029)+"rs"](S)}}let Cm=async function(c,r){let s=t;this[s(1776)]=!1,e.IFczQ(clearTimeout,this[s(1378)+s(1251)+"utId"]),r()},Rm=async function(c,r){let s=t;if(!this[s(1545)]||this._ws[s(1558)+"te"]!==this[s(1547)])return e[s(1615)](r);let{pingInterval:l}=this[s(415)];this[s(1402)+s(1361)]?.[s(1248)+s(902)+s(1822)]();for(let m=0;m<this[s(602)+s(1797)][s(1511)];m++){let y=this[s(602)+s(1797)][m];if(this._ws.readyState===this[s(1547)]&&e[s(1719)](null,y))this[s(1545)]&&this._ws[s(933)](y),this[s(602)+s(1797)][m]=null;else break}this["_message"+s(1797)]=this["_message"+s(1797)][s(653)](m=>!!m),this["_pingPon"+s(1576)+"Id"]=e[s(522)](setTimeout,()=>this._ping(),l),this[s(1775)+"hOpenEvent"](c),this[s(357)+"er"]&&this[s(1545)]&&(this[s(1545)][s(572)+"pe"]=this[s(1379)+s(1624)]);let h=this["_endpoin"+s(1361)]?.["getCurre"+s(1025)+"nt"]();this[s(1270)](s(694)+h+s(1267)),r()},Pm=async function(c,r){let s=t,l=this["_endpoin"+s(1361)]?.[s(478)+s(1025)+"nt"]();this._debug(s(694)+l),r()};class Dm extends Wa{constructor(r){let s=t,l={DvyhC:function(S,g){return e[V(1542)](S,g)},SIcNm:function(S,g){return e[V(1050)](S,g)},bYQkp:function(S,g){return e[V(535)](S,g)},Clqju:e[s(955)],alzEW:e[s(1044)],VjlHJ:function(S,g,L){return e[s(1553)](S,g,L)},FfHZX:function(S,g){return S===g},YNrqn:s(1707),KrgtT:function(S,g,L,O){return e[s(1292)](S,g,L,O)},BoKMf:e[s(360)],DNwNq:function(S,g){return e[s(1342)](S,g)},qImZA:e.nxLRQ,JuRUP:"Module",pbYKF:function(S,g){return e[s(1090)](S,g)},zFJlY:e[s(369)],LsAcR:function(S,g,L){return e[s(768)](S,g,L)},axiva:function(S,g,L){return e[s(1764)](S,g,L)}};super(),this[s(566)+s(1777)+s(1769)]=!0,this[s(357)+"er"]=yr,this._isNode=Vg,this[s(1077)+"T"]=Gn,this[s(1030)+"X"]=wi,this[s(493)+"r"]=_i,this._messageQueue=[],this[s(1402)+s(1361)]=null,this[s(402)+s(554)]=!1,this[s(1379)+s(1624)]=e[s(1709)],this[s(1378)+s(1013)]=!1,this[s(1378)+s(1251)+s(1051)]=null,this[s(1183)+s(625)+s(1614)]=null,this[s(435)+s(1576)+"Id"]=null,this[s(636)]=0,this._isInit=!1,this._url="",this[s(1793)+s(1128)]=null,this[s(1329)+s(665)]=null,this[s(1252)+s(815)]=null,this[s(504)+"ls"]=e.ZjLQp,this[s(575)]=3,this.CONNECTING=0,this[s(1547)]=1,this[s(1773)]=2,this[s(802)]=S=>{let g=s,L={kommx:function(O,B,F){return e.eJBZN(O,B,F)},rhmHT:function(O,B,F){return e.qRysC(O,B,F)},gypmO:function(O){return e[V(1627)](O)}};if(e.XTtTI(e.WlEHi,e[g(816)]))try{e[g(745)]!=="WMqLC"?(FDyNCs[g(517)](_0x21609a,_0x39b879,8),FDyNCs.rhmHT(_0x2436e3,_0x304b19,_0x2c6c0c)):e[g(576)]($l,this,S,[Cm,Rm,Pm])}catch(O){let B=e[g(1461)](wt,g(1746),{message:O.message,code:wn[g(1157)+"OR"],error:O});this[g(1775)+g(863)+g(927)](B)}else FDyNCs.gypmO(_0x22a729),FDyNCs[g(1771)](_0x5235b5)},this._onMessage=async S=>{let g=s,{pingInterval:L,pingFrequency:O}=this._options;if((l.SIcNm("hi",S[g(960)])&&l[g(1429)](l[g(1012)],O)||l[g(763)]===O)&&(this[g(1400)+g(490)](),this[g(910)]("ping_onc"+g(1150)+"s","success"),this[g(435)+g(1576)+"Id"]=l[g(1109)](setTimeout,this[g(669)][g(1305)](this),L)),!l[g(574)]("hi",S[g(960)]))try{if(l[g(341)](l.YNrqn,l[g(1304)]))l.KrgtT($l,this,S,[dm,am,km,Tm,Am,cm]);else return XTMlim[g(574)](-1,this[g(1272)])&&XTMlim[g(1429)](-1,this[g(837)])?_0x11c304[g(1015)](0,0,this[g(340)]):XTMlim[g(1429)](-1,this[g(1272)])?_0xa1ab43.fromBits(0,XTMlim[g(1394)](this[g(837)],1),this[g(340)]):_0x224a70[g(1015)](this[g(1272)]+1,this[g(837)],this[g(340)])}catch(B){let F=l[g(1109)](wt,l[g(724)],{message:B[g(1500)],code:wn[g(1643)+g(327)],error:B});this[g(1775)+g(863)+g(927)](F)}},this[s(1261)]=S=>{let g=s,L={bCMNS:function(F,$){return l[V(1027)](F,$)},odvJD:l.qImZA,bjnVJ:l[g(1340)],KLzMP:g(377)+"le"},O=this[g(1402)+"tManager"]?.[g(882)+"chMaxTries"](),B=this[g(1402)+g(1361)]?.[g(478)+"ntEndpoint"]();if(O&&!S[g(1500)])if(l.pbYKF(l.zFJlY,l[g(1425)]))GvRlep[g(1052)](GvRlep[g(492)],typeof _0x5cd908)&&_0x4675ce[g(1518)+g(800)]&&_0x735295.defineProperty(_0x1e6744,_0x314e5a[g(1518)+g(800)],{value:GvRlep[g(1818)]}),_0x1160bd[g(824)+g(1266)](_0x5f0f12,GvRlep.KLzMP,{value:!0});else{let F="connect "+B+(g(1763)+g(1513)+g(533)+"ed");this[g(1775)+g(863)+g(927)](l.LsAcR(wt,l[g(724)],{message:F,code:wn["MAX_RETR"+g(943)+"R"],error:S}));return}this._ws&&l[g(1429)](this._ws[g(1558)+"te"],this[g(1547)])&&this[g(593)+g(1255)](),this._dispatchErrorEvent(l[g(1510)](wt,l[g(724)],{message:S.message,code:wn[g(1601)+g(1336)],error:S}))},this._onClose=async S=>{let g=s,L={wWOsD:function(B){return e[V(977)](B)},baekM:g(1699),dRIED:g(1746),ZeXeV:e[g(754)]};this[g(1800)+"mer"](),this["_clearPi"+g(490)](),this[g(773)+g(1730)+"rs"](),this[g(1545)]=null,this[g(1378)+g(1013)]=!1;let O=this[g(1402)+g(1361)]?.[g(882)+"chMaxTries"]();if(!O&&this["_navigat"+g(325)]()&&!this[g(402)+g(554)]){let B=this[g(1402)+g(1361)]?.["getCurre"+g(1025)+"nt"](),F=this[g(415)][g(528)+g(555)+g(1504)](S.code,S.reason);this[g(1775)+g(1613)+"ent"](e[g(564)](kt,g(1175),{code:1006,reason:S[g(828)]||g(1579)+"ng faile"+g(673)+g(1418)+g(684)+"ame: "+B,willReconnect:F})),F&&this[g(1378)]();return}if(S[g(1373)]!==1e3&&this["_readyCl"+g(554)]){this[g(1775)+g(1613)+g(927)](e[g(514)](kt,e[g(1455)],{code:1e3,reason:g(678)})),this["_endpoin"+g(1361)]?.["resetEnd"+g(902)+g(1822)](),this["_pingLos"+g(815)]?.["resetCou"+g(585)]();return}if(e.IrlNJ(1e3,S[g(1373)])&&O)if(e[g(1069)]===g(793)){let B={RVgvC:g(1746),wBkyX:function(de){return oniLHY.wWOsD(de)},NqlDC:"AbortError",GNMCW:function(de){return de()}},F=()=>{let de=g;_0x347619[de(963)+de(1331)+de(441)](de(1699),$),_0x1d093a[de(963)+de(1331)+de(441)](B.RVgvC,pe),_0x21de08[de(963)+"entListener"](de(1479),pe)},$=()=>{B[g(711)](_0x4752e3),B.wBkyX(F)},pe=()=>{let de=g;_0x2d82b8(_0x19f776[de(1746)]||new _0x4133dd(B.NqlDC,de(1108)+"or")),B[de(1307)](F)};_0x4e2b17[g(1107)+g(984)](oniLHY.baekM,$),_0x2d249f[g(1107)+"Listener"](oniLHY[g(472)],pe),_0x4b6678["addEvent"+g(984)](oniLHY.ZeXeV,pe)}else{let B=this._endpointManager?.[g(478)+"ntEndpoint"](),F=S[g(828)];F||(F=await e[g(842)](tm,this[g(654)])),F=g(1579)+g(1642)+"d, "+F+(g(1259)+g(705))+B+(g(1597)+g(1399)+g(455)),this[g(1775)+g(1613)+g(927)](e[g(541)](kt,e[g(1455)],{code:S[g(1373)],reason:F}));let $=g(1079)+B+(g(1763)+"ax retri"+g(533)+"ed");this[g(1775)+g(863)+g(927)](e[g(1833)](wt,e[g(360)],{message:$,code:wn[g(618)+g(943)+"R"]})),this[g(1402)+g(1361)]?.["resetEnd"+g(902)+g(1822)](),this._pingLossCounter?.[g(553)+"nter"]();return}if(e[g(624)](1e3,S[g(1373)])&&!S.reason){let B=this[g(1402)+g(1361)]?.[g(478)+g(1025)+"nt"]();this[g(1775)+g(1613)+g(927)](kt(e.DeTlc,{code:S.code,reason:g(1579)+g(1642)+g(673)+g(1418)+"n, hostn"+g(1033)+B})),this._endpointManager?.["resetEnd"+g(902)+"fig"](),this[g(1252)+g(815)]?.[g(553)+"nter"]();return}this._dispatchCloseEvent(S),this[g(1402)+g(1361)]?.[g(1248)+"pointConfig"](),this["_pingLos"+g(815)]?.[g(553)+g(585)]()},this[s(1338)]=null,this.onerror=null,this[s(1036)+"e"]=null,this[s(1419)]=null,this[s(1652)+s(1260)]=null,this[s(1716)+s(1827)]=null,this[s(1424)+s(1657)+"yReconnect"]=null,this[s(1582)+"nLine"]=this[s(1582)+"nLine"].bind(this),this[s(1582)+s(919)]=this[s(1582)+s(919)][s(1305)](this),this[s(1519)+"ageHide"]=this[s(1519)+s(1074)][s(1305)](this),this[s(1519)+s(918)]=this[s(1519)+s(918)][s(1305)](this),this[s(415)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength: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.FxbwE,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1715)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:m}=r,y=Array[s(577)](h)?h:e.QcgRi(s(1397),typeof h)?[h]:[];if(!y||e[s(857)](0,y.length))throw new Error(e[s(1345)]);if(!e[s(1661)](Xg,m))throw new Error(e[s(1478)]);Object.assign(this[s(415)],r),this[s(1402)+"tManager"]=new Kl(y,this._options[s(1634)+"es"]),this[s(1252)+s(815)]=new em(this._options["pingLoss"+s(695)]),this[s(415)]["automati"+s(1440)]&&(this[s(1776)]=!0,this[s(1378)]()),this[s(415)][s(543)+s(414)+s(376)]&&(this[s(1077)+"T"]||this[s(1030)+"X"]?this[s(620)+s(1454)+s(560)]():this[s(357)+"er"]&&this[s(832)+s(1008)+s(984)]())}_handleOnLine(){let r=t;this._options[r(767)+"utoReconnect"]||this[r(402)+r(554)]||this[r(1207)+r(1260)]()}[t(1582)+t(919)](){let r=t;this[r(1188)+r(483)+"t"]();let s=e.JiDue(ja,e[r(1516)],{message:e[r(1700)]});this[r(1424)+r(1657)+r(1350)+"ct"]&&this[r(1424)+r(1657)+"yReconnect"](s)}[t(832)+t(1008)+t(984)](){let r=t;this[r(357)+"er"]&&window[r(1107)+r(984)](e.ftcVx,this[r(1582)+r(870)]),this[r(357)+"er"]&&window[r(1107)+"Listener"](e[r(1317)],this[r(1582)+"ffLine"]),this[r(357)+"er"]&&window["addEvent"+r(984)](e[r(880)],this[r(1519)+r(1074)]),this[r(357)+"er"]&&window["addEvent"+r(984)](e[r(1750)],this["_handleP"+r(918)])}[t(530)+t(1008)+t(984)](){let r=t;this._isBrowser&&window[r(963)+r(1331)+r(441)]("online",this[r(1582)+r(870)]),this[r(357)+"er"]&&window["removeEv"+r(1331)+r(441)](e[r(1317)],this._handleOffLine),this[r(357)+"er"]&&window["removeEventListe"+r(441)](e[r(880)],this[r(1519)+r(1074)]),this[r(357)+"er"]&&window[r(963)+r(1331)+r(441)](r(1206),this[r(1519)+r(918)])}[t(1519)+t(1074)](r){let s=t;!r.persisted&&(this._isBrowser&&window[s(963)+s(1331)+s(441)](e.GhpYy,this[s(1519)+s(1074)]),this._isBrowser&&window[s(963)+s(1331)+"ner"](e.zJaqZ,this._handlePageShow),this[s(1175)]()),this[s(357)+"er"]&&window[s(963)+s(1331)+"ner"](e[s(1829)],this[s(1582)+s(870)]),this[s(357)+"er"]&&window[s(963)+s(1331)+s(441)](e.ZaINm,this["_handleO"+s(919)])}[t(1519)+"ageShow"](r){let s=t,l={tllur:function(h,m,y){return e.eUZAL(h,m,y)}};r.persisted&&(e[s(513)]!==e[s(513)]?this[s(910)](s(1746),DXVMIl[s(949)](_0x9dfaee,s(1746),{..._0x4f427f,message:_0x3423ce[s(843)]||""})):(this[s(592)+s(325)]()&&(!this[s(1545)]||e.XeLaC(this[s(1545)].readyState,this[s(1547)])||e[s(1540)](this[s(1545)][s(1558)+"te"],this[s(1135)+"NG"]))&&this["_handleO"+s(870)](),this[s(357)+"er"]&&window[s(1107)+s(984)](e.ftcVx,this[s(1582)+"nLine"]),this._isBrowser&&window[s(1107)+s(984)](e.ZaINm,this[s(1582)+s(919)])))}async[t(1309)+t(1294)](r){let s=t,l={fNORl:function(h,m,y,S){return e.PBygh(h,m,y,S)},WClJH:e[s(1427)],ecUlZ:"x_fronti"+s(774)+"ck",BeiDa:s(395)+s(453)+"k",xDfJd:function(h,m,y){return e[s(564)](h,m,y)},XGeRl:e.WUTJW,XRSGR:function(h,m){return h(m)},aHBfF:e[s(1551)]};if(e.WRxwo!==e[s(1756)]){let h=!!this[s(415)][s(396)+"S"];if(!h)return{enabled:h,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let m=SRLljZ[s(1790)](_0x81db6f,_0x52c841[s(1500)].headers,SRLljZ[s(359)],"2"),y=m&&SRLljZ[s(1790)](_0xca4eaa,_0x2de7a8[s(1500)].headers,SRLljZ[s(464)],"1"),S=m&&_0x23bb66(_0xef0b05[s(1500)][s(497)],SRLljZ[s(1499)],"1"),g=S?SRLljZ[s(844)](_0x1c1a94,_0xe17211[s(1500)][s(497)],SRLljZ[s(626)])?.[s(1622)](",")[s(653)](_0x1a42b5)||[]:[];return{enabled:h,isQoSMessage:m,isQoSAck:y,isAckCleanupMessage:S,ackMsgIds:g}}else{let{fpID:h,deviceID:m,bddID:y,ttwID:S,accessKey:g,aID:L,customParams:O={},enableAutoAck:B,enableQoS:F,QoSLevel:$,env:pe}=this[s(415)],de,be,Ae;if(this[s(357)+"er"]||this[s(1030)+"X"]||this[s(1077)+"T"])de=location&&e[s(676)](e[s(531)],location.protocol)?e[s(976)]:s(878),be=r.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),Ae=/^wss(.*:\/\/)/[s(945)](r)?r:""+de+be;else if(e[s(1333)](e.sXDQp,e[s(1457)])){let yi={CAHRT:function(En,bn){let Lm=s;return SRLljZ[Lm(386)](En,bn)}};_0x608bf9[s(1107)+s(984)](SRLljZ.aHBfF,En=>{let bn=s;_0x2a428f(yi[bn(1351)](_0x5cf4d3,_0x94b2dc[bn(836)]),En[bn(1610)+"on"],En[bn(1420)+"on"],_0x2658d7(_0x5c848c[bn(1567)+bn(817)]))})}else de="wss://",be=r.replace(/(^http)((?:[s]*:\/\/))/,""),Ae=/(^ws)((?:[s]*:\/\/))/[s(945)](be)?be:""+de+be;let yn=y?e[s(1481)]:S?e[s(1390)]:s(446)+"d",Tt=y||S||m;if(e.AnzQz(!Tt,!yn))throw new Error(e.xfvFF);let br=e[s(916)](e.UGXQj,typeof O)?await O():O,Ya=pe?e[s(322)](Qg,pe.xUseEnv,pe[s(1095)]):{},Qa=Object[s(924)]({device_platform:e[s(649)],version_code:e[s(1406)],access_key:g,fpid:h,aid:L,[yn]:Tt,xsack:B?1:0,xaack:B?1:0,xsqos:F?1:0,qos_level:F?$:void 0,qos_sdk_version:2,...Ya},br),Om=Object[s(440)](Qa)[s(1295)]((yi,En)=>Qa[En]!==void 0?""+yi+(yi?"&":"?")+En+"="+Qa[En]:yi,"");return Ae+s(1514)+Om}}async _connect(){let r=t,s={VxeEw:e[r(1829)],jDPXO:e[r(1317)],JrRhy:e[r(1750)]};if(!(this[r(1378)+r(1013)]||this[r(402)+"osed"])){this[r(1378)+r(1013)]=!0;try{if(e[r(1300)](e[r(1368)],e.RNVgr)){let h=""+_0x4f7c98.now(),m=_0x2403be||(_0x590c8c=e[r(795)](_0x545a6e,_0x1ced8b)),y=_0x2e3af5.random()[r(1518)](16)[r(899)](-6);return e[r(1164)](e[r(1223)]("02",h),m)+y}else{let l=this[r(1402)+r(1361)]?.[r(1594)+r(750)+r(401)+r(1550)+r(1664)](),{timeoutInterval:h}=this[r(415)];if(l){let y=this[r(1402)+"tManager"]?.["getCurre"+r(1025)+"nt"](),S=this["_endpoin"+r(1361)]?.[r(641)+r(1607)+r(1780)+"UpdateCount"](),g=this["_endpoin"+r(1361)]?.[r(478)+r(1025)+r(1134)+r(883)]();if(S)if(e.eUPLx("eXMIZ",e.mNOFk)){let L=r(1079)+y+(r(1059)+r(1597)+"tries re"+r(982)+r(947)+r(1651)+r(1724))+S+(r(1817)+"y"),O=e[r(1035)](wt,e[r(360)],{message:L,code:wn[r(618)+r(943)+"R"]});this[r(1270)](L),this["_dispatc"+r(863)+"ent"](O),this[r(654)]=await this[r(1309)+"eUrl"](S),this[r(1270)]("connect "+S+" "+g+r(337)),this[r(773)+r(1730)+"rs"]()}else this[r(357)+"er"]&&_0x22f3d2[r(1107)+r(984)](rYxiZb[r(1825)],this[r(1582)+r(870)]),this[r(357)+"er"]&&_0x2c30b1["addEvent"+r(984)](rYxiZb.jDPXO,this[r(1582)+"ffLine"]),this[r(357)+"er"]&&_0x3fc535[r(1107)+"Listener"]("pagehide",this[r(1519)+"ageHide"]),this[r(357)+"er"]&&_0x6be7f4[r(1107)+r(984)](rYxiZb[r(847)],this[r(1519)+r(918)]);else{let L=r(1079)+y+(" timeout"+r(1597)+r(1399)+r(455));this[r(1270)](L),this[r(1775)+r(863)+r(927)](e[r(970)](wt,r(1746),{message:L,code:wn[r(618)+r(943)+"R"]}));return}}else if(e.gMuio(e[r(539)],e[r(539)])){if(e[r(1654)](4,_0x19d02e[r(1511)])){let y=_0x4377f2[r(994)+"g"](0,e[r(1392)](4,_0x5ea55[r(1511)])),S=y.concat(_0x225a16);_0x2af80a[r(567)](S)}else _0x4f054e[r(567)](_0x198e3b);_0x305e77&&(_0x2f42c8+=1),_0x1162c6+=1,_0x28a349=!1}else{let y=this._endpointManager?.[r(478)+r(1025)+r(1697)+r(1729)](),S=this[r(1402)+"tManager"]?.[r(478)+"ntEndpoi"+r(1134)+"ount"]();this[r(654)]=await this["_generat"+r(1294)](e[r(727)](y,"")),this[r(1270)](r(1079)+y+" "+S+r(337)),this[r(773)+r(1730)+"rs"]()}if(this[r(1776)])this[r(1776)]=!1;else{let y=e.AZVUy(ja,e[r(1516)],{message:r(1196)});this[r(1652)+r(1260)]&&this[r(1652)+"econnect"](y)}let m=this["_endpoin"+r(1361)]?.[r(478)+r(1025)+r(1134)+r(883)]()||0;m>1&&await this[r(1630)](m-1),this[r(1270)]("connecti"+r(971)+this._url+(r(451)+"ls: ")+this[r(504)+"ls"]),this[r(1545)]=e[r(355)](Zg,{url:this[r(654)],protocols:[this[r(504)+"ls"]],headers:this._options[r(1520)+"ramParams"][r(898)+r(1437)]},this[r(415)].ws),(this[r(357)+"er"]||this[r(493)+"r"])&&this._ws&&(this[r(1545)][r(572)+"pe"]=this[r(1379)+r(1624)]),this[r(1781)+r(956)](),this[r(1378)+r(1251)+r(1051)]=e[r(1515)](setTimeout,this._onTimeout.bind(this),h)}}catch(l){throw this._connectLock=!1,l}}}["_clearTi"+t(1113)](){let r=t;e.StfKX(clearTimeout,this[r(1378)+r(1251)+r(1051)]),this[r(1378)+r(1251)+r(1051)]=null}[t(1400)+t(490)](){let r=t;e[r(704)](clearTimeout,this[r(435)+"gTimeoutId"]),e[r(795)](clearTimeout,this["_reconnectTimeou"+r(1614)]),this[r(435)+"gTimeoutId"]=null,this["_reconnectTimeou"+r(1614)]=null}[t(1270)](...r){let s=t;this._options[s(1448)]&&console[s(1492)][s(939)](console,[e[s(992)],...r])}[t(1064)+"rvalValue"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:m}=this[s(415)],y=e.KGxEv(l,Math[s(1525)](m,r-1));return e[s(1751)](y,h)?h:y}[t(669)](){let r=t;if(this[r(1545)]&&this[r(1545)][r(1558)+"te"]===this.CONNECTING){this._clearPingTimer(),this[r(435)+r(1576)+"Id"]=e[r(1459)](setTimeout,this[r(669)][r(1305)](this),this[r(415)][r(1106)+"rval"]);return}if(!this._ws||e[r(398)](this._ws[r(1558)+"te"],this[r(1547)]))return void this[r(1207)+r(1260)]();this[r(1545)]&&this[r(1545)][r(933)]("hi"),this["_reconne"+r(625)+r(1614)]=e[r(674)](setTimeout,this["_handleR"+r(1260)+r(896)][r(1305)](this),this._options[r(598)+r(1168)+r(646)])}[t(1207)+t(1260)+t(896)](){let r=t;this[r(1252)+"sCounter"]?.addCount(),this.emit(e[r(390)],e[r(1355)]),this[r(1252)+r(815)]?.[r(882)+r(328)+"nt"]()?this[r(1207)+"econnect"]():this[r(669)]()}[t(592)+t(325)](){let r=t;return this[r(1077)+"T"]||this._isMiniWX?this["_miniNav"+r(1777)+r(1769)]:(this[r(357)+"er"]||this[r(493)+"r"])&&this[r(415)][r(543)+"tworkCha"+r(376)]?navigator.onLine:!0}["_handleR"+t(1260)](){let r=t;!this["_navigat"+r(325)]()||this[r(402)+r(554)]||(this[r(1402)+r(1361)]?.[r(1248)+r(902)+"fig"](),this[r(1252)+r(815)]?.[r(553)+r(585)](),this[r(1545)]?this[r(593)+r(1255)](1001,e[r(1102)],!0):this[r(1378)]())}[t(620)+t(1454)+"ange"](){let r=t,s={sHlcB:function(l,h,m){return e[V(447)](l,h,m)},ViyOz:function(l,h){return l!==h},avpaz:e[r(1680)],MdYZC:e[r(1312)]};this[r(1077)+"T"]?tt["onNetworkStatusC"+r(1824)](({isConnected:l})=>{let h=r,m={ixVoo:function(y,S,g){return s.sHlcB(y,S,g)}};s[h(715)](s[h(1741)],s[h(1121)])?(this["_miniNav"+h(1777)+"line"]=l,l?this[h(1582)+h(870)]():this[h(1582)+h(919)]()):(_0x3938c4(_0x4310f4,74),XwpckS[h(664)](_0x4432f2,_0x246235,_0x4533a7))}):this[r(1030)+"X"]&&wx[r(548)+r(819)+"hange"](({isConnected:l})=>{let h=r;this[h(566)+h(1777)+"line"]=l,l?this[h(1582)+"nLine"]():this["_handleO"+h(919)]()})}_wait(r){let s=t,l={BzvNF:function(h,m){return e[V(790)](h,m)},YSSYQ:function(h,m,y){return e[V(1358)](h,m,y)}};if(e[s(1389)](e.RXiyq,e[s(867)]))_0x502eb5+=thGSnL[s(1332)](_0x252f94,_0x525e6c),_0x172726++;else return new Promise(h=>{let m=s;l[m(1480)](setTimeout,h,this["_getInte"+m(1245)+"e"](r))})}["_disconn"+t(1255)](r=1e3,s="",l=!1){this[t(1545)]&&this._destroyWebSocket(r,s,l)}[t(821)+"ut"](){let r=t,s=this["_endpoin"+r(1361)]?.[r(478)+r(1025)+"nt"]();this[r(1270)](r(1079)+s+r(1059)),this[r(593)+r(1255)](1001,e[r(1668)],!0)}[t(1220)](r){let s=t,l=Qt(r);this._ws&&this._ws[s(1558)+"te"]===this[s(1547)]&&(this._ws&&this._ws[s(933)](l),this[s(1270)](e[s(1318)],r))}[t(773)+t(1730)+"rs"](){let r=t,s=e.gPLnk[r(1622)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[r(1545)])return;continue;case"1":this[r(1545)][r(963)+r(1331)+"ner"](r(1746),this[r(1261)]);continue;case"2":this[r(1545)][r(963)+"entListe"+r(441)](e[r(408)],this[r(802)]);continue;case"3":this[r(1545)]["removeEv"+r(1331)+r(441)]("message",this._onMessage);continue;case"4":this[r(1545)][r(963)+r(1331)+"ner"](e[r(1455)],this[r(465)]);continue}break}}[t(1781)+t(956)](){let r=t,s=e[r(1081)][r(1622)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1545)]["addEvent"+r(984)](e.PLgri,this._onOpen);continue;case"1":if(!this[r(1545)])return;continue;case"2":this[r(1545)][r(1107)+r(984)](r(1746),this[r(1261)]);continue;case"3":this[r(1545)][r(1107)+r(984)](e[r(1539)],this[r(1002)+"ge"]);continue;case"4":this[r(1545)][r(1107)+r(984)](e[r(1455)],this._onClose);continue}break}}["_wsInsta"+t(911)](r=1e3,s=""){let l=t;try{this[l(1545)]&&this[l(1545)][l(1175)](r,s)}catch{}}[t(1188)+t(483)+"t"](r=1e3,s="",l=!1){let h=t;if(this[h(1400)+h(490)](),this[h(1800)+"mer"](),this[h(773)+h(1730)+"rs"](),this[h(662)+h(911)](1e3,s),this[h(1378)+h(1013)]=!1,l&&this[h(592)+"orOnline"]()&&!this["_readyCl"+h(554)]){if(this[h(1402)+h(1361)]?.[h(882)+h(342)+"es"]()){let y=this[h(1402)+"tManager"]?.[h(478)+h(1025)+"nt"]();this["_dispatc"+h(1613)+h(927)](kt(e[h(1455)],{code:1006,reason:h(1079)+y+(" timeout"+h(1597)+h(1399)+h(455)),wasClean:!0}))}else{let y=this[h(415)]["reconnec"+h(555)+h(1504)](r,s);this[h(1775)+h(1613)+h(927)](e[h(967)](kt,e[h(1455)],{code:r,reason:s,wasClean:!0,willReconnect:y})),y&&this[h(1378)]()}return}this._navigatorOnline()||this[h(402)+h(554)]?this[h(1775)+h(1613)+"ent"](kt(e[h(1455)],{code:r,reason:e.wMPJr})):this[h(1775)+"hCloseEv"+h(927)](e[h(1226)](kt,e[h(1455)],{code:1006,reason:h(907)+h(827)+h(484)+"ine"})),this._ws=null,this[h(1402)+"tManager"]?.[h(1248)+h(902)+h(1822)](),this[h(1252)+"sCounter"]?.[h(553)+h(585)]()}[t(1775)+t(1496)+"nt"](r){let s=t;this.emit(e[s(408)],r),this[s(1419)]&&this[s(1419)](r)}[t(1775)+t(738)+t(1474)](r){let s=t;if(e[s(473)]("sQkhm",e[s(1466)]))this[s(910)](e[s(1539)],r),this[s(1036)+"e"]&&this[s(1036)+"e"](r);else return _0x44c0df.log(e[s(1130)],_0xaec748,_0x124bea,_0x10dbb9),this._qosDB[s(1753)]({cursor_name:_0x3cc0e1,cursor:_0x10ea7d,service:_0x1111e4})}[t(1775)+t(382)+"ageEvent"](r){let s=t;this[s(910)](e[s(835)],r),this[s(1716)+s(1827)]&&this[s(1716)+s(1827)](r)}[t(1775)+t(863)+t(927)](r){let s=t;this[s(910)](s(1746),r),this[s(1577)]&&this[s(1577)](r)}[t(1775)+t(1613)+t(927)](r){let s=t;this[s(910)](e.DeTlc,r),this[s(1338)]&&this[s(1338)](r)}get binaryType(){let r=t;return e.vwwCX===e[r(1689)]?new _0x9c93b0(_0x5b6e8f,{message:_0x1d2fb5,code:_0x3a8731,error:_0x54b4d4}):this._ws?this[r(1545)][r(572)+"pe"]:this["_binaryT"+r(1624)]}set[t(572)+"pe"](r){let s=t;this[s(1379)+s(1624)]=r,this[s(1545)]&&(this._ws[s(572)+"pe"]=r)}get[t(324)+"nt"](){let r=t;return this[r(1402)+"tManager"]?.[r(478)+"ntEndpoi"+r(1134)+r(883)]()||0}get[t(1648)+"Amount"](){let r=t;return this[r(602)+"Queue"].reduce((l,h)=>(l+=h&&h[r(1826)+"th"]||0,l),0)+(this._ws?this[r(1545)]["buffered"+r(736)]:0)}get[t(521)+"ns"](){let r=t;return this._ws?this._ws[r(521)+"ns"]:""}get[t(1449)](){let r=t;return this[r(1545)]?this[r(1545)][r(1449)]:""}get[t(1558)+"te"](){let r=t;return this[r(1545)]?this[r(1545)][r(1558)+"te"]:this[r(415)][r(691)+r(1440)]?this.CONNECTING:this[r(575)]}get[t(397)](){let r=t;return this._ws?this[r(1545)][r(397)]:this[r(654)]}close(r=1e3,s){let l=t,h=e[l(1087)].split("|"),m=0;for(;;){switch(h[m++]){case"0":this[l(1400)+"ngTimer"]();continue;case"1":if(this[l(1545)][l(1558)+"te"]===this[l(575)]||e.vcIsH(this._ws[l(1558)+"te"],this.CLOSING))return void this._debug(e[l(1549)]);continue;case"2":this[l(1800)+l(1113)]();continue;case"3":this[l(402)+l(554)]=!0;continue;case"4":this[l(530)+l(1008)+l(984)]();continue;case"5":this["_QoSMana"+l(1128)]?.[l(796)]();continue;case"6":this["_destroy"+l(483)+"t"](r,s);continue;case"7":if(!this._ws)return void this[l(1270)]("close, ws instan"+l(1323)+l(1453)+"ed");continue}break}}async[t(933)](r,s){let l=t;if(e.QTJgX(null,r))throw new Error(e.cURCE);e.bLRCO(e[l(561)],typeof r)&&(r=JSON[l(1353)+"y"](r)),e[l(1708)](e.ASApT,typeof r)&&!e[l(703)](r,ArrayBuffer)&&!(r[l(476)]&&e[l(834)](r.buffer,ArrayBuffer))&&(r=JSON[l(1353)+"y"](r));let h=await e.idfbv(Zl,r),m=Yg(r),{method:y=0,service:S=this[l(415)][l(1566)],logID:g=this[l(415)][l(1745)+l(1339)](),headers:L=this[l(415)][l(497)],payloadEncoding:O=this[l(415)][l(391)+l(1143)],payloadType:B=this[l(415)][l(1009)+l(1624)],logIDNew:F=this[l(415)][l(411)+l(1321)][l(952)+l(954)+l(1596)+"ew"]?e[l(542)](i,this[l(415)].logIDNewConfig[l(685)]):""}=e[l(1154)](s,{});if(!S)throw new Error(e.hftLs);let $={SeqID:ce[l(686)+"er"](this._seqId++),LogID:ce[l(686)+"er"](g),service:S,method:y,headers:L,payloadEncoding:e[l(1065)](O,Object)?O.encoding?O[l(806)]:"":O,payloadType:e.QWrVf(B,Object)?B[l(1097)]?B[l(1097)]:m:B||m,payload:h,LogIDNew:F},pe=e[l(1172)](Qt,$);return this._ws&&this._ws[l(1558)+"te"]===this[l(1547)]?(this[l(1545)]&&this[l(1545)][l(933)](pe),this._debug(e[l(519)],$)):this[l(602)+l(1797)][l(1511)]<this[l(415)][l(450)+l(1552)+"ength"]?(this[l(602)+l(1797)][l(567)](pe),this._debug(e[l(1617)],$)):(this["_message"+l(1797)].shift(),this._messageQueue[l(567)](pe)),{seqID:this[l(636)],logID:g,logIDNew:F}}async[t(528)+"t"](r){let s=t,l={mmJjr:function(y,S){return e[V(1616)](y,S)}},{url:h}=e[s(1201)](r,{}),m=Array[s(577)](h)?h:e.BszbC(e[s(1533)],typeof h)?[h]:[];if(r&&Object[s(924)](this[s(415)],r),m&&m[s(1511)]?this[s(1402)+s(1361)]=new Kl(m,this[s(415)][s(1634)+"es"]):this[s(1402)+s(1361)]?.["resetEnd"+s(902)+"fig"](),this[s(1252)+"sCounter"]?.[s(553)+s(585)](this[s(415)][s(1224)+s(695)]),this[s(402)+s(554)]=!1,this[s(1545)]&&e[s(1090)](this._ws[s(1558)+"te"],this[s(575)]))this[s(593)+s(1255)](1e3,e[s(1600)],!0);else if(e[s(1458)](e[s(931)],e[s(931)]))this._isInit=!0,this._connect();else if(Bziorf.mmJjr(_0x527a56,_0x27cfa5))return _0xf787d0}async[t(1442)](){let r=t;if(!this[r(1378)+r(1013)]){let s=(r(1041)+"3").split("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(402)+"osed"]=!1;continue;case"1":this[r(1252)+r(815)]?.["resetCou"+r(585)]();continue;case"2":this[r(1402)+r(1361)]?.[r(1248)+r(902)+r(1822)]();continue;case"3":this[r(1378)]();continue;case"4":this[r(1776)]=!0;continue}break}}}["addEvent"+t(984)](r,s){this.on(r,s)}[t(442)+"Event"](r){let s=t,{type:l}=r;this[s(910)](l,r)}[t(963)+t(1331)+t(441)](r,s){this.off(r,s)}pingOnce(){let r=t,s={Fknum:function(l,h){return e[V(897)](l,h)},zAXtZ:"success",VINkn:e[r(1375)],LmPAN:r(1369)+r(590)+"t",TggNy:function(l,h,m){return e[r(322)](l,h,m)}};return new Promise((l,h)=>{let m=r,y={CNRXg:function(L,O){return s[V(1047)](L,O)},qXMCZ:s[m(1244)],sMpvk:m(1369)+m(590)+"t"};this[m(1400)+m(490)](),this[m(435)+m(1576)+"Id"]=s[m(687)](setTimeout,this[m(669)][m(1305)](this),this[m(415)][m(1106)+"rval"]);let S=()=>{let L=m;s.Fknum(l,s[L(1649)]),this[L(670)](s[L(1244)],S),this.off(s[L(1216)],g)},g=()=>{let L=m;y[L(469)](h,L(1118)),this[L(670)](y[L(545)],S),this[L(670)](y[L(333)],g)};this.on(m(1369)+m(1150)+"s",S),this.on(s.LmPAN,g),this[m(669)]()})}}})(),He[M(721)+M(826)]=Me[M(721)+M(826)],He[M(1120)+M(980)]=Me[M(1120)+M(980)],He[M(964)+"e"]=Me[M(964)+"e"],He[M(1474)]=Me[M(1474)],He.FWS=Me[M(1381)],He["Frontier"+M(352)+M(431)]=Me[M(1423)+M(352)+"vent"],He[M(352)+M(431)]=Me["MessageE"+M(431)],He[M(491)+"t"]=Me[M(491)+"t"],He["Reconnec"+M(1795)]=Me[M(766)+M(1795)],He["createCl"+M(826)]=Me["createCl"+M(826)],He["createEr"+M(980)]=Me["createEr"+M(980)],He[M(917)+M(853)+"nt"]=Me[M(917)+M(853)+"nt"],He[M(849)+M(381)]=Me[M(849)+M(381)],He["createRe"+M(1765)+M(431)]=Me["createRe"+M(1765)+M(431)],He[M(1732)+M(999)]=Me[M(1732)+M(999)],He[M(498)+"ame"]=Me[M(498)+M(887)];for(Ea in Me)[M(721)+M(826),M(1120)+"rorEvent",M(964)+"e",M(1474),M(1381),"Frontier"+M(352)+M(431),M(352)+"vent",M(491)+"t",M(766)+M(1795),M(940)+M(826),M(393)+M(980),M(917)+"ssageEvent","createOp"+M(381),M(392)+M(1765)+M(431),M(1732)+M(999),M(498)+M(887)][M(1611)](Ea)===-1&&(He[Ea]=Me[Ea]);function ka(){let t=["y1nnuuS","zMzLCG","CgjduhC","zKfstwy","ywjVCNq","wvntwve","zvrxyKq","D2fVu0G","x2zVCM1HDeu","sNnHDxe","CwLHDKC","qNHduNa","quzlrM0","ywjfwwC","uKzcCfu","y2XoC0u","sufIuKW","Bg9N","zg1MCKC","wvzoDMe","CwvJvKu","Ae9Wzw5fDMu","yMrpuw4","vxPPAgy","qMvPrge","BwvZC2fNzq","vvfWrfC","EujxCui","ywXSzwqGBxu","ChrVCG","yvfKA0G","B2nRzxrtDwm","tgLQCvm","u2HtzeK","sg9QAwK","yxHPDMe","BgvUz3rO","nxW0FdD8mhW","yxGGCMv0CMK","l3DZl3yY","wgf6ywu","s0fLr0m","tg50DMS","Dg9tDhjPBMC","x2HHBMrSzva","BwLUAvbYB2C","ENLezNy","y3vhAKi","Cg9W","rgneCxO","Cg93","BMCGB3iGyw4","Bvj2q1q","vvrkCvu","CuDdAu0","zxjFywnRx20","ve1cEvm","ign1CNnVCIa","qvnbCfq","BhPXsKC","y2HHCKnVzgu","x2n1CNnVCKy","Au1kzgi","BerOsxe","EwzeALy","sgDJvwq","ruvVDem","suDiq2S","CLzHBhvLCW","wKPkD0G","x3DZ","vLDgCe0","t1bftG","A0LfvKm","vhv4Dwm","AgvKtwf4uMu","B0DUB28","z2vrDwv1zuW","Dxnyr00","ExfXy0K","Aw1LCYbPBIa","CMTLCKDSB2i","yxLIrxy","CMvHzhLtDge","D0nQwva","DwLouKm","A1jMCgm","qvbtEeG","EgrmEfK","nhWYFdf8m3W","tgjSzM8","C2vYDMLJzq","DhjHBNnHy3q","CgzPsui","wuXIs3i","ywDLrxzLBNq","yvnrEfC","tg9Nsuq","qLHSz0i","vNvUy1e","B2LRtgS","z1rPBwvVDxq","B25LCNjVCG","wgz0EwK","y29UBMvJDgK","B2jlvfq","B0vvAve","x2HHBMrSzu8","Dw5KzwzPBMu","B25fCNjVCG","nZCYnJC3rMXoELfK","C2v0zgi","zNfgvhi","zM9YrwfJAa","BhHKt2G","BMXWrwC","u2vYDMLJzvC","DwvRu2q","rfrrsMC","y2HLy2TdDxi","DMfSDwu","DgvmB2Djre4","lcbTyxGGCMu","z2v0sxrLBq","AxnszwfKEq","Be1pz0W","tKfusvzfx0u","ALnpEwK","y2fSBa","rLDlzMS","v2zywKq","sg1JC0O","ywnRDxbfBMq","BMnqug8","turdrMy","B2XKvMvYC2K","Aw5KzxHpzG","ALPkweu","AenSB3nLrxy","DeLK","Ae5RtKK","C2nOtxi","BNfjrhy","BgvY","mhWZFdf8nhW","CKjnrfi","qvb3vLO","C3bSAxq","DLfpqKS","ExbL","C3bSAwnL","y1n0B3i","rMvPywq","Dg9Y","vLLOzem","x3DHAxq","CMvWBgfJzq","rxDxrui","BKrQv2q","Bwf4uMv0CMK","u1j3D2W","ihrYEsbYzwm","wxH2Deu","zKfrsfe","DMvYC2LVBMm","suvhCMK","BxnN","BMCGzMfPBgu","tuvtu0fhrv8","ufjcAgW","C29YDa","EKjtC2C","z0DfuKq","yNvMzMvYzwq","EKfyDfO","vMnNANq","yMfJA3vWigu","B25tDgfYDfi","zwDHzgW","EwjtAMq","zxf1ywXZ","CMznrxa","BwvKAwf0zwW","CMvHzhDYAxq","CuHAue8","yM9KEq","A3riv0e","BM1pwNe","vK1IDxi","DhjPzxm","Axnby2TdBgu","DMLJzuLeig8","x2rItMfTzq","vefJDeW","EK1StKy","Ae9Hthy","ywrKt25L","D2fgy2K","AKzpEwC","vhvyz04","y0TOyw0","yxPZD1y","CYbHBhjLywq","y29UDgLUDwu","BuPADNu","uNzWvLi","u1jPsgu","DMvY","A2v5","D3jPDgu","rKrJug0","ywrK","vvDir1u","x2LUAxrqCM8","z05gs1e","u0XsuuW","Dg9oDw1Izxi","AxnAzxjV","wK1Otui","ANrkBNm","BMDcEKm","zwTcBxy","BNrbBMrvCgq","mxWZFdb8nxW","y29TCgXLDgu","thvyExm","DuPkqK8","rMLMtKm","BhrPCgXLihq","tKvhreG","t3PgzLy","B2nRzxrgywK","vLbLwMy","uKDwBhC","AM5Az0u","A1j4twm","sKfbq0O","sLnptLa","tg5vzwm","z2vtEw5J","EgL0suW","B25szwnLAxy","DePVuKK","mxWWFdr8m3W","sxjStKO","wvj1CxO","x2nYzwf0zvm","vvHpwMe","u3Lns2y","BMrWB2LUDca","q3DICxy","ChD4Dui","mZG1mta0nMTUsKDVrq","q1nrBfK","yxrLq291BNq","C0XPC3rLBMu","DgLUzYbZzxi","zgvJB2rLzey","BNHmuLe","wMDAwuu","Aw5PDcbrB1m","y3vYCMvUDeK","rNblDxa","C2v0y3vYC28","tuvPqKG","swXQwg8","yxzWyxO","u3nTEMW","s2fjvw4","rwLuqLC","Bg9Nsurhzw4","zxjYB3i","rMzvrhy","yNL0zu9MzNm","ywr2yw5Jzq","EKPHCvO","thrwB3e","DgHHBIbSB2m","C2v0","yMXVy2TLza","BM5Ly3q","v1j4D28","sLHKvLa","vw5YBfy","wMLWBvi","C3vWyve","Bgf4sNy","v01Qt0O","igzHAwWSig0","qLj0Aue","y29UBMvJDeu","tMvyquu","Ee9ctee","AgvHzgvY","BgLUzq","AM9PBG","z3LWBu8","s25oA1i","q0Xpu0LorW","yxnL","x2rPC3bHDgm","x2LZsw5PDa","AwDHDg9Yt24","vMPQC2S","EevlAxa","Cg9PBNrbBMq","x2fKzfDZtgK","rwHWCKW","B2zMBgLUzq","CwXkuvm","BK5Xy0C","CMvXDwLYzwq","qNjPzgDL","v050wgm","D0jcBxe","zK5puMW","CgjICdi","z3jPt3e","x1fVu01HBMe","ywXPzcb1CMW","Dev2zw50","C3HNyuO","uxvLDwu","quXTzLi","z0DTCfy","x2nSzwfYvgK","CNjVCK1LC3m","CM92AwrLigi","Bwv0Ag9K","tKDFrvjst1i","uvnYsLq","y1DRwve","D2vI","C3Pvq0e","AxnFywnR","wLDAs0q","EsbJBg9Zzwq","CwzqDue","uuTssw0","CLvfvgu","wevkt0e","BND4v1G","ihrVihjLDhi","yMPUvKO","vKrfqKG","u25hwu8","wgnAtMe","zMLN","CuDNv24","AgfUz2u","vNHLrxC","yNL0zuXLBMC","zufJAW","Ahr0Chm6","zNrJvNG","qLzNAey","uvvwBeG","CgfKuLC","AhrRzeu","Bgr1u1K","zgrjrcWGzgu","AhzoA3u","v2LUzg93","vxbKyxrLq28","wM9xs2q","zLvKyxy","AhzpDKG","C3rVCMu","swjez1K","u29ls0O","AwXLx25HBwu","CMv0CNLdB3u","B3jpBMXPBMu","DxrMofDYAxq","rvjst1i","y2HnyxHdB3u","B3jLtMfTzxm","sKLdr3u","z0LYEw8","AuTcD1e","C01WDMS","yMLNAfG","ueLnBeO","AuzJuwy","ihrPBwvZ","y3vYC29YlNm","zNjVBunOyxi","Dw5ZAwDUzwq","rMziwLG","y2HnyxHuCMK","tMTMCge","yuDRvgi","nhWY","ANDvuwO","tfb2q28","Cw9Z","DKT0sue","thzcufq","zgDVs2K","twvZC2fNzuu","BLnLDLq","rK9cuui","tK1utvy","ysbTDxn0igi","x2LZqNjVD3m","B2nRzxq","v0nSsKG","Cgf6s0y","v1HmDha","wKTXDgm","EvHVt04","CNnVCL92ywW","ww1AzMi","vhjjANC","sezOs1a","uhjPBwfYEuS","BwvvCuO","AfrpvuC","zwrPyxrLBhK","vufAqKC","t2LRBNm","qNLSuue","D2fZq2XLyw4","BMDLza","x19LC01Vzhu","BMvJDa","zNvUy3rPB24","mZyXnJmWD2n0A0vl","zw5fDMvUDa","AefJA01LC3m","DejAChm","zezbuKy","wgfMyum","wfjtr1i","v2vPEgLUsLm","q2jjB2K","x0vysvnu","C3HzBKq","Cgf5Bg9Hzeu","y3jLyxrLuMu","y3jLyxrLrxi","sxjWwg4","Ef9MCM9UDgK","zw5HyMXLuw8","DxjS","v0LKEvK","uuTLs1O","D2XNwgm","B2LUDfjLywm","x3jLywr5q2W","CM92AwrLige","wvDHDwS","ywnRtxnNswq","AeLPrg0","ywzL","ueXNCMK","suzJELe","zNbuDvi","Bg9NsurozxC","DuvSvu0","AxnmB25N","DhDVCMTdAge","x29WDgLVBNm","DeT1BuO","B2zMC2v0","tLz4wgW","uhrPqLm","uhzPDLm","y1rjCwC","yMfSu2nVCgu","ruHUtgG","BwfW","yMrFzgLK","u3LUAhq","D2j0A2y","vNzhwhK","r2vuENe","u2TPCcbWyxm","DMvUDa","igzPzwXKoIa","BwLUzW","Ee9nq3u","x3bPBMDqB24","ywvws2q","rKHsDeS","mhW5FdH8nNW","B0vmuMO","A2v5CW","BMvY","zgLZCgf0y2G","BurAsNO","wvzmsLC","r2LxBu4","zgv2AwnLx2K","rgTMyKm","rfDUr0q","yND6vve","Bwf4twvZC2e","ihbYB3rVy28","AhbxvKi","zxjFAxnFywm","wxPXD0e","ywnOzwq","yxH3AwG","yMTrq0S","A3HOEKi","vhvOuKK","yKHzELq","wKvyy2e","BMvcyvi","wLjVBxa","zwnvBfO","x29Uq2XVC2u","vK9Qwvy","CfHMs1C","C3vJy2vZCW","q05swgC","y2niDey","z2rHqxi","zfjjruq","DNbNB1e","Aw5nwu8","zLHRBMq","yNvMzMvY","mZu2ntq1CuDzDKDu","z2v0q3vYCMu","EfPSufm","Dg9iyxnO","v3PADKW","zw5XDwv1zq","v2vIu29JA2u","B3jRig9MzMW","uNbytvG","BMv4DcGPigm","zwvKzwq","s3zuBeq","qLHRBge","BMDuAw1LCG","t3bLBKv2zw4","B2r2sKq","x2LZv29YA2u","vgHJyKC","EvbVCMe","CMvJzxzPzwq","AgvHzgvYCW","zw5JB2rLrNi","ywXS","C2fNzq","ChjVDg90Exa","Dw50","y253uMG","x3bYB3rVy28","C2P4Dvq","ywvqvum","uKTVyKC","wKnTtfK","D2DpC2W","zNDZxZeUmc4","EwHkree","EvDNCLe","DvbNs1a","AKPjy1e","Fdr8m3W1","u2nXvxK","A29TBxG","DhDRt0G","CLz6Awe","qxPnDgi","zxH0zw5ZAw8","B09Vy3C","ohDRsNPLCG","r3Lfwge","vfnTuwC","zMLUza","zuT3t2C","CMvJB25Uzwm","qMzdwNq","x2rYB3bhBg8","vfr6z0y","vwrwswW","zxmGCMvHy2G","x2LUAxq","A2LZquW","EwDRBuq","EM5PrLi","B3jL","sxPdsxq","y3vYC29Yx2y","sMLeDwu","zK9bDNK","BgLZDgvUtMu","CMjlEgm","CvHnq1O","y2vfAeu","wKftrwW","B25ozxr3B3i","CKHOwhq","CuLZBLi","DgLLCKPtt04","zK55y2K","CMvZzxrdB3u","B3nLza","DeLUDgvYy2u","rxfzuKO","z0X1v1y","z0j1y0q","BM93","yw5Nzq","yNfQtw0","wM1Vz3G","C0zYBhy","s1HMrwG","AMvJDfn0B3i","x21PBMLoyxy","ChvZAa","ywDL","AgHJteC","qxPTuLu","EKvMsxu","yMLUyxj5vhK","x194x21Zz18","rhz5Aem","q0Xpu0ve","u21VvhO","AxnbCNjHEq","BwvZC2fNztO","zg9Uzq","ENLhtuO","y2XVC2uSihC","yMfoDNi","AwrI","B2zcvha","BNrLCG","mxWYFdn8mhW","y2vZC0HHBMq","vxvxCLm","wffQshC","zv90Aw1LB3u","ChfjyKK","x25HDMLNyxq","x2rPC2nVBM4","z1Hereu","AvfksNu","vMfxDem","vw5PBxbSzw0","CgLUz1rPBwu","svfIChm","uu12rxG","Aw50zwDLCIa","x21LC3nHz2u","ywXSq3vYC28","yNL0zxm","tw9KDwXL","zMvY","vwrnrhK","Dhr3Awq","sg1dB0e","CMLLC0nVDw4","svzVwwq","rKn3Cey","Ec1TC2CTy3u","BKTdzNG","Aw5KzxGGB3u","x2LUDgvYDMe","rK90C3u","tufyx1jfvfi","Aw5Lza","x29UugfNzu4","m3WYFdb8nhW","CK5Ls0m","zgfsy2q","Du10yMG","y3ruAw1LB3u","weDLuMW","teniENq","DgfIyxnL","Cgu6ia","vuPODuG","vLb0A1q","Aw5JBhvKzxm","z2TszKy","D3PoufC","u2z3r3i","x3nLCuLK","y29UBMvJDfm","Bg9IywXty28","wwz3D2S","AxDlqNa","CMvWBgfJzui","zeXKzLm","tgfhCMC","ignVzgu6ia","DuLMuKq","DMfS","DNPczeC","D3nZoI8V","A1bADxO","s1LjEM4","txnmqwe","r1fbww0","zMLSDgvY","x3vYBa","tg1RB3C","EgHytMK","wKPltgi","y3vYC29Y","vuDwwxG","tLb2Ahy","A1jpB3u","x3DZsw5ZDge","qunqBxK","AxHwB28","yw5Hz2vY","zwnMENO","qKrTyxC","DLzVDM8","x3bPBMC","B2zM","q3HMwve","y1Pcuxy","zcWGDw5RBM8","zgDPB2q","Awr0D20","z25zrw4","rujHAhG","yNLL","rKLRzKu","DgjetgG","vxvpz0y","v01Xtem","wgjRz0S","BIWGAg9ZDg4","DxnLCKLW","zNjVBu51Bwi","vgDNtNK","Aw47y2HHCNm","uhDKAM0","AfjYrwS","yxv0B21HDgK","swDxDNe","z2v0qwXSs2u","B3bLBIa","q291BNq","zLbuA3O","vMHREgO","tLnOCfy","rKHWCuW","BfrPBwvVDxq","BxnNsuq","rNnnA3O","r1H3sgu","qK5fA2e","Bwu6ia","zuzmt1u","yw5ZzM9YBvq","Auvyu0e","ELbXrwS","q29Kzq","D0jREvG","ExvHDeO","ru1LBvq","zgvS","vML5t3O","D0Pfz3K","CMvJzwL2zwq","u2v0Auy","rKLmrv9ot1q","Dg9VigXHCMC","q3vZDg9Tq2W","yMn0sxm","DcbSAw1PDa","qM9ltwy","yu5WAeO","BKvHqMq","uwL3B0C","zwDoDg4","yxbWzw5Kq2G","swfxEuy","uMPvqMG","zxj2AwnL","sejMwLC","AxnrB1nby2S","qwfrsNC","qw1VDw50","rhjTtgu","Ae1LC3nHz2u","ELDYwg8","y2TzqvG","Ec1TC2CTCw8","qvnuCfa","AwTOrhy","B25dBg9Zzq","BK50see","t2TwCMi","vNPSD2S","vhv1vgG","Dhj1y3rVCIa","CMvUDevUzha","CMfNzvn5BMm","u0r1uLa","rfvrt28","whLSDxC","rLDhv0m","AxbnvxO","zNjVBNrPzxi","BMrWB2LUDfq","sgXqywu","ANfAEwK","CM92AwrLihC","icSG","ywX6rvC","mJG3mtG2thDhCxrw","y2f0y2G","uMvJB25Uzwm","zgLZywjSzue","DePNzfu","CLrxzfu","v2T1twS","suvHDLO","CfnrzuC","x3jLBw92zvC","zxjFCw9Zx2e","vfjYv3O","yxbWBgLJyxq","rwPZD0G","BKLurLC","qu5PzxK","zfjNwvi","vgXTtgq","AMTPwgq","De9rtMi","BM9Uzv9UB24","Bxriqui","se1szhC","A2r3wKi","y3brC2G","B2fK","quPwDK4","C2DPza","mtb8mtf8oxW","q1bPAwK","Aw5KzxG","AxLXsgC","y2XVC2veqG","BgrjDu8","Chrsu2u","ANnsBwW","vgfN","CuzlsfC","x29Ut3bLBG","yKnXz2K","q2LODNm","Cvj5C0m","zw5JB2rPBMC","D2rxshO","zgvSzxrLrge","wMfpuw0","yvfkvuO","sNjszwi","u2vXsuq","CgzdEKq","Efziz3C","C0nVDw50zxi","v2XfsgK","Aw9U","B1nWqKK","A1n0yxr1C0m","uLLftfe","x29UvgLTzw8","zwfXEe8","wfblvu4","zgvMAw5Luhi","Aw9Ul2PZB24","B3nLrxzLBNq","yxKSig5LDhC","CMvHC29U","zMLSzw5HBwu","z2v0q3vYC28","zM9Yy2u","x2LUAxrhBg8","x2XPC3rLBMu","t1HlwwO","ugnoqNi","CMvZDwX0","AgLNAa","svzwCMq","yKrivLa","EwXyweq","B3bLBG","EMj2BeC","zxjYtxnN","EerMsMq","x0rctMfTzq","rxnWvhm","sNjsAhK","rhL4ufO","y3jLyxrLt3a","Dg9mB3DLCKm","DNbNCNO","EfnkB2C","C3nHz2vfDMu","vwjTuxe","tMfcz2W","o2nOyxjZzxq","u21kuwS","q0H6B2W","CNzHBa","zNjVBuHHC2G","uLPXuui","vKfeqLG","AevYCM9Yrxy","EfzKBw8","DxbKyxrLq3u","Afz5Aum","uLHPExe","wgvmyum","CMvQzwn0","BKXPBMu","yw51Ce1LC3m","yvnXruW","ywnRx2nVzgu","q2P2quK","mxW4Fdz8m3W","B3bLBKrc","CLvkCfe","D3m6lY8","AKzJuwW","r2HWwxK","seTbzuS","y2HLy2Tszwe","B3vUDa","x3bHDgHlzxK","qxjRtum","EfD2Beu","yw1L","B3zuAuC","Devxy2C","Ew5fBhC","B2jQzwn0u3q","BNvotgW","sfjZuuK","A3POu3K","senwB2K","vgLTzw91Da","A1rotum","y3vZDg9Tshq","C2XPy2u","r3r4seK","BMrLEa","Cg9PBNrdB24","rw5AvKu","twvUAfO","ChjVy2vZCW","DhjPBq","z29PBMCGyxC","AMTvrhK","C0Xf","zw1PDa","BMnLq2XVC2u","C1HWCNC","BMfTzq","uezQCui","z2v0s2v5","DuTjr2e","y3jLyxrLtwu","ywDLu2HVDW","zMzmAw5L","ELzfrMm","r05jyM0","z3bisLu","DvzArMW","yxnZAwDU","zwDIAK0","q2vnrKK","zw50","Dxb1yM4","zMD6BLO","t3DozM4","wg5RCge","s3vtELC","C2vUza","qMDUwK4","y2XLyxjtDg8","t1b3vuC","z2v0t3DUuhi","CNnVCL9Uyw0","yxbWBhK","y3jLyxrLq2W","Bwf4tg9ZC0m","qvroywW","suvtx0vsuK8","svPSruy","DgvZDa","B25nzxnZywC","AwXSihvZzsa","D01qsNi","DgXSDxi","z09iAha","zufrrM8","zw5HyMXLqxu","D0vnEfq","Dg9hzw5LCMe","B0flC2K","C3rLBMvYCW","vKT6CwS","C3rVCcbPBw0","qNrnANC","zgf0yq","BgDKDey","Au9iDwq","CMvTB3zLrxy","rxjYB3jdB2q","BgLUzw5V","CMvTB3zLq2G","vwzjwwq","tKz1quy","ENHlEM4","CMvtCge","BMCGDxjSoIa","turqyxO","x2TLEvbHDgG","uLPywgm","BgLTAxq","z2TvsKy","vhbAAg8","DNHkuxi","y2z5ELq","CM9YrxzLBNq","q1zwrvm","ywnOzwqSihC","AMLfC08","tgLZDgvUzxi","sLfTB2i","EhjpyvK","zxjFCw9Z","y29SBM8","rKHJExK","CvPNz2G","BwLZzq","BwvVCuC","yxnJCMLWDa","C3vIC3rYAw4","svDbyw4","ru5WCwK","wNzjBwy","mdaWma","CMfTzq","CMfUzg9T","suzQueC","x29UtwvZC2e","t1L1t3y","twTLCei","r0HHC1y","z2vjBMzVu3K","tgLmEK0","yMfSrxzLBNq","Cgf5Bg9Hzfq","zvvqthG","A2vRsvi","q2XXANu","tg9JAW","AeXJzhi","zNjVBujPDhm","Dufnrvi","yxrHlcbKyxq","s0LQzwu","Dxj4A3a","DwLAugW","yxKSihrYEsa","x3fVC0rc","zu9TDei","zfDVCMTLCKC","BNrfBMrWB2K","CK1lEe8","re53tNe","reD2Awy","C2v0q3vYC28","x2LZtwLUAvC","C2HPzNq","tMPUCem","yw1LoIa","te1Xr1K","z2L4DMC","B25TzxnZywC","x2n1CNnVCK4","BwPfzuW","q1H2tMG","qvrMEwO","mNWXFdb8nhW","tvbOuw8","u2HHCMvKv28","rNHID0u","tvfkrhC","C2Ttr08","rMTUDw0","q1bjy0K","ufbjEe4","twv5ALy","Dxrjza","yKnntLm","Eg9tBKm","refmBg8","DgfYz2v0","Cg5PtK0","C2v0sxrLBq","swffuNe","ihrPBwvVDxq","zxrgCKK","D2LSBfjLy28","AgfZt3DUuhi","vxfrthu","x2DLDeLUDgu","vM1sCvC","B3bsvgu","y3jLyxrLrwW","DufvvKG","ChriCKW","zLPZD0q","Bg5pzva","y2ndAKS","z1jItuC","ywDLsgLKzq","vMjMCKi","vMLlEey","x2LZtwLUAvq","CMvZB2X2zq","y29UBMvJDca","DurgsvC","D3vHy0S","ru5HEfi","v3HyEKq","BKLptwK","CNnVCKzPBgu","qNndqxq","y1DgCKO","uwDAD2i","odCXodi0yurPCuzX","uMvutgO","C2vUDa","EwfOA2u","zsbHihn0CMK","DgHLBG","Efrurw52","uuTjtfa","DhLWzq","ngv6B29jAG","B21iCge","qKjgy08","ihzHBgLKihm","qxbJBwe","ywDku2S","C3vIyxjYyxK","sertqNO","CgLUz0LUDgu","ywrKrxzLBNq","qwjVCNrfCNi","vMPSseO","BwvZ","D3jPDgvvAw4","y3jLyxrLt2i","BwvY","lcbxzwjtB2m","BezSDxnO","quzqDu0","CgXLyxnLiha","DgLTzw91Da","rxvduuK","q3vZDg9Trxi","twrzwKm","C0jf","y3btrMG","veThwey","uu1JtxO","yK5Zue8","wuX4zwy","z2vY","yxDnzxu","zMrUuuq","AMrpDvq","vvLyAhy","wefmt2e","BNruCMLLC0m","q09otKvdveK","EgPWsw4","igfYCMf5yNu","zNjVBuj5Dgu","EeXkvhe","Dgv4Dc9Qyxy","BLjWtMS","x3bYzwzPEa","BMnVzgLUzW","B3rivM4","tLvoEwO","rMDHs0G","rePfwhq","Dfnzy2i","BuXbBK4","zv9ZDwnJzxm","aaaaaaaaaaa","u3Lzrwi","C3jJ","z2ftvhe","zw5KCg9PBNq","zxH0ugf5Bg8","t1bftL9fuLi","ue9urNC","vxzwqMm","Cgrdseq","BLvhv2i","CMvHzfvjBNq","z0znzu8","wxLbAvi","BeHHBMrSzxi","v2nYDei","y3vYCMvUDeu","B3v0sw50zxi","AwXLtMfTzq","C0voBLe","tgrWDgu","ve5KCK8","AxnrB1nnzxm","D1vYvLK","y2XVC2u","D3fzt0W","Cgf5Bg9Hza","D09HsvO","twLZC2LUzYa","tLbyzNC","C29Tzq","zwrtyNy","x3jLy29UBMu","yMLUyxj5","AuPUtLe","te1jzwq","sfz5whi","x2rLC3rYB3K","t2jQzwn0","y29UDgv4Da","wvjqswy","EfvLBgC","uwvcyNG","rMrfv0W","y3vYC29Yx24","C3rHCNq","AgfZ","rgH6A2m","Bxb2yvG","q09oveLovuu","vMLTswO","swLuBwK","yvbHAgS","zgjHvw8","zNjHBwvuExa","CgfNzxnOB3C","x2HHBMrSzvi","qKDss04","u3rYyxrLz3K","zK1Vz08","CLzvzfq","v3DluNe","ywTLDgC","CfrbAMW","y291BNq","tg1qqu4","sLvMCum","vxvlywq","q0HVDKK","x3nLBMrby2S","rgHqruq","v0XKzwm","zuXmtey","CgLUz0XVC3m","D2PmD3u","AerfD2y","x3nVy2TLDa","EuDnu2u","CvnAtxa","C2v0u3rVCMe","re1drLK","zw50zwqGDhK","zxjYtM8","Dgv4DfbHEwW","q0r5Efe","yw1Lu3bHy2u","u1fowgK","s05jDLG","tKHsq2i","r3DVzNe","y0rby0u","yuPnswK","rgvKAwnHDgu","vKLoA24","CNzHBfzHBhu","s0fnzvy","uNHVwuq","CMvZzxrfBMq","zwr6wwO","sKrnBMe","Aw9UvgLTzw8","x3bPBMDmB3m","z1bPDLa","DgLTzw91DcW","zwn0","BwvZC2fNzv8","z3nWrvq","zgvSzxrL","lcbOB3n0BMe","zwnVBM5Ly3q","x29UrxjYB3i","uLLmrue","t0rHuMG","CuXbBKe","sefjzMS","B3bLCNr5","ihn1y2nLC3m","CIb0DhDjra","A0LUEMm","x2rLyNvN","Ahr0Ca","Bg93","EgnkzM8","uef0zLe","rgz3CKC","y3r5uMK","Dw5RBM93BIa","qwHNqxq","DwXzDLe","zMXVB3i","ugf1rNy","vw5Oyw5KBgu","zMX1C2HfEha","Cerwt2O","ueLHruq","zMLYweG","Aw5N","teP4ve0","mJeYmda5AM5tuwHp","DMfSDwvZ","suLoqLG","zMXTv28","C0XcwK8","zvvYBa","CMvKDwnL","Dgv4Dc9WBge","EhfVtNq","D2nNAg0","z2v0u3rVCMe","z2HjExq","ANzPEem","z2v0qwXS","EK1jCxe","wu5YCw4","yMLUza","Ec11C2uT","r05nq1C","z3rHqKO","x2DLBMvYyxq","BhrTAeq","uuHitKu","u2PwC2y","rg5bzxe","BwT6vLq","DcbVzIbYyw4","Bu94uva","wMfjtM0","txjuy2u","Exbezu0","Dg9cExrLC0i","q29UzMLN","AvnIBM8","y2uGBM90igK","zeToq0e","tg9NsurozxC","z2v0","C1P3twK","CxHNt08","x2n1CNnVCK0","DujtBgq","zw50tgLZDgu","qNP2tKy","CePdrMG","Cw9Zx18","ChDIEhq","uLjpuG","vMrKsxm","B25JBg9Zzq","zxjHDg9Y","sNvsvva","C2vYDMLJzs0","v1rjBwC","BNvTyMvY","z2fytfq","ufjhvvi","ALnczLC","yxjYyxLIDwy","BerVuLq","Cgvtv0e","EvjLy29UBMu","q0fiuLq","rMvRELa","C3rYAw5NAwy","yK1eBKK","wvzqCK0","z0niyve","r3zRCve","BvPis1e","ENfIDNC","ig1LC3nHz2u","De1HBMfNzxi","y3r4","ywfjAMu","rwv2DLy","DK5RvNq","ywXty29Wzq","BvfAvg0","yur3zNu","CgLUz19VBMm","A21Mug0","Ewvstu0","wNv4vhK","y29Kzq","reiGzMfPBgu","Ew5gsNO","txnUB0W","wM1Jwg4","x2nVBM5Ly3q","x2jPBMfYEvq","Chvgrhu","rLDt","CKvHBMe","v3rTrMC","B3HoCha","Cuvsr3q","Dg9cExrLCW","AxjLza","id4G","shPgEu0","tgXju0q","uKj5zKG","CgDZyxK","q0HRq00","yLLrA3a","ihzHBgLKigq","t3zfww4","C3rYAw5N","u3HnvKW","DhjPzxmGCMu","x2nSzwfYugK","CLHmC1C","x2vUzhbVAw4","rK1xr2q","yNzlrwC","yxv0BW","DxvKqwq","zLfvExi","y29Uy2f0","Eg55y1q","C2vYDMvYvgK","Aevbvfi","t3vWuuG","DNfcwuS","reTIsuy","BerAuNu","ru5MrwW","uuHLs1e","D24GCMvHC28","B25VCgvU","BMv3vMvYC2K","B3rvq2y","ueXstgu","rNjVBNrPzxi","B25tDg9Wsw0","EKzkBfK","DgrJru8","q29MufO","twzHq3C","u0LJtM0","BKrezKi","ELHeDfK","mdaWmdaWmda","y2XLyxi","Chv0","sgfrr0G","CMvHzg9UBhK","DhbizwfKzxi","B3jRzxjhBg8","ChbL","y09Wzw4","BvfdCMq","y29UBMvJDa","sgHQBNC","vKLkC1q","qunmuve","CLDmvg0","y29UC3rYDwm","zgvIDwC","ChjVDg9JB2W","BwfUDwfSihi","Ag9cBg4","A0fIuMm","BML0AwfSAxO","zxrxB3jRq2G","rgvuBgm","uvzyyMe","C1Heuxa","y2nNs0W","rNHOC2K","rKDAtMu","AK9wC3i","qwTWEhG","AezLwKm","DfvXAhK","DMvYC2LVBG","qM1Sy2e","s2nmB3C","zxHWB3j0CW","nxW3Fdf8nG","zw5HyMXLvhi","CgfYC2u","pxv0zI04","BeDwyNC","rxzLBNq"];return ka=function(){return t},ka()}var Ea;Object[M(824)+M(1266)](He,M(377)+"le",{value:!0})});import{existsSync as NI,openSync as FI}from"node:fs";import{mkdir as BI}from"node:fs/promises";import{dirname as zI}from"node:path";import{fileURLToPath as UI}from"node:url";function qI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Il(t=Z()){return NI(t.libEntry)?t.libEntry:UI(new URL("../index.ts",import.meta.url))}async function sg(t={}){let e=t.paths??Z(),n=t.entryOverride??Il(e),i=qI(e,process.env.COZE_BRIDGE_LOG_MODE);await BI(zI(i),{recursive:!0});let o=FI(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],f=dt(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[As]:"1"}});if(f.unref(),typeof f.pid!="number")throw new Error("failed to spawn daemon (no pid)");return HI.info("daemon spawned",{pid:f.pid,entry:n}),{pid:f.pid,entry:n}}var HI,As,Da=ot(()=>{"use strict";Wt();ne();Pe();HI=q("spawn-daemon"),As="COZE_BRIDGE_DAEMON"});import{spawn as zA}from"node:child_process";import{mkdir as UA,unlink as HA,writeFile as qA}from"node:fs/promises";import{dirname as GA,join as jA}from"node:path";function gi(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function WA(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${gi(n)}</key>
|
|
21
|
-
<string>${
|
|
20
|
+
`+n)}function yr(t,e,n,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,yr),t.emit("wsClientError",d,n,e)}else Is(n,i,o,a)}});var Vx=ue(qe=>{"use strict";var N=$;(function(t,e){let n=$,i=t();for(;;)try{if(-parseInt(n(471))/1*(-parseInt(n(426))/2)+-parseInt(n(912))/3+parseInt(n(1123))/4+parseInt(n(1280))/5*(-parseInt(n(922))/6)+-parseInt(n(1161))/7+-parseInt(n(937))/8+parseInt(n(760))/9===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ka,610975);var nI=Object["definePr"+N(1237)],rI=Object[N(432)+N(1498)+N(1284)],qx=(t,e)=>function(){return t&&(e=(0,t[{gBfYq:function(o,a){return o(a)}}.gBfYq(rI,t)[0]])(t=0)),e},iI=(t,e)=>{let n={cwJaB:function(o,a,d,u){return o(a,d,u)}};for(var i in e)n.cwJaB(nI,t,i,{get:e[i],enumerable:!0})};function sI(){return Bx||(Bx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function oI(){let t=N;return zx||(zx=[IDBCursor[t(294)+"e"][t(940)],IDBCursor.prototype.continue,IDBCursor[t(294)+"e"]["continue"+t(731)+"ey"]])}function aI(t){let e=N,n={hWUmm:function(o,a){return o(a)},JhjMK:function(o){return o()},zZLKc:function(o,a){return o(a)},SjMZD:e(1460),tsgwE:"error",KzShB:function(o,a){return o!=a},Sjajb:e(505)+"d",GXfEw:function(o,a){return o instanceof a},zMusW:e(985)},i=new Promise((o,a)=>{let d=e,u={TMJFj:n[d(1196)],uPUdv:n[d(1021)]},f=()=>{let g=d;t[g(1177)+g(421)+g(1557)](u[g(641)],p),t[g(1177)+g(421)+g(1557)](u[g(117)],x)},p=()=>{let g=d;n[g(1039)](o,tn(t[g(1032)])),n[g(686)](f)},x=()=>{let g=d;n[g(321)](a,t[g(1173)]),n[g(686)](f)};t["addEvent"+d(913)](n[d(1196)],p),t[d(1560)+d(913)](n[d(1021)],x)});return i.then(o=>{let a=e;if(n[a(1205)](o,IDBCursor))if(n[a(1283)]==="XcuZp")bl.set(o,t);else{let d={qbOUu:function(u,f){return n.KzShB(u,f)},GEByH:n.Sjajb,gPiRs:a(400),lqUhW:a(208)+"le"};_0x2e33b0.r=u=>{let f=a;d[f(1359)](d[f(692)],typeof _0x1c70e2)&&_0x45211e["toString"+f(1419)]&&_0x39be00[f(716)+f(1237)](u,_0x661fe3[f(1250)+f(1419)],{value:d.gPiRs}),_0x2a8b4e[f(716)+"operty"](u,d[f(379)],{value:!0})}}})[e(611)](()=>{}),Ta[e(423)](i,t),i}function cI(t){let e=N,n={GoYgg:e(762),bFDrQ:e(770),NmSWS:e(1543)+"or",mHCef:function(o){return o()},HeYNI:e(1173)};if(Ca[e(1266)](t))return;let i=new Promise((o,a)=>{let d=e,u={DIpxl:function(g){return n[$(296)](g)}},f=()=>{let g=$;t[g(1177)+g(421)+"ner"](n.GoYgg,p),t[g(1177)+g(421)+"ner"](g(1173),x),t[g(1177)+g(421)+g(1557)](n.bFDrQ,x)},p=()=>{u[$(462)](o),u.DIpxl(f)},x=()=>{let g=$;a(t[g(1173)]||new DOMException(n.NmSWS,n[g(1423)])),n[g(296)](f)};t["addEvent"+d(913)](d(762),p),t[d(1560)+d(913)](n[d(718)],x),t["addEvent"+d(913)](d(770),x)});Ca[e(423)](t,i)}function dI(t){Pa={dJAsH:function(i,o){return i(o)}}[N(346)](t,Pa)}function lI(t){let e=N,n={hLknc:function(i,o){return i(o)},MybCl:function(i,o,a){return i(o,a)},PfTBE:function(i,o,a){return i(o,a)},JgSwU:function(i,o){return i(o)},XbPnB:function(i,o){return i===o},xUFLI:function(i,o){return i in o},nJUQl:"objectStoreNames",pnIns:function(i){return i()},zMCDr:"ENcuG",jdvYZ:e(412)};if(n[e(1084)](t,IDBDatabase[e(294)+"e"][e(878)+e(926)])&&!n[e(126)](n.nJUQl,IDBTransaction[e(294)+"e"]))return function(i,...o){let a=e,d=t[a(894)](n[a(455)](As,this),i,...o);return yl[a(423)](d,i[a(837)]?i.sort():[i]),n[a(455)](tn,d)};if(n[e(155)](oI)[e(1270)](t)){if(n.zMCDr!==n[e(948)])return function(...i){let o=e;return t.apply(As(this),i),n[o(455)](tn,bl[o(131)](this))};n[e(191)](_0x473458,_0x2fd6c6,58),n[e(1392)](_0x20359a,_0x5f54b3,_0xe9c27b)}return function(...i){let o=e;return n[o(455)](tn,t[o(1203)](n[o(547)](As,this),i))}}function uI(t){let e=N,n={jaWWK:e(1208),nThPN:function(i,o){return i(o)},gSndZ:function(i,o){return i instanceof o},kzUPR:function(i,o,a){return i(o,a)}};return typeof t===n[e(910)]?n.nThPN(lI,t):(n.gSndZ(t,IDBTransaction)&&n[e(1033)](cI,t),n[e(494)](jx,t,sI())?new Proxy(t,Pa):t)}function tn(t){let e=N,n={EYZZV:function(o,a){return o instanceof a},GPJLl:function(o,a){return o(a)},ZZGUM:function(o,a){return o!==a}};if(n[e(711)](t,IDBRequest))return aI(t);if(Ia.has(t))return Ia.get(t);let i=n.GPJLl(uI,t);return n[e(623)](i,t)&&(Ia.set(t,i),Ta[e(423)](i,t)),i}function ka(){let t=["sxLxshq","tLjzuMe","zujgs2i","A0Liz08","ywnRDxbfBMq","mxWWFdn8mNW","vKrzD3y","yNvMzMvY","zMLSDgvY","wvzjyxO","q2DrDLG","x21PBMLoyxy","BwLZzq","B3nLza","C0XPC3rLBMu","sNnfvfq","CM9YrxzLBNq","BxjfAeC","ihjLy29UBMu","x3nLCuLK","zwrPyxrLBhK","CMvWBgfJzq","tLziA0m","C2vYDMvYvgK","z2vtEw5J","uhPdBeK","uMvJB25Uzwm","B3nLrxzLBNq","BM93","tfHjwei","tMLeDNy","EeXKtw8","Ae9Wzw5fDMu","ndeYndm4nMTwy2jPBG","rM9KAeW","vK9pC2e","zvDAv3G","CxjUEuu","DgvZDa","z1Dktem","D0PQt0C","B25LCNjVCG","DK1ds0m","y2HKvgG","B25Uzwn0Aw4","zxjYB3i","v05SCxa","DwLRuvu","rNrpzxu","CMvTB3zLrxy","AMjoAve","uejmy3y","t3bLBKv2zw4","reiGzMfPBgu","zwHjrg4","vKjeDLm","s0vqDxG","te9is3i","sw1vuMe","AuDnv0C","z2v0q3vYCMu","ve5NC2q","BKviBey","x2nVBM5Ly3q","DgzztLC","CwT0tLG","CM92AwrLihy","Aw1LCYbPBIa","u2PnwKq","u25YrgO","ihrYEsbYzwm","Dg9cExrLCW","vxLHDuS","BMv4DcGPigm","CNv5CNy","yxbWBhK","qxbUwha","r1HMrxC","q0DZt1u","wNfHt1y","zNvUy3rPB24","v1jRDvu","CYbWyxjHBxm","v2vprey","y2XVC2u","x2n1CNnVCK4","CNjVCK1LC3m","qunIteG","AxnFywnR","B25TzxnZywC","CNnVCL9Uyw0","tg5SrM4","v212sLq","CMvQzwn0","DMnQqMm","r1LZvvy","v2DZwui","C2nYAxb0","q291BNq","D1bQvva","twTeDMm","q0Xpu0ve","uhvyqu4","y2X0qLy","txDxAgS","BIWGAg9ZDg4","Curdq0i","qxbowKy","uMfkzey","B3bLCNr5","ohW3FdeWFdK","rKXWrMu","vevnvLK","zxq9DxrMltG","t0LsEhq","x2rLC3rYB3K","CMfTugfYyw0","Dgv4Dc9WBge","x3bYzwzPEa","y29UDgLUDwu","zgvJB2rLzey","AevYCM9Yrxy","Dg9tDhjPBMC","Ew5jtfK","zMj4rwS","uhngqM4","zxjYtxnN","zM9Yy2u","AwzntM0","EwnItNK","A09mwLi","y2Dmr2i","wKLeqLG","B2fK","ignVzgu6ia","zgf0yq","z2zvqLK","Ewv5rM8","AgfZ","vNvtBxK","DKLsA0W","x3bPBMDqB24","Aw5JBhvKzxm","yw51Ce1LC3m","ign1CNnVCIa","qxD2zhm","Cxn1qK4","m3WX","x2HHBMrSzva","BwvZC2fNztO","uuT4tee","tKDvq3K","mJu1wwvltu9d","y1zLtei","Dev2zw50","EK11C1C","BwvZ","yxKSig5LDhC","C29lquC","zw5XDwv1zq","EKrsug0","EwHRr08","mdaWmdaWmda","sfr3D3G","vhLtqwy","CgLUz0XVC3m","B25fCNjVCG","y2HnyxHuCMK","vwXvuM0","s2LMyxi","Bwn5BeS","y2uGBM90igK","D2XLtuS","B1bzC0C","yNL0zu9MzNm","tfHcCxu","A0PewKO","C0jf","B3bLBIa","zMvY","B25VCgvU","zxHWB3j0CW","CMvKDwnL","ywvizg4","rerAshi","DhLWzq","y3jLyxrLq2W","B2zMBgLUzq","AM9PBG","z2v0qwXSs2u","vwjZEfm","ChjVDg9JB2W","r3Hez0y","tg9NsurozxC","qLn5Egi","tfbbBwq","zxjFAxnFywm","BMrUCNK","qLnJs0C","AenSB3nLrxy","Bgnvyvq","AxnrB1nnzxm","r3zvBLO","s3n6ALu","DLfNruS","x29UvgLTzw8","AuDruw4","x2LZsw5PDa","sezluwC","rfHIsgO","u1vuuMy","qKrRq3K","u2TPCcbWyxm","zwnVBM5Ly3q","De5nvKW","rLf4rLK","z2v0s2v5","EMD5rxu","x3jLywr5q2W","yw5Hz2vY","v0DAENa","DvPAyKe","BMCGB3iGyw4","x21LC3nHz2u","EKPnBfC","twzrA1q","zfrKy2i","rfnXAgO","B25SAw5L","C2vUDa","EfHOsMm","Cwjpvxu","x2HHBMrSzu8","BMnVzgLUzW","v2vPEgLUsLm","CNnVCL92ywW","q1zzq0C","B1n5zLO","y2XVC2uSihC","vMj4uMe","EvH1D0O","x2XPC3rLBMu","Du1puxa","zhreAeu","vgXir0i","wgnnzKi","AgvKtwf4uMu","u2PTs3e","rfvkDuO","zxfMCKO","yMvMBu8","qxfszNG","r3DmrvK","EejkyMC","uuDiyMe","x3nVy2TLDa","BgjXDuG","AKDztvu","DeLUDgvYy2u","AhfxqKy","uML2z3e","AxnrB1nby2S","De1mz0e","y1rXwfq","ugzuqKu","BgvUz3rO","Aw9UvgLTzw8","C3vIC3rYAw4","y1byBw0","sevdvuW","tg9JAW","C3bwuNC","AwfvDgm","zuvUC1K","t0TQu0m","DLLYyKC","zwvKzwq","t2jQzwn0","Dg9mB3DLCKm","sxrbDxK","x3bHDgHlzxK","zxjYtM8","CePAC00","AvjduM0","uKXzsNG","CgXLyxnLiha","v3LIALu","C2DPza","rMjzs1q","m3WYFdr8mxW","t3HpDhK","vgfN","vvbuu0K","BgvY","wKrrveK","tM1tv1m","yxrLq291BNq","u2HHCMvKv28","DxrMofDYAxq","tvzuELO","tg1xvhi","tezLs3y","B2zM","x2rPC2nVBM4","r1bowuS","wfPoCM8","yML3C1i","vuDoExC","Du5Mzxm","qKrivuy","AhrRswK","rxbHD20","txvWBxC","CM92AwrLihC","D3jPDgu","rNLmzMW","Dxr4ueK","svj0CwS","Dw5ZAwDUzwq","vgrbrvG","AxbzENa","Dgv4DfbHEwW","q29UzMLN","y3jLyxrLt2i","AgfUz2u","zMLSzw5HBwu","mxWWFdj8nhW","qw1VDw50","sMT6C0q","vvv1A0G","qKPSre0","Cg9PBNrbBMq","C3vJy2vZCW","z1bcEwu","zKn1veq","q2TtrxG","C2v0y3vYC28","CMvJzwL2zwq","AvPzv0K","qu93sem","CvLnswO","CgLUz0LUDgu","y3jLyxrLtwu","svvHzLO","u3b5Cwq","AwXK","tMrxBK4","twvZC2fNzuu","C3rYAw5N","AfHjEui","x2nSzwfYvgK","BMrLEa","vLjSz2K","EvjLy29UBMu","x2TLEvbHDgG","x0rctMfTzq","EeP6DK0","x2HHBMrSzvi","y2HLy2Tszwe","Ec1TC2CTy3u","sLnptLa","BMvLzf9Hy2S","vKTgDxe","zgvSzxrLrge","CMvZzxrfBMq","zMzmAw5L","mdaWma","u0TIA2m","r2DMsgC","C1PJq0O","B3bLCNr5tMe","rxjYB3jdB2q","qurlDLu","Bw5OEei","Efrurw52","B1LKDKi","sKLQuha","sMPAwNa","ihrPBwvZ","Dg9iyxnO","BKXPBMu","wMzKvva","qwzjr3O","AuzeDuW","zfHkAwG","BLnLBKy","uMnxsK8","Bg93","BMrWB2LUDca","zLrOEKy","v0TeCMq","DMLJzuLeig8","tLPZEM0","zM9YrwfJAa","DK10CNK","Chv0","s0v2BM0","qLjjEgK","svjjEeq","t1bftL9fuLi","yxnL","AwDHDg9Yt24","q25ny2u","BNbdA0C","EwPKwhq","ruHXDKq","rNjVBNrPzxi","tuTKAgS","EMLhyLO","BuvRwvy","vxbmwue","C3nHz2vfDMu","zgLZCgf0y2G","q3vZDg9Tq2W","se56A3a","qwjVCNrfCNi","ChvZAa","De1HBMfNzxi","rLjpthK","v3PIENu","tLL6uw0","sxrVrgW","DxrVuMvJB24","tLDqsw8","Cw9Zx18","B05mt2i","ueTYBxO","lcbTyxGGCMu","ExvOvgq","BMvY","DgTty0O","D0LUveS","ywrKrxzLBNq","x2rItMfTzq","wMzNtva","zNjVBunOyxi","CfnIshe","AgLNAa","uNDpwha","zu5jB00","y09Wzw4","pxv0zI04","yw1JBKC","rhn0BLG","zNjVBuj5Dgu","wNjTCve","B2nRzxq","qwDkyMm","EwzKD3K","B0TgBMS","CMvZB2X2zq","D2nUteq","EunYteC","yKHvsxe","y2XLyxi","zxzNwha","BM5Ly3q","BfHZthy","EhjvA0m","DxLXsvu","C2v0q3vYC28","z2v0u3rVCMe","EgnntxC","yMfSrxzLBNq","AxrRzhq","zu1UCxa","ywnRtxnNswq","BMfTzq","x3nLBMrby2S","CNzHBa","DMntELi","weroAfC","D2LwC0y","sKf5qK0","sKvZsgy","BMCGDxjSoIa","v3v0EhC","Dvbvzhy","t1reyKi","ExPlzhu","zhzpy2S","B1HXqw4","y29UBMvJDfm","y1PUEeS","DgLTzw91DcW","wenxvuu","EfvgteK","vKvWCNK","ihzHBgLKihm","C3vIyxjYyxK","Bwu6ia","z2v0","x3jLy29UBMu","yKvyuLa","uu5bDKq","wwn4vfm","r0HfyKK","ExH1qw4","BxnNsuq","AxmGDw5Kzwy","AgvHzgvY","zwn0","A1n0yxr1C0m","Eu1qExq","zNjVBujPDhm","tfbfswO","rw9eEem","qK5es2i","ugr1D1u","zMLUza","qKzOze0","Cg9W","z2vY","x2vUzhbVAw4","CgziueK","Cg5jBNm","DMfSDwu","x3fVC0rc","z09vufe","t2TOy2u","BxD2C00","zgjdyNq","tMXbyum","ywXS","Cw9hwMy","DcbVzIbYyw4","v09vB3q","C2zJqKS","C2vYDMLJzs0","EKzSzKi","y3vYCMvUDeK","yM1hwNu","ueTUs0G","qNPwwMC","wNnpEvy","CMvUDevUzha","B25nzxnZywC","q09oveLovuu","t21jzMq","EhjJwgq","A3D6DhK","CKn3EKe","B3jRig9MzMW","wu9qwMC","su5tvefova","Buz6Axi","zMzMzG","DKjrCeq","wLHewKO","D1vctKm","ywXPzcb1CMW","txLIq2W","zfrqrxu","CMvJzxzPzwq","y291BNq","qNjPzgDL","ywWGy3vYC28","Dg9cExrLC0i","BeXswgG","ELfZCgK","ihn1y2nLC3m","A3H5uLq","x3bYB3rVy28","DezXsgy","sM1TquK","ve5IELa","C2vUzf9Hy2S","uw1er2u","x19LC01Vzhu","yw5ZzM9YBvq","BwvKAwf0zwW","sKPLzuK","zgLoufm","DeXPt3G","qNzPExe","u2vXsuq","rxzLBNq","ENfzC3q","thfUwxi","zgv2AwnLx2K","DezpExK","swjxz2W","vKnNBvK","zxH0zw5ZAw8","sunKrKW","ww5ptwm","rxrYC2u","txz3uuu","Eu12uMi","CIb0DhDjra","Dxrjza","aaaaaaaaaaa","te9MB2W","x29Ut3bLBG","x29UrxjYB3i","z2vrDwv1zuW","zNvtvK0","ENneDuC","DMzJz1y","yMLUza","seXvyvy","vezPCKu","vePdzLC","zxj5yKm","q25qy3q","Bu5mD1m","Bg9IywXty28","DhLrq3u","A1r2thG","BNrbBMrvCgq","C3rYAw5NAwy","vNjwsvC","uLjpuG","t3nprfe","CKT2A2C","B3v0sw50zxi","AxnmB25N","DuXYwgG","Bw13Ee4","t1f0Bem","EhzHwe8","yxrZBha","v3nHwKS","y3vYC29Y","yvrWq0G","qKvUBMK","qxHiufG","v05KyK4","B2zMC2v0","AxnXzKG","Cg9PBNrdB24","suXeyxO","EK94uuq","nNW1Fdr8mxW","yw1L","zMLduxK","sxvPrxO","CwHJC28","ywnR","BeTmv0y","vK9UqMC","vfrOyvy","ChvYrw8","B3bLBKrc","y0HsDee","q3znB1O","ugfzqxa","wwvfvuK","EeLiwuC","AefJA01LC3m","CgvYC2LZDgu","v21AANG","x3jLBw92zvC","yxnZAwDU","ChjVDg90Exa","Ewjqs20","BuHdzwy","uLnjA2C","Cg93","ug5cy1O","vNnjBwG","ywrKt25L","Aw50zwDLCIa","CMvTB3zLq2G","BgLZDgvUtMu","DgHLBG","yxGGCMv0CMK","CgnIywW","Cxfyr0q","AwrI","qu1MDNC","DMfSDwvZ","zgvS","DgLUzYbZzxi","veneshe","vxbKyxrLq28","ywXSq3vYC28","t2fABuO","ihzHBgLKigq","ywnRx2nVzgu","AeLRufe","ELPms2m","Aw5L","y29SBM8","ywDL","BMDLza","vLf1sNq","A0n0suS","z2v0sxrLBq","zxj2AwnL","uNbRs3K","EuDUBfy","wvvtCw8","tgTdA0i","tNDlt3y","BML0AwfSAxO","vLrMquu","Cgf5Bg9Hzfq","AgfZt3DUuhi","qwvbzum","vKTtvvu","wwjluxa","sfPREeS","Aw5PDcbrB1m","tfrys2K","Bfvetg8","zePbC0G","vwTzvgu","CxrczK4","rLfWrhe","yxv0B21HDgK","wezOqK0","yxnJCMLWDa","z3L1sw4","s2LuAuW","DwPdEMW","Bwv0Ag9K","AxbRBxO","CM92AwrLigi","r0HAwhm","D1vdAhG","C2v0u3rVCMe","B25tDg9Wsw0","sgDPDMW","Cermwum","DMvY","yNv5zMG","x29Uq2XVC2u","zxjFDhrS","C0f2u3q","tvfvtKW","zufJAW","C3D3BLC","r2fWq00","sgTNBum","q2LIENG","wwfOAwi","zg9Uzq","rwfjtMy","BhfvAfC","x3bPBMDmB3m","zw5JB2rLrNi","quXXywO","tKfusvzfx0u","B2jQzwn0u3q","D24GCMvHC28","B25ozxr3B3i","CMvHzfvjBNq","Evryzfe","CMjqzuC","u0Tvrgu","DNDguu4","AvHmEfq","vgT1sKm","swnfqxm","A3v4r2m","x2rYB3bhBg8","qNvHC1m","s3P3y20","BNrfBMrWB2K","tw9KDwXL","rgvTwum","zNjVBu51Bwi","CgfNzxnOB3C","AMvJDfn0B3i","rNv6uMC","rxbsrMm","B01NrwW","ChbL","vurhCxu","s0vZCeq","B2Ddt2e","y2HXquq","DKTNufm","yMLUyxj5","vfjwwMm","BMDuAw1LCG","sKTpD2u","BwLUzW","CM92AwrLige","EfP4CLi","zw50tgLZDgu","zw5JB2rPBMC","C2v0","rLjptLrjrvi","Bg9NsurozxC","mJmZneHTCe5Yuq","ywzL","CMv0CNLdB3u","zcWG","CgLgu2S","zg9HugG","z2v0t3DUuhi","yxv0BW","C2vUza","uuz0yNK","C2HPzNq","y3vZDg9Tshq","zuzet2W","sefIvgK","B0zluK8","ALfnDge","C2HequC","B25JBg9Zzq","ywrK","FdD8nhWXmhW","A2v5","AvDrrxq","sNDjyLG","vvnowvi","uxjICNe","BNruCMLLC0m","x2LZqNjVD3m","zKffu2i","y3vYCMvUDeu","AeXRBMm","x2DLBMvYyxq","zw5NDgG","D1LZv1e","t0LLEg4","seDIrui","Bezkq3m","reLWEgW","sgTLDgi","q3z1zxa","zxjHDg9Y","zxf1ywXZ","zxjFBxnNAwq","ufftBM8","sezmz0m","wgnqB1G","nJq1yuD2Bwnb","tuHUvwq","uhzQsuW","CMvHC29U","Ahr0Chm6","DgLTzw91Da","EvjMsgK","wKLhCxq","igfYCMf5yNu","DvrdEhK","y2vZC0HHBMq","x2jPBMfYEvq","D3jPDgvvAw4","t1bqtvO","r0jeAMy","ywnRx2LK","o2nOyxjZzxq","DMvUDa","q29Kzq","zMX1C2HfEha","BuzzEgi","wvzbA1u","rgzsrK0","A3Pvufi","x29WDgLVBNm","C3bSAxq","mNWXFdb8m3W","DurZv1m","BfrPBwvVDxq","tfjOu0i","wK5KC2W","vw5PBxbSzw0","s3P1AMC","wLL3Dxe","Dw5KzwzPBMu","y29Kzq","uhvzueK","D2roEeu","A2jtEMu","EuLWEKO","v2LUzg93","Dg9cExrLC0W","Ahr0Ca","uvrcsfi","z0v6y04","BNLPruy","DfPtwwu","uwjZEu0","CMvZzxruCMK","qMHSzvC","DLLYr0O","sxLiAuW","Ag5MCNe","yxjYyxLIDwy","sMjQAg0","EK1bvLe","yuLAEKC","tufyx1jfvfi","DvnLrgC","zv9ZDwnJzxm","ywnOzwqSihC","Bwf4uMv0CMK","DgvmB2Djre4","yxbWBgLJyxq","ihrPBwvVDxq","y0jfAgu","uwHYz1e","x2n1CNnVCKy","CNncC2K","qwPPv1O","Dfvdthy","CMvZzxrdB3u","ChrVCG","D2LSBfjLy28","ywrHCg8","uhnwsu4","sMDtD1u","sMTvBeC","BgLUzq","Axnby2TdBgu","icSG","EwzAq1i","zw50zwqGDhK","vgDztNa","v0HoB0m","zg1jAvq","DxPJCxe","zw5HyMXLqxu","q05IzuO","wuvhwve","vhrzzvC","vw5Oyw5KBgu","rvvfv2i","C3rHCNq","sw5Ur1i","mhW0","qMDnCLi","nxWXFdn8mNW","yNLL","ChDntxi","s3nbEKe","BwvZC2fNzv8","z29PBMCGyxC","DxnLCKLW","Cg9Pt2S","CMvWBgfJzui","AKPzA00","BMnLq2XVC2u","AwvSEK0","v2rQBKi","wwzxDhC","z2v0q3vYC28","A3ndyK0","BezSDxnO","rMjTDMO","AvzNzwK","Dw9qrxa","z29Ltvy","rhjsqKG","tKXNDwC","jMPZy2fSBgi","x2LZtwLUAvq","AKf3v0G","CM5qq0O","x2LUAxrqCM8","D3nZoI8V","rgvKAwnHDgu","rerRsfO","v3nht1y","sLLuzgO","ywDLu2HVDW","BLrlzum","DNH3CxO","swz1ugm","yxrHlcbKyxq","zw50","Cw9Z","q3zivg8","mNWWFdf8m3W","ruXqq1u","y2f0y2G","AxbMtLq","CxLlrgC","A3fgyw8","uxnMDeq","CMvJB25Uzwm","v1vey3G","t3PlAfC","tunhwK0","DgvRu1i","mNWXFdn8mhW","zv90Aw1LB3u","wLPhvu0","C2jTt3q","y3jLyxrLt3a","qvr6DKm","wKDyA0i","BgLUzw5V","DeXJtgq","rxrjAxC","B3vUDa","zxjFCw9Zx2e","u3v6uva","A3HkwfO","yK1TDee","D0n2z08","yNL0zxm","y0nky24","zcWGDw5RBM8","uMPqt1e","ve1krMO","DLPis04","Dhj1y3rVCIa","uxvLDwu","Ehz1AgW","r0Lfte4","CwfysNC","y29UBMvJDa","ysbTDxn0igi","D3LZCxO","uNLvtMO","CYbHBhjLywq","yNvMzMvYzwq","zxrxB3jRq2G","CMvHzhLtDge","v0vxyLC","D3m6lY8","y2jhvfG","mhWZ","y29UDgv4Da","CKDbCw4","t0rAzeS","yMLUyxj5vhK","BgLTAxq","uw54u08","z2vjBMzVu3K","BNHvrwW","zNjVBNrPzxi","DeLK","Aw9Ul2PZB24","Dhr3Awq","CgfYC2u","CLzHBhvLCW","BKPiz1i","z1zfuha","B3jL","y29UBMvJDeu","tMfHA3C","CxnRBg8","B2XAvey","A3b6rw4","sMjduMy","thfZuM4","rNzbAhK","y3ruAw1LB3u","sMHQtuS","AxPwwgi","turlDNm","C2vYDMLJzq","oxW2FdeXFda","ChLgB1C","r0vcEuG","wgvYrwq","Dgv4Dc9Qyxy","z1bHwxu","A2zxDKK","u1zru3u","C3rVCMu","t0TYuLu","Bu1lCfq","rur2C1K","zuTPD1m","qMXWwxu","igzPzwXKoIa","vwnRDue","Dwj2Dw0","wun2vKW","C3zPEuW","D2Tbz1e","x2LZtwLUAvC","rvLAwLy","Aw5Lza","C3rLBMvYCW","A0n4EKO","CNr6A3K","zgvMAw5Luhi","v01hwu8","sgvztKK","mNW0Fdf8nxW","DhDVCMTdAge","q09otKvdveK","B25tDgfYDfi","rNfnANy","Bg9N","vKXWAfm","vMnVt1i","y2HHCKnVzgu","sfbSEgG","tMfTzq","B1bluva","uhjPBwfYEuS","tgDVzvq","DhjPzxmGCMu","vhPkwK4","yMXVy2TLza","BwLUAvbYB2C","suvtx0vsuK8","tKfzuum","zNjVBuHHC2G","x2LUDgvYDMe","Aw5KzxG","AKfztKC","zgHkzwC","D1Dxsw8","x2DLDeLUDgu","q3vZDg9Trxi","wxfRt1q","CMLLC0nVDw4","uwjmzeG","DeLzD0K","tLfxEhy","C2fNzq","sez4t2K","y29Uy2f0","Agnfrg0","tNzXAhm","AvDgBMO","qunfExi","EKPzt0K","mteZoti0odHjqwnjAKG","C2jtuwS","y29TCgXLDgu","Dg1yuhC","z3bpBem","CMvHzhDYAxq","EMHjzw4","B25pCgvU","BfDkz0O","B3jRzxjhBg8","ywjVCNq","s1btrKG","CvjkBhC","yuPQvfC","x2LUAxrhBg8","C0HUALu","Cgf5Bg9Hzeu","Ae1LC3nHz2u","B3jpBMXPBMu","DxbNCMfKzw4","CerHvgi","EwfLB2y","B1Lry1m","qMDVA1y","C01KwKq","BeHHBMrSzxi","shPmDfu","CMfNzvn5BMm","zw1PDa","wwXHvw4","C0Xf","Dg9VigXHCMC","B0zRq08","uvH2vgq","x3bPBMC","v3btrNG","EhbqzfO","wuTkzxe","yMTYuva","tu1Xuw8","z0TtEw4","y2XVC2veqG","BMzyyxe","DgfYz2v0","y2HLy2TdDxi","AwXLx25HBwu","t0z4Ewq","sMTYzg0","Aw5KzxGGB3u","rK1nEfG","q0vYyKy","Eg1LvwW","Ew1KBw4","CeX1DNy","DgPItgu","lcbxzwjtB2m","x25HDMLNyxq","yMrFzgLK","veXZDfC","AhPAz0S","t3jMB3C","t0P2zKO","AMXOquu","AgflrfC","sLnRDNy","rM9Uuvq","n3WWFdn8mG","zNjHBwvuExa","EKvNwfC","Be1kEKm","qvjNALO","rxbJqum","qwHHENO","su1YA3m","vuTzwMq","B3jLtMfTzxm","BxLJvxG","C29YDa","AxnszwfKEq","u0vOBvG","ywDLrxzLBNq","sxbWEvm","x1fVu01HBMe","zxmGCMvHy2G","vwHhBNy","zMX1Dxe","Be1Yzw8","CuDftfC","BMrWB2LUDfq","vgDzCey","EMjzD1K","y0jythq","B25mAw5L","lcbOB3n0BMe","y29UC3rYDwm","vNDYAgC","x2nSzwfYugK","Cg9oDMS","Bw9AA08","y3jLyxrLrwW","q0TyBM8","sgPyrhO","tMHWyvy","ywrKq291BNq","C3bSAwnL","r296y0G","A2v0ignVBNm","yNDyvem","y3vYC29Yx24","BvjbDwe","rfztsM4","Ae1xzuG","Dxz1rue","id4G","BM9Uzv9UB24","tgPSyuu","Dw5RBM93BIa","DLnmD0C","DhjHBNnHy3q","zw5fDMvUDa","BvbRvvK","Dw50","BKvKuwC","BxHMuLm","shvIr2q","Ag5Kzxq","uxzwrMS","Ef9MCM9UDgK","CNzHBfzHBhu","CMvXDwLYzwq","CMfUzg9T","yMfJA3vWigu","CNnVCKzPBgu","shDoCLG","y2fSBa","ywnOzwq","DePozuS","v3n5tw4","y3jLyxrLuMu","y29UBMvJDgK","A1DHvey","yNL0zuXLBMC","x3DHAxq","B2nRzxrtDwm","zwjTzuC","qxDpyu0","BhrPCgXLihq","t1rZs1G","x29UtwvZC2e","CgLUz1rPBwu","AMfxv0S","q0Xpu0LorW","oty3mZq3yuf5whfM","tgLZDgvUzxi","q095B3q","AxnbCNjHEq","qMHUvem","x2LUAxq","D2fZq2XLyw4","vvjwzuy","tfvkwMS","EgXuqwS","ndi3mJzeueHWq3i","x2zVCM1HDeu","Fdv8nNWZ","zLnSrNa","Aw9U","rw5SCg4","zvvYBa","Bgjgrg4","vwXrAei","B25dBg9Zzq","BerfALy","x3vYBa","rw10Bu0","rvjst1i","uKvVz2m","nJG1nJG4ogXpCMfZDa","r3vqEg4","Bg5zqxq","ywr2yw5Jzq","s2rsDgK","D2HRBgC","Dg9oDw1Izxi","BxPxEMm","y3jLyxrLrxi","x2rPC3bHDgm","ze1drhi","AMr2wvO","BfPyBw0","B2nRzxrgywK","q2zLuwG","CfHsBuO","BwvY","x194x21Zz18","vwHPCMO","zgvSzxrL","wNjxte4","C2H5EgS","CMfTzq","A2v5CW","q3P5DwO","u3rYyxrLz3K","D2vI","DgzLqKe","zxD5tM0","AgvHzgvYCW","ALn6rxa","zw5KCg9PBNq","wxL1wxy","C2v0sxrLBq","Cgf5Bg9Hza","ywXSB2nvBNm","y3vYC29YlNm","BNrLCG","z2u6ia","qLjMrem","tuvtu0fhrv8","zgrjrcWGzgu","yM9L","Dg9Y","x2fKzfDZtgK","x2rLyNvN","zxH0ugf5Bg8","DLzxq1u","wgn1wNa","yK1mtgO","rLDt","vurJzw4","AgPMELm","r0HgCwu","yw1Lu3bHy2u","B25UAMW","tg9Nsuq","CgzkvMC","z1rPBwvVDxq","Cw9Xswu","yM9KEq","AxjLza","l3DZl3yY","s2D4uNu","y2n4Ahu","wuznELq","zNLkyxC","rNnzqMi","yKflA0i","FdH8mNWXFdm","y1nrEvm","nhWWFdj8mxW","zcbLCNjVCI4","uND4tMG","sxDMuwe","sKHWuxK","s2v1tee","ver4tg0","v3PHBfG","twLZC2LUzYa","C3rVCcbPBw0","AxLstMu","r09hA0K","zMLN","DhnND0u","DhjPzxm","thnIzuu","ExbL","y3r4","quvfzwe","vNbZD3e","EKTHyNu","Cgu6ia","x3DZsw5ZDge","z2v0qwXS","CMvZDwX0","BLrOue4","z293wwS","CwL3uLe","zMzLCG","ELfHEuO","zgv1veq","AfDvBw0","ywX3yxLZ","DgLLCKPtt04","vwDvBvu","zgLZywjSzue","wK5QwMG","Bezzv24","wuXRC1C","DfjiCgK","ufjgvKG","x2n1CNnVCK0","C0nVDw50zxi","vgPQEwK","BhntB1i","BMv3vMvYC2K","CxHNy3u","Aw5KzxHpzG","q0fuA1K","sNH6zge","wvPAy3G","vgTlA2i","DxjS","uLHmzwS","yLDUz28","x2LZv29YA2u","z1jOtva","y2XLyxjtDg8","zgjZB0y","wvnSuKe","z1L3z0K","zKrmDuG","zNDZxZeUmc4","quXm","x2nYzwf0zvm","vfforg4","x29UugfNzu4","v2vIu29JA2u","y2HnyxHdB3u","qvzet3C","zxfovey","B25szwnLAxy","BwvZC2fNzq","BwLNq00","CgLUz19VBMm","sfjdwuu","wgjqBKi","yvvQrvK","u0XxDu8","sLfjDxG","B3bLBG","DxbKyxrLq3u","y29UBMvJDca","x3DZ","DcbSAw1PDa","ywDLsgLKzq","yw5Nzq","DhbizwfKzxi","z1nwA1e","D09Kzw0","Bwf4tg9ZC0m","DLzsCei","AendtKO","r3Lxuuu","v2rruu8","AxbuvKq","AwXLtMfTzq","ENbkwhe","C2XPy2u","tNLrq1O","txzHtvq","t1bftG","CNDLB0m","DxPVueS","y3vYC29Yx2y","vgLTzw91Da","quPOt3q","tvz6Bey","DKj5she","yvPuqK4","vxbdEMq","C1DtB3O","yMfSu2nVCgu","BMCGzMfPBgu","AuDJsNK","mJG5nZqYohHgyLvwuG","zu1Jt3u","u3HnvNu","ywnRpwzYB24","CMvHzg9UBhK"];return ka=function(){return t},ka()}var jx,Bx,zx,bl,Ca,yl,Ia,Ta,Pa,As,Ux=qx({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={WNlqp:function(n,i){return n instanceof i},oXqAn:function(n,i){return n===i},NGUCy:function(n,i){return n===i},yeyFo:t(384)+t(835),wysqz:t(698),KeuLA:function(n,i){return n(i)},HzLtU:t(1082)+t(530)+"s",EHqvD:function(n,i,o){return n(i,o)},cCEYW:function(n,i){return n!==i},wDpSC:t(391),jcCop:t(1227),VTfAE:function(n,i){return n===i},ONaBE:t(377),dmIiT:function(n,i){return n in i}};jx=(n,i)=>i.some(o=>n instanceof o),bl=new WeakMap,Ca=new WeakMap,yl=new WeakMap,Ia=new WeakMap,Ta=new WeakMap,Pa={get(n,i,o){let a=t;if(e[a(1174)](n,IDBTransaction)){if(e[a(121)](i,a(377)))return Ca[a(131)](n);if(e[a(1279)](i,e[a(1265)]))return n[a(384)+a(835)]||yl[a(131)](n);if(e[a(1279)](i,e[a(650)]))return o["objectSt"+a(835)][1]?void 0:o["objectSt"+a(676)](o[a(384)+a(835)][0])}return e[a(1013)](tn,n[i])},set(n,i,o){return n[i]=o,!0},has(n,i){let o=t;if(e.cCEYW(e.wDpSC,e.jcCop))return n instanceof IDBTransaction&&(e[o(336)](i,e.ONaBE)||i===e[o(650)])?!0:e[o(556)](i,n);this["_clearPi"+o(416)](),this[o(788)](e[o(786)],"success"),this[o(1269)+o(995)+"Id"]=e[o(1533)](_0xc9f372,this[o(794)][o(239)](this),_0x114098)}},As=n=>Ta.get(n)}}),Wx={};iI(Wx,{deleteDB:()=>hI,openDB:()=>fI,unwrap:()=>As,wrap:()=>tn});function $(t,e){t=t-104;let n=ka(),i=n[t];if($.bFbLeG===void 0){var o=function(f){let p="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",x="",g="";for(let v=0,w,E,S=0;E=f.charAt(S++);~E&&(w=v%4?w*64+E:E,v++%4)?x+=String.fromCharCode(255&w>>(-2*v&6)):0)E=p.indexOf(E);for(let v=0,w=x.length;v<w;v++)g+="%"+("00"+x.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(g)};$.EDwoqP=o,$.ZLQcWi={},$.bFbLeG=!0}let a=n[0],d=t+a,u=$.ZLQcWi[d];return u?i=u:(i=$.EDwoqP(i),$.ZLQcWi[d]=i),i}function fI(t,e,{blocked:n,upgrade:i,blocking:o,terminated:a}={}){let d=N,u={qoqIe:function(x,g){return x(g)},BlpYu:d(1212),XCWUE:"versionchange"},f=indexedDB[d(1088)](t,e),p=u.qoqIe(tn,f);return i&&f[d(1560)+d(913)](d(779)+d(1404),x=>{let g=d;i(u[g(996)](tn,f[g(1032)]),x.oldVersion,x.newVersion,u[g(996)](tn,f[g(878)+g(926)]))}),n&&f[d(1560)+"Listener"]("blocked",()=>n()),p.then(x=>{let g=d;a&&x["addEvent"+g(913)](u[g(703)],()=>a()),o&&x[g(1560)+g(913)](u[g(125)],()=>o())}).catch(()=>{}),p}function hI(t,{blocked:e}={}){let n=N,i=indexedDB[n(1491)+"tabase"](t);return e&&i["addEvent"+n(913)](n(735),()=>e()),tn(i)[n(305)](()=>{})}function Hx(t,e){let n=N,i={tFqHf:n(765)+"e",PlchK:n(1127),LpFaV:function(f,p){return f instanceof p},rGAqn:function(f,p){return f in p},FqMjv:function(f,p){return f===p},USpsQ:n(1476)};if(!(i.LpFaV(t,IDBDatabase)&&!i[n(661)](e,t)&&i[n(723)](typeof e,i.USpsQ)))return;if(Aa[n(131)](e))return Aa[n(131)](e);let o=e[n(1149)](/FromIndex$/,""),a=e!==o,d=$x.includes(o);if(!(o in(a?IDBIndex:IDBObjectStore).prototype)||!(d||Kx[n(1270)](o)))return;let u=async function(f,...p){let x=n,g=this[x(878)+x(926)](f,d?i[x(203)]:i.PlchK),v=g[x(698)];return a&&(v=v[x(741)](p[x(436)]())),(await Promise[x(163)]([v[o](...p),d&&g[x(377)]]))[0]};return Aa.set(e,u),u}var Kx,$x,Aa,pI=qx({"node_modules/idb/build/index.js"(){let t=N,e={PuXAN:t(1523),HubGd:t(444),zFlfB:t(956),CnMce:t(131),QhrgQ:t(1344),mRAua:t(1031),jgOLg:t(1317)+"ys",uLrXh:t(194),NwKOv:function(o,a){return o(a)},iGcJy:function(o){return o()}},n=(t(568)+t(566))[t(496)]("|"),i=0;for(;;){switch(n[i++]){case"0":Aa=new Map;continue;case"1":Ux();continue;case"2":$x=[e[t(1230)],e[t(884)],e[t(169)],"clear"];continue;case"3":Kx=[e[t(1530)],e[t(537)],e[t(869)],e.jgOLg,e[t(257)]];continue;case"4":e[t(334)](dI,o=>({...o,get:(a,d,u)=>Hx(a,d)||o.get(a,d,u),has:(a,d)=>!!Hx(a,d)||o[t(1266)](a,d)}));continue;case"5":e[t(1122)](Ux);continue}break}}}),xI={idb:function(t){let e=N;t.exports=Promise.resolve()[e(305)](()=>(pI(),Wx))[e(305)](function(n){return n})}},Gx={};function en(t){let e=N,n={OYpYd:e(1417)+"0",VNiEg:function(u,f){return u!==f}},i=n.OYpYd[e(496)]("|"),o=0;for(;;){switch(i[o++]){case"0":return d[e(1309)];case"1":xI[t](d,d[e(1309)],en);continue;case"2":if(n.VNiEg(void 0,a))return a[e(1309)];continue;case"3":var a=Gx[t];continue;case"4":var d=Gx[t]={exports:{}};continue}break}}en.d=(t,e)=>{let n=$;for(var i in e)en.o(e,i)&&!en.o(t,i)&&Object[n(716)+n(1237)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;en.o=(e,n)=>Object.prototype[t(338)+t(1237)].call(e,n)})(),(()=>{let t=N,e={xlTAk:"undefined",GIELN:t(208)+"le"};en.r=n=>{let i=t;e[i(921)]!=typeof Symbol&&Symbol["toString"+i(1419)]&&Object[i(716)+i(1237)](n,Symbol[i(1250)+"Tag"],{value:i(400)}),Object[i(716)+i(1237)](n,e[i(646)],{value:!0})}})();var Fe={};(()=>{let t=N,e={REogc:function(c,r){return c(r)},OJvfJ:function(c,r){return c+r},lKLWF:function(c,r){return c+r},MVzlF:function(c,r){return c*r},NYzQm:function(c,r,s){return c(r,s)},kxyRT:function(c,r){return c!==r},aeHdn:t(1223),ADKvU:function(c,r){return c+r},ACEyr:function(c,r){return c(r)},lMreo:function(c,r){return c(r)},wiVsF:t(1494),CATkY:t(186),lUDLo:function(c,r,s){return c(r,s)},kCtIK:function(c,r,s){return c(r,s)},mrEhG:t(812),bmGZu:function(c,r){return c(r)},ApnXp:"5|3|1|0|2|4",dTPEu:t(977)+"ERROR",PzClI:t(528)+t(737)+"R",BFhdM:t(1527)+"OR",PaYAp:"CONNECTING_ERROR",YCvVL:t(383)+t(252),PRFVH:t(1212),cSQyS:t(1088),TlHGB:t(1080),tMLgA:t(1173),mcylK:function(c,r){return c!==r},ODZdK:t(500),OQtlC:function(c,r){return c>r},hIkPQ:function(c,r){return c<r},ebmeG:function(c,r){return c<r},MQUNL:function(c,r){return c-r},yMvRb:function(c,r){return c===r},rPSoQ:t(1038),eqfrJ:t(1414),ZYwuq:function(c,r){return c!==r},WsGOV:function(c,r){return c-r},TtYeW:function(c,r){return c-r},lMJzC:t(1355),mNLwS:t(871),iZYWI:function(c,r){return c===r},TgYpF:t(947),VRlgi:function(c,r){return c-r},JHpQy:function(c,r){return c!==r},kwzty:function(c,r){return c|r},NQWxv:function(c,r){return c<<r},zEgXW:function(c,r){return c&r},BhleW:function(c,r){return c<<r},ruyrv:function(c,r){return c&r},DUJuJ:t(588),zpJXq:function(c,r){return c>>>r},aJjTW:function(c,r){return c(r)},DrRBH:function(c,r){return c(r)},JjZZp:t(1016)+t(889)+t(704)+t(446),HXoUj:function(c){return c()},GPNYK:function(c,r){return c(r)},OFxyd:t(1082)+t(530)+"s",cKCjV:t(735),CVYCG:function(c,r,s){return c(r,s)},jbNiQ:function(c,r,s){return c(r,s)},MvaMT:function(c,r){return c!==r},nJHgR:function(c,r){return c!==r},eMnqp:function(c,r,s){return c(r,s)},BhnTC:function(c,r,s){return c(r,s)},ogCOa:function(c,r){return c!==r},LPAmd:function(c,r,s){return c(r,s)},ujCzl:function(c){return c()},EvdCi:function(c,r,s){return c(r,s)},qhcso:function(c,r){return c!==r},jGYMU:function(c,r){return c===r},IWosm:"WMiBh",XcMfB:function(c,r,s){return c(r,s)},kqFao:function(c,r){return c!==r},LTXKi:"clRDW",lFYWn:function(c,r,s){return c(r,s)},URVeF:function(c,r){return c!==r},CNbeJ:function(c,r,s){return c(r,s)},jHnGa:function(c,r){return c!==r},PsVIN:function(c,r,s){return c(r,s)},Vwrhg:t(450),SZqDn:function(c,r,s){return c(r,s)},MkDvc:function(c,r){return c(r)},GuPxn:function(c,r){return c>>>r},kIHgO:function(c,r){return c(r)},jQMta:function(c,r){return c(r)},CnPct:function(c,r){return c(r)},ARgjZ:function(c,r){return c(r)},xmeUl:function(c,r){return c&r},AgJbc:function(c,r){return c===r},nSenF:t(1016)+t(889)+t(704)+t(993),IyWHt:t(1016)+t(889)+t(704)+t(356),TkuJC:function(c,r){return c instanceof r},uvuEA:t(1245)+"in;chars"+t(1241),AEEea:"applicat"+t(670)+t(487)+t(1569),SUTRf:"string",eKiwS:t(414),ZfgMP:function(c,r,s,l){return c(r,s,l)},GOGkI:function(c,r){return c!==r},KPSFH:t(1524),KiTiL:function(c,r,s){return c(r,s)},iyRNe:function(c,r){return c+r},NdWnN:t(502)+t(553)+t(1029),bwXTC:function(c,r){return c===r},FtOeu:t(1052),MyuxU:t(1510),ueqGE:function(c,r){return c>>r},lZXmm:function(c,r){return c>=r},VOnBg:function(c,r){return c===r},ZrmqQ:t(1292),ynILY:t(809),AwOaM:function(c,r,s,l,h){return c(r,s,l,h)},GHZXs:function(c,r){return c!==r},GgfHg:t(1457),shyxk:function(c,r){return c===r},HECUL:t(1340)+"t limit",Orfow:function(c,r){return c>=r},dbsoF:function(c,r){return c!==r},mMKpT:t(1581),iGMWG:function(c,r){return c>r},kTvLx:function(c,r){return c>r},TThaV:t(1567),hcEDm:"Read pas"+t(1092),WNdbN:function(c,r,s){return c(r,s)},RwxNh:function(c,r){return c<r},WzalX:function(c,r){return c+r},tLiOx:function(c,r){return c+r},TEMVY:function(c,r){return c===r},DfRFM:function(c,r){return c+r},gowYk:function(c,r){return c+r},WEWbW:function(c,r){return c&r},wCvgO:function(c,r){return c<<r},wcnLD:function(c,r){return c&r},yCrLG:function(c,r){return c!==r},AxHPX:"Ouexx",izVXb:function(c,r){return c(r)},lcUaT:function(c,r){return c==r},OKrRU:function(c,r){return c+r},zQayJ:function(c,r){return c+r},ApNZF:function(c,r){return c+r},wkAgQ:function(c,r){return c+r},NZszm:function(c,r){return c!==r},tUCLv:function(c,r){return c<<r},cVeLB:function(c,r){return c|r},JEsHf:function(c,r){return c<<r},buyfh:function(c,r){return c&r},htkIi:function(c,r){return c<r},qoGZf:function(c,r){return c>=r},RyUNj:function(c,r){return c(r)},OxOty:function(c,r){return c==r},QmDGe:function(c,r){return c&r},vBQpD:function(c,r){return c+r},HNzkp:function(c,r){return c!==r},zKabu:t(507),eWZWx:function(c,r){return c+r},uyqIU:function(c,r){return c+r},VKFuq:function(c,r){return c<<r},JAyBM:function(c,r){return c|r},sbmOt:function(c,r){return c|r},JmmAI:function(c,r){return c<<r},mFYxb:function(c,r){return c>>r},MvwQE:function(c,r){return c!==r},gVEPp:t(317),NVHkC:function(c,r){return c<r},aIZzG:function(c,r){return c<=r},jJYkM:function(c,r){return c<r},Wwomk:function(c,r){return c-r},WeODF:function(c,r){return c===r},BRIxi:t(883),vYrGJ:function(c,r){return c>=r},bWngo:function(c,r){return c<<r},AOwHC:function(c,r){return c<r},LkCkB:function(c,r){return c===r},YLksW:t(143),vfeaJ:function(c,r){return c|r},CgQvX:function(c,r){return c|r},rweoC:function(c,r){return c&r},wleMK:function(c,r){return c|r},LqnYr:function(c,r){return c&r},JKOwe:function(c,r){return c>>r},uDsWS:function(c,r){return c|r},DVSJn:t(1400),nyiEF:function(c,r,s){return c(r,s)},SnrDj:function(c,r){return c<r},SqBMW:t(1437),kfWvI:t(388),zQspi:function(c,r){return c(r)},uZZbA:function(c,r){return c&r},lXsLv:function(c,r,s){return c(r,s)},EpcAC:function(c,r){return c|r},wJjOG:function(c,r){return c(r)},nnsRk:function(c,r){return c&r},znztx:function(c,r){return c&r},Enlpn:function(c,r){return c&r},VcoOR:function(c,r){return c<<r},IRIxD:function(c,r){return c&r},qYMIj:function(c,r){return c(r)},jAwWH:function(c,r){return c&r},cBXLt:t(969),zhIen:function(c,r){return c(r)},VuSmy:function(c,r){return c&r},Okhce:function(c,r){return c&r},xvuhl:function(c,r){return c(r)},rtzky:function(c,r){return c<<r},yzKdu:function(c,r){return c(r)},pcbal:function(c,r){return c&r},Awvds:function(c,r){return c&r},GzVKr:function(c,r){return c(r)},EtIiw:function(c,r){return c<<r},VNTBR:function(c,r){return c&r},BEnni:function(c,r){return c>>>r},VCgmY:function(c,r){return c|r},tkScJ:function(c,r){return c>>>r},NsmxJ:function(c,r){return c>>>r},oFKRO:function(c,r){return c<r},XDNhW:function(c,r){return c<r},PsFBn:function(c,r){return c>>>r},zbYwY:function(c,r){return c&r},xrcXd:function(c,r){return c&r},JYTdj:function(c,r){return c!==r},erybC:function(c,r){return c|r},YcxTS:function(c,r){return c|r},oBOdK:function(c,r){return c|r},glvhN:function(c,r){return c>>>r},QbLdH:function(c,r){return c&r},DemYC:function(c,r){return c>>>r},FbYKT:function(c,r){return c&r},UlURm:function(c,r){return c>>>r},pSbHq:function(c,r){return c|r},ALqaj:function(c,r){return c&r},GvUnZ:function(c,r){return c>>>r},RSIkg:function(c,r){return c&r},XVJpx:function(c,r){return c|r},OzKhW:function(c,r){return c|r},hzluP:function(c,r){return c|r},UyauK:function(c,r){return c|r},iXLxT:function(c,r){return c|r},vYrbG:function(c,r){return c<r},rGjaN:function(c,r,s){return c(r,s)},lFJCs:function(c,r){return c>>r},MKdhk:t(347),cltBV:function(c,r){return c===r},QbsyM:function(c,r){return c|r},ZsOyV:function(c,r){return c|r},VDYwv:function(c,r){return c<<r},WpSFx:function(c,r){return c<<r},befmO:function(c,r){return c|r},TNbzP:function(c,r){return c<<r},HRCYE:t(616)+"t",sAvSt:t(564),zJMlW:t(638),bMLLj:function(c,r){return c|r},vMtry:function(c,r){return c|r},yhkGO:function(c,r){return c<<r},mrdtZ:function(c,r){return c<<r},dvOck:function(c,r){return c|r},SLWuO:function(c,r){return c<<r},swwnW:function(c,r){return c<<r},qyKDg:function(c,r){return c>>>r},HwNrX:function(c,r){return c<<r},vcSzR:function(c,r){return c===r},Bviyq:t(1448),qxgcu:function(c,r){return c&r},rsBsi:function(c,r){return c>>>r},xxsKi:function(c,r){return c>>>r},Kzujg:function(c,r){return c>>>r},HjXDz:function(c,r){return c&r},vQgEK:function(c,r){return c>>>r},WOUot:function(c,r){return c<=r},prtTQ:function(c,r){return c>=r},YlaUn:function(c,r){return c!==r},tfYNW:t(580),fbxEk:function(c,r){return c>=r},PxWnS:function(c,r){return c|r},yGnlV:function(c,r){return c%r},ewyNm:function(c,r){return c/r},QvVFk:function(c,r){return c+r},VdCVq:function(c,r){return c>>>r},OsODQ:function(c,r){return c>>>r},MHnUd:function(c,r){return c+r},gyuIn:function(c,r){return c*r},eBFKb:function(c,r){return c>>>r},RXLek:function(c,r){return c&r},QKxLA:function(c,r){return c&r},CNWsl:function(c,r){return c>>>r},VrVIW:function(c,r){return c>>>r},evgXp:function(c,r){return c+r},TDxLm:function(c,r){return c<<r},rHdcG:function(c,r){return c<<r},DstnX:function(c,r){return c>>>r},iFDuL:function(c,r){return c===r},Jkrdm:function(c,r){return c===r},EaINf:function(c,r){return c===r},TBncW:function(c,r){return c+r},cZnxK:function(c,r){return c&r},jlhAE:function(c,r){return c&r},fThzF:function(c,r){return c>>>r},gSVkQ:function(c,r){return c&r},cPXmm:function(c,r){return c&r},OMGyh:function(c,r){return c>>>r},kNsJL:function(c,r){return c>>>r},oFkCO:function(c,r){return c>>>r},kWaTF:function(c,r){return c&r},xpPdZ:function(c,r){return c>>>r},mnhxB:function(c,r){return c&r},LjlaE:"4|2|0|5|"+t(1275),TgYNp:function(c,r){return c==r},ndnry:function(c,r){return c(r)},YnOMc:function(c,r,s,l){return c(r,s,l)},zsDuG:t(1551),ybPKm:"CdgXc",oNLOb:function(c,r){return c===r},yBHww:function(c,r){return c>r},CKXno:"complete",Kifar:"abort",PduwU:t(1337),uNfes:function(c,r){return c===r},BcqJT:function(c,r){return c instanceof r},jSzEp:function(c,r){return c+r},USNYR:t(562)+t(1009),hnfrq:function(c,r){return c+r},BScKG:"qjcWg",fiCQy:"3|0|4|1|2",qGELW:function(c,r){return c+r},BJlDM:function(c,r,s){return c(r,s)},shDAG:function(c,r){return c!==r},pDLYC:"lPCXI",QTBHR:function(c,r,s){return c(r,s)},AqRfx:function(c,r,s){return c(r,s)},vfcgV:function(c){return c()},MwWhk:function(c){return c()},dtDhE:t(1027),tZSYe:function(c,r,s){return c(r,s)},hqWBF:t(1017)+t(1148)+t(1146)+"ct",poNvk:function(c,r){return c!==r},SiPCR:t(743),cfPQh:t(1495),Spyqd:function(c,r){return c||r},RpkKy:function(c,r){return c!=r},NyQCZ:t(505)+"d",SxMVu:function(c,r){return c+r},COxpH:function(c,r){return c===r},QyIHC:t(833),JsETT:t(1133)+"4",pNeeQ:function(c,r){return c<=r},NAtDT:t(1201)+"alled mu"+t(906)+t(1195)+"process",YfWtw:function(c,r){return c+r},uzcqq:function(c,r){return c-r},onnjl:function(c,r){return c>=r},Jbjhm:function(c,r){return c<r},IcEAs:function(c,r){return c&r},YOPZg:function(c,r){return c<r},HPlxh:function(c,r){return c&r},fluuq:function(c,r){return c>=r},GwLEY:function(c,r){return c-r},AjiWZ:function(c,r){return c<<r},kuxGc:function(c,r){return c&r},ZfdUP:function(c,r){return c|r},uikQU:function(c,r){return c|r},wInTK:function(c,r){return c&r},LgoeT:function(c,r){return c!==r},dOYVf:function(c,r){return c(r)},QsftD:t(1059),gDDbL:"FcoCa",biwsR:t(783),gpOlC:function(c,r){return c<r},cbGTX:function(c,r){return c!==r},tRHpi:t(439),DpgTX:function(c,r){return c>>r},WKDrd:function(c,r){return c===r},yxuAn:function(c,r){return c&r},vVRpB:function(c,r){return c===r},bUhEx:t(719)+t(659),ipfNT:function(c,r){return c&r},xcMMw:function(c,r){return c|r},vnDPg:function(c,r){return c+r},zMAVQ:function(c,r){return c+r},NhpaV:function(c,r){return c|r},vxwqz:t(1258),ZqaOV:function(c,r){return c>>r},pwMMr:function(c,r){return c&r},WMGYO:function(c,r){return c==r},VLphS:function(c){return c()},nTKeC:function(c,r){return c===r},Tjjyi:t(1354),diNPS:function(c,r){return c!=r},AVDOw:function(c,r){return c instanceof r},PKrmz:function(c,r){return c instanceof r},ehIDn:"applicat"+t(670),qktNX:function(c,r){return c==r},hXIyB:t(408),TQNDn:function(c,r){return c<r},AREbF:function(c,r){return c<=r},JNgTn:function(c,r){return c<r},lDEjV:function(c,r){return c&r},pXRmJ:function(c,r){return c<r},gfUBY:function(c,r){return c&r},qaXJw:function(c,r){return c&r},EmtmM:function(c,r){return c|r},QnxSO:function(c,r){return c&r},tyQCu:function(c,r){return c<<r},vcjBc:function(c,r){return c<<r},vMCKC:function(c,r){return c&r},TFirE:function(c,r){return c+r},GHEbI:function(c,r){return c+r},SxpcR:t(876)+t(474),PVjrR:t(513),vByHq:t(309),KgxRu:t(302)+t(791)+"e",NiDvv:function(c,r,s,l){return c(r,s,l)},ZXDZJ:function(c,r){return c!==r},YqkOT:t(375),Wutxw:t(555),ODdUc:"YeQnk",Zsbhe:t(1157),nxUEl:t(515),QgCFu:function(c,r){return c!==r},nEdQg:"VEaGT",NLgug:function(c,r){return c!=r},oMgEl:t(1322),whklg:function(c,r){return c===r},pLuvv:t(939),EDvsY:function(c,r){return c<r},gWJLC:function(c,r){return c&r},XZNro:function(c,r){return c&r},oKFnk:t(1304),fSlFp:function(c,r){return c===r},QFtby:t(714),Yahib:t(282),soKAG:t(160),YEGYQ:t(1064),uTCxy:function(c,r){return c||r},QBSud:function(c,r,s){return c(r,s)},haKDW:function(c,r){return c===r},yRfHi:t(1320),cHRtA:function(c,r){return c!=r},CbKvB:t(343)+t(1181)+"d",WbzMy:function(c,r){return c!==r},Kzwcm:t(836),UgUmU:t(1159),VsImh:t(572)+"id",zJYOI:function(c,r){return c!==r},ccxhu:"sQuYp",mFzir:t(818),CfeQh:"x_frontier_qos",irZOL:t(887)+t(632)+"ck",LPEIj:function(c,r,s,l){return c(r,s,l)},KEspD:"x_fronti"+t(1324)+"k",GozcH:"x_frontier_ack_m"+t(1415),XtJdX:t(1489),aUjEY:function(c,r){return c&&r},adapo:t(1216),RkRGB:t(486),KFkBZ:function(c,r){return c||r},UGNyw:t(319),WjcPI:t(1465),AtXGC:t(793),YbKQp:function(c,r){return c instanceof r},fAESb:t(874)+"e",sviyL:function(c,r,s,l){return c(r,s,l)},bRmiA:function(c,r){return c&r},VEpry:function(c,r){return c|r},AeAeC:function(c,r){return c||r},ZIDBX:function(c,r){return c(r)},uMOQp:function(c,r){return c+r},BuasS:t(808)+t(165)+t(975),VKSUU:function(c,r){return c||r},UPTSI:function(c,r){return c-r},qDCCB:function(c,r){return c===r},InnGR:t(738),HnpMz:function(c,r,s,l){return c(r,s,l)},hRMQa:function(c,r){return c+r},ZDQTI:t(529),ONHpF:function(c,r){return c<r},FROLy:function(c,r,s){return c(r,s)},IRtqk:function(c,r){return c>>>r},olZTF:function(c,r){return c+r},ybLuX:function(c,r){return c|r},nNcDy:function(c,r){return c<<r},tIYwI:function(c,r){return c<<r},sWSoz:function(c,r){return c+r},nEHlF:function(c,r){return c+r},iRCRm:function(c,r){return c|r},Etrse:function(c,r){return c<<r},RjPOQ:function(c,r){return c+r},EUEWb:function(c,r){return c<<r},Wdpwh:function(c,r){return c+r},aTpCH:function(c,r){return c&r},hjfzS:function(c,r){return c>>>r},SKUDe:function(c,r){return c+r},aFWuk:function(c,r){return c>>>r},PvjIL:function(c,r){return c+r},UDcen:function(c,r){return c>>>r},tLcLd:function(c,r){return c+r},gPaYu:function(c,r){return c&r},FonQT:function(c,r){return c&r},LnlFn:function(c,r){return c|r},mgiTA:function(c,r){return c|r},XdCQu:function(c,r){return c|r},sQGUH:function(c,r){return c&r},MEPiC:function(c,r){return c<<r},HGbEB:function(c,r){return c<r},wUBNC:function(c,r){return c+r},yIpzJ:"header",hndet:function(c,r,s,l){return c(r,s,l)},RwOXp:t(689),WgsYB:"curvalue",lDvsa:function(c,r){return c(r)},BRfDC:t(285),tjbLe:function(c,r,s){return c(r,s)},Czyuj:function(c,r){return c+r},rnPCJ:t(173),HLUaV:"cursor_f"+t(805),FQpDq:"FILE_NOT_EXIST",ipkmz:function(c,r){return c+r},lLRXh:t(834),kpzEn:"WuhKu",VbxRa:t(868)+t(274),cajXG:t(1071),bkrQP:t(184),yfdwy:t(177),rPRmK:function(c,r,s,l){return c(r,s,l)},PXQIU:"setdb",LcZLz:t(1464)+"r",ZrWLN:"timeout",npCkG:function(c,r){return c!==r},pJZsM:t(1399),xtjpc:t(1447),YZZcx:t(217),JQIux:function(c,r,s){return c(r,s)},FsYBb:t(573)+t(1285)+t(182)+t(322),YVAkU:function(c,r){return c*r},JbCRf:function(c,r){return c!==r},HFKQg:t(1078),ZFdYz:t(506),JkUlG:t(887)+t(467),kbSze:function(c,r){return c(r)},qrnyE:t(887)+t(368),YHPRM:"x-msg-qos",xZxrR:function(c,r){return c(r)},EpRFc:function(c,r,s){return c(r,s)},rUMHJ:t(1487)+t(1363)+"ue",YVIaz:function(c,r){return c+r},YKJeq:function(c){return c()},chdTh:t(1002),UpCzd:t(485),qsuBN:function(c){return c()},cTqXT:function(c,r){return c===r},ILDaz:function(c,r){return c===r},HTwwx:function(c){return c()},YSlRA:function(c,r){return c!==r},XcPoX:function(c,r){return c===r},OTsKX:t(763),hDDwx:function(c,r){return c(r)},TRVZc:function(c,r){return c<<r},xBJbg:function(c){return c()},WmvJT:t(1512),JJeeI:function(c,r){return c===r},xIHYG:function(c,r,s){return c(r,s)},doaPh:function(c){return c()},WGZzp:function(c,r){return c===r},pfJVg:t(1040),pfHPI:function(c,r){return c===r},OmIfd:t(433),ksCbM:"success",WmZjx:function(c,r){return c===r},TGzzF:function(c,r,s){return c(r,s)},ppozt:"bAKkB",WdQQO:function(c,r,s){return c(r,s)},yXuwJ:function(c,r,s){return c(r,s)},FvAhy:function(c,r,s){return c(r,s)},jZJNV:function(c,r){return c>r},pcybQ:function(c,r){return c!==r},bEXRP:"bye",QNAvD:function(c,r,s){return c(r,s)},UDGqu:"aehJr",xLbSB:t(571),cBEhe:t(524)+t(1307),jySpJ:t(1413)+t(1194)+t(190),Naakw:t(1413)+t(1441)+t(1210)+t(815)+t(866)+t(643)+t(139)+t(712),oBWLk:function(c,r,s){return c(r,s)},zgyEu:t(1315),nfXaq:"pagehide",HFLgC:t(403),ImURa:t(1259),Fbmvj:t(258),fkIZy:"wUChx",gLhdw:t(596),SuzQP:t(657),LsbeE:t(219)+"d",PQSno:function(c,r){return c||r},HkgmC:t(1413)+t(358)+t(978)+t(1519)+t(229),pyFoW:function(c,r){return c==r},fuSVM:function(c,r,s){return c(r,s)},wYsWQ:function(c,r,s){return c(r,s)},iGQQn:function(c,r,s){return c(r,s)},OlVur:function(c,r,s){return c(r,s)},zDRPm:function(c,r,s,l){return c(r,s,l)},VOOsa:"JCqgq",bMmtA:function(c,r){return c(r)},IyHiL:function(c,r){return c*r},ItAuy:function(c,r){return c>r},NRYRa:function(c,r,s){return c(r,s)},iWFnj:t(573)+"ay, try reconnec"+t(313)+t(365),iVgei:"HwCYE",UckuA:t(124)+t(1198)+t(1172)+"g",KdRti:function(c,r){return c(r)},IfuPc:function(c,r){return c===r},MDKvs:t(206),LFeKv:t(621)+"4",lisEV:function(c,r){return c===r},vVWCU:t(610),sbSQk:function(c,r,s){return c(r,s)},LOfol:function(c,r){return c===r},sMdZD:function(c,r,s,l){return c(r,s,l)},MVTzZ:t(1114),wOdem:function(c,r){return c===r},WUDcx:t(929),ykJuQ:t(1008)+t(1238)+t(924),aZTBN:function(c,r,s,l){return c(r,s,l)},AtRBM:t(107),rKvkg:function(c,r,s,l){return c(r,s,l)},SEhmX:t(168)+t(107),qqXGD:t(1537),LqsRn:t(273)+t(826),rbPeG:t(1366)+"s instan"+t(1299)+t(335)+"ed",BgMrR:"please p"+t(419)+t(318)+t(605)+t(649)+"e a stri"+t(1350)+t(479)+t(1036),Ahazz:function(c,r){return c==r},jAYNG:"number",ycbNy:function(c,r){return c(r)},piFSk:t(1413)+t(419)+t(128)+"ervice",XerEd:t(1287),FQxFY:function(c,r){return c||r},EoDxC:function(c,r){return c==r},ICdFL:function(c,r){return c(r)},ZGXkB:"ping_onc"+t(622)+"t",YeEUI:function(c,r){return c(r)},oYQcS:function(c,r){return c!==r},qRJlw:"YfBHk",NlAaC:t(511),oPKQP:function(c,r){return c!=r},eEnsY:function(c,r){return c!=r},ATzvC:t(1405),VBDvS:function(c,r){return c===r},KEPux:t(597)+"dWorkerG"+t(246)+"pe",LWIss:function(c,r){return c!=r},aGJdt:function(c,r){return c!=r},NOfKl:function(c,r){return c!=r},XPOQJ:function(c,r){return c===r},hzZgK:t(1425)+"rkerGlobalScope",xlYdN:"ServiceW"+t(769)+t(1120),IppyS:function(c,r){return c!=r},tfeBA:function(c,r,s){return c(r,s)}};en.r(Fe),en.d(Fe,{FWS:()=>Om,CustomErrorEvent:()=>Ul,createCloseEvent:()=>Rt,ReconnectEvent:()=>zl,createErrorEvent:()=>Et,decodedFrame:()=>Ut,createOpenEvent:()=>Kl,CustomCloseEvent:()=>Hl,createReconnectEvent:()=>$a,FrontierMessageEvent:()=>ql,encodeFrame:()=>nn,createMessageEvent:()=>Wl,OpenEvent:()=>jl,ErrorCode:()=>vn,Event:()=>vr,MessageEvent:()=>Gl});let n="";function i(c=""){let r=t,s="02",l=""+Date[r(1156)](),h=n||(n=e[r(936)](f,c)),_=Math[r(890)]()[r(1250)](16)[r(1106)](-6);return e[r(821)](e.lKLWF(e[r(279)](s,l),h),_)}function o(){let c=t;return e[c(279)](e[c(1115)](1e4,Date[c(1156)]()),Math.floor(1e4*Math.random()))}function a(c){let r=t;return(Array(8).join("0")+e[r(1548)](parseInt,c,10)[r(1250)](2))[r(1106)](-8)}function d(c){let r=t;return e.kxyRT(r(1179),e[r(1311)])?e.ADKvU(e.ACEyr(Array,4)[r(1316)]("0"),e[r(1548)](parseInt,c,2)[r(1250)](16))[r(1106)](-4):this[r(1091)]?this[r(1091)][r(655)+"te"]:this[r(495)][r(350)+r(1568)]?this[r(721)+"NG"]:this[r(1229)]}function u(c){let r=t,s=c[r(496)](/\./).map(_=>a(_)),l=[];return l[0]=e[r(846)](d,s[0]+s[1]),l[1]=d(e[r(1500)](s[2],s[3])),[e[r(112)],e[r(112)],e[r(112)],r(1494),e[r(112)],e[r(1056)],l[0],l[1]][r(1316)]("")}function f(c){let r=t,s={DDZHr:function(l,h,_){return e.lUDLo(l,h,_)},OIRxt:function(l,h,_){return e.kCtIK(l,h,_)}};if(e[r(1145)]==="FQPdu")s[r(1312)](_0x1a624d,_0x30e6fd,90),s[r(1242)](_0x4c851b,_0x2c030e,_0xa78e82);else{let l=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(c),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]))/.test(c);return l?e[r(171)](u,c):h?e[r(171)](p,c):r(1290)+r(1290)+r(1290)+r(1290)}}function p(c){let r=t,s={NQkJI:e[r(1048)],MCGZM:e.cSQyS,VpfcO:e[r(1372)],TJCfW:e[r(1390)]};if(e[r(1298)](e[r(662)],e[r(662)]))_0x2fe4d4[r(1578)]()[r(305)](()=>{this["_addWsLi"+r(713)]()});else{let l="",h=[],_=0,b=0,I=!0,m="0000";if(e[r(259)](c.indexOf("::"),-1)){let O=c[r(496)]("::");for(let F=0;e.hIkPQ(F,O[r(1393)]);F++){let V=O[F];if(V[r(1055)](":")>0){let X=V[r(496)](":");I&&(_=X.length),b+=X[r(1393)];for(let J=0;e[r(904)](J,X[r(1393)]);J++)if(e[r(201)](4,X[J][r(1393)])){let Me=m[r(1395)+"g"](0,e[r(370)](4,X[J][r(1393)])),ge=Me[r(754)](X[J]);h[r(1544)](ge)}else h[r(1544)](X[J]);I=!1}else if(e[r(228)](e.rPSoQ,e[r(1377)])){let X=(r(497)+"4")[r(496)]("|"),J=0;for(;;){switch(X[J++]){case"0":this[r(1091)][r(1560)+r(913)](s.NQkJI,this._onClose);continue;case"1":this[r(1091)]["addEvent"+r(913)](s[r(619)],this[r(233)]);continue;case"2":if(!this[r(1091)])return;continue;case"3":this[r(1091)][r(1560)+r(913)](s.VpfcO,this[r(908)+"ge"]);continue;case"4":this[r(1091)][r(1560)+r(913)](s[r(242)],this._onError);continue}break}}else{if(e[r(504)](4,V[r(1393)])){let X=m.substring(0,e.WsGOV(4,V[r(1393)])),J=X[r(754)](V);h[r(1544)](J)}else h[r(1544)](V);I&&(_+=1),b+=1,I=!1}}let L="";for(let F=0;e[r(904)](F,e[r(561)](8,b));F++)L=L[r(754)](m);for(let F=0;F<h.length;F++)if(F===_)if(e[r(829)]!==e[r(245)])l=l.concat(L),l=l.concat(h[F]);else{let V=e[r(1204)].split("|"),X=0;for(;;){switch(V[X++]){case"0":_0x393374[_0x51cd61["MESSAGE_"+r(935)]=5004]=e[r(192)];continue;case"1":_0x3d58ad[_0x2fb0db[e[r(1153)]]=5003]=e[r(1153)];continue;case"2":_0x53676b[_0x53318b[e.BFhdM]=5005]=e[r(150)];continue;case"3":_0x549afc[_0x5b0cfa[e[r(286)]]=5002]=e[r(286)];continue;case"4":return _0x45a298;case"5":_0xa5bc18[_0x52fccc[e.YCvVL]=5001]=e[r(707)];continue}break}}else l=l.concat(h[F]);return l}if(e[r(1466)](e[r(849)],r(947))){let O=c[r(496)](":");for(let L=0;e[r(320)](L,O[r(1393)]);L++){let F=O[L];if(O[L][r(1393)]!==4){let V=m.substring(0,e[r(1480)](4,O[L].length)),X=V[r(754)](F);l=l[r(754)](X)}else l=l[r(754)](F)}return l}else this[r(968)+"s"]=_0x131451,this.maxRetries=_0x7acd36,this["currentI"+r(1479)]=0,this[r(454)+r(848)+r(748)+"t"]=0}}function x(c,r){let s=t,l=c[s(446)];e[s(1012)](void 0,l)&&(e[s(1548)](ce,r,10),e.kCtIK(je,r,l));let h=c.value;h!==void 0&&(e.NYzQm(ce,r,18),e[s(1548)](je,r,h))}function g(c){let r=t,s={hCCNJ:function(l,h){return e.VRlgi(l,h)},IuiEz:function(l,h){return e[$(180)](l,h)},PnBcZ:function(l,h){return e.NQWxv(l,h)},MkVTx:function(l,h){return e[$(828)](l,h)},BDkCy:function(l,h){return e.BhleW(l,h)},Hketb:function(l,h){return e[$(828)](l,h)},LOHKr:function(l,h){return e[$(1202)](l,h)},XFhBM:function(l,h){return l>>h},IbWgl:function(l,h){return l&h}};if(e[r(228)](e[r(1376)],e[r(1376)])){let l={};e:for(;!K(c);){let h=e.bmGZu(te,c);switch(e[r(1105)](h,3)){case 0:break e;case 1:l[r(446)]=e[r(345)](Se,c,e.aJjTW(te,c));break;case 2:l[r(156)]=e[r(345)](Se,c,e.DrRBH(te,c));break;default:e[r(327)](C,c,7&h)}}if(e.iZYWI(void 0,l.key))throw new Error(e[r(1505)]);if(l[r(156)]===void 0)throw new Error(r(1016)+r(889)+" field: "+r(156));return l}else{let l=s[r(1100)](s[r(276)](s.PnBcZ(7&_0x2c2d52,18)|s[r(299)](s.MkVTx(63,_0x2d4219[_0x174a3f++]),12)|s[r(1339)](s[r(463)](63,_0x340eb7[_0x3f1d87++]),6),s[r(1185)](63,_0x3eb12d[_0x506ffc++])),65536);_0x156481+=_0x30ba18[r(1563)+r(489)](55296+s[r(351)](l,10)),_0xd0e212+=_0x195544[r(1563)+r(489)](56320+s[r(221)](1023,l))}}function v(c){let r=t,s=e.HXoUj(R);return w(c,s),e[r(1432)](M,s)}function w(c,r){let s=t,l={RcWJO:e[s(1390)],eMcOu:function(ge,nt,rn){return e.lUDLo(ge,nt,rn)},vSLwG:e.cKCjV,gPBye:function(ge,nt){return ge(nt)}},h=c[s(215)];e[s(1298)](void 0,h)&&(e[s(1364)](ce,r,8),e[s(1178)](pt,r,h));let _=c[s(993)];e[s(1108)](void 0,_)&&(ce(r,16),e.lUDLo(pt,r,_));let b=c[s(689)];e[s(674)](void 0,b)&&(e.eMnqp(ce,r,24),e[s(916)](pt,r,e[s(1432)](P,b)));let I=c.method;e.ogCOa(void 0,I)&&(ce(r,32),e[s(1323)](pt,r,e[s(936)](P,I)));let m=c.headers;if(m!==void 0)for(let ge of m){ce(r,42);let nt=e[s(355)](R);x(ge,nt),ce(r,nt.limit),T(r,nt),D(nt)}let O=c["payloadE"+s(1361)];O!==void 0&&(e.EvdCi(ce,r,50),je(r,O));let L=c[s(337)+s(1024)];e[s(277)](void 0,L)&&(e[s(1385)]("hOFmJ",e.IWosm)?this[s(788)](l[s(1514)],l[s(1124)](_0x814903,l[s(1514)],{message:this[s(923)+s(1214)+s(324)](_0x12a242)})):(ce(r,58),e[s(1373)](je,r,L)));let F=c[s(971)];if(e.kqFao(void 0,F))if(e[s(344)]!==e.LTXKi){let ge=_0x58a8bc.deleteDatabase(_0x4d7071);return _0x4a0ef7&&ge[s(1560)+s(913)](PHnrbg[s(877)],()=>_0x58a8e4()),PHnrbg[s(1461)](_0x27ea69,ge)[s(305)](()=>{})}else e[s(1364)](ce,r,66),e.BhnTC(ce,r,F[s(1393)]),e[s(105)](le,r,F);let V=c[s(1321)];e[s(614)](void 0,V)&&(e[s(327)](ce,r,74),e[s(1045)](je,r,V));let X=c[s(1151)+"ming"];e[s(919)](void 0,X)&&(e[s(559)](ce,r,82),e[s(1045)](je,r,X));let J=c[s(138)];e.jHnGa(void 0,J)&&(e[s(546)](ce,r,90),e[s(1364)](je,r,J));let Me=c[s(827)+"e"];if(Me!==void 0)if(e.jGYMU(e[s(855)],"zMPoc")){let ge={zFnFW:s(476),LmWTr:e[s(806)],MMqQo:s(1082)+"e_timeout"};return new _0x2d97b0((nt,rn)=>{let xe=s,me={GyWQE:function(Ye,vi){return Ye(vi)},GHFqe:xe(1460),atslp:xe(1082)+xe(622)+"t",TCDHq:ge.zFnFW,JSkvv:ge[xe(1428)]};this["_clearPi"+xe(416)](),this[xe(1269)+xe(995)+"Id"]=_0x3a2249(this._ping[xe(239)](this),this[xe(495)][xe(1469)+xe(109)]);let be=()=>{let Ye=xe;me[Ye(1101)](nt,me[Ye(990)]),this[Ye(1430)](Ye(1082)+Ye(530)+"s",be),this[Ye(1430)](me[Ye(261)],sn)},sn=()=>{let Ye=xe;me.GyWQE(rn,me[Ye(314)]),this[Ye(1430)](me[Ye(824)],be),this.off(Ye(1082)+Ye(622)+"t",sn)};this.on(ge[xe(1428)],be),this.on(ge[xe(799)],sn),this[xe(794)]()})}else ce(r,96),e.SZqDn(pt,r,P(Me))}function E(c){return S(e[t(589)](z,c))}function S(c){let r=t,s={};e:for(;!K(c);){let l=e[r(1228)](te,c);switch(e[r(938)](l,3)){case 0:break e;case 1:s[r(215)]=dt(c,!0);break;case 2:s[r(993)]=dt(c,!0);break;case 3:s[r(689)]=e[r(589)](te,c);break;case 4:s.method=e[r(1131)](te,c);break;case 5:{let h=e.bmGZu(A,c);(s[r(966)]||(s[r(966)]=[]))[r(1544)](g(c)),c.limit=h;break}case 6:s[r(776)+r(1361)]=Se(c,e.jQMta(te,c));break;case 7:s[r(337)+r(1024)]=e[r(345)](Se,c,e.GPNYK(te,c));break;case 8:s[r(971)]=e[r(327)](ae,c,e[r(846)](te,c));break;case 9:s[r(1321)]=e.jbNiQ(Se,c,e[r(244)](te,c));break;case 10:s[r(1151)+r(418)]=e.NYzQm(Se,c,e[r(936)](te,c));break;case 11:s[r(138)]=e.jbNiQ(Se,c,e.REogc(te,c));break;case 12:s[r(827)+"e"]=e[r(830)](te,c);break;default:C(c,e[r(811)](7,l))}}if(e[r(1466)](void 0,s[r(215)]))throw new Error(r(1016)+"required field: "+r(215));if(e[r(1575)](void 0,s.LogID))throw new Error(e[r(1513)]);if(s[r(689)]===void 0)throw new Error(r(1016)+r(889)+r(704)+r(689));if(s[r(356)]===void 0)throw new Error(e[r(1128)]);return s}function A(c){let r=t,s=te(c),l=c[r(664)];return c[r(664)]=c[r(268)]+s,l}function C(c,r){let s=t;if(e[s(1019)](e[s(771)],e[s(771)]))if(e.TkuJC(_0x1e9dd8.payload,_0x2a321b)){let l=e[s(393)](this[s(495)][s(776)+s(1361)],_0x6bacbb)?{force:!!this[s(495)][s(776)+"ncoding"][s(1255)],encoding:this[s(495)][s(776)+s(1361)][s(422)]?this[s(495)][s(776)+s(1361)][s(422)].replace(/\s/g,"")[s(1406)+s(1528)]():""}:{force:!1,encoding:this[s(495)][s(776)+s(1361)]?this[s(495)][s(776)+s(1361)][s(1149)](/\s/g,"")["toLowerC"+s(1528)]():""},h=_0x107293[s(776)+s(1361)]?_0x42bfb2[s(776)+s(1361)][s(1149)](/\s/g,"")[s(1406)+s(1528)]():"",_=this[s(495)][s(337)+"ype"]instanceof _0x1888ff?{force:!!this[s(495)].payloadType[s(1255)],type:this[s(495)]["payloadT"+s(1024)][s(1313)]?this[s(495)][s(337)+s(1024)][s(1313)][s(1149)](/\s/g,"")["toLowerC"+s(1528)]():""}:{force:!1,type:this[s(495)][s(337)+s(1024)]?this[s(495)][s(337)+s(1024)][s(1149)](/\s/g,"")[s(1406)+s(1528)]():""},b=_0x215e3b[s(337)+"ype"]?_0x4d284b[s(337)+s(1024)][s(1149)](/\s/g,"")[s(1406)+s(1528)]():"",I=_[s(1255)]?_[s(1313)]:b||_.type,m=l[s(1255)]?l[s(422)]:h||l[s(422)],O=[e.uvuEA,"applicat"+s(670),e[s(1026)],e[s(1338)]],L=["none_none",e[s(702)]];this[s(495)]["enableTr"+s(209)+s(983)+"ad"]&&O[s(1270)](I)&&(!m||L[s(1270)](m))?_0x520c73["textPayl"+s(1261)]=e[s(1562)](_0x31af6a,_0x52a11f.payload,0,_0x1200b6[s(971)][s(901)+"th"]):_0x22f87e["textPayl"+s(1261)]=""}else _0x5c3e68["textPayl"+s(1261)]="";else switch(r){case 0:for(;128&e[s(589)](U,c););break;case 2:e.KiTiL(W,c,te(c));break;case 5:e[s(345)](W,c,4);break;case 1:e[s(327)](W,c,8);break;default:throw new Error(e[s(1018)](e[s(1474)],r))}}function P(c){let r=t;return e[r(867)](e[r(1176)],e.MyuxU)?new _0x54855d(_0x4b00cc,{code:_0x563546,reason:_0x252b13,wasClean:_0x22c9b9,willReconnect:_0x2abc3b}):(c|=0,{low:c,high:e.ueqGE(c,31),unsigned:e.lZXmm(c,0)})}let y=[];function R(){let c=t;if(e[c(280)](e[c(1573)],e[c(1251)]))this[c(592)+"T"]||this[c(710)+"X"]?this[c(1074)+"etWorkCh"+c(1094)]():this[c(452)+"er"]&&this[c(774)+c(1591)+c(913)]();else{let r=y[c(151)]();return r?(r[c(268)]=r[c(664)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}}function D(c){let r=t;e[r(359)](e.GgfHg,e[r(1496)])?FvCbfE[r(905)](_0xd5072f,FvCbfE[r(1432)](_0x3a49d7,_0x270fb9[r(1032)]),_0x25d06d.oldVersion,_0x1ef7b6[r(1053)+"on"],_0xe156bb(_0x238e78[r(878)+"ion"])):y.push(c)}function z(c){return{bytes:c,offset:0,limit:c[t(1393)]}}function M(c){let r=t,s=c[r(637)],l=c.limit;return e[r(958)](s[r(1393)],l)?s:s[r(129)](0,l)}function W(c,r){let s=t;if(e[s(259)](e[s(821)](c[s(268)],r),c[s(664)]))throw new Error(e[s(1397)]);c[s(268)]+=r}function K(c){let r=t;return e[r(820)](c.offset,c[r(664)])}function se(c,r){let s=t;if(e[s(1066)](e[s(700)],"bHUIq"))return!0;{let l=c.bytes,h=c[s(268)],_=c.limit,b=h+r;if(e[s(1187)](b,l[s(1393)])){let I=new Uint8Array(e[s(1115)](2,b));I.set(l),c.bytes=I}return c[s(268)]=b,e.kTvLx(b,_)&&(c[s(664)]=b),h}}function Q(c,r){let s=t;if(e[s(1575)]("eNIoM",e[s(281)])){let l=c[s(268)];if(e[s(248)](l+r,c.limit))throw new Error(e[s(755)]);return c[s(268)]+=r,l}else{let l=_0x76285d.substring(0,4-_0x1b610a[_0xcd5206].length),h=l[s(754)](_0x3278bd);_0x5b82fb=_0x5ed38f.concat(h)}}function ae(c,r){let s=e.XcMfB(Q,c,r);return c.bytes.subarray(s,s+r)}function le(c,r){let s=t,l=e[s(267)](se,c,r[s(1393)]);c[s(637)][s(423)](r,l)}function Se(c,r){let s=t,l={sHnjU:function(O,L){return e[$(1010)](O,L)},gYwgI:function(O,L){return e.ruyrv(O,L)},RNJQC:function(O,L){return e.WzalX(O,L)},isqfH:function(O,L){return e[$(938)](O,L)}},h=Q(c,r),_=String["fromChar"+s(489)],b=c[s(637)],I="\uFFFD",m="";for(let O=0;e[s(1010)](O,r);O++){let L=b[e[s(213)](O,h)],F,V,X,J;if(e[s(1240)](128&L,0))m+=e[s(1432)](_,L);else if(e[s(228)](e[s(828)](224,L),192))e.lZXmm(e[s(493)](O,1),r)?m+=I:(F=b[e[s(1034)](e[s(279)](O,h),1)],e[s(277)](e.WEWbW(192,F),128)?m+=I:(J=e[s(180)](e[s(636)](e[s(1579)](31,L),6),63&F),J<128?m+=I:e[s(1580)](e[s(266)],e[s(266)])?(_0x3bf68b["frontier"+s(1488)]=void 0,_0x238d96(s(876)+s(474))):(m+=e[s(687)](_,J),O++)));else if(e[s(1328)](e[s(1202)](240,L),224))e[s(820)](e[s(699)](O,2),r)?m+=I:(F=b[e[s(1037)](e[s(1235)](O,h),1)],V=b[e[s(709)](O+h,2)],e[s(1520)](e.zEgXW(e[s(180)](F,e.tUCLv(V,8)),49344),32896)?m+=I:(J=e.cVeLB(e[s(520)](e[s(656)](15,L),12),e.JEsHf(e[s(366)](63,F),6))|63&V,e.htkIi(J,2048)||e.qoGZf(J,55296)&&J<=57343?m+=I:(m+=e[s(651)](_,J),O+=2)));else if(e.OxOty(e[s(207)](248,L),240))if(e[s(949)](e[s(187)](O,3),r))m+=I;else if(e[s(1542)](e[s(1028)],e[s(1028)])){let Me={HFxOi:function(me,be){return l[s(775)](me,be)},ZNdsl:function(me,be){return me>be},JIjPp:function(me,be){return me(be)},IUafZ:function(me,be){return l[s(1068)](me,be)},AaGyi:function(me,be){return l.RNJQC(me,be)},oYdvB:function(me,be){return me|be}},ge=_0x5103bb||8192,nt=l[s(269)](ge,1),rn=null,xe=ge;return function(me){let be=s;if(Me[be(753)](me,1)||Me[be(501)](me,nt))return Me[be(1504)](_0x2bb50c,me);Me[be(501)](xe+me,ge)&&(rn=_0x4407e1(ge),xe=0);let sn=_0xc7d97a.call(rn,xe,xe+=me);return Me[be(1471)](7,xe)&&(xe=Me.AaGyi(Me[be(1503)](7,xe),1)),sn}}else F=b[e.DfRFM(O+h,1)],V=b[e[s(1164)](e.gowYk(O,h),2)],X=b[e.uyqIU(O+h,3)],(e.kwzty(F|V<<8,e[s(1490)](X,16))&12632256)!==8421504?m+=I:(J=e[s(113)](e.cVeLB(e[s(624)](e[s(204)](7&L,18),e.tUCLv(63&F,12)),e.BhleW(e[s(1579)](63,V),6)),e[s(811)](63,X)),J<65536||J>1114111?m+=I:(J-=65536,m+=_(e[s(491)](J,10)+55296,e[s(366)](1023,J)+56320),O+=3));else m+=I}return m}function je(c,r){let s=t;if(e[s(227)](s(317),e[s(675)])){let l=e.WNdbN(_0x23d211,e[s(1390)],{message:_0x3d8580[s(1080)],code:_0x133b7a["MESSAGE_"+s(935)],error:_0x171ef9});this[s(946)+"hErrorEv"+s(606)](l)}else{let l=r[s(1393)],h=0;for(let I=0;e.NVHkC(I,l);I++){let m=r[s(727)+"At"](I);m>=55296&&e.aIZzG(m,56319)&&e[s(577)](e.iyRNe(I,1),l)&&(m=e.Wwomk(e[s(1034)](m<<10,r[s(727)+"At"](++I)),56613888)),h+=e[s(320)](m,128)?1:e[s(1010)](m,2048)?2:m<65536?3:4}ce(c,h);let _=se(c,h),b=c[s(637)];for(let I=0;e.hIkPQ(I,l);I++)if(e[s(1211)](e[s(1525)],s(883))){let m=r[s(727)+"At"](I);e[s(521)](m,55296)&&e[s(527)](m,56319)&&e[s(577)](I+1,l)&&(m=e[s(599)](e.tLiOx(e[s(1062)](m,10),r[s(727)+"At"](++I)),56613888)),e[s(1467)](m,128)?b[_++]=m:(m<2048?b[_++]=e[s(180)](m>>6&31,192):e[s(333)](e[s(1046)],s(448))?(this[s(256)]=!0,this.low=e[s(113)](0,_0x3231ae),this[s(1565)]=e.sbmOt(0,_0x30a849),this.unsigned=!!_0x2cd914):(e[s(320)](m,65536)?b[_++]=e.vfeaJ(e[s(811)](e[s(491)](m,12),15),224):(b[_++]=e[s(1138)](e.rweoC(m>>18,7),240),b[_++]=e[s(1300)](e[s(218)](e[s(417)](m,12),63),128)),b[_++]=e[s(180)](e[s(656)](m>>6,63),128)),b[_++]=e[s(498)](e[s(1579)](63,m),128))}else return this._qosDB[s(838)]}}function T(c,r){let s=t;if(e[s(201)](s(172),e[s(870)])){let l=e[s(516)](se,c,r[s(664)]),h=c[s(637)],_=r[s(637)];for(let b=0,I=r.limit;e.SnrDj(b,I);b++)h[e[s(1235)](b,l)]=_[b]}else this[s(1139)+s(1529)+s(549)]=_0x5ac08b,_0x405505?this._handleOnLine():this["_handleO"+s(1493)]()}function U(c){return c[t(637)][Q(c,1)]}function q(c,r){let s=t,l=e.EvdCi(se,c,1);c[s(637)][l]=r}function te(c){let r=t,s=0,l=0,h;do{if(e.SqBMW===e[r(696)])return new _0x21286b(_0x18bb32,{data:_0x173497});h=e[r(199)](U,c),e[r(1010)](s,32)&&(l|=e[r(636)](e[r(1349)](127,h),s)),s+=7}while(e[r(828)](128,h));return l}function ce(c,r){let s=t;for(r>>>=0;r>=128;)e[s(1585)](q,c,e[s(831)](e.zEgXW(127,r),128)),r>>>=7;e[s(1373)](q,c,r)}function dt(c,r){let s=t,l=0,h=0,_=0,b;if(b=e[s(1168)](U,c),l=e[s(366)](127,b),e.nnsRk(128,b)&&(b=e[s(244)](U,c),l|=e.wCvgO(e.znztx(127,b),7),e[s(927)](128,b)&&(b=U(c),l|=e[s(726)](e[s(207)](127,b),14),e[s(1526)](128,b)&&(b=e[s(1468)](U,c),l|=e.JmmAI(e[s(927)](127,b),21),e[s(828)](128,b)&&(b=e[s(773)](U,c),h=127&b,e[s(593)](128,b)))))){if(e[s(201)](e[s(851)],e[s(851)]))return s(668)+"_"+this._DBName;b=e[s(766)](U,c),h|=e.BhleW(e[s(1267)](127,b),7),e[s(159)](128,b)&&(b=e[s(645)](U,c),h|=e[s(715)](e.IRIxD(127,b),14),e.Enlpn(128,b)&&(b=e[s(119)](U,c),h|=(127&b)<<21,e[s(1202)](128,b)&&(b=U(c),_=e[s(307)](127,b),e[s(1273)](128,b)&&(b=e.GzVKr(U,c),_|=e[s(630)](e.VNTBR(127,b),7)))))}return{low:l|h<<28,high:e[s(498)](e[s(1105)](h,4),_<<24),unsigned:r}}function pt(c,r){let s=t,l=e[s(265)](r[s(1515)],0),h=e.BEnni(e.VCgmY(e.tkScJ(r.low,28),e.EtIiw(r[s(1565)],4)),0),_=e.NsmxJ(r.high,24),b=_===0?h===0?e[s(440)](l,16384)?l<128?1:2:l<2097152?3:4:h<16384?e.NVHkC(h,128)?5:6:e[s(111)](h,2097152)?7:8:_<128?9:10,I=e.lXsLv(se,c,b),m=c[s(637)];switch(b){case 10:m[e[s(1034)](I,9)]=e[s(1526)](e.PsFBn(_,7),1);case 9:m[I+8]=e[s(1520)](9,b)?e.wleMK(128,_):e[s(850)](127,_);case 8:m[I+7]=e[s(1520)](8,b)?e[s(1300)](e[s(1253)](h,21),128):e[s(179)](e[s(1558)](h,21),127);case 7:m[e[s(187)](I,6)]=e[s(600)](7,b)?e[s(243)](e[s(1558)](h,14),128):e[s(927)](h>>>14,127);case 6:m[e[s(1015)](I,5)]=e[s(1520)](6,b)?h>>>7|128:e.PsFBn(h,7)&127;case 5:m[e[s(1164)](I,4)]=e[s(1019)](5,b)?e[s(135)](128,h):e[s(1202)](127,h);case 4:m[e[s(1235)](I,3)]=e[s(600)](4,b)?e.oBOdK(e.glvhN(l,21),128):e[s(749)](e[s(401)](l,21),127);case 3:m[e[s(1587)](I,2)]=e.qhcso(3,b)?e.YcxTS(l>>>14,128):e.FbYKT(e[s(1296)](l,14),127);case 2:m[I+1]=e[s(919)](2,b)?e[s(1564)](l>>>7,128):e[s(382)](e[s(1330)](l,7),127);case 1:m[I]=b!==1?e[s(1300)](128,l):e.RSIkg(127,l)}}function Ut(c){return E(c)}function nn(c){return v(c)}let En=65536,jn=t(231),bt=En*En,Er=e[t(492)](bt,bt),Ue=e[t(965)](Er,2),_e=String.prototype[t(727)+"At"];class de{constructor(r,s,l){let h=t;this[h(256)]=!0,this.low=e.XVJpx(0,r),this.high=e[h(618)](0,s),this[h(1446)]=!!l}static[t(256)](r){let s=t,l={YUSqo:function(h,_){return e.hzluP(h,_)},JkzsD:function(h,_){return e[$(1200)](h,_)},UbsxS:function(h,_){return e[$(392)](h,_)},yaeof:function(h,_){return e[$(114)](h,_)},UpLYA:function(h,_){return h<<_},rCwzA:function(h,_){return e[$(159)](h,_)},GapCM:function(h,_){return e[$(1403)](h,_)},OKjSC:function(h,_){return e[$(248)](h,_)},ZIGqt:function(h,_,b){return e.rGjaN(h,_,b)},fDLuH:function(h,_){return e[$(493)](h,_)},CErbF:function(h,_){return e[$(461)](h,_)},WsyMn:function(h,_){return h&_}};if(e.JHpQy(e[s(1535)],e.MKdhk))_0x20883e=Pflvtm[s(332)](Pflvtm[s(1456)](Pflvtm[s(1318)](Pflvtm[s(781)](7&_0x32b51d,18),Pflvtm[s(1538)](Pflvtm[s(181)](63,_0x254110),12)),Pflvtm[s(1538)](63&_0x441643,6)),Pflvtm[s(181)](63,_0x1229ba)),Pflvtm[s(373)](_0x26c83e,65536)||Pflvtm[s(1402)](_0xcac46b,1114111)?_0x29a1ea+=_0x26ed0f:(_0x2401a9-=65536,_0x5af37d+=Pflvtm[s(478)](_0x515443,Pflvtm[s(1069)](Pflvtm[s(810)](_0x228152,10),55296),Pflvtm[s(1069)](Pflvtm[s(897)](1023,_0x10ffde),56320)),_0x564380+=3);else return r&&e[s(1231)](!0,r[s(256)])}static[t(144)](r,s,l){return new de(r,s,l)}static[t(1572)+"s"](r,s,l){let h=t;return l?de["fromByte"+h(790)](r,s):de[h(1572)+"sBE"](r,s)}static["fromByte"+t(790)](r,s){let l=t;return new de(e[l(518)](e[l(174)](e.oBOdK(r[0],e[l(1134)](r[1],8)),e[l(795)](r[2],16)),e[l(751)](r[3],24)),e[l(1378)](e[l(222)](r[4],e[l(520)](r[5],8)),r[6]<<16)|e.TNbzP(r[7],24),s)}static["fromByte"+t(1305)](r,s){let l=t;if(e[l(1352)]!==e[l(1352)]){let h=e[l(1373)](_0x22c87e,e.HRCYE,{message:e[l(369)]});this[l(722)+"econnect"]&&this["onStartR"+l(1341)](h)}else return new de(e[l(1200)](e[l(1300)](e[l(541)](r[4],24)|r[5]<<16,r[6]<<8),r[7]),e.bMLLj(e[l(1522)](e[l(831)](e.yhkGO(r[0],24),e[l(204)](r[1],16)),e.mrdtZ(r[2],8)),r[3]),s)}static[t(739)](r){let s=t;return r===jn?xt:new de(e.zpJXq(e[s(1281)](e.dvOck(_e[s(894)](r,0)|e[s(1086)](_e[s(894)](r,1),8),e[s(372)](_e.call(r,2),16)),e[s(520)](_e[s(894)](r,3),24)),0),e[s(613)](e.OzKhW(e.UyauK(_e[s(894)](r,4),_e[s(894)](r,5)<<8)|_e[s(894)](r,6)<<16,e[s(893)](_e[s(894)](r,7),24)),0),!0)}[t(1507)](){let r=t;if(e[r(110)](e[r(214)],r(1448)))return String[r(1563)+r(489)](e.qxgcu(255,this[r(1515)]),e[r(539)](this.low,8)&255,e[r(927)](e.xxsKi(this[r(1515)],16),255),e[r(503)](this[r(1515)],24),255&this[r(1565)],e.rweoC(this[r(1565)]>>>8,255),e[r(861)](e[r(1332)](this.high,16),255),this.high>>>24);this.emit(r(278),_0x7634fc),this[r(1079)+r(371)]&&this[r(1079)+r(371)](_0x156442)}static[t(402)+"er"](r,s=!0){let l=t;if(e[l(846)](isNaN,r))return s?Wg:xt;if(s){if(e.prtTQ(r,Er))return $g}else if(e[l(789)](e[l(1192)],e[l(1192)])){if(e[l(166)](_0x31e4d5,-_0x5c501a))return _0x5db6c0;if(_0x3fcbfd+1>=_0x1e47cb)return _0x10bff4}else{if(r<=-Ue)return Vg;if(e[l(1252)](r+1,Ue))return Kg}return de.fromBits(e.PxWnS(e[l(331)](r,bt),0),e[l(120)](e.ewyNm(r,bt),0),s)}[t(943)](){let r=t;return this[r(1446)]?e[r(886)](e.VdCVq(this[r(1565)],0)*bt,e[r(253)](this[r(1515)],0)):e.MHnUd(e[r(353)](this[r(1565)],bt),e[r(253)](this[r(1515)],0))}isZero(){let r=t;return e.vcSzR(0,this.high)&&this[r(1515)]===0}[t(444)](r){let s=t;de[s(256)](r)||(r=de.fromNumber(r));let l=e[s(1130)](this[s(1565)],16),h=e[s(1061)](65535,this[s(1565)]),_=this.low>>>16,b=65535&this[s(1515)],I=e[s(1296)](r[s(1565)],16),m=e[s(1278)](65535,r.high),O=e.CNWsl(r[s(1515)],16),L=65535&r[s(1515)],F=0,V=0,X=0,J=0;return J+=e[s(187)](b,L),X+=e[s(1253)](J,16),J&=65535,X+=e.WzalX(_,O),V+=e[s(251)](X,16),X&=65535,V+=e[s(187)](h,m),F+=V>>>16,V&=65535,F+=e[s(1583)](l,I),F&=65535,de[s(144)](e[s(1014)](X,16)|J,e[s(1300)](e.rHdcG(F,16),V),this.unsigned)}[t(466)](r){let s=t;return de.isLong(r)||(r=de.fromNumber(r)),e[s(919)](this[s(1446)],r.unsigned)&&e[s(1466)](e[s(1571)](this[s(1565)],31),1)&&e[s(1511)](r.high>>>31,1)?!1:this.high===r[s(1565)]&&e[s(110)](this[s(1515)],r[s(1515)])}[t(301)](){let r=t;return e[r(807)](-1,this[r(1515)])&&this[r(1565)]===-1?de[r(144)](0,0,this[r(1446)]):e[r(378)](-1,this.low)?de[r(144)](0,e[r(213)](this[r(1565)],1),this[r(1446)]):de[r(144)](e.TBncW(this[r(1515)],1),this[r(1565)],this.unsigned)}[t(1199)](r){return r?this[t(512)+"E"]():this.toBytesBE()}[t(512)+"E"](){let r=t,s=this[r(1565)],l=this[r(1515)];return[e[r(123)](255,l),e[r(822)](e[r(1330)](l,8),255),e.GvUnZ(l,16)&255,e[r(1517)](l,24),e[r(1096)](255,s),e[r(1396)](e.OMGyh(s,8),255),e[r(251)](s,16)&255,e.kNsJL(s,24)]}[t(197)+"E"](){let r=t,s=this[r(1565)],l=this[r(1515)];return[e[r(792)](s,24),e[r(1105)](s,16)&255,e[r(1278)](s>>>8,255),e[r(900)](255,s),e[r(1105)](l,24),e[r(382)](e[r(796)](l,16),255),l>>>8&255,e[r(1501)](255,l)]}}let xt=new de(0,0,!1),Wg=new de(0,0,!0),Kg=de[t(144)](-1,2147483647,!1),$g=de.fromBits(-1,-1,!0),Vg=de[t(144)](0,-2147483648,!1);var vn=(function(c){let r=t,s=e[r(875)][r(496)]("|"),l=0;for(;;){switch(s[l++]){case"0":c[c[e.PzClI]=5003]=r(528)+r(737)+"R";continue;case"1":return c;case"2":c[c[e[r(286)]]=5002]=e[r(286)];continue;case"3":c[c[e[r(150)]]=5005]=e[r(150)];continue;case"4":c[c[e.YCvVL]=5001]=r(383)+"RROR";continue;case"5":c[c[e.dTPEu]=5004]=e[r(192)];continue}break}})({});class vr{constructor(r){let s=t;this[s(1313)]=r,this[s(803)]=null}}class zl extends vr{constructor(r,s){let l=t;super(r),this[l(1080)]=s&&s[l(1080)]||null}}class Ul extends vr{constructor(r,s){let l=t;super(r),this[l(1173)]=s&&s[l(1173)]||null,this[l(323)]=s&&s[l(323)]||0,this.filename=s&&s[l(1453)]||"",this[l(628)]=s&&s[l(628)]||0,this[l(1080)]=s&&s[l(1080)]||"",this.code=s&&s[l(506)]||5001}}class Hl extends vr{constructor(r,s){let l=t,h=(l(1454)+"3").split("|"),_=0;for(;;){switch(h[_++]){case"0":this[l(506)]=s&&s[l(506)]||0;continue;case"1":super(r);continue;case"2":this[l(474)]=s&&s[l(474)]||"";continue;case"3":this[l(544)+l(1584)]=s&&s.willReconnect||!1;continue;case"4":this[l(918)]=s&&s[l(918)]||!1;continue}break}}}class Gl extends vr{constructor(r,s){super(r),this.data=s&&s.data||null}}class ql extends Gl{constructor(r,s){let l=t;super(r),this[l(1263)]=s&&s.data||null,this[l(1080)]=s&&s[l(1080)]||null}}class jl extends vr{constructor(r,s){let l=t;if(l(1551)===e[l(237)])super(r),this[l(1263)]=s&&s[l(1263)]||null;else{if(e[l(554)](e[l(1338)],typeof _0x2c30da)){let h=new _0x5c1407(e[l(1325)](_0x2e3ec4,_0x411514));return e[l(225)](_0x3d89e1,_0x253098,h,0),h}return e[l(393)](_0x35ae98,_0x4e174f)?new _0x29e390(_0x42f7d0):new _0xf21277(_0xe54d4e.buffer,_0x4e6bb1[l(1302)+"et"],_0x4ced44[l(901)+"th"])}}}function Et(c,{message:r,code:s,error:l}){return new Ul(c,{message:r,code:s,error:l})}function Rt(c,{code:r,reason:s,wasClean:l,willReconnect:h}){return new Hl(c,{code:r,reason:s,wasClean:l,willReconnect:h})}function Wl(c,{data:r,message:s}){return new ql(c,{data:r,message:s})}function Kl(c,{data:r}){return new jl(c,{data:r})}function $a(c,{message:r}){return new zl(c,{message:r})}class $l{constructor(r,s){let l=t;this[l(968)+"s"]=r,this[l(532)+"es"]=s,this[l(170)+l(1479)]=0,this["currentEndpointT"+l(748)+"t"]=0}[t(1492)+t(270)+t(1020)](){let r=t;this[r(170)+"ndex"]=0,this["currentE"+r(848)+r(748)+"t"]=0}[t(519)+"es"](){let r=t;this[r(454)+r(848)+"riesCount"]=0}[t(1188)+t(399)+"nt"](){let r=t,s={xDiRG:function(l,h){return l+h},Wzbzu:function(l,h){return l<h},zOxQD:function(l,h,_){return l(h,_)},eSdZs:function(l,h){return e[$(1086)](l,h)}};if(e[r(295)]!==e[r(295)]){let l=0,h=_0x26ff2a,_=s.xDiRG(_0x3cddfd,4);for(;s[r(1547)](h,_);){let{value:b,offset:I}=s[r(272)](_0x25b433,_0x2227f5,h);h=I,l=s.eSdZs(l,8)>>>0,l+=b}return{value:l,offset:_}}else return this.endpoints[this[r(170)+r(1479)]]}[t(1188)+t(399)+t(451)+t(631)](){let r=t;return this[r(454)+r(848)+r(748)+"t"]}checkReachMaxTries(){let r=t;return!!(e[r(949)](this[r(170)+r(1479)],this[r(968)+"s"].length)||e[r(1553)](this[r(170)+r(1479)],e[r(599)](this[r(968)+"s"][r(1393)],1))&&e[r(1211)](this[r(454)+r(848)+r(748)+"t"],this[r(532)+"es"]))}[t(804)+"rentEndpointReachedMaxRe"+t(1022)](){let r=t;return e[r(554)](this[r(170)+r(1479)],this.endpoints.length)?!0:e.yBHww(this["currentE"+r(848)+"riesCount"],this[r(532)+"es"])}[t(576)+t(1132)+t(1459)+t(315)+t(881)](){let r=t;return this[r(454)+r(848)+r(748)+"t"]=1,this[r(170)+r(1479)]++,this[r(968)+"s"][this[r(170)+r(1479)]]}[t(1188)+t(399)+"ntAndUpd"+t(1424)](){let r=t,s={UhGnv:e[r(860)],pDaTb:e[r(1390)],pEouQ:e[r(1297)]};if(e.PduwU===e[r(148)])return this[r(454)+r(848)+r(748)+"t"]++,this["getCurre"+r(399)+"nt"]();_0xf04c2["removeEv"+r(421)+r(1557)](DREtdL[r(844)],_0x2e8716),_0x28e593[r(1177)+r(421)+r(1557)](DREtdL[r(780)],_0xa43f46),_0x57a7de["removeEventListe"+r(1557)](DREtdL.pEouQ,_0x2574f5)}}let Sr=(e[t(212)](t(505)+"d",typeof globalThis)&&e[t(1231)](e[t(162)],globalThis[t(854)+t(980)][t(107)])||e[t(730)](e[t(1107)],typeof window)&&e.NlAaC===window[t(854)+"tor"][t(107)])&&e[t(1401)](e.NyQCZ,typeof document),Wn=t(505)+"d"!=typeof globalThis&&(e[t(807)](e[t(626)],globalThis[t(854)+t(980)][t(107)])||e[t(1183)](e[t(1184)],globalThis.constructor.name))&&e.LWIss(e[t(1107)],typeof tt),bi=(e.aGJdt(t(505)+"d",typeof globalThis)&&e[t(626)]===globalThis[t(854)+t(980)][t(107)]||e[t(1107)]==typeof globalThis||e.NOfKl(e[t(1107)],typeof globalThis)&&!!globalThis[t(1362)+t(195)])&&e[t(330)](e[t(1107)],typeof wx),Ei=e[t(330)](t(505)+"d",typeof globalThis)&&(e.XPOQJ(e[t(1184)],globalThis[t(854)+"tor"][t(107)])||e[t(1553)](e[t(819)],globalThis["construc"+t(980)][t(107)])||e[t(823)](e.xlYdN,globalThis[t(854)+t(980)][t(107)]))&&e[t(841)](e.NyQCZ,typeof self),Jg=e[t(1107)]!=typeof globalThis&&t(1405)===globalThis.constructor[t(107)]&&e[t(730)](e.NyQCZ,typeof global)&&e[t(925)](e[t(626)],global[t(854)+t(980)][t(107)])&&typeof process<"u"&&!!process.version;class Va{constructor(){let r=t;this[r(1369)+"rs"]={}}[t(788)](r,...s){let l=t,h=this[l(1369)+"rs"][r];if(h)h.slice()[l(1521)](_=>_.fn[l(1203)](_[l(1025)],s));else if(e[l(1436)](e[l(1390)],r)&&!this[l(1169)]){let _=s.length&&s[0];if(e.BcqJT(_,Error))throw _;let b=new Error(e[l(967)](e[l(449)],_?e.ADKvU(e[l(523)](" (",_[l(1080)]),")"):""));throw b[l(660)]=_,_}return this}[t(1430)](r,s){let l=t;if(e[l(958)](void 0,r))this._listeners={};else if(e.uNfes(void 0,s))this._listeners[r]=null;else{let h=this[l(1369)+"rs"][r];if(h)for(let _=0;e[l(1197)](_,h.length);)e.bwXTC(h[_].fn,s)?h[l(864)](_,1):++_}return this}on(r,s,l){let h=t;if(e[h(1326)]!=="qepFj")return(this[h(1369)+"rs"][r]||(this[h(1369)+"rs"][r]=[]))[h(1544)]({fn:s,ctx:l||this}),this;_0x3e8ef3[h(423)](_0x2eec5f,_0x1a5b91),_0x2ce9a2.set(_0x4553cf,_0x560bfb)}}class Zg extends Va{["_formatE"+t(1214)+t(324)](r){let s=t;return r[s(1254)]||r[s(1409)]?(s(1277)+" "+(r[s(1254)]||"")+s(1262)+(r[s(1409)]||"")).trim():JSON.stringify(r)}constructor(r,s,l){let h=t;super(),this[h(1383)]=null,bi&&wx[h(122)+h(1574)]&&(this[h(1383)]=wx["connectS"+h(1574)]({url:r,protocols:s,header:l,fail:this[h(1072)+h(950)+"lHandler"][h(239)](this),success:this[h(1072)+h(903)+h(481)+h(1421)].bind(this)})),Wn&&tt[h(122)+h(1574)]&&(this[h(1383)]=tt[h(122)+h(1574)]({url:r,protocols:s,header:l,fail:this[h(1072)+h(950)+h(785)][h(239)](this),success:this["_createS"+h(903)+h(481)+h(1421)].bind(this)}))}["_createSocketSuc"+t(481)+t(1421)](){let r=t;Promise[r(1578)]()[r(305)](()=>{let s=r;this[s(981)+s(713)]()})}[t(1072)+t(950)+t(785)](r){let s=t;if(e[s(442)](e[s(364)],e.pDLYC)){let l=e[s(275)][s(496)]("|"),h=0;for(;;){switch(l[h++]){case"0":if(e[s(1438)](_0x149d0f[s(1393)],40))return _0xc0ee71(_0x59d151,_0x2baaef,_0x321940)+_0x5c6ea8;continue;case"1":if(_0x2ce62d.write)return e.evgXp(_0x57eb3c[s(1442)](_0x931011,_0x2089b0),_0x54d36b);continue;case"2":return e[s(847)](e[s(1562)](_0x21bbed,_0x218fac,_0x2d1b4a,_0x11c4a3),_0x1d4d37);case"3":if(!_0x36b39a)return _0x574659;continue;case"4":if(_0x4cfe5d[s(1426)+"e"])return _0x241b98[s(1426)+"e"](_0x654362,_0x193a99)+_0x3b564f;continue}break}}else Promise[s(1578)]()[s(305)](()=>{let l=s,h=e[l(1548)](Et,e.tMLgA,{message:this["_formatE"+l(1214)+l(324)](r)});this[l(788)](e.tMLgA,h);let _=e.BJlDM(Rt,e[l(1048)],{reason:this["_formatE"+l(1214)+"age"](r)});this.emit(l(1212),_)})}[t(981)+"steners"](){let r=t,s={Mupmw:e[r(1372)],COyot:function(l,h,_){return l(h,_)},CaXGs:r(1173)};this._socket[r(767)](l=>{let h=r;this[h(788)](h(1088),e[h(514)](Kl,"open",{...l,data:l.errMsg||""}))}),this[r(1383)][r(931)](l=>{let h=r;this[h(788)](e.PRFVH,e[h(1379)](Rt,h(1212),{...l}))}),this[r(1383)][r(176)+"e"](l=>{let h=r;this.emit(s.Mupmw,s[h(914)](Wl,s[h(1440)],{...l}))}),this[r(1383)][r(1294)](l=>{let h=r;this[h(788)](h(1173),s[h(914)](Et,s.CaXGs,{...l,message:l[h(1254)]||""}))})}send(r){let s=t,l={gmiLE:e[s(1390)]};if(r instanceof Uint8Array){let h=r[s(1135)][s(1106)](r[s(1302)+"et"],r.byteLength+r[s(1302)+"et"]);this._socket&&this[s(1383)][s(434)]({data:h,fail:_=>{let b=s;this[b(788)](l.gmiLE,Et(l.gmiLE,{message:this["_formatE"+b(1214)+"age"](_)}))}})}else this[s(1383)]&&this[s(1383)].send({data:r,fail:h=>{let _=s;this.emit(e[_(1390)],e[_(1364)](Et,e.tMLgA,{message:this[_(923)+_(1214)+_(324)](h)}))}})}[t(1212)](r,s){let l=t;this[l(1383)]&&this[l(1383)][l(1212)]({code:r,reason:s})}["addEvent"+t(913)](r,s){this.on(r,s)}["removeEv"+t(421)+t(1557)](r,s){this[t(1430)](r,s)}get[t(655)+"te"](){let r=t;return this[r(1383)][r(655)+"te"]}get binaryType(){let r=t;return this._socket[r(663)+"pe"]}set binaryType(r){}get url(){let r=t;return this[r(1383)][r(1060)]}get[t(1319)](){let r=t;return this._socket[r(1319)]}get[t(223)+"ns"](){let r=t;return this[r(1383)][r(223)+"ns"]}get["buffered"+t(1455)](){let r=t;if(e[r(1108)](e[r(1371)],e[r(1371)]))FvCbfE[r(238)](_0x566a5e),FvCbfE.MwWhk(_0x11dc78);else return 0}}function Yg(c,r){let s=t;if(e[s(857)](e.SiPCR,e.cfPQh)){if(r)return new r(c[s(1060)],c[s(1319)]);if(e.Spyqd(bi,Wn))return new Zg(c[s(1060)],c[s(1319)],c[s(966)]);if((Sr||Ei)&&e[s(330)](e[s(1107)],typeof WebSocket)&&WebSocket)return new WebSocket(c[s(1060)],c[s(1319)+"s"])}else{this[s(1243)+"WebSocket"]();let l=e[s(517)](_0x13a6d9,s(616)+"t",{message:e[s(1387)]});this[s(362)+s(210)+s(1481)+"ct"]&&this[s(362)+"mediatelyReconnect"](l)}}function Xg(c){let r=t;if(e.COxpH(r(260),e.QyIHC))return _0xcdc9a9[r(483)+"t8"]?_0x4a5380[r(483)+"t8"](_0x1b750c,_0x4e5c71):_0x4d8d70[_0x21086f]=255&_0x279a7c,e[r(1125)](_0x14bde1,1);{let s=e[r(1143)][r(496)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(bi&&wx["connectS"+r(1574)])return!0;continue;case"1":if(c)return!0;continue;case"2":if(e[r(1472)](Sr,Ei)&&e.RpkKy(r(505)+"d",typeof WebSocket)&&WebSocket)return!0;continue;case"3":if(Wn&&tt["connectS"+r(1574)])return!0;continue;case"4":return!1}break}}}function Vl(c,r,s){let l=t,h={ipTVD:function(I,m){return e.pNeeQ(I,m)},kxJXZ:e.NAtDT,hZlot:function(I,m){return e[$(1231)](I,m)},dbCbt:function(I,m){return e[$(1500)](I,m)}},_=-1;async function b(I){let m=$;return h[m(1103)](I,_)?Promise[m(1221)](new Error(h[m(634)])):(_=I,h.hZlot(I,s[m(1393)])?Promise.resolve():s[I][m(239)](c)(r,b[m(239)](null,h[m(161)](I,1))))}e[l(1432)](b,0)}function Jl(c){let r=t,s=0,l=0;for(let h=0;h<c[r(1393)];++h)l=c.charCodeAt(h),e.hIkPQ(l,128)?s+=1:e[r(1150)](l,2048)?s+=2:e[r(1096)](64512,l)===55296&&(64512&c.charCodeAt(e[r(581)](h,1)))===56320?(++h,s+=4):s+=3;return s}function Zl(c,r,s){let l=t;if(e.RwxNh(e[l(557)](s,r),1))return"";let h="";for(let _=r;_<s;){let b=c[_++];if(e.pNeeQ(b,127))h+=String[l(1563)+l(489)](b);else if(e[l(992)](b,192)&&e[l(525)](b,224))h+=String[l(1563)+l(489)](e[l(1564)](e[l(893)](e[l(394)](31,b),6),63&c[_++]));else if(b>=224&&e[l(183)](b,240))h+=String.fromCharCode(e[l(205)](e[l(728)](15,b),12)|e[l(795)](e[l(900)](63,c[_++]),6)|63&c[_++]);else if(e[l(845)](b,240)){let I=e[l(1380)](e[l(986)](e[l(540)](e[l(307)](7,b),18),e[l(1054)](63,c[_++])<<12)|e[l(751)](e.IRIxD(63,c[_++]),6)|e.kuxGc(63,c[_++]),65536);h+=String[l(1563)+l(489)](55296+e[l(461)](I,10)),h+=String[l(1563)+l(489)](e[l(847)](56320,e[l(395)](1023,I)))}}return h}function Ja(c,r,s){let l=t,h={FyLfl:function(_,b){return e[$(732)](_,b)},sfcBK:function(_,b){return _-b},ItoDl:function(_,b){return _+b},Cvuep:function(_,b){return e.dOYVf(_,b)}};if(e[l(333)](e[l(615)],l(1059))){let _=s,b,I;for(let m=0;m<c[l(1393)];++m)if(e.gDDbL!==e[l(1434)])if(b=c[l(727)+"At"](m),e[l(111)](b,128))r[s++]=b;else if(e[l(764)](b,2048))if(e.cbGTX(e[l(1047)],e[l(1047)])){let O=_0x2fa6da[l(496)](":");_0x5e67ee&&(_0x118842=O[l(1393)]),_0x53dc5d+=O[l(1393)];for(let L=0;L<O.length;L++)if(InNprv[l(1443)](4,O[L].length)){let F=_0x5684b5.substring(0,InNprv[l(167)](4,O[L].length)),V=F[l(754)](O[L]);_0x28470a[l(1544)](V)}else _0x349a94.push(O[L]);_0x1b7b73=!1}else r[s++]=e.DpgTX(b,6)|192,r[s++]=e.kuxGc(63,b)|128;else if(e[l(1518)](e[l(137)](64512,b),55296)&&e[l(1099)](e[l(366)](64512,I=c[l(727)+"At"](e.eWZWx(m,1))),56320)){let O=e.bUhEx[l(496)]("|"),L=0;for(;;){switch(O[L++]){case"0":r[s++]=e[l(518)](e[l(612)](e.ueqGE(b,6),63),128);continue;case"1":r[s++]=e[l(1590)](b>>18,240);continue;case"2":b=e.vnDPg(e[l(526)](65536,e[l(1490)](e.FbYKT(1023,b),10)),1023&I);continue;case"3":r[s++]=e.NhpaV(63&b,128);continue;case"4":++m;continue;case"5":r[s++]=e.YcxTS(e[l(1501)](e[l(461)](b,12),63),128);continue}break}}else if(e[l(603)]!=="vqjEh")r[s++]=e[l(1378)](e[l(1207)](b,12),224),r[s++]=e.OzKhW(e[l(570)](e[l(417)](b,6),63),128),r[s++]=e[l(1509)](e[l(395)](63,b),128);else return InNprv[l(1549)](InNprv[l(464)](_0x324122,4)[l(1316)]("0"),_0xa91710(_0x2e6d3e,2)[l(1250)](16)).slice(-4);else this[l(157)]?.[l(312)](_0x592473.message_id);return s-_}else _0x94b58f[_0x500010++]=e[l(1509)](e[l(491)](_0x4d748d,12),224),_0x72608[_0x44b2a7++]=e.mnhxB(_0x1ec090>>6,63)|128,_0xa6969d[_0x154718++]=e[l(1175)](e.wInTK(63,_0x57ce4e),128)}async function Yl(c){let r=t;if(e[r(717)](e[r(1338)],typeof c)){let s=new Uint8Array(Jl(c));return Ja(c,s,0),s}return e[r(393)](c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c[r(1135)],c[r(1302)+"et"],c[r(901)+"th"])}function Qg(c){let r=t;try{if(e[r(602)](e[r(1051)],r(1354)))return e[r(212)](r(1476),typeof c)&&(e[r(1077)](c,ArrayBuffer)||c[r(1135)]&&e[r(1554)](c.buffer,ArrayBuffer))||e.RpkKy(e[r(1338)],typeof c)?"":(JSON[r(672)](c),e[r(1182)]);FvCbfE[r(589)](_0x18021e,_0x63520(_0x5927cf[r(1032)])),FvCbfE[r(725)](_0x3e11e8)}catch{return e[r(1193)]("string",typeof c)?e[r(872)]:""}}let em=(c,r)=>{let s=t;switch(c){case s(979):case e[s(1477)]:return{["x-use-"+c]:1,"x-tt-env":r};default:return{}}};class tm{constructor(r){let s=t;this[s(1098)+s(631)]=r,this[s(194)]=0}[t(863)](){let r=t;this[r(194)]++}[t(1486)+"chMaxCount"](){let r=t;if(e[r(1436)](r(930),r(930)))return e[r(164)](this[r(194)],this[r(1098)+"ount"]);{if(e[r(1480)](_0x959360,_0x3a15cb)<1)return"";let s="";for(let l=_0x548535;e[r(1073)](l,_0x478165);){let h=_0x54ce00[l++];if(e.AREbF(h,127))s+=_0xbad5a[r(1563)+r(489)](h);else if(h>=192&&e.JNgTn(h,224))s+=_0xc5be2.fromCharCode(e.NQWxv(e[r(932)](31,h),6)|e[r(297)](63,_0x3a52d0[l++]));else if(h>=224&&e[r(952)](h,240))s+=_0x3e64b5.fromCharCode(e[r(498)](e[r(120)](e[r(1264)](15,h)<<12,e[r(1490)](e.VuSmy(63,_0x24332a[l++]),6)),e[r(647)](63,_0x308eae[l++])));else if(h>=240){let _=e.hzluP(e[r(934)](e[r(1134)](e[r(665)](7,h),18),e[r(247)](63&_0x19fffe[l++],12))|e[r(1222)](e.zEgXW(63,_0x3b2b15[l++]),6),e.vMCKC(63,_0x52f558[l++]))-65536;s+=_0x2847f9[r(1563)+"Code"](e[r(241)](55296,e[r(1207)](_,10))),s+=_0x33126d[r(1563)+r(489)](e[r(136)](56320,1023&_))}}return s}}[t(542)+t(974)](r=0){let s=t;this["maxLossC"+s(631)]=r,this[s(194)]=0}}async function nm(c){let r=t,s={uoPEp:function(l,h){return l(h)},ubvum:e.SxpcR,aGXRN:function(l,h){return l(h)},RaJdF:r(1225),amcnG:r(694)+r(352),yfZCR:e.PVjrR,SjmKq:r(1497)};return new Promise(l=>{let h=r;if(!Sr)return s.aGXRN(l,h(876)+h(474));try{let _=document[h(859)+"ement"](s[h(1236)]);window[h(668)+"JSONP"]=b=>{let I=h;document[I(997)][I(303)+"ild"](_),window["frontier"+I(1488)]=void 0,s[I(587)](l,b&&b.msg||s[I(706)])},_[h(1313)]=s[h(1570)],_.src=c[h(1149)](/^ws/,s[h(552)])+(h(591)+h(1126)+h(1041)+"P");try{document[h(997)]["appendCh"+h(1473)](_)}catch{document.body[h(303)+h(1473)](_)}}catch{h(158)!==s[h(1375)]?(window["frontier"+h(1488)]=void 0,l("unknown "+h(474))):this["flushExp"+h(998)]()}})}function Sn(c,r,s){let l=t;return!!c?.[l(149)](h=>h[l(446)]===r&&h[l(156)]===s)}function Ir(c,r){let s=t;return c?.[s(149)](l=>l[s(446)]===r)?.[s(156)]}let Za=null;async function rm(){let c=t;return Za||(Za=Promise[c(1578)]().then(en[c(239)](en,e[c(1116)]))),Za}class im extends Va{constructor(r,s){let l=t;super(),this._dbName=r,this._keyPath=s,this._qosDB=void 0,this[l(595)+l(1140)]=null}async[t(283)](){await this[t(917)]()}async[t(917)](){let r=t;if(!this._qosDB){if(this[r(595)+r(1140)])return this[r(595)+r(1140)];try{if(e[r(658)](e[r(116)],e.ODdUc)){let s=this[r(1561)],l=this[r(1482)];this[r(595)+"mise"]=(async()=>{let h=r,_={qiwRQ:e[h(1e3)],WeFON:function(b,I,m,O){return e.NiDvv(b,I,m,O)},VQuJt:function(b,I){return b+I}};if(e[h(188)](e[h(747)],h(1342))){let{openDB:b}=await rm();this._qosDB=await e[h(1562)](b,h(668)+"_"+s,1,{upgrade(I){let m=h;I[m(1451)+m(404)+"e"](s,{keyPath:l})}})}else{if(_0x545651>_0x2f8bbb)throw new _0x5a6c64(_[h(1035)]);let b=3;for(;b>=0;){let I=255&_0x18a7e6;_.WeFON(_0x177c61,I,_0x337105,_[h(326)](_0x4a4c15,b)),_0x4c1db2>>>=8,b--}return _[h(326)](_0x5197d6,4)}})(),await this[r(595)+r(1140)]}else _0x26eece=_0x168170(_0x549617)}catch(s){console[r(724)](s)}finally{if(e[r(919)](e.Zsbhe,e[r(667)]))this[r(595)+r(1140)]=null;else return this[r(157)]?.isReady}}}async get(r){let s=t;try{return await this[s(917)](),this[s(157)]?.[s(131)](this[s(1561)],r)}catch(l){console.log(l)}}async[t(423)](r,s){let l=t;return await this[l(917)](),this[l(157)]?.[l(1523)](this[l(1561)],r)}async[t(312)](r){let s=t;try{return await this[s(917)](),this[s(157)]?.[s(956)](this[s(1561)],r)}catch(l){console[s(724)](l)}}async[t(1582)](){let r=t;try{return await this[r(917)](),this[r(157)]?.[r(1582)](this[r(1561)])}catch(s){if(e.QgCFu(e[r(882)],e[r(882)]))try{this[r(157)]?.[r(1212)](),this._qosDB=void 0}catch(l){_0x596285[r(724)](l)}else console.log(s)}}async[t(960)](){let r=t;return await this[r(917)](),this[r(157)]?.[r(1317)+"ys"](this[r(1561)])}async getAll(){let r=t,s={mPkUY:function(l,h){return l||h},CvHTo:function(l,h){return e[$(590)](l,h)},pCgvb:e[r(1107)]};if(e[r(674)](e[r(407)],r(1256)))return await this[r(917)](),this[r(157)]?.[r(1031)](this[r(1561)]);if(_0x18d3d7)return new _0x373d5a(_0x5122bc[r(1060)],_0xbb8937[r(1319)]);if(lNlWUI.mPkUY(_0x4461d6,_0x184af1))return new _0x25ba96(_0x22059d.url,_0x41fbab[r(1319)],_0x6732a8[r(966)]);if(lNlWUI[r(880)](_0x105d23,_0x594dda)&&lNlWUI[r(608)](lNlWUI.pCgvb,typeof _0x45a71a)&&_0x1db281)return new _0x35a6c4(_0x589681.url,_0x5becbc.protocols)}async[t(801)](){try{this._qosDB?.close(),this._qosDB=void 0}catch(r){console.log(r)}}get isReady(){let r=t;try{if(e[r(942)](e[r(813)],r(939)))return!!this[r(157)];this[r(982)](r(1465),_0x4fd663[r(1080)]),e[r(355)](_0x2e8d22)}catch(s){return console[r(724)](s),!1}}}class sm{constructor(r,s){let l=t;this._DBName=r,this[l(1408)]=s,this[l(157)]=localStorage}async[t(283)](){}get _prefix(){return"frontier_"+this[t(1483)]}async get(r){let s=t,l=this[s(157)][s(328)](this._prefix);return JSON.parse(e.Spyqd(l,"{}"))[r]}async set(r,s){let l=t,h=this[l(157)][l(328)](this[l(1246)]),_=JSON[l(672)](e[l(1472)](h,"{}"));return _[s||r[this[l(1408)]]]=r,this._qosDB[l(970)](this[l(1246)],JSON[l(250)+"y"](_)),s||r[this._pathKey]}async[t(312)](r){let s=t,l=this._qosDB.getItem(this._prefix),h=JSON[s(672)](l||"{}");return h[r]=void 0,this._qosDB[s(970)](this[s(1246)],JSON[s(250)+"y"](h))}async[t(1582)](){let r=t;if(e[r(1577)]!=="JXFZD")return this._qosDB[r(1582)]();{let s=0,l=0,h;do h=e[r(441)](_0x58737a,_0x3c7f72),e[r(701)](s,32)&&(l|=e[r(247)](e[r(1167)](127,h),s)),s+=7;while(e[r(1433)](128,h));return l}}async[t(960)](){let r=t;if(e[r(925)](e[r(435)],e[r(435)])){let l=this[r(157)][r(328)](this[r(1246)]),h=JSON.parse(l||"{}");return Object[r(960)](h)}else for(var s in _0x59de3a)_0x59e9db.o(_0x4df5a6,s)&&!_0x29d694.o(_0x65538c,s)&&_0x391256[r(716)+"operty"](_0x579b6f,s,{enumerable:!0,get:_0xeaf383[s]})}async[t(1031)](){let r=t,s=this[r(157)][r(328)](this[r(1246)]),l=JSON[r(672)](s||"{}");return Object[r(311)](l)}[t(801)](){return Promise[t(1578)]()}get[t(838)](){return!!this._qosDB}}class om{constructor(r,s){let l=t;this[l(1483)]=r,this._pathKey=s,this[l(157)]=Wn?tt:bi?wx:null}async[t(283)](){}get[t(1246)](){return t(668)+"_"+this._DBName}async[t(131)](r){let s=t;if(e[s(1518)](e[s(376)],e.Yahib)){let l=this[s(157)][s(1589)+"geSync"](this[s(1246)]);return JSON[s(672)](l||"{}")[r]}else return _0x12f153(_0x4a7511.apply(FvCbfE[s(589)](_0x59ec58,this),_0x3e8a9d))}async[t(423)](r,s){let l=t;if(e[l(1518)](e[l(1286)],e[l(1286)])){let h=this[l(157)][l(1589)+"geSync"](this[l(1246)]),_=JSON[l(672)](e[l(1472)](h,"{}"));return _[s||r[this[l(1408)]]]=r,this[l(157)][l(361)+l(1152)](this._prefix,JSON[l(250)+"y"](_)),s||r[this._pathKey]}else{let h=new _0x4574f3(_0x50f482(_0x42d3b2));return e[l(1562)](_0x7657bf,_0x3bcc34,h,0),h}}async del(r){let s=t,l=this[s(157)][s(1589)+s(1152)](this[s(1246)]),h=JSON[s(672)](l||"{}");return h[r]=void 0,this[s(157)]["setStora"+s(1152)](this._prefix,JSON[s(250)+"y"](h))}async[t(1582)](){let r=t;return this[r(157)][r(1065)+r(787)]()}async[t(960)](){let r=t;if(e.VOnBg(e[r(560)],e[r(560)])){let s=this[r(157)][r(1589)+r(666)+"nc"](this[r(1246)]),l=JSON[r(672)](e[r(480)](s,"{}"));return Object.keys(l)}else return this[r(1383)][r(1060)]}async[t(1031)](){let r=t,s=this[r(157)][r(1589)+r(666)+"nc"](this[r(1246)]),l=JSON.parse(s||"{}");return Object[r(311)](l)}[t(801)](){return Promise.resolve()}get[t(838)](){return!!this[t(157)]}}function Xl(c,r){let s=t,l={ZNjZh:function(h,_,b){return e.QBSud(h,_,b)},Uhirj:function(h,_){return e[$(967)](h,_)}};if(e[s(823)](e[s(477)],s(896))){let h=HtmMkW[s(1044)](_0x3f7d4f,_0x24e50d,_0x5f4820);return _0x18b6b6[s(637)][s(129)](h,HtmMkW[s(955)](h,_0x3a11c6))}else{if(Wn||Wn)return new om(c,r);if(e[s(1472)](Sr,Ei)&&typeof indexedDB<"u")return new im(c,r);if(e[s(1472)](Sr,Ei)&&e[s(284)](s(505)+"d",typeof localStorage))return new sm(c,r);throw new Error(e.CbKvB)}}class am{constructor(){let r=t;if(e.WbzMy(e[r(398)],e[r(1042)]))this["_interva"+r(499)+"Id"]=null,this[r(740)+"l"]=36e5,this[r(157)]=e[r(345)](Xl,r(607),e[r(300)]);else return this[r(1091)]?this[r(1091)][r(1319)]:""}async[t(740)+t(584)](){let r=t;clearInterval(this["_interva"+r(499)+"Id"]),this[r(740)+r(499)+"Id"]=e[r(105)](setInterval,()=>{let s=r;this[s(490)+s(998)]()},this[r(740)+"l"])}async[t(283)](){let r=t;await this._qosDB[r(283)]()[r(305)](()=>{let s=r;this[s(740)+s(584)]()})}async["flushExp"+t(998)](){let r=t,s={PuWSa:function(_,b){return e.xvuhl(_,b)},bKLbo:function(_,b){return e[$(759)](_,b)},FodhL:e[r(1001)]};(await this[r(157)]?.[r(1031)]()||[])[r(1136)](({timestamp:_})=>_<Date[r(1156)]())[r(1521)](_=>{let b=r;s.bKLbo(s[b(1162)],s.FodhL)?(s.PuWSa(_0x3dcf92,this[b(1191)+b(1394)+"utId"]),this[b(1191)+b(1394)+b(230)]=null):this._qosDB?.[b(312)](_.message_id)})}async[t(312)](r){let s=t,l={ACbLH:function(h,_,b){return e[$(546)](h,_,b)}};if(e[s(1542)](e[s(185)],e[s(185)]))GSmzDK[s(1215)](_0x4aab70,_0x7b0fbd,50),_0x19a168(_0x36fc04,_0x389405);else return this[s(157)]?.[s(312)](r)}async[t(423)](r,s){return this[t(157)]?.set({message_id:r,timestamp:s})}async get(r){let s=t;return this._qosDB?.[s(131)](r)}async closeDB(){let r=t;e[r(244)](clearInterval,this[r(740)+r(499)+"Id"]),await this._qosDB?.[r(801)]()}get isReady(){return this._qosDB?.isReady}}function Ya(c){let r=t,s=!!this._options.enableQoS;if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(1158)](Sn,c[r(1080)][r(966)],e[r(951)],"2"),h=l&&e[r(1562)](Sn,c[r(1080)][r(966)],e.irZOL,"1"),_=l&&e[r(145)](Sn,c[r(1080)][r(966)],e[r(410)],"1"),b=_?e[r(1178)](Ir,c[r(1080)][r(966)],e[r(865)])?.split(",")[r(1136)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:_,ackMsgIds:b}}async function Ql(){let c=t;return this[c(842)+c(152)]||(this[c(842)+c(152)]=new am),this["_QoSMana"+c(152)][c(838)]||await this["_QoSMana"+c(152)][c(283)](),this[c(842)+"ger"]}async function cm(c,r){let s=t,{enableAutoAck:l}=this[s(495)],h=e[s(145)](Sn,c[s(1080)][s(966)],e.XtJdX,"1"),_=Sn(c[s(1080)].headers,"is_ack","1"),b=Ya[s(894)](this,c);if(e[s(1085)](l,h)){let{SeqID:I,LogID:m,service:O,LogIDNew:L,method:F}=c[s(1080)];this[s(108)]({SeqID:I,LogID:m,LogIDNew:L,service:O,method:F,headers:[{key:e[s(545)],value:"1"},{key:e.RkRGB,value:e.KFkBZ(L,"")},{key:e[s(1435)],value:"0"}]})}_&&!b[s(1389)]&&this[s(946)+s(289)+s(840)](c),r()}async function dm(c,r){let s=t;this[s(982)](e.WjcPI,c[s(1080)]),e.MwWhk(r)}async function lm(c,r){let s=t,l=e[s(1468)](Ut,await Yl(c[s(1263)]));try{if(e[s(1554)](l[s(971)],Uint8Array)){if(e.shDAG(e.AtXGC,"QXvTd"))return this[s(157)][s(1065)+s(787)]();{let h=e[s(393)](this._options["payloadE"+s(1361)],Object)?{force:!!this[s(495)][s(776)+"ncoding"][s(1255)],encoding:this[s(495)][s(776)+s(1361)][s(422)]?this._options[s(776)+s(1361)].encoding[s(1149)](/\s/g,"")["toLowerC"+s(1528)]():""}:{force:!1,encoding:this[s(495)].payloadEncoding?this[s(495)][s(776)+s(1361)][s(1149)](/\s/g,"")["toLowerC"+s(1528)]():""},_=l[s(776)+s(1361)]?l["payloadE"+s(1361)][s(1149)](/\s/g,"")[s(1406)+s(1528)]():"",b=e[s(341)](this[s(495)][s(337)+s(1024)],Object)?{force:!!this._options[s(337)+s(1024)][s(1255)],type:this[s(495)][s(337)+s(1024)][s(1313)]?this[s(495)]["payloadT"+s(1024)].type[s(1149)](/\s/g,"")[s(1406)+s(1528)]():""}:{force:!1,type:this._options[s(337)+"ype"]?this[s(495)][s(337)+"ype"][s(1149)](/\s/g,"")[s(1406)+"ase"]():""},I=l[s(337)+s(1024)]?l[s(337)+s(1024)][s(1149)](/\s/g,"")["toLowerC"+s(1528)]():"",m=b[s(1255)]?b[s(1313)]:I||b[s(1313)],O=h.force?h.encoding:_||h.encoding,L=[s(1245)+"in;chars"+s(1241),e.ehIDn,s(534)+"ion/json"+s(487)+s(1569),e.SUTRf],F=[e[s(453)],e[s(702)]];this._options.enableTransformTextPayload&&L[s(1270)](m)&&(!O||F.includes(O))?l[s(1449)+s(1261)]=e[s(708)](Zl,l.payload,0,l.payload[s(901)+"th"]):l["textPayl"+s(1261)]=""}}else l[s(1449)+s(1261)]=""}catch(h){l[s(1449)+s(1261)]="",console[s(724)](h)}c[s(1080)]=l,r()}function um(c,r,s){let l=t,h=e[l(339)](s,8192),_=e[l(253)](h,1),b=null,I=h;return function(m){let O=l;if(e[O(1150)](m,1)||e[O(259)](m,_))return e[O(651)](c,m);I+m>h&&(b=c(h),I=0);let L=r.call(b,I,I+=m);return e.bRmiA(7,I)&&(I=e.jSzEp(e[O(127)](7,I),1)),L}}let fm=4294967295;function hm(c,r,s){let l=t;return e[l(1260)](RangeError,e[l(1500)](e[l(1370)](e[l(886)](e[l(821)](e[l(847)](e[l(397)],c),l(551)),e[l(340)](r,1)),l(873)),s))}function pm(c,r,s){let l=t;if(e[l(1234)](l(1189),e[l(565)])){let{initReconnectInterval:h,maxReconnectInterval:_,reconnectIntervalGrowFactor:b}=this[l(495)],I=e[l(1115)](h,_0x4f8cf6[l(298)](b,e[l(1420)](_0x146b7c,1)));return e[l(248)](I,_)?_:I}else{if(e[l(259)](s,fm))throw new Error("integer "+l(791)+"e");let h=3;for(;h>=0;){let _=e[l(1110)](255,s);e.HnpMz(Qa,_,c,e.hRMQa(r,h)),s>>>=8,h--}return r+4}}function xm(c,r){let s=t,l={lWJgJ:e.TlHGB};if(e[s(1575)](e[s(1422)],s(529))){let h=0,_=r,b=r+4;for(;e.ONHpF(_,b);){let{value:I,offset:m}=e[s(1546)](Xa,c,_);_=m,h=e[s(1445)](e.tUCLv(h,8),0),h+=I}return{value:h,offset:b}}else this[s(788)](eeXpND[s(768)],_0x127aaa(eeXpND[s(768)],{..._0x1f8045}))}function gm(c,r,s){let l=t;return c?e.hIkPQ(c[l(1393)],40)?e[l(1158)](Ja,c,r,s)+s:r[l(1426)+"e"]?e.MHnUd(r[l(1426)+"e"](c,s),s):r[l(1442)]?r[l(1442)](c,s)+s:e[l(680)](e[l(1562)](Ja,c,r,s),s):s}function mm(c,r){let s=t,l=new de(e.ybLuX(e[s(113)](e.nNcDy(c[r+4],24),e[s(750)](c[e[s(1119)](r,5)],16))|c[e.nEHlF(r,6)]<<8,c[e.hRMQa(r,7)]),e[s(618)](e[s(1411)](e[s(226)](c[e[s(640)](r,0)],24),e[s(1222)](c[r+1],16)),e[s(563)](c[r+2],8))|c[e.Wdpwh(r,3)],!0);return r+=8,{value:l,offset:e.QvVFk(r,8)}}function wm(c,r,s){let l=t,h=c[l(1515)],_=c[l(1565)];return r[s]=_>>>24,r[e.zMAVQ(s,1)]=e[l(264)](_>>>16,255),r[e[l(1037)](s,2)]=e[l(927)](e[l(989)](_,8),255),r[e[l(390)](s,3)]=255&_,r[s+4]=h>>>24,r[e[l(187)](s,5)]=e[l(1416)](e.aFWuk(h,16),255),r[e[l(473)](s,6)]=e[l(1170)](e[l(988)](h,8),255),r[e[l(629)](s,7)]=e[l(695)](255,h),s+=8,s}function Xa(c,r){let s=t;return c[s(387)+"8"]?{value:c[s(387)+"8"](r),offset:e[s(136)](r,1)}:{value:e[s(825)](255,c[r]),offset:e[s(1190)](r,1)}}function Qa(c,r,s){let l=t;return r[l(483)+"t8"]?r[l(483)+"t8"](c,s):r[s]=e.lDEjV(255,c),e[l(472)](s,1)}let _m=function(c){return new Uint8Array(c)},ym=e.NyQCZ!=typeof Buffer?Buffer[t(972)+t(427)]:e[t(964)](um,_m,Uint8Array[t(294)+"e"][t(129)]),bm=16,ec=32;function Em(c){let r=t,s=0,l={};for(let h=0;e[r(460)](h,c[r(1393)]);h++)l[c[h][r(868)+"ame"]]=e[r(846)](Jl,c[h][r(868)+r(274)]),s+=e[r(189)](14,l[c[h]["cursor_n"+r(274)]]);return[s,l]}function eu(c,r,s){let l=t,h={iWQEt:function(O,L,F,V){return e[$(225)](O,L,F,V)},BNDKb:e[l(510)],CkSEx:function(O,L,F,V){return e[l(885)](O,L,F,V)},PFGbP:e.RwOXp,fCuTD:function(O,L,F,V){return e[l(145)](O,L,F,V)},TzJZN:l(107),migCM:e[l(1224)]},[_,b]=Em(c),I=e.lDvsa(ym,_),m=0;return c[l(1521)](O=>{let L=l;console[L(724)](L(973)+L(329),O,O.service),m=h[L(447)](Qa,0,I,m),console[L(724)](h[L(147)],m),m=h[L(1463)](pm,I,m,O[L(689)]||0),console[L(724)](h.PFGbP,m),m=h[L(447)](Qa,b[O[L(868)+L(274)]],I,m),console[L(724)](L(168)+L(107),m),m=h[L(1462)](gm,O[L(868)+L(274)],I,m),console[L(724)](h[L(734)],m),m=h[L(1462)](wm,de.fromNumber(O.cursor||r),I,m),console[L(724)](h[L(1081)],m)}),{frameType:ec,headers:[{key:l(1112)+"ile_name",value:s}],payload:I}}function vm(c){let r=t,s=0,l=[];for(;e.RwxNh(s,c[r(901)+"th"]);){if(e[r(1298)](r(285),e[r(976)]))return _0x58d722|=0,{low:_0x20c5b2,high:e[r(461)](_0x24e084,31),unsigned:e.fluuq(_0x1c90db,0)};{let{offset:h}=Xa(c,s);s=h;let _={cursor_name:"",cursor:0,service:0},{value:b,offset:I}=e[r(814)](xm,c,s);_[r(689)]=b,s=I;let{value:m,offset:O}=Xa(c,s);s=O,_.cursor_name=e[r(708)](Zl,c,s,e[r(961)](s,m)),s+=m;let{value:L,offset:F}=e[r(1546)](mm,c,s);_[r(263)]=L[r(943)](),s=F,l[r(1544)](_)}}return l}function Sm(){let c=t;if(e.NZszm(c(173),e[c(594)])){let{type:r}=_0x265f8b;this[c(788)](r,_0x4b162e)}else return{frameType:ec,headers:[{key:e[c(240)],value:e[c(349)]}],payload:void 0}}class Im{constructor(r,s,l){let h=t;if(e[h(1520)](e[h(198)],e[h(681)]))this[h(1213)+h(991)]=r,this[h(538)+h(1104)]=s,this[h(1351)+h(962)]=l,this[h(157)]=Xl(this[h(1213)+h(991)],e[h(1367)]);else{let _=_0x380da0[h(637)],b=_0x3402d2[h(268)],I=_0x1f85a4[h(664)],m=e[h(357)](b,_0x429b24);if(m>_[h(1393)]){let O=new _0x2acafc(e[h(1115)](2,m));O[h(423)](_),_0x54d476[h(637)]=O}return _0x544e69[h(268)]=m,m>I&&(_0x581ea1[h(664)]=m),b}}async[t(283)](){let r=t;await this._qosDB[r(283)]()}async[t(582)+"rs"](){let r=t;if(!this[r(157)][r(838)])return;let s=this["_message"+r(962)],l=await this._qosDB.getAll();switch(console[r(724)](r(316)+r(673),l),s){case e.cajXG:return l&&l[r(1393)]?eu(l,0,this[r(538)+r(1104)]):void 0;case e[r(798)]:return;case e[r(1576)]:return l&&l[r(1393)]?e.rPRmK(eu,l,0,this["_cursorF"+r(1104)]):Sm()}}async set(r,s,l){let h=t;return console.log(e.PXQIU,r,s,l),this[h(157)][h(423)]({cursor_name:r,cursor:s,service:l})}async[t(1588)+"rs"](r){let s=t,l=vm(r);for(let h of l)console[s(724)](e.LcZLz,l),await this[s(157)].set(h)}async[t(131)](r){let s=t;return(await this[s(157)][s(131)](r))?.[s(263)]}async[t(801)](){let r=t;e[r(1531)](e[r(1410)],r(1003))?await this[r(157)].closeDB():(this[r(380)+r(1050)]?.addCount(),this.emit(r(1082)+r(622)+"t",e[r(957)]),this[r(380)+r(1050)]?.[r(1486)+"chMaxCount"]()?this["_handleR"+r(1341)]():this._ping())}[t(1089)+t(892)+t(729)](r){let s=t;e[s(1436)]("XqmnC",e.xtjpc)?(this[s(1351)+s(644)][s(436)](),this["_message"+s(644)][s(1544)](_0x340c34)):this["_cursorF"+s(1104)]=r}get isReady(){let r=t;return this[r(157)][r(838)]}}let Am=t(954)+t(1552);async function tu(c){let r=t;if(!this._options.enableQoS)return null;let{aID:s,fpID:l,messageStrategy:h}=this._options,_=c||Am;try{return this[r(1049)+"anager"]?c&&this["_cursorM"+r(1347)]["updateCu"+r(892)+r(729)](c):this[r(1049)+r(1347)]=new Im(l+"_"+s+"_"+_,_,h),this["_cursorM"+r(1347)].isReady||await this[r(1049)+"anager"].openDB(),this["_cursorM"+r(1347)]}catch{if(e[r(411)](e[r(1058)],e[r(1058)]))_0x30ffe3="wss://",_0x3b9414=_0x4210d1[r(1149)](/(^http)((?:[s]*:\/\/))/,""),_0xb63a5=/(^ws)((?:[s]*:\/\/))/[r(1166)](_0x482c07)?_0x477b32:""+_0x260e29+_0x506036;else return null}}async function km(c,r){let s=t,l={mzWzc:function(h,_){return e.YVAkU(h,_)}};if(e.JbCRf(s(1078),e[s(1336)])){if(this[s(856)+s(416)](),this[s(1478)+s(953)](),this["_removeW"+s(1142)+"rs"](),this[s(1030)+"nceClose"](1e3,_0x1ce854),this[s(1191)+"Lock"]=!1,_0x2f2316&&this["_navigat"+s(778)]()&&!this[s(1346)+s(1141)]){if(this[s(153)+s(1545)]?.[s(1486)+"chMaxTries"]()){let _=this[s(153)+"tManager"]?.[s(1188)+s(399)+"nt"]();this[s(946)+s(1327)+s(606)](e.jbNiQ(_0xb9045a,e[s(1048)],{code:1006,reason:s(1090)+_+(s(535)+s(1555)+s(733)+"ached"),wasClean:!0}))}else{let _=this[s(495)]["reconnec"+s(1386)+"ptor"](_0x4070ea,_0x2780d5);this[s(946)+"hCloseEv"+s(606)](_0x253529(e[s(1048)],{code:_0x573f52,reason:_0x3cdace,wasClean:!0,willReconnect:_})),_&&this._connect()}return}this["_navigat"+s(778)]()||this[s(1346)+"osed"]?this["_dispatc"+s(1327)+s(606)](e[s(354)](_0x49483a,e.PRFVH,{code:_0x2211cf,reason:s(569)})):this[s(946)+s(1327)+s(606)](e[s(1087)](_0x477346,e[s(1048)],{code:1006,reason:e[s(1004)]})),this[s(1091)]=null,this[s(153)+s(1545)]?.[s(1492)+"pointCon"+s(1020)](),this["_pingLos"+s(1050)]?.[s(542)+"nter"]()}else{let h=Sn(c[s(1080)].headers,e.ZFdYz,"-1"),_=e[s(1562)](Sn,c[s(1080)].headers,s(1216),"1"),b=e[s(1178)](Ir,c[s(1080)][s(966)],e[s(548)]),I=e[s(509)](Number,e[s(1458)](Ir,c.message.headers,e[s(1165)]))||0,m=Ya.call(this,c),O=e.ZfgMP(Sn,c[s(1080)][s(966)],e.YHPRM,"2"),L=Ir(c[s(1080)][s(966)],s(1487)+s(1218)+"e"),F=e[s(420)](Number,e[s(406)](Ir,c[s(1080)].headers,e.rUMHJ));if(m[s(1389)])return e[s(725)](r);let V=m[s(1329)+s(752)]?await Ql[s(894)](this):null;if(e[s(1187)](c[s(1080)][s(689)],0)&&_&&!h||c[s(1080)][s(689)]>0){if(b&&m[s(1329)+s(752)]&&V)return!!!await V[s(131)](b)&&(this[s(946)+s(777)+s(216)](c),await V[s(423)](b,e[s(1137)](Date.now(),I))),e[s(1232)](r);if(O){let X=await tu[s(894)](this);if(!X)return this[s(946)+s(777)+s(216)](c),e[s(797)](r);let J=await X[s(131)](L)??-1;if(J<F)if(e[s(1171)]!==e[s(1118)])this[s(946)+s(777)+s(216)](c),X[s(423)](L,F,c[s(1080)][s(689)]);else{let Me=new _0x3b54b7(ozisvz[s(944)](2,_0x311f2d));Me[s(423)](_0x4e893f),_0x4b5bbb[s(637)]=Me}else throw new Error(s(193)+" message"+s(1272)+F+(" larger than loc"+s(196)+"r ")+J);return r()}return this[s(946)+s(777)+s(216)](c),e[s(1274)](r)}}}async function Cm(c,r){let s=t,l=Ya.call(this,c);if(!l[s(1329)+s(752)])return e[s(797)](r);let h=await Ql[s(894)](this);if(l[s(550)+s(1271)+s(324)]&&l[s(106)+"s"][s(1393)])for(let _ of l[s(106)+"s"])await h[s(312)](_);e[s(1274)](r)}async function Tm(c,r){let s=t,l=e[s(1391)](c.message[s(827)+"e"],bm),h=e[s(271)](c[s(1080)][s(827)+"e"],ec);if(e[s(1085)](!l,!h))return e[s(355)](r);let _=Ir(c[s(1080)][s(966)],"cursor_file_name");if(!_)return e.qsuBN(r);let b=await tu[s(894)](this,_);if(!b)return e[s(1291)](r);if(l){let I=await b.getCursors(),m={frameType:I?.["frameType"],SeqID:de.fromNumber(this._seqId++),LogID:de[s(402)+"er"](this._options["logIDGen"+s(465)]()),service:9e3,method:5,headers:I?.[s(966)],payload:I?.[s(971)]},O=e[s(1432)](v,m);this[s(1091)]&&this[s(1091)][s(655)+"te"]&&this[s(1091)].send(O)}if(h){let I=c[s(1080)][s(971)];I&&b[s(1588)+"rs"](I)}}let Pm=async function(c,r){let s=t,l={Epawm:function(h,_){return h<_},OIexn:function(h,_){return e[$(1067)](h,_)},vKgPS:function(h,_){return e[$(1480)](h,_)}};if(e[s(470)](e.OTsKX,e[s(907)]))this[s(1335)]=!1,e.hDDwx(clearTimeout,this[s(1191)+s(1394)+"utId"]),r();else{let h=_0x3cf94b[s(496)](":");for(let _=0;lhiBVA[s(1439)](_,h[s(1393)]);_++){let b=h[_];if(lhiBVA[s(459)](4,h[_][s(1393)])){let I=_0x515aaf[s(1395)+"g"](0,lhiBVA[s(413)](4,h[_][s(1393)])),m=I[s(754)](b);_0x24afbc=_0x1506ce[s(754)](m)}else _0x2e933d=_0x46d7b5[s(754)](b)}return _0x273a88}},Rm=async function(c,r){let s=t,l={GtrQl:function(b,I){return b|I},OTDbB:function(b,I){return e.EpcAC(b,I)},xJzvM:function(b,I){return e[$(415)](b,I)},LUJZk:function(b,I){return b<<I},WsaZK:function(b,I){return e[$(862)](b,I)}};if(!this._ws||e[s(201)](this._ws.readyState,this[s(1109)]))return e[s(1381)](r);let{pingInterval:h}=this._options;this[s(153)+s(1545)]?.[s(1492)+"pointConfig"]();for(let b=0;e[s(1197)](b,this[s(1351)+s(644)][s(1393)]);b++){if(e[s(1019)](e[s(1220)],e[s(1220)]))return new _0x40f725(jCJkew.GtrQl(jCJkew[s(118)](_0x417a2e[0],_0x9aeff5[1]<<8)|jCJkew.xJzvM(_0x1288fc[2],16),jCJkew[s(920)](_0x50b717[3],24)),jCJkew[s(262)](jCJkew[s(118)](jCJkew[s(118)](_0x330348[4],jCJkew[s(1484)](_0x2222c4[5],8)),jCJkew[s(920)](_0x2a9865[6],16)),jCJkew.xJzvM(_0x173c3e[7],24)),_0x1141c5);{let I=this["_message"+s(644)][b];if(e[s(211)](this._ws[s(655)+"te"],this[s(1109)])&&I!==null)this._ws&&this[s(1091)].send(I),this[s(1351)+s(644)][b]=null;else break}}this[s(1351)+s(644)]=this[s(1351)+"Queue"][s(1136)](b=>!!b),this[s(1269)+s(995)+"Id"]=e[s(288)](setTimeout,()=>this[s(794)](),h),this[s(946)+s(1160)+"nt"](c),this[s(452)+"er"]&&this._ws&&(this[s(1091)].binaryType=this[s(482)+s(1024)]);let _=this["_endpoin"+s(1545)]?.[s(1188)+s(399)+"nt"]();this[s(982)](s(1306)+_+s(200)),e[s(431)](r)},Dm=async function(c,r){let s=t,l=this[s(153)+"tManager"]?.[s(1188)+s(399)+"nt"]();this._debug(s(1306)+l),r()};class Om extends Va{constructor(r){let s=t,l={poiOk:function(I,m,O){return e[$(684)](I,m,O)},HZkxK:s(1173),oPYsG:function(I,m){return e.jZJNV(I,m)},DDkHZ:s(1212),AMfvw:function(I,m){return e.pcybQ(I,m)},tFOyy:e[s(133)],oOsxx:function(I,m){return e.kbSze(I,m)},LXBqu:function(I,m,O){return e[s(134)](I,m,O)},wdNxE:function(I,m,O){return I(m,O)},gKSyn:e[s(409)],RLYJx:e.xLbSB,IwfQa:function(I,m,O){return I(m,O)}};super(),this[s(1139)+s(1529)+s(549)]=!0,this[s(452)+"er"]=Sr,this._isNode=Jg,this[s(592)+"T"]=Wn,this._isMiniWX=bi,this[s(1063)+"r"]=Ei,this[s(1351)+s(644)]=[],this["_endpoin"+s(1545)]=null,this[s(1346)+s(1141)]=!1,this[s(482)+s(1024)]=e[s(536)],this[s(1191)+s(1398)]=!1,this[s(1191)+"ionTimeo"+s(230)]=null,this["_reconne"+s(685)+"tId"]=null,this["_pingPon"+s(995)+"Id"]=null,this[s(1147)]=0,this[s(1335)]=!1,this[s(933)]="",this[s(842)+s(152)]=null,this[s(1049)+"anager"]=null,this[s(380)+s(1050)]=null,this[s(202)+"ls"]="pbbp2",this[s(1229)]=3,this[s(721)+"NG"]=0,this.OPEN=1,this.CLOSING=2,this[s(233)]=I=>{let m=s;try{Vl(this,I,[Pm,Rm,Dm])}catch(O){let L=l[m(575)](Et,l[m(342)],{message:O[m(1080)],code:vn[m(1527)+"OR"],error:O});this[m(946)+"hErrorEv"+m(606)](L)}},this[s(908)+"ge"]=async I=>{let m=s,{pingInterval:O,pingFrequency:L}=this[m(495)];if((e[m(1211)]("hi",I[m(1263)])&&e[m(1348)](e.pfJVg,L)||e[m(154)](e[m(178)],L))&&(this[m(856)+m(416)](),this[m(788)](e[m(806)],e[m(583)]),this[m(1269)+m(995)+"Id"]=e[m(1548)](setTimeout,this[m(794)].bind(this),O)),!e[m(291)]("hi",I[m(1263)]))try{e.sviyL(Vl,this,I,[lm,cm,Cm,Tm,km,dm])}catch(F){let V=e.TGzzF(Et,m(1173),{message:F[m(1080)],code:vn[m(977)+m(935)],error:F});this[m(946)+m(1249)+"ent"](V)}},this[s(234)]=I=>{let m=s;if(e[m(411)](m(1005),e.ppozt))return this[m(170)+m(1479)]==this.endpoints.length?!0:fKmlop[m(1301)](this[m(454)+m(848)+m(748)+"t"],this[m(532)+"es"]);{let O=this[m(153)+m(1545)]?.[m(1486)+m(1295)+"es"](),L=this[m(153)+m(1545)]?.["getCurre"+m(399)+"nt"]();if(O&&!I[m(1080)]){let F="connect "+L+(" fail, m"+m(306)+m(843)+"ed");this[m(946)+"hErrorEvent"](e[m(1102)](Et,m(1173),{message:F,code:vn[m(528)+m(737)+"R"],error:I}));return}this._ws&&e[m(1511)](this[m(1091)][m(655)+"te"],this.OPEN)&&this["_disconn"+m(141)](),this[m(946)+m(1249)+m(606)](e[m(1368)](Et,e[m(1390)],{message:I[m(1080)],code:vn[m(383)+"RROR"],error:I}))}},this[s(367)]=async I=>{let m=s;this[m(1478)+m(953)](),this[m(856)+m(416)](),this[m(292)+"sListeners"](),this[m(1091)]=null,this[m(1191)+m(1398)]=!1;let O=this[m(153)+"tManager"]?.["checkRea"+m(1295)+"es"]();if(!O&&this[m(816)+"orOnline"]()&&!this[m(1346)+m(1141)]){let L=this[m(153)+m(1545)]?.[m(1188)+m(399)+"nt"](),F=this._options[m(616)+m(1386)+m(543)](I.code,I[m(474)]);this[m(946)+"hCloseEv"+m(606)](l.poiOk(Rt,l[m(598)],{code:1006,reason:I[m(474)]||m(899)+"ng faile"+m(639)+m(385)+m(1233)+"ame: "+L,willReconnect:F})),F&&this[m(1191)]();return}if(l[m(310)](1e3,I[m(506)])&&this[m(1346)+m(1141)]){this[m(946)+"hCloseEv"+m(606)](l[m(575)](Rt,l[m(598)],{code:1e3,reason:l[m(220)]})),this._endpointManager?.["resetEnd"+m(270)+"fig"](),this[m(380)+m(1050)]?.["resetCou"+m(974)]();return}if(l.AMfvw(1e3,I[m(506)])&&O){let L=this[m(153)+m(1545)]?.getCurrentEndpoint(),F=I[m(474)];F||(F=await l.oOsxx(nm,this[m(933)])),F=m(899)+m(1121)+m(429)+F+(m(853)+m(130))+L+(", max re"+m(733)+"ached"),this[m(946)+m(1327)+m(606)](l[m(1303)](Rt,l[m(598)],{code:I[m(506)],reason:F}));let V=m(1090)+L+(" fail, m"+m(306)+m(843)+"ed");this[m(946)+m(1249)+"ent"](l[m(508)](Et,l[m(342)],{message:V,code:vn["MAX_RETR"+m(737)+"R"]})),this[m(153)+m(1545)]?.["resetEnd"+m(270)+m(1020)](),this[m(380)+m(1050)]?.[m(542)+"nter"]();return}if(l[m(310)](1e3,I[m(506)])&&!I[m(474)])if(l[m(800)]!==l[m(1412)]){let L=this[m(153)+"tManager"]?.[m(1188)+m(399)+"nt"]();this[m(946)+m(1327)+m(606)](l[m(1011)](Rt,l.DDkHZ,{code:I.code,reason:m(899)+"ng failed, unknown reason, hostname: "+L})),this[m(153)+m(1545)]?.[m(1492)+m(270)+m(1020)](),this[m(380)+m(1050)]?.[m(542)+m(974)]();return}else this[m(1335)]=!1,_0x43359d(this[m(1191)+"ionTimeo"+m(230)]),_0x364c2f();this[m(946)+m(1327)+m(606)](I),this[m(153)+m(1545)]?.resetEndpointConfig(),this._pingLossCounter?.[m(542)+m(974)]()},this[s(443)]=null,this[s(1169)]=null,this[s(1217)+"e"]=null,this.onopen=null,this["onStartR"+s(1341)]=null,this[s(1079)+"eAck"]=null,this["onStopIm"+s(210)+s(1481)+"ct"]=null,this[s(1360)+s(1508)]=this._handleOnLine[s(239)](this),this[s(1360)+s(1493)]=this[s(1360)+s(1493)][s(239)](this),this[s(1276)+s(1093)]=this[s(1276)+s(1093)][s(239)](this),this["_handleP"+s(601)]=this._handlePageShow.bind(this),this[s(495)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e.ewyNm(1,0),service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:s(433),pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:s(177),env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:_}=r,b=Array[s(915)](h)?h:e[s(1328)](e[s(1338)],typeof h)?[h]:[];if(!b||e[s(291)](0,b[s(1393)]))throw new Error(e.jySpJ);if(!e.wJjOG(Xg,_))throw new Error(e[s(678)]);Object.assign(this[s(495)],r),this[s(153)+s(1545)]=new $l(b,this[s(495)][s(532)+"es"]),this._pingLossCounter=new tm(this[s(495)][s(1293)+"Count"]),this[s(495)][s(350)+s(1568)]&&(this[s(1335)]=!0,this[s(1191)]()),this._options[s(304)+s(720)+s(325)]&&(this[s(592)+"T"]||this[s(710)+"X"]?this[s(1074)+s(654)+s(1094)]():this[s(452)+"er"]&&this[s(774)+s(1591)+s(913)]())}["_handleO"+t(1508)](){let r=t;this._options[r(1043)+r(1550)+"nect"]||this[r(1346)+"osed"]||this["_handleR"+r(1341)]()}["_handleO"+t(1493)](){let r=t;this[r(1243)+r(1075)+"t"]();let s=e.oBWLk($a,e[r(1083)],{message:e[r(1387)]});this[r(362)+r(210)+"yReconnect"]&&this[r(362)+"mediatel"+r(1481)+"ct"](s)}[t(774)+t(1591)+t(913)](){let r=t;this[r(452)+"er"]&&window.addEventListener(r(1356),this[r(1360)+"nLine"]),this[r(452)+"er"]&&window[r(1560)+r(913)](e[r(1345)],this["_handleO"+r(1493)]),this[r(452)+"er"]&&window[r(1560)+"Listener"](e[r(802)],this[r(1276)+r(1093)]),this[r(452)+"er"]&&window[r(1560)+r(913)](e[r(469)],this["_handleP"+r(601)])}[t(396)+t(1591)+t(913)](){let r=t;this._isBrowser&&window["removeEventListe"+r(1557)](r(1356),this._handleOnLine),this._isBrowser&&window[r(1177)+r(421)+"ner"](e[r(1345)],this["_handleO"+r(1493)]),this[r(452)+"er"]&&window[r(1177)+r(421)+r(1557)](e[r(802)],this[r(1276)+r(1093)]),this[r(452)+"er"]&&window[r(1177)+"entListe"+r(1557)](e[r(469)],this["_handleP"+r(601)])}[t(1276)+t(1093)](r){let s=t,l={bOmIp:function(h,_){return e.KFkBZ(h,_)}};if(!r[s(290)+"d"])if(e.pcybQ(s(1259),e[s(1186)])){let h=this._qosDB[s(328)](this[s(1246)]);return _0x2a672f[s(672)](XrcZPO.bOmIp(h,"{}"))[_0x5d9779]}else this._isBrowser&&window[s(1177)+s(421)+"ner"](e[s(802)],this["_handleP"+s(1093)]),this[s(452)+"er"]&&window[s(1177)+s(421)+s(1557)](e[s(469)],this[s(1276)+s(601)]),this[s(1212)]();this[s(452)+"er"]&&window[s(1177)+s(421)+s(1557)](s(1356),this[s(1360)+s(1508)]),this[s(452)+"er"]&&window[s(1177)+s(421)+s(1557)](e[s(1345)],this["_handleO"+s(1493)])}["_handleP"+t(601)](r){let s=t;s(1388)!==e[s(585)]?r[s(290)+"d"]&&(this["_navigat"+s(778)]()&&(!this[s(1091)]||e[s(857)](this[s(1091)][s(655)+"te"],this.OPEN)||e[s(1531)](this._ws.readyState,this[s(721)+"NG"]))&&this[s(1360)+s(1508)](),this._isBrowser&&window[s(1560)+s(913)](s(1356),this[s(1360)+s(1508)]),this[s(452)+"er"]&&window[s(1560)+s(913)](s(1315),this[s(1360)+s(1493)])):_0x1e7f12.log(_0x23ebf0)}async[t(456)+t(928)](r){let s=t,l={WtAwi:"0|2|3|4|1",OPPMZ:function(Kn,$n){return Kn!==$n}},{fpID:h,deviceID:_,bddID:b,ttwID:I,accessKey:m,aID:O,customParams:L={},enableAutoAck:F,enableQoS:V,QoSLevel:X,env:J}=this[s(495)],Me,ge,nt;if(this._isBrowser||this._isMiniWX||this[s(592)+"T"])if(e.dbsoF(e.fkIZy,s(360))){let Kn=l.WtAwi.split("|"),$n=0;for(;;){switch(Kn[$n++]){case"0":var rn=_0x5b50ab[_0x4a3ca7];continue;case"1":return xe[s(1309)];case"2":if(aUBqdz[s(484)](void 0,rn))return rn[s(1309)];continue;case"3":var xe=_0x193546[_0x42e1fc]={exports:{}};continue;case"4":_0x3adf1f[_0x2eb1e8](xe,xe[s(1309)],_0x44f9b3);continue}break}}else Me=location&&e[s(1418)](s(475),location.protocol)?e.gLhdw:e[s(633)],ge=r[s(1149)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),nt=/^wss(.*:\/\/)/[s(1166)](r)?r:""+Me+ge;else Me=s(596),ge=r[s(1149)](/(^http)((?:[s]*:\/\/))/,""),nt=/(^ws)((?:[s]*:\/\/))/[s(1166)](ge)?ge:""+Me+ge;let me=b?s(817):I?s(671):e[s(1023)],be=b||I||_;if(e[s(468)](!be,!me))throw new Error(e[s(374)]);let sn=e[s(691)](s(1208),typeof L)?await e[s(238)](L):L,Ye=J?e[s(236)](em,J.xUseEnv,J[s(1502)]):{},vi=Object[s(293)]({device_platform:s(963),version_code:s(1070)+"0",access_key:m,fpid:h,aid:O,[me]:be,xsack:F?1:0,xaack:F?1:0,xsqos:V?1:0,qos_level:V?X:void 0,qos_sdk_version:2,...Ye},sn),Lm=Object[s(960)](vi)[s(1310)]((Kn,$n)=>vi[$n]!==void 0?""+Kn+(Kn?"&":"?")+$n+"="+vi[$n]:Kn,"");return nt+s(999)+Lm}async[t(1191)](){let r=t;if(!(this._connectLock||this[r(1346)+r(1141)])){this[r(1191)+r(1398)]=!0;try{let s=this[r(153)+"tManager"]?.["checkCur"+r(175)+"ointReac"+r(1374)+r(1022)](),{timeoutInterval:l}=this[r(495)];if(s){let _=this["_endpoin"+r(1545)]?.[r(1188)+r(399)+"nt"](),b=this[r(153)+r(1545)]?.[r(576)+r(1132)+r(1459)+r(315)+r(881)](),I=this["_endpoin"+r(1545)]?.[r(1188)+r(399)+r(451)+r(631)]();if(b){let m="connect "+_+(r(535)+", max retries re"+r(531)+"ill use "+r(891)+r(1516))+b+" to retry",O=Et(e[r(1390)],{message:m,code:vn[r(528)+r(737)+"R"]});this[r(982)](m),this[r(946)+r(1249)+r(606)](O),this[r(933)]=await this._generateUrl(b),this[r(982)](r(1090)+b+" "+I+r(1506)),this[r(292)+"sListeners"]()}else{let m=r(1090)+_+(" timeout"+r(1555)+"tries re"+r(895));this[r(982)](m),this["_dispatc"+r(1249)+"ent"](Et(r(1173),{message:m,code:vn.MAX_RETRIES_ERROR}));return}}else{let _=this[r(153)+r(1545)]?.[r(1188)+"ntEndpoi"+r(249)+"ateCount"](),b=this[r(153)+"tManager"]?.[r(1188)+"ntEndpoi"+r(451)+r(631)]();this[r(933)]=await this[r(456)+r(928)](e[r(340)](_,"")),this._debug("connect "+_+" "+b+r(1506)),this[r(292)+"sListeners"]()}if(this[r(1335)])this[r(1335)]=!1;else{let _=e[r(458)]($a,e[r(1083)],{message:e[r(369)]});this["onStartR"+r(1341)]&&this["onStartR"+r(1341)](_)}let h=this[r(153)+r(1545)]?.[r(1188)+"ntEndpointTriesC"+r(631)]()||0;h>1&&await this[r(902)](h-1),this[r(982)](r(899)+r(115)+this[r(933)]+" protocols: "+this[r(202)+"ls"]),this[r(1091)]=e[r(1334)](Yg,{url:this[r(933)],protocols:[this[r(202)+"ls"]],headers:this[r(495)][r(736)+r(1244)+"s"][r(437)+r(1095)]},this[r(495)].ws),(this[r(452)+"er"]||this._isWorker)&&this[r(1091)]&&(this[r(1091)][r(663)+"pe"]=this[r(482)+"ype"]),this[r(981)+r(713)](),this[r(1191)+"ionTimeo"+r(230)]=e.OlVur(setTimeout,this[r(1333)+"ut"][r(239)](this),l)}catch(s){throw this[r(1191)+r(1398)]=!1,s}}}[t(1478)+"mer"](){let r=t;e[r(1163)]!==r(1556)?(e[r(758)](clearTimeout,this["_connect"+r(1394)+r(230)]),this[r(1191)+r(1394)+r(230)]=null):e[r(1288)](_0x173581,this,_0x17ad59,[_0x174f85,_0x25c9a3,_0x5a9291,_0x1d6ee8,_0x389e6a,_0x44c9c3])}["_clearPi"+t(416)](){let r=t;e.lDvsa(clearTimeout,this[r(1269)+r(995)+"Id"]),e[r(635)](clearTimeout,this[r(132)+r(685)+r(669)]),this[r(1269)+"gTimeoutId"]=null,this["_reconne"+r(685)+r(669)]=null}_debug(...r){let s=t;this[s(495)].debug&&console[s(724)][s(1203)](console,[s(424)+">",...r])}[t(745)+"rvalValue"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:_}=this[s(495)],b=e[s(522)](l,Math.pow(_,r-1));return e[s(1407)](b,h)?h:b}[t(794)](){let r=t;if(this._ws&&e[r(1234)](this[r(1091)][r(655)+"te"],this[r(721)+"NG"])){this[r(856)+"ngTimer"](),this[r(1269)+"gTimeoutId"]=e[r(327)](setTimeout,this[r(794)][r(239)](this),this[r(495)][r(1469)+r(109)]);return}if(!this[r(1091)]||this._ws[r(655)+"te"]!==this.OPEN)return void this[r(1485)+r(1341)]();this[r(1091)]&&this[r(1091)].send("hi"),this[r(132)+r(685)+r(669)]=e[r(1129)](setTimeout,this[r(1485)+r(1341)+r(1113)][r(239)](this),this._options[r(909)+r(255)+"val"])}[t(1485)+t(1341)+t(1113)](){let r=t;this[r(380)+r(1050)]?.[r(863)](),this[r(788)](r(1082)+"e_timeout",e[r(957)]),this["_pingLos"+r(1050)]?.[r(1486)+r(1076)+"nt"]()?this[r(1485)+"econnect"]():this._ping()}[t(816)+"orOnline"](){let r=t;return this[r(592)+"T"]||this._isMiniWX?this[r(1139)+r(1529)+r(549)]:(this[r(452)+"er"]||this[r(1063)+"r"])&&this._options[r(304)+r(720)+r(325)]?navigator[r(852)]:!0}[t(1485)+t(1341)](){let r=t;!this["_navigat"+r(778)]()||this[r(1346)+r(1141)]||(this[r(153)+r(1545)]?.["resetEnd"+r(270)+r(1020)](),this[r(380)+"sCounter"]?.[r(542)+r(974)](),this[r(1091)]?this[r(1431)+r(141)](1001,e[r(757)],!0):this[r(1191)]())}[t(1074)+t(654)+"ange"](){let r=t;this._isMiniTT?tt[r(386)+r(142)+r(1452)](({isConnected:s})=>{let l=r;this[l(1139)+l(1529)+l(549)]=s,s?this[l(1360)+l(1508)]():this["_handleO"+l(1493)]()}):this._isMiniWX&&wx[r(386)+r(142)+r(1452)](({isConnected:s})=>{let l=r;this[l(1139)+l(1529)+l(549)]=s,s?this[l(1360)+l(1508)]():this[l(1360)+l(1493)]()})}[t(902)](r){let s=t,l={lbquH:function(h,_){return e[$(504)](h,_)},KszjU:e[s(586)],eWiMS:function(h,_,b){return h(_,b)}};return new Promise(h=>{let _=s;l[_(1384)](_(1111),l[_(1331)])?l.eWiMS(setTimeout,h,this[_(745)+_(888)+"e"](r)):(this[_(1483)]=_0x5a2107,this[_(1408)]=_0x29b70b,this[_(157)]=_0x26e2ec?_0x181a5f:_0x1bfed6?_0xbc99aa:null)})}["_disconn"+t(141)](r=1e3,s="",l=!1){let h=t;this[h(1091)]&&this[h(1243)+h(1075)+"t"](r,s,l)}[t(1333)+"ut"](){let r=t,s=this[r(153)+r(1545)]?.getCurrentEndpoint();this[r(982)]("connect "+s+r(535)),this[r(1431)+r(141)](1001,e[r(705)],!0)}[t(108)](r){let s=t,l=e[s(941)](nn,r);this._ws&&e[s(604)](this[s(1091)].readyState,this.OPEN)&&(this[s(1091)]&&this[s(1091)][s(434)](l),this[s(982)](e[s(688)],r))}["_removeW"+t(1142)+"rs"](){let r=t,s=e[r(1429)][r(496)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1091)][r(1177)+r(421)+"ner"](e[r(1372)],this[r(908)+"ge"]);continue;case"1":this[r(1091)][r(1177)+r(421)+r(1557)](e.cSQyS,this[r(233)]);continue;case"2":if(!this[r(1091)])return;continue;case"3":this[r(1091)]["removeEv"+r(421)+r(1557)](e[r(1048)],this._onClose);continue;case"4":this[r(1091)]["removeEv"+r(421)+r(1557)](e.tMLgA,this[r(234)]);continue}break}}[t(981)+"steners"](){let r=t,s=(r(609)+"4")[r(496)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1091)][r(1560)+r(913)](e[r(1007)],this[r(233)]);continue;case"1":this[r(1091)].addEventListener(e.PRFVH,this._onClose);continue;case"2":if(!this[r(1091)])return;continue;case"3":this[r(1091)][r(1560)+"Listener"](e.TlHGB,this._onMessage);continue;case"4":this[r(1091)]["addEvent"+r(913)]("error",this[r(234)]);continue}break}}["_wsInsta"+t(578)](r=1e3,s=""){let l=t;try{this[l(1091)]&&this[l(1091)].close(r,s)}catch{}}[t(1243)+t(1075)+"t"](r=1e3,s="",l=!1){let h=t;if(this[h(856)+h(416)](),this["_clearTi"+h(953)](),this["_removeW"+h(1142)+"rs"](),this[h(1030)+h(578)](1e3,s),this["_connect"+h(1398)]=!1,l&&this[h(816)+"orOnline"]()&&!this[h(1346)+h(1141)]){if(this[h(153)+h(1545)]?.[h(1486)+"chMaxTries"]())if(e.lisEV(e.vVWCU,e[h(984)])){let b=this["_endpoin"+h(1545)]?.[h(1188)+h(399)+"nt"]();this[h(946)+h(1327)+h(606)](e[h(761)](Rt,h(1212),{code:1006,reason:h(1090)+b+(h(535)+h(1555)+h(733)+h(895)),wasClean:!0}))}else return _0x7e3671[h(1203)](_0xd03e46(this),_0x24b5a2),FvCbfE[h(635)](_0x30b3c3,_0x20eecc.get(this));else{let b=this[h(495)][h(616)+h(1386)+h(543)](r,s);this[h(946)+"hCloseEv"+h(606)](e[h(684)](Rt,e[h(1048)],{code:r,reason:s,wasClean:!0,willReconnect:b})),b&&this[h(1191)]()}return}this[h(816)+h(778)]()||this[h(1346)+h(1141)]?this[h(946)+"hCloseEvent"](e[h(1548)](Rt,e[h(1048)],{code:r,reason:e[h(133)]})):this["_dispatc"+h(1327)+h(606)](e.QNAvD(Rt,e[h(1048)],{code:1006,reason:e[h(1004)]})),this[h(1091)]=null,this["_endpoin"+h(1545)]?.[h(1492)+h(270)+h(1020)](),this[h(380)+"sCounter"]?.["resetCou"+h(974)]()}[t(946)+t(1160)+"nt"](r){let s=t;this.emit(e[s(1007)],r),this[s(1308)]&&this.onopen(r)}[t(946)+"hMessageEvent"](r){let s=t;this.emit(s(1080),r),this[s(1217)+"e"]&&this.onmessage(r)}[t(946)+t(289)+"ageEvent"](r){let s=t;this[s(788)](s(278),r),this[s(1079)+s(371)]&&this[s(1079)+"eAck"](r)}[t(946)+t(1249)+"ent"](r){let s=t,l={MfQkT:function(h,_){return e[$(232)](h,_)},vIRkL:e[s(994)],tekSR:e[s(178)],Jxzda:e[s(806)],moZkO:e[s(583)],qsklo:function(h,_,b){return h(_,b)},cyFSY:function(h,_,b,I){return e[s(784)](h,_,b,I)}};if(e[s(682)](e[s(1427)],s(1206)))this[s(788)](e[s(1390)],r),this[s(1169)]&&this[s(1169)](r);else{let{pingInterval:h,pingFrequency:_}=this._options;if((YHMMTT[s(1353)]("hi",_0x50c454[s(1263)])&&YHMMTT[s(1353)](YHMMTT[s(1268)],_)||YHMMTT[s(620)]===_)&&(this["_clearPi"+s(416)](),this.emit(YHMMTT[s(1057)],YHMMTT[s(858)]),this._pingPongTimeoutId=YHMMTT[s(679)](_0x2be468,this._ping.bind(this),h)),YHMMTT.MfQkT("hi",_0x2f0018[s(1263)]))return;try{YHMMTT.cyFSY(_0x4b6030,this,_0x34719f,[_0x3235b1,_0x14a961,_0x3d987a,_0x483148,_0x129d18,_0x250077])}catch(b){let I=_0x4d28c3("error",{message:b.message,code:_0x58d5d5[s(977)+s(935)],error:b});this["_dispatchErrorEv"+s(606)](I)}}}[t(946)+t(1327)+t(606)](r){let s=t;this[s(788)]("close",r),this.onclose&&this[s(443)](r)}get[t(663)+"pe"](){let r=t;return e[r(1097)](e[r(617)],e.WUDcx)?this._ws?this[r(1091)][r(663)+"pe"]:this[r(482)+r(1024)]:_0x21c670||(_0x5b02=[_0x1bcb91[r(294)+"e"].advance,_0x3e0c2b[r(294)+"e"][r(1247)],_0x19c9d3[r(294)+"e"]["continue"+r(731)+"ey"]])}set[t(663)+"pe"](r){let s=t;this[s(482)+s(1024)]=r,this[s(1091)]&&(this[s(1091)][s(663)+"pe"]=r)}get[t(428)+"nt"](){let r=t;return this[r(153)+r(1545)]?.[r(1188)+r(399)+r(451)+"ount"]()||0}get[t(653)+t(1455)](){let r=t,s=this[r(1351)+r(644)].reduce((l,h)=>(l+=h&&h.byteLength||0,l),0);return e[r(493)](s,this[r(1091)]?this[r(1091)]["buffered"+r(1455)]:0)}get[t(223)+"ns"](){let r=t;return this[r(1091)]?this._ws[r(223)+"ns"]:""}get protocol(){let r=t;if(e.JbCRf(e.qqXGD,e[r(308)])){let s=e.ykJuQ.split("|"),l=0;for(;;){switch(s[l++]){case"0":_0x2956ca=e[r(1288)](_0x5785f6,0,_0x4b14d0,_0x40fe3d);continue;case"1":_0x5d2f00=e[r(1117)](_0x2611ad,_0x45b0da,_0xb348bc,_0x1c16f4[r(689)]||0);continue;case"2":_0x3ec682[r(724)](r(140),_0x478927);continue;case"3":_0x4e1789[r(724)](e.WgsYB,_0x4b5403);continue;case"4":_0x2191e6[r(724)](r(973)+r(329),_0x68d9d3,_0x411839[r(689)]);continue;case"5":_0x23cbde[r(724)](e.AtRBM,_0x465623);continue;case"6":_0xe6f4f4=e[r(885)](_0x29c122,_0x66000[r(402)+"er"](_0x57ef32[r(263)]||_0x125080),_0x1a9c76,_0x327457);continue;case"7":_0x2fe10a=e[r(254)](_0x196ee7,_0x486574[_0x1e8b9e.cursor_name],_0x4bd964,_0x2a864c);continue;case"8":_0x102a2b[r(724)](e[r(1566)],_0x1e63de);continue;case"9":_0x11e13b=_0x1f8eef(_0x5dda4a[r(868)+r(274)],_0x3e0711,_0x13fc0c);continue;case"10":_0x5ef253[r(724)](e[r(839)],_0x30d9d2);continue}break}}else return this[r(1091)]?this[r(1091)][r(1319)]:""}get[t(655)+"te"](){let r=t;return this[r(1091)]?this[r(1091)][r(655)+"te"]:this[r(495)][r(350)+r(1568)]?this[r(721)+"NG"]:this[r(1229)]}get[t(1060)](){let r=t;return this[r(1091)]?this[r(1091)][r(1060)]:this[r(933)]}[t(1212)](r=1e3,s){let l=t,h=e[l(683)][l(496)]("|"),_=0;for(;;){switch(h[_++]){case"0":if(!this[l(1091)])return void this._debug(e[l(389)]);continue;case"1":this[l(396)+l(1591)+"Listener"]();continue;case"2":this["_destroy"+l(1075)+"t"](r,s);continue;case"3":if(e[l(1575)](this._ws[l(655)+"te"],this[l(1229)])||e[l(1385)](this[l(1091)][l(655)+"te"],this[l(911)]))return void this[l(982)](l(1366)+l(652)+"y closed");continue;case"4":this[l(856)+l(416)]();continue;case"5":this["_clearTi"+l(953)]();continue;case"6":this[l(1346)+l(1141)]=!0;continue;case"7":this[l(842)+l(152)]?.[l(801)]();continue}break}}async[t(434)](r,s){let l=t;if(e.WMGYO(null,r))throw new Error(e[l(567)]);e[l(832)](e[l(742)],typeof r)&&(r=JSON.stringify(r)),e[l(212)](e.SUTRf,typeof r)&&!(r instanceof ArrayBuffer)&&!(r[l(1135)]&&r[l(1135)]instanceof ArrayBuffer)&&(r=JSON[l(250)+"y"](r));let h=await e[l(1257)](Yl,r),_=e[l(936)](Qg,r),{method:b=0,service:I=this._options[l(689)],logID:m=this._options["logIDGen"+l(465)](),headers:O=this[l(495)][l(966)],payloadEncoding:L=this[l(495)][l(776)+l(1361)],payloadType:F=this._options[l(337)+l(1024)],logIDNew:V=this[l(495)][l(425)+l(1450)][l(558)+"toGenera"+l(533)+"ew"]?i(this[l(495)][l(425)+l(1450)][l(574)]):""}=s||{};if(!I)throw new Error(e[l(430)]);let X={SeqID:de[l(402)+"er"](this._seqId++),LogID:de[l(402)+"er"](m),service:I,method:b,headers:O,payloadEncoding:e.BcqJT(L,Object)?L[l(422)]?L[l(422)]:"":L,payloadType:F instanceof Object?F[l(1313)]?F[l(1313)]:_:F||_,payload:h,LogIDNew:V},J=e[l(199)](nn,X);return this[l(1091)]&&this[l(1091)].readyState===this[l(1109)]?(this[l(1091)]&&this._ws[l(434)](J),this[l(982)](l(1357),X)):this[l(1351)+"Queue"][l(1393)]<this[l(495)]["maxMessa"+l(235)+l(457)]?(this[l(1351)+l(644)][l(1544)](J),this._debug(e[l(693)],X)):(this[l(1351)+"Queue"][l(436)](),this._messageQueue.push(J)),{seqID:this._seqId,logID:m,logIDNew:V}}async[t(616)+"t"](r){let s=t,{url:l}=e[s(1343)](r,{}),h=Array[s(915)](l)?l:e[s(146)]("string",typeof l)?[l]:[];r&&Object[s(293)](this[s(495)],r),h&&h[s(1393)]?this[s(153)+s(1545)]=new $l(h,this._options[s(532)+"es"]):this[s(153)+"tManager"]?.["resetEnd"+s(270)+s(1020)](),this[s(380)+s(1050)]?.["resetCou"+s(974)](this[s(495)][s(1293)+s(1226)]),this[s(1346)+s(1141)]=!1,this._ws&&this._ws.readyState!==this[s(1229)]?this[s(1431)+s(141)](1e3,"manual r"+s(1341)+"ing",!0):(this[s(1335)]=!0,this[s(1191)]())}async[t(648)](){let r=t;if(!this[r(1191)+r(1398)]){let s=e[r(1429)].split("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1335)]=!0;continue;case"1":this["_pingLos"+r(1050)]?.[r(542)+"nter"]();continue;case"2":this[r(153)+r(1545)]?.[r(1492)+r(270)+"fig"]();continue;case"3":this["_readyCl"+r(1141)]=!1;continue;case"4":this[r(1191)]();continue}break}}}["addEvent"+t(913)](r,s){this.on(r,s)}[t(1540)+t(216)](r){let s=t;if(s(744)===s(1365))return this[s(454)+"ndpointTriesCount"]=1,this[s(170)+s(1479)]++,this[s(968)+"s"][this[s(170)+"ndex"]];{let{type:l}=r;this[s(788)](l,r)}}[t(1177)+t(421)+t(1557)](r,s){this[t(1430)](r,s)}pingOnce(){let r=t,s={xXhJc:e[r(1367)],xkYJX:function(l,h){return e[r(287)](l,h)},QGHba:e[r(957)],Hgivl:e[r(806)]};if(e[r(782)](e[r(772)],e[r(772)]))this[r(1213)+r(991)]=_0x25e34e,this["_cursorF"+r(1104)]=_0x5bc763,this["_message"+r(962)]=_0x374ae6,this[r(157)]=_0x4becbe(this._cursorNameSpace,ZHiqSu[r(1358)]);else return new Promise((l,h)=>{let _=r,b={ielzM:function(O,L){return e[$(224)](O,L)},FLpFe:e.ZGXkB};this["_clearPi"+_(416)](),this[_(1269)+_(995)+"Id"]=e[_(516)](setTimeout,this[_(794)][_(239)](this),this[_(495)]["pingInte"+_(109)]);let I=()=>{let O=_;b[O(579)](l,O(1460)),this[O(1430)](O(1082)+"e_success",I),this[O(1430)](b[O(1239)],m)},m=()=>{let O=_;s.xkYJX(h,s[O(1382)]),this.off(s[O(363)],I),this[O(1430)](O(1082)+"e_timeout",m)};this.on(_(1082)+_(530)+"s",I),this.on(e[_(627)],m),this._ping()})}}})(),qe[N(1541)+"oseEvent"]=Fe[N(1541)+"oseEvent"],qe[N(746)+N(1144)]=Fe[N(746)+N(1144)],qe[N(1499)+"e"]=Fe[N(1499)+"e"],qe.Event=Fe[N(216)],qe[N(987)]=Fe[N(987)],qe[N(1534)+N(1475)+"vent"]=Fe[N(1534)+N(1475)+"vent"],qe[N(1475)+"vent"]=Fe.MessageEvent,qe[N(1180)+"t"]=Fe[N(1180)+"t"],qe["Reconnec"+N(1282)]=Fe.ReconnectEvent,qe.createCloseEvent=Fe[N(1314)+N(1155)],qe["createEr"+N(1144)]=Fe[N(945)+N(1144)],qe[N(1470)+"ssageEvent"]=Fe["createMe"+N(1539)+"nt"],qe[N(625)+"enEvent"]=Fe["createOp"+N(879)],qe["createRe"+N(677)+"vent"]=Fe["createReconnectE"+N(488)],qe[N(1248)+N(959)]=Fe[N(1248)+N(959)],qe[N(381)+N(274)]=Fe[N(381)+N(274)];for(Sa in Fe)[N(1541)+N(1155),N(746)+N(1144),"ErrorCode","Event",N(987),N(1534)+N(1475)+N(488),N(1475)+"vent",N(1180)+"t",N(1154)+N(1282),N(1314)+N(1155),"createEr"+N(1144),N(1470)+N(1539)+"nt",N(625)+N(879),N(898)+"connectEvent",N(1248)+N(959),N(381)+N(274)].indexOf(Sa)===-1&&(qe[Sa]=Fe[Sa]);var Sa;Object[N(716)+"operty"](qe,N(208)+"le",{value:!0})});import{existsSync as NI,openSync as FI}from"node:fs";import{mkdir as BI}from"node:fs/promises";import{dirname as zI}from"node:path";import{fileURLToPath as UI}from"node:url";function GI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Al(t=Z()){return NI(t.libEntry)?t.libEntry:UI(new URL("../index.ts",import.meta.url))}async function og(t={}){let e=t.paths??Z(),n=t.entryOverride??Al(e),i=GI(e,process.env.COZE_BRIDGE_LOG_MODE);await BI(zI(i),{recursive:!0});let o=FI(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=ht(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[Ts]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return HI.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var HI,Ts,Ma=lt(()=>{"use strict";Vt();re();De();HI=H("spawn-daemon"),Ts="COZE_BRIDGE_DAEMON"});import{spawn as zA}from"node:child_process";import{mkdir as UA,unlink as HA,writeFile as GA}from"node:fs/promises";import{dirname as qA,join as jA}from"node:path";function _i(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function WA(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${_i(n)}</key>
|
|
21
|
+
<string>${_i(i)}</string>`).join(`
|
|
22
22
|
`);return e?`
|
|
23
23
|
<key>EnvironmentVariables</key>
|
|
24
24
|
<dict>
|
|
25
25
|
${e}
|
|
26
|
-
</dict>`:""}function KA(t,e){return new Promise((n,i)=>{let o=zA(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
|
|
26
|
+
</dict>`:""}function KA(t,e){return new Promise((n,i)=>{let o=zA(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 wi,Ds,Ha,Ml,Tg=lt(()=>{"use strict";re();wi=H("supervisor.launchd"),Ds="ai.coze.bridge",Ha=KA,Ml={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>${Ds}</string>
|
|
32
32
|
<key>ProgramArguments</key>
|
|
33
33
|
<array>
|
|
34
|
-
<string>${
|
|
35
|
-
<string>${
|
|
34
|
+
<string>${_i(t.nodeBin)}</string>
|
|
35
|
+
<string>${_i(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>${_i(t.logFile)}</string>
|
|
46
46
|
<key>StandardErrorPath</key>
|
|
47
|
-
<string>${
|
|
47
|
+
<string>${_i(t.logFile)}</string>${WA(t.env)}
|
|
48
48
|
</dict>
|
|
49
49
|
</plist>
|
|
50
|
-
`},configPath(t){return jA(t.homeDir,"Library","LaunchAgents",`${
|
|
51
|
-
`):""}function
|
|
50
|
+
`},configPath(t){return jA(t.homeDir,"Library","LaunchAgents",`${Ds}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await UA(qA(i),{recursive:!0}),await GA(i,this.renderConfig(t),"utf8"),wi.info("plist written",{plistPath:i,activate:n}),!n)return;await Ha("launchctl",["unload","-w",i]).catch(a=>wi.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await Ha("launchctl",["load","-w",i]),wi.info("launchd job loaded",{label:Ds});let o=process.getuid?.()??0;await Ha("launchctl",["kickstart","-k",`gui/${o}/${Ds}`]),wi.info("launchd job kickstarted",{label:Ds,uid:o})},async uninstall(t){let e=this.configPath(t);await Ha("launchctl",["unload","-w",e]).catch(n=>wi.warn("launchctl unload failed (ignored)",{err:String(n)})),await HA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),wi.info("launchd job removed",{plistPath:e})}}});import{spawn as $A}from"node:child_process";import{mkdir as VA,unlink as JA,writeFile as ZA}from"node:fs/promises";import{dirname as YA,join as Pg}from"node:path";function qa(t,e){return t.isRoot?e:["--user",...e]}function QA(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
|
|
51
|
+
`):""}function ja(t,e){return new Promise((n,i)=>{let o=$A(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 Ga,yi,XA,Nl,Rg=lt(()=>{"use strict";re();Ga=H("supervisor.systemd"),yi="coze-bridge.service",XA="/etc/systemd/system";Nl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
|
|
52
52
|
Description=Coze Bridge daemon
|
|
53
53
|
After=network.target
|
|
54
54
|
|
|
@@ -62,7 +62,7 @@ StandardError=append:${t.logFile}
|
|
|
62
62
|
${QA(t.env)}
|
|
63
63
|
[Install]
|
|
64
64
|
WantedBy=${e}
|
|
65
|
-
`},configPath(t){return t.isRoot?
|
|
65
|
+
`},configPath(t){return t.isRoot?Pg(XA,yi):Pg(t.homeDir,".config","systemd","user",yi)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await VA(YA(i),{recursive:!0}),await ZA(i,this.renderConfig(t),"utf8"),Ga.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await ja("systemctl",qa(t,["daemon-reload"])),await ja("systemctl",qa(t,n?["enable","--now",yi]:["enable",yi])),Ga.info("systemd unit enabled",{unitName:yi,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await ja("systemctl",qa(t,["disable","--now",yi])).catch(n=>Ga.warn("systemctl disable failed (ignored)",{err:String(n)})),await JA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await ja("systemctl",qa(t,["daemon-reload"])).catch(()=>{}),Ga.info("systemd unit removed",{unitPath:e})}}});import{spawn as ek}from"node:child_process";import{join as tk}from"node:path";function Dg(t,e){return new Promise((n,i)=>{let o=ek(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 Fl,Wa,Bl,Og=lt(()=>{"use strict";re();Fl=H("supervisor.taskscheduler"),Wa="CozeBridge",Bl={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,64 @@ WantedBy=${e}
|
|
|
86
86
|
</Exec>
|
|
87
87
|
</Actions>
|
|
88
88
|
</Task>
|
|
89
|
-
`},configPath(t){return tk(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 Pg("schtasks",["/Create","/SC","ONLOGON","/TN",qa,"/TR",n,"/RU",t.userName,"/F"]),Nl.info("task scheduler entry created",{task:qa,logFile:t.logFile})},async uninstall(t){await Pg("schtasks",["/Delete","/TN",qa,"/F"]).catch(e=>Nl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Nl.info("task scheduler entry removed",{task:qa})}}});var Og={};tc(Og,{buildContext:()=>ak,getSupervisor:()=>ik,launchdSupervisor:()=>Ll,systemdSupervisor:()=>Ml,taskSchedulerSupervisor:()=>Fl});import{homedir as nk,userInfo as rk}from"node:os";function ik(t=process.platform){switch(t){case"darwin":return Ll;case"linux":return Ml;case"win32":return Fl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function ok(){let t={};for(let e of sk){let n=process.env[e];n&&(t[e]=n)}return t}function ak(){let t=Z();return{nodeBin:process.execPath,entry:Il(t),logFile:t.logFile,homeDir:nk(),userName:rk().username,isRoot:process.getuid?.()===0,env:ok()}}var sk,Lg=ot(()=>{"use strict";Pe();Da();Tg();Rg();Dg();sk=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();vn();var hf=q("acp-installer-warmup"),aw=["claude-code","codex"];async function xf(t={}){let e=t.ensure??kr,i=(await Promise.allSettled(aw.map(async o=>{let a=await e(o);hf.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&hf.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))})}tn();ne();import{readdir as vw}from"node:fs/promises";import{mkdir as wf,readFile as Ew,writeFile as _f}from"node:fs/promises";import{join as cc}from"node:path";var bw={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function Tr(t,e,n){await wf(t,{recursive:!0});let i=bw[e],o=cc(t,i);return await _f(o,n??"","utf8"),o}async function dc(t,e,n){let i=cc(t,".claude");await wf(i,{recursive:!0});let o=cc(i,"settings.local.json"),a={};try{let f=await Ew(o,"utf8"),u=JSON.parse(f);typeof u=="object"&&u!==null&&!Array.isArray(u)&&(a=u)}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 _f(o,JSON.stringify(a,null,2),"utf8"),o}var et=q("agent-detail-sync"),Sw=6e4,Iw=5*6e4,Hs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await vw(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 we(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 we(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(u){et.warn("detail RPC failed, using local data",{agentId:e,err:String(u)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,Iw):Sw;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 f=!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,f=!0):o.deployType&&et.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){et.debug("detail sync: no diff",{agentId:e});return}await Le(i,this.opts.paths),et.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),f?(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 Tr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var zd=en(Yf(),1);import{createHash as IE}from"node:crypto";import{lstat as Pd,mkdir as Dd,readFile as Bo,readdir as rh,rm as Od,stat as Fd,writeFile as Ld}from"node:fs/promises";import{homedir as AE}from"node:os";import{basename as eh,dirname as kE,join as xe,normalize as TE,relative as Bd,resolve as Md,sep as ih}from"node:path";import{Readable as sh}from"node:stream";import{pipeline as oh}from"node:stream/promises";import $w from"events";import ct from"fs";import{EventEmitter as dd}from"node:events";import Lu from"node:stream";import{StringDecoder as Vw}from"node:string_decoder";import Fu from"node:path";import Ur from"node:fs";import{dirname as a_,parse as c_}from"path";import{EventEmitter as g_}from"events";import jc from"assert";import{Buffer as tr}from"buffer";import*as ru from"zlib";import m_ from"zlib";import{posix as Or}from"node:path";import{basename as W_}from"node:path";import yo from"fs";import qt from"fs";import fu from"path";import{win32 as iy}from"node:path";import wu from"path";import Yu from"node:fs";import Ey from"node:assert";import{randomBytes as Qu}from"node:crypto";import se from"node:fs";import Ue from"node:path";import e0 from"fs";import Co from"node:fs";import Wi from"node:path";import pt from"node:fs";import Ty from"node:fs/promises";import vo from"node:path";import{join as f0}from"node:path";import xt from"node:fs";import x0 from"node:path";var Ww=Object.defineProperty,Kw=(t,e)=>{for(var n in e)Ww(t,n,{get:e[n],enumerable:!0})},Qf=typeof process=="object"&&process?process:{stdout:null,stderr:null},Jw=t=>!!t&&typeof t=="object"&&(t instanceof ir||t instanceof Lu||Zw(t)||Xw(t)),Zw=t=>!!t&&typeof t=="object"&&t instanceof dd&&typeof t.pipe=="function"&&t.pipe!==Lu.Writable.prototype.pipe,Xw=t=>!!t&&typeof t=="object"&&t instanceof dd&&typeof t.write=="function"&&typeof t.end=="function",nn=Symbol("EOF"),rn=Symbol("maybeEmitEnd"),In=Symbol("emittedEnd"),Ks=Symbol("emittingEnd"),ki=Symbol("emittedError"),$s=Symbol("closed"),eu=Symbol("read"),Vs=Symbol("flush"),tu=Symbol("flushChunk"),Rt=Symbol("encoding"),Dr=Symbol("decoder"),Ge=Symbol("flowing"),Ti=Symbol("paused"),Fr=Symbol("resume"),je=Symbol("buffer"),nt=Symbol("pipes"),We=Symbol("bufferLength"),pc=Symbol("bufferPush"),Js=Symbol("bufferShift"),Qe=Symbol("objectMode"),De=Symbol("destroyed"),gc=Symbol("error"),mc=Symbol("emitData"),nu=Symbol("emitEnd"),wc=Symbol("emitEnd2"),Bt=Symbol("async"),_c=Symbol("abort"),Zs=Symbol("aborted"),Ci=Symbol("signal"),Kn=Symbol("dataListeners"),ht=Symbol("discarded"),Ri=t=>Promise.resolve().then(t),Yw=t=>t(),Qw=t=>t==="end"||t==="finish"||t==="prefinish",e_=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,t_=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Mu=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Fr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},n_=class extends Mu{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)}},r_=t=>!!t.objectMode,i_=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",ir=class extends dd{[Ge]=!1;[Ti]=!1;[nt]=[];[je]=[];[Qe];[Rt];[Bt];[Dr];[nn]=!1;[In]=!1;[Ks]=!1;[$s]=!1;[ki]=null;[We]=0;[De]=!1;[Ci];[Zs]=!1;[Kn]=0;[ht]=!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");r_(e)?(this[Qe]=!0,this[Rt]=null):i_(e)?(this[Rt]=e.encoding,this[Qe]=!1):(this[Qe]=!1,this[Rt]=null),this[Bt]=!!e.async,this[Dr]=this[Rt]?new Vw(this[Rt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[je]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[nt]});let{signal:n}=e;n&&(this[Ci]=n,n.aborted?this[_c]():n.addEventListener("abort",()=>this[_c]()))}get bufferLength(){return this[We]}get encoding(){return this[Rt]}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[Bt]}set async(t){this[Bt]=this[Bt]||!!t}[_c](){this[Zs]=!0,this.emit("abort",this[Ci]?.reason),this.destroy(this[Ci]?.reason)}get aborted(){return this[Zs]}set aborted(t){}write(t,e,n){if(this[Zs])return!1;if(this[nn])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[Bt]?Ri:Yw;if(!this[Qe]&&!Buffer.isBuffer(t)){if(t_(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(e_(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[Ge]&&this[We]!==0&&this[Vs](!0),this[Ge]?this.emit("data",t):this[pc](t),this[We]!==0&&this.emit("readable"),n&&i(n),this[Ge]):t.length?(typeof t=="string"&&!(e===this[Rt]&&!this[Dr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Rt]&&(t=this[Dr].write(t)),this[Ge]&&this[We]!==0&&this[Vs](!0),this[Ge]?this.emit("data",t):this[pc](t),this[We]!==0&&this.emit("readable"),n&&i(n),this[Ge]):(this[We]!==0&&this.emit("readable"),n&&i(n),this[Ge])}read(t){if(this[De])return null;if(this[ht]=!1,this[We]===0||t===0||t&&t>this[We])return this[rn](),null;this[Qe]&&(t=null),this[je].length>1&&!this[Qe]&&(this[je]=[this[Rt]?this[je].join(""):Buffer.concat(this[je],this[We])]);let e=this[eu](t||null,this[je][0]);return this[rn](),e}[eu](t,e){if(this[Qe])this[Js]();else{let n=e;t===n.length||t===null?this[Js]():typeof n=="string"?(this[je][0]=n.slice(t),e=n.slice(0,t),this[We]-=t):(this[je][0]=n.subarray(t),e=n.subarray(0,t),this[We]-=t)}return this.emit("data",e),!this[je].length&&!this[nn]&&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[nn]=!0,this.writable=!1,(this[Ge]||!this[Ti])&&this[rn](),this}[Fr](){this[De]||(!this[Kn]&&!this[nt].length&&(this[ht]=!0),this[Ti]=!1,this[Ge]=!0,this.emit("resume"),this[je].length?this[Vs]():this[nn]?this[rn]():this.emit("drain"))}resume(){return this[Fr]()}pause(){this[Ge]=!1,this[Ti]=!0,this[ht]=!1}get destroyed(){return this[De]}get flowing(){return this[Ge]}get paused(){return this[Ti]}[pc](t){this[Qe]?this[We]+=1:this[We]+=t.length,this[je].push(t)}[Js](){return this[Qe]?this[We]-=1:this[We]-=this[je][0].length,this[je].shift()}[Vs](t=!1){do;while(this[tu](this[Js]())&&this[je].length);!t&&!this[je].length&&!this[nn]&&this.emit("drain")}[tu](t){return this.emit("data",t),this[Ge]}pipe(t,e){if(this[De])return t;this[ht]=!1;let n=this[In];return e=e||{},t===Qf.stdout||t===Qf.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[nt].push(e.proxyErrors?new n_(this,t,e):new Mu(this,t,e)),this[Bt]?Ri(()=>this[Fr]()):this[Fr]()),t}unpipe(t){let e=this[nt].find(n=>n.dest===t);e&&(this[nt].length===1?(this[Ge]&&this[Kn]===0&&(this[Ge]=!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[ht]=!1,this[Kn]++,!this[nt].length&&!this[Ge]&&this[Fr]();else if(t==="readable"&&this[We]!==0)super.emit("readable");else if(Qw(t)&&this[In])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ki]){let i=e;this[Bt]?Ri(()=>i.call(this,this[ki])):i.call(this,this[ki])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Kn]=this.listeners("data").length,this[Kn]===0&&!this[ht]&&!this[nt].length&&(this[Ge]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Kn]=0,!this[ht]&&!this[nt].length&&(this[Ge]=!1)),e}get emittedEnd(){return this[In]}[rn](){!this[Ks]&&!this[In]&&!this[De]&&this[je].length===0&&this[nn]&&(this[Ks]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[$s]&&this.emit("close"),this[Ks]=!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[Bt]?(Ri(()=>this[mc](n)),!0):this[mc](n);if(t==="end")return this[nu]();if(t==="close"){if(this[$s]=!0,!this[In]&&!this[De])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ki]=n,super.emit(gc,n);let o=!this[Ci]||this.listeners("error").length?super.emit("error",n):!1;return this[rn](),o}else if(t==="resume"){let o=super.emit("resume");return this[rn](),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[rn](),i}[mc](t){for(let n of this[nt])n.dest.write(t)===!1&&this.pause();let e=this[ht]?!1:super.emit("data",t);return this[rn](),e}[nu](){return this[In]?!1:(this[In]=!0,this.readable=!1,this[Bt]?(Ri(()=>this[wc]()),!0):this[wc]())}[wc](){if(this[Dr]){let e=this[Dr].end();if(e){for(let n of this[nt])n.dest.write(e);this[ht]||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[Rt]?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[ht]=!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[nn])return e();let i,o,a=x=>{this.off("data",d),this.off("end",f),this.off(De,u),e(),o(x)},d=x=>{this.off("error",a),this.off("end",f),this.off(De,u),this.pause(),i({value:x,done:!!this[nn]})},f=()=>{this.off("error",a),this.off("data",d),this.off(De,u),e(),i({done:!0,value:void 0})},u=()=>a(new Error("stream destroyed"));return new Promise((x,p)=>{o=p,i=x,this.once(De,u),this.once("error",a),this.once("end",f),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ht]=!1;let t=!1,e=()=>(this.pause(),this.off(gc,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(gc,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[ht]=!0,this[je].length=0,this[We]=0;let e=this;return typeof e.close=="function"&&!this[$s]&&e.close(),t?this.emit("error",t):this.emit(De),this}static get isStream(){return Jw}},s_=ct.writev,Ln=Symbol("_autoClose"),Lt=Symbol("_close"),Pi=Symbol("_ended"),he=Symbol("_fd"),yc=Symbol("_finished"),cn=Symbol("_flags"),Ec=Symbol("_flush"),qc=Symbol("_handleChunk"),Gc=Symbol("_makeBuf"),Gi=Symbol("_mode"),Xs=Symbol("_needDrain"),qr=Symbol("_onerror"),Gr=Symbol("_onopen"),bc=Symbol("_onread"),Br=Symbol("_onwrite"),Mn=Symbol("_open"),Ot=Symbol("_path"),Cn=Symbol("_pos"),zt=Symbol("_queue"),zr=Symbol("_read"),vc=Symbol("_readSize"),an=Symbol("_reading"),Di=Symbol("_remain"),Sc=Symbol("_size"),ao=Symbol("_write"),$n=Symbol("_writing"),co=Symbol("_defaultFlag"),er=Symbol("_errored"),ld=class extends ir{[er]=!1;[he];[Ot];[vc];[an]=!1;[Sc];[Di];[Ln];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[er]=!1,this[he]=typeof e.fd=="number"?e.fd:void 0,this[Ot]=t,this[vc]=e.readSize||16*1024*1024,this[an]=!1,this[Sc]=typeof e.size=="number"?e.size:1/0,this[Di]=this[Sc],this[Ln]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[he]=="number"?this[zr]():this[Mn]()}get fd(){return this[he]}get path(){return this[Ot]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Mn](){ct.open(this[Ot],"r",(t,e)=>this[Gr](t,e))}[Gr](t,e){t?this[qr](t):(this[he]=e,this.emit("open",e),this[zr]())}[Gc](){return Buffer.allocUnsafe(Math.min(this[vc],this[Di]))}[zr](){if(!this[an]){this[an]=!0;let t=this[Gc]();if(t.length===0)return process.nextTick(()=>this[bc](null,0,t));ct.read(this[he],t,0,t.length,null,(e,n,i)=>this[bc](e,n,i))}}[bc](t,e,n){this[an]=!1,t?this[qr](t):this[qc](e,n)&&this[zr]()}[Lt](){if(this[Ln]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ct.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[qr](t){this[an]=!0,this[Lt](),this.emit("error",t)}[qc](t,e){let n=!1;return this[Di]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[Di]<=0)&&(n=!1,this[Lt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[he]=="number"&&this[zr](),!1;case"error":return this[er]?!1:(this[er]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},o_=class extends ld{[Mn](){let t=!0;try{this[Gr](null,ct.openSync(this[Ot],"r")),t=!1}finally{t&&this[Lt]()}}[zr](){let t=!0;try{if(!this[an]){this[an]=!0;do{let e=this[Gc](),n=e.length===0?0:ct.readSync(this[he],e,0,e.length,null);if(!this[qc](n,e))break}while(!0);this[an]=!1}t=!1}finally{t&&this[Lt]()}}[Lt](){if(this[Ln]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ct.closeSync(t),this.emit("close")}}},So=class extends $w{readable=!1;writable=!0;[er]=!1;[$n]=!1;[Pi]=!1;[zt]=[];[Xs]=!1;[Ot];[Gi];[Ln];[he];[co];[cn];[yc]=!1;[Cn];constructor(t,e){e=e||{},super(e),this[Ot]=t,this[he]=typeof e.fd=="number"?e.fd:void 0,this[Gi]=e.mode===void 0?438:e.mode,this[Cn]=typeof e.start=="number"?e.start:void 0,this[Ln]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[Cn]!==void 0?"r+":"w";this[co]=e.flags===void 0,this[cn]=e.flags===void 0?n:e.flags,this[he]===void 0&&this[Mn]()}emit(t,...e){if(t==="error"){if(this[er])return!1;this[er]=!0}return super.emit(t,...e)}get fd(){return this[he]}get path(){return this[Ot]}[qr](t){this[Lt](),this[$n]=!0,this.emit("error",t)}[Mn](){ct.open(this[Ot],this[cn],this[Gi],(t,e)=>this[Gr](t,e))}[Gr](t,e){this[co]&&this[cn]==="r+"&&t&&t.code==="ENOENT"?(this[cn]="w",this[Mn]()):t?this[qr](t):(this[he]=e,this.emit("open",e),this[$n]||this[Ec]())}end(t,e){return t&&this.write(t,e),this[Pi]=!0,!this[$n]&&!this[zt].length&&typeof this[he]=="number"&&this[Br](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Pi]?(this.emit("error",new Error("write() after end()")),!1):this[he]===void 0||this[$n]||this[zt].length?(this[zt].push(t),this[Xs]=!0,!1):(this[$n]=!0,this[ao](t),!0)}[ao](t){ct.write(this[he],t,0,t.length,this[Cn],(e,n)=>this[Br](e,n))}[Br](t,e){t?this[qr](t):(this[Cn]!==void 0&&typeof e=="number"&&(this[Cn]+=e),this[zt].length?this[Ec]():(this[$n]=!1,this[Pi]&&!this[yc]?(this[yc]=!0,this[Lt](),this.emit("finish")):this[Xs]&&(this[Xs]=!1,this.emit("drain"))))}[Ec](){if(this[zt].length===0)this[Pi]&&this[Br](null,0);else if(this[zt].length===1)this[ao](this[zt].pop());else{let t=this[zt];this[zt]=[],s_(this[he],t,this[Cn],(e,n)=>this[Br](e,n))}}[Lt](){if(this[Ln]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ct.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Nu=class extends So{[Mn](){let t;if(this[co]&&this[cn]==="r+")try{t=ct.openSync(this[Ot],this[cn],this[Gi])}catch(e){if(e?.code==="ENOENT")return this[cn]="w",this[Mn]();throw e}else t=ct.openSync(this[Ot],this[cn],this[Gi]);this[Gr](null,t)}[Lt](){if(this[Ln]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ct.closeSync(t),this.emit("close")}}[ao](t){let e=!0;try{this[Br](null,ct.writeSync(this[he],t,0,t.length,this[Cn])),e=!1}finally{if(e)try{this[Lt]()}catch{}}}},d_=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"]]),l_=t=>!!t.sync&&!!t.file,f_=t=>!t.sync&&!!t.file,u_=t=>!!t.sync&&!t.file,h_=t=>!t.sync&&!t.file,x_=t=>!!t.file,p_=t=>d_.get(t)||t,fd=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=p_(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Yi=(t,e,n,i,o)=>Object.assign((a=[],d,f)=>{Array.isArray(a)&&(d=a,a={}),typeof d=="function"&&(f=d,d=void 0),d=d?Array.from(d):[];let u=fd(a);if(o?.(u,d),l_(u)){if(typeof f=="function")throw new TypeError("callback not supported for sync tar functions");return t(u,d)}else if(f_(u)){let x=e(u,d);return f?x.then(()=>f(),f):x}else if(u_(u)){if(typeof f=="function")throw new TypeError("callback not supported for sync tar functions");return n(u,d)}else if(h_(u)){if(typeof f=="function")throw new TypeError("callback only supported with file option");return i(u,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:o}),w_=m_.constants||{ZLIB_VERNUM:4736},jt=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},w_)),__=tr.concat,iu=Object.getOwnPropertyDescriptor(tr,"concat"),y_=t=>t,Ic=iu?.writable===!0||iu?.set!==void 0?t=>{tr.concat=t?y_:__}:t=>{},nr=Symbol("_superWrite"),Ys=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"}},Ac=Symbol("flushFlag"),ud=class extends ir{#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 ru[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new ru[e](t)}catch(n){throw new Ys(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 Ys(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return jc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(tr.alloc(0),{[Ac]: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}[nr](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=tr.from(t,e)),this.#e)return;jc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},Ic(!0);let d;try{let u=typeof t[Ac]=="number"?t[Ac]:this.#r;d=this.#t._processChunk(t,u),Ic(!1)}catch(u){Ic(!1),this.#o(new Ys(u,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",u=>this.#o(new Ys(u,this.write)));let f;if(d)if(Array.isArray(d)&&d.length>0){let u=d[0];f=this[nr](tr.from(u));for(let x=1;x<d.length;x++)f=this[nr](d[x])}else f=this[nr](tr.from(d));return n&&n(),f}},Bu=class extends ud{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||jt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||jt.Z_FINISH,t.fullFlushFlag=jt.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(jt.Z_SYNC_FLUSH),jc(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)}}}},E_=class extends Bu{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[nr](t){return this.#e?(this.#e=!1,t[9]=255,super[nr](t)):super[nr](t)}},b_=class extends Bu{constructor(t){super(t,"Unzip")}},zu=class extends ud{constructor(t,e){t=t||{},t.flush=t.flush||jt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||jt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=jt.BROTLI_OPERATION_FLUSH,super(t,e)}},v_=class extends zu{constructor(t){super(t,"BrotliCompress")}},S_=class extends zu{constructor(t){super(t,"BrotliDecompress")}},Uu=class extends ud{constructor(t,e){t=t||{},t.flush=t.flush||jt.ZSTD_e_continue,t.finishFlush=t.finishFlush||jt.ZSTD_e_end,t.fullFlushFlag=jt.ZSTD_e_flush,super(t,e)}},I_=class extends Uu{constructor(t){super(t,"ZstdCompress")}},A_=class extends Uu{constructor(t){super(t,"ZstdDecompress")}},k_=(t,e)=>{if(Number.isSafeInteger(t))t<0?C_(t,e):T_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},T_=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},C_=(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]=Hu(o):o===0?e[i-1]=0:(n=!0,e[i-1]=qu(o))}},R_=t=>{let e=t[0],n=e===128?D_(t.subarray(1,t.length)):e===255?P_(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},P_=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var a=Number(t[o]),d;i?d=Hu(a):a===0?d=a:(i=!0,d=qu(a)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},D_=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},Hu=t=>(255^t)&255,qu=t=>(255^t)+1&255,O_={};Kw(O_,{code:()=>hd,isCode:()=>lo,isName:()=>L_,name:()=>Io,normalFsTypes:()=>Gu});var lo=t=>Io.has(t),L_=t=>hd.has(t),Gu=new Set(["0","","1","2","3","4","5","6","7","D"]),Io=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"]]),hd=new Map(Array.from(Io).map(t=>[t[1],t[0]])),M_=t=>t===void 0||t<0?void 0:t,rr=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=Vn(t,e+156,1),a=Gu.has(o),d=a?n:void 0,f=a?i:void 0;if(this.path=d?.path??Vn(t,e,100),this.mode=d?.mode??f?.mode??Rn(t,e+100,8),this.uid=d?.uid??f?.uid??Rn(t,e+108,8),this.gid=d?.gid??f?.gid??Rn(t,e+116,8),this.size=M_(d?.size??f?.size??Rn(t,e+124,12)),this.mtime=d?.mtime??f?.mtime??kc(t,e+136,12),this.cksum=Rn(t,e+148,12),f&&this.#n(f,!0),d&&this.#n(d),lo(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Vn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??f?.uname??Vn(t,e+265,32),this.gname=d?.gname??f?.gname??Vn(t,e+297,32),this.devmaj=d?.devmaj??f?.devmaj??Rn(t,e+329,8)??0,this.devmin=d?.devmin??f?.devmin??Rn(t,e+337,8)??0,t[e+475]!==0){let x=Vn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Vn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??kc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??kc(t,e+488,12)}let u=256;for(let x=e;x<e+148;x++)u+=t[x];for(let x=e+156;x<e+512;x++)u+=t[x];this.cksumValid=u===this.cksum,this.cksum===void 0&&u===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=N_(this.path||"",n),o=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Jn(t,e,100,o)||this.needPax,this.needPax=Pn(t,e+100,8,this.mode)||this.needPax,this.needPax=Pn(t,e+108,8,this.uid)||this.needPax,this.needPax=Pn(t,e+116,8,this.gid)||this.needPax,this.needPax=Pn(t,e+124,12,this.size)||this.needPax,this.needPax=Tc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Jn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Jn(t,e+265,32,this.uname)||this.needPax,this.needPax=Jn(t,e+297,32,this.gname)||this.needPax,this.needPax=Pn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Pn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Jn(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=Jn(t,e+345,155,a)||this.needPax:(this.needPax=Jn(t,e+345,130,a)||this.needPax,this.needPax=Tc(t,e+476,12,this.atime)||this.needPax,this.needPax=Tc(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let f=e;f<e+148;f++)d+=t[f];for(let f=e+156;f<e+512;f++)d+=t[f];return this.cksum=d,Pn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Io.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(hd.get(t));if(lo(e)||e==="Unsupported")this.#e=e;else if(lo(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},N_=(t,e)=>{let n=t,i="",o,a=Or.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=Or.dirname(n),n=Or.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=Or.join(Or.basename(i),n),i=Or.dirname(i));while(i!==a&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Vn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),kc=(t,e,n)=>F_(Rn(t,e,n)),F_=t=>t===void 0?void 0:new Date(t*1e3),Rn=(t,e,n)=>Number(t[e])&128?R_(t.subarray(e,e+n)):z_(t,e,n),B_=t=>isNaN(t)?void 0:t,z_=(t,e,n)=>B_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),U_={12:8589934591,8:2097151},Pn=(t,e,n,i)=>i===void 0?!1:i>U_[n]||i<0?(k_(i,t.subarray(e,e+n)),!0):(H_(t,e,n,i),!1),H_=(t,e,n,i)=>t.write(q_(i,n),e,n,"ascii"),q_=(t,e)=>G_(Math.floor(t).toString(8),e),G_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Tc=(t,e,n,i)=>i===void 0?!1:Pn(t,e,n,i.getTime()/1e3),j_=new Array(156).join("\0"),Jn=(t,e,n,i)=>i===void 0?!1:(t.write(i+j_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),_o=class ju{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 rr({path:("PaxHeader/"+W_(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(V_,Object.create(null)),V_=(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 f=+d;f>=0&&(t[a]=f);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[a]=+d;break}return t},J_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,te=J_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),Z_=class extends ir{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=te(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?te(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=te(t.path)),t.linkpath&&(t.linkpath=te(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},Ao=(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))},X_=1024*1024,Wc=Buffer.from([31,139]),Kc=Buffer.from([40,181,47,253]),Y_=Math.max(Wc.length,Kc.length),yt=Symbol("state"),Zn=Symbol("writeEntry"),sn=Symbol("readEntry"),Cc=Symbol("nextEntry"),su=Symbol("processEntry"),Ut=Symbol("extendedHeader"),Oi=Symbol("globalExtendedHeader"),An=Symbol("meta"),ou=Symbol("emitMeta"),_e=Symbol("buffer"),on=Symbol("queue"),kn=Symbol("ended"),Rc=Symbol("emittedEnd"),Xn=Symbol("emit"),Ce=Symbol("unzip"),Qs=Symbol("consumeChunk"),eo=Symbol("consumeChunkSub"),Pc=Symbol("consumeBody"),au=Symbol("consumeMeta"),cu=Symbol("consumeHeader"),Li=Symbol("consuming"),Dc=Symbol("bufferConcat"),to=Symbol("maybeEnd"),Lr=Symbol("writing"),Ht=Symbol("aborted"),no=Symbol("onDone"),Yn=Symbol("sawValidEntry"),ro=Symbol("sawNullBlock"),io=Symbol("sawEOF"),du=Symbol("closeStream"),Q_=1e3,Mi=Symbol("compressedBytesRead"),Oc=Symbol("decompressedBytesRead"),lu=Symbol("checkDecompressionRatio"),ey=()=>!0,Xi=class extends g_{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[on]=[];[_e];[sn];[Zn];[yt]="begin";[An]="";[Ut];[Oi];[kn]=!1;[Ce];[Ht]=!1;[Yn];[ro]=!1;[io]=!1;[Lr]=!1;[Li]=!1;[Rc]=!1;[Mi]=0;[Oc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(no,()=>{(this[yt]==="begin"||this[Yn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(no,t.ondone):this.on(no,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:Q_,this.maxMetaEntrySize=t.maxMetaEntrySize||X_,this.filter=typeof t.filter=="function"?t.filter:ey;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[du]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){Ao(this,t,e,n)}[cu](t,e){this[Yn]===void 0&&(this[Yn]=!1);let n;try{n=new rr(t,e,this[Ut],this[Oi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[ro]?(this[io]=!0,this[yt]==="begin"&&(this[yt]="header"),this[Xn]("eof")):(this[ro]=!0,this[Xn]("nullBlock"));else if(this[ro]=!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[Zn]=new Z_(n,this[Ut],this[Oi]);if(!this[Yn])if(o.remain){let a=()=>{o.invalid||(this[Yn]=!0)};o.on("end",a)}else this[Yn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Xn]("ignoredEntry",o),this[yt]="ignore",o.resume()):o.size>0&&(this[An]="",o.on("data",a=>this[An]+=a),this[yt]="meta"):(this[Ut]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Xn]("ignoredEntry",o),this[yt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[yt]="body":(this[yt]="header",o.end()),this[sn]?this[on].push(o):(this[on].push(o),this[Cc]())))}}}[du](){queueMicrotask(()=>this.emit("close"))}[su](t){let e=!0;if(!t)this[sn]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[sn]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Cc]()),e=!1);return e}[Cc](){do;while(this[su](this[on].shift()));if(this[on].length===0){let t=this[sn];!t||t.flowing||t.size===t.remain?this[Lr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Pc](t,e){let n=this[Zn];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[yt]="header",this[Zn]=void 0,n.end()),o.length}[au](t,e){let n=this[Zn],i=this[Pc](t,e);return!this[Zn]&&n&&this[ou](n),i}[Xn](t,e,n){this[on].length===0&&!this[sn]?this.emit(t,e,n):this[on].push([t,e,n])}[ou](t){switch(this[Xn]("meta",this[An]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ut]=_o.parse(this[An],this[Ut],!1);break;case"GlobalExtendedHeader":this[Oi]=_o.parse(this[An],this[Oi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ut]??Object.create(null);this[Ut]=e,e.path=this[An].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ut]||Object.create(null);this[Ut]=e,e.linkpath=this[An].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Ht]){if(this[Ce]){let e=this[Ce];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Ht]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[lu](t){this[Oc]+=t.length;let e=this[Oc]/this[Mi];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[Ht])return n?.(),!1;if((this[Ce]===void 0||this.brotli===void 0&&this[Ce]===!1)&&t){if(this[_e]&&(t=Buffer.concat([this[_e],t]),this[_e]=void 0),t.length<Y_)return this[_e]=t,n?.(),!0;for(let d=0;this[Ce]===void 0&&d<Wc.length;d++)t[d]!==Wc[d]&&(this[Ce]=!1);let o=!1;if(this[Ce]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Kc.length;d++)if(t[d]!==Kc[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[Ce]===!1&&a)if(t.length<512)if(this[kn])this.brotli=!0;else return this[_e]=t,n?.(),!0;else try{new rr(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ce]===void 0||this[Ce]===!1&&(this.brotli||o)){let d=this[kn];this[kn]=!1,this[Ce]=this[Ce]===void 0?new b_({}):o?new A_({}):new S_({}),this[Ce].on("data",u=>{this[lu](u)&&this[Qs](u)}),this[Ce].on("error",u=>{this[Ht]||this.abort(u)}),this[Ce].on("end",()=>{this[kn]=!0,this[Qs]()}),this[Lr]=!0,this[Mi]+=t.length;let f=!!this[Ce][d?"end":"write"](t);return this[Lr]=!1,n?.(),f}}this[Lr]=!0,this[Ce]?(this[Mi]+=t.length,this[Ce].write(t)):this[Qs](t),this[Lr]=!1;let i=this[on].length>0?!1:this[sn]?this[sn].flowing:!0;return!i&&this[on].length===0&&this[sn]?.once("drain",()=>this.emit("drain")),n?.(),i}[Dc](t){t&&!this[Ht]&&(this[_e]=this[_e]?Buffer.concat([this[_e],t]):t)}[to](){if(this[kn]&&!this[Rc]&&!this[Ht]&&!this[Li]){this[Rc]=!0;let t=this[Zn];if(t?.blockRemain){let e=this[_e]?this[_e].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[_e]&&t.write(this[_e]),t.end()}this[Xn](no)}}[Qs](t){if(this[Li]&&t)this[Dc](t);else if(!t&&!this[_e])this[to]();else if(t){if(this[Li]=!0,this[_e]){this[Dc](t);let e=this[_e];this[_e]=void 0,this[eo](e)}else this[eo](t);for(;this[_e]&&this[_e]?.length>=512&&!this[Ht]&&!this[io];){let e=this[_e];this[_e]=void 0,this[eo](e)}this[Li]=!1}(!this[_e]||this[kn])&&this[to]()}[eo](t){let e=0,n=t.length;for(;e+512<=n&&!this[Ht]&&!this[io];)switch(this[yt]){case"begin":case"header":this[cu](t,e),e+=512;break;case"ignore":case"body":e+=this[Pc](t,e);break;case"meta":e+=this[au](t,e);break;default:throw new Error("invalid state: "+this[yt])}e<n&&(this[_e]=this[_e]?Buffer.concat([t.subarray(e),this[_e]]):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[Ht]||(this[Ce]?(t&&(this[Mi]+=t.length,this[Ce].write(t)),this[Ce].end()):(this[kn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[to]())),this}},ji=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)},ty=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Wu=(t,e)=>{let n=new Map(e.map(a=>[ji(a),!0])),i=t.filter,o=(a,d="")=>{let f=d||c_(a).root||".",u;if(a===f)u=!1;else{let x=n.get(a);u=x!==void 0?x:o(a_(a),f)}return n.set(a,u),u};t.filter=i?(a,d)=>i(a,d)&&o(ji(a)):a=>o(ji(a))},ny=t=>{let e=new Xi(t),n=t.file,i;try{i=Ur.openSync(n,"r");let o=Ur.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),f=Ur.readSync(i,d,0,o.size,0);e.end(f===d.byteLength?d:d.subarray(0,f))}else{let d=0,f=Buffer.allocUnsafe(a);for(;d<o.size;){let u=Ur.readSync(i,f,0,a,d);if(u===0)break;d+=u,e.write(f.subarray(0,u))}e.end()}}finally{if(typeof i=="number")try{Ur.closeSync(i)}catch{}}},ry=(t,e)=>{let n=new Xi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Ur.stat(o,(f,u)=>{if(f)d(f);else{let x=new ld(o,{readSize:i,size:u.size});x.on("error",d),x.pipe(n)}})})},jr=Yi(ny,ry,t=>new Xi(t),t=>new Xi(t),(t,e)=>{e?.length&&Wu(t,e),t.noResume||ty(t)}),Ku=(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:sy,parse:uu}=iy,xd=t=>{let e="",n=uu(t);for(;sy(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=uu(t)}return[e,t]},ko=["|","<",">","?",":"],pd=ko.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),oy=new Map(ko.map((t,e)=>[t,pd[e]])),ay=new Map(pd.map((t,e)=>[t,ko[e]])),hu=t=>ko.reduce((e,n)=>e.split(n).join(oy.get(n)),t),cy=t=>pd.reduce((e,n)=>e.split(n).join(ay.get(n)),t),$u=(t,e)=>e?(t=te(t).replace(/^\.(\/|$)/,""),ji(e)+"/"+t):te(t),dy=16*1024*1024,xu=Symbol("process"),pu=Symbol("file"),gu=Symbol("directory"),$c=Symbol("symlink"),mu=Symbol("hardlink"),Ni=Symbol("header"),fo=Symbol("read"),Vc=Symbol("lstat"),uo=Symbol("onlstat"),Jc=Symbol("onread"),Zc=Symbol("onreadlink"),Xc=Symbol("openfile"),Yc=Symbol("onopenfile"),Dn=Symbol("close"),Eo=Symbol("mode"),Qc=Symbol("awaitDrain"),Lc=Symbol("ondrain"),Gt=Symbol("prefix"),Vu=class extends ir{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=fd(e);super(),this.path=te(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||dy,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=te(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?te(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]=xd(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=cy(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=te(n.absolute||fu.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[uo](o):this[Vc]()}warn(t,e,n={}){return Ao(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Vc](){qt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[uo](e)})}[uo](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=uy(t),this.emit("stat",t),this[xu]()}[xu](){switch(this.type){case"File":return this[pu]();case"Directory":return this[gu]();case"SymbolicLink":return this[$c]();default:return this.end()}}[Eo](t){return Ku(t,this.type==="Directory",this.portable)}[Gt](t){return $u(t,this.prefix)}[Ni](){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 rr({path:this[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](this.linkpath):this.linkpath,mode:this[Eo](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 _o({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[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[gu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ni](),this.end()}[$c](){qt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Zc](e)})}[Zc](t){this.linkpath=te(t),this[Ni](),this.end()}[mu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=te(fu.relative(this.cwd,t)),this.stat.size=0,this[Ni](),this.end()}[pu](){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[mu](e);this.linkCache.set(t,this.absolute)}if(this[Ni](),this.stat.size===0)return this.end();this[Xc]()}[Xc](){qt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Yc](e)})}[Yc](t){if(this.fd=t,this.#e)return this[Dn]();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[fo]()}[fo](){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");qt.read(t,e,n,i,o,(a,d)=>{if(a)return this[Dn](()=>this.emit("error",a));this[Jc](d)})}[Dn](t=()=>{}){this.fd!==void 0&&qt.close(this.fd,t)}[Jc](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[Dn](()=>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[Dn](()=>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[Lc]():this[Qc](()=>this[Lc]())}[Qc](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)}[Lc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Dn](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[fo]()}},ly=class extends Vu{sync=!0;[Vc](){this[uo](qt.lstatSync(this.absolute))}[$c](){this[Zc](qt.readlinkSync(this.absolute))}[Xc](){this[Yc](qt.openSync(this.absolute,"r"))}[fo](){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=qt.readSync(e,n,i,o,a);this[Jc](d),t=!1}finally{if(t)try{this[Dn](()=>{})}catch{}}}[Qc](t){t()}[Dn](t=()=>{}){this.fd!==void 0&&qt.closeSync(this.fd),t()}},fy=class extends ir{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 Ao(this,t,e,n)}constructor(t,e={}){let n=fd(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=te(t.path),this.mode=t.mode!==void 0?this[Eo](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?te(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[d,f]=xd(this.path);d&&typeof f=="string"&&(this.path=f,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new rr({path:this[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](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 _o({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[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](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)}[Gt](t){return $u(t,this.prefix)}[Eo](t){return Ku(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}},uy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",hy=class Hr{tail;head;length=0;static create(e=[]){return new Hr(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++)py(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)gy(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 Hr;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 Hr;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 Hr;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 Hr;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=xy(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 xy(t,e,n){let i=e,o=e?e.next:t.head,a=new gd(n,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function py(t,e){t.tail=new gd(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function gy(t,e){t.head=new gd(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var gd=class{list;next;prev;value;constructor(t,e,n,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,n?(n.prev=this,this.next=n):this.next=void 0}},_u=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},yu=Buffer.alloc(1024),ho=Symbol("onStat"),Fi=Symbol("ended"),Pt=Symbol("queue"),Bi=Symbol("pendingLinks"),Tn=Symbol("current"),Qn=Symbol("process"),zi=Symbol("processing"),so=Symbol("processJob"),Dt=Symbol("jobs"),Mc=Symbol("jobDone"),xo=Symbol("addFSEntry"),Eu=Symbol("addTarEntry"),ed=Symbol("stat"),td=Symbol("readdir"),po=Symbol("onreaddir"),go=Symbol("pipe"),bu=Symbol("entry"),Nc=Symbol("entryOpt"),mo=Symbol("writeEntryClass"),Ju=Symbol("write"),Fc=Symbol("ondrain"),To=class extends ir{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[mo];onWriteEntry;[Pt];[Bi]=new Map;[Dt]=0;[zi]=!1;[Fi]=!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=te(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[mo]=Vu,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 E_(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new v_(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new I_(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[Fc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Fc]);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[Pt]=new hy,this[Dt]=0,this.jobs=Number(t.jobs)||4,this[zi]=!1,this[Fi]=!1}[Ju](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[Fi]=!0,this[Qn](),n&&n(),this}write(t){if(this[Fi])throw new Error("write after end");return typeof t=="string"?this[xo](t):this[Eu](t),this.flowing}[Eu](t){let e=te(wu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new _u(t.path,e);n.entry=new fy(t,this[Nc](n)),n.entry.on("end",()=>this[Mc](n)),this[Dt]+=1,this[Pt].push(n)}this[Qn]()}[xo](t){let e=te(wu.resolve(this.cwd,t));this[Pt].push(new _u(t,e)),this[Qn]()}[ed](t){t.pending=!0,this[Dt]+=1;let e=this.follow?"stat":"lstat";yo[e](t.absolute,(n,i)=>{t.pending=!1,this[Dt]-=1,n?this.emit("error",n):this[ho](t,i)})}[ho](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[Tn])this[so](t);else{let n=`${e.dev}:${e.ino}`,i=this[Bi].get(n);i?i.push(t):this[Bi].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Qn]()}[td](t){t.pending=!0,this[Dt]+=1,yo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[Dt]-=1,e)return this.emit("error",e);this[po](t,n)})}[po](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Qn]()}[Qn](){if(!this[zi]){this[zi]=!0;for(let t=this[Pt].head;t&&this[Dt]<this.jobs;t=t.next)if(this[so](t.value),t.value.ignore){let e=t.next;this[Pt].removeNode(t),t.next=e}this[zi]=!1,this[Fi]&&this[Pt].length===0&&this[Dt]===0&&(this.zip?this.zip.end(yu):(super.write(yu),super.end()))}}get[Tn](){return this[Pt]&&this[Pt].head&&this[Pt].head.value}[Mc](t){this[Pt].shift(),this[Dt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Bi].get(n);if(i){this[Bi].delete(n);for(let o of i)o.pending=!1,this[so](o)}}this[Qn]()}[so](t){if(t.pending&&t.pendingLink&&t===this[Tn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Tn]&&!t.piped&&this[go](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[ho](t,e):this[ed](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[po](t,e):this[td](t),!t.readdir)return}if(t.entry=this[bu](t),!t.entry){t.ignore=!0;return}t===this[Tn]&&!t.piped&&this[go](t)}}}[Nc](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}}[bu](t){this[Dt]+=1;try{return new this[mo](t.path,this[Nc](t)).on("end",()=>this[Mc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Fc](){this[Tn]&&this[Tn].entry&&this[Tn].entry.resume()}[go](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[xo](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={}){Ao(this,t,e,n)}},md=class extends To{sync=!0;constructor(t){super(t),this[mo]=ly}pause(){}resume(){}[ed](t){let e=this.follow?"statSync":"lstatSync";this[ho](t,yo[e](t.absolute))}[td](t){this[po](t,yo.readdirSync(t.absolute))}[go](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[xo](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Ju](i)})}},my=(t,e)=>{let n=new md(t),i=new Nu(t.file,{mode:t.mode||438});n.pipe(i),Zu(n,e)},wy=(t,e)=>{let n=new To(t),i=new So(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 Xu(n,e).catch(a=>n.emit("error",a)),o},Zu=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?jr({file:Fu.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Xu=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await jr({file:Fu.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},_y=(t,e)=>{let n=new md(t);return Zu(n,e),n},yy=(t,e)=>{let n=new To(t);return Xu(n,e).catch(i=>n.emit("error",i)),n},GT=Yi(my,wy,_y,yy,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),by=process.env.__FAKE_PLATFORM__||process.platform,t0=by==="win32",{O_CREAT:n0,O_NOFOLLOW:vu,O_TRUNC:r0,O_WRONLY:i0}=e0.constants,s0=Number(process.env.__FAKE_FS_O_FILENAME__)||e0.constants.UV_FS_O_FILEMAP||0,vy=t0&&!!s0,Sy=512*1024,Iy=s0|r0|n0|i0,Su=!t0&&typeof vu=="number"?vu|r0|n0|i0:null,o0=Su!==null?()=>Su:vy?t=>t<Sy?Iy:"w":()=>"w",nd=(t,e,n)=>{try{return Co.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},bo=(t,e,n,i)=>{Co.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},Ay=(t,e,n,i,o)=>{if(e.isDirectory())a0(Wi.resolve(t,e.name),n,i,a=>{if(a)return o(a);let d=Wi.resolve(t,e.name);bo(d,n,i,o)});else{let a=Wi.resolve(t,e.name);bo(a,n,i,o)}},a0=(t,e,n,i)=>{Co.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 bo(t,e,n,i);let d=a.length,f=null,u=x=>{if(!f){if(x)return i(f=x);if(--d===0)return bo(t,e,n,i)}};for(let x of a)Ay(t,x,e,n,u)})},ky=(t,e,n,i)=>{e.isDirectory()&&c0(Wi.resolve(t,e.name),n,i),nd(Wi.resolve(t,e.name),n,i)},c0=(t,e,n)=>{let i;try{i=Co.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return nd(t,e,n);throw a}for(let o of i)ky(t,o,e,n);return nd(t,e,n)},d0=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"}},Ro=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"}},Cy=(t,e)=>{pt.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new d0(t,n?.code||"ENOTDIR")),e(n)})},Ry=(t,e,n)=>{t=te(t);let i=e.umask??18,o=e.mode|448,a=(o&i)!==0,d=e.uid,f=e.gid,u=typeof d=="number"&&typeof f=="number"&&(d!==e.processUid||f!==e.processGid),x=e.preserve,p=e.unlink,w=te(e.cwd),b=(v,I)=>{v?n(v):I&&u?a0(I,d,f,A=>b(A)):a?pt.chmod(t,o,n):n()};if(t===w)return Cy(t,b);if(x)return Ty.mkdir(t,{mode:o,recursive:!0}).then(v=>b(null,v??void 0),b);let _=te(vo.relative(w,t)).split("/");rd(w,_,o,p,w,void 0,b)},rd=(t,e,n,i,o,a,d)=>{if(e.length===0)return d(null,a);let f=e.shift(),u=te(vo.resolve(t+"/"+f));pt.mkdir(u,n,l0(u,e,n,i,o,a,d))},l0=(t,e,n,i,o,a,d)=>f=>{f?pt.lstat(t,(u,x)=>{if(u)u.path=u.path&&te(u.path),d(u);else if(x.isDirectory())rd(t,e,n,i,o,a,d);else if(i)pt.unlink(t,p=>{if(p)return d(p);pt.mkdir(t,n,l0(t,e,n,i,o,a,d))});else{if(x.isSymbolicLink())return d(new Ro(t,t+"/"+e.join("/")));d(f)}}):(a=a||t,rd(t,e,n,i,o,a,d))},Py=t=>{let e=!1,n;try{e=pt.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new d0(t,n??"ENOTDIR")}},Dy=(t,e)=>{t=te(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==0,a=e.uid,d=e.gid,f=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),u=e.preserve,x=e.unlink,p=te(e.cwd),w=v=>{v&&f&&c0(v,a,d),o&&pt.chmodSync(t,i)};if(t===p)return Py(p),w();if(u)return w(pt.mkdirSync(t,{mode:i,recursive:!0})??void 0);let b=te(vo.relative(p,t)).split("/"),_;for(let v=b.shift(),I=p;v&&(I+="/"+v);v=b.shift()){I=te(vo.resolve(I));try{pt.mkdirSync(I,i),_=_||I}catch{let A=pt.lstatSync(I);if(A.isDirectory())continue;if(x){pt.unlinkSync(I),pt.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new Ro(I,I+"/"+b.join("/"))}}return w(_)},Bc=Object.create(null),Iu=1e4,Mr=new Set,Oy=t=>{Mr.has(t)?Mr.delete(t):Bc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Mr.add(t);let e=Bc[t],n=Mr.size-Iu;if(n>Iu/10){for(let i of Mr)if(Mr.delete(i),delete Bc[i],--n<=0)break}return e},Ly=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,My=Ly==="win32",Ny=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=f0(i,n)),e.push(n||"/"),e},[]),Fy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=My?["win32 parallelization disabled"]:t.map(i=>ji(f0(Oy(i))));let n=new Set(t.map(i=>Ny(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 f=d[1];if(!f){this.#e.delete(a);continue}if(d.shift(),typeof f=="function")o.add(f);else for(let u of f)o.add(u)}for(let a of i){let d=this.#e.get(a),f=d?.[0];if(!(!d||!(f instanceof Set)))if(f.size===1&&d.length===1){this.#e.delete(a);continue}else if(f.size===1){d.shift();let u=d[0];typeof u=="function"&&o.add(u)}else f.delete(t)}return this.#r.delete(t),o.forEach(a=>this.#i(a)),!0}},By=()=>process.umask(),Au=Symbol("onEntry"),id=Symbol("checkFs"),ku=Symbol("checkFs2"),sd=Symbol("isReusable"),Et=Symbol("makeFs"),od=Symbol("file"),ad=Symbol("directory"),wo=Symbol("link"),Tu=Symbol("symlink"),Cu=Symbol("hardlink"),qi=Symbol("ensureNoSymlink"),Ru=Symbol("unsupported"),Pu=Symbol("checkPath"),zc=Symbol("stripAbsolutePath"),On=Symbol("mkdir"),Ke=Symbol("onError"),oo=Symbol("pending"),Du=Symbol("pend"),Nr=Symbol("unpend"),Uc=Symbol("ended"),Hc=Symbol("maybeClose"),cd=Symbol("skip"),Ki=Symbol("doChown"),$i=Symbol("uid"),Vi=Symbol("gid"),Ji=Symbol("checkedCwd"),zy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Zi=zy==="win32",Uy=1024,Hy=(t,e)=>{if(!Zi)return se.unlink(t,e);let n=t+".DELETE."+Qu(16).toString("hex");se.rename(t,n,i=>{if(i)return e(i);se.unlink(n,e)})},qy=t=>{if(!Zi)return se.unlinkSync(t);let e=t+".DELETE."+Qu(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},Ou=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,wd=class extends Xi{[Uc]=!1;[Ji]=!1;[oo]=0;reservations=new Fy;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[Uc]=!0,this[Hc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:Uy,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=te(Ue.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:By():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[Au](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Hc](){this[Uc]&&this[oo]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[zc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,a]=xd(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 f=Ue.posix.dirname(t.path),u=Ue.posix.normalize(Ue.posix.join(f,d.join("/")));if(u.startsWith("../")||u==="..")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}[Pu](t){let e=te(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=te(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[zc](t,"path")||!this[zc](t,"linkpath"))return!1;if(t.absolute=Ue.isAbsolute(t.path)?te(Ue.resolve(t.path)):te(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:te(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+hu(String(t.absolute).slice(i.length));let{root:o}=Ue.win32.parse(t.path);t.path=o+hu(t.path.slice(o.length))}return!0}[Au](t){if(!this[Pu](t))return t.resume();switch(Ey.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[id](t);default:return this[Ru](t)}}[Ke](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Nr](),e.resume())}[On](t,e,n){Ry(te(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},n)}[Ki](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[$i](t){return Ou(this.uid,t.uid,this.processUid)}[Vi](t){return Ou(this.gid,t.gid,this.processGid)}[od](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new So(String(t.absolute),{flags:o0(t.size),mode:n,autoClose:!1});i.on("error",f=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[Ke](f,t),e()});let o=1,a=f=>{if(f){i.fd&&se.close(i.fd,()=>{}),this[Ke](f,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,u=>{u?this[Ke](u,t):this[Nr](),e()})};i.on("finish",()=>{let f=String(t.absolute),u=i.fd;if(typeof u=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,p=t.mtime;se.futimes(u,x,p,w=>w?se.utimes(f,x,p,b=>a(b&&w)):a())}if(typeof u=="number"&&this[Ki](t)){o++;let x=this[$i](t),p=this[Vi](t);typeof x=="number"&&typeof p=="number"&&se.fchown(u,x,p,w=>w?se.chown(f,x,p,b=>a(b&&w)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",f=>{this[Ke](f,t),e()}),t.pipe(d)),d.pipe(i)}[ad](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[On](String(t.absolute),n,i=>{if(i){this[Ke](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[Nr](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Ki](t)&&(o++,se.chown(String(t.absolute),Number(this[$i](t)),Number(this[Vi](t)),a)),a()})}[Ru](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Tu](t,e){let n=te(Ue.relative(this.cwd,Ue.resolve(Ue.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[qi](t,this.cwd,n,()=>this[wo](t,String(t.linkpath),"symlink",e),i=>{this[Ke](i,t),e()})}[Cu](t,e){let n=te(Ue.resolve(this.cwd,String(t.linkpath))),i=te(String(t.linkpath)).split("/");this[qi](t,this.cwd,i,()=>this[wo](t,n,"link",e),o=>{this[Ke](o,t),e()})}[qi](t,e,n,i,o){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Ue.resolve(e,a);se.lstat(d,(f,u)=>{if(f)return i();if(u?.isSymbolicLink())return o(new Ro(d,Ue.resolve(d,n.join("/"))));this[qi](t,d,n,i,o)})}[Du](){this[oo]++}[Nr](){this[oo]--,this[Hc]()}[cd](t){this[Nr](),t.resume()}[sd](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Zi}[id](t){this[Du]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[ku](t,n))}[ku](t,e){let n=d=>{e(d)},i=()=>{this[On](this.cwd,this.dmode,d=>{if(d){this[Ke](d,t),n();return}this[Ji]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=te(Ue.dirname(String(t.absolute)));if(d!==this.cwd)return this[On](d,this.dmode,f=>{if(f){this[Ke](f,t),n();return}a()})}a()},a=()=>{se.lstat(String(t.absolute),(d,f)=>{if(f&&(this.keep||this.newer&&f.mtime>(t.mtime??f.mtime))){this[cd](t),n();return}if(d||this[sd](t,f))return this[Et](null,t,n);if(f.isDirectory()){if(t.type==="Directory"){let u=this.chmod&&t.mode&&(f.mode&4095)!==t.mode,x=p=>this[Et](p??null,t,n);return u?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),u=>this[Et](u??null,t,n))}if(t.absolute===this.cwd)return this[Et](null,t,n);Hy(String(t.absolute),u=>this[Et](u??null,t,n))})};this[Ji]?o():i()}[Et](t,e,n){if(t){this[Ke](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[od](e,n);case"Link":return this[Cu](e,n);case"SymbolicLink":return this[Tu](e,n);case"Directory":case"GNUDumpDir":return this[ad](e,n)}}[wo](t,e,n,i){se[n](e,String(t.absolute),o=>{o?this[Ke](o,t):(this[Nr](),t.resume()),i()})}},Ui=t=>{try{return[null,t()]}catch(e){return[e,null]}},u0=class extends wd{sync=!0;[Et](t,e){return super[Et](t,e,()=>{})}[id](t){if(!this[Ji]){let o=this[On](this.cwd,this.dmode);if(o)return this[Ke](o,t);this[Ji]=!0}if(t.absolute!==this.cwd){let o=te(Ue.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[On](o,this.dmode);if(a)return this[Ke](a,t)}}let[e,n]=Ui(()=>se.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[cd](t);if(e||this[sd](t,n))return this[Et](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Ui(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[Et](d,t)}let[o]=Ui(()=>se.rmdirSync(String(t.absolute)));this[Et](o,t)}let[i]=t.absolute===this.cwd?[]:Ui(()=>qy(String(t.absolute)));this[Et](i,t)}[od](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let f;try{se.closeSync(o)}catch(u){f=u}(d||f)&&this[Ke](d||f,t),e()},o;try{o=se.openSync(String(t.absolute),o0(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[Ke](d,t)),t.pipe(a)),a.on("data",d=>{try{se.writeSync(o,d,0,d.length)}catch(f){i(f)}}),a.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let f=t.atime||new Date,u=t.mtime;try{se.futimesSync(o,f,u)}catch(x){try{se.utimesSync(String(t.absolute),f,u)}catch{d=x}}}if(this[Ki](t)){let f=this[$i](t),u=this[Vi](t);try{se.fchownSync(o,Number(f),Number(u))}catch(x){try{se.chownSync(String(t.absolute),Number(f),Number(u))}catch{d=d||x}}}i(d)})}[ad](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[On](String(t.absolute),n);if(i){this[Ke](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ki](t))try{se.chownSync(String(t.absolute),Number(this[$i](t)),Number(this[Vi](t)))}catch{}e(),t.resume()}[On](t,e){try{return Dy(te(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}}[qi](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[f,u]=Ui(()=>se.lstatSync(a));if(f)return i();if(u.isSymbolicLink())return o(new Ro(a,Ue.resolve(e,n.join("/"))))}i()}[wo](t,e,n,i){let o=`${n}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[Ke](a,t)}}},Gy=t=>{let e=new u0(t),n=t.file,i=Yu.statSync(n),o=t.maxReadSize||16*1024*1024;new o_(n,{readSize:o,size:i.size}).pipe(e)},jy=(t,e)=>{let n=new wd(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Yu.stat(o,(f,u)=>{if(f)d(f);else{let x=new ld(o,{readSize:i,size:u.size});x.on("error",d),x.pipe(n)}})})},h0=Yi(Gy,jy,t=>new u0(t),t=>new wd(t),(t,e)=>{e?.length&&Wu(t,e)}),Wy=(t,e)=>{let n=new md(t),i=!0,o,a;try{try{o=xt.openSync(t.file,"r+")}catch(u){if(u?.code==="ENOENT")o=xt.openSync(t.file,"w+");else throw u}let d=xt.fstatSync(o),f=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let p=0,w=0;p<512;p+=w){if(w=xt.readSync(o,f,p,f.length-p,a+p),a===0&&f[0]===31&&f[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let u=new rr(f);if(!u.cksumValid)break;let x=512*Math.ceil((u.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&u.mtime&&t.mtimeCache.set(String(u.path),u.mtime)}i=!1,Ky(t,n,a,o,e)}finally{if(i)try{xt.closeSync(o)}catch{}}},Ky=(t,e,n,i,o)=>{let a=new Nu(t.file,{fd:i,start:n});e.pipe(a),Vy(e,o)},$y=(t,e)=>{e=Array.from(e);let n=new To(t),i=(o,a,d)=>{let f=(b,_)=>{b?xt.close(o,v=>d(b)):d(null,_)},u=0;if(a===0)return f(null,0);let x=0,p=Buffer.alloc(512),w=(b,_)=>{if(b||_===void 0)return f(b);if(x+=_,x<512&&_)return xt.read(o,p,x,p.length-x,u+x,w);if(u===0&&p[0]===31&&p[1]===139)return f(new Error("cannot append to compressed archives"));if(x<512)return f(null,u);let v=new rr(p);if(!v.cksumValid)return f(null,u);let I=512*Math.ceil((v.size??0)/512);if(u+I+512>a||(u+=I+512,u>=a))return f(null,u);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,xt.read(o,p,0,512,u,w)};xt.read(o,p,0,512,u,w)};return new Promise((o,a)=>{n.on("error",a);let d="r+",f=(u,x)=>{if(u&&u.code==="ENOENT"&&d==="r+")return d="w+",xt.open(t.file,d,f);if(u||!x)return a(u);xt.fstat(x,(p,w)=>{if(p)return xt.close(x,()=>a(p));i(x,w.size,(b,_)=>{if(b)return a(b);let v=new So(t.file,{fd:x,start:_});n.pipe(v),v.on("error",a),v.on("close",o),Jy(n,e)})})};xt.open(t.file,d,f)})},Vy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?jr({file:x0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Jy=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await jr({file:x0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Hi=Yi(Wy,$y,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!x_(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")}),iC=Yi(Hi.syncFile,Hi.asyncFile,Hi.syncNoFile,Hi.asyncNoFile,(t,e=[])=>{Hi.validate?.(t,e),Zy(t)}),Zy=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))};tn();var rt={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",SET_CONFIG_OPTION:"_agent/setConfigOption",LIST_AVAILABLE_MODELS:"_agent/listAvailableModels"};function sr(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function p0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function Po(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function g0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function m0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function w0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function or(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Ct();import{homedir as Yy}from"node:os";import _0 from"node:path";var y0=".claude",E0="settings.json",Do=new Map;function b0(t){return _0.join(t,y0,E0)}async function v0(t,e){let n=b0(t),o=(Do.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>{let a=await Ye(n)??{};a.effortLevel=e,await ut(n,a)});Do.set(n,o);try{await o}finally{Do.get(n)===o&&Do.delete(n)}}async function S0(t){let n=(await Ye(b0(t)))?.effortLevel;return typeof n=="string"?n:void 0}async function I0(){let t=_0.join(Yy(),y0,E0),n=(await Ye(t))?.effortLevel;return typeof n=="string"?n:void 0}Wt();Ze();ne();Pe();Ze();function Qi(t,e){if(sr(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function _d(t,e){if(sr(t)==="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_CLOUD",`${e} is not allowed for cloud agent`)}function es(t){return t.startsWith("http://")||t.startsWith("https://")}function Wr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as QC}from"node:fs";import{dirname as t2,join as n2}from"node:path";import{fileURLToPath as i2}from"node:url";var Kt="0.3.2-alpha.106";var yd={"claude-code":{effort:["default","low","medium","high","xhigh","max"],fastMode:null},codex:{effort:["low","medium","high","xhigh"],fastMode:["off","on"]},hermes:{effort:null,fastMode:null},openclaw:{effort:null,fastMode:null}};function T0(t,e){return yd[t][e]}import{mkdir as xE,rm as G0}from"node:fs/promises";import{join as is}from"node:path";Ct();import{readFileSync as sE}from"node:fs";var oE=384;async function Ed(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await ut(t.agentEnvFile,n,{mode:oE})}function ar(t){try{let e=JSON.parse(sE(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Lo(t,e,n={},i=o=>o){return{...i({...t,...ar(e)}),...n}}Ct();function ts(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(aE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
|
|
89
|
+
`},configPath(t){return tk(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 Dg("schtasks",["/Create","/SC","ONLOGON","/TN",Wa,"/TR",n,"/RU",t.userName,"/F"]),Fl.info("task scheduler entry created",{task:Wa,logFile:t.logFile})},async uninstall(t){await Dg("schtasks",["/Delete","/TN",Wa,"/F"]).catch(e=>Fl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Fl.info("task scheduler entry removed",{task:Wa})}}});var Lg={};nc(Lg,{buildContext:()=>ak,getSupervisor:()=>ik,launchdSupervisor:()=>Ml,systemdSupervisor:()=>Nl,taskSchedulerSupervisor:()=>Bl});import{homedir as nk,userInfo as rk}from"node:os";function ik(t=process.platform){switch(t){case"darwin":return Ml;case"linux":return Nl;case"win32":return Bl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function ok(){let t={};for(let e of sk){let n=process.env[e];n&&(t[e]=n)}return t}function ak(){let t=Z();return{nodeBin:process.execPath,entry:Al(t),logFile:t.logFile,homeDir:nk(),userName:rk().username,isRoot:process.getuid?.()===0,env:ok()}}var sk,Mg=lt(()=>{"use strict";De();Ma();Tg();Rg();Og();sk=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});re();In();var hu=H("acp-installer-warmup"),aw=["claude-code","codex"];async function pu(t={}){let e=t.ensure??Pr,i=(await Promise.allSettled(aw.map(async o=>{let a=await e(o);hu.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&hu.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))})}an();re();import{readdir as vw}from"node:fs/promises";import{mkdir as wu,readFile as bw,writeFile as _u}from"node:fs/promises";import{join as dc}from"node:path";var Ew={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function Rr(t,e,n){await wu(t,{recursive:!0});let i=Ew[e],o=dc(t,i);return await _u(o,n??"","utf8"),o}async function lc(t,e,n){let i=dc(t,".claude");await wu(i,{recursive:!0});let o=dc(i,"settings.local.json"),a={};try{let u=await bw(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 _u(o,JSON.stringify(a,null,2),"utf8"),o}var st=H("agent-detail-sync"),Sw=6e4,Iw=5*6e4,js=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await vw(n)}catch(o){st.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}st.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let a=await ye(o,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){st.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,a)}catch(d){st.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),st.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){st.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){st.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await ye(e,this.opts.paths);if(!i){st.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){st.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let p=this.retryQueue.get(e),x=p?Math.min(p.currentDelay*2,Iw):Sw;this.retryQueue.set(e,{dueAt:Date.now()+x,currentDelay:x});return}if(o.agentId&&o.agentId!==e){st.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"?(st.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):o.deployType&&st.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){st.debug("detail sync: no diff",{agentId:e});return}await Oe(i,this.opts.paths),st.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}),st.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await Rr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Ud=on(Xu(),1);import{createHash as Ib}from"node:crypto";import{lstat as Dd,mkdir as Od,readFile as Ho,readdir as ih,rm as Ld,stat as Bd,writeFile as Md}from"node:fs/promises";import{homedir as Ab}from"node:os";import{basename as th,dirname as kb,join as pe,normalize as Cb,relative as zd,resolve as Nd,sep as sh}from"node:path";import{Readable as oh}from"node:stream";import{pipeline as ah}from"node:stream/promises";import $w from"events";import ft from"fs";import{EventEmitter as ld}from"node:events";import Mf from"node:stream";import{StringDecoder as Vw}from"node:string_decoder";import Bf from"node:path";import qr from"node:fs";import{dirname as a_,parse as c_}from"path";import{EventEmitter as g_}from"events";import Wc from"assert";import{Buffer as sr}from"buffer";import*as rf from"zlib";import m_ from"zlib";import{posix as Nr}from"node:path";import{basename as W_}from"node:path";import vo from"fs";import Wt from"fs";import ff from"path";import{win32 as iy}from"node:path";import _f from"path";import Qf from"node:fs";import by from"node:assert";import{randomBytes as e0}from"node:crypto";import oe from"node:fs";import Ge from"node:path";import t0 from"fs";import Do from"node:fs";import Vi from"node:path";import _t from"node:fs";import Cy from"node:fs/promises";import Ao from"node:path";import{join as f0}from"node:path";import wt from"node:fs";import x0 from"node:path";var Ww=Object.defineProperty,Kw=(t,e)=>{for(var n in e)Ww(t,n,{get:e[n],enumerable:!0})},Qu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Jw=t=>!!t&&typeof t=="object"&&(t instanceof cr||t instanceof Mf||Zw(t)||Yw(t)),Zw=t=>!!t&&typeof t=="object"&&t instanceof ld&&typeof t.pipe=="function"&&t.pipe!==Mf.Writable.prototype.pipe,Yw=t=>!!t&&typeof t=="object"&&t instanceof ld&&typeof t.write=="function"&&typeof t.end=="function",cn=Symbol("EOF"),dn=Symbol("maybeEmitEnd"),kn=Symbol("emittedEnd"),Js=Symbol("emittingEnd"),Pi=Symbol("emittedError"),Zs=Symbol("closed"),ef=Symbol("read"),Ys=Symbol("flush"),tf=Symbol("flushChunk"),Ot=Symbol("encoding"),Mr=Symbol("decoder"),We=Symbol("flowing"),Ri=Symbol("paused"),Ur=Symbol("resume"),Ke=Symbol("buffer"),ot=Symbol("pipes"),$e=Symbol("bufferLength"),gc=Symbol("bufferPush"),Xs=Symbol("bufferShift"),it=Symbol("objectMode"),Le=Symbol("destroyed"),mc=Symbol("error"),wc=Symbol("emitData"),nf=Symbol("emitEnd"),_c=Symbol("emitEnd2"),Ht=Symbol("async"),yc=Symbol("abort"),Qs=Symbol("aborted"),Di=Symbol("signal"),Zn=Symbol("dataListeners"),mt=Symbol("discarded"),Oi=t=>Promise.resolve().then(t),Xw=t=>t(),Qw=t=>t==="end"||t==="finish"||t==="prefinish",e_=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,t_=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Nf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Ur](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},n_=class extends Nf{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)}},r_=t=>!!t.objectMode,i_=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",cr=class extends ld{[We]=!1;[Ri]=!1;[ot]=[];[Ke]=[];[it];[Ot];[Ht];[Mr];[cn]=!1;[kn]=!1;[Js]=!1;[Zs]=!1;[Pi]=null;[$e]=0;[Le]=!1;[Di];[Qs]=!1;[Zn]=0;[mt]=!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");r_(e)?(this[it]=!0,this[Ot]=null):i_(e)?(this[Ot]=e.encoding,this[it]=!1):(this[it]=!1,this[Ot]=null),this[Ht]=!!e.async,this[Mr]=this[Ot]?new Vw(this[Ot]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ke]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[ot]});let{signal:n}=e;n&&(this[Di]=n,n.aborted?this[yc]():n.addEventListener("abort",()=>this[yc]()))}get bufferLength(){return this[$e]}get encoding(){return this[Ot]}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[it]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Ht]}set async(t){this[Ht]=this[Ht]||!!t}[yc](){this[Qs]=!0,this.emit("abort",this[Di]?.reason),this.destroy(this[Di]?.reason)}get aborted(){return this[Qs]}set aborted(t){}write(t,e,n){if(this[Qs])return!1;if(this[cn])throw new Error("write after end");if(this[Le])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[Ht]?Oi:Xw;if(!this[it]&&!Buffer.isBuffer(t)){if(t_(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(e_(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[it]?(this[We]&&this[$e]!==0&&this[Ys](!0),this[We]?this.emit("data",t):this[gc](t),this[$e]!==0&&this.emit("readable"),n&&i(n),this[We]):t.length?(typeof t=="string"&&!(e===this[Ot]&&!this[Mr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Ot]&&(t=this[Mr].write(t)),this[We]&&this[$e]!==0&&this[Ys](!0),this[We]?this.emit("data",t):this[gc](t),this[$e]!==0&&this.emit("readable"),n&&i(n),this[We]):(this[$e]!==0&&this.emit("readable"),n&&i(n),this[We])}read(t){if(this[Le])return null;if(this[mt]=!1,this[$e]===0||t===0||t&&t>this[$e])return this[dn](),null;this[it]&&(t=null),this[Ke].length>1&&!this[it]&&(this[Ke]=[this[Ot]?this[Ke].join(""):Buffer.concat(this[Ke],this[$e])]);let e=this[ef](t||null,this[Ke][0]);return this[dn](),e}[ef](t,e){if(this[it])this[Xs]();else{let n=e;t===n.length||t===null?this[Xs]():typeof n=="string"?(this[Ke][0]=n.slice(t),e=n.slice(0,t),this[$e]-=t):(this[Ke][0]=n.subarray(t),e=n.subarray(0,t),this[$e]-=t)}return this.emit("data",e),!this[Ke].length&&!this[cn]&&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[cn]=!0,this.writable=!1,(this[We]||!this[Ri])&&this[dn](),this}[Ur](){this[Le]||(!this[Zn]&&!this[ot].length&&(this[mt]=!0),this[Ri]=!1,this[We]=!0,this.emit("resume"),this[Ke].length?this[Ys]():this[cn]?this[dn]():this.emit("drain"))}resume(){return this[Ur]()}pause(){this[We]=!1,this[Ri]=!0,this[mt]=!1}get destroyed(){return this[Le]}get flowing(){return this[We]}get paused(){return this[Ri]}[gc](t){this[it]?this[$e]+=1:this[$e]+=t.length,this[Ke].push(t)}[Xs](){return this[it]?this[$e]-=1:this[$e]-=this[Ke][0].length,this[Ke].shift()}[Ys](t=!1){do;while(this[tf](this[Xs]())&&this[Ke].length);!t&&!this[Ke].length&&!this[cn]&&this.emit("drain")}[tf](t){return this.emit("data",t),this[We]}pipe(t,e){if(this[Le])return t;this[mt]=!1;let n=this[kn];return e=e||{},t===Qu.stdout||t===Qu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[ot].push(e.proxyErrors?new n_(this,t,e):new Nf(this,t,e)),this[Ht]?Oi(()=>this[Ur]()):this[Ur]()),t}unpipe(t){let e=this[ot].find(n=>n.dest===t);e&&(this[ot].length===1?(this[We]&&this[Zn]===0&&(this[We]=!1),this[ot]=[]):this[ot].splice(this[ot].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[mt]=!1,this[Zn]++,!this[ot].length&&!this[We]&&this[Ur]();else if(t==="readable"&&this[$e]!==0)super.emit("readable");else if(Qw(t)&&this[kn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Pi]){let i=e;this[Ht]?Oi(()=>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[Zn]=this.listeners("data").length,this[Zn]===0&&!this[mt]&&!this[ot].length&&(this[We]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Zn]=0,!this[mt]&&!this[ot].length&&(this[We]=!1)),e}get emittedEnd(){return this[kn]}[dn](){!this[Js]&&!this[kn]&&!this[Le]&&this[Ke].length===0&&this[cn]&&(this[Js]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Zs]&&this.emit("close"),this[Js]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Le&&this[Le])return!1;if(t==="data")return!this[it]&&!n?!1:this[Ht]?(Oi(()=>this[wc](n)),!0):this[wc](n);if(t==="end")return this[nf]();if(t==="close"){if(this[Zs]=!0,!this[kn]&&!this[Le])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[Pi]=n,super.emit(mc,n);let o=!this[Di]||this.listeners("error").length?super.emit("error",n):!1;return this[dn](),o}else if(t==="resume"){let o=super.emit("resume");return this[dn](),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[dn](),i}[wc](t){for(let n of this[ot])n.dest.write(t)===!1&&this.pause();let e=this[mt]?!1:super.emit("data",t);return this[dn](),e}[nf](){return this[kn]?!1:(this[kn]=!0,this.readable=!1,this[Ht]?(Oi(()=>this[_c]()),!0):this[_c]())}[_c](){if(this[Mr]){let e=this[Mr].end();if(e){for(let n of this[ot])n.dest.write(e);this[mt]||super.emit("data",e)}}for(let e of this[ot])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[it]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[it]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[it])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Ot]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Le,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[mt]=!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[cn])return e();let i,o,a=p=>{this.off("data",d),this.off("end",u),this.off(Le,f),e(),o(p)},d=p=>{this.off("error",a),this.off("end",u),this.off(Le,f),this.pause(),i({value:p,done:!!this[cn]})},u=()=>{this.off("error",a),this.off("data",d),this.off(Le,f),e(),i({done:!0,value:void 0})},f=()=>a(new Error("stream destroyed"));return new Promise((p,x)=>{o=x,i=p,this.once(Le,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[mt]=!1;let t=!1,e=()=>(this.pause(),this.off(mc,e),this.off(Le,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(mc,e),this.once(Le,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Le])return t?this.emit("error",t):this.emit(Le),this;this[Le]=!0,this[mt]=!0,this[Ke].length=0,this[$e]=0;let e=this;return typeof e.close=="function"&&!this[Zs]&&e.close(),t?this.emit("error",t):this.emit(Le),this}static get isStream(){return Jw}},s_=ft.writev,Nn=Symbol("_autoClose"),Ft=Symbol("_close"),Li=Symbol("_ended"),he=Symbol("_fd"),bc=Symbol("_finished"),hn=Symbol("_flags"),Ec=Symbol("_flush"),qc=Symbol("_handleChunk"),jc=Symbol("_makeBuf"),Ki=Symbol("_mode"),eo=Symbol("_needDrain"),Wr=Symbol("_onerror"),Kr=Symbol("_onopen"),vc=Symbol("_onread"),Hr=Symbol("_onwrite"),Fn=Symbol("_open"),Nt=Symbol("_path"),Rn=Symbol("_pos"),Gt=Symbol("_queue"),Gr=Symbol("_read"),Sc=Symbol("_readSize"),fn=Symbol("_reading"),Mi=Symbol("_remain"),Ic=Symbol("_size"),uo=Symbol("_write"),Yn=Symbol("_writing"),fo=Symbol("_defaultFlag"),ir=Symbol("_errored"),ud=class extends cr{[ir]=!1;[he];[Nt];[Sc];[fn]=!1;[Ic];[Mi];[Nn];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[ir]=!1,this[he]=typeof e.fd=="number"?e.fd:void 0,this[Nt]=t,this[Sc]=e.readSize||16*1024*1024,this[fn]=!1,this[Ic]=typeof e.size=="number"?e.size:1/0,this[Mi]=this[Ic],this[Nn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[he]=="number"?this[Gr]():this[Fn]()}get fd(){return this[he]}get path(){return this[Nt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Fn](){ft.open(this[Nt],"r",(t,e)=>this[Kr](t,e))}[Kr](t,e){t?this[Wr](t):(this[he]=e,this.emit("open",e),this[Gr]())}[jc](){return Buffer.allocUnsafe(Math.min(this[Sc],this[Mi]))}[Gr](){if(!this[fn]){this[fn]=!0;let t=this[jc]();if(t.length===0)return process.nextTick(()=>this[vc](null,0,t));ft.read(this[he],t,0,t.length,null,(e,n,i)=>this[vc](e,n,i))}}[vc](t,e,n){this[fn]=!1,t?this[Wr](t):this[qc](e,n)&&this[Gr]()}[Ft](){if(this[Nn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ft.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Wr](t){this[fn]=!0,this[Ft](),this.emit("error",t)}[qc](t,e){let n=!1;return this[Mi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[Mi]<=0)&&(n=!1,this[Ft](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[he]=="number"&&this[Gr](),!1;case"error":return this[ir]?!1:(this[ir]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},o_=class extends ud{[Fn](){let t=!0;try{this[Kr](null,ft.openSync(this[Nt],"r")),t=!1}finally{t&&this[Ft]()}}[Gr](){let t=!0;try{if(!this[fn]){this[fn]=!0;do{let e=this[jc](),n=e.length===0?0:ft.readSync(this[he],e,0,e.length,null);if(!this[qc](n,e))break}while(!0);this[fn]=!1}t=!1}finally{t&&this[Ft]()}}[Ft](){if(this[Nn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ft.closeSync(t),this.emit("close")}}},ko=class extends $w{readable=!1;writable=!0;[ir]=!1;[Yn]=!1;[Li]=!1;[Gt]=[];[eo]=!1;[Nt];[Ki];[Nn];[he];[fo];[hn];[bc]=!1;[Rn];constructor(t,e){e=e||{},super(e),this[Nt]=t,this[he]=typeof e.fd=="number"?e.fd:void 0,this[Ki]=e.mode===void 0?438:e.mode,this[Rn]=typeof e.start=="number"?e.start:void 0,this[Nn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[Rn]!==void 0?"r+":"w";this[fo]=e.flags===void 0,this[hn]=e.flags===void 0?n:e.flags,this[he]===void 0&&this[Fn]()}emit(t,...e){if(t==="error"){if(this[ir])return!1;this[ir]=!0}return super.emit(t,...e)}get fd(){return this[he]}get path(){return this[Nt]}[Wr](t){this[Ft](),this[Yn]=!0,this.emit("error",t)}[Fn](){ft.open(this[Nt],this[hn],this[Ki],(t,e)=>this[Kr](t,e))}[Kr](t,e){this[fo]&&this[hn]==="r+"&&t&&t.code==="ENOENT"?(this[hn]="w",this[Fn]()):t?this[Wr](t):(this[he]=e,this.emit("open",e),this[Yn]||this[Ec]())}end(t,e){return t&&this.write(t,e),this[Li]=!0,!this[Yn]&&!this[Gt].length&&typeof this[he]=="number"&&this[Hr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Li]?(this.emit("error",new Error("write() after end()")),!1):this[he]===void 0||this[Yn]||this[Gt].length?(this[Gt].push(t),this[eo]=!0,!1):(this[Yn]=!0,this[uo](t),!0)}[uo](t){ft.write(this[he],t,0,t.length,this[Rn],(e,n)=>this[Hr](e,n))}[Hr](t,e){t?this[Wr](t):(this[Rn]!==void 0&&typeof e=="number"&&(this[Rn]+=e),this[Gt].length?this[Ec]():(this[Yn]=!1,this[Li]&&!this[bc]?(this[bc]=!0,this[Ft](),this.emit("finish")):this[eo]&&(this[eo]=!1,this.emit("drain"))))}[Ec](){if(this[Gt].length===0)this[Li]&&this[Hr](null,0);else if(this[Gt].length===1)this[uo](this[Gt].pop());else{let t=this[Gt];this[Gt]=[],s_(this[he],t,this[Rn],(e,n)=>this[Hr](e,n))}}[Ft](){if(this[Nn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ft.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Ff=class extends ko{[Fn](){let t;if(this[fo]&&this[hn]==="r+")try{t=ft.openSync(this[Nt],this[hn],this[Ki])}catch(e){if(e?.code==="ENOENT")return this[hn]="w",this[Fn]();throw e}else t=ft.openSync(this[Nt],this[hn],this[Ki]);this[Kr](null,t)}[Ft](){if(this[Nn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ft.closeSync(t),this.emit("close")}}[uo](t){let e=!0;try{this[Hr](null,ft.writeSync(this[he],t,0,t.length,this[Rn])),e=!1}finally{if(e)try{this[Ft]()}catch{}}}},d_=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"]]),l_=t=>!!t.sync&&!!t.file,u_=t=>!t.sync&&!!t.file,f_=t=>!!t.sync&&!t.file,h_=t=>!t.sync&&!t.file,p_=t=>!!t.file,x_=t=>d_.get(t)||t,fd=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=x_(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},ts=(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=fd(a);if(o?.(f,d),l_(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(u_(f)){let p=e(f,d);return u?p.then(()=>u(),u):p}else if(f_(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(f,d)}else if(h_(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}),w_=m_.constants||{ZLIB_VERNUM:4736},$t=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},w_)),__=sr.concat,sf=Object.getOwnPropertyDescriptor(sr,"concat"),y_=t=>t,Ac=sf?.writable===!0||sf?.set!==void 0?t=>{sr.concat=t?y_:__}:t=>{},or=Symbol("_superWrite"),to=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"}},kc=Symbol("flushFlag"),hd=class extends cr{#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 rf[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new rf[e](t)}catch(n){throw new to(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 to(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Wc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(sr.alloc(0),{[kc]: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}[or](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=sr.from(t,e)),this.#e)return;Wc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},Ac(!0);let d;try{let f=typeof t[kc]=="number"?t[kc]:this.#r;d=this.#t._processChunk(t,f),Ac(!1)}catch(f){Ac(!1),this.#o(new to(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 to(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[or](sr.from(f));for(let p=1;p<d.length;p++)u=this[or](d[p])}else u=this[or](sr.from(d));return n&&n(),u}},zf=class extends hd{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||$t.Z_NO_FLUSH,t.finishFlush=t.finishFlush||$t.Z_FINISH,t.fullFlushFlag=$t.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($t.Z_SYNC_FLUSH),Wc(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)}}}},b_=class extends zf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[or](t){return this.#e?(this.#e=!1,t[9]=255,super[or](t)):super[or](t)}},E_=class extends zf{constructor(t){super(t,"Unzip")}},Uf=class extends hd{constructor(t,e){t=t||{},t.flush=t.flush||$t.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||$t.BROTLI_OPERATION_FINISH,t.fullFlushFlag=$t.BROTLI_OPERATION_FLUSH,super(t,e)}},v_=class extends Uf{constructor(t){super(t,"BrotliCompress")}},S_=class extends Uf{constructor(t){super(t,"BrotliDecompress")}},Hf=class extends hd{constructor(t,e){t=t||{},t.flush=t.flush||$t.ZSTD_e_continue,t.finishFlush=t.finishFlush||$t.ZSTD_e_end,t.fullFlushFlag=$t.ZSTD_e_flush,super(t,e)}},I_=class extends Hf{constructor(t){super(t,"ZstdCompress")}},A_=class extends Hf{constructor(t){super(t,"ZstdDecompress")}},k_=(t,e)=>{if(Number.isSafeInteger(t))t<0?T_(t,e):C_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},C_=(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]=Gf(o):o===0?e[i-1]=0:(n=!0,e[i-1]=qf(o))}},P_=t=>{let e=t[0],n=e===128?D_(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=Gf(a):a===0?d=a:(i=!0,d=qf(a)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},D_=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},Gf=t=>(255^t)&255,qf=t=>(255^t)+1&255,O_={};Kw(O_,{code:()=>pd,isCode:()=>ho,isName:()=>L_,name:()=>Co,normalFsTypes:()=>jf});var ho=t=>Co.has(t),L_=t=>pd.has(t),jf=new Set(["0","","1","2","3","4","5","6","7","D"]),Co=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"]]),pd=new Map(Array.from(Co).map(t=>[t[1],t[0]])),M_=t=>t===void 0||t<0?void 0:t,ar=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=Xn(t,e+156,1),a=jf.has(o),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??Xn(t,e,100),this.mode=d?.mode??u?.mode??Dn(t,e+100,8),this.uid=d?.uid??u?.uid??Dn(t,e+108,8),this.gid=d?.gid??u?.gid??Dn(t,e+116,8),this.size=M_(d?.size??u?.size??Dn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??Cc(t,e+136,12),this.cksum=Dn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),ho(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Xn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Xn(t,e+265,32),this.gname=d?.gname??u?.gname??Xn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??Dn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??Dn(t,e+337,8)??0,t[e+475]!==0){let p=Xn(t,e+345,155);this.path=p+"/"+this.path}else{let p=Xn(t,e+345,130);p&&(this.path=p+"/"+this.path),this.atime=n?.atime??i?.atime??Cc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??Cc(t,e+488,12)}let f=256;for(let p=e;p<e+148;p++)f+=t[p];for(let p=e+156;p<e+512;p++)f+=t[p];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=N_(this.path||"",n),o=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Qn(t,e,100,o)||this.needPax,this.needPax=On(t,e+100,8,this.mode)||this.needPax,this.needPax=On(t,e+108,8,this.uid)||this.needPax,this.needPax=On(t,e+116,8,this.gid)||this.needPax,this.needPax=On(t,e+124,12,this.size)||this.needPax,this.needPax=Tc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Qn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Qn(t,e+265,32,this.uname)||this.needPax,this.needPax=Qn(t,e+297,32,this.gname)||this.needPax,this.needPax=On(t,e+329,8,this.devmaj)||this.needPax,this.needPax=On(t,e+337,8,this.devmin)||this.needPax,this.needPax=Qn(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=Qn(t,e+345,155,a)||this.needPax:(this.needPax=Qn(t,e+345,130,a)||this.needPax,this.needPax=Tc(t,e+476,12,this.atime)||this.needPax,this.needPax=Tc(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,On(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Co.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(pd.get(t));if(ho(e)||e==="Unsupported")this.#e=e;else if(ho(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},N_=(t,e)=>{let n=t,i="",o,a=Nr.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=Nr.dirname(n),n=Nr.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=Nr.join(Nr.basename(i),n),i=Nr.dirname(i));while(i!==a&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Xn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),Cc=(t,e,n)=>F_(Dn(t,e,n)),F_=t=>t===void 0?void 0:new Date(t*1e3),Dn=(t,e,n)=>Number(t[e])&128?P_(t.subarray(e,e+n)):z_(t,e,n),B_=t=>isNaN(t)?void 0:t,z_=(t,e,n)=>B_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),U_={12:8589934591,8:2097151},On=(t,e,n,i)=>i===void 0?!1:i>U_[n]||i<0?(k_(i,t.subarray(e,e+n)),!0):(H_(t,e,n,i),!1),H_=(t,e,n,i)=>t.write(G_(i,n),e,n,"ascii"),G_=(t,e)=>q_(Math.floor(t).toString(8),e),q_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Tc=(t,e,n,i)=>i===void 0?!1:On(t,e,n,i.getTime()/1e3),j_=new Array(156).join("\0"),Qn=(t,e,n,i)=>i===void 0?!1:(t.write(i+j_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),Eo=class Wf{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 ar({path:("PaxHeader/"+W_(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 Wf(K_($_(e),n),i)}},K_=(t,e)=>e?Object.assign({},e,t):t,$_=t=>t.replace(/\n$/,"").split(`
|
|
91
|
+
`).reduce(V_,Object.create(null)),V_=(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},J_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ne=J_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),Z_=class extends cr{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=ne(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?ne(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=ne(t.path)),t.linkpath&&(t.linkpath=ne(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},To=(t,e,n,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=n instanceof Error&&n.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(n instanceof Error&&(i=Object.assign(n,i),n=n.message),t.emit("warn",e,n,i)):n instanceof Error?t.emit("error",Object.assign(n,i)):t.emit("error",Object.assign(new Error(`${e}: ${n}`),i))},Y_=1024*1024,Kc=Buffer.from([31,139]),$c=Buffer.from([40,181,47,253]),X_=Math.max(Kc.length,$c.length),St=Symbol("state"),er=Symbol("writeEntry"),ln=Symbol("readEntry"),Pc=Symbol("nextEntry"),of=Symbol("processEntry"),qt=Symbol("extendedHeader"),Ni=Symbol("globalExtendedHeader"),Cn=Symbol("meta"),af=Symbol("emitMeta"),Ee=Symbol("buffer"),un=Symbol("queue"),Tn=Symbol("ended"),Rc=Symbol("emittedEnd"),tr=Symbol("emit"),Pe=Symbol("unzip"),no=Symbol("consumeChunk"),ro=Symbol("consumeChunkSub"),Dc=Symbol("consumeBody"),cf=Symbol("consumeMeta"),df=Symbol("consumeHeader"),Fi=Symbol("consuming"),Oc=Symbol("bufferConcat"),io=Symbol("maybeEnd"),Fr=Symbol("writing"),jt=Symbol("aborted"),so=Symbol("onDone"),nr=Symbol("sawValidEntry"),oo=Symbol("sawNullBlock"),ao=Symbol("sawEOF"),lf=Symbol("closeStream"),Q_=1e3,Bi=Symbol("compressedBytesRead"),Lc=Symbol("decompressedBytesRead"),uf=Symbol("checkDecompressionRatio"),ey=()=>!0,es=class extends g_{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[un]=[];[Ee];[ln];[er];[St]="begin";[Cn]="";[qt];[Ni];[Tn]=!1;[Pe];[jt]=!1;[nr];[oo]=!1;[ao]=!1;[Fr]=!1;[Fi]=!1;[Rc]=!1;[Bi]=0;[Lc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(so,()=>{(this[St]==="begin"||this[nr]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(so,t.ondone):this.on(so,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:Q_,this.maxMetaEntrySize=t.maxMetaEntrySize||Y_,this.filter=typeof t.filter=="function"?t.filter:ey;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[lf]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){To(this,t,e,n)}[df](t,e){this[nr]===void 0&&(this[nr]=!1);let n;try{n=new ar(t,e,this[qt],this[Ni])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[oo]?(this[ao]=!0,this[St]==="begin"&&(this[St]="header"),this[tr]("eof")):(this[oo]=!0,this[tr]("nullBlock"));else if(this[oo]=!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[er]=new Z_(n,this[qt],this[Ni]);if(!this[nr])if(o.remain){let a=()=>{o.invalid||(this[nr]=!0)};o.on("end",a)}else this[nr]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[tr]("ignoredEntry",o),this[St]="ignore",o.resume()):o.size>0&&(this[Cn]="",o.on("data",a=>this[Cn]+=a),this[St]="meta"):(this[qt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[tr]("ignoredEntry",o),this[St]=o.remain?"ignore":"header",o.resume()):(o.remain?this[St]="body":(this[St]="header",o.end()),this[ln]?this[un].push(o):(this[un].push(o),this[Pc]())))}}}[lf](){queueMicrotask(()=>this.emit("close"))}[of](t){let e=!0;if(!t)this[ln]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[ln]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Pc]()),e=!1);return e}[Pc](){do;while(this[of](this[un].shift()));if(this[un].length===0){let t=this[ln];!t||t.flowing||t.size===t.remain?this[Fr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Dc](t,e){let n=this[er];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[St]="header",this[er]=void 0,n.end()),o.length}[cf](t,e){let n=this[er],i=this[Dc](t,e);return!this[er]&&n&&this[af](n),i}[tr](t,e,n){this[un].length===0&&!this[ln]?this.emit(t,e,n):this[un].push([t,e,n])}[af](t){switch(this[tr]("meta",this[Cn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[qt]=Eo.parse(this[Cn],this[qt],!1);break;case"GlobalExtendedHeader":this[Ni]=Eo.parse(this[Cn],this[Ni],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[qt]??Object.create(null);this[qt]=e,e.path=this[Cn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[qt]||Object.create(null);this[qt]=e,e.linkpath=this[Cn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[jt]){if(this[Pe]){let e=this[Pe];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[jt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[uf](t){this[Lc]+=t.length;let e=this[Lc]/this[Bi];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[jt])return n?.(),!1;if((this[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[Ee]&&(t=Buffer.concat([this[Ee],t]),this[Ee]=void 0),t.length<X_)return this[Ee]=t,n?.(),!0;for(let d=0;this[Pe]===void 0&&d<Kc.length;d++)t[d]!==Kc[d]&&(this[Pe]=!1);let o=!1;if(this[Pe]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<$c.length;d++)if(t[d]!==$c[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[Pe]===!1&&a)if(t.length<512)if(this[Tn])this.brotli=!0;else return this[Ee]=t,n?.(),!0;else try{new ar(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Pe]===void 0||this[Pe]===!1&&(this.brotli||o)){let d=this[Tn];this[Tn]=!1,this[Pe]=this[Pe]===void 0?new E_({}):o?new A_({}):new S_({}),this[Pe].on("data",f=>{this[uf](f)&&this[no](f)}),this[Pe].on("error",f=>{this[jt]||this.abort(f)}),this[Pe].on("end",()=>{this[Tn]=!0,this[no]()}),this[Fr]=!0,this[Bi]+=t.length;let u=!!this[Pe][d?"end":"write"](t);return this[Fr]=!1,n?.(),u}}this[Fr]=!0,this[Pe]?(this[Bi]+=t.length,this[Pe].write(t)):this[no](t),this[Fr]=!1;let i=this[un].length>0?!1:this[ln]?this[ln].flowing:!0;return!i&&this[un].length===0&&this[ln]?.once("drain",()=>this.emit("drain")),n?.(),i}[Oc](t){t&&!this[jt]&&(this[Ee]=this[Ee]?Buffer.concat([this[Ee],t]):t)}[io](){if(this[Tn]&&!this[Rc]&&!this[jt]&&!this[Fi]){this[Rc]=!0;let t=this[er];if(t?.blockRemain){let e=this[Ee]?this[Ee].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[Ee]&&t.write(this[Ee]),t.end()}this[tr](so)}}[no](t){if(this[Fi]&&t)this[Oc](t);else if(!t&&!this[Ee])this[io]();else if(t){if(this[Fi]=!0,this[Ee]){this[Oc](t);let e=this[Ee];this[Ee]=void 0,this[ro](e)}else this[ro](t);for(;this[Ee]&&this[Ee]?.length>=512&&!this[jt]&&!this[ao];){let e=this[Ee];this[Ee]=void 0,this[ro](e)}this[Fi]=!1}(!this[Ee]||this[Tn])&&this[io]()}[ro](t){let e=0,n=t.length;for(;e+512<=n&&!this[jt]&&!this[ao];)switch(this[St]){case"begin":case"header":this[df](t,e),e+=512;break;case"ignore":case"body":e+=this[Dc](t,e);break;case"meta":e+=this[cf](t,e);break;default:throw new Error("invalid state: "+this[St])}e<n&&(this[Ee]=this[Ee]?Buffer.concat([t.subarray(e),this[Ee]]):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[jt]||(this[Pe]?(t&&(this[Bi]+=t.length,this[Pe].write(t)),this[Pe].end()):(this[Tn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[io]())),this}},$i=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)},ty=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Kf=(t,e)=>{let n=new Map(e.map(a=>[$i(a),!0])),i=t.filter,o=(a,d="")=>{let u=d||c_(a).root||".",f;if(a===u)f=!1;else{let p=n.get(a);f=p!==void 0?p:o(a_(a),u)}return n.set(a,f),f};t.filter=i?(a,d)=>i(a,d)&&o($i(a)):a=>o($i(a))},ny=t=>{let e=new es(t),n=t.file,i;try{i=qr.openSync(n,"r");let o=qr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),u=qr.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=qr.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{qr.closeSync(i)}catch{}}},ry=(t,e)=>{let n=new es(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),qr.stat(o,(u,f)=>{if(u)d(u);else{let p=new ud(o,{readSize:i,size:f.size});p.on("error",d),p.pipe(n)}})})},$r=ts(ny,ry,t=>new es(t),t=>new es(t),(t,e)=>{e?.length&&Kf(t,e),t.noResume||ty(t)}),$f=(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:sy,parse:hf}=iy,xd=t=>{let e="",n=hf(t);for(;sy(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=hf(t)}return[e,t]},Po=["|","<",">","?",":"],gd=Po.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),oy=new Map(Po.map((t,e)=>[t,gd[e]])),ay=new Map(gd.map((t,e)=>[t,Po[e]])),pf=t=>Po.reduce((e,n)=>e.split(n).join(oy.get(n)),t),cy=t=>gd.reduce((e,n)=>e.split(n).join(ay.get(n)),t),Vf=(t,e)=>e?(t=ne(t).replace(/^\.(\/|$)/,""),$i(e)+"/"+t):ne(t),dy=16*1024*1024,xf=Symbol("process"),gf=Symbol("file"),mf=Symbol("directory"),Vc=Symbol("symlink"),wf=Symbol("hardlink"),zi=Symbol("header"),po=Symbol("read"),Jc=Symbol("lstat"),xo=Symbol("onlstat"),Zc=Symbol("onread"),Yc=Symbol("onreadlink"),Xc=Symbol("openfile"),Qc=Symbol("onopenfile"),Ln=Symbol("close"),So=Symbol("mode"),ed=Symbol("awaitDrain"),Mc=Symbol("ondrain"),Kt=Symbol("prefix"),Jf=class extends cr{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=fd(e);super(),this.path=ne(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||dy,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=ne(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?ne(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]=xd(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=cy(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ne(n.absolute||ff.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[xo](o):this[Jc]()}warn(t,e,n={}){return To(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Jc](){Wt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[xo](e)})}[xo](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=fy(t),this.emit("stat",t),this[xf]()}[xf](){switch(this.type){case"File":return this[gf]();case"Directory":return this[mf]();case"SymbolicLink":return this[Vc]();default:return this.end()}}[So](t){return $f(t,this.type==="Directory",this.portable)}[Kt](t){return Vf(t,this.prefix)}[zi](){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 ar({path:this[Kt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kt](this.linkpath):this.linkpath,mode:this[So](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new Eo({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Kt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kt](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)}[mf](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[zi](),this.end()}[Vc](){Wt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Yc](e)})}[Yc](t){this.linkpath=ne(t),this[zi](),this.end()}[wf](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ne(ff.relative(this.cwd,t)),this.stat.size=0,this[zi](),this.end()}[gf](){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[wf](e);this.linkCache.set(t,this.absolute)}if(this[zi](),this.stat.size===0)return this.end();this[Xc]()}[Xc](){Wt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Qc](e)})}[Qc](t){if(this.fd=t,this.#e)return this[Ln]();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[po]()}[po](){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");Wt.read(t,e,n,i,o,(a,d)=>{if(a)return this[Ln](()=>this.emit("error",a));this[Zc](d)})}[Ln](t=()=>{}){this.fd!==void 0&&Wt.close(this.fd,t)}[Zc](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[Ln](()=>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[Ln](()=>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[Mc]():this[ed](()=>this[Mc]())}[ed](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)}[Mc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Ln](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[po]()}},ly=class extends Jf{sync=!0;[Jc](){this[xo](Wt.lstatSync(this.absolute))}[Vc](){this[Yc](Wt.readlinkSync(this.absolute))}[Xc](){this[Qc](Wt.openSync(this.absolute,"r"))}[po](){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=Wt.readSync(e,n,i,o,a);this[Zc](d),t=!1}finally{if(t)try{this[Ln](()=>{})}catch{}}}[ed](t){t()}[Ln](t=()=>{}){this.fd!==void 0&&Wt.closeSync(this.fd),t()}},uy=class extends cr{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,n={}){return To(this,t,e,n)}constructor(t,e={}){let n=fd(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=ne(t.path),this.mode=t.mode!==void 0?this[So](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?ne(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=xd(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 ar({path:this[Kt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new Eo({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Kt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kt](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)}[Kt](t){return Vf(t,this.prefix)}[So](t){return $f(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}},fy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",hy=class jr{tail;head;length=0;static create(e=[]){return new jr(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++)xy(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)gy(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 jr;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 jr;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 jr;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 jr;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=py(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 py(t,e,n){let i=e,o=e?e.next:t.head,a=new md(n,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function xy(t,e){t.tail=new md(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function gy(t,e){t.head=new md(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var md=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}},yf=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},bf=Buffer.alloc(1024),go=Symbol("onStat"),Ui=Symbol("ended"),Lt=Symbol("queue"),Hi=Symbol("pendingLinks"),Pn=Symbol("current"),rr=Symbol("process"),Gi=Symbol("processing"),co=Symbol("processJob"),Mt=Symbol("jobs"),Nc=Symbol("jobDone"),mo=Symbol("addFSEntry"),Ef=Symbol("addTarEntry"),td=Symbol("stat"),nd=Symbol("readdir"),wo=Symbol("onreaddir"),_o=Symbol("pipe"),vf=Symbol("entry"),Fc=Symbol("entryOpt"),yo=Symbol("writeEntryClass"),Zf=Symbol("write"),Bc=Symbol("ondrain"),Ro=class extends cr{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[yo];onWriteEntry;[Lt];[Hi]=new Map;[Mt]=0;[Gi]=!1;[Ui]=!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=ne(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[yo]=Jf,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 b_(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new v_(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new I_(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[Bc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Bc]);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[Lt]=new hy,this[Mt]=0,this.jobs=Number(t.jobs)||4,this[Gi]=!1,this[Ui]=!1}[Zf](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[Ui]=!0,this[rr](),n&&n(),this}write(t){if(this[Ui])throw new Error("write after end");return typeof t=="string"?this[mo](t):this[Ef](t),this.flowing}[Ef](t){let e=ne(_f.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new yf(t.path,e);n.entry=new uy(t,this[Fc](n)),n.entry.on("end",()=>this[Nc](n)),this[Mt]+=1,this[Lt].push(n)}this[rr]()}[mo](t){let e=ne(_f.resolve(this.cwd,t));this[Lt].push(new yf(t,e)),this[rr]()}[td](t){t.pending=!0,this[Mt]+=1;let e=this.follow?"stat":"lstat";vo[e](t.absolute,(n,i)=>{t.pending=!1,this[Mt]-=1,n?this.emit("error",n):this[go](t,i)})}[go](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[Pn])this[co](t);else{let n=`${e.dev}:${e.ino}`,i=this[Hi].get(n);i?i.push(t):this[Hi].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[rr]()}[nd](t){t.pending=!0,this[Mt]+=1,vo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[Mt]-=1,e)return this.emit("error",e);this[wo](t,n)})}[wo](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[rr]()}[rr](){if(!this[Gi]){this[Gi]=!0;for(let t=this[Lt].head;t&&this[Mt]<this.jobs;t=t.next)if(this[co](t.value),t.value.ignore){let e=t.next;this[Lt].removeNode(t),t.next=e}this[Gi]=!1,this[Ui]&&this[Lt].length===0&&this[Mt]===0&&(this.zip?this.zip.end(bf):(super.write(bf),super.end()))}}get[Pn](){return this[Lt]&&this[Lt].head&&this[Lt].head.value}[Nc](t){this[Lt].shift(),this[Mt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Hi].get(n);if(i){this[Hi].delete(n);for(let o of i)o.pending=!1,this[co](o)}}this[rr]()}[co](t){if(t.pending&&t.pendingLink&&t===this[Pn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Pn]&&!t.piped&&this[_o](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[go](t,e):this[td](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[wo](t,e):this[nd](t),!t.readdir)return}if(t.entry=this[vf](t),!t.entry){t.ignore=!0;return}t===this[Pn]&&!t.piped&&this[_o](t)}}}[Fc](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}}[vf](t){this[Mt]+=1;try{return new this[yo](t.path,this[Fc](t)).on("end",()=>this[Nc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Bc](){this[Pn]&&this[Pn].entry&&this[Pn].entry.resume()}[_o](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[mo](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={}){To(this,t,e,n)}},wd=class extends Ro{sync=!0;constructor(t){super(t),this[yo]=ly}pause(){}resume(){}[td](t){let e=this.follow?"statSync":"lstatSync";this[go](t,vo[e](t.absolute))}[nd](t){this[wo](t,vo.readdirSync(t.absolute))}[_o](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[mo](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Zf](i)})}},my=(t,e)=>{let n=new wd(t),i=new Ff(t.file,{mode:t.mode||438});n.pipe(i),Yf(n,e)},wy=(t,e)=>{let n=new Ro(t),i=new ko(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 Xf(n,e).catch(a=>n.emit("error",a)),o},Yf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?$r({file:Bf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Xf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await $r({file:Bf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},_y=(t,e)=>{let n=new wd(t);return Yf(n,e),n},yy=(t,e)=>{let n=new Ro(t);return Xf(n,e).catch(i=>n.emit("error",i)),n},qC=ts(my,wy,_y,yy,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),Ey=process.env.__FAKE_PLATFORM__||process.platform,n0=Ey==="win32",{O_CREAT:r0,O_NOFOLLOW:Sf,O_TRUNC:i0,O_WRONLY:s0}=t0.constants,o0=Number(process.env.__FAKE_FS_O_FILENAME__)||t0.constants.UV_FS_O_FILEMAP||0,vy=n0&&!!o0,Sy=512*1024,Iy=o0|i0|r0|s0,If=!n0&&typeof Sf=="number"?Sf|i0|r0|s0:null,a0=If!==null?()=>If:vy?t=>t<Sy?Iy:"w":()=>"w",rd=(t,e,n)=>{try{return Do.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},Io=(t,e,n,i)=>{Do.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},Ay=(t,e,n,i,o)=>{if(e.isDirectory())c0(Vi.resolve(t,e.name),n,i,a=>{if(a)return o(a);let d=Vi.resolve(t,e.name);Io(d,n,i,o)});else{let a=Vi.resolve(t,e.name);Io(a,n,i,o)}},c0=(t,e,n,i)=>{Do.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 Io(t,e,n,i);let d=a.length,u=null,f=p=>{if(!u){if(p)return i(u=p);if(--d===0)return Io(t,e,n,i)}};for(let p of a)Ay(t,p,e,n,f)})},ky=(t,e,n,i)=>{e.isDirectory()&&d0(Vi.resolve(t,e.name),n,i),rd(Vi.resolve(t,e.name),n,i)},d0=(t,e,n)=>{let i;try{i=Do.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return rd(t,e,n);throw a}for(let o of i)ky(t,o,e,n);return rd(t,e,n)},l0=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"}},Oo=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)=>{_t.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new l0(t,n?.code||"ENOTDIR")),e(n)})},Py=(t,e,n)=>{t=ne(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),p=e.preserve,x=e.unlink,g=ne(e.cwd),v=(E,S)=>{E?n(E):S&&f?c0(S,d,u,A=>v(A)):a?_t.chmod(t,o,n):n()};if(t===g)return Ty(t,v);if(p)return Cy.mkdir(t,{mode:o,recursive:!0}).then(E=>v(null,E??void 0),v);let w=ne(Ao.relative(g,t)).split("/");id(g,w,o,x,g,void 0,v)},id=(t,e,n,i,o,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),f=ne(Ao.resolve(t+"/"+u));_t.mkdir(f,n,u0(f,e,n,i,o,a,d))},u0=(t,e,n,i,o,a,d)=>u=>{u?_t.lstat(t,(f,p)=>{if(f)f.path=f.path&&ne(f.path),d(f);else if(p.isDirectory())id(t,e,n,i,o,a,d);else if(i)_t.unlink(t,x=>{if(x)return d(x);_t.mkdir(t,n,u0(t,e,n,i,o,a,d))});else{if(p.isSymbolicLink())return d(new Oo(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,id(t,e,n,i,o,a,d))},Ry=t=>{let e=!1,n;try{e=_t.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new l0(t,n??"ENOTDIR")}},Dy=(t,e)=>{t=ne(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,p=e.unlink,x=ne(e.cwd),g=E=>{E&&u&&d0(E,a,d),o&&_t.chmodSync(t,i)};if(t===x)return Ry(x),g();if(f)return g(_t.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=ne(Ao.relative(x,t)).split("/"),w;for(let E=v.shift(),S=x;E&&(S+="/"+E);E=v.shift()){S=ne(Ao.resolve(S));try{_t.mkdirSync(S,i),w=w||S}catch{let A=_t.lstatSync(S);if(A.isDirectory())continue;if(p){_t.unlinkSync(S),_t.mkdirSync(S,i),w=w||S;continue}else if(A.isSymbolicLink())return new Oo(S,S+"/"+v.join("/"))}}return g(w)},zc=Object.create(null),Af=1e4,Br=new Set,Oy=t=>{Br.has(t)?Br.delete(t):zc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Br.add(t);let e=zc[t],n=Br.size-Af;if(n>Af/10){for(let i of Br)if(Br.delete(i),delete zc[i],--n<=0)break}return e},Ly=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,My=Ly==="win32",Ny=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=f0(i,n)),e.push(n||"/"),e},[]),Fy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=My?["win32 parallelization disabled"]:t.map(i=>$i(f0(Oy(i))));let n=new Set(t.map(i=>Ny(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}},By=()=>process.umask(),kf=Symbol("onEntry"),sd=Symbol("checkFs"),Cf=Symbol("checkFs2"),od=Symbol("isReusable"),It=Symbol("makeFs"),ad=Symbol("file"),cd=Symbol("directory"),bo=Symbol("link"),Tf=Symbol("symlink"),Pf=Symbol("hardlink"),Wi=Symbol("ensureNoSymlink"),Rf=Symbol("unsupported"),Df=Symbol("checkPath"),Uc=Symbol("stripAbsolutePath"),Mn=Symbol("mkdir"),Ve=Symbol("onError"),lo=Symbol("pending"),Of=Symbol("pend"),zr=Symbol("unpend"),Hc=Symbol("ended"),Gc=Symbol("maybeClose"),dd=Symbol("skip"),Ji=Symbol("doChown"),Zi=Symbol("uid"),Yi=Symbol("gid"),Xi=Symbol("checkedCwd"),zy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Qi=zy==="win32",Uy=1024,Hy=(t,e)=>{if(!Qi)return oe.unlink(t,e);let n=t+".DELETE."+e0(16).toString("hex");oe.rename(t,n,i=>{if(i)return e(i);oe.unlink(n,e)})},Gy=t=>{if(!Qi)return oe.unlinkSync(t);let e=t+".DELETE."+e0(16).toString("hex");oe.renameSync(t,e),oe.unlinkSync(e)},Lf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,_d=class extends es{[Hc]=!1;[Xi]=!1;[lo]=0;reservations=new Fy;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[Hc]=!0,this[Gc]()},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:Uy,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Qi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ne(Ge.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:By():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[kf](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Gc](){this[Hc]&&this[lo]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Uc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,a]=xd(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Qi&&/^[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=Ge.posix.dirname(t.path),f=Ge.posix.normalize(Ge.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}[Df](t){let e=ne(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=ne(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[Uc](t,"path")||!this[Uc](t,"linkpath"))return!1;if(t.absolute=Ge.isAbsolute(t.path)?ne(Ge.resolve(t.path)):ne(Ge.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:ne(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}=Ge.win32.parse(String(t.absolute));t.absolute=i+pf(String(t.absolute).slice(i.length));let{root:o}=Ge.win32.parse(t.path);t.path=o+pf(t.path.slice(o.length))}return!0}[kf](t){if(!this[Df](t))return t.resume();switch(by.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[sd](t);default:return this[Rf](t)}}[Ve](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[zr](),e.resume())}[Mn](t,e,n){Py(ne(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)}[Ji](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}[Zi](t){return Lf(this.uid,t.uid,this.processUid)}[Yi](t){return Lf(this.gid,t.gid,this.processGid)}[ad](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new ko(String(t.absolute),{flags:a0(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&oe.close(i.fd,()=>{}),i.write=()=>!0,this[Ve](u,t),e()});let o=1,a=u=>{if(u){i.fd&&oe.close(i.fd,()=>{}),this[Ve](u,t),e();return}--o===0&&i.fd!==void 0&&oe.close(i.fd,f=>{f?this[Ve](f,t):this[zr](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let p=t.atime||new Date,x=t.mtime;oe.futimes(f,p,x,g=>g?oe.utimes(u,p,x,v=>a(v&&g)):a())}if(typeof f=="number"&&this[Ji](t)){o++;let p=this[Zi](t),x=this[Yi](t);typeof p=="number"&&typeof x=="number"&&oe.fchown(f,p,x,g=>g?oe.chown(u,p,x,v=>a(v&&g)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[Ve](u,t),e()}),t.pipe(d)),d.pipe(i)}[cd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Mn](String(t.absolute),n,i=>{if(i){this[Ve](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[zr](),t.resume())};t.mtime&&!this.noMtime&&(o++,oe.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Ji](t)&&(o++,oe.chown(String(t.absolute),Number(this[Zi](t)),Number(this[Yi](t)),a)),a()})}[Rf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Tf](t,e){let n=ne(Ge.relative(this.cwd,Ge.resolve(Ge.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Wi](t,this.cwd,n,()=>this[bo](t,String(t.linkpath),"symlink",e),i=>{this[Ve](i,t),e()})}[Pf](t,e){let n=ne(Ge.resolve(this.cwd,String(t.linkpath))),i=ne(String(t.linkpath)).split("/");this[Wi](t,this.cwd,i,()=>this[bo](t,n,"link",e),o=>{this[Ve](o,t),e()})}[Wi](t,e,n,i,o){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Ge.resolve(e,a);oe.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new Oo(d,Ge.resolve(d,n.join("/"))));this[Wi](t,d,n,i,o)})}[Of](){this[lo]++}[zr](){this[lo]--,this[Gc]()}[dd](t){this[zr](),t.resume()}[od](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Qi}[sd](t){this[Of]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[Cf](t,n))}[Cf](t,e){let n=d=>{e(d)},i=()=>{this[Mn](this.cwd,this.dmode,d=>{if(d){this[Ve](d,t),n();return}this[Xi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=ne(Ge.dirname(String(t.absolute)));if(d!==this.cwd)return this[Mn](d,this.dmode,u=>{if(u){this[Ve](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[dd](t),n();return}if(d||this[od](t,u))return this[It](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,p=x=>this[It](x??null,t,n);return f?oe.chmod(String(t.absolute),Number(t.mode),p):p()}if(t.absolute!==this.cwd)return oe.rmdir(String(t.absolute),f=>this[It](f??null,t,n))}if(t.absolute===this.cwd)return this[It](null,t,n);Hy(String(t.absolute),f=>this[It](f??null,t,n))})};this[Xi]?o():i()}[It](t,e,n){if(t){this[Ve](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[ad](e,n);case"Link":return this[Pf](e,n);case"SymbolicLink":return this[Tf](e,n);case"Directory":case"GNUDumpDir":return this[cd](e,n)}}[bo](t,e,n,i){oe[n](e,String(t.absolute),o=>{o?this[Ve](o,t):(this[zr](),t.resume()),i()})}},qi=t=>{try{return[null,t()]}catch(e){return[e,null]}},h0=class extends _d{sync=!0;[It](t,e){return super[It](t,e,()=>{})}[sd](t){if(!this[Xi]){let o=this[Mn](this.cwd,this.dmode);if(o)return this[Ve](o,t);this[Xi]=!0}if(t.absolute!==this.cwd){let o=ne(Ge.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[Mn](o,this.dmode);if(a)return this[Ve](a,t)}}let[e,n]=qi(()=>oe.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[dd](t);if(e||this[od](t,n))return this[It](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?qi(()=>{oe.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[It](d,t)}let[o]=qi(()=>oe.rmdirSync(String(t.absolute)));this[It](o,t)}let[i]=t.absolute===this.cwd?[]:qi(()=>Gy(String(t.absolute)));this[It](i,t)}[ad](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[Ve](d||u,t),e()},o;try{o=oe.openSync(String(t.absolute),a0(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[Ve](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(p){try{oe.utimesSync(String(t.absolute),u,f)}catch{d=p}}}if(this[Ji](t)){let u=this[Zi](t),f=this[Yi](t);try{oe.fchownSync(o,Number(u),Number(f))}catch(p){try{oe.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||p}}}i(d)})}[cd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Mn](String(t.absolute),n);if(i){this[Ve](i,t),e();return}if(t.mtime&&!this.noMtime)try{oe.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ji](t))try{oe.chownSync(String(t.absolute),Number(this[Zi](t)),Number(this[Yi](t)))}catch{}e(),t.resume()}[Mn](t,e){try{return Dy(ne(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}}[Wi](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=Ge.resolve(a,d);let[u,f]=qi(()=>oe.lstatSync(a));if(u)return i();if(f.isSymbolicLink())return o(new Oo(a,Ge.resolve(e,n.join("/"))))}i()}[bo](t,e,n,i){let o=`${n}Sync`;try{oe[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[Ve](a,t)}}},qy=t=>{let e=new h0(t),n=t.file,i=Qf.statSync(n),o=t.maxReadSize||16*1024*1024;new o_(n,{readSize:o,size:i.size}).pipe(e)},jy=(t,e)=>{let n=new _d(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Qf.stat(o,(u,f)=>{if(u)d(u);else{let p=new ud(o,{readSize:i,size:f.size});p.on("error",d),p.pipe(n)}})})},p0=ts(qy,jy,t=>new h0(t),t=>new _d(t),(t,e)=>{e?.length&&Kf(t,e)}),Wy=(t,e)=>{let n=new wd(t),i=!0,o,a;try{try{o=wt.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=wt.openSync(t.file,"w+");else throw f}let d=wt.fstatSync(o),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let x=0,g=0;x<512;x+=g){if(g=wt.readSync(o,u,x,u.length-x,a+x),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!g)break e}let f=new ar(u);if(!f.cksumValid)break;let p=512*Math.ceil((f.size||0)/512);if(a+p+512>d.size)break;a+=p,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,Ky(t,n,a,o,e)}finally{if(i)try{wt.closeSync(o)}catch{}}},Ky=(t,e,n,i,o)=>{let a=new Ff(t.file,{fd:i,start:n});e.pipe(a),Vy(e,o)},$y=(t,e)=>{e=Array.from(e);let n=new Ro(t),i=(o,a,d)=>{let u=(v,w)=>{v?wt.close(o,E=>d(v)):d(null,w)},f=0;if(a===0)return u(null,0);let p=0,x=Buffer.alloc(512),g=(v,w)=>{if(v||w===void 0)return u(v);if(p+=w,p<512&&w)return wt.read(o,x,p,x.length-p,f+p,g);if(f===0&&x[0]===31&&x[1]===139)return u(new Error("cannot append to compressed archives"));if(p<512)return u(null,f);let E=new ar(x);if(!E.cksumValid)return u(null,f);let S=512*Math.ceil((E.size??0)/512);if(f+S+512>a||(f+=S+512,f>=a))return u(null,f);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),p=0,wt.read(o,x,0,512,f,g)};wt.read(o,x,0,512,f,g)};return new Promise((o,a)=>{n.on("error",a);let d="r+",u=(f,p)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",wt.open(t.file,d,u);if(f||!p)return a(f);wt.fstat(p,(x,g)=>{if(x)return wt.close(p,()=>a(x));i(p,g.size,(v,w)=>{if(v)return a(v);let E=new ko(t.file,{fd:p,start:w});n.pipe(E),E.on("error",a),E.on("close",o),Jy(n,e)})})};wt.open(t.file,d,u)})},Vy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?$r({file:x0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Jy=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await $r({file:x0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},ji=ts(Wy,$y,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!p_(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")}),iT=ts(ji.syncFile,ji.asyncFile,ji.syncNoFile,ji.asyncNoFile,(t,e=[])=>{ji.validate?.(t,e),Zy(t)}),Zy=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))};an();var at={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",SET_CONFIG_OPTION:"_agent/setConfigOption",LIST_AVAILABLE_MODELS:"_agent/listAvailableModels"};function dr(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function g0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function Lo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function m0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function w0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function _0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function lr(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Dt();import{homedir as Xy}from"node:os";import y0 from"node:path";var b0=".claude",E0="settings.json",Mo=new Map;function v0(t){return y0.join(t,b0,E0)}async function S0(t,e){let n=v0(t),o=(Mo.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>{let a=await rt(n)??{};a.effortLevel=e,await gt(n,a)});Mo.set(n,o);try{await o}finally{Mo.get(n)===o&&Mo.delete(n)}}async function I0(t){let n=(await rt(v0(t)))?.effortLevel;return typeof n=="string"?n:void 0}async function A0(){let t=y0.join(Xy(),b0,E0),n=(await rt(t))?.effortLevel;return typeof n=="string"?n:void 0}Vt();Qe();re();De();Qe();function ns(t,e){if(dr(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function yd(t,e){if(dr(t)==="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_CLOUD",`${e} is not allowed for cloud agent`)}function rs(t){return t.startsWith("http://")||t.startsWith("https://")}function Vr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as QT}from"node:fs";import{dirname as t2,join as n2}from"node:path";import{fileURLToPath as i2}from"node:url";var Jt="0.3.2-alpha.107";var bd={"claude-code":{effort:["default","low","medium","high","xhigh","max"],fastMode:null},codex:{effort:["low","medium","high","xhigh"],fastMode:["off","on"]},hermes:{effort:null,fastMode:null},openclaw:{effort:null,fastMode:null}};function T0(t,e){return bd[t][e]}import{mkdir as pb,rm as j0}from"node:fs/promises";import{join as as}from"node:path";Dt();import{readFileSync as sb}from"node:fs";var ob=384;async function Ed(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await gt(t.agentEnvFile,n,{mode:ob})}function ur(t){try{let e=JSON.parse(sb(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Fo(t,e,n={},i=o=>o){return{...i({...t,...ur(e)}),...n}}Dt();function is(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(ab(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
|
|
92
92
|
`)}
|
|
93
|
-
`}function
|
|
94
|
-
`)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}
|
|
95
|
-
`)}}function
|
|
93
|
+
`}function ab(t){if(t.includes(`
|
|
94
|
+
`)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}re();De();import{homedir as lb}from"node:os";import{join as ub}from"node:path";Qe();re();var Bo="1008033",P0="1289";var R0="pbbp2",D0="https://www.coze.cn",O0="/api/coze_claw/resource/get_frontier_key",cb="https://www.coze.cn",db="wss://frontier.coze.cn";function Jr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??cb}function L0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??db}function Bn(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 os(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var ss=H("handshake");async function vd(t){let e=Jr(t.endpoint),n=t.timeoutMs??1e4,i=`${Vr(e)}${O0}?aid=${encodeURIComponent(Bo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Bn(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),n);ss.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")??"",p=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let E=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${E.slice(0,200)}`)}let x=await u.json();if(x.code!==void 0&&x.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${x.code} msg=${x.msg??"-"} logid=${f}`);let g=x.data??{},v=typeof g.access_key=="string"&&g.access_key||typeof g.accessKey=="string"&&g.accessKey||void 0,w=typeof g.device_id=="string"&&g.device_id||typeof g.deviceId=="string"&&g.deviceId||void 0;if(!v||!w){let E=JSON.stringify(x).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${E}`)}return ss.info("handshake ok",{remoteDeviceId:w,logid:f,traceId:p}),{accessKey:v,deviceId:w}}catch(u){if(u instanceof k)throw ss.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw ss.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let f=u.cause;throw ss.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var zo=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Bt="auto",Id="default",Sd=19e4,M0=32e3;function F0(t){if(!(At(t.model)&&!t.effort&&!t.fastMode))return{model:t.model,...t.effort?{effort:t.effort}:{},...t.fastMode?{fastMode:t.fastMode}:{}}}function B0(t){return{model:Ad(t.model)??Bt,...t.modelToken?{modelToken:t.modelToken}:{}}}function At(t){return!t||t===Bt}var fb=new Set(["auto","\u81EA\u52A8"]);function Ad(t){let e=t?.trim();if(e)return fb.has(e.toLowerCase())?Bt:e}function z0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=zo,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Bt;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!At(t.model)&&t.model!==Id&&(e.ANTHROPIC_MODEL=t.model);return e}function U0(t,e,n,i){let o={};if(t.modelToken?o.model=t.model||Bt:At(t.model)||(o.model=t.model),t.effort&&(o.model_reasoning_effort=t.effort),t.modelToken){let a={name:"coze",base_url:`${zo}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=Uo(e,n,i);Object.keys(d).length>0&&(a.http_headers=d),o.model_providers={coze:a},o.model_context_window=t.modelInfo?.contextWindow??Sd}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function H0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Uo(t,e,n){let{ttEnv:i,usePpe:o}=os(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 G0(t,e,n,i){if(!t.modelToken)return{};let o=Uo(e,n,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,u])=>`${d}:${u}`).join(`
|
|
95
|
+
`)}}function kd(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Cd(t){return t.model||Bt}function N0(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 q0(t,e,n,i,o){if(!t.modelToken)return null;let a=Cd(t),d=Uo(e,n,o),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let f=[N0(a,u,t.modelInfo?.contextWindow??Sd,t.modelInfo?.maxOutput??M0)],p=new Set([a]);for(let g of i??[])!g||p.has(g)||(p.add(g),f.push(N0(g,["text"],Sd,M0)));let x={baseUrl:`${zo}/v1`,api:"openai-completions",apiKey:t.modelToken,models:f};return Object.keys(d).length>0&&(x.headers=d),x}function hb(t){if(t!==void 0)return t?"auto":"text"}function Td(t,e,n){let i=Uo(e,n),o=t.model||Bt,a=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${zo}/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=hb(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(` - ${ub(lb(),".hermes","skills")}`),`${a.join(`
|
|
96
96
|
`)}
|
|
97
|
-
`}var
|
|
98
|
-
`).slice(1,6).join(" | ")}),await
|
|
99
|
-
`).slice(1,6).join(" | ")}),await G0(n,{recursive:!0,force:!0}).catch(i=>cr.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var Cd=new Map;function $0(t){let e=Cd.get(t.agentId);if(e)return e;let n=pE(t).finally(()=>Cd.delete(t.agentId));return Cd.set(t.agentId,n),n}Wt();import{createHash as V0}from"node:crypto";import{readFile as gE}from"node:fs/promises";import{homedir as mE}from"node:os";import wE from"node:path";var _E=3e4;function dn(t){return typeof t=="object"&&t!==null?t:null}function $r(t){return Array.isArray(t)?t:[]}function vt(t){return typeof t=="string"?t:void 0}function J0(t,e){return t.map(n=>dn(n)).filter(n=>n!==null).map(n=>{let i={id:vt(n[e])??""},o=vt(n.name),a=vt(n.description);return o&&(i.name=o),a&&(i.description=a),i}).filter(n=>n.id!=="")}function yE(t){let e=$r(t.configOptions);if(e.length===0)return null;let n=null,i,o,a,d,f;for(let x of e){let p=dn(x);if(!p)continue;let w=vt(p.id);if(!w)continue;let b=$r(p.options);w==="model"?(n=J0(b,"value"),i=vt(p.currentValue)):w==="effort"||w==="reasoning_effort"?(o=vt(p.currentValue),d=b.map(_=>vt(dn(_)?.value)).filter(_=>_!==void 0)):w==="fast-mode"&&(a=vt(p.currentValue),f=b.map(_=>vt(dn(_)?.value)).filter(_=>_!==void 0))}return n!==null||i!==void 0||o!==void 0||a!==void 0||d!==void 0||f!==void 0?{models:n??[],...i?{currentModelId:i}:{},...o?{currentEffort:o}:{},...a?{currentFastMode:a}:{},...d?{effortLevels:d}:{},...f?{fastModes:f}:{}}:null}function EE(t){let e=dn(t.models);if(!e)return null;let n=$r(e.availableModels);if(n.length===0)return null;let i=J0(n,"modelId");if(i.length===0)return null;let o=vt(e.currentModelId);return{models:i,...o?{currentModelId:o}:{}}}function Z0(t,e){let n=dn(e);if(!n)return null;let i=dn(n.result)??n;return t==="hermes"?EE(i):yE(i)}function bE(t){let e=[],n=t.split(/\r?\n/),i=!1,o=-1,a=null,d=-1,f=!1,u=-1,x=p=>p.length-p.trimStart().length;for(let p of n){let w=p.replace(/#.*$/,"").trimEnd();if(w.trim()==="")continue;let b=x(w),_=w.trim();if(!i){_==="providers:"&&(i=!0,o=b);continue}if(b<=o&&!_.startsWith("-"))break;if((a===null||b<=d)&&_.endsWith(":")&&!_.startsWith("-")){a=_.slice(0,-1).trim(),d=b,f=!1;continue}if(a!==null){if(!f){_==="models:"&&(f=!0,u=b);continue}if(_.startsWith("-")&&b>u){let v=_.slice(1).trim(),I,A=v.match(/^(?:model|id)\s*:\s*(.+)$/);if(A?.[1]?I=A[1].trim():v&&!v.includes(":")&&(I=v),I){let T=I.replace(/^["']|["']$/g,"");e.push({id:`${a}:${T}`,providerId:a})}continue}b<=u&&(f=!1,b<=d&&_.endsWith(":")&&(a=_.slice(0,-1).trim(),d=b))}}return e}async function X0(t){let e=t??mE(),n=wE.join(e,".hermes","config.yaml"),i;try{i=await gE(n,"utf8")}catch{return null}let o=bE(i);return o.length===0?null:{models:o}}async function Y0(t){let e;try{({stdout:e}=await Oo(t,["models","list","--json","--log-level","silent"],{timeout:_E,maxBuffer:4*1024*1024}))}catch{return null}return vE(e)}function vE(t){let e;try{e=JSON.parse(t)}catch{return null}let n=$r(dn(e)?.models);if(n.length===0)return null;let i=n.map(u=>dn(u)).filter(u=>u!==null&&u.available!==!1),o=i.filter(u=>$r(u.tags).some(x=>x==="configured")),a=o.length>0?o:i,d=[],f;for(let u of a){let x=vt(u.key);if(!x)continue;let p={id:x},w=vt(u.name);w&&(p.name=w);let b=x.indexOf("/");b>0&&(p.providerId=x.slice(0,b)),d.push(p),!f&&$r(u.tags).some(_=>_==="default")&&(f=x)}return d.length===0?null:{models:d,...f?{defaultModelId:f}:{}}}function SE(t){let e=[...t].sort((n,i)=>n.id.localeCompare(i.id));return V0("sha1").update(JSON.stringify(e)).digest("hex")}function Q0(t){return V0("sha1").update(SE(t.models)).update(JSON.stringify(t.effortLevels??null)).update(JSON.stringify(t.fastModes??null)).digest("hex")}var X=q("agent-handlers"),th=5*1024*1024,CE=1,RE=6,PE=new Set(["node_modules",".git",".coze","dist","build",".next"]),DE=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,OE=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,LE=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function ME(t){let e=t?.trim();return e?LE.test(e)||OE.test(e)?e:(X.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function NE(t){return new Promise((e,n)=>{let i=dt("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 FE(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var zo=class t{constructor(e){this.opts=e}opts;static OPENCLAW_MODEL_CACHE_TTL_MS=18e4;openclawRefreshInFlight=!1;get paths(){return this.opts.paths??Z()}async listSkills(e){e._meta;let n=or(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Oe(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:f}=Jr(a,n,o,this.paths),u=[],x=new Set;for(let w of d){let b=xe(f,w.relPath,"SKILL.md");await Fd(b).then(v=>v.isFile()).catch(()=>!1)&&(u.push(qE(w)),x.add(w.relPath))}if(e.scanLocal){let w=await uh(n,o,a,this.paths),b=await hh(n,a);for(let _ of[...w,...b])x.has(_.relPath)||(x.add(_.relPath),u.push(_.skill))}return{skills:a==="hermes"?u.filter(w=>w.skillName!=="yuanbao"):u}}async addSkills(e){e._meta;let n=or(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((u,x)=>[u.skillId,x])),f=[];for(let u of o){let x=await Uo({agentId:n,workspace:i.workspace,framework:i.framework,skill:u,paths:this.paths});Ho(a,d,x),f.push(u)}return await Ii(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:f}}async removeSkills(e){e._meta;let n=or(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:f}=Jr(i.framework,n,i.workspace,this.paths);for(let u of a){if(!o.has(u.skillId)){d.push(u);continue}let x=xe(f,u.relPath);X.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:u.skillId,relPath:u.relPath,skillBase:f,absDir:x}),await Od(x,{recursive:!0,force:!0}),X.info("skill removed",{agentId:n,skillId:u.skillId,relPath:u.relPath})}return await Ii(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=or(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");X.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??Oe(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,f=await zE(n,o,a,e.skillName,d,this.paths);if(!f){let R=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${R}: ${e.skillName}`)}let{absDir:u,relPath:x,dirName:p}=f,w=xe(u,"SKILL.md"),b=new zd.default;b.addLocalFolder(u,p);let _=b.toBuffer();if(_.length>nh)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${nh}`);let v=await Bo(w,{encoding:"utf8"}).then(R=>lh(R).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):X.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??dh(n,x);if(i&&!d){let R=i.skills??[],E=R.find(P=>P.relPath===x);E?(E.version=A,E.skillId=T):R.push({skillId:T,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await Ii(n,R)}return X.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:T,version:A}),{ok:!0,skillId:T,version:A}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[o,a]of i.sessions){if(!a.downstream)continue;let d=a.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(a)){a.reloadAfterTurn=!0,X.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let u=a.downstream;a.downstream=void 0,X.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d}),u.stop(n).catch(x=>X.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 X.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await we(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return X.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await Tr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw X.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Le(i),X.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:i.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async upgradeBridge(e){let n=e.agentId||e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await we(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&es(e.registry)&&o.push(`--registry=${e.registry}`);let a=ME(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&DE.test(d)&&o.push("--env",d);let f=await NE(o);return X.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:f,targetVersion:a,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:f,message:"bridge upgrade started"}}async disconnectAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await we(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Le(i),X.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}):(X.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST",`${rt.DELETE}: missing agentId`);X.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 we(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=Oe(n);return a==="cloud"?(X.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 Od(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Le(i)),X.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=Id(e.model)??Mt;if(sr(e._meta)!=="cloud")return this.switchModelLocal(e,n);let i=await we(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await Le(i),X.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return X.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=>X.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let f=o.framework==="hermes"&&FE(d,o.modelInfo);if(o.framework==="hermes"&&!f){let x=[];for(let[p,w]of o.allSessionQueues())x.push(w.enqueue(async()=>{let b=o.sessions.get(p);if(!(!b?.downstream||!b.acpSessionId))try{await b.downstream.setSessionModel?.({sessionId:b.acpSessionId,modelId:n})}catch(_){X.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:p,acpId:b.acpSessionId,err:String(_)})}}));return await Promise.all(x),X.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:x.length}),{ok:!0}}let u=[];for(let[x,p]of o.allSessionQueues())u.push(p.enqueue(async()=>{let w=o.sessions.get(x);w?.downstream&&(await w.downstream.stop(`switchModel: ${n}`).catch(()=>{}),w.downstream=void 0)}));return await Promise.all(u),X.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:u.length}),{ok:!0}}async switchModelLocal(e,n){let i=await we(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,await Le(i),X.info("_agent/switchModel(local): model persisted",{agentId:e.agentId,model:n});let o=this.opts.agents.get(e.agentId);if(!o)return X.info("_agent/switchModel(local): agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};if(o.model=n,bt(n))return X.info("_agent/switchModel(local): auto sentinel, skip runtime fan-out",{agentId:e.agentId}),{ok:!0};let a=await this.fanOutConfigAxis(o,e.agentId,"model",n,"_agent/switchModel(local)");return X.info("_agent/switchModel(local): sessions updated via set_config_option",{agentId:e.agentId,model:n,cloudSessions:a}),{ok:!0}}async fanOutConfigAxis(e,n,i,o,a){let d=[];for(let[f,u]of e.allSessionQueues())d.push(u.enqueue(async()=>{let x=e.sessions.get(f);!x?.downstream||!x.acpSessionId||await x.downstream.setConfigOption(x.acpSessionId,i,o).catch(p=>X.warn(`${a}: set_config_option failed (ignored)`,{agentId:n,cloudId:f,err:String(p)}))}));return await Promise.all(d),d.length}async setConfigOption(e){if(_d(e._meta,rt.SET_CONFIG_OPTION),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/setConfigOption: missing agentId");let n=await we(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=T0(n.framework,e.configType);if(!i)throw new k("CAPABILITY_UNSUPPORTED",`${n.framework} does not support config '${e.configType}'`);let o=this.opts.modelListCache?.get(n.framework);if(!((e.configType==="effort"?o?.effortLevels:o?.fastModes)??i).includes(e.value))throw new k("IPC_BAD_REQUEST",`invalid ${e.configType} value '${e.value}' for ${n.framework}`);let d=e.value;n.framework==="claude-code"&&e.configType==="effort"&&e.value==="default"&&(d=await this.resolveEffortDefault(n.workspace));let f=n[e.configType];n[e.configType]=d,await Le(n),X.info("_agent/setConfigOption: persisted",{agentId:e.agentId,configType:e.configType,value:d}),n.framework==="claude-code"&&e.configType==="effort"&&await v0(n.workspace,d).catch(x=>X.warn("_agent/setConfigOption: writeCcWorkspaceEffort failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=this.opts.agents.get(e.agentId);return u&&(e.configType==="effort"?u.setEffort(d):u.setFastMode(d),await this.fanOutConfigAxis(u,e.agentId,e.configType,d,"_agent/setConfigOption")),{ok:!0,previousValue:f,currentValue:d}}async resolveEffortDefault(e){let n=await S0(e).catch(()=>{});if(n)return n;let i=await I0().catch(()=>{});return i||"default"}async listAvailableModels(e){if(_d(e._meta,rt.LIST_AVAILABLE_MODELS),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/listAvailableModels: missing agentId");let n=await we(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=n.framework,o=this.opts.modelListCache,a=[],d,f="fallback",u=o?.get(i);if(u&&u.models.length>0)a=u.models,d=u.defaultModelId,f="cache",i==="openclaw"&&this.maybeRefreshOpenclawModels(u.cachedAt);else if(i==="hermes"){let T=await X0().catch(()=>null);T&&T.models.length>0&&(a=T.models,d=T.defaultModelId,f="disk")}else if(i==="openclaw"){let T=await this.opts.openclawModelLister?.().catch(()=>null);T&&T.models.length>0&&(a=T.models,d=T.defaultModelId,f="disk",o?.update("openclaw",T).catch(()=>{}))}let x=o?.getRuntimeCurrent(e.agentId),p;n.model&&!bt(n.model)?p=n.model:p=x?.model??d;let w=n.effort??x?.effort,b=n.fastMode??x?.fastMode,_=yd[i],v=u?.effortLevels??_.effort,I=u?.fastModes??_.fastMode,A={switchModel:!0,switchEffort:_.effort!==null,switchFastMode:_.fastMode!==null,...v?{supportedEffortLevels:[...v]}:{},...I?{supportedFastModes:[...I]}:{}};return{framework:i,models:a,...d?{defaultModelId:d}:{},...p?{currentModelId:p}:{},...A.switchEffort&&w?{currentEffort:w}:{},...A.switchFastMode&&b?{currentFastMode:b}:{},source:f,capabilities:A}}maybeRefreshOpenclawModels(e){let n=this.opts.openclawModelLister,i=this.opts.modelListCache;!n||!i||this.openclawRefreshInFlight||Date.now()-e<t.OPENCLAW_MODEL_CACHE_TTL_MS||(this.openclawRefreshInFlight=!0,(async()=>{try{let o=await n();o&&o.models.length>0&&await i.update("openclaw",o)}catch{}finally{this.openclawRefreshInFlight=!1}})())}async detail(e){let n=e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST",`${rt.DETAIL}: missing cozeAgentId`);let i=await we(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=this.opts.modelListCache?.getRuntimeCurrent(n),a=i.effort??o?.effort,d=i.fastMode??o?.fastMode;return{agentId:n,agentName:i.agentName??"",cozeIdentity:i.cozeIdentity??"",framework:i.framework,...i.description!==void 0?{description:i.description}:{},...i.model?{model:i.model}:{},...a?{effort:a}:{},...d?{fastMode:d}:{}}}async resetAgent(e){if(Qi(e._meta,rt.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${rt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,rt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>X.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,rt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),X.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 Si(e,o)}async clearPersistedAcpSessionIds(e){let n=await we(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 Le(n)}async repairAgent(e){if(Qi(e._meta,rt.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${rt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${rt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){X.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,rt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){X.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){X.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Qi(e._meta,"_agent/getFileTree");let n=e._meta,i=or(n),o=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(o,a),f=await Pd(d).catch(()=>null);if(!f)throw new k("IPC_BAD_REQUEST",`path not found: ${a}`);if(f.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${a}`);if(!await vi(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let u=eb(e.depth);return f.isDirectory()?{tree:await QE(o,d,a,u)}:{tree:[{name:tb(a),path:gh(a||"."),isDir:!1,size:f.size,modifiedAt:Math.floor(f.mtimeMs)}]}}async getFileContent(e){Qi(e._meta,"_agent/getFileContent");let n=or(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),a=await Pd(o).catch(()=>null);if(!a||!a.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(a.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await vi(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>th)throw new k("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${th})`);let d=await Bo(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 we(e).catch(()=>null))?.workspace??Oe(e).workspace}safeJoin(e,n){let i=Md(e,n||"."),o=Bd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${ih}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return we(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function ah(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new k("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new k("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function Jr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:xe(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:xe(".agents","skills")};case"hermes":return{base:dr(e,i??Z()),subdir:"skills"}}}function ch(t){let e=AE();if(t==="claude-code")return[xe(e,".claude","skills")];if(t==="codex")return[xe(e,".agents","skills"),xe(e,".codex","skills")];if(t==="openclaw")return[xe(e,".agents","skills"),xe(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||xe(e,"AppData","Local");return[xe(n,"hermes","skills"),xe(e,".hermes","skills")]}return[xe(e,".hermes","skills")]}return[]}async function BE(t,e,n,i,o,a){let d=async f=>Fd(xe(f,"SKILL.md")).then(u=>u.isFile()).catch(()=>!1);if(!o){let{base:f,subdir:u}=Jr(n,t,e,a),x=xe(u,i),p=xe(f,x);return await d(p)?{absDir:p,relPath:x}:null}for(let f of ch(n)){let u=xe(f,i);if(await d(u))return{absDir:u,relPath:u}}return null}async function zE(t,e,n,i,o,a){let d=ah(i),f=await BE(t,e,n,d,o,a);if(f)return{...f,dirName:d};let x=(o?await hh(t,n):await uh(t,e,n,a)).filter(b=>b.skill.skillName===i);if(x.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${x.map(b=>eh(b.relPath)).join(", ")} \u2014 rename or remove duplicates`);let p=x[0];return p?{absDir:o?p.relPath:xe(e,p.relPath),relPath:p.relPath,dirName:eh(p.relPath)}:null}function dh(t,e){return(IE("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function lh(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
|
|
97
|
+
`}var fr=H("hermes-config"),W0="dont_ask",K0="default";function hr(t,e){return as(Ne(t,e).root,"hermes-home")}async function xb(t){let e=hr(t.agentId,t.paths);await pb(e,{recursive:!0,mode:448});let n=is({...process.env,...ur(t.paths.agentEnvFile)});await vt(as(e,".env"),n,{mode:384});let i=Td(t.modelConfig,t.cozeEnv,t.mockScenario);await vt(as(e,"config.yaml"),i,{mode:384}),fr.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function $0(t){let e=hr(t.agentId,t.paths),n=as(e,"state.db"),i=as(e,"config.yaml");fr.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 j0(n,{force:!0}).catch(a=>fr.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let o=Td({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await vt(i,o,{mode:384}).catch(a=>fr.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(a)})),fr.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function Rd(t,e){let n=hr(t,e);fr.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 j0(n,{recursive:!0,force:!0}).catch(i=>fr.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var Pd=new Map;function V0(t){let e=Pd.get(t.agentId);if(e)return e;let n=xb(t).finally(()=>Pd.delete(t.agentId));return Pd.set(t.agentId,n),n}Vt();import{createHash as J0}from"node:crypto";import{readFile as gb}from"node:fs/promises";import{homedir as mb}from"node:os";import wb from"node:path";var _b=3e4;function pn(t){return typeof t=="object"&&t!==null?t:null}function Zr(t){return Array.isArray(t)?t:[]}function kt(t){return typeof t=="string"?t:void 0}function Z0(t,e){return t.map(n=>pn(n)).filter(n=>n!==null).map(n=>{let i={id:kt(n[e])??""},o=kt(n.name),a=kt(n.description);return o&&(i.name=o),a&&(i.description=a),i}).filter(n=>n.id!=="")}function yb(t){let e=Zr(t.configOptions);if(e.length===0)return null;let n=null,i,o,a,d,u;for(let p of e){let x=pn(p);if(!x)continue;let g=kt(x.id);if(!g)continue;let v=Zr(x.options);g==="model"?(n=Z0(v,"value"),i=kt(x.currentValue)):g==="effort"||g==="reasoning_effort"?(o=kt(x.currentValue),d=v.map(w=>kt(pn(w)?.value)).filter(w=>w!==void 0)):g==="fast-mode"&&(a=kt(x.currentValue),u=v.map(w=>kt(pn(w)?.value)).filter(w=>w!==void 0))}return n!==null||i!==void 0||o!==void 0||a!==void 0||d!==void 0||u!==void 0?{models:n??[],...i?{currentModelId:i}:{},...o?{currentEffort:o}:{},...a?{currentFastMode:a}:{},...d?{effortLevels:d}:{},...u?{fastModes:u}:{}}:null}function bb(t){let e=pn(t.models);if(!e)return null;let n=Zr(e.availableModels);if(n.length===0)return null;let i=Z0(n,"modelId");if(i.length===0)return null;let o=kt(e.currentModelId);return{models:i,...o?{currentModelId:o}:{}}}function Y0(t,e){let n=pn(e);if(!n)return null;let i=pn(n.result)??n;return t==="hermes"?bb(i):yb(i)}function Eb(t){let e=[],n=t.split(/\r?\n/),i=!1,o=-1,a=null,d=-1,u=!1,f=-1,p=x=>x.length-x.trimStart().length;for(let x of n){let g=x.replace(/#.*$/,"").trimEnd();if(g.trim()==="")continue;let v=p(g),w=g.trim();if(!i){w==="providers:"&&(i=!0,o=v);continue}if(v<=o&&!w.startsWith("-"))break;if((a===null||v<=d)&&w.endsWith(":")&&!w.startsWith("-")){a=w.slice(0,-1).trim(),d=v,u=!1;continue}if(a!==null){if(!u){w==="models:"&&(u=!0,f=v);continue}if(w.startsWith("-")&&v>f){let E=w.slice(1).trim(),S,A=E.match(/^(?:model|id)\s*:\s*(.+)$/);if(A?.[1]?S=A[1].trim():E&&!E.includes(":")&&(S=E),S){let C=S.replace(/^["']|["']$/g,"");e.push({id:`${a}:${C}`,providerId:a})}continue}v<=f&&(u=!1,v<=d&&w.endsWith(":")&&(a=w.slice(0,-1).trim(),d=v))}}return e}async function X0(t){let e=t??mb(),n=wb.join(e,".hermes","config.yaml"),i;try{i=await gb(n,"utf8")}catch{return null}let o=Eb(i);return o.length===0?null:{models:o}}async function Q0(t){let e;try{({stdout:e}=await No(t,["models","list","--json","--log-level","silent"],{timeout:_b,maxBuffer:4*1024*1024}))}catch{return null}return vb(e)}function vb(t){let e;try{e=JSON.parse(t)}catch{return null}let n=Zr(pn(e)?.models);if(n.length===0)return null;let i=n.map(f=>pn(f)).filter(f=>f!==null&&f.available!==!1),o=i.filter(f=>Zr(f.tags).some(p=>p==="configured")),a=o.length>0?o:i,d=[],u;for(let f of a){let p=kt(f.key);if(!p)continue;let x={id:p},g=kt(f.name);g&&(x.name=g);let v=p.indexOf("/");v>0&&(x.providerId=p.slice(0,v)),d.push(x),!u&&Zr(f.tags).some(w=>w==="default")&&(u=p)}return d.length===0?null:{models:d,...u?{defaultModelId:u}:{}}}function Sb(t){let e=[...t].sort((n,i)=>n.id.localeCompare(i.id));return J0("sha1").update(JSON.stringify(e)).digest("hex")}function eh(t){return J0("sha1").update(Sb(t.models)).update(JSON.stringify(t.effortLevels??null)).update(JSON.stringify(t.fastModes??null)).digest("hex")}var Y=H("agent-handlers"),nh=5*1024*1024,Tb=1,Pb=6,Rb=new Set(["node_modules",".git",".coze","dist","build",".next"]),Db=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ob=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Lb=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Mb(t){let e=t?.trim();return e?Lb.test(e)||Ob.test(e)?e:(Y.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Nb(t){return new Promise((e,n)=>{let i=ht("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 Fb(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var Go=class t{constructor(e){this.opts=e}opts;static OPENCLAW_MODEL_CACHE_TTL_MS=18e4;openclawRefreshInFlight=!1;get paths(){return this.opts.paths??Z()}async listSkills(e){e._meta;let n=lr(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Ne(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Xr(a,n,o,this.paths),f=[],p=new Set;for(let g of d){let v=pe(u,g.relPath,"SKILL.md");await Bd(v).then(E=>E.isFile()).catch(()=>!1)&&(f.push(Gb(g)),p.add(g.relPath))}if(e.scanLocal){let g=await hh(n,o,a,this.paths),v=await ph(n,a);for(let w of[...g,...v])p.has(w.relPath)||(p.add(w.relPath),f.push(w.skill))}return{skills:a==="hermes"?f.filter(g=>g.skillName!=="yuanbao"):f}}async addSkills(e){e._meta;let n=lr(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((f,p)=>[f.skillId,p])),u=[];for(let f of o){let p=await qo({agentId:n,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});jo(a,d,p),u.push(f)}return await Ci(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=lr(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:u}=Xr(i.framework,n,i.workspace,this.paths);for(let f of a){if(!o.has(f.skillId)){d.push(f);continue}let p=pe(u,f.relPath);Y.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:f.skillId,relPath:f.relPath,skillBase:u,absDir:p}),await Ld(p,{recursive:!0,force:!0}),Y.info("skill removed",{agentId:n,skillId:f.skillId,relPath:f.relPath})}return await Ci(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=lr(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");Y.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??Ne(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,u=await zb(n,o,a,e.skillName,d,this.paths);if(!u){let P=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${P}: ${e.skillName}`)}let{absDir:f,relPath:p,dirName:x}=u,g=pe(f,"SKILL.md"),v=new Ud.default;v.addLocalFolder(f,x);let w=v.toBuffer();if(w.length>rh)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${w.length} bytes exceeds limit ${rh}`);let E=await Ho(g,{encoding:"utf8"}).then(P=>uh(P).description).catch(()=>{}),S={};this.opts.publishSkillToMarketplace?S=await this.opts.publishSkillToMarketplace({zip:w,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...E?{description:E}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):Y.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=S.version??"v1.0",C=S.skillId??e.skillId??lh(n,p);if(i&&!d){let P=i.skills??[],y=P.find(R=>R.relPath===p);y?(y.version=A,y.skillId=C):P.push({skillId:C,skillName:e.skillName,relPath:p,version:A,installedAt:Date.now(),...E?{description:E}:{}}),await Ci(n,P)}return Y.info("skill published",{agentId:n,skillName:e.skillName,relPath:p,zipBytes:w.length,skillId:C,version:A}),{ok:!0,skillId:C,version:A}}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,Y.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,Y.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(n).catch(p=>Y.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:o,err:String(p)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return Y.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await ye(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return Y.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await Rr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw Y.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Oe(i),Y.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:i.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async upgradeBridge(e){let n=e.agentId||e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await ye(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&rs(e.registry)&&o.push(`--registry=${e.registry}`);let a=Mb(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&Db.test(d)&&o.push("--env",d);let u=await Nb(o);return Y.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 k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await ye(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Oe(i),Y.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}):(Y.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST",`${at.DELETE}: missing agentId`);Y.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 ye(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=Ne(n);return a==="cloud"?(Y.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 Ld(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Oe(i)),Y.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=Ad(e.model)??Bt;if(dr(e._meta)!=="cloud")return this.switchModelLocal(e,n);let i=await ye(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await Oe(i),Y.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return Y.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(p=>Y.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(p)}));let u=o.framework==="hermes"&&Fb(d,o.modelInfo);if(o.framework==="hermes"&&!u){let p=[];for(let[x,g]of o.allSessionQueues())p.push(g.enqueue(async()=>{let v=o.sessions.get(x);if(!(!v?.downstream||!v.acpSessionId))try{await v.downstream.setSessionModel?.({sessionId:v.acpSessionId,modelId:n})}catch(w){Y.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:x,acpId:v.acpSessionId,err:String(w)})}}));return await Promise.all(p),Y.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:p.length}),{ok:!0}}let f=[];for(let[p,x]of o.allSessionQueues())f.push(x.enqueue(async()=>{let g=o.sessions.get(p);g?.downstream&&(await g.downstream.stop(`switchModel: ${n}`).catch(()=>{}),g.downstream=void 0)}));return await Promise.all(f),Y.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:f.length}),{ok:!0}}async switchModelLocal(e,n){let i=await ye(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,await Oe(i),Y.info("_agent/switchModel(local): model persisted",{agentId:e.agentId,model:n});let o=this.opts.agents.get(e.agentId);if(!o)return Y.info("_agent/switchModel(local): agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};if(o.model=n,At(n))return Y.info("_agent/switchModel(local): auto sentinel, skip runtime fan-out",{agentId:e.agentId}),{ok:!0};let a=await this.fanOutConfigAxis(o,e.agentId,"model",n,"_agent/switchModel(local)");return Y.info("_agent/switchModel(local): sessions updated via set_config_option",{agentId:e.agentId,model:n,cloudSessions:a}),{ok:!0}}async fanOutConfigAxis(e,n,i,o,a){let d=[];for(let[u,f]of e.allSessionQueues())d.push(f.enqueue(async()=>{let p=e.sessions.get(u);!p?.downstream||!p.acpSessionId||await p.downstream.setConfigOption(p.acpSessionId,i,o).catch(x=>Y.warn(`${a}: set_config_option failed (ignored)`,{agentId:n,cloudId:u,err:String(x)}))}));return await Promise.all(d),d.length}async setConfigOption(e){if(yd(e._meta,at.SET_CONFIG_OPTION),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/setConfigOption: missing agentId");let n=await ye(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=T0(n.framework,e.configType);if(!i)throw new k("CAPABILITY_UNSUPPORTED",`${n.framework} does not support config '${e.configType}'`);let o=this.opts.modelListCache?.get(n.framework);if(!((e.configType==="effort"?o?.effortLevels:o?.fastModes)??i).includes(e.value))throw new k("IPC_BAD_REQUEST",`invalid ${e.configType} value '${e.value}' for ${n.framework}`);let d=e.value;n.framework==="claude-code"&&e.configType==="effort"&&e.value==="default"&&(d=await this.resolveEffortDefault(n.workspace));let u=n[e.configType];n[e.configType]=d,await Oe(n),Y.info("_agent/setConfigOption: persisted",{agentId:e.agentId,configType:e.configType,value:d}),n.framework==="claude-code"&&e.configType==="effort"&&await S0(n.workspace,d).catch(p=>Y.warn("_agent/setConfigOption: writeCcWorkspaceEffort failed (ignored)",{agentId:e.agentId,err:String(p)}));let f=this.opts.agents.get(e.agentId);return f&&(e.configType==="effort"?f.setEffort(d):f.setFastMode(d),await this.fanOutConfigAxis(f,e.agentId,e.configType,d,"_agent/setConfigOption")),{ok:!0,previousValue:u,currentValue:d}}async resolveEffortDefault(e){let n=await I0(e).catch(()=>{});if(n)return n;let i=await A0().catch(()=>{});return i||"default"}async listAvailableModels(e){if(yd(e._meta,at.LIST_AVAILABLE_MODELS),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/listAvailableModels: missing agentId");let n=await ye(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=n.framework,o=this.opts.modelListCache,a=[],d,u="fallback",f=o?.get(i);if(f&&f.models.length>0)a=f.models,d=f.defaultModelId,u="cache",i==="openclaw"&&this.maybeRefreshOpenclawModels(f.cachedAt);else if(i==="hermes"){let C=await X0().catch(()=>null);C&&C.models.length>0&&(a=C.models,d=C.defaultModelId,u="disk")}else if(i==="openclaw"){let C=await this.opts.openclawModelLister?.().catch(()=>null);C&&C.models.length>0&&(a=C.models,d=C.defaultModelId,u="disk",o?.update("openclaw",C).catch(()=>{}))}let p=o?.getRuntimeCurrent(e.agentId),x;n.model&&!At(n.model)?x=n.model:(x=p?.model??n.resolvedModelId??d,x&&x!==n.resolvedModelId&&(n.resolvedModelId=x,await Oe(n).catch(C=>Y.warn("listAvailableModels: persist resolvedModelId failed (ignored)",{agentId:e.agentId,err:String(C)}))));let g=n.effort??p?.effort,v=n.fastMode??p?.fastMode,w=bd[i],E=f?.effortLevels??w.effort,S=f?.fastModes??w.fastMode,A={switchModel:!0,switchEffort:w.effort!==null,switchFastMode:w.fastMode!==null,...E?{supportedEffortLevels:[...E]}:{},...S?{supportedFastModes:[...S]}:{}};return{framework:i,models:a,...d?{defaultModelId:d}:{},...x?{currentModelId:x}:{},...A.switchEffort&&g?{currentEffort:g}:{},...A.switchFastMode&&v?{currentFastMode:v}:{},source:u,capabilities:A}}maybeRefreshOpenclawModels(e){let n=this.opts.openclawModelLister,i=this.opts.modelListCache;!n||!i||this.openclawRefreshInFlight||Date.now()-e<t.OPENCLAW_MODEL_CACHE_TTL_MS||(this.openclawRefreshInFlight=!0,(async()=>{try{let o=await n();o&&o.models.length>0&&await i.update("openclaw",o)}catch{}finally{this.openclawRefreshInFlight=!1}})())}async detail(e){let n=e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST",`${at.DETAIL}: missing cozeAgentId`);let i=await ye(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=this.opts.modelListCache?.getRuntimeCurrent(n),a=i.effort??o?.effort,d=i.fastMode??o?.fastMode;return{agentId:n,agentName:i.agentName??"",cozeIdentity:i.cozeIdentity??"",framework:i.framework,...i.description!==void 0?{description:i.description}:{},...i.model?{model:i.model}:{},...a?{effort:a}:{},...d?{fastMode:d}:{}}}async resetAgent(e){if(ns(e._meta,at.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${at.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,at.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>Y.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,at.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),Y.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 ki(e,o)}async clearPersistedAcpSessionIds(e){let n=await ye(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 Oe(n)}async repairAgent(e){if(ns(e._meta,at.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${at.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${at.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){Y.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,at.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){Y.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){Y.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){ns(e._meta,"_agent/getFileTree");let n=e._meta,i=lr(n),o=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(o,a),u=await Dd(d).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${a}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${a}`);if(!await Ai(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let f=eE(e.depth);return u.isDirectory()?{tree:await Qb(o,d,a,f)}:{tree:[{name:tE(a),path:mh(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){ns(e._meta,"_agent/getFileContent");let n=lr(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),a=await Dd(o).catch(()=>null);if(!a||!a.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(a.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await Ai(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>nh)throw new k("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${nh})`);let d=await Ho(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 ye(e).catch(()=>null))?.workspace??Ne(e).workspace}safeJoin(e,n){let i=Nd(e,n||"."),o=zd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${sh}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return ye(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function ch(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new k("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new k("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function Xr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:pe(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:pe(".agents","skills")};case"hermes":return{base:hr(e,i??Z()),subdir:"skills"}}}function dh(t){let e=Ab();if(t==="claude-code")return[pe(e,".claude","skills")];if(t==="codex")return[pe(e,".agents","skills"),pe(e,".codex","skills")];if(t==="openclaw")return[pe(e,".agents","skills"),pe(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||pe(e,"AppData","Local");return[pe(n,"hermes","skills"),pe(e,".hermes","skills")]}return[pe(e,".hermes","skills")]}return[]}async function Bb(t,e,n,i,o,a){let d=async u=>Bd(pe(u,"SKILL.md")).then(f=>f.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:f}=Xr(n,t,e,a),p=pe(f,i),x=pe(u,p);return await d(x)?{absDir:x,relPath:p}:null}for(let u of dh(n)){let f=pe(u,i);if(await d(f))return{absDir:f,relPath:f}}return null}async function zb(t,e,n,i,o,a){let d=ch(i),u=await Bb(t,e,n,d,o,a);if(u)return{...u,dirName:d};let p=(o?await ph(t,n):await hh(t,e,n,a)).filter(v=>v.skill.skillName===i);if(p.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${p.map(v=>th(v.relPath)).join(", ")} \u2014 rename or remove duplicates`);let x=p[0];return x?{absDir:o?x.relPath:pe(e,x.relPath),relPath:x.relPath,dirName:th(x.relPath)}:null}function lh(t,e){return(Ib("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function uh(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],f=a[2].trim();(f.startsWith('"')&&f.endsWith('"')||f.startsWith("'")&&f.endsWith("'"))&&(f=f.slice(1,-1)),f&&(i[d]=f)}return i}async function fh(t,e,n,i){let o=await rh(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let a=[];for(let d of o){let f=d.isDirectory();if(!f&&d.isSymbolicLink()&&(f=!!(await Fd(xe(e,d.name)).catch(()=>null))?.isDirectory()),!f)continue;let u=d.name,x=xe(n,u),p=xe(e,u,"SKILL.md"),w=await Bo(p,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let b=lh(w);a.push({relPath:x,skill:{skillId:dh(t,x),skillName:b.name||u,...b.description?{description:b.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function uh(t,e,n,i){let{base:o,subdir:a}=Jr(n,t,e,i);return fh(t,xe(o,a),a,!1)}async function hh(t,e){let n=[],i=new Set;for(let o of ch(e)){let a=await fh(t,o,o,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var UE=3e4,HE=50*1024*1024,nh=10*1024*1024,Vr=3e4;async function Uo(t){let{agentId:e,workspace:n,framework:i,skill:o,paths:a}=t;if(!o.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let d=typeof o.content=="string"&&o.content.length>0,f=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!d&&!f)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=ah(o.skillName),{base:x,subdir:p}=Jr(i,e,n,a),w=xe(p,u),b=xe(x,w);if(await Dd(b,{recursive:!0}),d){let v=Buffer.from(o.content,"utf8");ss(v.length),await Ld(xe(b,"SKILL.md"),v,"utf8")}else{let v=await jE(o.downloadUrl);KE(v)?await ZE(v,b):$E(v)?await VE(v,b):await Ld(xe(b,"SKILL.md"),v.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:w,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return X.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:w,source:d?"content":"downloadUrl"}),_}function Ho(t,e,n){let i=e.get(n.skillId);if(i!==void 0){t[i]=n;return}e.set(n.skillId,t.length),t.push(n)}function qE(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 GE(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 xh(t,e){let n=await we(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Kt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await Le(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((w,b)=>[w.skillId,b])),f=a.filter(w=>w.builtin===!0&&!!w.downloadUrl);if(f.length===0)return n.skillsRefreshedForVersion=i,await Le(n,e),{status:"noop",count:0};let u=0,x=0,{base:p}=Jr(n.framework,t,n.workspace,e);X.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:p,builtinCount:f.length,builtinRelPaths:f.map(w=>w.relPath)});for(let w of f)try{let b=xe(p,w.relPath);X.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:w.skillId,relPath:w.relPath,rmTarget:b}),await Od(b,{recursive:!0,force:!0});let _=await Uo({agentId:t,workspace:n.workspace,framework:n.framework,skill:GE(w),...e?{paths:e}:{}});Ho(a,d,_),u+=1}catch(b){x+=1,X.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:w.skillId,skillName:w.skillName,err:String(b)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await Le(n,e),X.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:u,failed:x}),{status:"refreshed",count:u}}async function jE(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);ss(e);let n=WE(t);return ss(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Bo(e);return ss(n.length),n}if(es(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),UE);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return ss(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function ss(t){if(t>HE)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function WE(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let n=!!e[2],i=e[3]??"";return n?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function KE(t){return t.length>=2&&t[0]===31&&t[1]===139}function $E(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 Nd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function VE(t,e){let n,i;try{n=new zd.default(t),i=n.getEntries()}catch(d){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let f=d.entryName;if(!f||Nd(f))continue;if(f.startsWith("/")||/^[A-Za-z]:[\\/]/.test(f))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${f}`);if(f.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${f}`);let u=d.header.attr>>>16&61440;if(u!==0&&u!==32768&&u!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${u.toString(16)} not allowed (symlink/hardlink/special): ${f}`)}let o=JE(i),a=Md(e);for(let d of i){if(Nd(d.entryName))continue;let f=d.entryName;if(o&&f.startsWith(o)&&(f=f.slice(o.length)),!f)continue;let u=Md(e,f),x=Bd(a,u);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${f}`);if(d.isDirectory){await Dd(u,{recursive:!0});continue}await Dd(kE(u),{recursive:!0});let p;try{p=d.getData()}catch(w){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await Ld(u,p)}}function JE(t){let e;for(let n of t){let i=n.entryName;if(!i||Nd(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 ZE(t,e){await XE(t);let n=h0({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Vr}ms)`))},Vr);try{await oh(sh.from(t),n)}catch(a){throw a instanceof k?a:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Vr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function XE(t){let e=[],n=jr({onReadEntry:a=>{let d=a.path,f=a.type;if(f!=="File"&&f!=="Directory"){e.push(`tar entry kind '${f}' 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 k("IPC_BAD_REQUEST",`tar list timeout (${Vr}ms)`))},Vr);try{await oh(sh.from(t),n)}catch(a){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Vr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var YE=5e3;async function QE(t,e,n,i){return ph(t,e,n,i,{count:0})}async function ph(t,e,n,i,o){if(i<=0)return[];let a;try{a=await rh(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let f of a){if(PE.has(f.name)||f.isSymbolicLink())continue;if(o.count>=YE){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let u=xe(e,f.name),x=TE(xe(n,f.name)),p=null;try{p=await Pd(u)}catch{continue}if(p.isSymbolicLink())continue;o.count++;let w={name:f.name,path:gh(Bd(t,u)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(w.children=await ph(t,u,x,i-1,o)),d.push(w)}return d.sort((f,u)=>f.isDir!==u.isDir?f.isDir?-1:1:f.name.localeCompare(u.name)),d}function eb(t){return!t||t<=0?CE:Math.min(t,RE)}function tb(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function gh(t){return t.split(ih).join("/")}ne();var Fn=q("agent-health-reporter"),nb=1e4,rb=3,os=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??nb,this.livenessFailureThreshold=e.livenessFailureThreshold??rb}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()}),Fn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Fn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Fn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Fn.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 f=ib(d);if(!f)continue;let u={agentId:d.agentId,status:f};d.patToken&&(u.patToken=d.patToken),d.accountId&&(u.accountId=d.accountId),n.push(u)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Kt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Fn.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=o?.authFailures;if(a&&a.length>0&&(Fn.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){Fn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Fn.warn("onTickEnd hook failed",{err:String(n)})}}};function ib(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}tn();import{copyFile as Ev,cp as bv,mkdir as Qo,readFile as vv,rm as Sv,stat as $d,writeFile as Iv}from"node:fs/promises";import{homedir as tx}from"node:os";import{basename as Av,join as fn}from"node:path";vn();import{existsSync as pb}from"node:fs";import{release as gb}from"node:os";import{basename as mb,isAbsolute as wb}from"node:path";function as(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 Xr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Bn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ze();var qo=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)}},Q={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 mh(t){return"method"in t&&"id"in t&&t.id!==void 0}function wh(t){return"method"in t&&!("id"in t)}function Go(t){return!("method"in t)&&"id"in t}var sb={AGENT_NOT_FOUND:Q.AGENT_NOT_FOUND,AGENT_BUSY:Q.AGENT_BUSY,AGENT_DISCONNECTED:Q.AGENT_DISCONNECTED,AGENT_TIMEOUT:Q.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Q.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Q.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Q.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Q.INTERNAL_ERROR,BRIDGE_INTERNAL:Q.INTERNAL_ERROR,IPC_AUTH_FAILED:Q.INTERNAL_ERROR,IPC_BAD_REQUEST:Q.INVALID_REQUEST,METHOD_NOT_FOUND:Q.METHOD_NOT_FOUND,CAPABILITY_UNSUPPORTED:Q.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Q.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Q.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Q.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Q.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Q.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Q.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Q.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Q.FILE_TOO_LARGE,UNSUPPORTED_MIME:Q.UNSUPPORTED_MIME,UPLOAD_FAILED:Q.UPLOAD_FAILED,UPSTREAM_NOT_READY:Q.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Q.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Q.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Q.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Q.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Q.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Q.SKILL_ZIP_TOO_LARGE};function ob(t){if(t!=null)return t instanceof Error?{name:t.name,message:cs(t.message)}:typeof t=="string"?cs(t):typeof t=="object"?cb(t):t}var ab=[[/\/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 cs(t){let e=t;for(let[n,i]of ab)e=e.replace(n,i);return e}function cb(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=cs(i):e[n]=i;return e}function ds(t){if(t instanceof k){let e=ob(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:sb[t.code]??Q.INTERNAL_ERROR,message:cs(t.message),data:n}}return{code:Q.INTERNAL_ERROR,message:cs(t instanceof Error?t.message:String(t))}}function _h(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,...f}=e;a=f}return new k(n,o,{retriable:e?.retriable??!1,cause:a})}function Eh(t){return`${JSON.stringify(t)}
|
|
103
|
-
`}var
|
|
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??fs,i=e?.isAliveFn??ls,o=e?.sleepFn??(f=>new Promise(u=>setTimeout(u,f))),a=e?.graceMs??3e3,d=e?.pollMs??100;for(let f of t)n(f,"SIGTERM");for(let f=0;f<a&&t.some(u=>i(u));f+=d)await o(Math.min(d,a-f));for(let f of t)i(f)&&n(f,"SIGKILL")}var xb=[{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 Ch(t,e){if(!e)return null;for(let n of xb)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 Ch(t,e)}function Ph(t,e){return Ch(t,e)}function ei(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 Dh(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:ei(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:ei(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:ei(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:ei(a,!1,e)}}var Oh=Je("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",6e4),_b=200,yb=40,Eb=Je("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),bb=Je("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),vb=Je("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Sb=Je("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Ib=Je("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Ab=Je("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Lh=500,kb=process.env.COZE_BRIDGE_TRACE_RPC==="1",Mh=Je("COZE_BRIDGE_TRACE_RPC_MAX",2e3);function Tb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Lh?t:`${e.slice(0,Lh)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Cb(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 Nh(t){try{return pb(t)}catch{return}}function Rb(t,e){return{platform:process.platform,osRelease:gb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:wb(e.command)?Nh(e.command):void 0,cwd:e.cwd,cwdExists:Nh(e.cwd),envKeys:e.envKeys}}function Pb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${mb(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var St=class{constructor(e){this.opts=e;this.log=q(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new jo({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Yr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=Lo(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=dt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,Sh(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>_b&&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,Ih(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 f of this.decoder.flush())this.dispatch(f)}catch(f){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(f)})}this.failAllPending(this.buildExitError(o,a));for(let f of this.exitHandlers)f(o,a)}),i.on("error",o=>{let a=o,d=Rb(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 k("AGENT_SPAWN_FAILED",Pb(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()));fs(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||fs(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:Ib,phase2GateMs:Eb,livenessWindowMs:bb,absoluteMaxMs:vb,approvalMaxMs:Ab,suspendThresholdMs:Sb,...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)}configIdFor(e){return e==="model"?"model":null}sendSetConfigOption(e,n,i){return this.call("session/set_config_option",{sessionId:e,configId:n,value:i}).then(()=>{})}setConfigOption(e,n,i){let o=this.configIdFor(n);return o===null?Promise.reject(new k("CAPABILITY_UNSUPPORTED",`${this.framework} does not support axis '${n}'`)):this.sendSetConfigOption(e,o,i)}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(Xr(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(Bn(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 k("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=as(a,e,n),f=(()=>{if(typeof n!="object"||n===null)return;let u=n.sessionId;return typeof u=="string"?u:void 0})();return new Promise((u,x)=>{let p={resolve:u,reject:x,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),b={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:ei(0,!1,o),sessionId:f};p.promptTimeout=b;let _=()=>{let v={startedAt:b.startedAt,lastActivityAt:b.lastActivityAt,firstFrameSeen:b.firstFrameSeen,hasActiveTool:b.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:b.suspendedMs,armedAt:b.armedAt,expectedIntervalMs:b.expectedIntervalMs},I=this.now(),A=Dh(v,b.cfg,I),T=R=>{b.armedAt=I,b.expectedIntervalMs=R,p.timer=setTimeout(_,R)};if(A.action==="suspend"){b.suspendedMs+=A.suspendedDeltaMs,b.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:b.suspendedMs,...b.sessionId?{sessionId:b.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(a),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:A.awaitingApproval,...b.sessionId?{sessionId:b.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${b.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${b.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...b.sessionId?{sessionId:b.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${b.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(_,b.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 k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,p);try{this.writeFrame(d)}catch(w){p.timer&&clearTimeout(p.timer),this.pending.delete(a),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.traceFrame("->",e),this.child.stdin.write(Eh(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}traceFrame(e,n){if(!kb)return;let i=n,o;try{let a=JSON.stringify(n);o=a===void 0||a.length<=Mh?n:`${a.slice(0,Mh)}...<truncated, total ${a.length} chars>`}catch{o="<unserializable>"}this.log.info(`rpc ${e}`,{dir:e,method:i.method,id:i.id,frame:o})}dispatch(e){if(this.traceFrame("<-",e),Go(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new k("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:Tb(e.result)}),n.resolve(e.result));return}if(wh(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(mh(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,f=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!f?e.activeToolCalls.add(a):f&&e.activeToolCalls.delete(a)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Bn(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(Bn(e.id,ds(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=_h(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=Ph(this.framework,Cb(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):n}buildExitError(e,n){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(yb).join(`
|
|
106
|
-
`),o=Rh(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:n,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function
|
|
107
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function ev(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]=
|
|
108
|
-
`)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{Ub(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function rv(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=Uh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}ne();var iv=q("hermes-downstream"),Vo=class extends St{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.setConfigOption(e,"model",this.modelId)}catch(n){iv.warn("hermes model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}setConfigOption(e,n,i){return n==="model"?this.setSessionModel({sessionId:e,modelId:i}).then(()=>{}):super.setConfigOption(e,n,i)}};Ze();var jh=3e4,ni=class extends St{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}`}]},jh))}get acpSessionName(){return this.sessionName}async setConfigOption(e,n,i){if(n!=="model")throw new k("CAPABILITY_UNSUPPORTED",`openclaw does not support axis '${n}'`);await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${i}`}]},jh)}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Ct();Ze();ne();Pe();function Wd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}vn();var Vt=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 Jo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;effort;fastMode;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),e.effort&&(this.effort=e.effort),e.fastMode&&(this.fastMode=e.fastMode)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}setEffort(e){this.effort=e}setFastMode(e){this.fastMode=e}getSessionQueue(e){let n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new Vt,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)ri(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 ri(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function ln(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Wt();ne();import{constants as Wh}from"node:fs";import{access as sv,readFile as ov}from"node:fs/promises";import{delimiter as av,dirname as cv,join as Kh}from"node:path";var it=q("framework-detector"),$h={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},dv=[".exe",".cmd",".bat",".ps1"],lr=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??dt,access:e.access??sv,readFile:e.readFile??ov}}async detect(e){let n=$h[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return it.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)]),f={path:i,version:a};return d&&(f.defaultAgent=d),f}async detectAll(){let e=await Promise.all(Object.keys($h).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(av).filter(Boolean),i=this.env.platform==="win32"?["",...dv]:[""];for(let o of n)for(let a of i){let d=Kh(o,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?Wh.F_OK:Wh.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 it.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 it.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=Kh(cv(o),"hermes-acp");return await this.isExecutable(a)?(it.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(it.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 it.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return it.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 it.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 it.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?(it.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}:(it.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return it.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return it.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||it.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){it.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&&(fv(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let o="",a=!1,d,f=u=>{a||(a=!0,d&&clearTimeout(d),i(u))};try{let u=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{u.kill("SIGKILL"),f(null)},15e3),u.stdout?.on("data",x=>{o+=x.toString("utf8")}),u.on("error",()=>f(null)),u.on("close",x=>f({code:x,stdout:o}))}catch{f(null)}})}},lv=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function fv(t){return t.replace(lv,"")}import{homedir as Jh}from"node:os";import{join as Xo}from"node:path";Ct();Wt();vr();Ze();ne();async function Zh(){let t=Xo(Jh(),".openclaw/openclaw.json");return Ye(t)}async function Xh(){return(await Zh())?.gateway?.auth?.token??""}var fr=q("openclaw.config"),uv=[0,5e3,5e3],hv=Je("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),Vh="models.providers.",Zo="agents.defaults.models",xv=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function ii(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 Yo=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Vt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??uv,this.cliTimeoutMs=e.cliTimeoutMs??hv,this.openclawDir=e.openclawDir??Xo(Jh(),".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,fr.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=dt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,f=x=>{d||(d=!0,clearTimeout(u),x())};o.stderr?.on("data",x=>{a+=x.toString("utf8")});let u=setTimeout(()=>{f(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);u.unref(),o.on("error",x=>f(()=>i(x))),o.on("close",x=>f(()=>{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){fr.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",`${Vh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Vh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Zo}[${e}]`,()=>this.runCli(["config","set",Zo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Zo}[${e}]`,`${Zo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await Zh())?.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=Xo(this.openclawDir,"identity","device.json"),i=(await Ye(e))?.deviceId?.trim();if(!i)return fr.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Xo(this.openclawDir,"devices","paired.json"),a=await Ye(o),d=a?.[i];if(!a||!d)return fr.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let f=d.tokens?.operator,u=ii(ii(d.scopes,d.approvedScopes??[]),f?.scopes??[]).filter(v=>v.startsWith("operator.")),x=ii([...xv],u),p=ii(d.scopes,x),w=ii(d.approvedScopes,x),b=f?ii(f.scopes,x):void 0;return p.length!==(d.scopes?.length??0)||w.length!==(d.approvedScopes?.length??0)||f!==void 0&&b?.length!==(f.scopes?.length??0)?(d.scopes=p,d.approvedScopes=w,f&&b&&(f.scopes=b),await ut(o,a,{mode:384}),fr.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(fr.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return fr.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 pv,writeFile as gv}from"node:fs/promises";import{join as mv}from"node:path";var wv=["```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(`
|
|
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 fh(t,e,n,i){let o=await ih(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 Bd(pe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,p=pe(n,f),x=pe(e,f,"SKILL.md"),g=await Ho(x,{encoding:"utf8"}).catch(()=>null);if(g===null)continue;let v=uh(g);a.push({relPath:p,skill:{skillId:lh(t,p),skillName:v.name||f,...v.description?{description:v.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function hh(t,e,n,i){let{base:o,subdir:a}=Xr(n,t,e,i);return fh(t,pe(o,a),a,!1)}async function ph(t,e){let n=[],i=new Set;for(let o of dh(e)){let a=await fh(t,o,o,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var Ub=3e4,Hb=50*1024*1024,rh=10*1024*1024,Yr=3e4;async function qo(t){let{agentId:e,workspace:n,framework:i,skill:o,paths:a}=t;if(!o.skillName)throw new k("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 k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let f=ch(o.skillName),{base:p,subdir:x}=Xr(i,e,n,a),g=pe(x,f),v=pe(p,g);if(await Od(v,{recursive:!0}),d){let E=Buffer.from(o.content,"utf8");cs(E.length),await Md(pe(v,"SKILL.md"),E,"utf8")}else{let E=await jb(o.downloadUrl);Kb(E)?await Zb(E,v):$b(E)?await Vb(E,v):await Md(pe(v,"SKILL.md"),E.toString("utf8"),"utf8")}let w={skillId:o.skillId,skillName:o.skillName,relPath:g,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 Y.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:g,source:d?"content":"downloadUrl"}),w}function jo(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 Gb(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 qb(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 xh(t,e){let n=await ye(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Jt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await Oe(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((g,v)=>[g.skillId,v])),u=a.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Oe(n,e),{status:"noop",count:0};let f=0,p=0,{base:x}=Xr(n.framework,t,n.workspace,e);Y.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:x,builtinCount:u.length,builtinRelPaths:u.map(g=>g.relPath)});for(let g of u)try{let v=pe(x,g.relPath);Y.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:g.skillId,relPath:g.relPath,rmTarget:v}),await Ld(v,{recursive:!0,force:!0});let w=await qo({agentId:t,workspace:n.workspace,framework:n.framework,skill:qb(g),...e?{paths:e}:{}});jo(a,d,w),f+=1}catch(v){p+=1,Y.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(v)})}return n.skills=a,p===0&&(n.skillsRefreshedForVersion=i),await Oe(n,e),Y.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:p}),{status:"refreshed",count:f}}async function jb(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);cs(e);let n=Wb(t);return cs(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Ho(e);return cs(n.length),n}if(rs(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),Ub);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return cs(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function cs(t){if(t>Hb)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Wb(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let n=!!e[2],i=e[3]??"";return n?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function Kb(t){return t.length>=2&&t[0]===31&&t[1]===139}function $b(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 Fd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Vb(t,e){let n,i;try{n=new Ud.default(t),i=n.getEntries()}catch(d){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||Fd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(p=>p===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=Jb(i),a=Nd(e);for(let d of i){if(Fd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=Nd(e,u),p=zd(a,f);if(p.startsWith("..")||p==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Od(f,{recursive:!0});continue}await Od(kb(f),{recursive:!0});let x;try{x=d.getData()}catch(g){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${g.message}`,{cause:g})}await Md(f,x)}}function Jb(t){let e;for(let n of t){let i=n.entryName;if(!i||Fd(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 Zb(t,e){await Yb(t);let n=p0({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Yr}ms)`))},Yr);try{await ah(oh.from(t),n)}catch(a){throw a instanceof k?a:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Yr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function Yb(t){let e=[],n=$r({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(p=>p==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Yr}ms)`))},Yr);try{await ah(oh.from(t),n)}catch(a){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Yr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Xb=5e3;async function Qb(t,e,n,i){return gh(t,e,n,i,{count:0})}async function gh(t,e,n,i,o){if(i<=0)return[];let a;try{a=await ih(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if(Rb.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=pe(e,u.name),p=Cb(pe(n,u.name)),x=null;try{x=await Dd(f)}catch{continue}if(x.isSymbolicLink())continue;o.count++;let g={name:u.name,path:mh(zd(t,f)),isDir:x.isDirectory(),size:x.size,modifiedAt:Math.floor(x.mtimeMs)};x.isDirectory()&&i>1&&(g.children=await gh(t,f,p,i-1,o)),d.push(g)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function eE(t){return!t||t<=0?Tb:Math.min(t,Pb)}function tE(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function mh(t){return t.split(sh).join("/")}re();var zn=H("agent-health-reporter"),nE=1e4,rE=3,ds=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??nE,this.livenessFailureThreshold=e.livenessFailureThreshold??rE}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()}),zn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),zn.info("heartbeat stopped"))}async tick(){if(this.inFlight){zn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,zn.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=iE(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:Jt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,zn.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=o?.authFailures;if(a&&a.length>0&&(zn.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){zn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){zn.warn("onTickEnd hook failed",{err:String(n)})}}};function iE(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}an();import{copyFile as bv,cp as Ev,mkdir as na,readFile as vv,rm as Sv,stat as Vd,writeFile as Iv}from"node:fs/promises";import{homedir as np}from"node:os";import{basename as Av,join as gn}from"node:path";In();import{existsSync as xE}from"node:fs";import{release as gE}from"node:os";import{basename as mE,isAbsolute as wE}from"node:path";function ls(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Qr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function ei(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Un(t,e){return{jsonrpc:"2.0",id:t,error:e}}Qe();var Wo=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)}},ee={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 wh(t){return"method"in t&&"id"in t&&t.id!==void 0}function _h(t){return"method"in t&&!("id"in t)}function Ko(t){return!("method"in t)&&"id"in t}var sE={AGENT_NOT_FOUND:ee.AGENT_NOT_FOUND,AGENT_BUSY:ee.AGENT_BUSY,AGENT_DISCONNECTED:ee.AGENT_DISCONNECTED,AGENT_TIMEOUT:ee.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:ee.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:ee.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:ee.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:ee.INTERNAL_ERROR,BRIDGE_INTERNAL:ee.INTERNAL_ERROR,IPC_AUTH_FAILED:ee.INTERNAL_ERROR,IPC_BAD_REQUEST:ee.INVALID_REQUEST,METHOD_NOT_FOUND:ee.METHOD_NOT_FOUND,CAPABILITY_UNSUPPORTED:ee.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:ee.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:ee.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:ee.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:ee.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:ee.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:ee.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:ee.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:ee.FILE_TOO_LARGE,UNSUPPORTED_MIME:ee.UNSUPPORTED_MIME,UPLOAD_FAILED:ee.UPLOAD_FAILED,UPSTREAM_NOT_READY:ee.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:ee.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:ee.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:ee.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:ee.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:ee.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:ee.SKILL_ZIP_TOO_LARGE};function oE(t){if(t!=null)return t instanceof Error?{name:t.name,message:us(t.message)}:typeof t=="string"?us(t):typeof t=="object"?cE(t):t}var aE=[[/\/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 us(t){let e=t;for(let[n,i]of aE)e=e.replace(n,i);return e}function cE(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=us(i):e[n]=i;return e}function fs(t){if(t instanceof k){let e=oE(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:sE[t.code]??ee.INTERNAL_ERROR,message:us(t.message),data:n}}return{code:ee.INTERNAL_ERROR,message:us(t instanceof Error?t.message:String(t))}}function yh(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 k(n,o,{retriable:e?.retriable??!1,cause:a})}function Eh(t){return`${JSON.stringify(t)}
|
|
103
|
+
`}var bh=10*1024*1024,$o=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>bh){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${bh} 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 Sh={"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"},xP=Object.fromEntries(Object.entries(Sh).map(([t,e])=>[e,t])),dE={"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:[]},ti=class{seq=0;next(e,n){this.seq+=1;let i=Sh[e]??lE(e),o=dE[i]??[],a=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>vh(n?.[f]??"")),u=uE(d).join(":");u&&a.push(u)}else n&&Object.values(n).some(d=>d)&&a.push(Object.values(n).filter(Boolean).map(d=>vh(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function lE(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function vh(t){return t.replace(/[:_\s]+/g,"-")}function uE(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Vt();Ar();Qe();re();De();import{execFileSync as fE,spawnSync as hE}from"node:child_process";function hs(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function ps(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),hE("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var Hd=new Set;function Ih(t){typeof t=="number"&&t>0&&Hd.add(t)}function Ah(t){typeof t=="number"&&Hd.delete(t)}function kh(){for(let t of Hd)ps(t,"SIGKILL")}var ni="coze-bridge-daemon";function Ch(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return fE("pgrep",["-U",String(o),"-f",ni],{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??ps,i=e?.isAliveFn??hs,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 pE=[{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 Ph(t,e){if(!e)return null;for(let n of pE)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 Ph(t,e)}function Dh(t,e){return Ph(t,e)}function ri(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 Oh(t,e,n){let o=n-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let p=t.suspendedMs+o,x=n-t.startedAt-p;return{action:"suspend",suspendedDeltaMs:o,rearmMs:ri(x,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:ri(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:ri(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:ri(a,!1,e)}}var Lh=Xe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",6e4),_E=200,yE=40,bE=Xe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),EE=Xe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),vE=Xe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),SE=Xe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),IE=Xe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),AE=Xe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Mh=500,kE=process.env.COZE_BRIDGE_TRACE_RPC==="1",Nh=Xe("COZE_BRIDGE_TRACE_RPC_MAX",2e3);function CE(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Mh?t:`${e.slice(0,Mh)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function TE(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 Fh(t){try{return xE(t)}catch{return}}function PE(t,e){return{platform:process.platform,osRelease:gE(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:wE(e.command)?Fh(e.command):void 0,cwd:e.cwd,cwdExists:Fh(e.cwd),envKeys:e.envKeys}}function RE(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${mE(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Ct=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new $o({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new ti;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=Fo(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=ht(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,Ih(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>_E&&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,Ah(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=PE(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 k("AGENT_SPAWN_FAILED",RE(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()));ps(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||ps(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:IE,phase2GateMs:bE,livenessWindowMs:EE,absoluteMaxMs:vE,approvalMaxMs:AE,suspendThresholdMs:SE,...n};return this.call("session/prompt",e,Lh,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Qr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}configIdFor(e){return e==="model"?"model":null}sendSetConfigOption(e,n,i){return this.call("session/set_config_option",{sessionId:e,configId:n,value:i}).then(()=>{})}setConfigOption(e,n,i){let o=this.configIdFor(n);return o===null?Promise.reject(new k("CAPABILITY_UNSUPPORTED",`${this.framework} does not support axis '${n}'`)):this.sendSetConfigOption(e,o,i)}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(ei(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(Un(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=Lh,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=ls(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,p)=>{let x={resolve:f,reject:p,timer:null,method:e,promptTimeout:null};if(o){let g=this.now(),v={cfg:o,startedAt:g,lastActivityAt:g,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:g,expectedIntervalMs:ri(0,!1,o),sessionId:u};x.promptTimeout=v;let w=()=>{let E={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},S=this.now(),A=Oh(E,v.cfg,S),C=P=>{v.armedAt=S,v.expectedIntervalMs=P,x.timer=setTimeout(w,P)};if(A.action==="suspend"){v.suspendedMs+=A.suspendedDeltaMs,v.lastActivityAt=S,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),C(A.rearmMs);return}if(A.action==="continue"){C(A.rearmMs);return}this.pending.delete(a),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:A.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),p(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),p(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};x.timer=setTimeout(w,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(x.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),p(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,x);try{this.writeFrame(d)}catch(g){x.timer&&clearTimeout(x.timer),this.pending.delete(a),p(g)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.traceFrame("->",e),this.child.stdin.write(Eh(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}traceFrame(e,n){if(!kE)return;let i=n,o;try{let a=JSON.stringify(n);o=a===void 0||a.length<=Nh?n:`${a.slice(0,Nh)}...<truncated, total ${a.length} chars>`}catch{o="<unserializable>"}this.log.info(`rpc ${e}`,{dir:e,method:i.method,id:i.id,frame:o})}dispatch(e){if(this.traceFrame("<-",e),Ko(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new k("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:CE(e.result)}),n.resolve(e.result));return}if(_h(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(wh(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(Un(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(Un(e.id,fs(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=yh(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=Dh(this.framework,TE(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):n}buildExitError(e,n){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(yE).join(`
|
|
106
|
+
`),o=Rh(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:n,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function DE(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 Vo=class extends Ct{framework="claude-code";constructor(e){let{command:n,args:i}=Ii("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 DE(e)}configIdFor(e){return e==="model"?"model":e==="effort"?"effort":null}};In();import{spawn as OE}from"node:child_process";import{closeSync as LE,existsSync as jd,mkdirSync as ME,mkdtempSync as NE,openSync as FE,readFileSync as jh,readSync as BE,readdirSync as zE,rmSync as UE,statSync as HE}from"node:fs";import{homedir as GE,tmpdir as qE}from"node:os";import{join as ii}from"node:path";var Bh=["default","acceptEdits","plan","auto","bypassPermissions"],zh=["read-only","auto","full-access"];var Uh=["default","accept_edits","dont_ask"];function Zt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return Bh.includes(e);case"codex":return zh.includes(e);case"hermes":return Uh.includes(e);case"openclaw":return!1}}function Jo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Hh(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function Gd(t){switch(t){case"claude-code":return Bh.join("/");case"codex":return zh.join("/");case"hermes":return Uh.join("/");case"openclaw":return""}}De();var Wd=9e4,jE=64*1024,WE=100;function KE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Wd:Math.max(1,Math.floor(e*1e3))}function $E(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Wd:Math.max(1,Math.floor(e))}function VE(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 Gh(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:Wd};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=VE(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?KE(e.timeout):$E(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function qd(t){if(Array.isArray(t))return t.flatMap(i=>qd(i));if(!t||typeof t!="object"){let i=Gh(t);return i?[i]:[]}let e=t;if(e.hooks)return qd(e.hooks);let n=Gh(e);return n?[n]:[]}function JE(t){let e=ii(t,"hooks.json");if(!jd(e))return[];let n=JSON.parse(jh(e,"utf8")),o=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return qd(o.Stop??o.stop)}function ZE(t,e){let n=ii(t,"sessions");if(!jd(n))return;let i=[],o=a=>{let d;try{d=zE(a,{withFileTypes:!0})}catch{return}for(let u of d){let f=ii(a,u.name);if(u.isDirectory())o(f);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:f,mtimeMs:HE(f).mtimeMs})}catch{}}};o(n),i.sort((a,d)=>d.mtimeMs-a.mtimeMs);for(let a of i.slice(0,WE))if(YE(a.path,e))return a.path}function YE(t,e){let n;try{n=FE(t,"r");let i=Buffer.alloc(jE),o=BE(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{LE(n)}catch{}}}function XE(t){return ur(t??Z().agentEnvFile)}function QE(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 ev(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]=QE(o.slice(a+1)))}return e}function tv(t){let e=ii(t,"cozeloop.env");return jd(e)?ev(jh(e,"utf8")):{}}function qh(t){let e=t?.trim();return e||void 0}function nv(t){let e=XE(t.agentEnvFile),n=qh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=qh(t.env?.HOME??e.HOME??process.env.HOME)??GE();return ii(i,".codex")}var Zo=class extends Ct{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;fastMode;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:a}=Ii("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??NE(ii(qE(),"coze-bridge-codex-home-")):nv(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&ME(d,{recursive:!0});let f=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,p={command:o,args:a,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...f?{env:f}:{}};super(p),this.authMethodId=e.authMethodId,this.codexHomeDir=d,this.cleanupCodexHomeDir=u,this.fastMode=e.fastMode}configIdFor(e){return e==="model"?"model":e==="effort"?"reasoning_effort":e==="fastMode"?"fast-mode":null}async afterSessionEstablished(e){if(this.fastMode)try{await this.setConfigOption(e,"fastMode",this.fastMode)}catch(n){this.log.warn("codex fast-mode post-establish failed (ignored)",{sessionId:e,err:String(n)})}}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=Zt("codex",e.modeId)?Jo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(rv(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=JE(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let o=ZE(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?tv(a):{},u=Fo(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=OE(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),p="",x=setTimeout(()=>{f.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);f.stderr?.setEncoding("utf8"),f.stderr?.on("data",g=>{p+=g,p.length>4e3&&(p=p.slice(-4e3))}),f.on("error",g=>{clearTimeout(x),o(g)}),f.on("close",(g,v)=>{if(clearTimeout(x),g===0){i();return}o(new Error(`hook exited code=${g} signal=${v} stderr=${p.slice(-1e3)}`))}),f.stdin.end(`${n}
|
|
108
|
+
`)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{UE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function rv(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=Hh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}re();var iv=H("hermes-downstream"),Yo=class extends Ct{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.setConfigOption(e,"model",this.modelId)}catch(n){iv.warn("hermes model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}setConfigOption(e,n,i){return n==="model"?this.setSessionModel({sessionId:e,modelId:i}).then(()=>{}):super.setConfigOption(e,n,i)}};Qe();var Wh=3e4,si=class extends Ct{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}`}]},Wh))}get acpSessionName(){return this.sessionName}async setConfigOption(e,n,i){if(n!=="model")throw new k("CAPABILITY_UNSUPPORTED",`openclaw does not support axis '${n}'`);await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${i}`}]},Wh)}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Dt();Qe();re();De();function Kd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}In();var Yt=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 Xo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;effort;fastMode;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),e.effort&&(this.effort=e.effort),e.fastMode&&(this.fastMode=e.fastMode)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}setEffort(e){this.effort=e}setFastMode(e){this.fastMode=e}getSessionQueue(e){let n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new Yt,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)oi(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 oi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function xn(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Vt();re();import{constants as Kh}from"node:fs";import{access as sv,readFile as ov}from"node:fs/promises";import{delimiter as av,dirname as cv,join as $h}from"node:path";var ct=H("framework-detector"),Vh={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},dv=[".exe",".cmd",".bat",".ps1"],pr=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??ht,access:e.access??sv,readFile:e.readFile??ov}}async detect(e){let n=Vh[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return ct.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(Vh).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(av).filter(Boolean),i=this.env.platform==="win32"?["",...dv]:[""];for(let o of n)for(let a of i){let d=$h(o,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?Kh.F_OK:Kh.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 ct.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 ct.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=$h(cv(o),"hermes-acp");return await this.isExecutable(a)?(ct.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(ct.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 ct.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return ct.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 ct.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 ct.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?(ct.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}:(ct.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return ct.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 ct.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||ct.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){ct.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&&(uv(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",p=>{o+=p.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",p=>u({code:p,stdout:o}))}catch{u(null)}})}},lv=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function uv(t){return t.replace(lv,"")}import{homedir as Zh}from"node:os";import{join as ea}from"node:path";Dt();Vt();Ar();Qe();re();async function Yh(){let t=ea(Zh(),".openclaw/openclaw.json");return rt(t)}async function Xh(){return(await Yh())?.gateway?.auth?.token??""}var xr=H("openclaw.config"),fv=[0,5e3,5e3],hv=Xe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),Jh="models.providers.",Qo="agents.defaults.models",pv=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function ai(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 ta=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Yt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??fv,this.cliTimeoutMs=e.cliTimeoutMs??hv,this.openclawDir=e.openclawDir??ea(Zh(),".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,xr.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=ht(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=p=>{d||(d=!0,clearTimeout(f),p())};o.stderr?.on("data",p=>{a+=p.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",p=>u(()=>i(p))),o.on("close",p=>u(()=>{p===0?n():i(new Error(`exit ${p}: ${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){xr.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",`${Jh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Jh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Qo}[${e}]`,()=>this.runCli(["config","set",Qo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Qo}[${e}]`,`${Qo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await Yh())?.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=ea(this.openclawDir,"identity","device.json"),i=(await rt(e))?.deviceId?.trim();if(!i)return xr.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=ea(this.openclawDir,"devices","paired.json"),a=await rt(o),d=a?.[i];if(!a||!d)return xr.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,f=ai(ai(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(E=>E.startsWith("operator.")),p=ai([...pv],f),x=ai(d.scopes,p),g=ai(d.approvedScopes,p),v=u?ai(u.scopes,p):void 0;return x.length!==(d.scopes?.length??0)||g.length!==(d.approvedScopes?.length??0)||u!==void 0&&v?.length!==(u.scopes?.length??0)?(d.scopes=x,d.approvedScopes=g,u&&v&&(u.scopes=v),await gt(o,a,{mode:384}),xr.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:p}),!0):(xr.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return xr.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 xv,writeFile as gv}from"node:fs/promises";import{join as mv}from"node:path";var wv=["```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
109
|
`),_v=["# 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 yv(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
|
|
115
|
-
`);await Iv(d,u,{mode:384})}else await Ev(a,d);re.info("migrated legacy Codex state",{agentId:t,name:o})}catch(f){f.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(f)})}}}}var Vd="acceptEdits",nx="full-access",rx="read-only";function Rv(t){return{INITIAL_AGENT_MODE:Ko(t)}}var Pv=(t,e,n,i,o,a,d,f,u,x,p,w)=>{switch(t){case"claude-code":{let b={...o?{...B0(o),...H0(o,d,f,w)}:{},...u??{},IS_SANDBOX:"1"};return new Wo({cwd:n,env:b,agentId:i})}case"codex":{let b=nx;x!==void 0&&($t("codex",x)?b=x:re.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _=!!o?.modelToken,v={...o?{...U0(o),...z0(o,d,f,w)}:{},...Rv(b),..._?{NO_BROWSER:"1"}:{},...u??{},..._?{COZELAB_ONBOARD_CLOUD:"true"}:{}};return new $o({cwd:n,agentId:i,...Object.keys(v).length>0?{env:v}:{},...o?.fastMode?{fastMode:o.fastMode}:{},..._?{authMethodId:"api-key",isolateCodexHome:!0,...p?{codexHomeDir:p}:{}}:{}})}case"openclaw":return new ni({command:e,cwd:n,agentId:i,...a?{sessionName:Wd(a)}:{}});case"hermes":return new Vo({command:e,cwd:n,agentId:i,...u&&Object.keys(u).length>0?{env:{...u}}:{},...o?.model&&!bt(o.model)?{modelId:o.model}:{}})}};function Kd(t){return t==="claude-code"||t==="codex"}var Dv={path:"",version:"cloud-deployed"},Qh="openclaw_gateway_unavailable",Ov="openclaw_default_agent_missing";function ex(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 Lv={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Mv=6e4,ea=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??Pv,this.createTimeoutMs=e.createTimeoutMs??Mv,this.detectorFactory=e.detectorFactory??(()=>new lr),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Yo({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??fn(tx(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{re.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=fn(e,".env");if(await $d(n).then(a=>a.isFile()).catch(()=>!1)){re.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=ts({...process.env,...ar(this.paths.agentEnvFile)});await _t(n,o,{mode:384}),re.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),re.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await we(e.agentId,this.paths).catch(()=>null),o=sr(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 k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")re.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(T=>re.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&a.deployType!=="cloud")re.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(T=>re.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){re.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let T=await we(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Le(T,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){re.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let T=await we(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Le(T,this.paths))}return re.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 k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${R}`)}let f=Oe(e.agentId,this.paths),u=o?"cloud":"local",x=e.framework==="openclaw"&&u==="local",p;x&&!n?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),b=e.workspace??w??f.workspace,_=new AbortController,v=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&Kd(e.framework)&&await kr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await Qo(f.root,{recursive:!0}),await Qo(b,{recursive:!0}),await Qo(f.logs,{recursive:!0}),T(),x||await Tr(b,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(u==="cloud"?await dc(b,"cloud"):await dc(b,"local",Vd)),T();let R=i,E=F0({model:e.model??R?.model}),P=p0(e._meta)??R?.accountId,D=e.patToken??R?.patToken,U=u==="cloud"?e.modelInfo??R?.modelInfo:void 0;if(I=new Jo({agentId:e.agentId,framework:e.framework,workspace:b,model:E.model??Mt,deployType:u,...P?{accountId:P}:{},...D?{patToken:D}:{},...U?{modelInfo:U}:{}}),I.status="ok",R?.sessions){let J=e.framework==="hermes"||u==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Y,oe]of Object.entries(R.sessions)){let le={acpSessionId:oe.acpSessionId,modelToken:oe.modelToken,tokenGeneratedAt:oe.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};J?oe.permissionMode===void 0?(le.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",re.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Y,framework:e.framework,fallback:le.permissionMode})):$t(e.framework,oe.permissionMode)?le.permissionMode=oe.permissionMode:re.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Y,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&re.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Y,framework:e.framework,deployType:u}),oe.cozeGroupId&&(le.cozeGroupId=oe.cozeGroupId),oe.tokenGroupId&&(le.tokenGroupId=oe.tokenGroupId),oe.requestScene&&(le.requestScene=oe.requestScene),I.sessions.set(Y,le)}let ie=Object.keys(R.sessions).length;ie>0&&re.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ie})}this.registry.register(I),A=!0,n?.revive||this.registry.warmupModelList?.(I);let N={agentId:e.agentId,framework:e.framework,workspace:b,cozeIdentity:e.cozeIdentity,createdAt:R?.createdAt??Date.now(),sessions:R?.sessions??{},model:E.model};if(u==="cloud"&&(N.deployType="cloud"),P&&(N.accountId=P),D&&(N.patToken=D),U&&(N.modelInfo=U),R?.skills&&(N.skills=R.skills),R?.agentName&&(N.agentName=R.agentName),R?.description&&(N.description=R.description),N.skillsRefreshedForVersion=R?.skillsRefreshedForVersion??Kt,e.framework==="openclaw"&&u==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,b)):re.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await Yh(b)&&re.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:b})}catch(J){re.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:b,err:String(J)})}}let K=e.initialSkills??[];if(K.length>0){let J=[...N.skills??[]],ie=new Map(J.map((le,Ee)=>[le.skillId,Ee])),Y=await Promise.allSettled(K.map(le=>Uo({agentId:e.agentId,workspace:b,framework:e.framework,skill:le,paths:this.paths}))),oe=0;for(let[le,Ee]of Y.entries()){let qe=K[le];qe&&(Ee.status==="fulfilled"?(Ho(J,ie,Ee.value),oe++):re.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:qe.skillId,skillName:qe.skillName,err:String(Ee.reason)}))}oe>0&&(N.skills=J,re.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:K.length}))}return await Le(N,this.paths),re.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:u}),{ok:!0,agentId:e.agentId,workspace:b,framework:e.framework}}catch(T){throw re.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),re.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:f.root,revive:n?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await Sv(f.root,{recursive:!0,force:!0}).catch(R=>re.warn("rm agent dir failed (ignored)",{err:String(R)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,n,i,o,a,d){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&Kd(e.framework))u=Dv;else throw e.framework==="hermes"?new k("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Kd(e.framework)&&!Fs(e.framework)&&(re.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await kr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:N0({model:e.model,effort:e.effort,fastMode:e.fastMode}),p;if(e.framework==="openclaw")p=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:a,requestScene:d,command:u.path});else if(e.framework==="hermes"){let w={...this.buildBinShimPathEnv()};x?.modelToken&&(await $0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:o,mockScenario:a}),w.HERMES_HOME=dr(e.agentId,this.paths)),p=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,a,w)}else{let w=e.sessions.get(i),b=ln(e)?w?.permissionMode??nx:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await Cv(e.agentId,this.paths),p=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,a,this.buildBinShimPathEnv(),b,e.framework==="codex"&&e.deployType==="cloud"?fn(Oe(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await p.start(),await p.initialize(Lv),p}catch(w){let b=p instanceof St?p.getStderrTail():[];throw b.length>0&&re.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof k?w.code:"unknown",recentStderr:b}),await p.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,w)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let o=await this.detectorFactory().probeOpenclawGateway(n);if(!o.reachable)return new k("AGENT_ENV_NOT_READY",ex(o),{cause:{reason:Qh}})}catch(o){re.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};re.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 re.info("openclaw lazy re-detect success",{agentId:n.defaultAgent.id,workspace:n.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=n,{id:n.defaultAgent.id,workspace:n.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:Ov}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new k("AGENT_ENV_NOT_READY",ex(n),{cause:{reason:Qh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,requestScene:f,command:u}=e,x=Wd(o);if(n.deployType==="local"){let b=await this.ensureOpenclawDefaultAgent(),_=i&&!bt(i.model)?i.model:void 0;return new ni({command:u,cwd:b.workspace,agentId:b.id,sessionName:x,..._?{slashModelOnStart:_}:{}})}let p=await Xh();try{let b=this.getOpenclawConfig();await b.ensureAcpDeviceScopes()&&await b.restartGateway()}catch(b){re.warn("acp device scope ensure failed (ignored)",{err:String(b)})}let w;if(i?.modelToken){let b=Ad(o),_=kd(i),v=`${b}/${_}`,I=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:f});if(this.ensuredProviders.get(v)!==I){let A=this.getOpenclawConfig(),T=await A.getAllowlistModelsForProvider(b),R=q0(i,a,d,T,f);R&&(await A.ensureProvider(b,R),await A.addModelToAllowlist(v),this.ensuredProviders.set(v,I))}w=v}else i&&!bt(i.model)&&(w=i.model);return new ni({command:u,cwd:n.workspace,agentId:n.agentId,sessionName:x,...p?{gatewayToken:p}:{},...w?{slashModelOnStart:w}:{}})}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=Ad(a),f=`${d}/${o}`,u=!0;try{await i.removeProvider(d)}catch(x){u=!1,re.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(f)}catch(x){u=!1,re.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:f,err:String(x)})}u&&this.ensuredProviders.delete(f)}}};import{randomUUID as cx}from"node:crypto";import{promises as qv}from"node:fs";import{basename as dx}from"node:path";Ze();ne();import{promises as Nv}from"node:fs";import{basename as Fv}from"node:path";var ix=q("file-upload"),Bv="/api/coze_claw/file/agent_upload",zv=6e4;async function sx(t,e={}){let i=`${Wr(Kr(e.handshakeBase))}${Bv}`,o=e.timeoutMs??zv,a=await Nv.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 f={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Nn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},u=new AbortController,x=setTimeout(()=>u.abort(),o);ix.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:f,body:d,signal:u.signal}),w=p.headers.get("x-tt-logid")??"";if(!p.ok){let v=await p.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${w}: ${v.slice(0,200)}`)}let b=await p.json();if(b.code!==void 0&&b.code!==0)throw new k("UPLOAD_FAILED",`upload code=${b.code} msg=${b.msg??"-"} logid=${w}`);let _=b.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(b).slice(0,200)}`);return ix.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(p){throw p instanceof k?p:p.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Fv(t.path)}`):new k("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}Ze();ne();import{extname as Uv}from"node:path";var Hv={".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 ox(t){let e=Uv(t).toLowerCase();return Hv[e]??"application/octet-stream"}Pe();var ta=q("agent-send"),ax=50*1024*1024;function lx(t,e,n){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(n);if(!o)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function fx(t,e,n,i,o,a){let f;for(let u=0;u<=2;u++)try{await t.core.sendAgentFileUpdate(e,n,i,o);return}catch(x){f=x,u<2&&(ta.warn("sendAgentFileUpdate failed, retrying",{attempt:u+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new k("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(f)}`,{cause:f})}async function ux(t,e){let{session:n,runtime:i}=lx(e.core,t.agentId,t.sessionId);if(!await vi(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await qv.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>ax)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${ax}`);let a=await ox(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??dx(t.path),f;try{f=await sx({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 ta.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:a,code:x instanceof k?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let u={sessionUpdate:"agent_file",messageId:cx(),content:{type:t.kind==="image"?"image":"resource",uri:f.uri,mimeType:a,name:d,sizeBytes:o.size,...f.fileId!==void 0?{fileId:f.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await fx(e,n,i,t.sessionId,u,"agent file uploaded to cloud but sendAgentFileUpdate failed"),ta.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:a,uri:f.uri}),{ok:!0,uri:f.uri,bytes:o.size,mimeType:a,...f.fileId!==void 0?{fileId:f.fileId}:{}}}async function hx(t,e){let{session:n,runtime:i}=lx(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new k("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??dx(t.path),a={sessionUpdate:"group_file",messageId:cx(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await fx(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),ta.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 xx(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,f=i[a]??0;if(d<f)return!0;if(d>f)return!1}return!1}Wt();ne();vn();var Jt=q("coze-cli-installer"),px="@coze/cli@latest",Gv="coze",gx="0.1.8",jv=5e3,Wv=5e3,Kv=9e4,mx=1e4,us=null,na=!1;async function Zd(t,e={}){if(na)return;if(us)return us;let n=e.exec??Oo;return us=(async()=>{try{let i=await $v(Gv,n),o=!1;if(i){let d=await Vv(n);if(d===void 0)Jt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(xx(d,gx))Jt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:gx}),o=!0;else{Jt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),na=!0;return}}let a=o?"upgrade-only":"full";Jt.info("coze-cli install start",{package:px,mode:a});try{await n("npm",["i","-g","--prefer-online",px],{timeout:Kv,maxBuffer:10*1024*1024}),Jt.info("coze-cli install ok")}catch(d){Jt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){na=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:mx}),Jt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Jt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:mx}),Jt.info("coze auth login ok")}catch(d){Jt.warn("coze auth login failed",{err:String(d)});return}na=!0}finally{us=null}})(),us}async function $v(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:jv});return ac(i)}catch{return}}async function Vv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:Wv});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Ct();var ra=class{cacheFilePath;memory=new Map;runtimeCurrent=new Map;writeQueue=new Vt;constructor(e){this.cacheFilePath=e}async loadFromDisk(){if(!this.cacheFilePath)return;let e=await Ye(this.cacheFilePath);if(e)for(let[n,i]of Object.entries(e))i&&this.memory.set(n,i)}get(e){return this.memory.get(e)}update(e,n){return this.writeQueue.enqueue(async()=>{let i=Q0(n),o=this.memory.get(e);if(o&&o.hash===i){if(o.cachedAt=Date.now(),n.defaultModelId&&o.defaultModelId!==n.defaultModelId){if(o.defaultModelId=n.defaultModelId,this.cacheFilePath){let f=await Ye(this.cacheFilePath)??{};f[e]=o,await ut(this.cacheFilePath,f)}return!0}return!1}let a={cachedAt:Date.now(),hash:i,models:n.models,...n.defaultModelId?{defaultModelId:n.defaultModelId}:{},...n.effortLevels?{effortLevels:n.effortLevels}:{},...n.fastModes?{fastModes:n.fastModes}:{}};if(this.memory.set(e,a),!this.cacheFilePath)return!0;let d=await Ye(this.cacheFilePath)??{};return d[e]=a,await ut(this.cacheFilePath,d),!0})}setRuntimeCurrent(e,n){let i=this.runtimeCurrent.get(e)??{};this.runtimeCurrent.set(e,{...i,...n.model!==void 0?{model:n.model}:{},...n.effort!==void 0?{effort:n.effort}:{},...n.fastMode!==void 0?{fastMode:n.fastMode}:{}})}getRuntimeCurrent(e){return this.runtimeCurrent.get(e)}};tn();Ct();Pe();var Jv=10*6e4;function _x(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Jv:e}function ia(t){return Ye(t??Z().configFile)}function hs(t,e){return ut(e??Z().configFile,t)}import{randomBytes as pS}from"node:crypto";vr();Ze();ne();import{createReadStream as Zv}from"node:fs";import{mkdir as Xv,readFile as Yv,realpath as Qv,stat as eS,writeFile as tS}from"node:fs/promises";import{basename as nS,dirname as Xd,isAbsolute as rS,join as iS,relative as sS,resolve as yx,sep as oS}from"node:path";import{createInterface as aS}from"node:readline";var bx=q("fs-rpc"),xs=Je("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function vx(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>xs)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${xs} bytes`);let i=await Ix(t.path,e);return await Xv(Xd(i),{recursive:!0}),await tS(i,t.content,"utf8"),bx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Sx(t,e){let n=await Ix(t.path,e),i=await eS(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>xs&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${xs} bytes`);let a;if(o&&i.size>xs)a=await cS(n,t.line??1,t.limit);else{let d=await Yv(n,"utf8");if(o){let f=d.split(`
|
|
116
|
-
`),
|
|
117
|
-
`)}else a=d}return
|
|
118
|
-
`)}async function Ix(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([Ex(yx(e)),Ex(yx(t))]),o=sS(n,i);if(dS(o,oS,rS(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function dS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Ex(t){let e=[],n=t;for(;n!==Xd(n);)try{let i=await Qv(n);return e.length?iS(i,...e.reverse()):i}catch{e.push(nS(n)),n=Xd(n)}return t}ne();var Ax=q("prompt-multimodal"),kx=10*1024*1024,lS=15e3,fS=6;async function Tx(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 uS(d))}}let o=Array.from({length:Math.min(fS,t.length)},()=>i());return await Promise.all(o),e}function Cx(t){return t.some(e=>e.type==="image")}async function uS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!es(e.uri))return t;try{let{buf:n,contentType:i}=await xS(e.uri),o=e.mimeType||hS(i)||"application/octet-stream";return Ax.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 Ax.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function hS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function xS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),lS);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>kx)throw new Error(`image too large: ${o.byteLength} bytes (max ${kx})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}tn();Ze();ne();var W=q("core"),gS=3e4,mS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,wS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",_S="\u5BA1\u6279\u5DF2\u8D85\u65F6",yS=3e4,ES="__model_warmup__",sa=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Yr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;modelListCache;openclawModelLister;modelListWarmupInFlight=new Set;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=_x(e.bridgeConfig),this.modelListCache=e.modelListCache,this.openclawModelLister=e.openclawModelLister}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}),ri(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(Bn(o,{code:Q.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:Q.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:Q.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Go(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&&mS.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,a=g0(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let f=this.requestSceneBySession.get(d);a&&f!==a?(this.requestSceneBySession.set(d,a),W.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&f!==void 0&&(this.requestSceneBySession.delete(d),W.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let f=this.extensions[e.method];if(!f){n!==null?await this.sendError(n,Q.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let u=await f(e,this);n!==null&&await this.upstream.send(Xr(n,u));return}if(e.method.startsWith("session/")){let f=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Xr(n,f));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Xr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,Q.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(f){W.error("handleFrame failed",{method:e.method,err:String(f)}),n!==null&&await this.upstream.send(Bn(n,ds(f)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let 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 u=o.sessions.get(a);if(u?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,p=Po(n._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,u,a,wS,x,p)}}let d=Date.now(),f=!1;try{let u=await o.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return f=!0,u}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:f})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=w0(i);switch(n){case"session/new":{let a=bS();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 k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let f=ln(e)?m0(i._meta):void 0;if(f!==void 0&&!$t(e.framework,f))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${f}; allowed: ${Hd(e.framework)}`);let u=Po(i._meta),x=this.requestSceneBySession.get(d),p=await this.ensureRuntime(e,d,u,x);if(f!==void 0&&p.permissionMode===void 0&&(p.permissionMode=f,await this.persistSessionMapping(e)),p.replySeq=0,await this.ensureDownstream(e,d,p),!p.downstream||!p.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(f!==void 0&&p.permissionMode!==void 0&&p.permissionMode!==f){let _=p.permissionMode;p.permissionMode=f,await this.persistSessionMapping(e);try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:f})}catch(v){throw p.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),v}}let w=i._meta?.cozeTriggerMsgId;if(w?e.activeTriggers.set(p.acpSessionId,w):e.activeTriggers.delete(p.acpSessionId),u?e.activeGroupIds.set(p.acpSessionId,u):e.activeGroupIds.delete(p.acpSessionId),u&&p.cozeGroupId!==u&&(p.cozeGroupId=u,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Cx(a.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let b=await Tx(a.prompt);try{let _=await p.downstream.sessionPrompt({...a,sessionId:p.acpSessionId,prompt:b});return p.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof k&&_.code==="AGENT_APPROVAL_TIMEOUT"){let v=p.pendingPermission;v&&(v.downstream.respondAgentRequest(v.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(v.upstreamId),p.pendingPermission=void 0);let I=p.acpSessionId,A=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,p,d,_S,A,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,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:p.acpSessionId}),_.stop("reload-after-turn").catch(v=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(v)})))}else p.downstream?.isAlive()&&this.armIdleTimer(e,d,p)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let f=e.sessions.get(d);if(e.hasSessionQueue(d)){let u=e.getSessionQueue(d);u.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:u.size}),u.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return f?.downstream?.isAlive()&&f.acpSessionId&&await f.downstream.sessionCancel({sessionId:f.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=o,d=a.sessionId,f=a.modeId,u=Po(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!ln(e))throw e.framework==="openclaw"?new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new k("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!$t(e.framework,f))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(f)}; allowed: ${Hd(e.framework)}`);if(u)return await this.handleGroupSetMode(e,u,f);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===f)return{};let p=x.permissionMode;if(x.permissionMode=f,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:f})}catch(w){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),w}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:f});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[d,f]of e.sessions)f.cozeGroupId===n&&f.permissionMode!==i&&o.push({cloudId:d,runtime:f,oldMode:f.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 f=d.runtime.downstream,u=d.runtime.acpSessionId;f?.isAlive()&&u&&a.push({downstream:f,acpSessionId:u,oldMode:d.oldMode,runtime:d.runtime})}for(let d of a)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(f){for(let u of o)u.runtime.permissionMode=u.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),f}return{}}async ensureRuntime(e,n,i,o){let a=e.sessions.get(n);if(a){let u=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){ri(a);let w=a.downstream;a.downstream=void 0,w&&await w.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=o,(u||x||p)&&await this.persistSessionMapping(e),a}let f={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 ln(e)&&(e.framework==="hermes"?f.permissionMode=e.deployType==="cloud"?j0:W0:f.permissionMode=e.framework==="claude-code"?Vd:rx),e.sessions.set(n,f),await this.persistSessionMapping(e),f}async requestSessionToken(e,n,i){let o={sessionId:n,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let a=await this.sendRequest(rt.GEN_MODEL_TOKEN,o,yS);if(!a?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return a.modelToken}catch(a){throw a instanceof k&&a.code==="MODEL_TOKEN_GEN_FAILED"?a:new k("MODEL_TOKEN_GEN_FAILED",a instanceof Error?a.message:String(a),{cause:a})}}async ensureDownstream(e,n,i){if(ri(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,a=3e4,d=i.spawnFailCount??0,f=i.spawnFailedAt??0;if(d>=o&&Date.now()-f<a)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((a-(Date.now()-f))/1e3)}s`);let u;try{let x=this.requestSceneBySession.get(n);x&&W.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),u=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=u,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{let x=await u.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace});W.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId}),this.piggybackModelList(e,x)}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 p=await u.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,this.piggybackModelList(e,p),await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await u.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,this.piggybackModelList(e,x),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 u.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(u.afterSessionEstablished&&i.acpSessionId&&await u.afterSessionEstablished(i.acpSessionId),ln(e)&&i.acpSessionId&&i.permissionMode)try{await u.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(ri(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 f=e.activeGroupIds.get(n.acpSessionId);f&&(a.cozeGroupId=f)}await this.upstream.send(Zr("session/update",{sessionId:i,update:o,_meta:a}))}async synthesizePromptReply(e,n,i,o,a,d){let f={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return a&&(f.cozeTriggerMsgId=a),d&&(f.cozeGroupId=d),await this.upstream.send(Zr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:f})).catch(u=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(u)})),{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(IS(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"&&ln(e)){let p=d.currentModeId;$t(e.framework,p)&&a.permissionMode!==p?(a.permissionMode=p,this.persistSessionMapping(e).catch(w=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof p=="string"&&!$t(e.framework,p)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:p})}if(d&&typeof d=="object"&&d.sessionUpdate==="config_option_update"){let p=d.configOptions;Array.isArray(p)&&this.piggybackModelList(e,{configOptions:p})}let f={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},u=e.activeTriggers.get(i);u&&(f.cozeTriggerMsgId=u);let x=e.activeGroupIds.get(i);x&&(f.cozeGroupId=x),this.upstream.send(Zr("session/update",{...n,sessionId:o,_meta:f})).catch(p=>W.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}piggybackModelList(e,n){let i=this.modelListCache;if(i)try{let o=Z0(e.framework,n);if(!o)return;(bt(e.model)||e.model===Sd)&&o.currentModelId&&!o.defaultModelId&&(o.defaultModelId=o.currentModelId),o.models.length>0&&i.update(e.framework,o).catch(d=>W.warn("piggyback model-list update failed (ignored)",{agentId:e.agentId,err:String(d)})),(o.currentModelId||o.currentEffort||o.currentFastMode)&&i.setRuntimeCurrent(e.agentId,{...o.currentModelId?{model:o.currentModelId}:{},...o.currentEffort?{effort:o.currentEffort}:{},...o.currentFastMode?{fastMode:o.currentFastMode}:{}})}catch(o){W.warn("piggyback model-list parse failed (ignored)",{agentId:e.agentId,err:String(o)})}}warmupModelList(e){let n=this.modelListCache;if(!n||e.deployType!=="local")return;let i=e.framework,o=i==="claude-code"||i==="codex"||i==="hermes",a=i==="openclaw";if(!o&&!a||o&&!this.sessionSpawner||a&&!this.openclawModelLister||n.get(i)||this.modelListWarmupInFlight.has(i))return;this.modelListWarmupInFlight.add(i),(a?this.runOpenclawModelWarmup(i):this.runModelListWarmup(e,i)).finally(()=>this.modelListWarmupInFlight.delete(i))}async runOpenclawModelWarmup(e){if(this.openclawModelLister)try{let n=await this.openclawModelLister();n&&n.models.length>0?(await this.modelListCache?.update("openclaw",n),W.info("openclaw model-list warm-up done",{framework:e,count:n.models.length})):W.warn("openclaw model-list warm-up: empty CLI result (ignored)",{framework:e})}catch(n){W.warn("openclaw model-list warm-up failed (ignored)",{framework:e,err:String(n)})}}async runModelListWarmup(e,n){if(!this.sessionSpawner)return;let i;try{i=await this.sessionSpawner(e,"",ES,this.currentCozeEnv,this.currentMockScenario,void 0);let o=await i.sessionNew({cwd:e.workspace});this.piggybackModelList(e,o),W.info("model-list warm-up done",{agentId:e.agentId,framework:n})}catch(o){W.warn("model-list warm-up failed (ignored)",{agentId:e.agentId,framework:n,err:String(o)})}finally{await i?.stop("model-list warm-up done").catch(()=>{})}}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:Q.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 vx(a,o);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await Sx(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,ds(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??{},f=a.sessionId,u=f?e.activeTriggers.get(f):void 0,x={cozeAgentId:e.agentId};u&&(x.cozeTriggerMsgId=u);let p=f?e.activeGroupIds.get(f):void 0;p&&(x.cozeGroupId=p);let w=f?this.reverseSessionId(e,f):void 0,b=w?e.sessions.get(w):void 0;b&&(b.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...a,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:w}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:f,cloudSessionId:w,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(as(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:Q.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"&&vS(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 qo(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=gS){let o=this.upstreamIds.next(e);return new Promise((a,d)=>{let f=setTimeout(()=>{this.pendingBridge.delete(o),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:a,reject:d,timer:f}),this.upstream.send(as(o,e,n)).catch(u=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(u)})})}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&&ln(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 Si(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(Bn(e,{code:n,message:i,data:{bridgeVersion:Kt}}))}};function bS(){return pS(16).toString("hex")}function vS(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 SS=["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."],Rx="Warning: ";function IS(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(Rx)?i.text.slice(Rx.length):i.text;return SS.some(a=>o.startsWith(a))}Ct();ne();Pe();import{randomBytes as AS}from"node:crypto";import{createServer as kS}from"node:http";var TS=1e6,Px=q("ipc"),oa=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=AS(32).toString("hex");let e=kS((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(),Px.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 _t(this.paths.portFile,String(this.port)),await _t(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){ps(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){ps(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await CS(e)}catch(f){ps(n,400,{error:"invalid json",detail:String(f)});return}try{let f=await a.handler(d,e);ps(n,200,f??{ok:!0})}catch(f){Px.error("IPC handler failed",{key:o,err:String(f)}),ps(n,500,{error:f instanceof Error?f.message:String(f)})}}};function ps(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function CS(t){let e=[],n=0;for await(let o of t){let a=o;if(n+=a.length,n>TS)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 J1=en(Ap(),1),Z1=en(pa(),1),X1=en(ai(),1),Y1=en(cl(),1),Q1=en(fl(),1),eI=en(ml(),1),Mp=en(_a(),1),tI=en(Lp(),1);var Np=Mp.default;Ze();ne();var{FWS:mI}=$p(),Ne=q("upstream.frontier"),Jp="application/json",Zp="none",wI=15e3;function _I(t){class e extends Np{constructor(i){super(i,R0,{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(of("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 Ss=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Ne.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:P0,...Nn(this.opts.ppeOverride)},n=_I(e),i=O0(this.opts.urlOverride),o={url:i,ws:n,fpID:C0,aID:Mo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Jp,force:!0},payloadEncoding:{encoding:Zp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new mI(o),d=!1,f=null,u,x,p=new Promise((_,v)=>{u=_,x=v}),w=_=>{d||(d=!0,f&&(clearTimeout(f),f=null),_?x(_):u())};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}),_&&w();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}),w(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},a.onmessage=_=>this.handleMessage(_),this.fws=a;let b=this.opts.openTimeoutMs??wI;f=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${b}ms (handshake or upgrade slow)`))},b),await a.connect();try{await p}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 k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let f=Date.now();throw f-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=f,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),a=e;Xp(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:Jp,payloadEncoding:Zp})}catch(f){throw Ne.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(f)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(f)}`,{cause:f})}}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=bI(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;Xp(a)||Ne.info("frontier frame in",{logid:EI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:yI(i)}),Promise.resolve(this.handler(o)).catch(d=>Ne.warn("frontier frame handler threw",{err:String(d)}))}};function Xp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Yp=2e3;function yI(t){return t.length<=Yp?t:`${t.slice(0,Yp)}...<truncated, total ${t.length} chars>`}function EI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function bI(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}}Ze();ne();var El=q("skill-publish"),vI="/api/marketplace/product/skill/publish_with_assets",SI=15e4;async function Qp(t,e={}){let i=`${Wr(Kr(e.handshakeBase))}${vI}`,o=e.timeoutMs??SI,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",...Nn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},f=new AbortController,u=setTimeout(()=>f.abort(),o);El.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:f.signal}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${_.slice(0,200)}`)}let w=await x.json();if(El.info("skill publish response",{logid:p,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${p}`);let b={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(b.skillId=String(w.data.skill_id)),w.data?.version&&(b.version=w.data.version),El.info("skill publish ok",{logid:p,skillId:b.skillId??"",version:b.version??""}),b}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(u)}}ne();var bl=q("upstream.switchable"),Ta=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;bl.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 bl.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>bl.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var vl=q("upstream"),hi=class{handler=null;async start(){vl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){vl.info("NoopUpstream stopped",{reason:e})}async send(e){vl.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)}};Ze();ne();Ct();ne();Pe();import{promises as II}from"node:fs";var eg=q("pat-token-store");async function Ca(t=Z()){try{let n=(await II.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(eg.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"&&eg.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function Is(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await _t(e.patTokenFile,t,{mode:384})}Pe();Pe();import{promises as Ra}from"node:fs";import{join as AI}from"node:path";function kI(t,e){return`#!/bin/sh
|
|
114
|
+
`}async function Qh(t){let e=mv(t,"HEARTBEAT.md"),n=await xv(e,"utf8");return yv(n)!==wv?!1:(await gv(e,_v),!0)}var ie=H("agent-manager"),kv=["hooks.json","cozeloop.env"],Cv=["hooks"];async function Tv(t,e){let n=gn(Ne(t,e).root,"codex-home"),i=gn(np(),".codex");if(n!==i){await na(n,{recursive:!0});for(let o of Cv){let a=gn(i,o),d=gn(n,o);try{await Vd(d);continue}catch{}try{await Ev(a,d,{recursive:!0,errorOnExist:!0,filter:u=>{let f=Av(u);return!f.endsWith(".log")&&!f.includes(".bak")}}),ie.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ie.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}for(let o of kv){let a=gn(i,o),d=gn(n,o);try{await Vd(d);continue}catch{}try{if(o==="cozeloop.env"){let f=(await vv(a,"utf8")).split(/\r?\n/).filter(p=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(p)).join(`
|
|
115
|
+
`);await Iv(d,f,{mode:384})}else await bv(a,d);ie.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ie.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var Jd="acceptEdits",rp="full-access",ip="read-only";function Pv(t){return{INITIAL_AGENT_MODE:Jo(t)}}var Rv=(t,e,n,i,o,a,d,u,f,p,x,g)=>{switch(t){case"claude-code":{let v={...o?{...z0(o),...G0(o,d,u,g)}:{},...f??{},IS_SANDBOX:"1"};return new Vo({cwd:n,env:v,agentId:i})}case"codex":{let v=rp;p!==void 0&&(Zt("codex",p)?v=p:ie.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:p}));let w=!!o?.modelToken,E={...o?{...H0(o),...U0(o,d,u,g)}:{},...Pv(v),...w?{NO_BROWSER:"1"}:{},...f??{},...w?{COZELAB_ONBOARD_CLOUD:"true"}:{}};return new Zo({cwd:n,agentId:i,...Object.keys(E).length>0?{env:E}:{},...o?.fastMode?{fastMode:o.fastMode}:{},...w?{authMethodId:"api-key",isolateCodexHome:!0,...x?{codexHomeDir:x}:{}}:{}})}case"openclaw":return new si({command:e,cwd:n,agentId:i,...a?{sessionName:Kd(a)}:{}});case"hermes":return new Yo({command:e,cwd:n,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{},...o?.model&&!At(o.model)?{modelId:o.model}:{}})}};function $d(t){return t==="claude-code"||t==="codex"}var Dv={path:"",version:"cloud-deployed"},ep="openclaw_gateway_unavailable",Ov="openclaw_default_agent_missing";function tp(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 Lv={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Mv=6e4,ra=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??Rv,this.createTimeoutMs=e.createTimeoutMs??Mv,this.detectorFactory=e.detectorFactory??(()=>new pr),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new ta({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??gn(np(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{ie.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=gn(e,".env");if(await Vd(n).then(a=>a.isFile()).catch(()=>!1)){ie.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=is({...process.env,...ur(this.paths.agentEnvFile)});await vt(n,o,{mode:384}),ie.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ie.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await ye(e.agentId,this.paths).catch(()=>null),o=dr(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 k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")ie.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(C=>ie.warn("dispose stale agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else if(o&&a.deployType!=="cloud")ie.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(C=>ie.warn("dispose drifted agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){ie.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let C=await ye(e.agentId,this.paths).catch(()=>null);C&&(C.patToken=e.patToken,await Oe(C,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){ie.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let C=await ye(e.agentId,this.paths).catch(()=>null);C&&(C.modelInfo=e.modelInfo,await Oe(C,this.paths))}return ie.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 k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${P}`)}let u=Ne(e.agentId,this.paths),f=o?"cloud":"local",p=e.framework==="openclaw"&&f==="local",x;p&&!n?.revive&&(x=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let g=x??(p?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??g??u.workspace,w=new AbortController,E=setTimeout(()=>w.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),S,A=!1;try{o&&$d(e.framework)&&await Pr(e.framework,w.signal);let C=()=>{if(w.signal.aborted)throw w.signal.reason instanceof Error?w.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await na(u.root,{recursive:!0}),await na(v,{recursive:!0}),await na(u.logs,{recursive:!0}),C(),p||await Rr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await lc(v,"cloud"):await lc(v,"local",Jd)),C();let P=i,y=B0({model:e.model??P?.model}),R=g0(e._meta)??P?.accountId,D=e.patToken??P?.patToken,z=f==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(S=new Xo({agentId:e.agentId,framework:e.framework,workspace:v,model:y.model??Bt,deployType:f,...R?{accountId:R}:{},...D?{patToken:D}:{},...z?{modelInfo:z}:{}}),S.status="ok",P?.sessions){let K=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Q,ae]of Object.entries(P.sessions)){let le={acpSessionId:ae.acpSessionId,modelToken:ae.modelToken,tokenGeneratedAt:ae.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};K?ae.permissionMode===void 0?(le.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",ie.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Q,framework:e.framework,fallback:le.permissionMode})):Zt(e.framework,ae.permissionMode)?le.permissionMode=ae.permissionMode:ie.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Q,framework:e.framework,value:ae.permissionMode}):ae.permissionMode!==void 0&&ie.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Q,framework:e.framework,deployType:f}),ae.cozeGroupId&&(le.cozeGroupId=ae.cozeGroupId),ae.tokenGroupId&&(le.tokenGroupId=ae.tokenGroupId),ae.requestScene&&(le.requestScene=ae.requestScene),S.sessions.set(Q,le)}let se=Object.keys(P.sessions).length;se>0&&ie.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:se})}this.registry.register(S),A=!0,n?.revive||this.registry.warmupModelList?.(S);let M={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:y.model};if(f==="cloud"&&(M.deployType="cloud"),R&&(M.accountId=R),D&&(M.patToken=D),z&&(M.modelInfo=z),P?.skills&&(M.skills=P.skills),P?.agentName&&(M.agentName=P.agentName),P?.description&&(M.description=P.description),M.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Jt,e.framework==="openclaw"&&f==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):ie.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await Qh(v)&&ie.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:v})}catch(K){ie.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:v,err:String(K)})}}let W=e.initialSkills??[];if(W.length>0){let K=[...M.skills??[]],se=new Map(K.map((le,Se)=>[le.skillId,Se])),Q=await Promise.allSettled(W.map(le=>qo({agentId:e.agentId,workspace:v,framework:e.framework,skill:le,paths:this.paths}))),ae=0;for(let[le,Se]of Q.entries()){let je=W[le];je&&(Se.status==="fulfilled"?(jo(K,se,Se.value),ae++):ie.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:je.skillId,skillName:je.skillName,err:String(Se.reason)}))}ae>0&&(M.skills=K,ie.info("initialSkills installed",{agentId:e.agentId,installed:ae,requested:W.length}))}return await Oe(M,this.paths),ie.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(C){throw ie.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),A&&S&&(await S.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),ie.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:C instanceof Error?C.stack:String(C)}),await Sv(u.root,{recursive:!0,force:!0}).catch(P=>ie.warn("rm agent dir failed (ignored)",{err:String(P)})),C instanceof k?C:new k("AGENT_SPAWN_FAILED",String(C),{cause:C})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,n,i,o,a,d){let f=this.config.frameworksCache?.[e.framework];if(!f)if(e.deployType==="cloud"&&$d(e.framework))f=Dv;else throw e.framework==="hermes"?new k("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);$d(e.framework)&&!Us(e.framework)&&(ie.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await Pr(e.framework));let p=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:F0({model:e.model,effort:e.effort,fastMode:e.fastMode}),x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:p,cloudSessionId:i,cozeEnv:o,mockScenario:a,requestScene:d,command:f.path});else if(e.framework==="hermes"){let g={...this.buildBinShimPathEnv()};p?.modelToken&&(await V0({paths:this.paths,agentId:e.agentId,modelConfig:p,cozeEnv:o,mockScenario:a}),g.HERMES_HOME=hr(e.agentId,this.paths)),x=this.factory(e.framework,f.path,e.workspace,e.agentId,p,i,o,a,g)}else{let g=e.sessions.get(i),v=xn(e)?g?.permissionMode??rp:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await Tv(e.agentId,this.paths),x=this.factory(e.framework,f.path,e.workspace,e.agentId,p,i,o,a,this.buildBinShimPathEnv(),v,e.framework==="codex"&&e.deployType==="cloud"?gn(Ne(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await x.start(),await x.initialize(Lv),x}catch(g){let v=x instanceof Ct?x.getStderrTail():[];throw v.length>0&&ie.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof k?g.code:"unknown",recentStderr:v}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,f.path,g)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let o=await this.detectorFactory().probeOpenclawGateway(n);if(!o.reachable)return new k("AGENT_ENV_NOT_READY",tp(o),{cause:{reason:ep}})}catch(o){ie.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};ie.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 ie.info("openclaw lazy re-detect success",{agentId:n.defaultAgent.id,workspace:n.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=n,{id:n.defaultAgent.id,workspace:n.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:Ov}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new k("AGENT_ENV_NOT_READY",tp(n),{cause:{reason:ep}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,requestScene:u,command:f}=e,p=Kd(o);if(n.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent(),w=i&&!At(i.model)?i.model:void 0;return new si({command:f,cwd:v.workspace,agentId:v.id,sessionName:p,...w?{slashModelOnStart:w}:{}})}let x=await Xh();try{let v=this.getOpenclawConfig();await v.ensureAcpDeviceScopes()&&await v.restartGateway()}catch(v){ie.warn("acp device scope ensure failed (ignored)",{err:String(v)})}let g;if(i?.modelToken){let v=kd(o),w=Cd(i),E=`${v}/${w}`,S=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(E)!==S){let A=this.getOpenclawConfig(),C=await A.getAllowlistModelsForProvider(v),P=q0(i,a,d,C,u);P&&(await A.ensureProvider(v,P),await A.addModelToAllowlist(E),this.ensuredProviders.set(E,S))}g=E}else i&&!At(i.model)&&(g=i.model);return new si({command:f,cwd:n.workspace,agentId:n.agentId,sessionName:p,...x?{gatewayToken:x}:{},...g?{slashModelOnStart:g}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=n??e.model;for(let a of e.sessions.keys()){let d=kd(a),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(p){f=!1,ie.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(p)})}try{await i.removeModelFromAllowlist(u)}catch(p){f=!1,ie.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(p)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as dp}from"node:crypto";import{promises as Gv}from"node:fs";import{basename as lp}from"node:path";Qe();re();import{promises as Nv}from"node:fs";import{basename as Fv}from"node:path";var sp=H("file-upload"),Bv="/api/coze_claw/file/agent_upload",zv=6e4;async function op(t,e={}){let i=`${Vr(Jr(e.handshakeBase))}${Bv}`,o=e.timeoutMs??zv,a=await Nv.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",...Bn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,p=setTimeout(()=>f.abort(),o);sp.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let x=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let E=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${x.status} logid=${g}: ${E.slice(0,200)}`)}let v=await x.json();if(v.code!==void 0&&v.code!==0)throw new k("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${g}`);let w=v.data?.file?.file_url;if(!w)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${g}: ${JSON.stringify(v).slice(0,200)}`);return sp.info("file upload ok",{uri:w,logid:g}),{uri:w}}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Fv(t.path)}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(p)}}Qe();re();import{extname as Uv}from"node:path";var Hv={".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 ap(t){let e=Uv(t).toLowerCase();return Hv[e]??"application/octet-stream"}De();var ia=H("agent-send"),cp=50*1024*1024;function up(t,e,n){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(n);if(!o)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function fp(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(p){u=p,f<2&&(ia.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(p)}),await new Promise(x=>setTimeout(x,5e3)))}throw new k("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function hp(t,e){let{session:n,runtime:i}=up(e.core,t.agentId,t.sessionId);if(!await Ai(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await Gv.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>cp)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${cp}`);let a=await ap(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??lp(t.path),u;try{u=await op({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(p){throw ia.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:a,code:p instanceof k?p.code:"UNKNOWN",message:p instanceof Error?p.message:String(p)}),p}let f={sessionUpdate:"agent_file",messageId:dp(),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 fp(e,n,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),ia.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 pp(t,e){let{session:n,runtime:i}=up(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new k("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??lp(t.path),a={sessionUpdate:"group_file",messageId:dp(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await fp(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),ia.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 xp(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}Vt();re();In();var Xt=H("coze-cli-installer"),gp="@coze/cli@latest",qv="coze",mp="0.1.8",jv=5e3,Wv=5e3,Kv=9e4,wp=1e4,xs=null,sa=!1;async function Yd(t,e={}){if(sa)return;if(xs)return xs;let n=e.exec??No;return xs=(async()=>{try{let i=await $v(qv,n),o=!1;if(i){let d=await Vv(n);if(d===void 0)Xt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(xp(d,mp))Xt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:mp}),o=!0;else{Xt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),sa=!0;return}}let a=o?"upgrade-only":"full";Xt.info("coze-cli install start",{package:gp,mode:a});try{await n("npm",["i","-g","--prefer-online",gp],{timeout:Kv,maxBuffer:10*1024*1024}),Xt.info("coze-cli install ok")}catch(d){Xt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){sa=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:wp}),Xt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Xt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:wp}),Xt.info("coze auth login ok")}catch(d){Xt.warn("coze auth login failed",{err:String(d)});return}sa=!0}finally{xs=null}})(),xs}async function $v(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:jv});return cc(i)}catch{return}}async function Vv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:Wv});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Dt();var oa=class{cacheFilePath;memory=new Map;runtimeCurrent=new Map;writeQueue=new Yt;constructor(e){this.cacheFilePath=e}async loadFromDisk(){if(!this.cacheFilePath)return;let e=await rt(this.cacheFilePath);if(e)for(let[n,i]of Object.entries(e))i&&this.memory.set(n,i)}get(e){return this.memory.get(e)}update(e,n){return this.writeQueue.enqueue(async()=>{let i=eh(n),o=this.memory.get(e);if(o&&o.hash===i){if(o.cachedAt=Date.now(),n.defaultModelId&&o.defaultModelId!==n.defaultModelId){if(o.defaultModelId=n.defaultModelId,this.cacheFilePath){let u=await rt(this.cacheFilePath)??{};u[e]=o,await gt(this.cacheFilePath,u)}return!0}return!1}let a={cachedAt:Date.now(),hash:i,models:n.models,...n.defaultModelId?{defaultModelId:n.defaultModelId}:{},...n.effortLevels?{effortLevels:n.effortLevels}:{},...n.fastModes?{fastModes:n.fastModes}:{}};if(this.memory.set(e,a),!this.cacheFilePath)return!0;let d=await rt(this.cacheFilePath)??{};return d[e]=a,await gt(this.cacheFilePath,d),!0})}setRuntimeCurrent(e,n){let i=this.runtimeCurrent.get(e)??{};this.runtimeCurrent.set(e,{...i,...n.model!==void 0?{model:n.model}:{},...n.effort!==void 0?{effort:n.effort}:{},...n.fastMode!==void 0?{fastMode:n.fastMode}:{}})}getRuntimeCurrent(e){return this.runtimeCurrent.get(e)}};an();Dt();De();var Jv=10*6e4;function _p(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Jv:e}function aa(t){return rt(t??Z().configFile)}function gs(t,e){return gt(e??Z().configFile,t)}import{randomBytes as xS}from"node:crypto";Ar();Qe();re();import{createReadStream as Zv}from"node:fs";import{mkdir as Yv,readFile as Xv,realpath as Qv,stat as eS,writeFile as tS}from"node:fs/promises";import{basename as nS,dirname as Xd,isAbsolute as rS,join as iS,relative as sS,resolve as yp,sep as oS}from"node:path";import{createInterface as aS}from"node:readline";var Ep=H("fs-rpc"),ms=Xe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function vp(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>ms)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${ms} bytes`);let i=await Ip(t.path,e);return await Yv(Xd(i),{recursive:!0}),await tS(i,t.content,"utf8"),Ep.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Sp(t,e){let n=await Ip(t.path,e),i=await eS(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>ms&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${ms} bytes`);let a;if(o&&i.size>ms)a=await cS(n,t.line??1,t.limit);else{let d=await Xv(n,"utf8");if(o){let u=d.split(`
|
|
116
|
+
`),f=Math.max(0,(t.line??1)-1),p=typeof t.limit=="number"?f+t.limit:void 0;a=u.slice(f,p).join(`
|
|
117
|
+
`)}else a=d}return Ep.info("fs/read_text_file ok",{path:n,size:a.length}),{content:a}}async function cS(t,e,n){let i=aS({input:Zv(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(`
|
|
118
|
+
`)}async function Ip(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([bp(yp(e)),bp(yp(t))]),o=sS(n,i);if(dS(o,oS,rS(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function dS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function bp(t){let e=[],n=t;for(;n!==Xd(n);)try{let i=await Qv(n);return e.length?iS(i,...e.reverse()):i}catch{e.push(nS(n)),n=Xd(n)}return t}re();var Ap=H("prompt-multimodal"),kp=10*1024*1024,lS=15e3,uS=6;async function Cp(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 fS(d))}}let o=Array.from({length:Math.min(uS,t.length)},()=>i());return await Promise.all(o),e}function Tp(t){return t.some(e=>e.type==="image")}async function fS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!rs(e.uri))return t;try{let{buf:n,contentType:i}=await pS(e.uri),o=e.mimeType||hS(i)||"application/octet-stream";return Ap.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 Ap.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function hS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function pS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),lS);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>kp)throw new Error(`image too large: ${o.byteLength} bytes (max ${kp})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}an();Qe();re();var j=H("core"),gS=3e4,mS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,wS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",_S="\u5BA1\u6279\u5DF2\u8D85\u65F6",yS=3e4,bS="__model_warmup__",ca=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new ti;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;modelListCache;openclawModelLister;modelListWarmupInFlight=new Set;modelListWarmupAttempted=new Set;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=_p(e.bridgeConfig),this.modelListCache=e.modelListCache,this.openclawModelLister=e.openclawModelLister}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(),j.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){j.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),j.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){j.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)&&j.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)=>{j.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),oi(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){j.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(Un(o,{code:ee.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>j.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:ee.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){j.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:ee.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Ko(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&mS.test(i)?this.currentCozeEnv=i:i&&j.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,a=m0(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),j.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),j.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,ee.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):j.warn("drop notification: extension not registered",{method:e.method});return}let f=await u(e,this);n!==null&&await this.upstream.send(ei(n,f));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(ei(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(ei(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,ee.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):j.warn("drop unknown notification",{method:e.method})}catch(u){j.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Un(n,fs(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let 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 p=n._meta?.cozeTriggerMsgId,x=Lo(n._meta);return j.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,f,a,wS,p,x)}}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{j.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}=_0(i);switch(n){case"session/new":{let a=ES();return j.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=o;return j.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 k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=xn(e)?w0(i._meta):void 0;if(u!==void 0&&!Zt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Gd(e.framework)}`);let f=Lo(i._meta),p=this.requestSceneBySession.get(d),x=await this.ensureRuntime(e,d,f,p);if(u!==void 0&&x.permissionMode===void 0&&(x.permissionMode=u,await this.persistSessionMapping(e)),x.replySeq=0,await this.ensureDownstream(e,d,x),!x.downstream||!x.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&x.permissionMode!==void 0&&x.permissionMode!==u){let w=x.permissionMode;x.permissionMode=u,await this.persistSessionMapping(e);try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(E){throw x.permissionMode=w,await this.persistSessionMapping(e).catch(()=>{}),E}}let g=i._meta?.cozeTriggerMsgId;if(g?e.activeTriggers.set(x.acpSessionId,g):e.activeTriggers.delete(x.acpSessionId),f?e.activeGroupIds.set(x.acpSessionId,f):e.activeGroupIds.delete(x.acpSessionId),f&&x.cozeGroupId!==f&&(x.cozeGroupId=f,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Tp(a.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let v=await Cp(a.prompt);try{let w=await x.downstream.sessionPrompt({...a,sessionId:x.acpSessionId,prompt:v});return x.lastActiveAt=Date.now(),w}catch(w){if(w instanceof k&&w.code==="AGENT_APPROVAL_TIMEOUT"){let E=x.pendingPermission;E&&(E.downstream.respondAgentRequest(E.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(E.upstreamId),x.pendingPermission=void 0);let S=x.acpSessionId,A=S?e.activeTriggers.get(S):void 0,C=S?e.activeGroupIds.get(S):void 0;return j.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,x,d,_S,A,C)}throw w}finally{if(e.activeTriggers.delete(x.acpSessionId),e.activeGroupIds.delete(x.acpSessionId),x.pendingPermission=void 0,x.reloadAfterTurn){x.reloadAfterTurn=!1;let w=x.downstream;w&&(x.downstream=void 0,j.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:x.acpSessionId}),w.stop("reload-after-turn").catch(E=>j.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(E)})))}else x.downstream?.isAlive()&&this.armIdleTimer(e,d,x)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let f=e.getSessionQueue(d);f.size>0&&(j.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:f.size}),f.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=o,d=a.sessionId,u=a.modeId,f=Lo(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!xn(e))throw e.framework==="openclaw"?new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new k("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Zt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Gd(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let p=e.sessions.get(d)??await this.ensureRuntime(e,d);if(p.permissionMode===u)return{};let x=p.permissionMode;if(p.permissionMode=u,await this.persistSessionMapping(e),p.downstream?.isAlive()&&p.acpSessionId)try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(g){throw p.permissionMode=x,await this.persistSessionMapping(e).catch(()=>{}),g}else j.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let 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 j.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};j.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,p=e.deployType==="cloud"&&a.tokenGroupId!==i,x=a.requestScene!==o;if(p&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),p||x){oi(a);let g=a.downstream;a.downstream=void 0,g&&await g.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=o,(f||p||x)&&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 xn(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?W0:K0:u.permissionMode=e.framework==="claude-code"?Jd:ip),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(at.GEN_MODEL_TOKEN,o,yS);if(!a?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return a.modelToken}catch(a){throw a instanceof k&&a.code==="MODEL_TOKEN_GEN_FAILED"?a:new k("MODEL_TOKEN_GEN_FAILED",a instanceof Error?a.message:String(a),{cause:a})}}async ensureDownstream(e,n,i){if(oi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<a)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((a-(Date.now()-u))/1e3)}s`);let f;try{let p=this.requestSceneBySession.get(n);p&&j.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:p}),f=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,p)}catch(p){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(j.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),p}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{let p=await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace});j.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId}),this.piggybackModelList(e,p)}catch(p){j.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(p)}),i.acpSessionId=void 0;let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,this.piggybackModelList(e,x),await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,this.piggybackModelList(e,p),await this.persistSessionMapping(e)}}catch(p){throw j.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(p)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,p}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),xn(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(p){j.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(p)})}}armIdleTimer(e,n,i){if(oi(i),this.isRuntimeBusy(e,i)){j.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)){j.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}j.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=>j.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(Qr("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(Qr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>j.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){j.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(o);if(!a){j.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(IS(n)){j.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"&&xn(e)){let x=d.currentModeId;Zt(e.framework,x)&&a.permissionMode!==x?(a.permissionMode=x,this.persistSessionMapping(e).catch(g=>j.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(g)}))):typeof x=="string"&&!Zt(e.framework,x)&&j.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:x})}if(d&&typeof d=="object"&&d.sessionUpdate==="config_option_update"){let x=d.configOptions;Array.isArray(x)&&this.piggybackModelList(e,{configOptions:x})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let p=e.activeGroupIds.get(i);p&&(u.cozeGroupId=p),this.upstream.send(Qr("session/update",{...n,sessionId:o,_meta:u})).catch(x=>j.warn("forward update failed",{agentId:e.agentId,err:String(x)}))}piggybackModelList(e,n){let i=this.modelListCache;if(i)try{let o=Y0(e.framework,n);if(!o)return;(At(e.model)||e.model===Id)&&o.currentModelId&&!o.defaultModelId&&(o.defaultModelId=o.currentModelId),o.models.length>0&&i.update(e.framework,o).catch(d=>j.warn("piggyback model-list update failed (ignored)",{agentId:e.agentId,err:String(d)})),(o.currentModelId||o.currentEffort||o.currentFastMode)&&i.setRuntimeCurrent(e.agentId,{...o.currentModelId?{model:o.currentModelId}:{},...o.currentEffort?{effort:o.currentEffort}:{},...o.currentFastMode?{fastMode:o.currentFastMode}:{}})}catch(o){j.warn("piggyback model-list parse failed (ignored)",{agentId:e.agentId,err:String(o)})}}warmupModelList(e){let n=this.modelListCache;if(!n||e.deployType!=="local")return;let i=e.framework,o=i==="claude-code"||i==="codex"||i==="hermes",a=i==="openclaw";if(!o&&!a||o&&!this.sessionSpawner||a&&!this.openclawModelLister||n.get(i)?.defaultModelId||this.modelListWarmupInFlight.has(i)||this.modelListWarmupAttempted.has(i))return;this.modelListWarmupAttempted.add(i),this.modelListWarmupInFlight.add(i),(a?this.runOpenclawModelWarmup(i):this.runModelListWarmup(e,i)).finally(()=>this.modelListWarmupInFlight.delete(i))}async runOpenclawModelWarmup(e){if(this.openclawModelLister)try{let n=await this.openclawModelLister();n&&n.models.length>0?(await this.modelListCache?.update("openclaw",n),j.info("openclaw model-list warm-up done",{framework:e,count:n.models.length})):j.warn("openclaw model-list warm-up: empty CLI result (ignored)",{framework:e})}catch(n){j.warn("openclaw model-list warm-up failed (ignored)",{framework:e,err:String(n)})}}async runModelListWarmup(e,n){if(!this.sessionSpawner)return;let i;try{i=await this.sessionSpawner(e,"",bS,this.currentCozeEnv,this.currentMockScenario,void 0);let o=await i.sessionNew({cwd:e.workspace});this.piggybackModelList(e,o),j.info("model-list warm-up done",{agentId:e.agentId,framework:n})}catch(o){j.warn("model-list warm-up failed (ignored)",{agentId:e.agentId,framework:n,err:String(o)})}finally{await i?.stop("model-list warm-up done").catch(()=>{})}}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}j.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:ee.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 vp(a,o);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await Sp(a,o);n.respondAgentRequest(i.id,d)}}catch(o){j.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,fs(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,p={cozeAgentId:e.agentId};f&&(p.cozeTriggerMsgId=f);let x=u?e.activeGroupIds.get(u):void 0;x&&(p.cozeGroupId=x);let g=u?this.reverseSessionId(e,u):void 0,v=g?e.sessions.get(g):void 0;v&&(v.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let w={...a,...g?{sessionId:g}:{},_meta:p};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:g}),j.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:g,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(ls(o,"session/request_permission",w)).catch(E=>{this.pendingUpstream.delete(o),j.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),n.respondAgentRequestError(i.id,{code:ee.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let o=n.value;this.clearPendingPermissionFor(o),e.error?(j.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"&&vS(e.result,o),j.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 Wo(e.error)):i.value.resolve(e.result);return}j.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 j.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=gS){let o=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(ls(o,e,n)).catch(f=>{let p=this.pendingBridge.get(o);p&&(clearTimeout(p.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&&xn(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 ki(e.agentId,n,this.paths)}catch(n){j.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(Un(e,{code:n,message:i,data:{bridgeVersion:Jt}}))}};function ES(){return xS(16).toString("hex")}function vS(t,e){if(!t||typeof t!="object"){j.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){j.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"){j.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")&&j.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var SS=["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."],Pp="Warning: ";function IS(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(Pp)?i.text.slice(Pp.length):i.text;return SS.some(a=>o.startsWith(a))}Dt();re();De();import{randomBytes as AS}from"node:crypto";import{createServer as kS}from"node:http";var CS=1e6,Rp=H("ipc"),da=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=AS(32).toString("hex");let e=kS((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(),Rp.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 vt(this.paths.portFile,String(this.port)),await vt(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){ws(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){ws(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await TS(e)}catch(u){ws(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);ws(n,200,u??{ok:!0})}catch(u){Rp.error("IPC handler failed",{key:o,err:String(u)}),ws(n,500,{error:u instanceof Error?u.message:String(u)})}}};function ws(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function TS(t){let e=[],n=0;for await(let o of t){let a=o;if(n+=a.length,n>CS)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 J1=on(kx(),1),Z1=on(wa(),1),Y1=on(li(),1),X1=on(dl(),1),Q1=on(fl(),1),eI=on(wl(),1),Nx=on(Ea(),1),tI=on(Mx(),1);var Fx=Nx.default;Qe();re();var{FWS:mI}=Vx(),Be=H("upstream.frontier"),Zx="application/json",Yx="none",wI=15e3;function _I(t){class e extends Fx{constructor(i){super(i,R0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Be.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(ou("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");Be.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Be.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...o)}}return e}var ks=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){Be.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:D0,...Bn(this.opts.ppeOverride)},n=_I(e),i=L0(this.opts.urlOverride),o={url:i,ws:n,fpID:P0,aID:Bo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Zx,force:!0},payloadEncoding:{encoding:Yx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new mI(o),d=!1,u=null,f,p,x=new Promise((w,E)=>{f=w,p=E}),g=w=>{d||(d=!0,u&&(clearTimeout(u),u=null),w?p(w):f())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let w=this.openCount===1;Be.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:w,openCount:this.openCount}),w&&g();for(let E of this.connectHandlers)Promise.resolve(E({initial:w})).catch(S=>Be.warn("onConnect handler threw (ignored)",{err:String(S)}))},a.onclose=w=>{this.opened=!1,Be.info("frontier closed",{code:w.code,reason:w.reason,willReconnect:w.willReconnect})},a.onerror=w=>{Be.warn("frontier error",{code:w.code,msg:w.message}),g(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${w.code} msg=${w.message??""}`))},a.onmessage=w=>this.handleMessage(w),this.fws=a;let v=this.opts.openTimeoutMs??wI;u=setTimeout(()=>{g(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await a.connect();try{await x}catch(w){try{a.close(1e3,"open failed")}catch(E){Be.warn("fws close during start failure threw (ignored)",{err:String(E)})}throw this.fws=null,this.opened=!1,w}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Be.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Be.warn("frontier send refused: upstream not started",{method:i}),new k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Be.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),a=e;Xx(a)||Be.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:Zx,payloadEncoding:Yx})}catch(u){throw Be.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=n(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Be.debug("drop non-adapter frontier frame",{service:n});return}let i=EI(e);if(!i){Be.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Be.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Be.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=o;Xx(a)||Be.info("frontier frame in",{logid:bI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:yI(i)}),Promise.resolve(this.handler(o)).catch(d=>Be.warn("frontier frame handler threw",{err:String(d)}))}};function Xx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Qx=2e3;function yI(t){return t.length<=Qx?t:`${t.slice(0,Qx)}...<truncated, total ${t.length} chars>`}function bI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function EI(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}}Qe();re();var El=H("skill-publish"),vI="/api/marketplace/product/skill/publish_with_assets",SI=15e4;async function eg(t,e={}){let i=`${Vr(Jr(e.handshakeBase))}${vI}`,o=e.timeoutMs??SI,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",...Bn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);El.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 p=await fetch(i,{method:"POST",headers:d,body:a,signal:u.signal}),x=p.headers.get("x-tt-logid")??"";if(!p.ok){let w=await p.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${p.status} logid=${x}: ${w.slice(0,200)}`)}let g=await p.json();if(El.info("skill publish response",{logid:x,httpStatus:p.status,code:g.code,msg:g.msg,dataSkillId:g.data?.skill_id??"",dataVersion:g.data?.version??""}),g.code!==void 0&&g.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${g.code} msg=${g.msg??"-"} logid=${x}`);let v={};return g.data?.skill_id!==void 0&&g.data.skill_id!==""&&(v.skillId=String(g.data.skill_id)),g.data?.version&&(v.version=g.data.version),El.info("skill publish ok",{logid:x,skillId:v.skillId??"",version:v.version??""}),v}catch(p){throw p instanceof k?p:p.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(f)}}re();var vl=H("upstream.switchable"),Ra=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;vl.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 vl.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>vl.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()}};re();var Sl=H("upstream"),gi=class{handler=null;async start(){Sl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Sl.info("NoopUpstream stopped",{reason:e})}async send(e){Sl.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)}};Qe();re();Dt();re();De();import{promises as II}from"node:fs";var tg=H("pat-token-store");async function Da(t=Z()){try{let n=(await II.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(tg.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"&&tg.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function Cs(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await vt(e.patTokenFile,t,{mode:384})}De();De();import{promises as Oa}from"node:fs";import{join as AI}from"node:path";function kI(t,e){return`#!/bin/sh
|
|
119
119
|
exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
|
|
120
|
-
`}function
|
|
120
|
+
`}function CI(t,e){return`@echo off\r
|
|
121
121
|
"${e}" "${t}" %*\r
|
|
122
|
-
`}async function
|
|
122
|
+
`}async function ng(t,e=Z()){let n=e.binDir;await Oa.mkdir(n,{recursive:!0});let i=AI(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,a=process.platform==="win32"?CI(t,o):kI(t,o);return await Oa.readFile(i,"utf8").catch(()=>null)===a||(await Oa.writeFile(i,a,"utf8"),process.platform!=="win32"&&await Oa.chmod(i,493)),n}re();De();import{execSync as rg}from"node:child_process";import{readFileSync as ig,unlinkSync as TI}from"node:fs";import{mkdir as PI,open as RI,readFile as sg,unlink as Il,writeFile as DI}from"node:fs/promises";import{dirname as OI}from"node:path";var LI=H("single-instance"),MI=t=>new Promise(e=>setTimeout(e,t)),La=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=>hs(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&&LI.warn("removing stale pid file",{stalePid:i}),await DI(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 sg(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Il(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 sg(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 PI(OI(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await RI(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 MI(this.claimLockIntervalMs);continue}await Il(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Il(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=ig(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(ni)||n.includes("lib/index.js"))}catch{}try{let n=rg(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(ni)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=rg(`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{ig(this.pidFile,"utf8").trim()===String(this.selfPid)&&TI(this.pidFile)}catch{}})}};Ma();re();var br=H("daemon.upstream-watchdog"),qI=12e4,jI=9e5,WI=3e4;function kl(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var Na=class{constructor(e){this.opts=e;this.softMs=e.softMs??kl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",qI),this.hardMs=e.hardMs??kl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",jI),this.intervalMs=e.intervalMs??kl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",WI),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?.(),br.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&&br.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&&br.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,br.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){br.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,br.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>br.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 G=H("daemon");async function cg(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){iu({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:T=>Ne(T,t).logs,listAgentIds:()=>Hs(t)});try{let{writeFileSync:T}=await import("node:fs");T(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
123
|
\u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
|
|
124
124
|
\u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
|
|
125
|
-
`)}catch{}}let e=new Pa({processTitle:Qr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await ia(),o=i??{};Ls({pid:process.pid}),G.info(i?"loaded bridge config":"initialized bridge config");let a=new Ta(new hi),d=new ra(t.modelCacheFile);await d.loadFromDisk().catch(C=>G.warn("modelListCache.loadFromDisk failed (ignored)",{err:String(C)}));let f=null,u=async()=>{let C=o.frameworksCache?.openclaw?.path;return C?Y0(C):null},x=new sa({upstream:a,paths:t,bridgeConfig:o,modelListCache:d,openclawModelLister:u,sessionSpawner:async(C,H,j,ee,ae,st)=>{if(!f)throw new Error("agentManager not ready");return f.spawnSessionDownstream(C,H,j,ee,ae,st)}}),p=new ea({paths:t,config:o,registry:x});f=p;let w,b,_=null,v={},I,A=null,T=null,R=null,E=new Vt;function P(C,H){return E.enqueue(()=>U(C,H))}function D(){T||(T=new Oa({isConnected:()=>a.isConnected()&&!(A?.isLivenessLost()??!1),forceReconnect:()=>R?P(R,{force:!0}):void 0,onFatal:C=>{if(process.env[As]==="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)}})),T.start()}async function U(C,H){let j=C,ee=j?.privatecode;if(!ee)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let ae=rs(j.env),st=j.handshake_url,lt=j.frontier_url,Ft=og(j.env,st,lt);if(R=j,!H?.force&&w===ee&&b===Ft){let Be=await KI(t);return x.agents.size===0&&Be?(G.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ma(t,p).catch(me=>G.warn("connect-noop auto-revive error (ignored)",{err:String(me)}))):G.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let Qt=!!w&&w!==ee,mn=b!==void 0&&b!==Ft,qn=Qt||mn,mt=await bd({privatecode:ee,...st?{endpoint:st}:{},ppeOverride:ae});if(qn){G.warn("connect config switched, resetting agents",{pcChanged:Qt,envChanged:mn,previousPc:w?La(w):"",nextPc:La(ee)});for(let Be of[...x.agents.values()])await Be.dispose("connect config switch").catch(()=>{}),x.agents.delete(Be.agentId);x.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on connect config switch",{count:x.disconnectedAgents.size}),x.disconnectedAgents.clear()),await a.swap(new hi,"connect switch").catch(()=>{})}_=mt.deviceId,Ls({deviceId:_,pid:process.pid}),Zd({patToken:ee,env:j.env}).catch(Be=>G.warn("coze-cli setup error (ignored)",{err:String(Be)}));let wr=new Ss({handshake:mt,privatecode:ee,...lt?{urlOverride:lt}:{},ppeOverride:ae,getPatTokenForAgent:Be=>x.agents.get(Be)?.patToken});return await a.swap(wr,"connect"),w=ee,b=Ft,v=ae,I=st,j.mock_scenario!==void 0&&(x.setMockScenario(j.mock_scenario),G.info("mock scenario set",{scenario:j.mock_scenario})),A||(A=new os({core:x,getDeviceId:()=>_??"",onTickEnd:()=>J.retryPending().catch(Be=>G.warn("detailSync.retryPending failed (ignored)",{err:String(Be)})),onAuthFailures:ie})),A.start(),D(),qn&&Ma(t,p).catch(Be=>G.warn("post-connect-switch auto-revive error (ignored)",{err:String(Be)})),Is(ee,t).catch(Be=>G.warn("writePatToken after /connect failed (ignored)",{err:String(Be)})),G.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}x.registerExtension("_agent/create",async C=>p.createAgent(C.params)),x.registerExtension("_agent/health",async()=>({ok:!0}));let N={},K=new zo({agents:x.agents,modelListCache:d,openclawModelLister:u,paths:t,publishSkillToMarketplace:async C=>{let H=x.agents.get(C.agentId)?.patToken??w;if(!H)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Qp({patToken:H,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:I,ppeOverride:v})},disposeAndMarkDisconnected:async(C,H)=>{let j=x.agents.get(C);if(j){await p.cleanupOpenclawSessionProviders(j).catch(ae=>G.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(ae)})),j.framework==="hermes"&&j.deployType==="cloud"&&await Rd(C,t).catch(ae=>G.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(ae)}));let ee=!0;try{await j.dispose(`disconnect: ${H}`)}catch(ae){ee=!1,G.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(ae)}),j.status="error"}ee&&(j.status="disconnected",x.unregister(C),x.disconnectedAgents.add(C))}else x.disconnectedAgents.add(C)},disposeForDelete:async(C,H)=>{let j=x.agents.get(C);j&&(await p.cleanupOpenclawSessionProviders(j).catch(ee=>G.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(ee)})),j.framework==="hermes"&&j.deployType==="cloud"&&await Rd(C,t).catch(ee=>G.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(ee)})),await j.dispose(`delete: ${H}`).catch(ee=>G.warn("dispose during delete failed (ignored)",{agentId:C,err:String(ee)})),x.unregister(C)),x.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!N.ref)throw new Error("agent-detail-sync not initialized yet");await N.ref.syncOne(C)},cleanupOpenclawProviders:async(C,H)=>{await p.cleanupOpenclawSessionProviders(C,H)},openclawRepair:async(C,H)=>{await p.openclawRepair(C,H)},hermesReset:async(C,H)=>{let j=await we(C).catch(()=>null);!j||j.framework!=="hermes"||j.deployType!=="cloud"||await K0({paths:t,agentId:C,model:j.model,modelInfo:j.modelInfo,cozeEnv:H,mockScenario:x.getMockScenario()})},isRuntimePendingPermission:C=>x.hasPendingPermissionFor(C)});x.registerExtension("_agent/listSkills",C=>K.listSkills(C.params)),x.registerExtension("_agent/addSkills",C=>K.addSkills(C.params)),x.registerExtension("_agent/removeSkills",C=>K.removeSkills(C.params)),x.registerExtension("_agent/publishSkill",C=>K.publishSkill(C.params)),x.registerExtension("_agent/getFileTree",C=>K.getFileTree(C.params)),x.registerExtension("_agent/getFileContent",C=>K.getFileContent(C.params)),x.registerExtension("_agent/update",C=>K.updateAgent(C.params)),x.registerExtension("_agent/disconnect",C=>K.disconnectAgent(C.params)),x.registerExtension("_agent/switchModel",C=>K.switchModel(C.params)),x.registerExtension("_agent/setConfigOption",C=>K.setConfigOption(C.params)),x.registerExtension("_agent/listAvailableModels",C=>K.listAvailableModels(C.params)),x.registerExtension("_agent/detail",C=>K.detail(C.params)),x.registerExtension("_agent/reset",C=>K.resetAgent(C.params)),x.registerExtension("_agent/repair",C=>K.repairAgent(C.params)),x.registerExtension("_agent/delete",C=>K.deleteAgent(C.params)),x.registerExtension("_agent/upgrade",C=>K.upgradeBridge(C.params));let J=new Hs({paths:t,handlers:K,agentManager:p,sendDetail:C=>x.sendRequest("_agent/detail",C)});N.ref=J;let ie=async C=>{await Promise.allSettled(C.map(async H=>{try{await K.disconnectAgent({agentId:H.agentId,reason:`auth_failure: code=${H.code} ${H.message}`}),G.info("agent disconnected due to auth failure from heartbeat response",{agentId:H.agentId,code:H.code,message:H.message})}catch(j){G.warn("disconnect during authFailure handling failed (ignored)",{agentId:H.agentId,err:String(j)})}}))};a.onConnect(({initial:C})=>{G.info("frontier upstream connected, triggering detail sync",{initial:C}),J.syncAll(C?"initial-connect":"reconnect").catch(H=>G.warn("detail sync top-level error (ignored)",{err:String(H)}))});let Y=new oa({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=x.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[As]==="1"?"manual":"supervisor",agents:[...x.agents.keys()],deviceId:_??"",frameworksCache:o.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let H=C,j=H?.privatecode,ee=H?.pairing_code;if(!j||!ee)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ae=rs(H.env),st=H.handshake_url,lt=H.frontier_url,Ft=og(H.env,st,lt),Qt=!!w&&w!==j,mn=b!==void 0&&b!==Ft,qn=Qt||mn,mt=await bd({privatecode:j,...st?{endpoint:st}:{},ppeOverride:ae});if(qn){G.warn("pair config switched, resetting agents",{pcChanged:Qt,envChanged:mn,previousPc:w?La(w):"",nextPc:La(j),previousEnvKey:b??"",nextEnvKey:Ft});for(let me of[...x.agents.values()])await me.dispose("pair config switch").catch(()=>{}),x.agents.delete(me.agentId);x.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on pair config switch",{count:x.disconnectedAgents.size}),x.disconnectedAgents.clear()),await a.swap(new hi,"pair switch").catch(()=>{})}_=mt.deviceId,Ls({deviceId:_,pid:process.pid}),Zd({patToken:j,env:H.env}).catch(me=>G.warn("coze-cli setup error (ignored)",{err:String(me)}));let wr=new Ss({handshake:mt,privatecode:j,...lt?{urlOverride:lt}:{},ppeOverride:ae,getPatTokenForAgent:me=>x.agents.get(me)?.patToken});await a.swap(wr,"pair");try{let me=new lr;o.frameworksCache=await me.detectAll(),await hs(o),G.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(me){G.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(me)})}let Be=Object.keys(o.frameworksCache??{});try{let me=await x.sendRequest("_agent/pair",{pairCode:ee,patToken:j,frameworks:Be,_meta:{cozeDeviceId:_}});G.info("_agent/pair ok",{pairResult:me}),w=j,b=Ft,v=ae,I=st,H.mock_scenario!==void 0&&(x.setMockScenario(H.mock_scenario),G.info("mock scenario set",{scenario:H.mock_scenario})),Is(j,t).catch(ft=>G.warn("writePatToken after /pair failed (ignored)",{err:String(ft)})),A||(A=new os({core:x,getDeviceId:()=>_??"",onTickEnd:()=>J.retryPending().catch(ft=>G.warn("detailSync.retryPending failed (ignored)",{err:String(ft)})),onAuthFailures:ie})),A.start(),D(),qn&&Ma(t,p).catch(ft=>G.warn("post-pair-switch auto-revive error (ignored)",{err:String(ft)}));let ce;return H.agent_id&&(ce=await VI(H.agent_id,t,p,ft=>x.sendRequest("_agent/detail",ft),j).catch(ft=>(G.error("--agent-id ensureAgent failed",{agentId:H.agent_id,err:String(ft)}),{ok:!1,agentId:H.agent_id??"",note:String(ft)}))),{ok:!0,note:"paired with cloud",...ce?{agent:ce}:{}}}catch(me){return G.error("_agent/pair failed",{err:String(me)}),{ok:!1,note:`pair failed: ${String(me)}`}}}},{method:"POST",path:"/connect",handler:C=>P(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let H=C;return{ok:!0,result:await p.createAgent(H)}}},{method:"POST",path:"/agent/send",handler:async C=>{let H=C;if(!H?.agentId||!H?.sessionId||!H?.kind||!H?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!w)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=H;return await(j.groupFile?hx:ux)(j,{core:x,patToken:w,handshakeBase:I,ppeOverride:v})}catch(j){if(j instanceof k)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async C=>{let H=C?.agent_id,j=await x.reloadAgents(H);return G.info("IPC /reload: recycled agent subprocesses",{agentId:H??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(G.info("IPC /shutdown received"),setImmediate(()=>{qe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:oe,token:le}=await Y.start();try{await tg(t.libEntry,t)}catch(C){G.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await x.start(),JI({paths:t,core:x,agentManager:p,detectAll:async()=>(o.frameworksCache=await new lr().detectAll(),await hs(o),o.frameworksCache)}).catch(C=>G.warn("startup warmup error (ignored)",{err:String(C)})),xf().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(vn(),uf));for(let H of["claude-code","codex"]){let j=await C(H);j&&G.info("acp wrapper version",{framework:H,version:j})}}).catch(C=>G.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let Ee=null,qe={port:oe,token:le,core:x,ipc:Y,shutdown(C){return Ee||(G.info("daemon shutdown",{reason:C}),Ee=(async()=>{A?.stop(),T?.stop(),await x.stop(C),await Y.stop(),await e.release()})(),Ee)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{qe.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>Ah()),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)}),G.info("daemon ready",{port:
|
|
127
|
-
`)){let
|
|
128
|
-
`;await
|
|
129
|
-
`).filter(d=>d.length>0).filter(d=>
|
|
130
|
-
`)}async function
|
|
131
|
-
`),1;for(let
|
|
132
|
-
`);return 0}let o=t.date??
|
|
125
|
+
`)}catch{}}let e=new La({processTitle:ni}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await aa(),o=i??{};Fs({pid:process.pid}),G.info(i?"loaded bridge config":"initialized bridge config");let a=new Ra(new gi),d=new oa(t.modelCacheFile);await d.loadFromDisk().catch(T=>G.warn("modelListCache.loadFromDisk failed (ignored)",{err:String(T)}));let u=null,f=async()=>{let T=o.frameworksCache?.openclaw?.path;return T?Q0(T):null},p=new ca({upstream:a,paths:t,bridgeConfig:o,modelListCache:d,openclawModelLister:f,sessionSpawner:async(T,U,q,te,ce,dt)=>{if(!u)throw new Error("agentManager not ready");return u.spawnSessionDownstream(T,U,q,te,ce,dt)}}),x=new ra({paths:t,config:o,registry:p});u=x;let g,v,w=null,E={},S,A=null,C=null,P=null,y=new Yt;function R(T,U){return y.enqueue(()=>z(T,U))}function D(){C||(C=new Na({isConnected:()=>a.isConnected()&&!(A?.isLivenessLost()??!1),forceReconnect:()=>P?R(P,{force:!0}):void 0,onFatal:T=>{if(process.env[Ts]==="1"){G.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:T});return}G.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:T}),process.exit(1)}})),C.start()}async function z(T,U){let q=T,te=q?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let ce=os(q.env),dt=q.handshake_url,pt=q.frontier_url,Ut=ag(q.env,dt,pt);if(P=q,!U?.force&&g===te&&v===Ut){let Ue=await KI(t);return p.agents.size===0&&Ue?(G.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ba(t,x).catch(_e=>G.warn("connect-noop auto-revive error (ignored)",{err:String(_e)}))):G.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let nn=!!g&&g!==te,En=v!==void 0&&v!==Ut,jn=nn||En,bt=await vd({privatecode:te,...dt?{endpoint:dt}:{},ppeOverride:ce});if(jn){G.warn("connect config switched, resetting agents",{pcChanged:nn,envChanged:En,previousPc:g?Fa(g):"",nextPc:Fa(te)});for(let Ue of[...p.agents.values()])await Ue.dispose("connect config switch").catch(()=>{}),p.agents.delete(Ue.agentId);p.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on connect config switch",{count:p.disconnectedAgents.size}),p.disconnectedAgents.clear()),await a.swap(new gi,"connect switch").catch(()=>{})}w=bt.deviceId,Fs({deviceId:w,pid:process.pid}),Yd({patToken:te,env:q.env}).catch(Ue=>G.warn("coze-cli setup error (ignored)",{err:String(Ue)}));let Er=new ks({handshake:bt,privatecode:te,...pt?{urlOverride:pt}:{},ppeOverride:ce,getPatTokenForAgent:Ue=>p.agents.get(Ue)?.patToken});return await a.swap(Er,"connect"),g=te,v=Ut,E=ce,S=dt,q.mock_scenario!==void 0&&(p.setMockScenario(q.mock_scenario),G.info("mock scenario set",{scenario:q.mock_scenario})),A||(A=new ds({core:p,getDeviceId:()=>w??"",onTickEnd:()=>K.retryPending().catch(Ue=>G.warn("detailSync.retryPending failed (ignored)",{err:String(Ue)})),onAuthFailures:se})),A.start(),D(),jn&&Ba(t,x).catch(Ue=>G.warn("post-connect-switch auto-revive error (ignored)",{err:String(Ue)})),Cs(te,t).catch(Ue=>G.warn("writePatToken after /connect failed (ignored)",{err:String(Ue)})),G.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}p.registerExtension("_agent/create",async T=>x.createAgent(T.params)),p.registerExtension("_agent/health",async()=>({ok:!0}));let M={},W=new Go({agents:p.agents,modelListCache:d,openclawModelLister:f,paths:t,publishSkillToMarketplace:async T=>{let U=p.agents.get(T.agentId)?.patToken??g;if(!U)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return eg({patToken:U,zip:T.zip,...T.skillId?{skillId:T.skillId}:{},skillName:T.skillName,...T.description?{description:T.description}:{},agentId:T.agentId,...T.accountId?{accountId:T.accountId}:{}},{handshakeBase:S,ppeOverride:E})},disposeAndMarkDisconnected:async(T,U)=>{let q=p.agents.get(T);if(q){await x.cleanupOpenclawSessionProviders(q).catch(ce=>G.warn("cleanup openclaw providers failed (ignored)",{agentId:T,err:String(ce)})),q.framework==="hermes"&&q.deployType==="cloud"&&await Rd(T,t).catch(ce=>G.warn("cleanup hermes-home failed (ignored)",{agentId:T,err:String(ce)}));let te=!0;try{await q.dispose(`disconnect: ${U}`)}catch(ce){te=!1,G.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:T,err:String(ce)}),q.status="error"}te&&(q.status="disconnected",p.unregister(T),p.disconnectedAgents.add(T))}else p.disconnectedAgents.add(T)},disposeForDelete:async(T,U)=>{let q=p.agents.get(T);q&&(await x.cleanupOpenclawSessionProviders(q).catch(te=>G.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:T,err:String(te)})),q.framework==="hermes"&&q.deployType==="cloud"&&await Rd(T,t).catch(te=>G.warn("cleanup hermes-home during delete failed (ignored)",{agentId:T,err:String(te)})),await q.dispose(`delete: ${U}`).catch(te=>G.warn("dispose during delete failed (ignored)",{agentId:T,err:String(te)})),p.unregister(T)),p.disconnectedAgents.delete(T)},detailSyncer:async T=>{if(!M.ref)throw new Error("agent-detail-sync not initialized yet");await M.ref.syncOne(T)},cleanupOpenclawProviders:async(T,U)=>{await x.cleanupOpenclawSessionProviders(T,U)},openclawRepair:async(T,U)=>{await x.openclawRepair(T,U)},hermesReset:async(T,U)=>{let q=await ye(T).catch(()=>null);!q||q.framework!=="hermes"||q.deployType!=="cloud"||await $0({paths:t,agentId:T,model:q.model,modelInfo:q.modelInfo,cozeEnv:U,mockScenario:p.getMockScenario()})},isRuntimePendingPermission:T=>p.hasPendingPermissionFor(T)});p.registerExtension("_agent/listSkills",T=>W.listSkills(T.params)),p.registerExtension("_agent/addSkills",T=>W.addSkills(T.params)),p.registerExtension("_agent/removeSkills",T=>W.removeSkills(T.params)),p.registerExtension("_agent/publishSkill",T=>W.publishSkill(T.params)),p.registerExtension("_agent/getFileTree",T=>W.getFileTree(T.params)),p.registerExtension("_agent/getFileContent",T=>W.getFileContent(T.params)),p.registerExtension("_agent/update",T=>W.updateAgent(T.params)),p.registerExtension("_agent/disconnect",T=>W.disconnectAgent(T.params)),p.registerExtension("_agent/switchModel",T=>W.switchModel(T.params)),p.registerExtension("_agent/setConfigOption",T=>W.setConfigOption(T.params)),p.registerExtension("_agent/listAvailableModels",T=>W.listAvailableModels(T.params)),p.registerExtension("_agent/detail",T=>W.detail(T.params)),p.registerExtension("_agent/reset",T=>W.resetAgent(T.params)),p.registerExtension("_agent/repair",T=>W.repairAgent(T.params)),p.registerExtension("_agent/delete",T=>W.deleteAgent(T.params)),p.registerExtension("_agent/upgrade",T=>W.upgradeBridge(T.params));let K=new js({paths:t,handlers:W,agentManager:x,sendDetail:T=>p.sendRequest("_agent/detail",T)});M.ref=K;let se=async T=>{await Promise.allSettled(T.map(async U=>{try{await W.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),G.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(q){G.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(q)})}}))};a.onConnect(({initial:T})=>{G.info("frontier upstream connected, triggering detail sync",{initial:T}),K.syncAll(T?"initial-connect":"reconnect").catch(U=>G.warn("detail sync top-level error (ignored)",{err:String(U)}))});let Q=new da({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let T=p.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[Ts]==="1"?"manual":"supervisor",agents:[...p.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...T?{mockScenario:T}:{}}}},{method:"POST",path:"/pair",handler:async T=>{let U=T,q=U?.privatecode,te=U?.pairing_code;if(!q||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ce=os(U.env),dt=U.handshake_url,pt=U.frontier_url,Ut=ag(U.env,dt,pt),nn=!!g&&g!==q,En=v!==void 0&&v!==Ut,jn=nn||En,bt=await vd({privatecode:q,...dt?{endpoint:dt}:{},ppeOverride:ce});if(jn){G.warn("pair config switched, resetting agents",{pcChanged:nn,envChanged:En,previousPc:g?Fa(g):"",nextPc:Fa(q),previousEnvKey:v??"",nextEnvKey:Ut});for(let _e of[...p.agents.values()])await _e.dispose("pair config switch").catch(()=>{}),p.agents.delete(_e.agentId);p.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on pair config switch",{count:p.disconnectedAgents.size}),p.disconnectedAgents.clear()),await a.swap(new gi,"pair switch").catch(()=>{})}w=bt.deviceId,Fs({deviceId:w,pid:process.pid}),Yd({patToken:q,env:U.env}).catch(_e=>G.warn("coze-cli setup error (ignored)",{err:String(_e)}));let Er=new ks({handshake:bt,privatecode:q,...pt?{urlOverride:pt}:{},ppeOverride:ce,getPatTokenForAgent:_e=>p.agents.get(_e)?.patToken});await a.swap(Er,"pair");try{let _e=new pr;o.frameworksCache=await _e.detectAll(),await gs(o),G.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(_e){G.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(_e)})}let Ue=Object.keys(o.frameworksCache??{});try{let _e=await p.sendRequest("_agent/pair",{pairCode:te,patToken:q,frameworks:Ue,_meta:{cozeDeviceId:w}});G.info("_agent/pair ok",{pairResult:_e}),g=q,v=Ut,E=ce,S=dt,U.mock_scenario!==void 0&&(p.setMockScenario(U.mock_scenario),G.info("mock scenario set",{scenario:U.mock_scenario})),Cs(q,t).catch(xt=>G.warn("writePatToken after /pair failed (ignored)",{err:String(xt)})),A||(A=new ds({core:p,getDeviceId:()=>w??"",onTickEnd:()=>K.retryPending().catch(xt=>G.warn("detailSync.retryPending failed (ignored)",{err:String(xt)})),onAuthFailures:se})),A.start(),D(),jn&&Ba(t,x).catch(xt=>G.warn("post-pair-switch auto-revive error (ignored)",{err:String(xt)}));let de;return U.agent_id&&(de=await VI(U.agent_id,t,x,xt=>p.sendRequest("_agent/detail",xt),q).catch(xt=>(G.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(xt)}),{ok:!1,agentId:U.agent_id??"",note:String(xt)}))),{ok:!0,note:"paired with cloud",...de?{agent:de}:{}}}catch(_e){return G.error("_agent/pair failed",{err:String(_e)}),{ok:!1,note:`pair failed: ${String(_e)}`}}}},{method:"POST",path:"/connect",handler:T=>R(T)},{method:"POST",path:"/_agent/create",handler:async T=>{let U=T;return{ok:!0,result:await x.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async T=>{let U=T;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!g)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let q=U;return await(q.groupFile?pp:hp)(q,{core:p,patToken:g,handshakeBase:S,ppeOverride:E})}catch(q){if(q instanceof k)return{ok:!1,code:q.code,message:q.message};throw q}}},{method:"POST",path:"/reload",handler:async T=>{let U=T?.agent_id,q=await p.reloadAgents(U);return G.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:q}),{ok:!0,recycled:q}}},{method:"POST",path:"/shutdown",handler:async()=>(G.info("IPC /shutdown received"),setImmediate(()=>{je.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ae,token:le}=await Q.start();try{await ng(t.libEntry,t)}catch(T){G.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(T)})}await p.start(),JI({paths:t,core:p,agentManager:x,detectAll:async()=>(o.frameworksCache=await new pr().detectAll(),await gs(o),o.frameworksCache)}).catch(T=>G.warn("startup warmup error (ignored)",{err:String(T)})),pu().then(async()=>{let{probeAcpVersion:T}=await Promise.resolve().then(()=>(In(),fu));for(let U of["claude-code","codex"]){let q=await T(U);q&&G.info("acp wrapper version",{framework:U,version:q})}}).catch(T=>G.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(T)}));let Se=null,je={port:ae,token:le,core:p,ipc:Q,shutdown(T){return Se||(G.info("daemon shutdown",{reason:T}),Se=(async()=>{A?.stop(),C?.stop(),await p.stop(T),await Q.stop(),await e.release()})(),Se)}};for(let T of["SIGTERM","SIGINT"])process.on(T,()=>{je.shutdown(T).then(()=>process.exit(0))});return process.on("exit",()=>kh()),process.on("unhandledRejection",T=>{G.error("unhandledRejection",{reason:T instanceof Error?T.message:String(T),stack:T instanceof Error?T.stack:void 0})}),process.on("uncaughtException",T=>{G.error("uncaughtException (will exit, supervisor will restart)",{message:T.message,stack:T.stack,name:T.name});try{process.stderr.write(`FATAL uncaughtException: ${T.stack??T.message}
|
|
126
|
+
`)}catch{}process.exit(1)}),G.info("daemon ready",{port:ae,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),YI({cliSpawned:process.env[Ts]==="1",readPatToken:()=>Da(t),connect:R}).catch(T=>G.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(T)})),je}async function KI(t){return Hs(t).length>0}function Fa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function ag(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function $I(t,e){let n=Hs(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(an(),qs));for(let a of n){await o(a,t).catch(d=>G.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),G.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),G.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){G.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(d)})}}}async function VI(t,e,n,i,o){let{loadAgentConfig:a}=await Promise.resolve().then(()=>(an(),qs)),d=await a(t,e);if(d){if(d.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);G.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let x=dg(d),g={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...x?{_meta:x}:{}};return await n.createAgent(g),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}G.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await n.createAgent(f);let p=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:p?"cloud agent acknowledged":"created from cloud detail"}}async function JI(t){let e=t.logger??G;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 $I(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await Ba(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await ZI(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function Ba(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(()=>(an(),qs));G.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(p){G.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(p)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){G.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){G.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{G.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let p=dg(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...p?{_meta:p}:{}},{revive:!0}),a+=1}catch(p){G.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(p)}),d+=1}}return G.info("auto-revive: done",{revived:a,skipped:d,total:i.length}),{revived:a,skipped:d,total:i.length}}async function ZI(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 xh(o,t)).status==="refreshed"&&(i+=1)}catch(a){G.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(a)})}return i>0&&G.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function YI(t){let e=t.logger??G;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 dg(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Ma();De();import{readFile as lg}from"node:fs/promises";var bn=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let n=await za(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:QI(i)}}}async request(e){let n=await za(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:XI(f)}}finally{clearTimeout(d)}}};async function za(t){try{let[e,n]=await Promise.all([lg(t.portFile,"utf8"),lg(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 XI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function QI(t){return t instanceof Error?t.message:String(t)}Vt();re();Ar();import{spawn as eA}from"node:child_process";import{userInfo as fg}from"node:os";var Cl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",tA=new Set(["bash","zsh","sh","dash","ksh"]),ug=Xe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),nA=2e3;function rA(t,e=Cl){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(`
|
|
127
|
+
`)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function iA(){let t=(process.env.SHELL??"").trim()||(fg().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return tA.has(e)?t:null}function sA(t){return new Promise(e=>{let n=`printf '%s' '${Cl}'; env; printf '%s' '${Cl}'`,i;try{i=eA(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??fg().homedir}})}catch{e(null);return}let o="",a=!1,d=x=>{try{i.pid&&process.kill(-i.pid,x)}catch{}},u=x=>{a||(a=!0,clearTimeout(f),clearTimeout(p),e(x))};i.stdout?.on("data",x=>{o+=x.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>d("SIGTERM"),ug),p=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},ug+nA)})}async function Tl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=iA();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??sA)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=rA(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}De();function qn(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}}In();import{chmod as oA,copyFile as hg,mkdir as xg,readFile as Rs,rename as pg,rm as Dl,stat as gg,writeFile as aA}from"node:fs/promises";import{homedir as pM}from"node:os";import{dirname as cA,join as ze,resolve as Ol,sep as Ps}from"node:path";import{fileURLToPath as dA}from"node:url";Vt();re();De();function mi(t,e,n,i){ut(t.bridgeLogsDir,e,"dist-install",n,i)}function mg(){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 lA(){return{darwin:{arm64:ze("vendor","aarch64-apple-darwin","bin","codex"),x64:ze("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:ze("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:ze("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:ze("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:ze("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function uA(t){let e=dA(t),n=cA(e),i=`${Ps}src${Ps}`;if(n.includes(i)||n.endsWith(`${Ps}src${Ps}cli`))return null;let o=Ol(n,"index.js"),a=Ol(n,"..","package.json");return{dist:o,pkgJson:a}}async function Ll(t={}){let e=t.paths??Z(),n=uA(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 E=JSON.parse(await Rs(o,"utf8"));a=E.version??"unknown",d=E.dependencies??{}}catch(E){throw mi(e,"error","cannot read source package.json",{err:String(E)}),new Error(`cannot read source package.json: ${String(E)}`,{cause:E})}let u=zs.map(E=>({name:E,spec:d[E]??"latest"})),f=u.map(({name:E,spec:S})=>`${E}@${S}`),p=await aa(e.configFile)??{},x=p.libVersion,g=await Rs(e.libEntry).then(()=>!0).catch(()=>!1),v=x===a,w=await wg(e,u);if(v&&g&&w)return{kind:"already-current",libVersion:a};if(!v||!g){await xg(e.libDir,{recursive:!0}),await hg(i,e.libEntry),await hg(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=Ol(e.libDir,"package.json"),S=`${JSON.stringify({type:"module"},null,2)}
|
|
128
|
+
`;await Rs(E,"utf8").catch(()=>null)!==S&&await aA(E,S)}return w||(t.installWrappers?await t.installWrappers(e,f):await pA(e,f,u)),p.libVersion=a,await gs(p,e.configFile),mi(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:x,toVersion:a}),v&&g?{kind:"already-current",libVersion:a}:x?{kind:"version-changed",fromVersion:x,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function wg(t,e){for(let n of e){let i=ze(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await Rs(i,"utf8"))}catch(d){return mi(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 mi(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!fA(a,n.spec))return mi(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!!await _g(ze(t.libDir,"node_modules"))}function fA(t,e){let n=Pl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=Pl(i.slice(1));if(!a)return!0;if(Rl(n,a)<0)return!1;let d=hA(a);return Rl(n,d)<0}let o=Pl(i);return o?Rl(n,o)===0:!0}function hA(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function Pl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Rl(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 pA(t,e,n){await mA(t.installLock,async()=>{if(await wg(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${Ps}.staging-${process.pid}-${i}`,a=ze(o,"node_modules"),d=ze(t.libDir,"node_modules");try{await xg(o,{recursive:!0}),await xA(e,o),await gA(a);let u=`${d}.trash-${i}`;await pg(d,u).catch(()=>{}),await pg(a,d),await Dl(u,{recursive:!0,force:!0}).catch(()=>{}),mi(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await Dl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function xA(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=ht("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 gA(t){for(let e of zs){let n=ze(t,...e.split("/")),i=JSON.parse(await Rs(ze(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=ze(t,".bin",o),d=await gg(a);process.platform!=="win32"&&!(d.mode&73)&&await oA(a,d.mode|73).catch(()=>{})}if(!await _g(t)){let e=mg()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function _g(t){let e=mg(),n=lA();if(!e||!n)return!0;let i=ze(t,"@openai","codex"),o=ze(t,...e.split("/")),a=[ze(i,"package.json"),ze(i,"bin","codex.js"),ze(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),ze(o,"package.json"),ze(o,n)];return(await Promise.all(a.map(u=>gg(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function mA(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 Dl(t,{force:!0}).catch(()=>{})}}ic();re();De();import{closeSync as bg,fstatSync as Eg,openSync as vg,readFileSync as wA,readSync as _A,readdirSync as yA,statSync as bA}from"node:fs";import{join as Ua}from"node:path";var EA=new Set(["debug","info","warn","error"]);function Sg(t){let e=t,n=qn(e,"--agent-id");e=n.rest;let i=qn(e,"--date");e=i.rest;let o=qn(e,"-n","--lines");e=o.rest;let a=qn(e,"--level");e=a.rest;let d=qn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,p=a.value&&EA.has(a.value)?a.value:void 0,x={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(x.agentId=n.value),i.value&&(x.date=i.value),p&&(x.level=p),d.value&&(x.grep=d.value),x}function vA(t,e){return t.agentId?Ua(Ne(t.agentId,e).logs,kr("agent",t.date)):Ua(e.bridgeLogsDir,kr("bridge",t.date))}function SA(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function IA(t,e){let n;try{n=yA(t)}catch{return[]}let i=[];for(let o of n){let a=rc(o,e);if(!a)continue;let d=0;try{d=bA(Ua(t,o)).size}catch{}i.push({file:Ua(t,o),date:a,size:d})}return i.sort((o,a)=>a.date.localeCompare(o.date)),i}function Ig(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"&&!au(n,e.level))return!1}return!0}var yg={debug:"90",info:"36",warn:"33",error:"31"},AA=new Set(["ts","level","module","msg"]);function kA(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Ag(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=kA(n.ts),o=typeof n.level=="string"?n.level:"",a=o.toUpperCase().padEnd(5);e.color&&yg[o]&&(a=`\x1B[${yg[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(([p])=>!AA.has(p)).map(([p,x])=>` ${p}=${typeof x=="string"?x:JSON.stringify(x)}`).join("");return`${i} ${a} ${d} ${u}${f}`}function CA(t,e,n){let a=wA(t,"utf8").split(`
|
|
129
|
+
`).filter(d=>d.length>0).filter(d=>Ig(d,{level:e.level,grep:e.grep}));for(let d of SA(a,e.lines))process.stdout.write(`${Ag(d,{raw:e.raw,color:n})}
|
|
130
|
+
`)}async function kg(t,e){let n=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Ne(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=IA(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
|
|
131
|
+
`),1;for(let p of f)process.stdout.write(`${p.date} ${(p.size/1024).toFixed(1)}KB ${p.file}
|
|
132
|
+
`);return 0}let o=t.date??Vn(new Date),a=vA({agentId:t.agentId,date:o},n);try{CA(a,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${a}
|
|
133
133
|
\u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
|
|
134
134
|
(legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
|
|
135
|
-
`),1}return t.follow&&await
|
|
136
|
-
`);o=
|
|
137
|
-
`)}await new Promise(
|
|
135
|
+
`),1}return t.follow&&await RA(a,t,i),0}var TA=500;function PA(t){try{let e=vg(t,"r");try{return Eg(e).size}finally{bg(e)}}catch{return 0}}async function RA(t,e,n){let i=PA(t),o="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let u="";try{let f=vg(t,"r");try{let p=Eg(f).size;if(p>i){let x=Buffer.allocUnsafe(p-i),g=_A(f,x,0,x.length,i);u=x.subarray(0,g).toString("utf8"),i+=g}}finally{bg(f)}}catch{}if(u){let f=(o+u).split(`
|
|
136
|
+
`);o=f.pop()??"";for(let p of f)p.length>0&&Ig(p,{level:e.level,grep:e.grep})&&process.stdout.write(`${Ag(p,{raw:e.raw,color:n})}
|
|
137
|
+
`)}await new Promise(f=>setTimeout(f,TA))}}finally{process.off("SIGINT",d)}}import{basename as DA,resolve as OA}from"node:path";De();var LA=9e4,MA={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,CAPABILITY_UNSUPPORTED: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 NA(t){return MA[t]??1}async function Cg(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
138
|
`),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
|
|
139
|
+
`),3;let i=await za(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.
|
|
140
140
|
`),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:OA(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 FA(i,"/agent/send",o,LA)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
|
|
141
141
|
`),4}if(!a.ok)return process.stderr.write(`Error: ${a.code}: ${a.message}
|
|
142
142
|
`),NA(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
|
|
143
|
-
`);else{let d=t.name??DA(o.path);if(t.groupFile){let
|
|
143
|
+
`);else{let d=t.name??DA(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
144
|
`)}else process.stdout.write(`Sent ${t.kind} ${d} (${BA(a.bytes)})
|
|
145
|
-
`)}return 0}async function FA(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}),
|
|
146
|
-
`)}function ck(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:
|
|
145
|
+
`)}return 0}async function FA(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 BA(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Bg=H("cli");function Ze(t,e){let{value:n,rest:i}=qn(t,e);return{value:n,rest:i}}function Ka(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
|
|
146
|
+
`)}function ck(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:P}=Ze(e.slice(1),"--agent-id");return P?{mode:"reload",agentId:P}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return dk(e.slice(1));if(e[0]==="log")return{mode:"log",...Sg(e.slice(1))};if(e[0]==="connect")return lk(e.slice(1));if(e.includes("--status"))return Ka("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ka("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ka("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ka("--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:p,rest:x}=Ze(n,"--handshake-url");n=x;let{value:g,rest:v}=Ze(n,"--frontier-url");n=v;let{value:w,rest:E}=Ze(n,"--mock-scenario");n=E;let{value:S}=Ze(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!a)return{mode:"help"};let C={mode:"pair",privatecode:i,pairingCode:a};return u&&(C.env=u),p&&(C.handshakeUrl=p),g&&(C.frontierUrl=g),w&&(C.mockScenario=w),S&&(C.agentId=S),A&&(C.skipRebuildEnv=!0),C}function dk(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:p}=Ze(i,"--agent-id");i=p;let{value:x,rest:g}=Ze(i,"--session-id");i=g;let{value:v,rest:w}=Ze(i,"--mime");i=w;let E=i.includes("--group-file");i=i.filter(C=>C!=="--group-file");let S=i.includes("--json"),A={mode:"send",kind:e,path:n,json:S};return o&&(A.caption=o),d&&(A.name=d),f&&(A.agentId=f),x&&(A.sessionId=x),E&&(A.groupFile=!0),v&&(A.mimeType=v),A}function lk(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:p}=Ze(e,"--frontier-url");e=p;let{value:x,rest:g}=Ze(e,"--mock-scenario");e=g;let v=e.includes("--skip-rebuild-env"),w={mode:"connect"};return n&&(w.privatecode=n),o&&(w.env=o),d&&(w.handshakeUrl=d),f&&(w.frontierUrl=f),x&&(w.mockScenario=x),v&&(w.skipRebuildEnv=!0),w}var uk=`
|
|
147
147
|
coze-bridge - local bridge daemon for cloud Agent Service
|
|
148
148
|
|
|
149
149
|
Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
|
|
@@ -224,52 +224,52 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
|
|
|
224
224
|
|
|
225
225
|
Internal:
|
|
226
226
|
<node> <entry> --daemon daemon mode (OS supervisor only)
|
|
227
|
-
`.trimStart();async function
|
|
228
|
-
`),0;case"daemon":{try{await
|
|
229
|
-
`),1;if(i.kind==="stale")return await
|
|
227
|
+
`.trimStart();async function zg(t=process.argv,e={}){let n=ck(t);switch(n.mode){case"help":return process.stdout.write(uk),0;case"version":return process.stdout.write(`${Jt}
|
|
228
|
+
`),0;case"daemon":{try{await cg()}catch(i){return Bg.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return fk(e);case"stop":return Hg(e);case"reload":return xk(n.agentId,e);case"log":return kg(n,e);case"update":return hk(e);case"purge":return mk(e);case"service-install":return wk(e);case"service-uninstall":return _k(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),yk(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),bk(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return Cg({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 Ug(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 fk(t){let e=t.paths??Z(),n=new bn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
229
|
+
`),1;if(i.kind==="stale")return await Ug(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
230
230
|
`),1;let o=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
|
|
231
231
|
${JSON.stringify(o.body,null,2)}
|
|
232
|
-
`),0}async function
|
|
233
|
-
`)}let
|
|
232
|
+
`),0}async function Hg(t){let e=t.paths??Z(),n=new bn(e),i=t.daemonSweep??(async()=>{let f=Ch();return await Th(f),f}),o=async()=>{t.skipProcessKill||await i(e)},a=await Os(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
|
+
`)}let u=await n.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
|
|
234
234
|
`:`coze-bridge: not running
|
|
235
|
-
`),0;if(
|
|
235
|
+
`),0;if(u.kind==="stale")return await Ug(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
236
236
|
`),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 hk(t){return await
|
|
240
|
-
`),e(1)})})}async function
|
|
237
|
+
`),0}catch(f){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
|
|
238
|
+
`),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
|
|
239
|
+
`),1)}}async function hk(t){return await Hg(t),(t.spawnNpx??pk)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function pk(t){return new Promise(e=>{let n=ht("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)}
|
|
240
|
+
`),e(1)})})}async function xk(t,e){let n=new bn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
|
|
241
241
|
`),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
242
|
`):process.stdout.write(`coze-bridge: reloaded ${a.length} agent(s): ${a.join(", ")||"(none)"}
|
|
243
243
|
`),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
|
|
244
244
|
`),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
|
|
245
|
-
`),1}}async function
|
|
245
|
+
`),1}}async function Os(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(()=>(Mg(),Lg)),i=e(),o=n();return{platform:i.platform,install:a=>i.install(o,a),uninstall:()=>i.uninstall(o)}}async function Gg(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??Ek,a=t.paths??Z();if(n.kind==="connected"){if(!gk(n.body))return n;ut(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=>ut(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await Fg(a.pidFile,o)}let d=t.spawnDaemon??og,u=await Os(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await Ng(e,i,o);if(f.kind==="connected")return f;ut(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){ut(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}ut(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 Fg(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
246
|
`));return process.stdout.write(`coze-bridge: starting daemon...
|
|
247
|
-
`),await d({paths:t.paths}),
|
|
247
|
+
`),await d({paths:t.paths}),Ng(e,i,o)}function gk(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 mk(t){let e=new bn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
|
|
248
248
|
`);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
|
|
249
|
+
`)}await new Promise(d=>setTimeout(d,500))}let i=await Os(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
|
|
250
250
|
`)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
|
|
251
251
|
`)}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
252
|
`)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
|
|
253
253
|
`),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
|
|
254
|
-
`),0}async function wk(t){let e=await
|
|
254
|
+
`),0}async function wk(t){let e=await Os(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
|
|
255
255
|
`),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
|
|
256
256
|
`),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
|
|
257
|
-
`),1}}async function _k(t){let e=await
|
|
257
|
+
`),1}}async function _k(t){let e=await Os(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
|
|
258
258
|
`),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
|
|
259
|
-
`),1}}async function qg(t,e,n){if(e)return
|
|
260
|
-
`),
|
|
261
|
-
`),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(
|
|
262
|
-
`)}let
|
|
263
|
-
`),1;let
|
|
259
|
+
`),1}}async function qg(t,e,n){if(e)return ut(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(ut(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(ut(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
|
|
260
|
+
`),ut(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function yk(t,e,n,i={},o,a){let d=new bn(n.paths),u=n.paths??Z(),f=await qg(u,a,n.reconstructEnv??Tl);if(await Ed(u,f).catch(g=>ut(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!n.skipDistInstall){let g=await Ll({paths:n.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
|
|
261
|
+
`),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(w=>setTimeout(w,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
|
|
262
|
+
`)}let p=await Gg(n,d);if(p.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${p.kind}
|
|
263
|
+
`),1;let x={privatecode:t,pairing_code:e};i.env&&(x.env=i.env),i.handshakeUrl&&(x.handshake_url=i.handshakeUrl),i.frontierUrl&&(x.frontier_url=i.frontierUrl),i.mockScenario&&(x.mock_scenario=i.mockScenario),o&&(x.agent_id=o);try{let g=await d.request({method:"POST",path:"/pair",body:x,timeoutMs:35e3});if(g.status===200&&g.body?.ok){let v=g.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
|
|
264
264
|
`),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
|
-
`),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(
|
|
266
|
-
`),1}catch(
|
|
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
|
|
271
|
-
`),t!==void 0&&await
|
|
272
|
-
`),1)}catch(
|
|
273
|
-
`),1}}async function
|
|
274
|
-
`),n(1)}
|
|
265
|
+
`),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(g.body)}
|
|
266
|
+
`),1}catch(g){return process.stderr.write(`coze-bridge: pair failed: ${String(g)}
|
|
267
|
+
`),1}}async function bk(t,e,n={},i){let o=e.paths??Z(),a=t??await Da(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 bn(e.paths),u=await qg(o,i,e.reconstructEnv??Tl);if(await Ed(o,u).catch(x=>ut(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(x)})),!e.skipDistInstall){let x=await Ll({paths:e.paths});x.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${x.fromVersion} \u2192 ${x.toVersion}
|
|
268
|
+
`),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):x.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${x.libVersion}
|
|
269
|
+
`)}let f=await Gg(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
|
|
270
|
+
`),1;let p={privatecode:a};n.env&&(p.env=n.env),n.handshakeUrl&&(p.handshake_url=n.handshakeUrl),n.frontierUrl&&(p.frontier_url=n.frontierUrl),n.mockScenario&&(p.mock_scenario=n.mockScenario);try{let x=await d.request({method:"POST",path:"/connect",body:p,timeoutMs:35e3});return x.status===200&&x.body?.ok?(process.stdout.write(`coze-bridge: connected (${x.body.note??"ok"})
|
|
271
|
+
`),t!==void 0&&await Cs(a,o).catch(g=>Bg.warn("writePatToken after connect failed (ignored)",{err:String(g)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(x.body)}
|
|
272
|
+
`),1)}catch(x){return process.stderr.write(`coze-bridge: connect failed: ${String(x)}
|
|
273
|
+
`),1}}async function Ng(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 Fg(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||!hs(u))return;await e(i)}}function Ek(t){return new Promise(e=>setTimeout(e,t))}re();function vk(t){let e=/^v?(\d+)/.exec(t.trim());return e&&Number(e[1])<22?"fatal":"ok"}function jg(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){if(vk(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
|
+
`),n(1)}jg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&su("warn");zg(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
|
|
275
275
|
`),process.exit(1)});
|