coze-bridge 0.3.2-beta.1 → 0.3.3
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 +66 -66
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,25 +5,25 @@ import { dirname as __coze_dirname } from 'node:path';
|
|
|
5
5
|
const require = __coze_createRequire(import.meta.url);
|
|
6
6
|
const __filename = __coze_fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __coze_dirname(__filename);
|
|
8
|
-
var
|
|
8
|
+
var Om=Object.create;var Ja=Object.defineProperty;var Dm=Object.getOwnPropertyDescriptor;var Lm=Object.getOwnPropertyNames;var Mm=Object.getPrototypeOf,Nm=Object.prototype.hasOwnProperty;var pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var it=(t,e)=>()=>(t&&(e=t(t=0)),e);var ue=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Za=(t,e)=>{for(var n in e)Ja(t,n,{get:e[n],enumerable:!0})},Fm=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Lm(e))!Nm.call(t,o)&&o!==n&&Ja(t,o,{get:()=>e[o],enumerable:!(i=Dm(e,o))||i.enumerable});return t};var Xt=(t,e,n)=>(n=t!=null?Om(Mm(t)):{},Fm(e||!t||!t.__esModule?Ja(n,"default",{value:t,enumerable:!0}):n,t));function $e(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var wr=it(()=>{"use strict"});import{createWriteStream as Bm,mkdirSync as zm,readdirSync as Um,unlinkSync as Hm}from"node:fs";import{join as Yl}from"node:path";function Un(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function _r(t,e){return`${t}-${e}.log`}function Ya(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Gm(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 Is(t,e,n,i){let o;try{o=Um(t)}catch{return}for(let a of o){let d=Ya(a,e);if(d&&Gm(d,n,i))try{Hm(Yl(t,a))}catch{}}}var pi,Xa=it(()=>{"use strict";pi=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Un(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{zm(this.dir,{recursive:!0});let n=Bm(Yl(this.dir,_r(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&&Is(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 qm,mkdirSync as
|
|
11
|
-
`;
|
|
12
|
-
`;if(ks){let d=Zm(o,i),u=d?Jm(ks,d):ks.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?$m.write(a):Km.write(a)}function
|
|
13
|
-
`),{cause:a})}}async function tw(t){let e=ec[t];if(e)try{let n=su.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(iu(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){
|
|
14
|
-
`,n)}var Tt=st(()=>{"use strict"});import{promises as lu,readdirSync as fw}from"node:fs";import{homedir as hw}from"node:os";import{sep as xw,join as ke,resolve as uu}from"node:path";function J(t){let e=t??hw(),n=ke(e,".coze"),i=ke(n,"bridge"),o=ke(i,"lib"),a=ke(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:ke(o,"index.js"),binDir:ke(i,"bin"),pidFile:ke(i,"bridge.pid"),portFile:ke(i,"bridge.port"),tokenFile:ke(i,"bridge.token"),patTokenFile:ke(i,"pat-token"),agentEnvFile:ke(i,"agent-env.json"),logFile:ke(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:ke(a,"daemon-stdio.log"),installLock:ke(i,"install.lock"),configFile:ke(i,"config.json"),modelCacheFile:ke(i,"model-cache.json"),agentsRoot:ke(n,"agents")}}function Re(t,e=J()){let n=ke(e.agentsRoot,t);return{root:n,config:ke(n,"config.json"),workspace:ke(n,"workspace"),logs:ke(n,"logs")}}function Ds(t=J()){try{return fw(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function mi(t,e){let n=await lu.realpath(uu(t)).catch(()=>null);if(!n)return!1;let i=await lu.realpath(uu(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+xw)}var Te=st(()=>{"use strict"});var Ls={};Za(Ls,{AGENT_CONFIG_FILE_MODE:()=>Os,enforceAgentConfigMode:()=>mw,loadAgentConfig:()=>me,persistAgentSessions:()=>wi,persistAgentSkills:()=>_i,saveAgentConfig:()=>Ce});import{chmod as pw,stat as gw}from"node:fs/promises";function me(t,e){return Ye(Re(t,e).config)}function Ce(t,e){return ft(Re(t.agentId,e).config,t,{mode:Os})}async function mw(t,e){if(process.platform==="win32")return;let n=Re(t,e).config;try{let i=await gw(n);if(!i.isFile())return;let o=i.mode&511;o!==Os&&(await pw(n,Os),fu.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;fu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function wi(t,e,n){let i=await me(t,n);i&&(i.sessions=Object.fromEntries(e),await Ce(i,n))}async function _i(t,e,n){let i=await me(t,n);i&&(i.skills=e,await Ce(i,n))}var fu,Os,en=st(()=>{"use strict";Tt();ne();Te();fu=H("agent-config"),Os=384});var sc=le((s2,pu)=>{pu.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 Ns=le(mu=>{var gu={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 vw(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(gu))mu[t]=vw(gu[t])});var Eu=le((a2,bu)=>{var Sw=pe("fs"),Ne=pe("path"),wu=sc(),Iw=Ns(),Aw=typeof process=="object"&&process.platform==="win32",_u=t=>typeof t=="object"&&t!==null,yu=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 Se(t){this.sep=Ne.sep,this.fs=Sw,_u(t)&&_u(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}bu.exports=Se;Se.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 Iw.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};Se.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=Ne.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Se.prototype.writeFileToAsync=function(t,e,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 h=Ne.dirname(t);a.fs.exists(h,function(p){p||a.makeDir(h),a.fs.open(t,"w",438,function(g,y){g?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(_,b){a.fs.write(b,e,0,e.length,0,function(){a.fs.close(b,function(){a.fs.chmod(t,i||438,function(){o(!0)})})})})}):y?a.fs.write(y,e,0,e.length,0,function(){a.fs.close(y,function(){a.fs.chmod(t,i||438,function(){o(!0)})})}):a.fs.chmod(t,i||438,function(){o(!0)})})})})})};Se.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=Ne.join(i,u),h=e.fs.statSync(f);(!o||o.test(f))&&d.push(Ne.normalize(f)+(h.isDirectory()?e.sep:"")),h.isDirectory()&&a&&(d=d.concat(n(f,o,a)))}),d}return n(t,void 0,!0)};Se.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=Ne.join(t,u),n.fs.stat(u,function(f,h){if(f)return e(f);h&&(i.push(Ne.normalize(u)+(h.isDirectory()?n.sep:"")),h.isDirectory()?n.findFilesAsync(u,function(p,g){if(p)return e(p);i=i.concat(g),--d||e(null,i)}):--d||e(null,i))})})})};Se.prototype.getAttributes=function(){};Se.prototype.setAttributes=function(){};Se.crc32update=function(t,e){return yu[(t^e)&255]^t>>>8};Se.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Se.crc32update(n,t[i++]);return~n>>>0};Se.methodToString=function(t){switch(t){case wu.STORED:return"STORED ("+t+")";case wu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Se.canonical=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.join(".",e)};Se.zipnamefix=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.posix.join(".",e)};Se.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let i=n-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Se.sanitize=function(t,e){t=Ne.resolve(Ne.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var a=Ne.normalize(Ne.join(t,n.slice(i,o).join(Ne.sep)));if(a.indexOf(t)===0)return a}return Ne.normalize(Ne.join(t,Ne.basename(e)))};Se.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Se.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Se.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Se.fromDate2DOS=function(t){let e=0,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};Se.isWin=Aw;Se.crcTable=yu});var Su=le((c2,vu)=>{var kw=pe("path");vu.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=kw.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 Au=le((d2,Iu)=>{Iu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var Ir=le((l2,Sr)=>{Sr.exports=Eu();Sr.exports.Constants=sc();Sr.exports.Errors=Ns();Sr.exports.FileAttr=Su();Sr.exports.decoder=Au()});var Tu=le((u2,ku)=>{var yn=Ir(),F=yn.Constants;ku.exports=function(){var t=20,e=10,n=0,i=0,o=0,a=0,d=0,u=0,f=0,h=0,p=0,g=0,y=0,_=0,b=0;t|=yn.isWin?2560:768,n|=F.FLG_EFS;let I={extraLen:0},k=E=>Math.max(0,E)>>>0,C=E=>Math.max(0,E)&65535,D=E=>Math.max(0,E)&255;return o=yn.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&F.FLG_EFS)>0},set flags_efs(E){E?n|=F.FLG_EFS:n&=~F.FLG_EFS},get flags_desc(){return(n&F.FLG_DESC)>0},set flags_desc(E){E?n|=F.FLG_DESC:n&=~F.FLG_DESC},get method(){return i},set method(E){switch(E){case F.STORED:this.version=10;case F.DEFLATED:default:this.version=20}i=E},get time(){return yn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=yn.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=k(E)},get timeHighByte(){return D(o>>>8)},get crc(){return a},set crc(E){a=k(E)},get compressedSize(){return d},set compressedSize(E){d=k(E)},get size(){return u},set size(E){u=k(E)},get fileNameLength(){return f},set fileNameLength(E){f=E},get extraLength(){return h},set extraLength(E){h=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return p},set commentLength(E){p=E},get diskNumStart(){return g},set diskNumStart(E){g=k(E)},get inAttr(){return y},set inAttr(E){y=k(E)},get attr(){return _},set attr(E){_=k(E)},get fileAttr(){return(_||0)>>16&4095},get offset(){return b},set offset(E){b=k(E)},get encrypted(){return(n&F.FLG_ENC)===F.FLG_ENC},get centralHeaderSize(){return F.CENHDR+f+h+p},get realDataOffset(){return b+F.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var O=E.slice(b,b+F.LOCHDR);if(O.readUInt32LE(0)!==F.LOCSIG)throw yn.Errors.INVALID_LOC();I.version=O.readUInt16LE(F.LOCVER),I.flags=O.readUInt16LE(F.LOCFLG),I.flags_desc=(I.flags&F.FLG_DESC)>0,I.method=O.readUInt16LE(F.LOCHOW),I.time=O.readUInt32LE(F.LOCTIM),I.crc=O.readUInt32LE(F.LOCCRC),I.compressedSize=O.readUInt32LE(F.LOCSIZ),I.size=O.readUInt32LE(F.LOCLEN),I.fnameLen=O.readUInt16LE(F.LOCNAM),I.extraLen=O.readUInt16LE(F.LOCEXT);let L=b+F.LOCHDR+I.fnameLen,z=L+I.extraLen;return E.slice(L,z)},loadFromBinary:function(E){if(E.length!==F.CENHDR||E.readUInt32LE(0)!==F.CENSIG)throw yn.Errors.INVALID_CEN();t=E.readUInt16LE(F.CENVEM),e=E.readUInt16LE(F.CENVER),n=E.readUInt16LE(F.CENFLG),i=E.readUInt16LE(F.CENHOW),o=E.readUInt32LE(F.CENTIM),a=E.readUInt32LE(F.CENCRC),d=E.readUInt32LE(F.CENSIZ),u=E.readUInt32LE(F.CENLEN),f=E.readUInt16LE(F.CENNAM),h=E.readUInt16LE(F.CENEXT),p=E.readUInt16LE(F.CENCOM),g=E.readUInt16LE(F.CENDSK),y=E.readUInt16LE(F.CENATT),_=E.readUInt32LE(F.CENATX),b=E.readUInt32LE(F.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(F.LOCHDR);return E.writeUInt32LE(F.LOCSIG,0),E.writeUInt16LE(e,F.LOCVER),E.writeUInt16LE(n,F.LOCFLG),E.writeUInt16LE(i,F.LOCHOW),E.writeUInt32LE(o,F.LOCTIM),E.writeUInt32LE(a,F.LOCCRC),E.writeUInt32LE(d,F.LOCSIZ),E.writeUInt32LE(u,F.LOCLEN),E.writeUInt16LE(f,F.LOCNAM),E.writeUInt16LE(I.extraLen,F.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(F.CENHDR+f+h+p);return E.writeUInt32LE(F.CENSIG,0),E.writeUInt16LE(t,F.CENVEM),E.writeUInt16LE(e,F.CENVER),E.writeUInt16LE(n,F.CENFLG),E.writeUInt16LE(i,F.CENHOW),E.writeUInt32LE(o,F.CENTIM),E.writeUInt32LE(a,F.CENCRC),E.writeUInt32LE(d,F.CENSIZ),E.writeUInt32LE(u,F.CENLEN),E.writeUInt16LE(f,F.CENNAM),E.writeUInt16LE(h,F.CENEXT),E.writeUInt16LE(p,F.CENCOM),E.writeUInt16LE(g,F.CENDSK),E.writeUInt16LE(y,F.CENATT),E.writeUInt32LE(_,F.CENATX),E.writeUInt32LE(b,F.CENOFF),E},toJSON:function(){let E=function(O){return O+" bytes"};return{made:t,version:e,flags:n,method:yn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(f),extraLength:E(h),commentLength:E(p),diskNumStart:g,inAttr:y,attr:_,offset:b,centralHeaderSize:E(F.CENHDR+f+h+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Pu=le((f2,Cu)=>{var Ar=Ir(),be=Ar.Constants;Cu.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 be.ENDHDR+o},loadFromBinary:function(a){if((a.length!==be.ENDHDR||a.readUInt32LE(0)!==be.ENDSIG)&&(a.length<be.ZIP64HDR||a.readUInt32LE(0)!==be.ZIP64SIG))throw Ar.Errors.INVALID_END();a.readUInt32LE(0)===be.ENDSIG?(t=a.readUInt16LE(be.ENDSUB),e=a.readUInt16LE(be.ENDTOT),n=a.readUInt32LE(be.ENDSIZ),i=a.readUInt32LE(be.ENDOFF),o=a.readUInt16LE(be.ENDCOM)):(t=Ar.readBigUInt64LE(a,be.ZIP64SUB),e=Ar.readBigUInt64LE(a,be.ZIP64TOT),n=Ar.readBigUInt64LE(a,be.ZIP64SIZE),i=Ar.readBigUInt64LE(a,be.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(be.ENDHDR+o);return a.writeUInt32LE(be.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,be.ENDSUB),a.writeUInt16LE(e,be.ENDTOT),a.writeUInt32LE(n,be.ENDSIZ),a.writeUInt32LE(i,be.ENDOFF),a.writeUInt16LE(o,be.ENDCOM),a.fill(" ",be.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 ac=le(oc=>{oc.EntryHeader=Tu();oc.MainHeader=Pu()});var Du=le((x2,Ru)=>{Ru.exports=function(t){var e=pe("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var o=e.createDeflateRaw(n),a=[],d=0;o.on("data",function(u){a.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),f=0;u.fill(0);for(var h=0;h<a.length;h++){var p=a[h];p.copy(u,f),f+=p.length}i&&i(u)}),o.end(t)}}}});var Lu=le((p2,Ou)=>{var Tw=+(process.versions?process.versions.node:"").split(".")[0]||0;Ou.exports=function(t,e){var n=pe("zlib");let i=Tw>=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),h=0;f.fill(0);for(var p=0;p<d.length;p++){var g=d[p];g.copy(f,h),h+=g.length}o&&o(f)}),a.end(t)}}}});var zu=le((g2,Fu)=>{"use strict";var{randomFillSync:Mu}=pe("crypto"),Cw=Ns(),Pw=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}),Bu=(t,e)=>Math.imul(t,e)>>>0,Nu=(t,e)=>Pw[(t^e)&255]^t>>>8,yi=()=>typeof Mu=="function"?Mu(Buffer.alloc(12)):yi.node();yi.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 Bs={genSalt:yi};function Fs(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])}Fs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Nu(e[0],t),e[1]+=e[0]&255,e[1]=Bu(e[1],134775813)+1,e[2]=Nu(e[2],e[1]>>>24),t};Fs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Bu(t,t^1)>>8&255};function Rw(t){let e=new Fs(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 Dw(t){let e=new Fs(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 Ow(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Rw(n),o=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==a)throw Cw.WRONG_PASSWORD();return i(t.slice(12))}function Lw(t){Buffer.isBuffer(t)&&t.length>=12?Bs.genSalt=function(){return t.slice(0,12)}:t==="node"?Bs.genSalt=yi.node:Bs.genSalt=yi}function Mw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Dw(n),a=Bs.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)}Fu.exports={decrypt:Ow,encrypt:Mw,_salter:Lw}});var Uu=le(zs=>{zs.Deflater=Du();zs.Inflater=Lu();zs.ZipCrypto=zu()});var dc=le((w2,Hu)=>{var ue=Ir(),Nw=ac(),Ie=ue.Constants,cc=Uu();Hu.exports=function(t,e){var n=new Nw.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),h=!0;let p=t,g=typeof p.decoder=="object"?p.decoder:ue.decoder;h=g.hasOwnProperty("efs")?g.efs:!1;function y(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(ue.crc32(E)!==n.localHeader.crc)return!1}else{let O={},L=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(L)==Ie.LOCSIG||e.readUInt32LE(L)==Ie.CENSIG)throw ue.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(L)==Ie.EXTSIG)O.crc=e.readUInt32LE(L+Ie.EXTCRC),O.compressedSize=e.readUInt32LE(L+Ie.EXTSIZ),O.size=e.readUInt32LE(L+Ie.EXTLEN);else if(e.readUInt16LE(L+12)===19280)O.crc=e.readUInt32LE(L+Ie.EXTCRC-4),O.compressedSize=e.readUInt32LE(L+Ie.EXTSIZ-4),O.size=e.readUInt32LE(L+Ie.EXTLEN-4);else throw ue.Errors.DESCRIPTOR_UNKNOWN();if(O.compressedSize!==n.compressedSize||O.size!==n.size||O.crc!==n.crc)throw ue.Errors.DESCRIPTOR_FAULTY();if(ue.crc32(E)!==O.crc)return!1}return!0}function b(E,O,L){if(typeof O>"u"&&typeof E=="string"&&(L=E,E=void 0),a)return E&&O&&O(Buffer.alloc(0),ue.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var z=y();if(z.length===0)return E&&O&&O(z),z;if(n.encrypted){if(typeof L!="string"&&!Buffer.isBuffer(L))throw ue.Errors.INVALID_PASS_PARAM();z=cc.ZipCrypto.decrypt(z,n,L)}var M=Buffer.alloc(n.size);switch(n.method){case ue.Constants.STORED:if(z.copy(M),_(M))return E&&O&&O(M),M;throw E&&O&&O(M,ue.Errors.BAD_CRC()),ue.Errors.BAD_CRC();case ue.Constants.DEFLATED:var K=new cc.Inflater(z,n.size);if(E)K.inflateAsync(function($){$.copy($,0),O&&(_($)?O($):O($,ue.Errors.BAD_CRC()))});else{if(K.inflate(M).copy(M,0),!_(M))throw ue.Errors.BAD_CRC(`"${g.decode(i)}"`);return M}break;default:throw E&&O&&O(Buffer.alloc(0),ue.Errors.UNKNOWN_METHOD()),ue.Errors.UNKNOWN_METHOD()}}function I(E,O){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&O&&O(y()),y();if(d.length&&!a){var L;switch(n.method){case ue.Constants.STORED:return n.compressedSize=n.size,L=Buffer.alloc(d.length),d.copy(L),E&&O&&O(L),L;default:case ue.Constants.DEFLATED:var z=new cc.Deflater(d);if(E)z.deflateAsync(function(K){L=Buffer.alloc(K.length),n.compressedSize=K.length,K.copy(L),O&&O(L)});else{var M=z.deflate();return n.compressedSize=M.length,M}z=null;break}}else if(E&&O)O(Buffer.alloc(0));else return Buffer.alloc(0)}function k(E,O){return ue.readBigUInt64LE(E,O)}function C(E){try{for(var O=0,L,z,M;O+4<E.length;)L=E.readUInt16LE(O),O+=2,z=E.readUInt16LE(O),O+=2,M=E.slice(O,O+z),O+=z,Ie.ID_ZIP64===L&&D(M)}catch{throw ue.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(E){var O,L,z,M;E.length>=Ie.EF_ZIP64_SCOMP&&(O=k(E,Ie.EF_ZIP64_SUNCOMP),n.size===Ie.EF_ZIP64_OR_32&&(n.size=O)),E.length>=Ie.EF_ZIP64_RHO&&(L=k(E,Ie.EF_ZIP64_SCOMP),n.compressedSize===Ie.EF_ZIP64_OR_32&&(n.compressedSize=L)),E.length>=Ie.EF_ZIP64_DSN&&(z=k(E,Ie.EF_ZIP64_RHO),n.offset===Ie.EF_ZIP64_OR_32&&(n.offset=z)),E.length>=Ie.EF_ZIP64_DSN+4&&(M=E.readUInt32LE(Ie.EF_ZIP64_DSN),n.diskNumStart===Ie.EF_ZIP64_OR_16&&(n.diskNumStart=M))}return{get entryName(){return g.decode(i)},get rawEntryName(){return i},set entryName(E){i=ue.toBuffer(E,g.encode);var O=i[i.length-1];a=O===47||O===92,n.fileNameLength=i.length},get efs(){return typeof h=="function"?h(this.entryName):h},get extra(){return u},set extra(E){u=E,n.extraLength=E.length,C(E)},get comment(){return g.decode(o)},set comment(E){if(o=ue.toBuffer(E,g.encode),n.commentLength=o.length,o.length>65535)throw ue.Errors.COMMENT_TOO_LONG()},get name(){var E=g.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:b(!1,null,E)},getDataAsync:function(E,O){n.changed?E(d):b(!0,E,O)},set attr(E){n.attr=E},get attr(){return n.attr},set header(E){n.loadFromBinary(E)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var E=n.centralHeaderToBinary(),O=ue.Constants.CENHDR;return i.copy(E,O),O+=i.length,u.copy(E,O),O+=n.extraLength,o.copy(E,O),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=f.length;let O=n.localHeaderToBinary(),L=Buffer.alloc(O.length+i.length+n.extraLocalLength);return O.copy(L,E),E+=O.length,i.copy(L,E),E+=i.length,f.copy(L,E),E+=f.length,L},toJSON:function(){let E=function(O){return"<"+(O&&O.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 Wu=le((_2,qu)=>{var Gu=dc(),Bw=ac(),Ve=Ir();qu.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),a=new Bw.MainHeader,d=!1,u=null;let f=new Set,h=e,{noSort:p,decoder:g}=h;t?b(h.readEntries):d=!0;function y(){let k=new Set;for(let C of Object.keys(i)){let D=C.split("/");if(D.pop(),!!D.length)for(let E=0;E<D.length;E++){let O=D.slice(0,E+1).join("/")+"/";k.add(O)}}for(let C of k)if(!(C in i)){let D=new Gu(h);D.entryName=C,D.attr=16,D.temporary=!0,n.push(D),i[D.entryName]=D,f.add(D)}}function _(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Ve.Constants.CENHDR)throw Ve.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var k=a.offset,C=0;C<n.length;C++){var D=k,E=new Gu(h,t);E.header=t.slice(D,D+=Ve.Constants.CENHDR),E.entryName=t.slice(D,D+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(D,D+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(D,D+E.header.commentLength)),k+=E.header.centralHeaderSize,n[C]=E,i[E.entryName]=E}f.clear(),y()}function b(k){var C=t.length-Ve.Constants.ENDHDR,D=Math.max(0,C-65535),E=D,O=t.length,L=-1,z=0;for(typeof h.trailingSpace=="boolean"&&h.trailingSpace&&(D=0),C;C>=E;C--)if(t[C]===80){if(t.readUInt32LE(C)===Ve.Constants.ENDSIG){L=C,z=C,O=C+Ve.Constants.ENDHDR,E=C-Ve.Constants.END64HDR;continue}if(t.readUInt32LE(C)===Ve.Constants.END64SIG){E=D;continue}if(t.readUInt32LE(C)===Ve.Constants.ZIP64SIG){L=C,O=C+Ve.readBigUInt64LE(t,C+Ve.Constants.ZIP64SIZE)+Ve.Constants.ZIP64LEAD;break}}if(L==-1)throw Ve.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(L,O)),a.commentLength&&(o=t.slice(z+Ve.Constants.ENDHDR)),k&&_()}function I(){n.length>1&&!p&&n.sort((k,C)=>k.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(k=>!f.has(k))},get comment(){return g.decode(o)},set comment(k){o=Ve.toBuffer(k,g.encode),a.commentLength=o.length},getEntryCount:function(){return d?n.length:a.diskEntries},forEach:function(k){this.entries.forEach(k)},getEntry:function(k){return d||_(),i[k]||null},setEntry:function(k){d||_(),n.push(k),i[k.entryName]=k,a.totalEntries=n.length},deleteFile:function(k,C=!0){d||_();let D=i[k];this.getEntryChildren(D,C).map(O=>O.entryName).forEach(this.deleteEntry)},deleteEntry:function(k){d||_();let C=i[k],D=n.indexOf(C);D>=0&&(n.splice(D,1),delete i[k],a.totalEntries=n.length)},getEntryChildren:function(k,C=!0){if(d||_(),typeof k=="object")if(k.isDirectory&&C){let D=[],E=k.entryName;for(let O of n)O.entryName.startsWith(E)&&D.push(O);return D}else return[k];return[]},getChildCount:function(k){if(k&&k.isDirectory){let C=this.getEntryChildren(k);return C.includes(k)?C.length-1:C.length}return 0},compressToBuffer:function(){d||_(),I();let k=[],C=[],D=0,E=0;a.size=0,a.offset=0;let O=0;for(let M of this.entries){let K=M.getCompressedData();M.header.offset=E;let $=M.packLocalHeader(),ie=$.length+K.length;E+=ie,k.push($),k.push(K);let X=M.packCentralHeader();C.push(X),a.size+=X.length,D+=ie+X.length,O++}D+=a.mainHeaderSize,a.offset=E,a.totalEntries=O,E=0;let L=Buffer.alloc(D);for(let M of k)M.copy(L,E),E+=M.length;for(let M of C)M.copy(L,E),E+=M.length;let z=a.toBinary();return o&&o.copy(z,Ve.Constants.ENDHDR),z.copy(L,E),t=L,d=!1,L},toAsyncBuffer:function(k,C,D,E){try{d||_(),I();let O=[],L=[],z=0,M=0,K=0;a.size=0,a.offset=0;let $=function(ie){if(ie.length>0){let X=ie.shift(),oe=X.entryName+X.extra.toString();D&&D(oe),X.getCompressedDataAsync(function(de){E&&E(oe),X.header.offset=M;let ye=X.packLocalHeader(),ze=ye.length+de.length;M+=ze,O.push(ye),O.push(de);let R=X.packCentralHeader();L.push(R),a.size+=R.length,z+=ze+R.length,K++,$(ie)})}else{z+=a.mainHeaderSize,a.offset=M,a.totalEntries=K,M=0;let X=Buffer.alloc(z);O.forEach(function(de){de.copy(X,M),M+=de.length}),L.forEach(function(de){de.copy(X,M),M+=de.length});let oe=a.toBinary();o&&o.copy(oe,Ve.Constants.ENDHDR),oe.copy(X,M),t=X,d=!1,k(X)}};$(Array.from(this.entries))}catch(O){C(O)}}}}});var $u=le((y2,Ku)=>{var ve=Ir(),Ee=pe("path"),Fw=dc(),zw=Wu(),Hn=(...t)=>ve.findLast(t,e=>typeof e=="boolean"),ju=(...t)=>ve.findLast(t,e=>typeof e=="string"),Uw=(...t)=>ve.findLast(t,e=>typeof e=="function"),Hw={noSort:!1,readEntries:!1,method:ve.Constants.NONE,fs:null};Ku.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),Hw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=ve.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new ve(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=ve.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=ve.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw ve.Errors.INVALID_FILENAME();let a=new zw(n,i),{canonical:d,sanitize:u,zipnamefix:f}=ve;function h(_){if(_&&a){var b;if(typeof _=="string"&&(b=a.getEntry(Ee.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(b=a.getEntry(_.entryName)),b)return b}return null}function p(_){let{join:b,normalize:I,sep:k}=Ee.posix;return b(Ee.isAbsolute(_)?"/":".",I(k+_.split("\\").join(k)+k))}function g(_){return _ instanceof RegExp?(function(b){return function(I){return b.test(I)}})(_):typeof _!="function"?()=>!0:_}let y=(_,b)=>{let I=b.slice(-1);return I=I===o.sep?o.sep:"",Ee.relative(_,b)+I};return{readFile:function(_,b){var I=h(_);return I&&I.getData(b)||null},childCount:function(_){let b=h(_);if(b)return a.getChildCount(b)},readFileAsync:function(_,b){var I=h(_);I?I.getDataAsync(b):b(null,"getEntry failed for:"+_)},readAsText:function(_,b){var I=h(_);if(I){var k=I.getData();if(k&&k.length)return k.toString(b||"utf8")}return""},readAsTextAsync:function(_,b,I){var k=h(_);k?k.getDataAsync(function(C,D){if(D){b(C,D);return}C&&C.length?b(C.toString(I||"utf8")):b("")}):b("")},deleteFile:function(_,b=!0){var I=h(_);I&&a.deleteFile(I.entryName,b)},deleteEntry:function(_){var b=h(_);b&&a.deleteEntry(b.entryName)},addZipComment:function(_){a.comment=_},getZipComment:function(){return a.comment||""},addZipEntryComment:function(_,b){var I=h(_);I&&(I.comment=b)},getZipEntryComment:function(_){var b=h(_);return b&&b.comment||""},updateFile:function(_,b){var I=h(_);I&&I.setData(b)},addLocalFile:function(_,b,I,k){if(o.fs.existsSync(_)){b=b?p(b):"";let C=Ee.win32.basename(Ee.win32.normalize(_));b+=I||C;let D=o.fs.statSync(_),E=D.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);D.isDirectory()&&(b+=o.sep),this.addFile(b,E,k,D)}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,b){_=typeof _=="object"?_:{localPath:_};let I=Ee.resolve(_.localPath),{comment:k}=_,{zipPath:C,zipName:D}=_,E=this;o.fs.stat(I,function(O,L){if(O)return b(O,!1);C=C?p(C):"";let z=Ee.win32.basename(Ee.win32.normalize(I));if(C+=D||z,L.isFile())o.fs.readFile(I,function(M,K){return M?b(M,!1):(E.addFile(C,K,k,L),setImmediate(b,void 0,!0))});else if(L.isDirectory())return C+=o.sep,E.addFile(C,Buffer.alloc(0),k,L),setImmediate(b,void 0,!0)})},addLocalFolder:function(_,b,I){if(I=g(I),b=b?p(b):"",_=Ee.normalize(_),o.fs.existsSync(_)){let k=o.findFiles(_),C=this;if(k.length)for(let D of k){let E=Ee.join(b,y(_,D));I(E)&&C.addLocalFile(D,Ee.dirname(E))}}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,b,I,k){k=g(k),I=I?p(I):"",_=Ee.normalize(_);var C=this;o.fs.open(_,"r",function(D){if(D&&D.code==="ENOENT")b(void 0,ve.Errors.FILE_NOT_FOUND(_));else if(D)b(void 0,D);else{var E=o.findFiles(_),O=-1,L=function(){if(O+=1,O<E.length){var z=E[O],M=y(_,z).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),k(M)?o.fs.stat(z,function(K,$){K&&b(void 0,K),$.isFile()?o.fs.readFile(z,function(ie,X){ie?b(void 0,ie):(C.addFile(I+M,X,"",$),L())}):(C.addFile(I+M+"/",Buffer.alloc(0),"",$),L())}):process.nextTick(()=>{L()})}else b(!0,void 0)};L()}})},addLocalFolderAsync2:function(_,b){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=Ee.resolve(p(_.localPath));let{zipPath:k,filter:C,namefix:D}=_;C instanceof RegExp?C=(function(L){return function(z){return L.test(z)}})(C):typeof C!="function"&&(C=function(){return!0}),k=k?p(k):"",D=="latin1"&&(D=L=>L.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=L=>L);let E=L=>Ee.join(k,D(y(localPath,L))),O=L=>Ee.win32.basename(Ee.win32.normalize(D(L)));o.fs.open(localPath,"r",function(L){L&&L.code==="ENOENT"?b(void 0,ve.Errors.FILE_NOT_FOUND(localPath)):L?b(void 0,L):o.findFilesAsync(localPath,function(z,M){if(z)return b(z);M=M.filter(K=>C(E(K))),M.length||b(void 0,!1),setImmediate(M.reverse().reduce(function(K,$){return function(ie,X){if(ie||X===!1)return setImmediate(K,ie,!1);I.addLocalFileAsync({localPath:$,zipPath:Ee.dirname(E($)),zipName:O($)},K)}},b))})})},addLocalFolderPromise:function(_,b){return new Promise((I,k)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},b),(C,D)=>{C&&k(C),D&&I(this)})})},addFile:function(_,b,I,k){_=f(_);let C=h(_),D=C!=null;D||(C=new Fw(i),C.entryName=_),C.comment=I||"";let E=typeof k=="object"&&k instanceof o.fs.Stats;E&&(C.header.time=k.mtime);var O=C.isDirectory?16:0;let L=C.isDirectory?16384:32768;return E?L|=4095&k.mode:typeof k=="number"?L|=4095&k:L|=C.isDirectory?493:420,O=(O|L<<16)>>>0,C.attr=O,C.setData(b),D||a.setEntry(C),C},getEntries:function(_){return a.password=_,a?a.entries:[]},getEntry:function(_){return h(_)},getEntryCount:function(){return a.getEntryCount()},forEach:function(_){return a.forEach(_)},extractEntryTo:function(_,b,I,k,C,D){k=Hn(!1,k),C=Hn(!1,C),I=Hn(!0,I),D=ju(C,D);var E=h(_);if(!E)throw ve.Errors.NO_ENTRY();var O=d(E.entryName),L=u(b,D&&!E.isDirectory?D:I?O:Ee.basename(O));if(E.isDirectory){var z=a.getEntryChildren(E);return z.forEach(function($){if($.isDirectory)return;var ie=$.getData();if(!ie)throw ve.Errors.CANT_EXTRACT_FILE();var X=d($.entryName),oe=u(b,I?X:Ee.basename(X));let de=C?$.header.fileAttr:void 0;o.writeFileTo(oe,ie,k,de)}),!0}var M=E.getData(a.password);if(!M)throw ve.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(L)&&!k)throw ve.Errors.CANT_OVERRIDE();let K=C?_.header.fileAttr:void 0;return o.writeFileTo(L,M,k,K),!0},test:function(_){if(!a)return!1;for(var b in a.entries)try{if(b.isDirectory)continue;var I=a.entries[b].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,b,I,k){if(I=Hn(!1,I),k=ju(I,k),b=Hn(!1,b),!a)throw ve.Errors.NO_ZIP();a.entries.forEach(function(C){var D=u(_,d(C.entryName));if(C.isDirectory){o.makeDir(D);return}var E=C.getData(k);if(!E)throw ve.Errors.CANT_EXTRACT_FILE();let O=I?C.header.fileAttr:void 0;o.writeFileTo(D,E,b,O);try{o.fs.utimesSync(D,C.header.time,C.header.time)}catch{throw ve.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,b,I,k){if(k=Uw(b,I,k),I=Hn(!1,I),b=Hn(!1,b),!k)return new Promise((L,z)=>{this.extractAllToAsync(_,b,I,function(M){M?z(M):L(this)})});if(!a){k(ve.Errors.NO_ZIP());return}_=Ee.resolve(_);let C=L=>u(_,Ee.normalize(d(L.entryName))),D=(L,z)=>new Error(L+': "'+z+'"'),E=[],O=[];a.entries.forEach(L=>{L.isDirectory?E.push(L):O.push(L)});for(let L of E){let z=C(L),M=I?L.header.fileAttr:void 0;try{o.makeDir(z),M&&o.fs.chmodSync(z,M),o.fs.utimesSync(z,L.header.time,L.header.time)}catch{k(D("Unable to create folder",z))}}O.reverse().reduce(function(L,z){return function(M){if(M)L(M);else{let K=Ee.normalize(d(z.entryName)),$=u(_,K);z.getDataAsync(function(ie,X){if(X)L(X);else if(!ie)L(ve.Errors.CANT_EXTRACT_FILE());else{let oe=I?z.header.fileAttr:void 0;o.writeFileToAsync($,ie,b,oe,function(de){de||L(D("Unable to write file",$)),o.fs.utimes($,z.header.time,z.header.time,function(ye){ye?L(D("Unable to set times",$)):L()})})}})}}},k)()},writeZip:function(_,b){if(arguments.length===1&&typeof _=="function"&&(b=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=a.compressToBuffer();if(I){var k=o.writeFileTo(_,I,!0);typeof b=="function"&&b(k?null:new Error("failed"),"")}}},writeZipPromise:function(_,b){let{overwrite:I,perm:k}=Object.assign({overwrite:!0},b);return new Promise((C,D)=>{!_&&i.filename&&(_=i.filename),_||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let O=L=>L?C(L):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,E,I,k,O)},D)})},toBufferPromise:function(){return new Promise((_,b)=>{a.toAsyncBuffer(_,b)})},toBuffer:function(_,b,I,k){return typeof _=="function"?(a.toAsyncBuffer(_,b,I,k),null):a.compressToBuffer()}}}});import{execFile as Zy,spawn as Yy,spawnSync as GT}from"node:child_process";import{promisify as Xy}from"node:util";function eb(t){if(process.platform!=="win32")return!1;if(E0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(E0,"").toLowerCase();return Qy.has(n)}function v0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return eb(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function ct(t,e=[],n={}){return Yy(t,e,v0(t,n))}function ko(t,e=[],n={}){return tb(t,e,v0(t,n))}var Qy,E0,tb,Wt=st(()=>{"use strict";Qy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),E0=/\.(cmd|bat|ps1)$/i;tb=Xy(Zy)});var un=le((pO,Px)=>{"use strict";var Tx=["nodebuffer","arraybuffer","fragments"],Cx=typeof Blob<"u";Cx&&Tx.push("blob");Px.exports={BINARY_TYPES:Tx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Cx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ls=le((gO,ta)=>{"use strict";var{EMPTY_BUFFER:kS}=un(),$d=Buffer[Symbol.species];function TS(t,e){if(t.length===0)return kS;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 $d(n.buffer,n.byteOffset,i):n}function Rx(t,e,n,i,o){for(let a=0;a<o;a++)n[i+a]=t[a]^e[a&3]}function Dx(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function CS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Vd(t){if(Vd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new $d(t):ArrayBuffer.isView(t)?e=new $d(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Vd.readOnly=!1),e}ta.exports={concat:TS,mask:Rx,toArrayBuffer:CS,toBuffer:Vd,unmask:Dx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=pe("bufferutil");ta.exports.mask=function(e,n,i,o,a){a<48?Rx(e,n,i,o,a):t.mask(e,n,i,o,a)},ta.exports.unmask=function(e,n){e.length<32?Dx(e,n):t.unmask(e,n)}}catch{}});var Mx=le((mO,Lx)=>{"use strict";var Ox=Symbol("kDone"),Jd=Symbol("kRun"),Zd=class{constructor(e){this[Ox]=()=>{this.pending--,this[Jd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Jd]()}[Jd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ox])}}};Lx.exports=Zd});var ni=le((wO,zx)=>{"use strict";var us=pe("zlib"),Nx=ls(),PS=Mx(),{kStatusCode:Bx}=un(),RS=Buffer[Symbol.species],DS=Buffer.from([0,0,255,255]),ra=Symbol("permessage-deflate"),fn=Symbol("total-length"),ei=Symbol("callback"),Mn=Symbol("buffers"),ti=Symbol("error"),na,Yd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!na){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;na=new PS(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[ei];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){na.add(o=>{this._decompress(e,n,(a,d)=>{o(),i(a,d)})})}compress(e,n,i){na.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"?us.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=us.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[ra]=this,this._inflate[fn]=0,this._inflate[Mn]=[],this._inflate.on("error",LS),this._inflate.on("data",Fx)}this._inflate[ei]=i,this._inflate.write(e),n&&this._inflate.write(DS),this._inflate.flush(()=>{let a=this._inflate[ti];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=Nx.concat(this._inflate[Mn],this._inflate[fn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[fn]=0,this._inflate[Mn]=[],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"?us.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=us.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[fn]=0,this._deflate[Mn]=[],this._deflate.on("data",OS)}this._deflate[ei]=i,this._deflate.write(e),this._deflate.flush(us.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=Nx.concat(this._deflate[Mn],this._deflate[fn]);n&&(a=new RS(a.buffer,a.byteOffset,a.length-4)),this._deflate[ei]=null,this._deflate[fn]=0,this._deflate[Mn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};zx.exports=Yd;function OS(t){this[Mn].push(t),this[fn]+=t.length}function Fx(t){if(this[fn]+=t.length,this[ra]._maxPayload<1||this[fn]<=this[ra]._maxPayload){this[Mn].push(t);return}this[ti]=new RangeError("Max payload size exceeded"),this[ti].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ti][Bx]=1009,this.removeListener("data",Fx),this.reset()}function LS(t){if(this[ra]._inflate=null,this[ti]){this[ei](this[ti]);return}t[Bx]=1007,this[ei](t)}});var ri=le((_O,ia)=>{"use strict";var{isUtf8:Ux}=pe("buffer"),{hasBlob:MS}=un(),NS=[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 BS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Xd(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 FS(t){return MS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ia.exports={isBlob:FS,isValidStatusCode:BS,isValidUTF8:Xd,tokenChars:NS};if(Ux)ia.exports.isValidUTF8=function(t){return t.length<24?Xd(t):Ux(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=pe("utf-8-validate");ia.exports.isValidUTF8=function(e){return e.length<32?Xd(e):t(e)}}catch{}});var rl=le((yO,$x)=>{"use strict";var{Writable:zS}=pe("stream"),Hx=ni(),{BINARY_TYPES:US,EMPTY_BUFFER:Gx,kStatusCode:HS,kWebSocket:GS}=un(),{concat:Qd,toArrayBuffer:qS,unmask:WS}=ls(),{isValidStatusCode:jS,isValidUTF8:qx}=ri(),sa=Buffer[Symbol.species],It=0,Wx=1,jx=2,Kx=3,el=4,tl=5,oa=6,nl=class extends zS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||US[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[GS]=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 sa(i.buffer,i.byteOffset+e,i.length-e),new sa(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 sa(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 Wx:this.getPayloadLength16(e);break;case jx:this.getPayloadLength64(e);break;case Kx:this.getMask();break;case el:this.getData(e);break;case tl:case oa: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[Hx.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=Wx: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=Kx:this._state=el}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=el}getData(e){let n=Gx;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&WS(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=tl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hx.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=Qd(i,n):this._binaryType==="arraybuffer"?o=qS(Qd(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=It):(this._state=oa,setImmediate(()=>{this.emit("message",o,!0),this._state=It,this.startLoop(e)}))}else{let o=Qd(i,n);if(!this._skipUTF8Validation&&!qx(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===tl||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=It):(this._state=oa,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,Gx),this.end();else{let i=e.readUInt16BE(0);if(!jS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let o=new sa(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!qx(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=oa,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[HS]=o,d}};$x.exports=nl});var ol=le((EO,Zx)=>{"use strict";var{Duplex:bO}=pe("stream"),{randomFillSync:KS}=pe("crypto"),Vx=ni(),{EMPTY_BUFFER:$S,kWebSocket:VS,NOOP:JS}=un(),{isBlob:ii,isValidStatusCode:ZS}=ri(),{mask:Jx,toBuffer:cr}=ls(),At=Symbol("kByteLength"),YS=Buffer.alloc(4),aa=8*1024,dr,si=aa,Mt=0,XS=1,QS=2,il=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=Mt,this.onerror=JS,this[VS]=void 0}static frame(e,n){let i,o=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||YS,n.generateMask?n.generateMask(i):(si===aa&&(dr===void 0&&(dr=Buffer.alloc(aa)),KS(dr,0,aa),si=0),i[0]=dr[si++],i[1]=dr[si++],i[2]=dr[si++],i[3]=dr[si++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[At]!==void 0?u=n[At]:(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 h=Buffer.allocUnsafe(o?u+a:a);return h[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(h[0]|=64),h[1]=f,f===126?h.writeUInt16BE(u,2):f===127&&(h[2]=h[3]=0,h.writeUIntBE(u,4,6)),n.mask?(h[1]|=128,h[a-4]=i[0],h[a-3]=i[1],h[a-2]=i[2],h[a-1]=i[3],d?[h,e]:o?(Jx(e,i,h,a,u),[h]):(Jx(e,i,e,0,u),[h,e])):[h,e]}close(e,n,i,o){let a;if(e===void 0)a=$S;else{if(typeof e!="number"||!ZS(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={[At]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Mt?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):ii(e)?(o=e.size,a=!1):(e=cr(e),o=e.length,a=cr.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};ii(e)?this._state!==Mt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Mt?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):ii(e)?(o=e.size,a=!1):(e=cr(e),o=e.length,a=cr.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};ii(e)?this._state!==Mt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Mt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[Vx.extensionName],a=n.binary?2:1,d=n.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):ii(e)?(u=e.size,f=!1):(e=cr(e),u=e.length,f=cr.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 h={[At]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:f,rsv1:d};ii(e)?this._state!==Mt?this.enqueue([this.getBlobData,e,this._compress,h,i]):this.getBlobData(e,this._compress,h,i):this._state!==Mt?this.enqueue([this.dispatch,e,this._compress,h,i]):this.dispatch(e,this._compress,h,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[At],this._state=QS,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(sl,this,u,o);return}this._bufferedBytes-=i[At];let d=cr(a);n?this.dispatch(d,n,i,o):(this._state=Mt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(a=>{process.nextTick(e1,this,a,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let a=this._extensions[Vx.extensionName];this._bufferedBytes+=i[At],this._state=XS,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");sl(this,f,o);return}this._bufferedBytes-=i[At],this._state=Mt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===Mt&&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)}};Zx.exports=il;function sl(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 e1(t,e,n){sl(t,e,n),t.onerror(e)}});var sp=le((vO,ip)=>{"use strict";var{kForOnEventAttribute:fs,kListener:al}=un(),Yx=Symbol("kCode"),Xx=Symbol("kData"),Qx=Symbol("kError"),ep=Symbol("kMessage"),tp=Symbol("kReason"),oi=Symbol("kTarget"),np=Symbol("kType"),rp=Symbol("kWasClean"),hn=class{constructor(e){this[oi]=null,this[np]=e}get target(){return this[oi]}get type(){return this[np]}};Object.defineProperty(hn.prototype,"target",{enumerable:!0});Object.defineProperty(hn.prototype,"type",{enumerable:!0});var lr=class extends hn{constructor(e,n={}){super(e),this[Yx]=n.code===void 0?0:n.code,this[tp]=n.reason===void 0?"":n.reason,this[rp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Yx]}get reason(){return this[tp]}get wasClean(){return this[rp]}};Object.defineProperty(lr.prototype,"code",{enumerable:!0});Object.defineProperty(lr.prototype,"reason",{enumerable:!0});Object.defineProperty(lr.prototype,"wasClean",{enumerable:!0});var ai=class extends hn{constructor(e,n={}){super(e),this[Qx]=n.error===void 0?null:n.error,this[ep]=n.message===void 0?"":n.message}get error(){return this[Qx]}get message(){return this[ep]}};Object.defineProperty(ai.prototype,"error",{enumerable:!0});Object.defineProperty(ai.prototype,"message",{enumerable:!0});var hs=class extends hn{constructor(e,n={}){super(e),this[Xx]=n.data===void 0?null:n.data}get data(){return this[Xx]}};Object.defineProperty(hs.prototype,"data",{enumerable:!0});var t1={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[fs]&&o[al]===e&&!o[fs])return;let i;if(t==="message")i=function(a,d){let u=new hs("message",{data:d?a:a.toString()});u[oi]=this,ca(e,this,u)};else if(t==="close")i=function(a,d){let u=new lr("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[oi]=this,ca(e,this,u)};else if(t==="error")i=function(a){let d=new ai("error",{error:a,message:a.message});d[oi]=this,ca(e,this,d)};else if(t==="open")i=function(){let a=new hn("open");a[oi]=this,ca(e,this,a)};else return;i[fs]=!!n[fs],i[al]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[al]===e&&!n[fs]){this.removeListener(t,n);break}}};ip.exports={CloseEvent:lr,ErrorEvent:ai,Event:hn,EventTarget:t1,MessageEvent:hs};function ca(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var da=le((SO,op)=>{"use strict";var{tokenChars:xs}=ri();function Jt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function n1(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,a=!1,d,u,f=-1,h=-1,p=-1,g=0;for(;g<t.length;g++)if(h=t.charCodeAt(g),d===void 0)if(p===-1&&xs[h]===1)f===-1&&(f=g);else if(g!==0&&(h===32||h===9))p===-1&&f!==-1&&(p=g);else if(h===59||h===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);p===-1&&(p=g);let _=t.slice(f,p);h===44?(Jt(e,_,n),n=Object.create(null)):d=_,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);else if(u===void 0)if(p===-1&&xs[h]===1)f===-1&&(f=g);else if(h===32||h===9)p===-1&&f!==-1&&(p=g);else if(h===59||h===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);p===-1&&(p=g),Jt(n,t.slice(f,p),!0),h===44&&(Jt(e,d,n),n=Object.create(null),d=void 0),f=p=-1}else if(h===61&&f!==-1&&p===-1)u=t.slice(f,g),f=p=-1;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(o){if(xs[h]!==1)throw new SyntaxError(`Unexpected character at index ${g}`);f===-1?f=g:i||(i=!0),o=!1}else if(a)if(xs[h]===1)f===-1&&(f=g);else if(h===34&&f!==-1)a=!1,p=g;else if(h===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(h===34&&t.charCodeAt(g-1)===61)a=!0;else if(p===-1&&xs[h]===1)f===-1&&(f=g);else if(f!==-1&&(h===32||h===9))p===-1&&(p=g);else if(h===59||h===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);p===-1&&(p=g);let _=t.slice(f,p);i&&(_=_.replace(/\\/g,""),i=!1),Jt(n,u,_),h===44&&(Jt(e,d,n),n=Object.create(null),d=void 0),u=void 0,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);if(f===-1||a||h===32||h===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=g);let y=t.slice(f,p);return d===void 0?Jt(e,y,n):(u===void 0?Jt(n,y,!0):i?Jt(n,u,y.replace(/\\/g,"")):Jt(n,u,y),Jt(e,d,n)),e}function r1(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(", ")}op.exports={format:r1,parse:n1}});var ha=le((kO,wp)=>{"use strict";var i1=pe("events"),s1=pe("https"),o1=pe("http"),dp=pe("net"),a1=pe("tls"),{randomBytes:c1,createHash:d1}=pe("crypto"),{Duplex:IO,Readable:AO}=pe("stream"),{URL:cl}=pe("url"),Nn=ni(),l1=rl(),u1=ol(),{isBlob:f1}=ri(),{BINARY_TYPES:ap,CLOSE_TIMEOUT:h1,EMPTY_BUFFER:la,GUID:x1,kForOnEventAttribute:dl,kListener:p1,kStatusCode:g1,kWebSocket:We,NOOP:lp}=un(),{EventTarget:{addEventListener:m1,removeEventListener:w1}}=sp(),{format:_1,parse:y1}=da(),{toBuffer:b1}=ls(),up=Symbol("kAborted"),ll=[8,13],xn=["CONNECTING","OPEN","CLOSING","CLOSED"],E1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_e=class t extends i1{constructor(e,n,i){super(),this._binaryType=ap[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=la,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]),fp(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ap.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 l1({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new u1(e,this._extensions,i.generateMask);this._receiver=o,this._sender=a,this._socket=e,o[We]=this,a[We]=this,e[We]=this,o.on("conclude",I1),o.on("drain",A1),o.on("error",k1),o.on("message",T1),o.on("ping",C1),o.on("pong",P1),a.onerror=R1,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",pp),e.on("data",fa),e.on("end",gp),e.on("error",mp),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[Nn.extensionName]&&this._extensions[Nn.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())}),xp(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){ul(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||la,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){ul(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||la,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){ul(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Nn.extensionName]||(o.compress=!1),this._sender.send(e||la,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(_e,"CONNECTING",{enumerable:!0,value:xn.indexOf("CONNECTING")});Object.defineProperty(_e.prototype,"CONNECTING",{enumerable:!0,value:xn.indexOf("CONNECTING")});Object.defineProperty(_e,"OPEN",{enumerable:!0,value:xn.indexOf("OPEN")});Object.defineProperty(_e.prototype,"OPEN",{enumerable:!0,value:xn.indexOf("OPEN")});Object.defineProperty(_e,"CLOSING",{enumerable:!0,value:xn.indexOf("CLOSING")});Object.defineProperty(_e.prototype,"CLOSING",{enumerable:!0,value:xn.indexOf("CLOSING")});Object.defineProperty(_e,"CLOSED",{enumerable:!0,value:xn.indexOf("CLOSED")});Object.defineProperty(_e.prototype,"CLOSED",{enumerable:!0,value:xn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_e.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_e.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[dl])return e[p1];return null},set(e){for(let n of this.listeners(t))if(n[dl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[dl]:!0})}})});_e.prototype.addEventListener=m1;_e.prototype.removeEventListener=w1;wp.exports=_e;function fp(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:h1,protocolVersion:ll[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,!ll.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${ll.join(", ")})`);let a;if(e instanceof cl)a=e;else try{a=new cl(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 I=new SyntaxError(f);if(t._redirects===0)throw I;ua(t,I);return}let h=d?443:80,p=c1(16).toString("base64"),g=d?s1.request:o1.request,y=new Set,_;if(o.createConnection=o.createConnection||(d?S1:v1),o.defaultPort=o.defaultPort||h,o.port=a.port||h,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 Nn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=_1({[Nn.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!E1.test(I)||y.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(I)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let b;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:a.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[k,C]of Object.entries(I))i.headers[k.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),b=t._req=g(o),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=g(o);o.timeout&&b.on("timeout",()=>{gt(t,b,"Opening handshake has timed out")}),b.on("error",I=>{b===null||b[up]||(b=t._req=null,ua(t,I))}),b.on("response",I=>{let k=I.headers.location,C=I.statusCode;if(k&&o.followRedirects&&C>=300&&C<400){if(++t._redirects>o.maxRedirects){gt(t,b,"Maximum redirects exceeded");return}b.abort();let D;try{D=new cl(k,e)}catch{let O=new SyntaxError(`Invalid URL: ${k}`);ua(t,O);return}fp(t,D,n,i)}else t.emit("unexpected-response",b,I)||gt(t,b,`Unexpected server response: ${I.statusCode}`)}),b.on("upgrade",(I,k,C)=>{if(t.emit("upgrade",I),t.readyState!==_e.CONNECTING)return;b=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){gt(t,k,"Invalid Upgrade header");return}let E=d1("sha1").update(p+x1).digest("base64");if(I.headers["sec-websocket-accept"]!==E){gt(t,k,"Invalid Sec-WebSocket-Accept header");return}let O=I.headers["sec-websocket-protocol"],L;if(O!==void 0?y.size?y.has(O)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":y.size&&(L="Server sent no subprotocol"),L){gt(t,k,L);return}O&&(t._protocol=O);let z=I.headers["sec-websocket-extensions"];if(z!==void 0){if(!_){gt(t,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=y1(z)}catch{gt(t,k,"Invalid Sec-WebSocket-Extensions header");return}let K=Object.keys(M);if(K.length!==1||K[0]!==Nn.extensionName){gt(t,k,"Server indicated an extension that was not requested");return}try{_.accept(M[Nn.extensionName])}catch{gt(t,k,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Nn.extensionName]=_}t.setSocket(k,C,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(b,t):b.end()}function ua(t,e){t._readyState=_e.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function v1(t){return t.path=t.socketPath,dp.connect(t)}function S1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=dp.isIP(t.host)?"":t.host),a1.connect(t)}function gt(t,e,n){t._readyState=_e.CLOSING;let i=new Error(n);Error.captureStackTrace(i,gt),e.setHeader?(e[up]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ua,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ul(t,e,n){if(e){let i=f1(e)?e.size:b1(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${xn[t.readyState]})`);process.nextTick(n,i)}}function I1(t,e){let n=this[We];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[We]!==void 0&&(n._socket.removeListener("data",fa),process.nextTick(hp,n._socket),t===1005?n.close():n.close(t,e))}function A1(){let t=this[We];t.isPaused||t._socket.resume()}function k1(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",fa),process.nextTick(hp,e._socket),e.close(t[g1])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function cp(){this[We].emitClose()}function T1(t,e){this[We].emit("message",t,e)}function C1(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,lp),e.emit("ping",t)}function P1(t){this[We].emit("pong",t)}function hp(t){t.resume()}function R1(t){let e=this[We];e.readyState!==_e.CLOSED&&(e.readyState===_e.OPEN&&(e._readyState=_e.CLOSING,xp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function xp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function pp(){let t=this[We];if(this.removeListener("close",pp),this.removeListener("data",fa),this.removeListener("end",gp),t._readyState=_e.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",cp),t._receiver.on("finish",cp))}function fa(t){this[We]._receiver.write(t)||this.pause()}function gp(){let t=this[We];t._readyState=_e.CLOSING,t._receiver.end(),this.end()}function mp(){let t=this[We];this.removeListener("error",mp),this.on("error",lp),t&&(t._readyState=_e.CLOSING,this.destroy())}});var Ep=le((CO,bp)=>{"use strict";var TO=ha(),{Duplex:D1}=pe("stream");function _p(t){t.emit("close")}function O1(){!this.destroyed&&this._writableState.finished&&this.destroy()}function yp(t){this.removeListener("error",yp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function L1(t,e){let n=!0,i=new D1({...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(_p,i);return}let d=!1;t.once("error",function(f){d=!0,a(f)}),t.once("close",function(){d||a(o),process.nextTick(_p,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",O1),i.on("error",yp),i}bp.exports=L1});var fl=le((PO,vp)=>{"use strict";var{tokenChars:M1}=ri();function N1(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&&M1[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}vp.exports={parse:N1}});var Pp=le((DO,Cp)=>{"use strict";var B1=pe("events"),xa=pe("http"),{Duplex:RO}=pe("stream"),{createHash:F1}=pe("crypto"),Sp=da(),ur=ni(),z1=fl(),U1=ha(),{CLOSE_TIMEOUT:H1,GUID:G1,kWebSocket:q1}=un(),W1=/^[+/0-9A-Za-z]{22}==$/,Ip=0,Ap=1,Tp=2,hl=class extends B1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:H1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:U1,...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=xa.createServer((i,o)=>{let a=xa.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=j1(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=Ip}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===Tp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ps,this);return}if(e&&this.once("close",e),this._state!==Ap)if(this._state=Ap,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(ps,this):process.nextTick(ps,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ps(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",kp);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){fr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){fr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!W1.test(a)){fr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){fr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){gs(n,400);return}let f=e.headers["sec-websocket-protocol"],h=new Set;if(f!==void 0)try{h=z1.parse(f)}catch{fr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],g={};if(this.options.perMessageDeflate&&p!==void 0){let y=new ur({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Sp.parse(p);_[ur.extensionName]&&(y.accept(_[ur.extensionName]),g[ur.extensionName]=y)}catch{fr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={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(y,(_,b,I,k)=>{if(!_)return gs(n,b||401,I,k);this.completeUpgrade(g,a,h,e,n,i,o)});return}if(!this.options.verifyClient(y))return gs(n,401)}this.completeUpgrade(g,a,h,e,n,i,o)}completeUpgrade(e,n,i,o,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[q1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ip)return gs(a,503);let h=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${F1("sha1").update(n+G1).digest("base64")}`],p=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&&(h.push(`Sec-WebSocket-Protocol: ${g}`),p._protocol=g)}if(e[ur.extensionName]){let g=e[ur.extensionName].params,y=Sp.format({[ur.extensionName]:[g]});h.push(`Sec-WebSocket-Extensions: ${y}`),p._extensions=e}this.emit("headers",h,o),a.write(h.concat(`\r
|
|
10
|
+
`),this.stream=void 0;return}this.currentDate!==void 0&&Is(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 qm,mkdirSync as jm}from"node:fs";import{join as Wm}from"node:path";function Ql(t){let e=t.retentionDays??Vm,n=t.clock??(()=>Un(new Date));ks={bridgeSink:new pi(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new pi(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();Is(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])Is(t.agentLogsDir(o),"agent",i,e)}function Jm(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function eu(t){Qa=t}function tu(t){return yr[Qa]<=yr[t]}function nu(t,e){let n=yr[t];return n===void 0?!0:n>=yr[e]}function Cs(t){Xl={...t}}function ru(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`${Un(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function st(t,e,n,i,o){try{let a=`${JSON.stringify({ts:ru(new Date),level:e,module:n,msg:i,...o})}
|
|
11
|
+
`;jm(t,{recursive:!0}),qm(Wm(t,_r("bridge",Un(new Date))),a)}catch{}}function Zm(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function As(t,e,n,i,o){if(yr[t]<yr[Qa])return;let a=`${JSON.stringify({ts:ru(new Date),level:t,module:e,msg:n,...Xl,...i})}
|
|
12
|
+
`;if(ks){let d=Zm(o,i),u=d?Jm(ks,d):ks.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?$m.write(a):Km.write(a)}function G(t,e){return{debug:(n,i)=>As("debug",t,n,i,e),info:(n,i)=>As("info",t,n,i,e),warn:(n,i)=>As("warn",t,n,i,e),error:(n,i)=>As("error",t,n,i,e),child:n=>G(`${t}.${n}`,e),forAgent:n=>G(t,n)}}var yr,Qa,Km,$m,Xl,Vm,ks,ne=it(()=>{"use strict";wr();Xa();yr={debug:10,info:20,warn:30,error:40},Qa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Km=process.stdout,$m=process.stderr,Xl={},Vm=$e("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ks=null});var k,Ve=it(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,n,i){super(n),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var au={};Za(au,{ACP_WRAPPER_NPM_PACKAGES:()=>Ps,_resetAcpInstallerForTests:()=>nw,_setBinaryPathCacheForTests:()=>rw,buildAcpSpawn:()=>gi,ensureAcpInstalled:()=>Er,getAcpBinaryPath:()=>Rs,pickWhichLine:()=>nc,probeAcpVersion:()=>tw,resolveAcpCommand:()=>ou});import{readFileSync as iu}from"node:fs";import{createRequire as Ym}from"node:module";import{dirname as Xm,resolve as Qm}from"node:path";function tc(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function nc(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 ew(t){let e=su.resolve(`${t.npmPackage}/package.json`),n=Xm(e),i=JSON.parse(iu(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 Qm(n,o)}async function Er(t,e){let n=ec[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=br.get(t);if(i)return i;let o=tc(t);if(o)return br.set(t,o),Ts.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let a=ew(n);return br.set(t,a),Ts.info("acp wrapper resolved",{framework:t,binary:n.binary,path:a}),a}catch(a){throw Ts.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 tw(t){let e=ec[t];if(e)try{let n=su.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(iu(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Ts.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function Rs(t){return br.get(t)}function ou(t,e){if(e)return e;let n=tc(t);if(n)return n;let i=Rs(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 gi(t,e,n){if(e)return{command:e,args:[...n]};let i=tc(t);if(i)return{command:i,args:[...n]};let o=ou(t);return{command:process.execPath,args:[o,...n]}}function nw(){br.clear()}function rw(t,e){br.set(t,e)}var Ts,ec,Ps,su,br,wn=it(()=>{"use strict";Ve();ne();Ts=G("agents.acp-installer"),ec={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Ps=Object.values(ec).filter(t=>t!==void 0).map(t=>t.npmPackage),su=Ym(import.meta.url),br=new Map});import{chmod as sw,mkdir as ow,readFile as aw,rename as cw,rm as dw,writeFile as lw}from"node:fs/promises";import{dirname as uw}from"node:path";async function Ze(t){try{let e=await aw(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function mt(t,e,n){await ow(uw(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await lw(i,e,{encoding:"utf8",mode:n?.mode}),await cw(i,t),n?.mode!==void 0&&await sw(t,n.mode)}catch(o){throw await dw(i,{force:!0}).catch(()=>{}),o}}async function lt(t,e,n){await mt(t,`${JSON.stringify(e,null,2)}
|
|
14
|
+
`,n)}var At=it(()=>{"use strict"});import{promises as lu,readdirSync as fw}from"node:fs";import{homedir as hw}from"node:os";import{sep as xw,join as ke,resolve as uu}from"node:path";function Z(t){let e=t??hw(),n=ke(e,".coze"),i=ke(n,"bridge"),o=ke(i,"lib"),a=ke(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:ke(o,"index.js"),binDir:ke(i,"bin"),pidFile:ke(i,"bridge.pid"),portFile:ke(i,"bridge.port"),tokenFile:ke(i,"bridge.token"),patTokenFile:ke(i,"pat-token"),agentEnvFile:ke(i,"agent-env.json"),logFile:ke(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:ke(a,"daemon-stdio.log"),installLock:ke(i,"install.lock"),configFile:ke(i,"config.json"),modelCacheFile:ke(i,"model-cache.json"),agentsRoot:ke(n,"agents")}}function Oe(t,e=Z()){let n=ke(e.agentsRoot,t);return{root:n,config:ke(n,"config.json"),workspace:ke(n,"workspace"),logs:ke(n,"logs")}}function Os(t=Z()){try{return fw(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function mi(t,e){let n=await lu.realpath(uu(t)).catch(()=>null);if(!n)return!1;let i=await lu.realpath(uu(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+xw)}var Ce=it(()=>{"use strict"});var Ls={};Za(Ls,{AGENT_CONFIG_FILE_MODE:()=>Ds,enforceAgentConfigMode:()=>mw,loadAgentConfig:()=>me,persistAgentSessions:()=>wi,persistAgentSkills:()=>_i,saveAgentConfig:()=>Te});import{chmod as pw,stat as gw}from"node:fs/promises";function me(t,e){return Ze(Oe(t,e).config)}function Te(t,e){return lt(Oe(t.agentId,e).config,t,{mode:Ds})}async function mw(t,e){if(process.platform==="win32")return;let n=Oe(t,e).config;try{let i=await gw(n);if(!i.isFile())return;let o=i.mode&511;o!==Ds&&(await pw(n,Ds),fu.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;fu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function wi(t,e,n){let i=await me(t,n);i&&(i.sessions=Object.fromEntries(e),await Te(i,n))}async function _i(t,e,n){let i=await me(t,n);i&&(i.skills=e,await Te(i,n))}var fu,Ds,Qt=it(()=>{"use strict";At();ne();Ce();fu=G("agent-config"),Ds=384});var sc=ue((s2,pu)=>{pu.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 Ns=ue(mu=>{var gu={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 vw(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(gu))mu[t]=vw(gu[t])});var Eu=ue((a2,bu)=>{var Sw=pe("fs"),Fe=pe("path"),wu=sc(),Iw=Ns(),Aw=typeof process=="object"&&process.platform==="win32",_u=t=>typeof t=="object"&&t!==null,yu=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 Se(t){this.sep=Fe.sep,this.fs=Sw,_u(t)&&_u(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}bu.exports=Se;Se.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 Iw.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};Se.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=Fe.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Se.prototype.writeFileToAsync=function(t,e,n,i,o){typeof i=="function"&&(o=i,i=void 0);let a=this;a.fs.exists(t,function(d){if(d&&!n)return o(!1);a.fs.stat(t,function(u,f){if(d&&f.isDirectory())return o(!1);var x=Fe.dirname(t);a.fs.exists(x,function(p){p||a.makeDir(x),a.fs.open(t,"w",438,function(m,y){m?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(_,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)})})})})}):y?a.fs.write(y,e,0,e.length,0,function(){a.fs.close(y,function(){a.fs.chmod(t,i||438,function(){o(!0)})})}):a.fs.chmod(t,i||438,function(){o(!0)})})})})})};Se.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=Fe.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&d.push(Fe.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(d=d.concat(n(f,o,a)))}),d}return n(t,void 0,!0)};Se.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=Fe.join(t,u),n.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Fe.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(p,m){if(p)return e(p);i=i.concat(m),--d||e(null,i)}):--d||e(null,i))})})})};Se.prototype.getAttributes=function(){};Se.prototype.setAttributes=function(){};Se.crc32update=function(t,e){return yu[(t^e)&255]^t>>>8};Se.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Se.crc32update(n,t[i++]);return~n>>>0};Se.methodToString=function(t){switch(t){case wu.STORED:return"STORED ("+t+")";case wu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Se.canonical=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.join(".",e)};Se.zipnamefix=function(t){if(!t)return"";let e=Fe.posix.normalize("/"+t.split("\\").join("/"));return Fe.posix.join(".",e)};Se.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]};Se.sanitize=function(t,e){t=Fe.resolve(Fe.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var a=Fe.normalize(Fe.join(t,n.slice(i,o).join(Fe.sep)));if(a.indexOf(t)===0)return a}return Fe.normalize(Fe.join(t,Fe.basename(e)))};Se.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Se.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Se.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Se.fromDate2DOS=function(t){let e=0,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};Se.isWin=Aw;Se.crcTable=yu});var Su=ue((c2,vu)=>{var kw=pe("path");vu.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=kw.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 Au=ue((d2,Iu)=>{Iu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var Ir=ue((l2,Sr)=>{Sr.exports=Eu();Sr.exports.Constants=sc();Sr.exports.Errors=Ns();Sr.exports.FileAttr=Su();Sr.exports.decoder=Au()});var Cu=ue((u2,ku)=>{var _n=Ir(),z=_n.Constants;ku.exports=function(){var t=20,e=10,n=0,i=0,o=0,a=0,d=0,u=0,f=0,x=0,p=0,m=0,y=0,_=0,E=0;t|=_n.isWin?2560:768,n|=z.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,C=b=>Math.max(0,b)&65535,P=b=>Math.max(0,b)&255;return o=_n.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return n},set flags(b){n=b},get flags_efs(){return(n&z.FLG_EFS)>0},set flags_efs(b){b?n|=z.FLG_EFS:n&=~z.FLG_EFS},get flags_desc(){return(n&z.FLG_DESC)>0},set flags_desc(b){b?n|=z.FLG_DESC:n&=~z.FLG_DESC},get method(){return i},set method(b){switch(b){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=b},get time(){return _n.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=_n.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=A(b)},get timeHighByte(){return P(o>>>8)},get crc(){return a},set crc(b){a=A(b)},get compressedSize(){return d},set compressedSize(b){d=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return f},set fileNameLength(b){f=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return p},set commentLength(b){p=b},get diskNumStart(){return m},set diskNumStart(b){m=A(b)},get inAttr(){return y},set inAttr(b){y=A(b)},get attr(){return _},set attr(b){_=A(b)},get fileAttr(){return(_||0)>>16&4095},get offset(){return E},set offset(b){E=A(b)},get encrypted(){return(n&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+f+x+p},get realDataOffset(){return E+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var R=b.slice(E,E+z.LOCHDR);if(R.readUInt32LE(0)!==z.LOCSIG)throw _n.Errors.INVALID_LOC();I.version=R.readUInt16LE(z.LOCVER),I.flags=R.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=R.readUInt16LE(z.LOCHOW),I.time=R.readUInt32LE(z.LOCTIM),I.crc=R.readUInt32LE(z.LOCCRC),I.compressedSize=R.readUInt32LE(z.LOCSIZ),I.size=R.readUInt32LE(z.LOCLEN),I.fnameLen=R.readUInt16LE(z.LOCNAM),I.extraLen=R.readUInt16LE(z.LOCEXT);let D=E+z.LOCHDR+I.fnameLen,U=D+I.extraLen;return b.slice(D,U)},loadFromBinary:function(b){if(b.length!==z.CENHDR||b.readUInt32LE(0)!==z.CENSIG)throw _n.Errors.INVALID_CEN();t=b.readUInt16LE(z.CENVEM),e=b.readUInt16LE(z.CENVER),n=b.readUInt16LE(z.CENFLG),i=b.readUInt16LE(z.CENHOW),o=b.readUInt32LE(z.CENTIM),a=b.readUInt32LE(z.CENCRC),d=b.readUInt32LE(z.CENSIZ),u=b.readUInt32LE(z.CENLEN),f=b.readUInt16LE(z.CENNAM),x=b.readUInt16LE(z.CENEXT),p=b.readUInt16LE(z.CENCOM),m=b.readUInt16LE(z.CENDSK),y=b.readUInt16LE(z.CENATT),_=b.readUInt32LE(z.CENATX),E=b.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(z.LOCHDR);return b.writeUInt32LE(z.LOCSIG,0),b.writeUInt16LE(e,z.LOCVER),b.writeUInt16LE(n,z.LOCFLG),b.writeUInt16LE(i,z.LOCHOW),b.writeUInt32LE(o,z.LOCTIM),b.writeUInt32LE(a,z.LOCCRC),b.writeUInt32LE(d,z.LOCSIZ),b.writeUInt32LE(u,z.LOCLEN),b.writeUInt16LE(f,z.LOCNAM),b.writeUInt16LE(I.extraLen,z.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(z.CENHDR+f+x+p);return b.writeUInt32LE(z.CENSIG,0),b.writeUInt16LE(t,z.CENVEM),b.writeUInt16LE(e,z.CENVER),b.writeUInt16LE(n,z.CENFLG),b.writeUInt16LE(i,z.CENHOW),b.writeUInt32LE(o,z.CENTIM),b.writeUInt32LE(a,z.CENCRC),b.writeUInt32LE(d,z.CENSIZ),b.writeUInt32LE(u,z.CENLEN),b.writeUInt16LE(f,z.CENNAM),b.writeUInt16LE(x,z.CENEXT),b.writeUInt16LE(p,z.CENCOM),b.writeUInt16LE(m,z.CENDSK),b.writeUInt16LE(y,z.CENATT),b.writeUInt32LE(_,z.CENATX),b.writeUInt32LE(E,z.CENOFF),b},toJSON:function(){let b=function(R){return R+" bytes"};return{made:t,version:e,flags:n,method:_n.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(f),extraLength:b(x),commentLength:b(p),diskNumStart:m,inAttr:y,attr:_,offset:E,centralHeaderSize:b(z.CENHDR+f+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Pu=ue((f2,Tu)=>{var Ar=Ir(),be=Ar.Constants;Tu.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 be.ENDHDR+o},loadFromBinary:function(a){if((a.length!==be.ENDHDR||a.readUInt32LE(0)!==be.ENDSIG)&&(a.length<be.ZIP64HDR||a.readUInt32LE(0)!==be.ZIP64SIG))throw Ar.Errors.INVALID_END();a.readUInt32LE(0)===be.ENDSIG?(t=a.readUInt16LE(be.ENDSUB),e=a.readUInt16LE(be.ENDTOT),n=a.readUInt32LE(be.ENDSIZ),i=a.readUInt32LE(be.ENDOFF),o=a.readUInt16LE(be.ENDCOM)):(t=Ar.readBigUInt64LE(a,be.ZIP64SUB),e=Ar.readBigUInt64LE(a,be.ZIP64TOT),n=Ar.readBigUInt64LE(a,be.ZIP64SIZE),i=Ar.readBigUInt64LE(a,be.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(be.ENDHDR+o);return a.writeUInt32LE(be.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,be.ENDSUB),a.writeUInt16LE(e,be.ENDTOT),a.writeUInt32LE(n,be.ENDSIZ),a.writeUInt32LE(i,be.ENDOFF),a.writeUInt16LE(o,be.ENDCOM),a.fill(" ",be.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 ac=ue(oc=>{oc.EntryHeader=Cu();oc.MainHeader=Pu()});var Ou=ue((x2,Ru)=>{Ru.exports=function(t){var e=pe("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var o=e.createDeflateRaw(n),a=[],d=0;o.on("data",function(u){a.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),f=0;u.fill(0);for(var x=0;x<a.length;x++){var p=a[x];p.copy(u,f),f+=p.length}i&&i(u)}),o.end(t)}}}});var Lu=ue((p2,Du)=>{var Cw=+(process.versions?process.versions.node:"").split(".")[0]||0;Du.exports=function(t,e){var n=pe("zlib");let i=Cw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var a=n.createInflateRaw(i),d=[],u=0;a.on("data",function(f){d.push(f),u+=f.length}),a.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var p=0;p<d.length;p++){var m=d[p];m.copy(f,x),x+=m.length}o&&o(f)}),a.end(t)}}}});var zu=ue((g2,Bu)=>{"use strict";var{randomFillSync:Mu}=pe("crypto"),Tw=Ns(),Pw=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}),Fu=(t,e)=>Math.imul(t,e)>>>0,Nu=(t,e)=>Pw[(t^e)&255]^t>>>8,yi=()=>typeof Mu=="function"?Mu(Buffer.alloc(12)):yi.node();yi.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 Fs={genSalt:yi};function Bs(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])}Bs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Nu(e[0],t),e[1]+=e[0]&255,e[1]=Fu(e[1],134775813)+1,e[2]=Nu(e[2],e[1]>>>24),t};Bs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Fu(t,t^1)>>8&255};function Rw(t){let e=new Bs(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 Ow(t){let e=new Bs(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 Dw(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Rw(n),o=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==a)throw Tw.WRONG_PASSWORD();return i(t.slice(12))}function Lw(t){Buffer.isBuffer(t)&&t.length>=12?Fs.genSalt=function(){return t.slice(0,12)}:t==="node"?Fs.genSalt=yi.node:Fs.genSalt=yi}function Mw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Ow(n),a=Fs.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)}Bu.exports={decrypt:Dw,encrypt:Mw,_salter:Lw}});var Uu=ue(zs=>{zs.Deflater=Ou();zs.Inflater=Lu();zs.ZipCrypto=zu()});var dc=ue((w2,Hu)=>{var fe=Ir(),Nw=ac(),Ie=fe.Constants,cc=Uu();Hu.exports=function(t,e){var n=new Nw.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let p=t,m=typeof p.decoder=="object"?p.decoder:fe.decoder;x=m.hasOwnProperty("efs")?m.efs:!1;function y(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(b){if(!n.flags_desc&&!n.localHeader.flags_desc){if(fe.crc32(b)!==n.localHeader.crc)return!1}else{let R={},D=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(D)==Ie.LOCSIG||e.readUInt32LE(D)==Ie.CENSIG)throw fe.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==Ie.EXTSIG)R.crc=e.readUInt32LE(D+Ie.EXTCRC),R.compressedSize=e.readUInt32LE(D+Ie.EXTSIZ),R.size=e.readUInt32LE(D+Ie.EXTLEN);else if(e.readUInt16LE(D+12)===19280)R.crc=e.readUInt32LE(D+Ie.EXTCRC-4),R.compressedSize=e.readUInt32LE(D+Ie.EXTSIZ-4),R.size=e.readUInt32LE(D+Ie.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(b)!==R.crc)return!1}return!0}function E(b,R,D){if(typeof R>"u"&&typeof b=="string"&&(D=b,b=void 0),a)return b&&R&&R(Buffer.alloc(0),fe.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var U=y();if(U.length===0)return b&&R&&R(U),U;if(n.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw fe.Errors.INVALID_PASS_PARAM();U=cc.ZipCrypto.decrypt(U,n,D)}var M=Buffer.alloc(n.size);switch(n.method){case fe.Constants.STORED:if(U.copy(M),_(M))return b&&R&&R(M),M;throw b&&R&&R(M,fe.Errors.BAD_CRC()),fe.Errors.BAD_CRC();case fe.Constants.DEFLATED:var V=new cc.Inflater(U,n.size);if(b)V.inflateAsync(function(J){J.copy(J,0),R&&(_(J)?R(J):R(J,fe.Errors.BAD_CRC()))});else{if(V.inflate(M).copy(M,0),!_(M))throw fe.Errors.BAD_CRC(`"${m.decode(i)}"`);return M}break;default:throw b&&R&&R(Buffer.alloc(0),fe.Errors.UNKNOWN_METHOD()),fe.Errors.UNKNOWN_METHOD()}}function I(b,R){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&R&&R(y()),y();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),b&&R&&R(D),D;default:case fe.Constants.DEFLATED:var U=new cc.Deflater(d);if(b)U.deflateAsync(function(V){D=Buffer.alloc(V.length),n.compressedSize=V.length,V.copy(D),R&&R(D)});else{var M=U.deflate();return n.compressedSize=M.length,M}U=null;break}}else if(b&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,R){return fe.readBigUInt64LE(b,R)}function C(b){try{for(var R=0,D,U,M;R+4<b.length;)D=b.readUInt16LE(R),R+=2,U=b.readUInt16LE(R),R+=2,M=b.slice(R,R+U),R+=U,Ie.ID_ZIP64===D&&P(M)}catch{throw fe.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(b){var R,D,U,M;b.length>=Ie.EF_ZIP64_SCOMP&&(R=A(b,Ie.EF_ZIP64_SUNCOMP),n.size===Ie.EF_ZIP64_OR_32&&(n.size=R)),b.length>=Ie.EF_ZIP64_RHO&&(D=A(b,Ie.EF_ZIP64_SCOMP),n.compressedSize===Ie.EF_ZIP64_OR_32&&(n.compressedSize=D)),b.length>=Ie.EF_ZIP64_DSN&&(U=A(b,Ie.EF_ZIP64_RHO),n.offset===Ie.EF_ZIP64_OR_32&&(n.offset=U)),b.length>=Ie.EF_ZIP64_DSN+4&&(M=b.readUInt32LE(Ie.EF_ZIP64_DSN),n.diskNumStart===Ie.EF_ZIP64_OR_16&&(n.diskNumStart=M))}return{get entryName(){return m.decode(i)},get rawEntryName(){return i},set entryName(b){i=fe.toBuffer(b,m.encode);var R=i[i.length-1];a=R===47||R===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,n.extraLength=b.length,C(b)},get comment(){return m.decode(o)},set comment(b){if(o=fe.toBuffer(b,m.encode),n.commentLength=o.length,o.length>65535)throw fe.Errors.COMMENT_TOO_LONG()},get name(){var b=m.decode(i);return a?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){d=fe.toBuffer(b,fe.decoder.encode),!a&&d.length?(n.size=d.length,n.method=fe.Constants.DEFLATED,n.crc=fe.crc32(b),n.changed=!0):n.method=fe.Constants.STORED},getData:function(b){return n.changed?d:E(!1,null,b)},getDataAsync:function(b,R){n.changed?b(d):E(!0,b,R)},set attr(b){n.attr=b},get attr(){return n.attr},set header(b){n.loadFromBinary(b)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var b=n.centralHeaderToBinary(),R=fe.Constants.CENHDR;return i.copy(b,R),R+=i.length,u.copy(b,R),R+=n.extraLength,o.copy(b,R),b},packLocalHeader:function(){let b=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,b),b+=R.length,i.copy(D,b),b+=i.length,f.copy(D,b),b+=f.length,D},toJSON:function(){let b=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:b(e),data:b(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ju=ue((_2,qu)=>{var Gu=dc(),Fw=ac(),Je=Ir();qu.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),a=new Fw.MainHeader,d=!1,u=null;let f=new Set,x=e,{noSort:p,decoder:m}=x;t?E(x.readEntries):d=!0;function y(){let A=new Set;for(let C of Object.keys(i)){let P=C.split("/");if(P.pop(),!!P.length)for(let b=0;b<P.length;b++){let R=P.slice(0,b+1).join("/")+"/";A.add(R)}}for(let C of A)if(!(C in i)){let P=new Gu(x);P.entryName=C,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,f.add(P)}}function _(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Je.Constants.CENHDR)throw Je.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var A=a.offset,C=0;C<n.length;C++){var P=A,b=new Gu(x,t);b.header=t.slice(P,P+=Je.Constants.CENHDR),b.entryName=t.slice(P,P+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(P,P+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(P,P+b.header.commentLength)),A+=b.header.centralHeaderSize,n[C]=b,i[b.entryName]=b}f.clear(),y()}function E(A){var C=t.length-Je.Constants.ENDHDR,P=Math.max(0,C-65535),b=P,R=t.length,D=-1,U=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),C;C>=b;C--)if(t[C]===80){if(t.readUInt32LE(C)===Je.Constants.ENDSIG){D=C,U=C,R=C+Je.Constants.ENDHDR,b=C-Je.Constants.END64HDR;continue}if(t.readUInt32LE(C)===Je.Constants.END64SIG){b=P;continue}if(t.readUInt32LE(C)===Je.Constants.ZIP64SIG){D=C,R=C+Je.readBigUInt64LE(t,C+Je.Constants.ZIP64SIZE)+Je.Constants.ZIP64LEAD;break}}if(D==-1)throw Je.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(D,R)),a.commentLength&&(o=t.slice(U+Je.Constants.ENDHDR)),A&&_()}function I(){n.length>1&&!p&&n.sort((A,C)=>A.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(A=>!f.has(A))},get comment(){return m.decode(o)},set comment(A){o=Je.toBuffer(A,m.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,C=!0){d||_();let P=i[A];this.getEntryChildren(P,C).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||_();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||_(),typeof A=="object")if(A.isDirectory&&C){let P=[],b=A.entryName;for(let R of n)R.entryName.startsWith(b)&&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||_(),I();let A=[],C=[],P=0,b=0;a.size=0,a.offset=0;let R=0;for(let M of this.entries){let V=M.getCompressedData();M.header.offset=b;let J=M.packLocalHeader(),ie=J.length+V.length;b+=ie,A.push(J),A.push(V);let X=M.packCentralHeader();C.push(X),a.size+=X.length,P+=ie+X.length,R++}P+=a.mainHeaderSize,a.offset=b,a.totalEntries=R,b=0;let D=Buffer.alloc(P);for(let M of A)M.copy(D,b),b+=M.length;for(let M of C)M.copy(D,b),b+=M.length;let U=a.toBinary();return o&&o.copy(U,Je.Constants.ENDHDR),U.copy(D,b),t=D,d=!1,D},toAsyncBuffer:function(A,C,P,b){try{d||_(),I();let R=[],D=[],U=0,M=0,V=0;a.size=0,a.offset=0;let J=function(ie){if(ie.length>0){let X=ie.shift(),oe=X.entryName+X.extra.toString();P&&P(oe),X.getCompressedDataAsync(function(le){b&&b(oe),X.header.offset=M;let ye=X.packLocalHeader(),Ue=ye.length+le.length;M+=Ue,R.push(ye),R.push(le);let T=X.packCentralHeader();D.push(T),a.size+=T.length,U+=Ue+T.length,V++,J(ie)})}else{U+=a.mainHeaderSize,a.offset=M,a.totalEntries=V,M=0;let X=Buffer.alloc(U);R.forEach(function(le){le.copy(X,M),M+=le.length}),D.forEach(function(le){le.copy(X,M),M+=le.length});let oe=a.toBinary();o&&o.copy(oe,Je.Constants.ENDHDR),oe.copy(X,M),t=X,d=!1,A(X)}};J(Array.from(this.entries))}catch(R){C(R)}}}}});var $u=ue((y2,Ku)=>{var ve=Ir(),Ee=pe("path"),Bw=dc(),zw=ju(),Hn=(...t)=>ve.findLast(t,e=>typeof e=="boolean"),Wu=(...t)=>ve.findLast(t,e=>typeof e=="string"),Uw=(...t)=>ve.findLast(t,e=>typeof e=="function"),Hw={noSort:!1,readEntries:!1,method:ve.Constants.NONE,fs:null};Ku.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),Hw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=ve.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new ve(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=ve.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=ve.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw ve.Errors.INVALID_FILENAME();let a=new zw(n,i),{canonical:d,sanitize:u,zipnamefix:f}=ve;function x(_){if(_&&a){var E;if(typeof _=="string"&&(E=a.getEntry(Ee.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(E=a.getEntry(_.entryName)),E)return E}return null}function p(_){let{join:E,normalize:I,sep:A}=Ee.posix;return E(Ee.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function m(_){return _ instanceof RegExp?(function(E){return function(I){return E.test(I)}})(_):typeof _!="function"?()=>!0:_}let y=(_,E)=>{let I=E.slice(-1);return I=I===o.sep?o.sep:"",Ee.relative(_,E)+I};return{readFile:function(_,E){var I=x(_);return I&&I.getData(E)||null},childCount:function(_){let E=x(_);if(E)return a.getChildCount(E)},readFileAsync:function(_,E){var I=x(_);I?I.getDataAsync(E):E(null,"getEntry failed for:"+_)},readAsText:function(_,E){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(E||"utf8")}return""},readAsTextAsync:function(_,E,I){var A=x(_);A?A.getDataAsync(function(C,P){if(P){E(C,P);return}C&&C.length?E(C.toString(I||"utf8")):E("")}):E("")},deleteFile:function(_,E=!0){var I=x(_);I&&a.deleteFile(I.entryName,E)},deleteEntry:function(_){var E=x(_);E&&a.deleteEntry(E.entryName)},addZipComment:function(_){a.comment=_},getZipComment:function(){return a.comment||""},addZipEntryComment:function(_,E){var I=x(_);I&&(I.comment=E)},getZipEntryComment:function(_){var E=x(_);return E&&E.comment||""},updateFile:function(_,E){var I=x(_);I&&I.setData(E)},addLocalFile:function(_,E,I,A){if(o.fs.existsSync(_)){E=E?p(E):"";let C=Ee.win32.basename(Ee.win32.normalize(_));E+=I||C;let P=o.fs.statSync(_),b=P.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);P.isDirectory()&&(E+=o.sep),this.addFile(E,b,A,P)}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,E){_=typeof _=="object"?_:{localPath:_};let I=Ee.resolve(_.localPath),{comment:A}=_,{zipPath:C,zipName:P}=_,b=this;o.fs.stat(I,function(R,D){if(R)return E(R,!1);C=C?p(C):"";let U=Ee.win32.basename(Ee.win32.normalize(I));if(C+=P||U,D.isFile())o.fs.readFile(I,function(M,V){return M?E(M,!1):(b.addFile(C,V,A,D),setImmediate(E,void 0,!0))});else if(D.isDirectory())return C+=o.sep,b.addFile(C,Buffer.alloc(0),A,D),setImmediate(E,void 0,!0)})},addLocalFolder:function(_,E,I){if(I=m(I),E=E?p(E):"",_=Ee.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),C=this;if(A.length)for(let P of A){let b=Ee.join(E,y(_,P));I(b)&&C.addLocalFile(P,Ee.dirname(b))}}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,E,I,A){A=m(A),I=I?p(I):"",_=Ee.normalize(_);var C=this;o.fs.open(_,"r",function(P){if(P&&P.code==="ENOENT")E(void 0,ve.Errors.FILE_NOT_FOUND(_));else if(P)E(void 0,P);else{var b=o.findFiles(_),R=-1,D=function(){if(R+=1,R<b.length){var U=b[R],M=y(_,U).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?o.fs.stat(U,function(V,J){V&&E(void 0,V),J.isFile()?o.fs.readFile(U,function(ie,X){ie?E(void 0,ie):(C.addFile(I+M,X,"",J),D())}):(C.addFile(I+M+"/",Buffer.alloc(0),"",J),D())}):process.nextTick(()=>{D()})}else E(!0,void 0)};D()}})},addLocalFolderAsync2:function(_,E){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=Ee.resolve(p(_.localPath));let{zipPath:A,filter:C,namefix:P}=_;C instanceof RegExp?C=(function(D){return function(U){return D.test(U)}})(C):typeof C!="function"&&(C=function(){return!0}),A=A?p(A):"",P=="latin1"&&(P=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=D=>D);let b=D=>Ee.join(A,P(y(localPath,D))),R=D=>Ee.win32.basename(Ee.win32.normalize(P(D)));o.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?E(void 0,ve.Errors.FILE_NOT_FOUND(localPath)):D?E(void 0,D):o.findFilesAsync(localPath,function(U,M){if(U)return E(U);M=M.filter(V=>C(b(V))),M.length||E(void 0,!1),setImmediate(M.reverse().reduce(function(V,J){return function(ie,X){if(ie||X===!1)return setImmediate(V,ie,!1);I.addLocalFileAsync({localPath:J,zipPath:Ee.dirname(b(J)),zipName:R(J)},V)}},E))})})},addLocalFolderPromise:function(_,E){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},E),(C,P)=>{C&&A(C),P&&I(this)})})},addFile:function(_,E,I,A){_=f(_);let C=x(_),P=C!=null;P||(C=new Bw(i),C.entryName=_),C.comment=I||"";let b=typeof A=="object"&&A instanceof o.fs.Stats;b&&(C.header.time=A.mtime);var R=C.isDirectory?16:0;let D=C.isDirectory?16384:32768;return b?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(_){return a.password=_,a?a.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return a.getEntryCount()},forEach:function(_){return a.forEach(_)},extractEntryTo:function(_,E,I,A,C,P){A=Hn(!1,A),C=Hn(!1,C),I=Hn(!0,I),P=Wu(C,P);var b=x(_);if(!b)throw ve.Errors.NO_ENTRY();var R=d(b.entryName),D=u(E,P&&!b.isDirectory?P:I?R:Ee.basename(R));if(b.isDirectory){var U=a.getEntryChildren(b);return U.forEach(function(J){if(J.isDirectory)return;var ie=J.getData();if(!ie)throw ve.Errors.CANT_EXTRACT_FILE();var X=d(J.entryName),oe=u(E,I?X:Ee.basename(X));let le=C?J.header.fileAttr:void 0;o.writeFileTo(oe,ie,A,le)}),!0}var M=b.getData(a.password);if(!M)throw ve.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(D)&&!A)throw ve.Errors.CANT_OVERRIDE();let V=C?_.header.fileAttr:void 0;return o.writeFileTo(D,M,A,V),!0},test:function(_){if(!a)return!1;for(var E in a.entries)try{if(E.isDirectory)continue;var I=a.entries[E].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,E,I,A){if(I=Hn(!1,I),A=Wu(I,A),E=Hn(!1,E),!a)throw ve.Errors.NO_ZIP();a.entries.forEach(function(C){var P=u(_,d(C.entryName));if(C.isDirectory){o.makeDir(P);return}var b=C.getData(A);if(!b)throw ve.Errors.CANT_EXTRACT_FILE();let R=I?C.header.fileAttr:void 0;o.writeFileTo(P,b,E,R);try{o.fs.utimesSync(P,C.header.time,C.header.time)}catch{throw ve.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,E,I,A){if(A=Uw(E,I,A),I=Hn(!1,I),E=Hn(!1,E),!A)return new Promise((D,U)=>{this.extractAllToAsync(_,E,I,function(M){M?U(M):D(this)})});if(!a){A(ve.Errors.NO_ZIP());return}_=Ee.resolve(_);let C=D=>u(_,Ee.normalize(d(D.entryName))),P=(D,U)=>new Error(D+': "'+U+'"'),b=[],R=[];a.entries.forEach(D=>{D.isDirectory?b.push(D):R.push(D)});for(let D of b){let U=C(D),M=I?D.header.fileAttr:void 0;try{o.makeDir(U),M&&o.fs.chmodSync(U,M),o.fs.utimesSync(U,D.header.time,D.header.time)}catch{A(P("Unable to create folder",U))}}R.reverse().reduce(function(D,U){return function(M){if(M)D(M);else{let V=Ee.normalize(d(U.entryName)),J=u(_,V);U.getDataAsync(function(ie,X){if(X)D(X);else if(!ie)D(ve.Errors.CANT_EXTRACT_FILE());else{let oe=I?U.header.fileAttr:void 0;o.writeFileToAsync(J,ie,E,oe,function(le){le||D(P("Unable to write file",J)),o.fs.utimes(J,U.header.time,U.header.time,function(ye){ye?D(P("Unable to set times",J)):D()})})}})}}},A)()},writeZip:function(_,E){if(arguments.length===1&&typeof _=="function"&&(E=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=a.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof E=="function"&&E(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,E){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},E);return new Promise((C,P)=>{!_&&i.filename&&(_=i.filename),_||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let R=D=>D?C(D):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,b,I,A,R)},P)})},toBufferPromise:function(){return new Promise((_,E)=>{a.toAsyncBuffer(_,E)})},toBuffer:function(_,E,I,A){return typeof _=="function"?(a.toAsyncBuffer(_,E,I,A),null):a.compressToBuffer()}}}});import{execFile as Zy,spawn as Yy,spawnSync as GC}from"node:child_process";import{promisify as Xy}from"node:util";function eb(t){if(process.platform!=="win32")return!1;if(E0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(E0,"").toLowerCase();return Qy.has(n)}function v0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return eb(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function at(t,e=[],n={}){return Yy(t,e,v0(t,n))}function ko(t,e=[],n={}){return tb(t,e,v0(t,n))}var Qy,E0,tb,Gt=it(()=>{"use strict";Qy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),E0=/\.(cmd|bat|ps1)$/i;tb=Xy(Zy)});var ln=ue((pD,Px)=>{"use strict";var Cx=["nodebuffer","arraybuffer","fragments"],Tx=typeof Blob<"u";Tx&&Cx.push("blob");Px.exports={BINARY_TYPES:Cx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Tx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ls=ue((gD,ta)=>{"use strict";var{EMPTY_BUFFER:kS}=ln(),$d=Buffer[Symbol.species];function CS(t,e){if(t.length===0)return kS;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 $d(n.buffer,n.byteOffset,i):n}function Rx(t,e,n,i,o){for(let a=0;a<o;a++)n[i+a]=t[a]^e[a&3]}function Ox(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function TS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Vd(t){if(Vd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new $d(t):ArrayBuffer.isView(t)?e=new $d(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Vd.readOnly=!1),e}ta.exports={concat:CS,mask:Rx,toArrayBuffer:TS,toBuffer:Vd,unmask:Ox};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=pe("bufferutil");ta.exports.mask=function(e,n,i,o,a){a<48?Rx(e,n,i,o,a):t.mask(e,n,i,o,a)},ta.exports.unmask=function(e,n){e.length<32?Ox(e,n):t.unmask(e,n)}}catch{}});var Mx=ue((mD,Lx)=>{"use strict";var Dx=Symbol("kDone"),Jd=Symbol("kRun"),Zd=class{constructor(e){this[Dx]=()=>{this.pending--,this[Jd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Jd]()}[Jd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Dx])}}};Lx.exports=Zd});var ni=ue((wD,zx)=>{"use strict";var us=pe("zlib"),Nx=ls(),PS=Mx(),{kStatusCode:Fx}=ln(),RS=Buffer[Symbol.species],OS=Buffer.from([0,0,255,255]),ra=Symbol("permessage-deflate"),un=Symbol("total-length"),ei=Symbol("callback"),Ln=Symbol("buffers"),ti=Symbol("error"),na,Yd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!na){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;na=new PS(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[ei];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){na.add(o=>{this._decompress(e,n,(a,d)=>{o(),i(a,d)})})}compress(e,n,i){na.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"?us.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=us.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[ra]=this,this._inflate[un]=0,this._inflate[Ln]=[],this._inflate.on("error",LS),this._inflate.on("data",Bx)}this._inflate[ei]=i,this._inflate.write(e),n&&this._inflate.write(OS),this._inflate.flush(()=>{let a=this._inflate[ti];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=Nx.concat(this._inflate[Ln],this._inflate[un]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[un]=0,this._inflate[Ln]=[],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"?us.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=us.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[un]=0,this._deflate[Ln]=[],this._deflate.on("data",DS)}this._deflate[ei]=i,this._deflate.write(e),this._deflate.flush(us.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=Nx.concat(this._deflate[Ln],this._deflate[un]);n&&(a=new RS(a.buffer,a.byteOffset,a.length-4)),this._deflate[ei]=null,this._deflate[un]=0,this._deflate[Ln]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};zx.exports=Yd;function DS(t){this[Ln].push(t),this[un]+=t.length}function Bx(t){if(this[un]+=t.length,this[ra]._maxPayload<1||this[un]<=this[ra]._maxPayload){this[Ln].push(t);return}this[ti]=new RangeError("Max payload size exceeded"),this[ti].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ti][Fx]=1009,this.removeListener("data",Bx),this.reset()}function LS(t){if(this[ra]._inflate=null,this[ti]){this[ei](this[ti]);return}t[Fx]=1007,this[ei](t)}});var ri=ue((_D,ia)=>{"use strict";var{isUtf8:Ux}=pe("buffer"),{hasBlob:MS}=ln(),NS=[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 FS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Xd(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 BS(t){return MS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ia.exports={isBlob:BS,isValidStatusCode:FS,isValidUTF8:Xd,tokenChars:NS};if(Ux)ia.exports.isValidUTF8=function(t){return t.length<24?Xd(t):Ux(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=pe("utf-8-validate");ia.exports.isValidUTF8=function(e){return e.length<32?Xd(e):t(e)}}catch{}});var rl=ue((yD,$x)=>{"use strict";var{Writable:zS}=pe("stream"),Hx=ni(),{BINARY_TYPES:US,EMPTY_BUFFER:Gx,kStatusCode:HS,kWebSocket:GS}=ln(),{concat:Qd,toArrayBuffer:qS,unmask:jS}=ls(),{isValidStatusCode:WS,isValidUTF8:qx}=ri(),sa=Buffer[Symbol.species],vt=0,jx=1,Wx=2,Kx=3,el=4,tl=5,oa=6,nl=class extends zS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||US[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[GS]=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=vt}_write(e,n,i){if(this._opcode===8&&this._state==vt)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 sa(i.buffer,i.byteOffset+e,i.length-e),new sa(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 sa(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 vt:this.getInfo(e);break;case jx:this.getPayloadLength16(e);break;case Wx:this.getPayloadLength64(e);break;case Kx:this.getMask();break;case el:this.getData(e);break;case tl:case oa: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[Hx.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=jx:this._payloadLength===127?this._state=Wx: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=Kx:this._state=el}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=el}getData(e){let n=Gx;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&jS(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=tl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hx.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===vt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=vt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Qd(i,n):this._binaryType==="arraybuffer"?o=qS(Qd(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=vt):(this._state=oa,setImmediate(()=>{this.emit("message",o,!0),this._state=vt,this.startLoop(e)}))}else{let o=Qd(i,n);if(!this._skipUTF8Validation&&!qx(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===tl||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=vt):(this._state=oa,setImmediate(()=>{this.emit("message",o,!1),this._state=vt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Gx),this.end();else{let i=e.readUInt16BE(0);if(!WS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let o=new sa(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!qx(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=vt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=vt):(this._state=oa,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=vt,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[HS]=o,d}};$x.exports=nl});var ol=ue((ED,Zx)=>{"use strict";var{Duplex:bD}=pe("stream"),{randomFillSync:KS}=pe("crypto"),Vx=ni(),{EMPTY_BUFFER:$S,kWebSocket:VS,NOOP:JS}=ln(),{isBlob:ii,isValidStatusCode:ZS}=ri(),{mask:Jx,toBuffer:cr}=ls(),St=Symbol("kByteLength"),YS=Buffer.alloc(4),aa=8*1024,dr,si=aa,Dt=0,XS=1,QS=2,il=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=Dt,this.onerror=JS,this[VS]=void 0}static frame(e,n){let i,o=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||YS,n.generateMask?n.generateMask(i):(si===aa&&(dr===void 0&&(dr=Buffer.alloc(aa)),KS(dr,0,aa),si=0),i[0]=dr[si++],i[1]=dr[si++],i[2]=dr[si++],i[3]=dr[si++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[St]!==void 0?u=n[St]:(e=Buffer.from(e),u=e.length):(u=e.length,o=n.mask&&n.readOnly&&!d);let f=u;u>=65536?(a+=8,f=127):u>125&&(a+=2,f=126);let x=Buffer.allocUnsafe(o?u+a:a);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=f,f===126?x.writeUInt16BE(u,2):f===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.mask?(x[1]|=128,x[a-4]=i[0],x[a-3]=i[1],x[a-2]=i[2],x[a-1]=i[3],d?[x,e]:o?(Jx(e,i,x,a,u),[x]):(Jx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,o){let a;if(e===void 0)a=$S;else{if(typeof e!="number"||!ZS(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={[St]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Dt?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):ii(e)?(o=e.size,a=!1):(e=cr(e),o=e.length,a=cr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[St]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};ii(e)?this._state!==Dt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Dt?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):ii(e)?(o=e.size,a=!1):(e=cr(e),o=e.length,a=cr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[St]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};ii(e)?this._state!==Dt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Dt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[Vx.extensionName],a=n.binary?2:1,d=n.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):ii(e)?(u=e.size,f=!1):(e=cr(e),u=e.length,f=cr.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[St]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:f,rsv1:d};ii(e)?this._state!==Dt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Dt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[St],this._state=QS,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(sl,this,u,o);return}this._bufferedBytes-=i[St];let d=cr(a);n?this.dispatch(d,n,i,o):(this._state=Dt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(a=>{process.nextTick(e1,this,a,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let a=this._extensions[Vx.extensionName];this._bufferedBytes+=i[St],this._state=XS,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");sl(this,f,o);return}this._bufferedBytes-=i[St],this._state=Dt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===Dt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][St],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][St],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)}};Zx.exports=il;function sl(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 e1(t,e,n){sl(t,e,n),t.onerror(e)}});var sp=ue((vD,ip)=>{"use strict";var{kForOnEventAttribute:fs,kListener:al}=ln(),Yx=Symbol("kCode"),Xx=Symbol("kData"),Qx=Symbol("kError"),ep=Symbol("kMessage"),tp=Symbol("kReason"),oi=Symbol("kTarget"),np=Symbol("kType"),rp=Symbol("kWasClean"),fn=class{constructor(e){this[oi]=null,this[np]=e}get target(){return this[oi]}get type(){return this[np]}};Object.defineProperty(fn.prototype,"target",{enumerable:!0});Object.defineProperty(fn.prototype,"type",{enumerable:!0});var lr=class extends fn{constructor(e,n={}){super(e),this[Yx]=n.code===void 0?0:n.code,this[tp]=n.reason===void 0?"":n.reason,this[rp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Yx]}get reason(){return this[tp]}get wasClean(){return this[rp]}};Object.defineProperty(lr.prototype,"code",{enumerable:!0});Object.defineProperty(lr.prototype,"reason",{enumerable:!0});Object.defineProperty(lr.prototype,"wasClean",{enumerable:!0});var ai=class extends fn{constructor(e,n={}){super(e),this[Qx]=n.error===void 0?null:n.error,this[ep]=n.message===void 0?"":n.message}get error(){return this[Qx]}get message(){return this[ep]}};Object.defineProperty(ai.prototype,"error",{enumerable:!0});Object.defineProperty(ai.prototype,"message",{enumerable:!0});var hs=class extends fn{constructor(e,n={}){super(e),this[Xx]=n.data===void 0?null:n.data}get data(){return this[Xx]}};Object.defineProperty(hs.prototype,"data",{enumerable:!0});var t1={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[fs]&&o[al]===e&&!o[fs])return;let i;if(t==="message")i=function(a,d){let u=new hs("message",{data:d?a:a.toString()});u[oi]=this,ca(e,this,u)};else if(t==="close")i=function(a,d){let u=new lr("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[oi]=this,ca(e,this,u)};else if(t==="error")i=function(a){let d=new ai("error",{error:a,message:a.message});d[oi]=this,ca(e,this,d)};else if(t==="open")i=function(){let a=new fn("open");a[oi]=this,ca(e,this,a)};else return;i[fs]=!!n[fs],i[al]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[al]===e&&!n[fs]){this.removeListener(t,n);break}}};ip.exports={CloseEvent:lr,ErrorEvent:ai,Event:fn,EventTarget:t1,MessageEvent:hs};function ca(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var da=ue((SD,op)=>{"use strict";var{tokenChars:xs}=ri();function $t(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function n1(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,a=!1,d,u,f=-1,x=-1,p=-1,m=0;for(;m<t.length;m++)if(x=t.charCodeAt(m),d===void 0)if(p===-1&&xs[x]===1)f===-1&&(f=m);else if(m!==0&&(x===32||x===9))p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let _=t.slice(f,p);x===44?($t(e,_,n),n=Object.create(null)):d=_,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(u===void 0)if(p===-1&&xs[x]===1)f===-1&&(f=m);else if(x===32||x===9)p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),$t(n,t.slice(f,p),!0),x===44&&($t(e,d,n),n=Object.create(null),d=void 0),f=p=-1}else if(x===61&&f!==-1&&p===-1)u=t.slice(f,m),f=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(o){if(xs[x]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);f===-1?f=m:i||(i=!0),o=!1}else if(a)if(xs[x]===1)f===-1&&(f=m);else if(x===34&&f!==-1)a=!1,p=m;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(x===34&&t.charCodeAt(m-1)===61)a=!0;else if(p===-1&&xs[x]===1)f===-1&&(f=m);else if(f!==-1&&(x===32||x===9))p===-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let _=t.slice(f,p);i&&(_=_.replace(/\\/g,""),i=!1),$t(n,u,_),x===44&&($t(e,d,n),n=Object.create(null),d=void 0),u=void 0,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(f===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let y=t.slice(f,p);return d===void 0?$t(e,y,n):(u===void 0?$t(n,y,!0):i?$t(n,u,y.replace(/\\/g,"")):$t(n,u,y),$t(e,d,n)),e}function r1(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(", ")}op.exports={format:r1,parse:n1}});var ha=ue((kD,wp)=>{"use strict";var i1=pe("events"),s1=pe("https"),o1=pe("http"),dp=pe("net"),a1=pe("tls"),{randomBytes:c1,createHash:d1}=pe("crypto"),{Duplex:ID,Readable:AD}=pe("stream"),{URL:cl}=pe("url"),Mn=ni(),l1=rl(),u1=ol(),{isBlob:f1}=ri(),{BINARY_TYPES:ap,CLOSE_TIMEOUT:h1,EMPTY_BUFFER:la,GUID:x1,kForOnEventAttribute:dl,kListener:p1,kStatusCode:g1,kWebSocket:We,NOOP:lp}=ln(),{EventTarget:{addEventListener:m1,removeEventListener:w1}}=sp(),{format:_1,parse:y1}=da(),{toBuffer:b1}=ls(),up=Symbol("kAborted"),ll=[8,13],hn=["CONNECTING","OPEN","CLOSING","CLOSED"],E1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_e=class t extends i1{constructor(e,n,i){super(),this._binaryType=ap[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=la,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]),fp(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ap.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 l1({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new u1(e,this._extensions,i.generateMask);this._receiver=o,this._sender=a,this._socket=e,o[We]=this,a[We]=this,e[We]=this,o.on("conclude",I1),o.on("drain",A1),o.on("error",k1),o.on("message",C1),o.on("ping",T1),o.on("pong",P1),a.onerror=R1,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",pp),e.on("data",fa),e.on("end",gp),e.on("error",mp),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[Mn.extensionName]&&this._extensions[Mn.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){xt(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())}),xp(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){ul(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||la,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){ul(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||la,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){ul(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Mn.extensionName]||(o.compress=!1),this._sender.send(e||la,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){xt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(_e,"CONNECTING",{enumerable:!0,value:hn.indexOf("CONNECTING")});Object.defineProperty(_e.prototype,"CONNECTING",{enumerable:!0,value:hn.indexOf("CONNECTING")});Object.defineProperty(_e,"OPEN",{enumerable:!0,value:hn.indexOf("OPEN")});Object.defineProperty(_e.prototype,"OPEN",{enumerable:!0,value:hn.indexOf("OPEN")});Object.defineProperty(_e,"CLOSING",{enumerable:!0,value:hn.indexOf("CLOSING")});Object.defineProperty(_e.prototype,"CLOSING",{enumerable:!0,value:hn.indexOf("CLOSING")});Object.defineProperty(_e,"CLOSED",{enumerable:!0,value:hn.indexOf("CLOSED")});Object.defineProperty(_e.prototype,"CLOSED",{enumerable:!0,value:hn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_e.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_e.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[dl])return e[p1];return null},set(e){for(let n of this.listeners(t))if(n[dl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[dl]:!0})}})});_e.prototype.addEventListener=m1;_e.prototype.removeEventListener=w1;wp.exports=_e;function fp(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:h1,protocolVersion:ll[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,!ll.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${ll.join(", ")})`);let a;if(e instanceof cl)a=e;else try{a=new cl(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 I=new SyntaxError(f);if(t._redirects===0)throw I;ua(t,I);return}let x=d?443:80,p=c1(16).toString("base64"),m=d?s1.request:o1.request,y=new Set,_;if(o.createConnection=o.createConnection||(d?S1:v1),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 Mn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=_1({[Mn.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!E1.test(I)||y.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(I)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:a.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,C]of Object.entries(I))i.headers[A.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=m(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=m(o);o.timeout&&E.on("timeout",()=>{xt(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[up]||(E=t._req=null,ua(t,I))}),E.on("response",I=>{let A=I.headers.location,C=I.statusCode;if(A&&o.followRedirects&&C>=300&&C<400){if(++t._redirects>o.maxRedirects){xt(t,E,"Maximum redirects exceeded");return}E.abort();let P;try{P=new cl(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);ua(t,R);return}fp(t,P,n,i)}else t.emit("unexpected-response",E,I)||xt(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,A,C)=>{if(t.emit("upgrade",I),t.readyState!==_e.CONNECTING)return;E=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){xt(t,A,"Invalid Upgrade header");return}let b=d1("sha1").update(p+x1).digest("base64");if(I.headers["sec-websocket-accept"]!==b){xt(t,A,"Invalid Sec-WebSocket-Accept header");return}let R=I.headers["sec-websocket-protocol"],D;if(R!==void 0?y.size?y.has(R)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":y.size&&(D="Server sent no subprotocol"),D){xt(t,A,D);return}R&&(t._protocol=R);let U=I.headers["sec-websocket-extensions"];if(U!==void 0){if(!_){xt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=y1(U)}catch{xt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(M);if(V.length!==1||V[0]!==Mn.extensionName){xt(t,A,"Server indicated an extension that was not requested");return}try{_.accept(M[Mn.extensionName])}catch{xt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Mn.extensionName]=_}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 ua(t,e){t._readyState=_e.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function v1(t){return t.path=t.socketPath,dp.connect(t)}function S1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=dp.isIP(t.host)?"":t.host),a1.connect(t)}function xt(t,e,n){t._readyState=_e.CLOSING;let i=new Error(n);Error.captureStackTrace(i,xt),e.setHeader?(e[up]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ua,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ul(t,e,n){if(e){let i=f1(e)?e.size:b1(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${hn[t.readyState]})`);process.nextTick(n,i)}}function I1(t,e){let n=this[We];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[We]!==void 0&&(n._socket.removeListener("data",fa),process.nextTick(hp,n._socket),t===1005?n.close():n.close(t,e))}function A1(){let t=this[We];t.isPaused||t._socket.resume()}function k1(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",fa),process.nextTick(hp,e._socket),e.close(t[g1])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function cp(){this[We].emitClose()}function C1(t,e){this[We].emit("message",t,e)}function T1(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,lp),e.emit("ping",t)}function P1(t){this[We].emit("pong",t)}function hp(t){t.resume()}function R1(t){let e=this[We];e.readyState!==_e.CLOSED&&(e.readyState===_e.OPEN&&(e._readyState=_e.CLOSING,xp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function xp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function pp(){let t=this[We];if(this.removeListener("close",pp),this.removeListener("data",fa),this.removeListener("end",gp),t._readyState=_e.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",cp),t._receiver.on("finish",cp))}function fa(t){this[We]._receiver.write(t)||this.pause()}function gp(){let t=this[We];t._readyState=_e.CLOSING,t._receiver.end(),this.end()}function mp(){let t=this[We];this.removeListener("error",mp),this.on("error",lp),t&&(t._readyState=_e.CLOSING,this.destroy())}});var Ep=ue((TD,bp)=>{"use strict";var CD=ha(),{Duplex:O1}=pe("stream");function _p(t){t.emit("close")}function D1(){!this.destroyed&&this._writableState.finished&&this.destroy()}function yp(t){this.removeListener("error",yp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function L1(t,e){let n=!0,i=new O1({...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(_p,i);return}let d=!1;t.once("error",function(f){d=!0,a(f)}),t.once("close",function(){d||a(o),process.nextTick(_p,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",D1),i.on("error",yp),i}bp.exports=L1});var fl=ue((PD,vp)=>{"use strict";var{tokenChars:M1}=ri();function N1(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&&M1[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}vp.exports={parse:N1}});var Pp=ue((OD,Tp)=>{"use strict";var F1=pe("events"),xa=pe("http"),{Duplex:RD}=pe("stream"),{createHash:B1}=pe("crypto"),Sp=da(),ur=ni(),z1=fl(),U1=ha(),{CLOSE_TIMEOUT:H1,GUID:G1,kWebSocket:q1}=ln(),j1=/^[+/0-9A-Za-z]{22}==$/,Ip=0,Ap=1,Cp=2,hl=class extends F1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:H1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:U1,...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=xa.createServer((i,o)=>{let a=xa.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=W1(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=Ip}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===Cp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ps,this);return}if(e&&this.once("close",e),this._state!==Ap)if(this._state=Ap,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(ps,this):process.nextTick(ps,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ps(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",kp);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){fr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){fr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!j1.test(a)){fr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){fr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){gs(n,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=z1.parse(f)}catch{fr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&p!==void 0){let y=new ur({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Sp.parse(p);_[ur.extensionName]&&(y.accept(_[ur.extensionName]),m[ur.extensionName]=y)}catch{fr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={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(y,(_,E,I,A)=>{if(!_)return gs(n,E||401,I,A);this.completeUpgrade(m,a,x,e,n,i,o)});return}if(!this.options.verifyClient(y))return gs(n,401)}this.completeUpgrade(m,a,x,e,n,i,o)}completeUpgrade(e,n,i,o,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[q1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ip)return gs(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${B1("sha1").update(n+G1).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;m&&(x.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[ur.extensionName]){let m=e[ur.extensionName].params,y=Sp.format({[ur.extensionName]:[m]});x.push(`Sec-WebSocket-Extensions: ${y}`),p._extensions=e}this.emit("headers",x,o),a.write(x.concat(`\r
|
|
15
15
|
`).join(`\r
|
|
16
|
-
`)),a.removeListener("error",kp),p.setSocket(a,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ps,this)})),u(p,o)}};
|
|
16
|
+
`)),a.removeListener("error",kp),p.setSocket(a,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ps,this)})),u(p,o)}};Tp.exports=hl;function W1(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 ps(t){t._state=Cp,t.emit("close")}function kp(){this.destroy()}function gs(t,e,n,i){n=n||xa.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} ${xa.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 fr(t,e,n,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,fr),t.emit("wsClientError",d,n,e)}else gs(n,i,o,a)}});var qp=le(Fe=>{"use strict";function j(t,e){t=t-363;let n=wa(),i=n[t];if(j.NKRmZV===void 0){var o=function(f){let h="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",g="";for(let y=0,_,b,I=0;b=f.charAt(I++);~b&&(_=y%4?_*64+b:b,y++%4)?p+=String.fromCharCode(255&_>>(-2*y&6)):0)b=h.indexOf(b);for(let y=0,_=p.length;y<_;y++)g+="%"+("00"+p.charCodeAt(y).toString(16)).slice(-2);return decodeURIComponent(g)};j.ABqDZt=o,j.kFJMHj={},j.NKRmZV=!0}let a=n[0],d=t+a,u=j.kFJMHj[d];return u?i=u:(i=j.ABqDZt(i),j.kFJMHj[d]=i),i}var B=j;(function(t,e){let n=j,i=t();for(;;)try{if(-parseInt(n(1361))/1+-parseInt(n(527))/2*(parseInt(n(1234))/3)+parseInt(n(1264))/4*(-parseInt(n(1271))/5)+-parseInt(n(1247))/6*(parseInt(n(1091))/7)+parseInt(n(510))/8*(parseInt(n(465))/9)+parseInt(n(1621))/10*(-parseInt(n(1e3))/11)+parseInt(n(1724))/12*(parseInt(n(1018))/13)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(wa,251607);var Q1=Object.defineProperty,eI=Object[B(1311)+"opertyNa"+B(1059)],Fp=(t,e)=>function(){return t&&(e=(0,t[eI(t)[0]])(t=0)),e},tI=(t,e)=>{for(var n in e)Q1(t,n,{get:e[n],enumerable:!0})};function nI(){return Op||(Op=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function rI(){let t=B;return Lp||(Lp=[IDBCursor.prototype[t(823)],IDBCursor[t(1619)+"e"].continue,IDBCursor[t(1619)+"e"]["continue"+t(1078)+"ey"]])}function iI(t){let e=B,n={HTGwP:e(933),YZrFv:e(902),EcJcU:function(o,a,d){return o(a,d)},tMQTO:"hikvx",LtlKH:function(o,a){return o(a)},cimQE:function(o){return o()},Esvow:function(o,a){return o instanceof a},ouqOg:e(1643)},i=new Promise((o,a)=>{let d=e,u={zNWnj:function(g,y){return n[j(965)](g,y)}},f=()=>{let g=j;t["removeEv"+g(1188)+g(1139)](n[g(1564)],h),t[g(1218)+g(1188)+g(1139)](n.YZrFv,p)},h=()=>{let g=j,y={jujCt:function(_,b,I){return n[j(1720)](_,b,I)}};n[g(1560)]!==n[g(1560)]?(this[g(1304)+g(461)]=_0x37605c,this[g(1911)+"ileName"]=_0x56d5a2,this[g(1658)+g(1245)]=_0x1dccee,this._qosDB=y[g(1820)](_0x342d6f,this["_cursorN"+g(461)],g(1296)+g(1130))):(n[g(965)](o,n.LtlKH(Yt,t[g(1109)])),n[g(1815)](f))},p=()=>{let g=j;u.zNWnj(a,t[g(902)]),f()};t["addEvent"+d(744)](d(933),h),t[d(1738)+d(744)](n.YZrFv,p)});return i[e(941)](o=>{let a=e;n[a(1899)](o,IDBCursor)&&(n[a(1443)]!=="KMYEv"?this.on(_0x285df0,_0x5db126):pl[a(541)](o,t))})[e(1089)](()=>{}),ya[e(541)](i,t),i}function wa(){let t=["txvIBMS","s01zrxy","t0fWveS","uerfru4","CeTIu3i","A2fAEKG","sunguNq","C0jf","B0vqvxK","vNvqD0y","twznyKG","zgvSzxrLrge","B0XJveq","C2nYAxb0","uMLIzg0","m3WWFdr8mxW","x21LC3nHz2u","Cgf5Bg9Hza","Dunnwhq","B3bLBKrc","y3jLyxrLt3a","x2LZtM9Kzq","v2rhwM8","y2XVC2u","s3rktxa","rwTPtKC","Axnby2TdBgu","v0PNu0G","sK1oruC","D2vxz3u","x2HHBMrSzu8","x2XPC3rLBMu","EvbTuwW","De1HBMfNzxi","C0Xf","B29Tv1q","y1nmuuS","BMDuAw1LCG","we1YrwG","B3jLtMfTzxm","t3bLBKv2zw4","yNL0zu9MzNm","CNDKsue","yw5Nzq","Aw5KzxGGB3u","AuTiwei","wKrTv0S","C2v0zgi","EvHIshu","zu9isgu","tK5cvMW","BeHOCvC","rwvAqMu","C0XPC3rLBMu","rLDt","DMH1u0y","sKjXtNK","tvPowwq","Eertugm","zKDtse0","wMfrqwG","qwfKyKq","BhDqqKq","wwfwBMW","yvbWzha","zMLN","tffoA2W","uLjpuG","C2v0u3rVCMe","zxjnzMy","uLnXDvy","mdaWmdaWmda","r1PjCwm","BLb0DNO","C1vuqNq","Dhr3Awq","s3jmBui","y2rvv2S","rwnky1u","EvDqrK8","yNvMzMvYzwq","DMfbzLy","ndq2mdC4nfL2thDwqG","wejwDfK","BgDVBMi","u09uAgO","CfPusfK","y2HLy2Tszwe","rNzVqve","x25HDMLNyxq","qw9TsNO","wNL6u0W","x3bHDgHlzxK","q1zpq24","veLfEMm","wMrZzum","ywrKrxzLBNq","Dg9Y","BxPmwfC","tevHDhy","C2vUzf9Hy2S","vuHZC3G","DgTyDuq","A2v5","u2Xey2y","DxrMofDYAxq","AerrCNm","z2v0sxrLBq","CMvJzwL2zwq","zMzmAw5L","q2HJy00","zw1PDa","wxPfDxy","y0TkDgG","Aw5Lza","z3jWzhG","BNrLCG","z2zdwgu","zgDTvvK","tuXYz0e","rg5AqvO","s2PjBuq","quLduNq","Aw47y2HHCNm","C1DmtMq","yMfSrxzLBNq","Bg9N","AvzpANa","qwjXthG","zxzNve0","x3jLy29UBMu","wxbiDMm","txDuEe0","vK9Or1a","sKXbCLu","wgXgu08","B2flDuq","s3b3BxK","rxzeyLe","y2HnyxHuCMK","AgfZt3DUuhi","C3vIyxjYyxK","igzHAwWSig0","wfDZrMe","zgvJB2rLzey","CMvHzhLtDge","ChrVCG","ywDLrxzLBNq","v3vsELq","rg9PBwW","yLfYr1a","ywnRx2nVzgu","zg9Uzq","AvrztLm","sKrlD0y","wurlyLO","A0v4vgW","r0z5A2C","tLrtrMu","y3fItKS","y29Kzq","CgfNzxnOB3C","t3fLEKG","B2zMBgLUzq","BMrWB2LUDfq","BLD3DNG","vM93yNO","yNrUCgu","x2rPC2nVBM4","CMvHzg9UBhK","q2zpCfG","zLzvwLa","AgzMs3m","y2LTuuu","rffrqwW","Cg93","CM92AwrLige","B3LkuMO","ANvQq3q","u2vlEue","B3bLBG","AMTHDMG","DxnLCKLW","qxvRyKq","AwDHDg9Yt24","EKrYq0W","ufntrem","ywrZCue","y1zRvK0","C1r3sve","ywnR","x3DZ","x2rItMfTzq","weHWrgy","igzPzwXKoIa","ywnRtxnNswq","uMHewNa","BgLZDgvUtMu","shzACfm","zxH0ugf5Bg8","x19LC01Vzhu","t3DRBLy","ruziEgi","uwrRD2i","Ae1LC3nHz2u","C2fNzq","yxbWzw5Kq2G","tLPHyw8","zhnzvuq","zw5HyMXLvhi","tNzivwK","y3nbCeq","quDvwgG","tezRDge","zK5qALq","vxvbvNq","y3vYC29YlNm","zNjVBujPDhm","y29UBMvJDgK","B2Dsue8","rLv2y1O","B3jpBMXPBMu","zxjYtxnN","BvnLyu8","EMHys3m","zKHuAgu","Aw5N","BhPKB20","zhjKBuW","vLPLBgq","BgLTAxq","uhjuzwO","CenJtLy","u1z5wxy","vfnptuq","yxHct3C","D0fkzeG","svHnAfy","D2fZq2XLyw4","B2nRzxrtDwm","y2HnyxHdB3u","x194x21Zz18","ywDLu2HVDW","DxbNCMfKzw4","CNHdBMG","tw5LAu8","Dg9iyxnO","zufJAW","zhbYENO","wLbmrM4","t01NB3u","yxKSihrYEsa","sg1QD3K","ihjLy29UBMu","y05cqw0","qLDzyNG","uNbmthC","rxn2B3C","thDjtxy","AgncyNG","zNjVBuj5Dgu","v2jtque","u0DXC1K","y3vYCMvUDeK","DNDcwLu","B3HXtgC","Bg9IywXty28","B2zM","yxLQuwu","x2n1CNnVCKy","qxLXBgm","su5tvefova","qvH3vKm","y3PXzvG","uMvJB25Uzwm","zw5HyMXLuw8","Cg9PBNrdB24","zw5NDgG","zM9Yy2u","A05otM8","ufrfENy","BMnLq2XVC2u","BNrfBMrWB2K","q1LZuMC","lcbOB3n0BMe","Chv0","uwv0sxy","B25SAw5L","zuPyDfO","CePSrMC","A2v0ignVBNm","A1DOyKW","zhzgsw0","BKHrDwe","AxmGDw5Kzwy","s2rADhK","BMT2vM4","DMnJrMe","EuPct1y","zgrjrcWGzgu","sfrjA1q","Dg9cExrLC0W","D2HfAuS","y1nZy24","yxGGCMv0CMK","B1z4vve","uhHyAeK","vKHYzxi","sKXHtfy","vLfNAfu","zxj2AwnL","Cg9ZzeO","rLnAzxK","uw9Vrwq","B25mAw5L","Dg9cExrLCW","q09oveLovuu","tNvpr3q","rNvJtgO","EMzJAwe","ihrPBwvZ","zw1VEw4","twPIquu","vvbNvvG","y2vZC0HHBMq","x2DLBMvYyxq","qxnOCg4","tuLAA2S","DKXPA1a","vff0v0K","ywnRpwzYB24","zeTLu2q","rxDRCvq","zxjFywnRx20","EwXvv0q","BgvY","zKDUug4","yM9KEq","zwXNuLC","CYbHBhjLywq","z1rPBwvVDxq","x2nYzwf0zvm","vufNEgC","CffREMK","zNjVBNrPzxi","Ec1TC2CTCw8","Bwu6ia","yMXVy2TLza","y1vjwhi","FdL8nhW3","z2vY","C2DPza","qw5AEuG","BwLZzq","yNL0zxm","Awnzwva","rezrsxK","sxjHANa","zw50","BLDvCNC","t29Pr0O","D24GCMvHC28","qvPLyw4","q1fAq3O","x1fVu01HBMe","DMHUCNO","BwfUDwfSihi","y29UBMvJDca","EvnytMO","zhjfrK4","Dw5KzwzPBMu","Ag1MsfO","CMvWBgfJzui","yw1Lu3bHy2u","B2nRzxq","sKPUtxu","ywnRDxbfBMq","nZjbCLDMzfC","tMfTzq","yxv0BW","CIb0DhDjra","CMvJzxzPzwq","yw5Hz2vY","BMrLEa","uMLqzNy","z2v0u3rVCMe","Ce9yrMq","z2v0q3vYC28","CunxAKm","zNjHBwvuExa","x29UugfNzu4","tefkqM8","zv90Aw1LB3u","DxjS","Beznvfe","Dg9hzw5LCMe","Cw9tsuC","y2vLCfK","wKzZrxG","z3bxBhi","tK9SEeW","r2vjyxy","rLzqre4","Bxros0C","A2LZu2W","y3vZDg9Tshq","thnwshG","twvZC2fNzuu","CgLUz0XVC3m","CvHUze4","yxnJCMLWDa","z25oEvC","EKf0vKC","y29UBMvJDeu","Avjcseq","sKvYwLm","Bg9Nsurhzw4","B2nRzxrgywK","BxHAsfy","s1L6vMe","rwLPBMi","ChbL","mtG3nJCYDuPeCwjz","qKzlyLy","x29Ut3bLBG","r2nREwG","se5zDey","CNrMBuK","CNnVCL9Uyw0","ALzIsNu","zxf1ywXZ","D0PYDxC","EuHzzMG","ueXuv0W","B25tDgfYDfi","C2vYDMvYvgK","C2v0y3vYC28","whzhvM8","q1jpq1i","ne1yDNjWrW","Ce5nvg8","Ahr0Ca","DK5pAwq","tLHSsg0","BeHHBMrSzxi","DurMt0S","zePNBNm","BgvlB08","DhHvvLm","C3nHz2vfDMu","C3rVCcbPBw0","B25fCNjVCG","AwXK","C2v0","t1HIq1u","zw50zwqGDhK","m3W3Fdb8nhW","BwLUAvbYB2C","tgPXAw4","AvzIC3m","vKXmywi","t1bhCfO","B3v0sw50zxi","zgvS","z3v2EMi","q0LPrK0","zw1LBNq","z3vcB28","B25szwnLAxy","B0zLtee","zujyrNC","y2fuDLy","zxjFDhrS","zg9uDfK","B2jQzwn0u3q","BwvKAwf0zwW","rufhr0C","zu5mreq","Cvvbvuu","o2nOyxjZzxq","uMThzve","vwTRwfC","y2HHCKnVzgu","vfHwExG","CMvWBgfJzq","rLH6zvO","z2vjBMzVu3K","y1vVsw0","ChjVy2vZCW","CMvZzxrfBMq","D2T1sgy","zxjHDg9Y","BwvZC2fNzq","DKLMBe8","s2j0wKW","D2LYB2e","sfrHtNm","tw9lsuy","ywXSzwqGBxu","zKzlvgq","EMDXwM4","AKjtDfi","CgvYC2LZDgu","AMfTrNm","CMjyuw8","CMLUq0W","tKLxugC","BgrQAhC","z2HYshq","zgHgA1y","x2LUDgvYDMe","zw5JB2rPBMC","ywX3yxLZ","zKLgq0e","qw1VDw50","B3jRig9MzMW","zfrsA24","m3W0Fdi","vgHIq1a","x29UvgLTzw8","Dg9mB3DLCKm","DMfSDwvZ","Cgu6ia","B3vUDa","x29Uq2XVC2u","BMv4DcGPigm","AKXrCM0","q2HgD0W","ywrKt25L","s2HmBhi","Cg9PBNrbBMq","Aw9UvgLTzw8","DMfS","yw1LoIa","A0nbvKm","CvzkrMi","s2njyvO","zwvKzwq","Du9WrKq","CNrRt0e","zhz1Cu4","zePwANm","CLbhEwS","vu5Nr2G","u3jWqu8","uLbbqNy","u0nZrwW","CMvZzxrdB3u","BMnVzgLUzW","zuHVv2m","Ef9MCM9UDgK","DfDhv0W","rfDqEwq","AxjLza","AunVrey","yNrOqKu","AevYCM9Yrxy","Dgv2qve","suDgzfu","Ahr0Chm6","x2HHBMrSzvi","A1bKswC","r1PsDMW","qKjSq0S","C3jJ","tNrQu1G","r3nnwNG","vfbuBNm","zg9Yr0m","yxnZAwDU","wKXbufe","s2HHufC","z2fmA1y","Bu9osLu","ufbJBvC","B0L4C28","DgvZDa","Bwf4twvZC2e","Cvr5BNO","A0HfzgG","vgfN","AuT0s1K","rufqwKS","z0X6zwm","vefut1u","Aw1LCYbPBIa","uvPltKe","CgTqqKm","BNruCMLLC0m","tgzxzNa","ALP3Bue","C09tCKe","yNLlveq","ExbUt3O","B2nhCui","CMvQzwn0","C25zDgS","D3jPDgvvAw4","rMHiz2y","tKfusvzfx0u","CwHxB2i","AxnFywnR","zM9YrwfJAa","tLPxzfK","ywrK","yuXZrwO","ihzHBgLKihm","Dw5ZAwDUzwq","zNDZxZeUmc4","rhv5Buu","B2XKvMvYC2K","DKfjwve","tfHrzxe","BKXPBMu","wKvpuKy","tgXkC0G","v0rJEMq","x2fKzfDZtgK","tuzuq1O","ze9ywvO","vw9yr2O","u1LVEvK","y2XVC2uSihC","zvjwqKO","wMTHDge","y1DYDeW","vu9csLG","yuDxAei","Dgv4Dc9Qyxy","DgLTzw91Da","EKrMzgW","yNvqy0e","AfDjDxK","shzrqvG","zsbHihn0CMK","txbAs20","A3bkvfi","x2rLyNvN","y2XLyxi","BeHhCeO","CMvKDwnL","x2LZqNjVD3m","y3vYC29Y","qvbpy1m","tvvdENu","CNroDve","t0rWEgq","CMfTzq","x3jLywr5q2W","B21Ry2K","DxjdvhC","yxjYyxLIDwy","uKXNr04","BuHcBgK","Dvzns3m","ihbYB3rVy28","tgLZDgvUzxi","yxv0B21HDgK","ANbWz2y","zMXVB3i","zKDtvM0","q09otKvdveK","CMvTB3zLq2G","A1n0yxr1C0m","CMLLC0nVDw4","CLDOEfe","rKvxEeW","zcbLCNjVCI4","zw5fDMvUDa","CM5duLi","DhbizwfKzxi","r0LysMm","y3ruAw1LB3u","qu9qAgC","DevqufG","BM5Ly3q","B3bLCNr5","ExrlwM8","AuDrwuK","DMvYC2LVBMm","ywXSq3vYC28","t21esxm","vhvOq3u","r1ntqxG","CMvHC29U","rM52zMO","EuPlrKG","CK5hqwG","C2vYDMLJzs0","t1PjrNa","wwn2rgW","C3rHCNq","lcbxzwjtB2m","Dfvdzuy","x2jPBMfYEvq","tMHuDMO","D1bcq2e","zv9ZDwnJzxm","thvdEgy","zLztAxq","qxfzuNi","z1rAuhe","B25dBg9Zzq","Cw9Z","qw5tvwu","wfz4zeK","CMvJB25Uzwm","Aw9Vyxa","Aw5JBhvKzxm","EgjWuNq","C1fLCvO","u1Hyz0i","A2v5CW","ExbL","BKTLwuC","CMfTugfYyw0","uhjbz1a","wwDdu0O","zgf0yq","D3m6lY8","Cuf3uwe","y3DICwK","Du1dre0","vKrLAK4","ue1ry2q","yxnL","zKfPwfK","t1jUDu8","yMLUyxj5vhK","DNL5wxq","B05crMO","EMTlq0q","AvfquMK","Bwf4uMv0CMK","B25nzxnZywC","ywr2yw5Jzq","DKTJD2y","ywHnwxq","AwXLx25HBwu","wxfZv2e","sMvNrxG","DcbSAw1PDa","y3vpywW","rMrJuhK","rKLmrv9ot1q","CenvA1y","yxD6B3m","Dg9cExrLC0i","weLVwNa","DgLLCKPtt04","EuDJD2O","Dxb0y3q","DhDVCMTdAge","v0zRsMi","BuvszNi","uezpAvO","z2v0qwXS","sM5czfi","x3DZsw5ZDge","tvPtDe4","CMvZB2X2zq","uwLHEum","BMf3tKO","EMnYrMG","CNLkyxm","zfD3Du8","DuPzsM8","ExPntwW","EurTrui","EgXnu20","x2rPC3bHDgm","x3nVy2TLDa","sKXOuLe","uwHZqKm","uLj5zMq","we5nBLe","zgvIDwC","Ew5Qteu","y3jQrei","Ee91Cgi","AgfZ","D0fVCgO","tejTAKC","m3WY","zhbpzKe","qvr1AMe","Ae1uEgy","icSG","y2fSBa","CM9YrxzLBNq","D2Xdwva","zhHRvu4","DNbtDvu","zhLdtM0","CgLUz09Uy2u","t3noshi","DeDXCLm","whHpy0O","DezuC24","z2v0q3vYCMu","yxv2Che","AhzNyuq","tg9Nsuq","B25ozxr3B3i","z2v0","CgXLyxnLiha","t1jjs1e","B2zMC2v0","vgLTzw91Da","BML0AwfSAxO","zMrQEvC","x2TLEvbHDgG","D2nPCvy","sezVt2i","zxjYB3i","EwfXru8","vvrsDLq","s0XuAha","tvrZDLa","B0jRuMW","B3nLza","Dhj5t3u","zK1bDK4","tKfesgG","AMznswG","wNzVBge","y29TCgXLDgu","zgPeCxu","rxDIDhe","u2TPCcbWyxm","z2vtEw5J","BwLUzW","x21PBMLoyxy","reXAtMe","qwXYz0K","AhHYq0e","DLHXs1C","D2rvqMm","mhW0Fdj8mxW","ywXty29Wzq","x2DLDeLUDgu","y2rYrhC","Bhm6ia","tw9KDwXL","q0Xpu0LorW","C3vJy2vZCW","v3b0rfG","qM55y2S","r0P2r2S","yw5ZzM9YBvq","seTYvuC","Bg9NsurozxC","x29UrxjYB3i","DgHLBG","tg9JAW","zvbguLu","CMvHzfvjBNq","zxrxB3jRq2G","wvf2Cuq","C2rVy2S","z29PBMCGyxC","DhLWzq","uLvTv1y","BfrPBwvVDxq","v2nsCwW","BwfW","reXvtM4","y29Uy2f0","vK9eDLG","Cgf5Bg9Hzfq","uMvHzcbWyxm","Dunpu3y","sK9oDei","r3vWAgm","BgLUzw5V","thHwrxy","vMrTvKO","thrSs0G","x2nSzwfYvgK","y2PzExa","Aw50zwDLCIa","zwn0","zNjVBuHHC2G","DvrRs2W","ywnRx2LK","vgvNv3G","jMPZy2fSBgi","CMfUzg9T","Fdz8m3WYFda","EvjLy29UBMu","BwvY","x2LZtwLUAvq","tNfJu2q","q3P3vKu","ve1YBMi","y2Hvu0K","v3vAD2m","uMP1rwu","x2LZsw5PDa","zwj2rgC","AxnAzxjV","z2Pjs3q","wLDHs3O","D0Lquwq","Bxz4z0C","qNbnteS","D1n3u3K","v2LUzg93","B25JBg9Zzq","sNjeqMe","qLHlswq","vMTpwNG","ntv3zLrdrMO","nxWZ","D2P2z04","rKTbsM0","tg9NsurozxC","Ec1TC2CTy3u","Ec11C2uT","ru15zNC","x2LUAxrqCM8","y09su0u","qMnkvva","rvjst1i","zLfhzLC","D0Povgi","zK1rBMy","ufzSB2m","Eg9RqLq","s3DZuMK","ntjosezpz1q","q29Prxq","EfrSq3O","tvHiCva","DgLUzYbZzxi","CwPusKC","D3nSEgy","CLzHBhvLCW","qK13yNC","q29Kzq","vwPwvwu","zxjYtM8","rLzHs0G","zw5HyMXLqxu","CNjVCK1LC3m","vfH2Ceq","yM9L","Dev2zw50","AwHrD0i","ChPPwhy","vLHsAMe","rwnpDMy","vMPiq1O","ueT1qvi","zNLdwue","ugvqEhy","wfLlAgy","ywnOzwqSihC","x2zVCM1HDeu","AKrrqNG","A2Tdr0K","BMDLza","uvHPtxq","r1fxA2O","v2vIu29JA2u","tgfXywm","Dg9oDw1Izxi","zgvSzxrL","s1jrBei","sg53Avi","t29xBwm","BwvZ","z3fmCuK","EKDuDLy","zMLSDgvY","BK1QEwW","CKPbCwC","seLQzxG","CNnVCKzPBgu","BMTdwvK","r3Psr2i","tefOEgq","CNzHBfzHBhu","AMvJDfn0B3i","CwHhAxu","DMvUDa","qMvWvei","CgLUz19VBMm","rgvKAwnHDgu","sgPiywm","uhjPBwfYEuS","lcbTyxGGCMu","zfjQyK8","AgvKtwf4uMu","wMzqAwW","x3jLBw92zvC","s1LQCuu","ihzHBgLKigq","AM9QC3u","Aw9Ul2PZB24","tMHRqLq","y2f0y2G","v0vLEe0","mti2mtm2nwjjwvbNvG","x2LUAxrhBg8","C2v0sxrLBq","u0DZsuu","quXm","tMntA3i","B25LCNjVCG","Aw5KzxHpzG","nhWZFdv8mxW","zfrZCKi","ChjVDg9JB2W","zxH0zw5ZAw8","sfvetw4","ENjJq1i","ugnJCvO","ExveDwK","ihrYEsbYzwm","CujyBwe","CMvZDwX0","s1P1ueu","BNLgDva","BMCGzMfPBgu","yLzeBvC","sffXsfu","C2vYDMLJzq","Dg9tDhjPBMC","AgfUz2u","txbcAeK","DwzuywS","BezSDxnO","CMTLCKDSB2i","A3DICfm","BffUELC","qKPTwM8","x2HHBMrSzva","C0fxruu","zMjNyNq","DMXuqKy","B2LUDfjLywm","yw1L","DeLUDgvYy2u","BgncA1O","rhrrDwK","AgPUsva","u2vXsuq","yuvqEMe","D2fJAxy","ywnOzwq","BMvY","C1vHCvK","AKz2wfi","Bg93","CwLcBfa","BNvTyMvY","qvPVy1m","AgLNAa","CMjLt1e","AxnrB1nnzxm","rMzIBwW","wgr2u1y","yMDwsvi","u2TOBNi","igXHCMDLCIa","x3bYB3rVy28","Dgv4DfbHEwW","CKDTuu0","qLrNvxe","r1nfB1e","mdaWma","AxnmB25N","sePIvLa","yw5KugK","B25byu8","z2v0qwXSs2u","x0rctMfTzq","tNLzwgS","x3bYzwzPEa","C3rYAw5N","zgvMAw5Luhi","zLrsAe4","AgXZtLC","u21QC1a","AgvHzgvYCW","AM14qNG","rhLSuNO","zw5JB2rLrNi","BMjOAfe","yvzWELK","veHjyuO","CNjcvhO","reTgyMq","x3nLCuLK","wNHTANu","BhnPD0y","tuvXqxC","s0jjCLe","C0nVDw50zxi","zw50tgLZDgu","Cen6CfO","qvP2u2m","t1bftL9fuLi","rLjOqNK","D2HMvMy","AgrIyMK","ywnhv3e","B3nLrxzLBNq","CMvXDwLYzwq","txjuDwK","uMvvsxi","DxbKyxrLq3u","qLL5q2C","B3L1wNu","zeHpD1q","C2vUza","zMLUza","CfDHBLC","AxnbCNjHEq","zhHJuLO","tLLqC3i","rxzLBNq","sfDrquq","zMvY","A3vvBei","uhfbtLG","ywDL","x2LZv29YA2u","sLzAB1K","CMvTB3zLrxy","sLPQC08","sejpC2m","BNDbAvC","C3rYAw5NAwy","Aezoz2G","DKLqzgm","zMLSzw5HBwu","AhbMr0i","x2LUAxq","vg9Vy1e","qMT2yKO","ChDbvfq","ywDLsgLKzq","x2n1CNnVCK0","Bwf4tg9ZC0m","ntG3odiZv2XrqMHS","z1Pky1i","sw9MsLO","AxnszwfKEq","r01xAKm","y291BNq","yvDetLq","wKLku00","EMH1Eg4","BMfTzq","BIWGAg9ZDg4","u3rYyxrLz3K","Dxrjza","nLzjtfP1sG","yMLUza","mNW5FdeW","yxrHlcbKyxq","Aw5bDKe","y3jLyxrLq2W","C3bSAwnL","t2jVBK0","D3zvswi","DgDQCwu","C3vIC3rYAw4","suvtx0vsuK8","zw5XDwv1zq","vwzLDfe","rxjYB3jdB2q","AxnTs2e","mxW1Fdb8nNW","mty1mK96tNDHwa","B25pCgvU","Cg90te8","yw5uEwi","zxjFCw9Zx2e","AvfuvNu","Efnzyva","nta1zKvnsLnm","tufyx1jfvfi","rKrovee","D1LAs2G","DhjHBNnHy3q","uMLtrxm","C3bSAxq","q291BNq","ign1CNnVCIa","seTAte0","DKHREKO","AgTwu3m","BMCGDxjSoIa","t0fuu0K","ywjVCNq","CePZCe4","Bwv0Ag9K","u0zYreK","uhfgsKO","zxHWB3j0CW","vefhChe","Chnft0O","y2HLy2TdDxi","EuHeugW","EvbWsNm","y3vYC29Yx24","D1frweK","v2XWq0m","uNzOEu4","vNb6veW","x3bPBMC","Cg9W","DgLTzw91DcW","x2n1CNnVCK4","y2LUEgC","yw51Ce1LC3m","B3bLBIa","AxnrB1nby2S","sureuvi","q2PkB3i","z2v0t3DUuhi","CMv0CNLdB3u","B25TzxnZywC","CMvUDevUzha","ruHiBMC","CgfNzwHPzgu","Cw9Zx18","rwTrwLa","yNvMzMvY","ig1LC3nHz2u","uNHnrLK","mxW0Fdv8mhW","pxv0zI04","B2fK","vvbJEu0","qvbRCKK","q0Xpu0ve","C2XPy2u","DhjPzxm","txDbDuq","zfHquhG","CKTMy2u","x3fVC0rc","shnxyKW","ve9ptMu","ywzL","s1fJBha","x2LZtwLUAvC","y29UC3rYDwm","C3D6sxO","y3vYCMvUDeu","x2vUzhbVAw4","t1LcEuK","zcWGDw5RBM8","yMrFzgLK","yKn6B0q","zMvIAMS","Cu5Qr2m","sgfxChq","t3vnsxu","zwn6thm","vMTxrLm","CKPVEgW","wg9bsNm","BMrWB2LUDca","rhr1Agi","CM92AwrLihC","B3rHzxy","BgvUz3rO","wKjHrM8","mZeYotK4vg1lAe56","AgvHzgvY","z2vrDwv1zuW","EKPSBNm","vefpCKq","v1jAtNe","BevtBhy","tK1mzMe","qwjVCNrfCNi","txDHEhi","C3rVCMu","terUufu","suflz0W","D3fNzhy","zwnVBM5Ly3q","BwzxCw8","AwLKCwu","nhWZFdj8mhW","Dg9vtey","B3jL","reiGzMfPBgu","mNWW","wwXSCKi","D01ks2O","C214tvO","suznBeC","sKrSDNe","uxHwwuO","q3vZDg9Trxi","CxvKDLu","AwXSihvZzsa","zMzLCG","CMfNzvn5BMm","t2DvCvq","BxnNsuq","DgDZrva","z2v0s2v5","DM1wDuy","x2rLC3rYB3K","A2nyAum","zcWG","s2DNquy","BNb1B3y","Efrurw52","D0r6Ahm","yxvbzLC","DeLK","se9fv0K","wKzYwMe","vKzLqM4","yK9REu4","qM5YBue","vKfKBuO","uvDtCLy","Dw50","y09Wzw4","uxvLDwu","wMnLtfu","zLvnEfi","ruvzuvO","DgHHBIbSB2m","C29Tzq","y0fwAuC","x29UtwvZC2e","vLr4swq","ChvZAa","y2uGBM90igK","EfvZzuvUDG","AwXLtMfTzq","C2vUDa","zvvYBa","rwL5q2y","uwDkzMu","CgfYC2u","DhjPBq","vfHgs1C","Ae9Wzw5fDMu","rejhD0q","u05Msvm","B25Uzwn0Aw4","ufbtrMK","C0HqtxO","B3vXt2C","B25VCgvU","uKnXsMK","twLZC2LUzYa","u1jTtee","wwD1DfO","rePJyMC","AK9pyvi","yxKSig5LDhC","y3jLyxrLrwW","t1bftG","BMvLzf9Hy2S","Cwv6sMS","rfb4vuK","ve5iAKi","x2nVBM5Ly3q","yLDLzKu","EufMEKG","x3bPBMDqB24","y2XVC2veqG","EvLxrxm","sLjAt2q","rMvJr2C","Auj2DwO","ihrPBwvVDxq","sLDIs0W","z0zLvxK","EhzusLO","igfYCMf5yNu","wNnlAuq","rNjVBNrPzxi","wgLjt2K","BM93","BNHWsNa","zKvhvgu","C3rLBMvYCW","sgHxEw8","ugDAt0S","BwvZC2fNzv8","yNL0zuXLBMC","Aw5L","BfzVCeW","wK9Pue4","y3jLyxrLt2i","EhrMCKS","tvDSqNG","sK1Yse4","x3vYBa","AurewMC","sLnptLa","y0PxwhC","y3jLyxrLuMu","shDUDhe","CNnVCL92ywW","t2jQzwn0","wMfKyK4","wK1bvMC","q3vZDg9Tq2W","AM9PBG","Dw5RBM93BIa","yK14rvq","zMTRzhK","zw5KCg9PBNq","ANjVrvq","C0nVC04","mtf8mNW5Fde","s291r3u","DxjVtxi","tMLksMe","BwXWCKe","DcbVzIbYyw4","wLvTtNy","t0zHveK","wK5tt0q","wvHXCNa","ihn1y2nLC3m","DxrVuMvJB24","zxbJu1q","vxbKyxrLq28","Aw9U","yNf6BNO","wgfhrge","rKPMtMq","t05ozge","D2LSBfjLy28","r3zrvNu","tg52Dvu","zg1Ov3O","CgjICdi","B3jRzxjhBg8","DhPJBuy","y3jLyxrLtwu","s2LIC2G","ELvYvxK","DLL4AeW","DMfSDwu","t2nbvKi","zNjVBunOyxi","x0vysvnu","Dgv4Dc9WBge","m3W0Fdf8mhW","sLnfAMq","AenSB3nLrxy","yLLkvvq","wgDhELO","DhjPzxmGCMu","s2XTB3m","r1PiCey","x2nSzwfYugK","CwXrEvq","CgLUz1rPBwu","zNjVBu51Bwi","yMzxwuG","vgHMEva","A3HABvu","r296wNO","EwjvyMy","De1rve8","txbuDvG","C29YDa","ywXSB2nvBNm","sfrhD1a","q29UzMLN","x3nLBMrby2S","zNvUy3rPB24","Cvnev1i","zeDSveC","tMfStum","y3r4","yxbWBgLJyxq","Dg1XB2C","CLzJvKe","svbsA2W","zxmGCMvHy2G","q3vgELu","wu5tBMS","t0X4rNK","z0PWAeS","wffmvKm","ignVzgu6ia","zeTTu3G","reP6Du4","CKnbr2W","BgLUzq","AefJA01LC3m","zMX1C2HfEha","yMfJA3vWigu","yxbWBhK","DMvYC2LVBG","zxq9DxrMltG","y2f3ANa","ohW1Fdb8mxW","uNv0sKm","y3jLyxrLrxi","DgvmB2Djre4","EK9LEwu","rfrKCwW","tgvRyxa","yuL5zeq","yxrLq291BNq","Cgf5Bg9Hzeu","x3bPBMDmB3m","D01wEwS","tvzYyNi","BK5ABvK","ohW1Fdf8mta","DxLbrKG","EKjcCKG","sMzbtK8","tuvtu0fhrv8","qwDdre8","AKXIEgG","Cgr0vMe","EvDSDwO","swvzq20","rgzcsg4","ChjVDg90Exa","rurkCK8","otKYndeWCgDQqMTX","DhzMAKO","A2nXCMG","y29UBMvJDfm","DNzuyvu","DMj6yxm","shPwBeq","x29WDgLVBNm","CvbAtvm","Aw5PDcbrB1m","re5xDu4","ENvtt2C","Ew5iBu0","CM92AwrLigi","DgfYz2v0","uLjowwe","ALzfCKi","B25tDg9Wsw0","qLHnu2q","zuntBK0","uMTfuhe"];return wa=function(){return t},wa()}function sI(t){let e=B,n={iVOjp:e(903),VFeBn:function(o){return o()},gZJcR:function(o,a){return o instanceof a},tGqrS:function(o,a){return o===a},bKsGE:"store",UjVUe:"WHiFn",JZjsO:function(o,a){return o(a)},TXvpD:e(1369)+"or",fEGTe:e(1285),hvgaD:e(753),ZfPil:"doOvi",ycfGO:e(914),bYJUT:e(902)};if(_a.has(t))return;let i=new Promise((o,a)=>{let d=e,u={nXUrP:d(914),VXRja:d(902),ZoszE:n[d(1477)],DJzuN:function(f,h,p,g){return f(h,p,g)},PqANX:function(f,h,p){return f(h,p)}};if(n[d(889)]!==n[d(1082)]){let f=()=>{let g=d;t[g(1218)+g(1188)+"ner"](u.nXUrP,h),t[g(1218)+g(1188)+"ner"](u[g(1038)],p),t[g(1218)+g(1188)+g(1139)](u.ZoszE,p)},h=()=>{let g=d;if(n[g(1769)]===n[g(1769)])n[g(1410)](o),n[g(1410)](f);else try{u[g(1584)](_0x204f97,this,_0x989bda,[_0x5e4e17,_0x3b005d,_0x4d7105])}catch(y){let _=u[g(1214)](_0x4e1050,g(902),{message:y[g(580)],code:_0x541144[g(1191)+"OR"],error:y});this["_dispatc"+g(644)+g(446)](_)}},p=()=>{let g=d,y={UPgUX:function(_,b){return n[j(1235)](_,b)},GZIqc:function(_,b){return n.tGqrS(_,b)},cNBAm:n.bKsGE};if(n[g(884)](n[g(1028)],n[g(1028)]))n[g(1219)](a,t.error||new DOMException(n[g(1033)],n[g(1033)])),n[g(1410)](f);else{if(y[g(411)](_0x43fe7e,_0x97a1a6)){if(y[g(1714)](_0x34672c,g(1794)))return _0x20ce58.get(_0x4e16d9);if(y.GZIqc(_0x377f3d,g(562)+"oreNames"))return _0x405401[g(562)+"oreNames"]||_0x4299cf[g(892)](_0x4d11d7);if(_0x280562===y[g(1896)])return _0x3969bb[g(562)+g(1681)][1]?void 0:_0x3d3fe8[g(562)+g(1380)](_0x30453a[g(562)+g(1681)][0])}return _0x1c11e3(_0x4418dc[_0x4e7354])}};t[d(1738)+d(744)](n.ycfGO,h),t["addEvent"+d(744)](n[d(1546)],p),t[d(1738)+d(744)](d(1285),p)}else return this[d(859)].extensions});_a.set(t,i)}function oI(t){ba={KwsRi:function(i,o){return i(o)}}[B(1017)](t,ba)}function aI(t){let e=B,n={EZJpm:function(i,o){return i(o)},jDQBx:function(i,o){return i(o)},KQclp:function(i,o){return i|o},VjHCZ:function(i,o){return i<<o},qudvU:function(i,o){return i<<o},OuMIu:function(i,o){return i|o},nwcPr:function(i,o){return i<<o},rbeOQ:function(i,o){return i<<o},GzRGb:function(i,o){return i(o)},ZFrZa:"objectSt"+e(1681),gJphK:function(i){return i()},dGlTG:e(1813),YqsWa:e(936)};return t===IDBDatabase[e(1619)+"e"].transaction&&!(n[e(1409)]in IDBTransaction.prototype)?function(i,...o){let a=e,d=t[a(876)](n.EZJpm(ms,this),i,...o);return xl.set(d,i[a(1562)]?i[a(1562)]():[i]),n[a(1047)](Yt,d)}:n[e(1580)](rI)[e(796)](t)?n[e(1569)]===n[e(827)]?new _0x563fe3(n[e(1337)](n[e(1040)](_0xce01b1[4],24)|n.VjHCZ(_0x4f72ac[5],16)|n[e(1390)](_0x525e99[6],8),_0x17fcf9[7]),n.KQclp(n[e(1337)](n[e(1350)](n.nwcPr(_0x49b43e[0],24),n[e(1040)](_0x4c2bce[1],16)),n[e(1147)](_0x27ca9e[2],8)),_0x25816e[3]),_0x10ad3f):function(...i){let o=e;return t[o(1590)](n[o(1068)](ms,this),i),Yt(pl[o(892)](this))}:function(...i){let o=e;return n[o(1068)](Yt,t[o(1590)](n[o(1068)](ms,this),i))}}function cI(t){let e=B,n={sUTBt:function(i,o){return i===o},JegEx:e(1567),JRZOd:function(i,o){return i instanceof o},jojsu:function(i,o,a){return i(o,a)},ZaQAh:function(i){return i()}};return n[e(1716)](typeof t,n[e(828)])?aI(t):(n[e(1464)](t,IDBTransaction)&&sI(t),n[e(1086)](zp,t,n[e(1702)](nI))?new Proxy(t,ba):t)}function Yt(t){let e=B,n={LBmjG:function(o,a){return o instanceof a},cinxg:function(o,a){return o(a)},hmfHZ:function(o,a){return o!==a}};if(n[e(870)](t,IDBRequest))return iI(t);if(ga.has(t))return ga.get(t);let i=n[e(1305)](cI,t);return n[e(459)](i,t)&&(ga[e(541)](t,i),ya.set(i,t)),i}var zp,Op,Lp,pl,_a,xl,ga,ya,ba,ms,Mp=Fp({"node_modules/idb/build/wrap-idb-value.js"(){let t=B,e={EMyfw:function(n,i){return n|i},AnSUe:function(n,i){return n>>i},DKFbd:function(n,i){return n|i},mbuCm:function(n,i){return n&i},LlJsH:function(n){return n()},dTRkn:function(n,i){return n===i},dmhWz:t(1773),yHDPl:function(n,i){return n instanceof i},WlpCC:t(1794),wIPQd:function(n,i){return n===i},FUvcZ:t(474),NMLfa:"store",RpLLw:function(n,i){return n===i},SLZfX:function(n,i){return n in i}};zp=(n,i)=>i[t(1422)](o=>n instanceof o),pl=new WeakMap,_a=new WeakMap,xl=new WeakMap,ga=new WeakMap,ya=new WeakMap,ba={get(n,i,o){let a=t;if(e[a(604)]("fXuYi",e[a(1530)]))_0x5023d3[_0x448582++]=e[a(1007)](e[a(792)](_0xaf668f,6),192),_0x4c5de2[_0x2f123a++]=e[a(1181)](e.mbuCm(63,_0x3e731d),128);else{if(e[a(1294)](n,IDBTransaction)){if(i===e[a(1298)])return _a[a(892)](n);if(e.dTRkn(i,a(562)+"oreNames")){if(e[a(991)](e[a(1862)],e[a(1862)]))return n[a(562)+a(1681)]||xl[a(892)](n);{let d=this[a(1342)+a(1675)]?.[a(887)+a(370)+"nt"]();this[a(725)](a(1307)+d),e[a(703)](_0x1f1a7d)}}if(i===e[a(1368)])return o[a(562)+a(1681)][1]?void 0:o[a(562)+a(1380)](o[a(562)+a(1681)][0])}return Yt(n[i])}},set(n,i,o){return n[i]=o,!0},has(n,i){let o=t;return e[o(1294)](n,IDBTransaction)&&(i===e[o(1298)]||e[o(1898)](i,e[o(1368)]))?!0:e.SLZfX(i,n)}},ms=n=>ya.get(n)}}),Up={};tI(Up,{deleteDB:()=>lI,openDB:()=>dI,unwrap:()=>ms,wrap:()=>Yt});function dI(t,e,{blocked:n,upgrade:i,blocking:o,terminated:a}={}){let d=B,u={DLZNa:function(p,g,y,_,b){return p(g,y,_,b)},czqeX:d(1665),qGoNs:d(767)+d(1117),VOhGP:function(p,g){return p(g)},wslxf:d(1885)+d(625),WRZNq:"blocked"},f=indexedDB[d(1822)](t,e),h=u[d(1775)](Yt,f);return i&&f[d(1738)+d(744)](u[d(1024)],p=>{let g=d;u[g(921)](i,Yt(f[g(1109)]),p[g(698)+"on"],p.newVersion,Yt(f[g(1275)+g(1522)]))}),n&&f["addEvent"+d(744)](u[d(1366)],()=>n()),h[d(941)](p=>{let g=d;a&&p["addEvent"+g(744)](u[g(1915)],()=>a()),o&&p[g(1738)+g(744)](u.qGoNs,()=>o())})[d(1089)](()=>{}),h}function lI(t,{blocked:e}={}){let n=B,i={weWgu:n(435),tmqog:function(a,d){return a(d)}},o=indexedDB[n(1653)+"tabase"](t);return e&&o["addEvent"+n(744)](i[n(1671)],()=>e()),i[n(1573)](Yt,o)[n(941)](()=>{})}function Np(t,e){let n=B,i={jrXBY:function(f,h){return f===h},SFrDI:n(1728),CIiFM:"readwrite",dvFIm:n(1811),yPpJs:function(f,h){return f instanceof h},rrBTz:function(f,h){return f===h},wMJKj:"string",vlTBF:function(f,h){return f!==h}};if(!(i[n(1295)](t,IDBDatabase)&&!(e in t)&&i[n(1180)](typeof e,i[n(1384)])))return;if(ma[n(892)](e))return ma[n(892)](e);let o=e[n(572)](/FromIndex$/,""),a=i[n(1128)](e,o),d=Gp[n(796)](o);if(!(o in(a?IDBIndex:IDBObjectStore).prototype)||!(d||Hp[n(796)](o)))return;let u=async function(f,...h){let p=n;if(!i.jrXBY(i[p(1288)],p(1900))){let g=this[p(1275)+p(1522)](f,d?i[p(553)]:i[p(380)]),y=g.store;return a&&(y=y.index(h.shift())),(await Promise.all([y[o](...h),d&&g[p(1794)]]))[0]}};return ma[n(541)](e,u),u}var Hp,Gp,ma,uI=Fp({"node_modules/idb/build/index.js"(){let t=B,e={TSOMD:t(926)+t(1001),FEWxL:function(o){return o()},XlXnx:t(373),CuFzU:"add",cUoIm:t(1397),KtJMp:t(844),LMjpI:t(1164)+"ys"},n=e[t(1876)].split("|"),i=0;for(;;){switch(n[i++]){case"0":e[t(754)](Mp);continue;case"1":Gp=[e.XlXnx,e[t(1577)],t(1055),t(726)];continue;case"2":Hp=[t(892),e[t(575)],e[t(1666)],e.LMjpI,t(1239)];continue;case"3":oI(o=>({...o,get:(a,d,u)=>Np(a,d)||o[t(892)](a,d,u),has:(a,d)=>!!Np(a,d)||o[t(868)](a,d)}));continue;case"4":Mp();continue;case"5":ma=new Map;continue}break}}}),fI={idb:function(t){let e=B,n={eGgYO:e(1543)+"2",nMjyl:e(458)+"d",okoAv:function(i,o){return i===o},qVJFb:e(1627)};t[e(1290)]=Promise[e(848)]()[e(941)](()=>(uI(),Up))[e(941)](function(i){let o=e,a={HPZwr:n.eGgYO,KZuPE:function(d,u){return d||u},KPrXt:function(d,u){return d!=u},jfMIh:n[o(1063)]};if(n.okoAv(n[o(623)],o(1627)))return i;{let d=a.HPZwr[o(1277)]("|"),u=0;for(;;){switch(d[u++]){case"0":if(a[o(1110)](_0x517c10,_0x48cd2b)&&a.KPrXt(a[o(912)],typeof _0x49a85d)&&_0x64083)return!0;continue;case"1":if(_0x346606&&_0x762ca3.connectSocket)return!0;continue;case"2":return!1;case"3":if(_0x1ca5e5)return!0;continue;case"4":if(_0x16e2fb&&_0x5136f9["connectS"+o(462)])return!0;continue}break}}})}},Bp={};function Zt(t){let e=B,n={Pxlid:e(1657)+"2"},i=n.Pxlid[e(1277)]("|"),o=0;for(;;){switch(i[o++]){case"0":if(a!==void 0)return a[e(1290)];continue;case"1":fI[t](d,d[e(1290)],Zt);continue;case"2":return d[e(1290)];case"3":var a=Bp[t];continue;case"4":var d=Bp[t]={exports:{}};continue}break}}Zt.d=(t,e)=>{let n=j;for(var i in e)Zt.o(e,i)&&!Zt.o(t,i)&&Object[n(1169)+n(764)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=B;Zt.o=(e,n)=>Object[t(1619)+"e"][t(1782)+t(764)][t(876)](e,n)})(),(()=>{let t=B,e={ogRPO:function(n,i){return n!=i},NzEkK:t(931),CQZCz:"__esModule"};Zt.r=n=>{let i=t;e[i(1861)]("undefined",typeof Symbol)&&Symbol["toString"+i(668)]&&Object[i(1169)+i(764)](n,Symbol[i(1116)+"Tag"],{value:e.NzEkK}),Object[i(1169)+i(764)](n,e[i(451)],{value:!0})}})();var De={};(()=>{let t=B,e={Ribdm:function(c,r){return c+r},GQWkj:function(c,r){return c>=r},rJoxl:function(c,r,s){return c(r,s)},JBqNy:function(c,r){return c|r},fHThe:function(c,r){return c!==r},bCzoD:t(1559),AyMoN:"XSxEh",oyuZu:function(c,r){return c*r},icYYP:function(c,r){return c*r},NcSkr:function(c,r,s){return c(r,s)},DQQAl:function(c,r){return c(r)},HTIkT:t(1159),KbtZL:"ffff",LuCxf:function(c,r){return c(r)},ynjLE:t(1713)+t(1713)+"0000000000000000",LFkta:t(1303)+t(1107)+t(1440)+"g",OgUqT:t(1774),TXVyx:t(693),VDejN:function(c,r){return c<r},rPGyk:"yhdFu",HJbVP:function(c,r){return c>r},clrvB:"VgjKt",AZvSc:function(c,r){return c!==r},ZBaFo:function(c,r){return c-r},BMwbw:function(c,r){return c===r},NtjSX:t(1439),wbMKw:function(c,r){return c-r},EkQZP:function(c,r){return c!==r},NOlxL:function(c,r,s){return c(r,s)},jroET:function(c,r,s){return c(r,s)},vhnrz:function(c,r,s){return c(r,s)},PFOiZ:function(c,r){return c(r)},dJgns:function(c,r,s){return c(r,s)},gLzec:function(c,r){return c(r)},AbqLx:function(c,r){return c===r},JMNEG:t(1446)+"required"+t(1836)+t(1538),PDEEN:function(c,r){return c(r)},uNhYt:function(c,r){return c*r},CROCR:function(c,r,s){return c(r,s)},kWhbL:"close",cuOal:function(c,r,s){return c(r,s)},vyyYt:function(c,r,s){return c(r,s)},Klmos:function(c,r,s){return c(r,s)},xlMSm:function(c,r){return c!==r},RCqJi:function(c,r){return c===r},HNYtF:function(c,r,s){return c(r,s)},ODpxd:function(c,r){return c!==r},eczLs:function(c,r,s){return c(r,s)},rJAqg:function(c){return c()},wJruw:function(c,r){return c(r)},RkGeQ:function(c,r){return c===r},zkKCD:t(1113),HQqHU:function(c,r,s){return c(r,s)},gfCXe:function(c,r,s){return c(r,s)},umkav:function(c,r,s){return c(r,s)},FdcPy:function(c,r,s){return c(r,s)},fUESB:"vxsie",RUmWV:function(c,r,s){return c(r,s)},MfMbH:function(c,r){return c!==r},JDKwF:function(c,r){return c===r},jLbxh:t(1499),WptDX:function(c,r,s){return c(r,s)},iKHXB:function(c,r){return c(r)},uVMKs:function(c,r){return c(r)},lgonb:function(c,r){return c(r)},wJNTb:function(c,r){return c>>>r},QWSrV:function(c,r){return c(r)},AZocS:function(c,r){return c(r)},csApD:function(c,r){return c(r)},wkuHf:function(c,r){return c(r)},jmxBx:function(c,r,s){return c(r,s)},XYKhf:function(c,r){return c(r)},RSquV:t(1446)+t(1197)+t(1836)+"SeqID",jppgf:function(c,r){return c===r},JrDBa:t(1446)+t(1197)+t(1836)+t(890),AMGvA:function(c,r){return c===r},OApTK:t(1446)+"required"+t(1836)+t(1115),MrTui:function(c,r){return c+r},OoiGJ:function(c,r,s){return c(r,s)},ghrHt:"Unimplem"+t(543)+t(610),XNMnQ:function(c,r){return c>>r},RutJC:t(1122),qXndN:function(c,r){return c&r},zfcia:function(c,r){return c!==r},ONNda:t(964),iBvuj:t(917)+t(829),ZadbN:function(c,r){return c>r},BFKbV:function(c,r){return c*r},RxMFY:function(c,r){return c>r},dKeSd:function(c,r){return c==r},crjDB:t(647),nWUrw:"wss://",HaNQm:t(807),lyEXF:t(566),dxcRZ:function(c,r){return c+r},NqcSd:t(958)+t(829),iooap:function(c,r){return c&r},rnCRR:function(c,r){return c|r},ATuja:function(c,r){return c>>r},vLikP:function(c,r){return c!==r},KrLmB:t(762),WuZwc:function(c,r){return c+r},NiJJa:function(c,r){return c===r},SYoyY:function(c,r){return c+r},evgTM:function(c,r){return c&r},iKtKY:function(c,r){return c==r},vXqKW:function(c,r){return c>=r},dsYUD:function(c,r){return c+r},tvfjJ:function(c,r){return c+r},oyJRj:function(c,r){return c&r},ZWaKz:function(c,r){return c<<r},QetIv:function(c,r){return c|r},OLxFy:function(c,r){return c&r},TegWx:function(c,r){return c>=r},jZwmA:function(c,r){return c+r},fVSit:function(c,r){return c+r},Zvola:function(c,r){return c&r},pCUkV:function(c,r){return c<<r},NTSFe:function(c,r){return c&r},eKKiI:function(c,r){return c<<r},PLTWL:function(c,r){return c&r},onAaO:function(c,r,s){return c(r,s)},wlCYP:function(c,r){return c+r},eNLDD:function(c,r){return c&r},ylUWD:t(689),sHPMz:function(c,r){return c&&r},FXzeZ:t(1793),dhFkV:function(c,r){return c&r},DWPyd:function(c,r){return c&r},GMWjC:function(c,r){return c>>>r},MneiO:t(850),pQkzi:"IDuEv",fDziD:function(c,r){return c<=r},UPcyM:function(c,r){return c+r},zhXKs:function(c,r){return c<<r},IGFdU:function(c,r){return c<r},zOeye:function(c,r,s){return c(r,s)},SVyYv:function(c,r){return c>=r},qTGYN:function(c,r){return c<=r},yJBOV:function(c,r){return c<r},grpdx:function(c,r){return c<r},HWQAD:t(929),JLArU:function(c,r){return c&r},cdUWk:function(c,r){return c|r},SOThj:function(c,r){return c&r},dKmSx:function(c,r){return c|r},ToocQ:function(c,r){return c&r},Guphc:function(c,r){return c>>r},fGnPn:function(c,r){return c>>r},HKZLM:function(c,r){return c|r},BnrmA:function(c,r){return c<r},MwAuD:function(c,r){return c+r},rKfce:function(c,r){return c!==r},qiBlP:t(1651),ahMYt:function(c,r){return c<<r},KYjqE:function(c,r){return c&r},afcPo:function(c,r,s){return c(r,s)},YgutZ:function(c,r){return c instanceof r},IofJZ:t(1794),xTlCz:function(c,r){return c===r},ZyzSL:t(1371),VHrer:t(529),cJWXw:t(974)+t(418)+t(837)+"P",MTsvP:function(c,r){return c(r)},cVkVM:function(c,r){return c+r},nHQua:function(c,r){return c&r},pCcNV:function(c,r){return c!==r},oDeyt:t(581),rxCnh:t(1009),QZKNA:function(c,r){return c&r},Dtuhb:function(c,r){return c&r},anTyb:function(c,r){return c(r)},aWDNT:function(c,r){return c(r)},JLaLV:function(c,r){return c&r},ZDmWK:function(c,r){return c!==r},iidqe:"DjCvr",iRBHD:function(c,r){return c<<r},yuDui:function(c,r){return c&r},eRVBJ:function(c,r){return c&r},iYXJk:function(c,r){return c&r},EkiNG:function(c,r){return c>>>r},Ashpn:function(c,r){return c===r},ZUmNv:function(c,r){return c<r},TXFKW:function(c,r){return c<r},wjvgN:function(c,r){return c<r},BJmZo:function(c,r){return c+r},uOpFD:function(c,r){return c&r},WJgSH:function(c,r){return c!==r},yHYfh:function(c,r){return c&r},vNOid:function(c,r){return c+r},XWsFa:function(c,r){return c>>>r},pkPBC:function(c,r){return c>>>r},mxcdn:function(c,r){return c+r},JMrHN:function(c,r){return c>>>r},VAdmJ:function(c,r){return c|r},NNBVl:function(c,r){return c&r},QOvad:function(c,r){return c+r},OATSI:function(c,r){return c|r},yXbHu:function(c,r){return c&r},wODle:function(c,r){return c+r},uyAFH:function(c,r){return c&r},MVrbr:function(c,r){return c>>>r},JJnMu:function(c,r){return c!==r},EwkqT:function(c,r){return c|r},gTZPq:function(c,r){return c+r},BkvbJ:function(c,r){return c>>>r},fdjyW:function(c,r){return c!==r},HnwiR:function(c,r){return c&r},wvyYb:function(c,r){return c(r)},UOBJX:function(c,r){return c>=r},GZRvl:function(c,r){return c<=r},nbhhQ:function(c,r){return c<<r},WEexM:function(c,r){return c===r},Zkata:t(614),cEfoA:function(c,r){return c(r)},FJfNd:function(c,r){return c===r},sWLNd:t(1599),OPGpZ:function(c,r){return c<<r},UHssx:function(c,r){return c|r},XoAJs:function(c,r){return c|r},tzcmF:function(c,r){return c<<r},FNEBq:function(c,r){return c<<r},QXiMt:function(c,r){return c<<r},TuhCu:t(1869),uaGsu:t(706),pdtVa:function(c,r){return c|r},dpOfA:function(c,r){return c<<r},JWbKL:function(c,r){return c|r},ocGqB:function(c,r){return c|r},MpBhI:function(c,r){return c<<r},SCsEl:function(c,r){return c<<r},kaZzH:function(c,r){return c|r},nxpJp:function(c,r){return c|r},fGSVm:function(c,r){return c<<r},YllrB:function(c,r){return c&r},MjbAE:function(c,r){return c&r},JSEjd:function(c,r){return c>>>r},adsqA:function(c,r){return c>>>r},whEiK:function(c,r){return c>>>r},fUMxR:function(c,r){return c&r},Ayqlc:function(c,r){return c>>>r},TGjHj:function(c,r){return c<=r},qhGiu:function(c,r){return c>=r},WDczd:function(c,r){return c|r},rWfPG:function(c,r){return c%r},gaLkV:function(c,r){return c>>>r},uSGuC:function(c,r){return c>>>r},EiyCf:function(c,r){return c+r},mtNKG:function(c,r){return c===r},fyCYA:function(c,r){return c===r},XaGDa:function(c,r){return c&r},HKrUG:function(c,r){return c&r},OZIFp:function(c,r){return c>>>r},ryJas:function(c,r){return c&r},MZNYd:function(c,r){return c>>>r},DFQIy:function(c,r){return c+r},xDSPc:function(c,r){return c>>>r},JErZS:function(c,r){return c+r},iQTVu:function(c,r){return c<<r},gFeUy:function(c,r){return c===r},mHBli:function(c,r){return c>>>r},djDqu:function(c,r){return c!==r},byKTD:"ZwShd",XvGVo:function(c,r){return c===r},OcAVB:function(c,r){return c&r},nWwvx:function(c,r){return c>>>r},rVcVA:function(c,r){return c&r},IAKgL:function(c,r){return c&r},FKAJm:function(c,r){return c>>>r},aVpzY:function(c,r){return c&r},fkkdy:function(c,r){return c>>>r},DJkzu:t(1322)+t(871),CfOpX:t(1612)+t(1011),wQlQS:t(687)+t(1709),fZAZH:t(1191)+"OR",sYsVQ:"CONNECTING_ERROR",YQvqD:t(1272)+t(1258)+"R",dgmUY:t(1420),OXbCU:t(1263)+t(605),FSZey:function(c,r){return c>=r},ePFRU:"PBHke",sAWEE:t(1605),VkOZx:function(c,r){return c!==r},VxRTn:t(513),TATOU:t(911),ZKogn:t(1335),jVbJu:t(1423),RhDZp:t(681),OoWmc:function(c,r){return c+r},vHkzJ:function(c,r){return c-r},hffKs:function(c,r){return c<<r},emoyn:function(c,r){return c<r},oVxUQ:function(c,r){return c|r},hkVSs:function(c,r){return c&r},kPdIg:function(c,r){return c>>r},UkkXW:function(c,r){return c|r},DOOuQ:function(c,r){return c&r},qlQyT:function(c,r){return c>>r},APOcS:function(c,r){return c|r},HlGUY:t(718),wIaQI:t(1741),qjTJG:function(c,r){return c-r},XdvSV:function(c,r){return c===r},FucLj:function(c,r){return c instanceof r},xbpRt:"Unhandle"+t(755),fMAvN:function(c,r){return c+r},AGUXh:function(c,r){return c===r},tUCeF:function(c,r){return c===r},YXqrp:function(c,r){return c<<r},waciv:function(c,r){return c<<r},hdbbi:function(c,r){return c&r},dJZZk:t(601),LfWfp:t(1890),fbgbt:t(902),JONtB:t(1822),rtfmI:function(c,r,s){return c(r,s)},eHoWc:t(580),eSMbF:function(c,r){return c!==r},hpfGB:"JXnnV",bOkyN:function(c,r,s){return c(r,s)},jkavh:function(c,r){return c instanceof r},mlprA:t(394),kkCGI:"UqHJY",qSDWR:function(c,r){return c(r)},PrTej:function(c,r){return c===r},LnvuU:t(1152),LAhxd:function(c,r){return c||r},zBBrH:function(c,r){return c||r},vAIYQ:t(458)+"d",PccqZ:function(c,r){return c!=r},toULF:t(613)+t(586)+"ltiple t"+t(673)+t(576),aiYBW:function(c,r){return c<r},CVOCn:function(c,r){return c&r},JVZoY:function(c,r){return c&r},KggAF:function(c,r){return c+r},DuymE:function(c,r,s){return c(r,s)},oeJpR:function(c,r,s){return c(r,s)},QiayC:function(c,r){return c<=r},Mubnk:function(c,r){return c<r},Doiml:function(c,r){return c>=r},bTRhB:function(c,r){return c|r},sTwIQ:function(c,r){return c<<r},FVPDN:function(c,r){return c>=r},XHpDf:t(1705),BTgUq:function(c,r){return c-r},DLUNn:function(c,r){return c<<r},bMxET:function(c,r){return c&r},TzNfg:function(c,r){return c&r},zuSOg:function(c,r){return c>>r},gnNyW:function(c,r){return c<r},VkWFS:t(1255),XBVtY:function(c,r){return c<r},Laqac:function(c,r){return c<r},zUrUy:function(c,r){return c>>r},NZWdY:function(c,r){return c===r},vmVuF:function(c,r){return c===r},AlrgI:function(c,r){return c+r},ulzWC:t(1099)+t(1382),uBTdy:function(c,r){return c>>r},eOHHe:function(c,r){return c&r},PMQcd:function(c,r){return c+r},XgGzZ:function(c,r){return c|r},cKJth:function(c,r){return c>>r},zAtVG:function(c,r){return c|r},MIZkk:function(c,r){return c>>r},zGTvV:function(c,r){return c&r},Eiinb:function(c,r){return c>>r},iQPRi:function(c,r){return c&r},DfBHn:t(1168),UfetQ:function(c,r,s,l){return c(r,s,l)},NhkBT:function(c,r){return c instanceof r},dorGC:function(c,r){return c instanceof r},ZEORF:t(1572)+"ion/json",vccFa:function(c,r){return c===r},YWNpF:t(1262),uJYJo:"DamKV",hpmxo:t(1542)+t(1765)+"et=utf-8",cqbNK:t(1034),udaUb:t(509),TQtWI:function(c,r){return c<r},GozZz:function(c,r){return c&r},WsZIJ:"UenPO",SGsIE:t(1151),buPcA:t(1502)+t(772),nNZmY:t(1655),ReUIr:t(716)+t(498),WbSAA:"liZMA",dJVjs:"rdTTz",NYPsr:"TaMYC",HBOsc:"idb",YzEuv:function(c,r,s,l){return c(r,s,l)},ATSKj:function(c,r){return c!==r},wqgdv:t(869),ldjhw:t(1484),OwknV:function(c,r){return c!==r},kqKUI:t(907),xokBT:"oxajO",WFkJb:t(1762),NOFLl:t(1510),iCrmb:t(1111),QjMgw:t(1523),mztig:t(1594)+"7|6|3|4|"+t(1249),TIEzc:t(1243),RkEPq:t(776)+t(1243),doTtY:"cursor.s"+t(398),fMQnf:function(c,r,s,l){return c(r,s,l)},XVxdI:"curvalue",acGWq:t(627),MpZKm:function(c,r){return c!==r},WVklo:t(1179),EaXNE:function(c,r,s){return c(r,s)},DNWuN:t(1639),BWYbx:function(c,r){return c(r)},lwPBD:"LUmHO",aqUiy:function(c,r){return c instanceof r},drdmL:t(1572)+t(1087)+t(567)+"=utf-8",sQeqZ:"none_none",MpTuX:"binary",fFKTd:t(1654),HGNNJ:t(886),nqvTs:function(c,r,s){return c(r,s)},jamFs:t(1732),dxkUN:t(856),VTxId:function(c,r){return c||r},tkXuD:function(c,r){return c||r},qNjGc:function(c,r){return c||r},hDQrs:function(c,r){return c!=r},EDJrO:function(c,r){return c||r},MWlBx:function(c,r){return c!=r},uMCDM:t(1630)+t(1381)+"d",tryOu:t(791),DXUsY:function(c,r){return c-r},UNgGh:function(c,r){return c===r},ZceLU:t(638)+"er_qos",Ljqin:t(638)+"er_is_ack",qezJk:function(c,r,s){return c(r,s)},dyCNm:"x_fronti"+t(421)+t(439),HOEWI:t(1454),gjIKt:t(972),MEqAw:function(c){return c()},APkrI:t(662),xtfrK:function(c,r){return c instanceof r},RPABv:function(c,r){return c instanceof r},posdJ:function(c,r){return c>r},kAvAD:function(c,r){return c>r},MoKIF:function(c,r){return c+r},HhWyo:t(1528),mERfr:function(c,r){return c(r)},hWIuy:function(c,r){return c||r},KsiNT:function(c,r){return c>>>r},sAFOm:function(c,r){return c(r)},bwcxG:function(c,r){return c+r},Qdkwb:function(c,r){return c+r},JDlvq:function(c,r){return c+r},HaWpt:t(1686)+t(1513)+"ge: ",OqezH:t(875),kcXiC:" > ",txUVS:function(c,r){return c>r},RYxmg:t(968)+"too large",ebqtN:function(c,r){return c>=r},wSwSy:function(c,r){return c&r},LsVHx:function(c,r,s,l){return c(r,s,l)},fGSHM:function(c,r){return c+r},kZlOt:function(c,r){return c+r},AadbD:function(c,r,s){return c(r,s)},elgRW:"1|2|0|3|4",rNGAh:function(c,r){return c<r},MUCzu:function(c,r){return c+r},Fnvfj:function(c,r){return c|r},IeYCm:function(c,r){return c|r},EvDbQ:function(c,r){return c<<r},yAfzH:function(c,r){return c<<r},mzLXW:function(c,r){return c+r},vKcwf:function(c,r){return c|r},yYWEs:function(c,r){return c|r},ImRGu:function(c,r){return c+r},QhsBC:function(c,r){return c+r},jVErB:function(c,r){return c&r},SmjsP:function(c,r){return c>>>r},lHhqW:function(c,r){return c&r},hfrRm:function(c,r){return c>>>r},cWrtL:function(c,r){return c+r},whfVf:function(c,r){return c+r},IFMlG:function(c,r){return c&r},wYZKh:function(c,r){return c+r},bfWYH:function(c,r){return c&r},sOSrA:function(c,r){return c+r},ufTak:function(c,r){return c|r},ORXDf:function(c,r){return c<<r},dRjbO:function(c,r){return c>>>r},TYOFO:function(c,r){return c+r},mfWqo:function(c,r,s,l){return c(r,s,l)},hFNgh:function(c,r,s,l){return c(r,s,l)},SRmLA:function(c,r){return c===r},FvoAQ:"cursor_f"+t(826),hRmFE:t(1742),LQNkl:function(c,r){return c<r},GSSAx:t(715),oomWT:function(c,r,s){return c(r,s)},uCOSv:function(c,r,s){return c(r,s)},Bwcxw:t(832)+t(1541),rwdIA:t(375),npuov:t(1316),erMff:t(1803),xOupb:t(916),mPkbh:t(901),ytKZo:function(c,r,s){return c(r,s)},PePxv:t(1095),oIxso:function(c,r,s,l){return c(r,s,l)},smxMZ:t(1913),Hwntq:t(404),rCAGl:function(c,r,s,l){return c(r,s,l)},zrcCR:"setdb",JfANO:function(c,r){return c(r)},bWefE:t(524)+"r",qTynz:"code",ChccM:function(c,r,s,l){return c(r,s,l)},wAJdH:t(638)+"er_msgid",mAVbW:t(638)+t(560),MXHqP:t(433)+"s",tevAQ:function(c,r){return c>r},BXKId:function(c){return c()},zJlns:function(c){return c()},YgCSJ:t(1189),fNPjT:"JBufg",yUBrp:function(c,r){return c&r},ZsKiD:function(c,r){return c>>>r},JfKpk:function(c,r){return c&r},SeKyA:function(c,r){return c>>>r},DylRz:function(c,r){return c&r},UAgxg:function(c,r){return c&r},kNNNo:function(c,r){return c>>>r},ySXNj:t(1877),PrAgP:function(c,r){return c&&r},KLThp:function(c){return c()},GZHpF:function(c){return c()},pgZyz:function(c,r){return c(r)},yPmQl:function(c,r){return c(r)},gpWlr:function(c,r){return c===r},qhWob:function(c){return c()},dXPPx:function(c,r){return c===r},ZXXTM:"XwWMx",sCosN:function(c,r,s){return c(r,s)},qoSIG:function(c,r,s){return c(r,s)},iDfdS:"bye",wpmIl:t(1123),chUSI:"PdCgp",AOPhg:function(c,r,s){return c(r,s)},aPpdp:function(c,r){return c|r},qPZMS:function(c,r,s,l){return c(r,s,l)},vwBZU:function(c,r){return c!==r},WdGZo:t(1625),LXQeq:function(c,r,s){return c(r,s)},EcOvf:t(467),zcrFh:"ping_onc"+t(785)+"s",RLgGN:t(933),Bnyck:function(c,r,s,l){return c(r,s,l)},ihQwB:function(c,r,s){return c(r,s)},febjk:function(c,r,s){return c(r,s)},PKuAR:t(739)+t(1212),GeIav:t(1531),rtNuQ:function(c,r){return c/r},RiSEs:function(c,r){return c==r},BcJUP:function(c,r){return c===r},dWwuO:t(893)+"rovide valid url",AtaTm:"OlATL",cwbqi:t(1723),Nbhxc:function(c,r,s){return c(r,s)},jqBlo:t(794)+"t",uptct:t(538)+"ediately"+t(1895)+"ct",BepTB:t(1805),PgZOK:t(1613),aohyS:t(1396),AICRt:function(c,r){return c!==r},AukbD:function(c,r){return c+r},XlFSO:function(c,r){return c&r},FVaKH:function(c,r){return c+r},cawjp:function(c,r){return c&r},mONJU:function(c,r){return c>>>r},NLYNZ:function(c,r){return c&r},snYtk:t(838),VODvX:function(c,r){return c==r},FecGg:function(c,r){return c||r},hMTxf:t(893)+t(1634)+t(387)+"viceID o"+t(468),KhLlr:"function",rinCL:function(c){return c()},wDzhs:function(c,r,s){return c(r,s)},dTsrB:"web",WcRql:t(696)+"0",iVbss:function(c,r){return c!==r},vIPdc:t(862),omkci:t(1037),HjHac:function(c,r){return c===r},AXwVC:t(1149),kHEdh:"fQGfW",XMrEh:function(c,r){return c>r},yzMMl:function(c,r,s){return c(r,s)},uCMXt:function(c,r){return c!==r},uTkKl:function(c,r){return c(r)},oUDbQ:"FRONTIER>",yWluj:function(c,r){return c!==r},iCoDF:t(1470),Kpwmy:t(450),ceepY:t(948)+t(1893)+t(794)+t(1022)+"ver",Vowbz:t(1799),UTRvT:"JtLfy",drEFN:function(c,r){return c+r},KBIrQ:"mzfuN",TPTns:t(1270),CoiEt:t(1581),uDfOK:function(c,r){return c===r},YWJcH:t(600),yhpaF:function(c,r){return c===r},xwhRG:function(c,r,s){return c(r,s)},EwcIc:function(c,r){return c!==r},zskKW:t(708),IXMhV:function(c,r,s){return c(r,s)},cUIXr:function(c,r,s){return c(r,s)},EAGGG:t(948)+t(1451)+t(603)+t(1483),LAJBo:t(1832),Zxmju:function(c,r){return c(r)},IZehN:function(c,r){return c!==r},caTvV:t(1158),oNBFj:function(c,r){return c===r},RiPfv:t(981),NalMC:function(c,r){return c||r},XIoZp:t(707),cSLQK:function(c,r){return c===r},nkCYY:t(1648),bthBE:function(c,r){return c===r},hbdje:t(1910),oxqLg:"4|6|3|7|1|2|0|5",qMObA:t(710)+t(427)+"y closed",MLrgA:t(710)+"s instan"+t(1427)+t(897)+"ed",oEPUy:t(893)+"rovide a"+t(1085)+t(1250)+"a must b"+t(722)+"ng or an"+t(1471)+t(1392),ZdseC:t(1144),Mwaxr:function(c,r){return c!=r},IDDQR:function(c,r){return c instanceof r},tsMhO:function(c,r){return c(r)},yJKFH:function(c,r){return c(r)},aEPza:function(c,r){return c||r},wQQXI:t(893)+t(1818)+t(694)+t(398),Cwgph:t(1430),dvuqN:function(c,r){return c<r},qBXma:t(1259),NIWPg:function(c,r){return c!==r},EeZBe:t(454)+t(1375)+t(1868),VZeld:"3|1|2|0|4",pJspN:t(391),RvhyN:t(717),lsiwF:t(558),TAOrD:function(c,r,s){return c(r,s)},urCTw:t(1075)+t(480)+"t",wiroa:"\0\0\0\0\0\0\0\0",guvzb:function(c,r){return c!=r},mThWP:function(c,r){return c===r},hxrCA:function(c,r){return c===r},kisSl:t(1076)+"dWorkerG"+t(1908)+"pe",hlsNW:function(c,r){return c===r},OmDIs:"Object",Ldzbo:function(c,r){return c!=r},HeVGt:function(c,r){return c!=r},OQOkf:"ServiceW"+t(1532)+"balScope",lESlv:function(c,r){return c!=r},GsMZx:function(c,r){return c===r},TNHjB:function(c,r,s){return c(r,s)}};Zt.r(De),Zt.d(De,{FWS:()=>Tm,CustomErrorEvent:()=>Ll,createCloseEvent:()=>kt,ReconnectEvent:()=>Ol,createErrorEvent:()=>wt,decodedFrame:()=>Nt,createOpenEvent:()=>Ul,CustomCloseEvent:()=>Ml,createReconnectEvent:()=>Fa,FrontierMessageEvent:()=>Bl,encodeFrame:()=>Xt,createMessageEvent:()=>zl,OpenEvent:()=>Fl,ErrorCode:()=>mn,Event:()=>pr,MessageEvent:()=>Nl});let n="";function i(c=""){let r=t,s="02",l=""+Date[r(1475)](),x=n||(n=f(c)),w=Math[r(975)]()[r(1116)](16).slice(-6);return e[r(1656)](e[r(1656)](s,l)+x,w)}function o(){let c=t;if(e[c(1867)](e[c(1346)],e.AyMoN))return e.oyuZu(1e4,Date[c(1475)]())+Math[c(747)](e.icYYP(1e4,Math[c(975)]()));for(_0x5c5f4c>>>=0;e.GQWkj(_0x13efd2,128);)e[c(1353)](_0x2ecece,_0x429028,e.JBqNy(127&_0x1340fa,128)),_0x322f1a>>>=7;e[c(1353)](_0x18d134,_0x3dea42,_0x12bb5a)}function a(c){let r=t;return e[r(1656)](Array(8)[r(1501)]("0"),e[r(1096)](parseInt,c,10)[r(1116)](2)).slice(-8)}function d(c){let r=t;return e[r(1656)](Array(4)[r(1501)]("0"),parseInt(c,2)[r(1116)](16)).slice(-4)}function u(c){let r=t,s=c.split(/\./)[r(953)](w=>a(w)),l=[];return l[0]=e[r(1816)](d,e[r(1656)](s[0],s[1])),l[1]=e[r(1816)](d,e[r(1656)](s[2],s[3])),[e[r(388)],e[r(388)],e[r(388)],e[r(388)],e.HTIkT,e[r(582)],l[0],l[1]][r(1501)]("")}function f(c){let r=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(664)](c),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(664)](c);return s?e[r(786)](u,c):l?h(c):e[r(865)]}function h(c){let r=t,s={awzos:e[r(1855)]},l="",x=[],w=0,v=0,S=!0,m=r(1159);if(c[r(1098)]("::")>-1)if(e[r(1867)](e[r(1394)],e[r(571)])){let A=c.split("::");for(let N=0;e.VDejN(N,A[r(1359)]);N++){if(r(925)===e[r(630)])return _0x264e19[r(1768)](r(1689),_0x3383e8,_0x5783b6,_0xf64663),this._qosDB[r(541)]({cursor_name:_0x426043,cursor:_0x2321c3,service:_0x1e7d87});{let Y=A[N];if(e.HJbVP(Y.indexOf(":"),0))if(e.fHThe(e.clrvB,r(1865))){let V=Y[r(1277)](":");S&&(w=V[r(1359)]),v+=V[r(1359)];for(let xe=0;e[r(811)](xe,V[r(1359)]);xe++)if(e[r(1190)](4,V[xe].length)){let ut=m[r(1257)+"g"](0,e[r(1360)](4,V[xe][r(1359)])),Je=ut[r(955)](V[xe]);x.push(Je)}else x[r(1426)](V[xe]);S=!1}else return _0x1a7c19[r(1864)]||_0x56b29d[r(1029)]?("message: "+(_0x32351c[r(1864)]||"")+r(1582)+(_0x497ea2[r(1029)]||""))[r(1435)]():_0x6e4fc5[r(1222)+"y"](_0x1bf4de);else if(e.BMwbw(e[r(653)],e.NtjSX)){if(e.AZvSc(4,Y[r(1359)]))if(e[r(1867)]("XIlCb",r(727))){let V=m[r(1257)+"g"](0,4-Y[r(1359)]),xe=V.concat(Y);x[r(1426)](xe)}else this[r(858)+r(1846)+"Event"](_0x1a8ef2),_0x24064b.set(_0x4899fc,_0x4bcd0e,_0x3b42a2[r(580)][r(1115)]);else x.push(Y);S&&(w+=1),v+=1,S=!1}else{let V=this[r(1342)+r(1675)]?.getCurrentEndpoint();this[r(725)](r(455)+V+r(1467)),this._disconnect(1001,s[r(834)],!0)}}}let P="";for(let N=0;N<e.wbMKw(8,v);N++)P=P[r(955)](m);for(let N=0;N<x.length;N++)N===w&&(l=l[r(955)](P)),l=l.concat(x[N]);return l}else this._messageQueue[r(1426)](_0x57424d),this[r(725)](r(1259),_0x178ef2);{let A=c[r(1277)](":");for(let P=0;e[r(811)](P,A[r(1359)]);P++){let N=A[P];if(A[P].length!==4){let Y=m[r(1257)+"g"](0,4-A[P][r(1359)]),V=Y[r(955)](N);l=l[r(955)](V)}else l=l[r(955)](N)}return l}}function p(c,r){let s=t,l=c[s(1745)];e.EkQZP(void 0,l)&&(e[s(488)](ae,r,10),e[s(1506)](ze,r,l));let x=c[s(1538)];e.EkQZP(void 0,x)&&(e[s(453)](ae,r,18),ze(r,x))}function g(c){let r=t,s={};e:for(;!$(c);){let l=ee(c);switch(l>>>3){case 0:break e;case 1:s.key=ye(c,e.PFOiZ(ee,c));break;case 2:s[r(1538)]=e[r(534)](ye,c,e[r(671)](ee,c));break;default:C(c,7&l)}}if(e.BMwbw(void 0,s[r(1745)]))throw new Error(r(1446)+"required"+r(1836)+r(1745));if(e[r(1770)](void 0,s[r(1538)]))throw new Error(e[r(1670)]);return s}function y(c){let r=t,s=O();return _(c,s),e[r(1645)](M,s)}function _(c,r){let s=t,l={HvZpS:function(Je,Ze){return e.PDEEN(Je,Ze)}},x=c[s(1135)];x!==void 0&&(e[s(830)](ae,r,8),e[s(453)](dt,r,x));let w=c[s(890)];w!==void 0&&(ae(r,16),e[s(817)](dt,r,w));let v=c[s(1115)];v!==void 0&&(e.jroET(ae,r,24),e[s(1549)](dt,r,e[s(843)](D,v)));let S=c[s(1287)];if(e.xlMSm(void 0,S))if(e.RCqJi(s(1809),s(1809)))e.HNYtF(ae,r,32),e.rJoxl(dt,r,e[s(1816)](D,S));else{let Je=new _0xc2f99c(e.uNhYt(2,_0x4a0a41));Je[s(541)](_0x3081d8),_0x1ecc66[s(442)]=Je}let m=c[s(1173)];if(e[s(734)](void 0,m))for(let Je of m){e[s(1351)](ae,r,42);let Ze=e[s(1064)](O);e.NOlxL(p,Je,Ze),e[s(817)](ae,r,Ze[s(1872)]),e.dJgns(R,r,Ze),e.wJruw(L,Ze)}let A=c["payloadE"+s(636)];if(e.ODpxd(void 0,A))if(e[s(568)](e[s(819)],e.zkKCD))e[s(526)](ae,r,50),e[s(1114)](ze,r,A);else{if(this["_endpoin"+s(1675)]?.[s(1729)+s(1781)+"es"]()){let Ze=this["_endpoin"+s(1675)]?.[s(887)+s(370)+"nt"]();this[s(858)+s(1545)+"ent"](e[s(534)](_0x2b304f,"close",{code:1006,reason:s(455)+Ze+(s(1467)+s(1079)+"tries re"+s(1138)),wasClean:!0}))}else{let Ze=this[s(1628)][s(794)+s(1131)+"ptor"](_0x557fea,_0x36d767);this[s(858)+s(1545)+s(446)](e[s(526)](_0x24219c,e.kWhbL,{code:_0xb4036e,reason:_0x2b0101,wasClean:!0,willReconnect:Ze})),Ze&&this[s(1458)]()}return}let P=c.payloadType;e[s(857)](void 0,P)&&(e[s(453)](ae,r,58),e[s(1759)](ze,r,P));let N=c.payload;e[s(1318)](void 0,N)&&(e.umkav(ae,r,66),e[s(831)](ae,r,N[s(1359)]),e[s(534)](de,r,N));let Y=c[s(1004)];if(Y!==void 0)if(s(615)!==e.fUESB)e[s(1096)](ae,r,74),e[s(950)](ze,r,Y);else return this[s(979)+"T"]||this[s(1338)+"X"]?this["_miniNavigatorOn"+s(1586)]:(this[s(729)+"er"]||this[s(1216)+"r"])&&this[s(1628)][s(1839)+s(840)+s(1049)]?_0x101f4b[s(402)]:!0;let V=c["serverTi"+s(919)];V!==void 0&&(ae(r,82),ze(r,V));let xe=c[s(1395)];e[s(1652)](void 0,xe)&&(e.HNYtF(ae,r,90),e.vhnrz(ze,r,xe));let ut=c.frameType;ut!==void 0&&(e[s(1796)](e[s(1614)],e[s(1614)])?(e[s(1549)](ae,r,96),e[s(934)](dt,r,D(ut))):(this[s(986)]=!1,l[s(1840)](_0x43331d,this[s(1458)+s(619)+"utId"]),_0x3fecc5()))}function b(c){let r=t;return e[r(1687)](I,e[r(742)](z,c))}function I(c){let r=t,s={};e:for(;!e.lgonb($,c);){let l=ee(c);switch(e[r(1013)](l,3)){case 0:break e;case 1:s.SeqID=it(c,!0);break;case 2:s[r(890)]=e[r(817)](it,c,!0);break;case 3:s[r(1115)]=e[r(671)](ee,c);break;case 4:s[r(1287)]=ee(c);break;case 5:{let x=e[r(1414)](k,c);(s[r(1173)]||(s.headers=[]))[r(1426)](e[r(1687)](g,c)),c[r(1872)]=x;break}case 6:s[r(1603)+"ncoding"]=e[r(950)](ye,c,ee(c));break;case 7:s[r(957)+r(801)]=e[r(526)](ye,c,ee(c));break;case 8:s[r(1659)]=oe(c,e[r(1145)](ee,c));break;case 9:s[r(1004)]=ye(c,e[r(1853)](ee,c));break;case 10:s[r(523)+r(919)]=ye(c,e[r(578)](ee,c));break;case 11:s[r(1395)]=e[r(1174)](ye,c,e[r(1726)](ee,c));break;case 12:s.frameType=e[r(1044)](ee,c);break;default:e[r(830)](C,c,7&l)}}if(e[r(1796)](void 0,s[r(1135)]))throw new Error(e[r(1712)]);if(e[r(746)](void 0,s.LogID))throw new Error(e[r(997)]);if(e.AMGvA(void 0,s[r(1115)]))throw new Error(e[r(1644)]);if(s.method===void 0)throw new Error(r(1446)+r(1197)+r(1836)+r(1287));return s}function k(c){let r=t,s=ee(c),l=c[r(1872)];return c[r(1872)]=e[r(1198)](c[r(895)],s),l}function C(c,r){let s=t;switch(r){case 0:for(;128&e.AZocS(U,c););break;case 2:e[s(448)](K,c,ee(c));break;case 5:K(c,4);break;case 1:e[s(1506)](K,c,8);break;default:throw new Error(e[s(596)]+r)}}function D(c){let r=t;return c|=0,{low:c,high:e[r(863)](c,31),unsigned:e[r(1051)](c,0)}}let E=[];function O(){let c=t,r=E[c(1302)]();return r?(r[c(895)]=r[c(1872)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function L(c){let r=t,s={nKeYG:r(933),hjnIP:"error"};e[r(1318)](e[r(1595)],e.RutJC)?(_0x1f6aab["removeEv"+r(1188)+r(1139)](oGYEQo[r(802)],_0x536529),_0x5ccb3b["removeEv"+r(1188)+"ner"](oGYEQo[r(1134)],_0x221edf)):E[r(1426)](c)}function z(c){let r=t,s={auvpq:function(l,x){return l<x},DPxUI:function(l,x){return e.JBqNy(l,x)},FhHgf:function(l,x){return e[j(863)](l,x)},inAvA:function(l,x){return l|x},jOOaR:function(l,x){return e[j(497)](l,x)},fAiXY:function(l,x){return e.XNMnQ(l,x)},sRdxj:function(l,x){return e[j(1698)](l,x)}};if(e[r(407)]("VdmVJ",e[r(1526)]))s.auvpq(_0x1efc91,2048)?_0x3f7575[_0x1030b0++]=s[r(1456)](s[r(686)](_0x1ff33a,6)&31,192):(s[r(888)](_0x458691,65536)?_0x1ab972[_0xae8c4e++]=s.inAvA(s[r(1450)](s[r(686)](_0x56740c,12),15),224):(_0x2698ce[_0x226cb7++]=s[r(1251)](s[r(1450)](s.FhHgf(_0x137dc9,18),7),240),_0x7c75db[_0x1f54ab++]=s[r(814)](_0x586285,12)&63|128),_0x32e1be[_0x5c5451++]=s.sRdxj(s[r(1450)](_0x493e91>>6,63),128)),_0x38cd6a[_0x16b177++]=63&_0x8c2e2|128;else return{bytes:c,offset:0,limit:c[r(1359)]}}function M(c){let r=t,s=c[r(442)],l=c[r(1872)];return e[r(1796)](s.length,l)?s:s[r(1783)](0,l)}function K(c,r){let s=t;if(e[s(1161)](c[s(895)]+r,c[s(1872)]))throw new Error(e[s(1466)]);c[s(895)]+=r}function $(c){let r=t;return c.offset>=c[r(1872)]}function ie(c,r){let s=t,l=c.bytes,x=c[s(895)],w=c[s(1872)],v=e[s(1656)](x,r);if(e[s(1498)](v,l.length)){let S=new Uint8Array(e.BFKbV(2,v));S[s(541)](l),c[s(442)]=S}return c.offset=v,e[s(1321)](v,w)&&(c[s(1872)]=v),x}function X(c,r){let s=t;if(e[s(746)](e.lyEXF,e.lyEXF)){let l=c[s(895)];if(e[s(1208)](l,r)>c.limit)throw new Error(e[s(980)]);return c.offset+=r,l}else _0x110196=_0x1e5efd&&e[s(419)](e[s(866)],_0x513e39.protocol)?e[s(447)]:e.HaNQm,_0x19740f=_0x47cb42[s(572)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),_0x17831f=/^wss(.*:\/\/)/[s(664)](_0x332591)?_0x2e4bdb:""+_0x30c1fa+_0x332677}function oe(c,r){let s=t,l=e[s(526)](X,c,r);return c[s(442)].subarray(l,l+r)}function de(c,r){let s=t;if(e[s(416)](e[s(1718)],e[s(1718)]))_0x21402e<65536?_0x46f7ee[_0x30baeb++]=e[s(1698)](e[s(497)](e[s(863)](_0x1c07c8,12),15),224):(_0x4b8b72[_0x59574d++]=e[s(863)](_0x5eb81f,18)&7|240,_0x46c7e7[_0x57cc03++]=e[s(795)](_0x1178dd>>12,63)|128),_0x15d6f2[_0x4aa0b3++]=e[s(757)](e[s(795)](e[s(873)](_0x43b14a,6),63),128);else{let l=e[s(817)](ie,c,r[s(1359)]);c.bytes[s(541)](r,l)}}function ye(c,r){let s=t,l=e.vhnrz(X,c,r),x=String[s(1540)+s(1027)],w=c.bytes,v="\uFFFD",S="";for(let m=0;m<r;m++){let A=w[e[s(984)](m,l)],P,N,Y,V;e[s(1511)](e[s(795)](128,A),0)?S+=e[s(786)](x,A):e.AMGvA(e.iooap(224,A),192)?e.GQWkj(e[s(709)](m,1),r)?S+=v:(P=w[m+l+1],e[s(734)](e[s(497)](192,P),128)?S+=v:(V=e[s(795)](31,A)<<6|e[s(1771)](63,P),e[s(811)](V,128)?S+=v:(S+=e[s(1414)](x,V),m++))):e.iKtKY(240&A,224)?e[s(924)](e.Ribdm(m,2),r)?S+=v:(P=w[e[s(1850)](e[s(1622)](m,l),1)],N=w[e[s(709)](e[s(709)](m,l),2)],e[s(1819)](e.rnCRR(P,e[s(990)](N,8)),49344)!==32896?S+=v:(V=e[s(1698)](e.QetIv(e[s(1771)](15,A)<<12,e[s(1579)](63,P)<<6),e[s(795)](63,N)),V<2048||e[s(1051)](V,55296)&&V<=57343?S+=v:(S+=x(V),m+=2))):e.evgTM(248,A)==240?e[s(973)](m+3,r)?S+=v:(P=w[e.dsYUD(m,l)+1],N=w[e.jZwmA(m,l)+2],Y=w[e[s(787)](m+l,3)],e[s(913)](e[s(757)](P,e[s(990)](N,8))|Y<<16,12632256)!==8421504?S+=v:(V=e[s(1698)](e[s(1698)](e[s(1698)](e.ZWaKz(e[s(795)](7,A),18),e[s(833)](e[s(1800)](63,P),12)),e.eKKiI(e[s(521)](63,N),6)),e[s(913)](63,Y)),e[s(811)](V,65536)||e[s(1498)](V,1114111)?S+=v:(V-=65536,S+=e.onAaO(x,e[s(878)](V>>10,55296),e[s(984)](e[s(565)](1023,V),56320)),m+=3))):S+=v}return S}function ze(c,r){let s=t,l={cwamo:s(1454),ORnuO:function(m,A,P,N){return m(A,P,N)},eJXtZ:e[s(422)],ZIJSM:function(m,A){return e[s(1442)](m,A)},vhuSF:e[s(573)],pKbSr:function(m,A){return m&A},sUaqY:function(m,A){return e[s(597)](m,A)},iTYNS:function(m,A){return m>>>A},iDDZg:function(m,A){return e[s(913)](m,A)},QAItQ:function(m,A){return e[s(1013)](m,A)},NXlHm:function(m,A){return e[s(640)](m,A)},IPRkl:function(m,A){return m>>>A},ynHmM:function(m,A){return e[s(1238)](m,A)}},x=r.length,w=0;for(let m=0;m<x;m++)if(e[s(1796)](e[s(1887)],e[s(431)])){let{enableAutoAck:A}=this._options,P=_0x4bd3ac(_0x33c38f[s(580)][s(1173)],l.cwamo,"1"),N=l[s(815)](_0x1e9a7c,_0x4a1ce3[s(580)][s(1173)],l.eJXtZ,"1"),Y=_0x4067dd[s(876)](this,_0x1616d8);if(l[s(1241)](A,P)){let{SeqID:V,LogID:xe,service:ut,LogIDNew:Je,method:Ze}=_0x466618[s(580)];this[s(1566)]({SeqID:V,LogID:xe,LogIDNew:Je,service:ut,method:Ze,headers:[{key:l[s(376)],value:"1"},{key:s(972),value:Je||""},{key:l[s(1697)],value:"0"}]})}N&&!Y[s(1308)]&&this["_dispatc"+s(1587)+"ageEvent"](_0x1d6e83),_0x185481()}else{let A=r[s(570)+"At"](m);A>=55296&&e.fDziD(A,56319)&&e.VDejN(e[s(1198)](m,1),x)&&(A=e.wbMKw(e[s(1325)](e.zhXKs(A,10),r[s(570)+"At"](++m)),56613888)),w+=e[s(646)](A,128)?1:e[s(811)](A,2048)?2:e[s(646)](A,65536)?3:4}ae(c,w);let v=e[s(1598)](ie,c,w),S=c[s(442)];for(let m=0;e[s(811)](m,x);m++){let A=r[s(570)+"At"](m);if(e[s(1875)](A,55296)&&e.qTGYN(A,56319)&&e[s(386)](e[s(1198)](m,1),x)&&(A=e.wbMKw(e[s(878)](e.pCUkV(A,10),r[s(570)+"At"](++m)),56613888)),e[s(1757)](A,128))S[v++]=A;else{if(e[s(1211)]===s(1170))return _0x4f1a26[s(1540)+s(1027)](l[s(1646)](255,this[s(1142)]),l[s(1140)](l[s(1795)](this[s(1142)],8),255),l[s(1491)](l.QAItQ(this[s(1142)],16),255),this[s(1142)]>>>24,l[s(531)](255,this.high),l[s(1140)](l[s(1575)](this[s(1146)],8),255),l[s(1633)](this[s(1146)],16)&255,l[s(1633)](this.high,24));A<2048?S[v++]=e[s(1776)](A>>6,31)|192:(A<65536?S[v++]=e.cdUWk(e.SOThj(e[s(863)](A,12),15),224):(S[v++]=e.dKmSx(e.ToocQ(e[s(961)](A,18),7),240),S[v++]=e[s(1719)](e[s(424)](A,12)&63,128)),S[v++]=e[s(1280)](e[s(1771)](e[s(873)](A,6),63),128)),S[v++]=63&A|128}}}function R(c,r){let s=t,l=e[s(1114)](ie,c,r[s(1872)]),x=c.bytes,w=r[s(442)];for(let v=0,S=r[s(1872)];e[s(1412)](v,S);v++)x[e[s(1330)](v,l)]=w[v]}function U(c){let r=t;if(e[r(407)](e[r(1143)],r(632)))return c[r(442)][e.jmxBx(X,c,1)];if(e[r(1332)](4,_0x79a752[r(1359)])){let s=_0x14d214[r(1257)+"g"](0,e[r(1360)](4,_0x3e7f23[r(1359)])),l=s[r(955)](_0x356fc0);_0x1f4990[r(1426)](l)}else _0x537b1c[r(1426)](_0x5d9621);_0x55e41b&&(_0x3ce414+=1),_0x8788d8+=1,_0xe83911=!1}function q(c,r){let s=t,l=ie(c,1);c[s(442)][l]=r}function ee(c){let r=t,s=0,l=0,x;do x=U(c),e[r(386)](s,32)&&(l|=e[r(825)](e[r(521)](127,x),s)),s+=7;while(e[r(1084)](128,x));return l}function ae(c,r){let s=t;for(r>>>=0;r>=128;)e.afcPo(q,c,e[s(1583)](e[s(521)](127,r),128)),r>>>=7;e[s(1598)](q,c,r)}function it(c,r){let s=t,l={JCvGi:s(716)+"ascript",zhuxn:function(m,A){return e[s(1330)](m,A)},vYxhL:e.VHrer,SAkLN:e[s(1493)],KjImD:function(m,A){return e[s(646)](m,A)},iGQYI:function(m,A){return e.ZadbN(m,A)},FRhBy:function(m,A){return e.MTsvP(m,A)},tWcpb:function(m,A){return e[s(1321)](m,A)},ZPLFn:function(m,A){return e[s(1830)](m,A)},epcST:function(m,A){return m&A},pmYQY:function(m,A){return m+A},KYzVa:function(m,A){return e[s(1280)](m,A)}},x=0,w=0,v=0,S;if(S=e[s(1645)](U,c),x=e[s(1228)](127,S),e.nHQua(128,S))if(e[s(1874)](e.oDeyt,e[s(1886)])){if(S=e[s(519)](U,c),x|=e[s(1866)](e[s(795)](127,S),7),128&S&&(S=U(c),x|=e.ZWaKz(e[s(674)](127,S),14),e[s(1356)](128,S)&&(S=e[s(1267)](U,c),x|=(127&S)<<21,e[s(1727)](128,S)&&(S=e[s(1240)](U,c),w=e[s(396)](127,S),e[s(674)](128,S))))){if(e[s(1688)](s(1623),s(1623))){let m=_0x46b6c3["createEl"+s(554)](s(1655));_0x4fdbc0[s(432)+s(1492)]=A=>{let P=s;_0x1d8c68[P(425)]["removeCh"+P(540)](m),_0x19c47f[P(432)+P(1492)]=void 0,_0x120914(A&&A.msg||P(1502)+P(772))},m[s(949)]=l.JCvGi,m[s(652)]=l[s(1242)](_0x27c909[s(572)](/^ws/,l[s(1537)]),l.SAkLN);try{_0x3943c.body["appendCh"+s(540)](m)}catch{_0x58809a[s(425)][s(750)+s(540)](m)}}else if(S=U(c),w|=(127&S)<<7,e[s(1771)](128,S)){if(e[s(734)](e[s(1377)],"DjCvr"))return qgxJRp[s(1448)](_0x34cd0a,_0x5a6fb7)&&(qgxJRp.BMwbw(_0x3477f3,qgxJRp[s(1236)])||qgxJRp[s(1020)](_0x5e52bd,qgxJRp[s(1733)]))?!0:_0x42ebd1 in _0x37041c;S=U(c),w|=e[s(502)](e[s(1106)](127,S),14),e[s(1776)](128,S)&&(S=e.wJruw(U,c),w|=e[s(1866)](e[s(711)](127,S),21),128&S&&(S=e[s(578)](U,c),v=e[s(381)](127,S),e.iYXJk(128,S)&&(S=U(c),v|=e[s(502)](127&S,7))))}}}else{if(l[s(1763)](_0x3e1b34,1)||l[s(766)](_0x4bd2b9,_0x201983))return l[s(1192)](_0x215343,_0x78b840);l.tWcpb(l[s(1891)](_0x1fb180,_0x51d1c3),_0x21b97a)&&(_0x3d9e78=_0x3e371c(_0x48f193),_0x5d4358=0);let m=_0x3b9766[s(876)](_0x45c293,_0x35e2e7,_0xe87154+=_0x242447);return l[s(1520)](7,_0x19f080)&&(_0x54f894=l.pmYQY(l[s(507)](7,_0x544602),1)),m}return{low:e[s(374)](x,w<<28),high:e.QetIv(w>>>4,v<<24),unsigned:r}}function dt(c,r){let s=t,l=r[s(1142)]>>>0,x=e.EkiNG(e[s(374)](r[s(1142)]>>>28,e[s(1866)](r.high,4)),0),w=e[s(1238)](r[s(1146)],24),v=w===0?e[s(414)](0,x)?e[s(1514)](l,16384)?e[s(1514)](l,128)?1:2:e[s(1436)](l,2097152)?3:4:x<16384?x<128?5:6:e[s(1002)](x,2097152)?7:8:e[s(1412)](w,128)?9:10,S=e[s(514)](ie,c,v),m=c[s(442)];switch(v){case 10:m[e[s(1124)](S,9)]=e[s(626)](e.GMWjC(w,7),1);case 9:m[e[s(1198)](S,8)]=e[s(1669)](9,v)?e[s(757)](128,w):e[s(520)](127,w);case 8:m[e[s(530)](S,7)]=e.xlMSm(8,v)?e[s(1785)](x,21)|128:e.yHYfh(e[s(675)](x,21),127);case 7:m[e.mxcdn(S,6)]=e[s(1867)](7,v)?e.JMrHN(x,14)|128:e[s(1106)](e[s(1238)](x,14),127);case 6:m[S+5]=e[s(1318)](6,v)?e[s(1413)](x>>>7,128):e[s(1692)](x>>>7,127);case 5:m[e.QOvad(S,4)]=e[s(407)](5,v)?e[s(1284)](128,x):e[s(1690)](127,x);case 4:m[e.wODle(S,3)]=v!==4?e[s(374)](e[s(1667)](l,21),128):e[s(1609)](e[s(1606)](l,21),127);case 3:m[e[s(709)](S,2)]=e[s(463)](3,v)?e[s(420)](e[s(675)](l,14),128):l>>>14&127;case 2:m[e[s(789)](S,1)]=e[s(1190)](2,v)?e[s(1229)](l,7)|128:e[s(381)](e[s(1013)](l,7),127);case 1:m[S]=e[s(898)](1,v)?128|l:e[s(1057)](127,l)}}function Nt(c){return e[t(906)](b,c)}function Xt(c){return e.wvyYb(y,c)}let gn=65536,Fn=e[t(583)],mt=gn*gn,xr=e[t(511)](mt,mt),Me=xr/2,ge=String.prototype.charCodeAt;class ce{constructor(r,s,l){let x=t;this[x(1160)]=!0,this[x(1142)]=0|r,this[x(1146)]=0|s,this[x(695)]=!!l}static[t(1160)](r){let s=t;if(e[s(1090)](s(1852),e[s(712)])){let l=_0x4a00cd[s(570)+"At"](_0x23dcc6);e[s(714)](l,55296)&&e[s(650)](l,56319)&&e[s(1830)](_0xab8fb,1)<_0x1ba052&&(l=e[s(1360)](e[s(1177)](l,10)+_0x1c14d3[s(570)+"At"](++_0x206ddd),56613888)),_0x137357+=e[s(646)](l,128)?1:e.BnrmA(l,2048)?2:e[s(1436)](l,65536)?3:4}else return r&&e.AbqLx(!0,r[s(1160)])}static[t(1859)](r,s,l){let x=t;if(e[x(1525)](x(883),e[x(1766)]))qgxJRp.cEfoA(_0x1665b9,_0x5394d0[x(902)]),_0x405dd4();else return new ce(r,s,l)}static fromBytes(r,s,l){let x=t;return l?ce[x(1902)+"sLE"](r,s):ce[x(1902)+x(1649)](r,s)}static[t(1902)+t(1676)](r,s){let l=t;return new ce(e.cdUWk(e[l(1719)](r[0],r[1]<<8),r[2]<<16)|e[l(549)](r[3],24),e.UHssx(e[l(1743)](e[l(1354)](r[4],e[l(1533)](r[5],8)),e.FNEBq(r[6],16)),e[l(1050)](r[7],24)),s)}static[t(1902)+t(1649)](r,s){let l=t,x={HIjex:function(w,v){return w===v}};if(e[l(770)]!==e.uaGsu)return new ce(e[l(1615)](e[l(825)](r[4],24)|e[l(872)](r[5],16),e[l(825)](r[6],8))|r[7],e[l(1468)](e[l(682)](e[l(1743)](e[l(1118)](r[0],24),e[l(634)](r[1],16)),e.SCsEl(r[2],8)),r[3]),s);{let w=_0x4185f5[l(442)],v=_0x322d28[l(1872)];return sHHszR[l(1065)](w[l(1359)],v)?w:w[l(1783)](0,v)}}static[t(970)](r){let s=t;return e[s(1796)](r,Fn)?lt:new ce((e[s(1647)](e[s(1476)](ge[s(876)](r,0),e[s(748)](ge[s(876)](r,1),8)),e[s(748)](ge.call(r,2),16))|e[s(748)](ge.call(r,3),24))>>>0,e[s(1489)](e[s(682)](e[s(1413)](e[s(1719)](ge.call(r,4),ge.call(r,5)<<8),e[s(634)](ge[s(876)](r,6),16)),ge[s(876)](r,7)<<24),0),!0)}[t(1888)](){let r=t;return String[r(1540)+r(1027)](e[r(1383)](255,this[r(1142)]),e[r(410)](e[r(1489)](this[r(1142)],8),255),e[r(396)](e[r(1544)](this[r(1142)],16),255),e[r(1829)](this[r(1142)],24),e[r(626)](255,this[r(1146)]),e[r(913)](e[r(390)](this[r(1146)],8),255),e[r(1419)](this[r(1146)]>>>16,255),e[r(1912)](this.high,24))}static[t(1554)+"er"](r,s=!0){let l=t;if(isNaN(r))return s?Ug:lt;if(s){if(e[l(924)](r,xr))return Gg}else{if(e.TGjHj(r,-Me))return qg;if(e[l(1072)](r+1,Me))return Hg}return ce.fromBits(e[l(704)](e.rWfPG(r,mt),0),r/mt|0,s)}toNumber(){let r=t;return this.unsigned?e[r(443)](e[r(660)](this[r(1146)],0),mt)+e.uSGuC(this[r(1142)],0):e[r(1432)](this[r(1146)]*mt,e[r(1238)](this[r(1142)],0))}[t(988)](){let r=t;return e[r(491)](0,this.high)&&e[r(1042)](0,this[r(1142)])}[t(692)](r){let s=t;ce[s(1160)](r)||(r=ce.fromNumber(r));let l=this[s(1146)]>>>16,x=e[s(1524)](65535,this[s(1146)]),w=this.low>>>16,v=e.HKrUG(65535,this[s(1142)]),S=e[s(777)](r.high,16),m=65535&r.high,A=r[s(1142)]>>>16,P=e[s(852)](65535,r.low),N=0,Y=0,V=0,xe=0;return xe+=e.dxcRZ(v,P),V+=e[s(1699)](xe,16),xe&=65535,V+=e[s(444)](w,A),Y+=e[s(1700)](V,16),V&=65535,Y+=e[s(503)](x,m),N+=Y>>>16,Y&=65535,N+=e[s(1830)](l,S),N&=65535,ce.fromBits(V<<16|xe,e.EwkqT(e[s(1269)](N,16),Y),this.unsigned)}[t(518)](r){let s=t;return ce.isLong(r)||(r=ce[s(1554)+"er"](r)),this[s(695)]!==r.unsigned&&e[s(1469)](e[s(1912)](this.high,31),1)&&e[s(1026)](e[s(741)](r.high,31),1)?!1:this.high===r[s(1146)]&&this[s(1142)]===r.low}[t(616)](){let r=t;if(e[r(915)](e[r(680)],e[r(680)])){let{type:s}=_0x345e02;this[r(1753)](s,_0x13259a)}else return e[r(568)](-1,this[r(1142)])&&e[r(525)](-1,this[r(1146)])?ce[r(1859)](0,0,this[r(695)]):e[r(746)](-1,this[r(1142)])?ce[r(1859)](0,this[r(1146)]+1,this[r(695)]):ce[r(1859)](e[r(984)](this.low,1),this.high,this[r(695)])}[t(403)](r){let s=t;return r?this[s(389)+"E"]():this[s(835)+"E"]()}[t(389)+"E"](){let r=t,s=this.high,l=this[r(1142)];return[e.SOThj(255,l),l>>>8&255,e[r(1539)](l>>>16,255),e[r(1807)](l,24),e[r(1419)](255,s),e[r(1574)](s>>>8,255),e.iYXJk(s>>>16,255),s>>>24]}[t(835)+"E"](){let r=t,s=this[r(1146)],l=this.low;return[e[r(1699)](s,24),e.BkvbJ(s,16)&255,e[r(1373)](e[r(1003)](s,8),255),e[r(1178)](255,s),e[r(1504)](l,24),l>>>16&255,e.iYXJk(l>>>8,255),255&l]}}let lt=new ce(0,0,!1),Ug=new ce(0,0,!0),Hg=ce[t(1859)](-1,2147483647,!1),Gg=ce[t(1859)](-1,-1,!0),qg=ce.fromBits(0,-2147483648,!1);var mn=(function(c){let r=t,s=e.DJkzu.split("|"),l=0;for(;;){switch(s[l++]){case"0":c[c[e[r(1812)]]=5004]=e[r(1812)];continue;case"1":c[c[r(687)+r(1709)]=5001]=e.wQlQS;continue;case"2":return c;case"3":c[c[e.fZAZH]=5005]=r(1191)+"OR";continue;case"4":c[c[r(749)+"NG_ERROR"]=5002]=e.sYsVQ;continue;case"5":c[c[e.YQvqD]=5003]=e[r(946)];continue}break}})({});class pr{constructor(r){let s=t;this[s(949)]=r,this[s(1635)]=null}}class Ol extends pr{constructor(r,s){let l=t;super(r),this[l(580)]=s&&s[l(580)]||null}}class Ll extends pr{constructor(r,s){let l=t;if(e[l(1760)]===e[l(1760)]){let x=e[l(542)].split("|"),w=0;for(;;){switch(x[w++]){case"0":this.colno=s&&s.colno||0;continue;case"1":super(r);continue;case"2":this[l(1802)]=s&&s[l(1802)]||5001;continue;case"3":this[l(962)]=s&&s.lineno||0;continue;case"4":this[l(580)]=s&&s[l(580)]||"";continue;case"5":this.error=s&&s[l(902)]||null;continue;case"6":this[l(1225)]=s&&s.filename||"";continue}break}}else return!!this._qosDB}}class Ml extends pr{constructor(r,s){let l=t,x={nMuWs:function(w,v){return e[j(1719)](w,v)},nwAiW:function(w,v){return w|v},auAfW:function(w,v){return e[j(825)](w,v)},bQrGP:function(w,v){return e.ZWaKz(w,v)},YcvDl:function(w,v){return w&v},nkvVn:function(w,v){return w<v},UuAVt:function(w,v){return e.FSZey(w,v)},OYByI:function(w,v){return e[j(650)](w,v)},DtQui:function(w,v){return e.QWSrV(w,v)}};e[l(491)](e[l(943)],e[l(1126)])?(_0x23ae46=VIUwlv.nMuWs(VIUwlv[l(1221)](VIUwlv[l(1406)](15&_0x457164,12),VIUwlv[l(1792)](VIUwlv[l(778)](63,_0x2c883a),6)),63&_0x5d3b0b),VIUwlv[l(384)](_0xb2a60b,2048)||VIUwlv[l(1857)](_0x3df7b3,55296)&&VIUwlv[l(1343)](_0x704c86,57343)?_0x54853a+=_0x4f26ee:(_0x461e4f+=VIUwlv[l(1133)](_0x10c819,_0x396661),_0x148655+=2)):(super(r),this[l(1802)]=s&&s[l(1802)]||0,this[l(772)]=s&&s.reason||"",this[l(1880)]=s&&s[l(1880)]||!1,this[l(1527)+l(763)]=s&&s[l(1527)+l(763)]||!1)}}class Nl extends pr{constructor(r,s){let l=t;super(r),this[l(806)]=s&&s.data||null}}class Bl extends Nl{constructor(r,s){let l=t;super(r),this.data=s&&s[l(806)]||null,this.message=s&&s[l(580)]||null}}class Fl extends pr{constructor(r,s){let l=t;super(r),this[l(806)]=s&&s[l(806)]||null}}function wt(c,{message:r,code:s,error:l}){let x=t;if(e[x(999)](e.VxRTn,e[x(672)]))return new Ll(c,{message:r,code:s,error:l});{let w=_0x4442eb[x(1257)+"g"](0,4-_0x3b9765[x(1359)]),v=w[x(955)](_0x20b3ce);_0xb98e6f.push(v)}}function kt(c,{code:r,reason:s,wasClean:l,willReconnect:x}){return new Ml(c,{code:r,reason:s,wasClean:l,willReconnect:x})}function zl(c,{data:r,message:s}){let l=t;if(e.ZKogn!==e[l(517)])return new Bl(c,{data:r,message:s});this[l(1233)+l(611)]=_0xbd829b,this[l(1239)]=0}function Ul(c,{data:r}){let s=t,l={kCGXW:function(x,w){return x(w)},ThfyP:function(x,w){return e[j(1325)](x,w)},zDrCL:function(x,w){return x(w)},BYyCg:s(1159),YNSnk:e[s(582)]};if(e[s(1332)](e[s(1838)],s(681))){let x=_0xb1101a.split(/\./)[s(953)](S=>_0x3c0674(S)),w=[];return w[0]=ABuKcU.kCGXW(_0x11e846,ABuKcU[s(1556)](x[0],x[1])),w[1]=ABuKcU[s(1827)](_0x37b614,ABuKcU[s(1556)](x[2],x[3])),[ABuKcU[s(1201)],s(1159),ABuKcU.BYyCg,ABuKcU[s(1201)],ABuKcU[s(1201)],ABuKcU[s(1578)],w[0],w[1]][s(1501)]("")}else return new Fl(c,{data:r})}function Fa(c,{message:r}){return new Ol(c,{message:r})}class Hl{constructor(r,s){let l=t;this[l(1505)+"s"]=r,this[l(821)+"es"]=s,this[l(1905)+l(471)]=0,this[l(1341)+l(1806)+l(752)+"t"]=0}[t(577)+t(364)+"fig"](){let r=t;this[r(1905)+r(471)]=0,this["currentEndpointT"+r(752)+"t"]=0}resetTries(){let r=t;this[r(1341)+"ndpointTriesCount"]=0}["getCurre"+t(370)+"nt"](){return this[t(1505)+"s"][this.currentIndex]}[t(887)+t(370)+t(676)+t(611)](){let r=t;return this["currentE"+r(1806)+r(752)+"t"]}[t(1729)+t(1781)+"es"](){let r=t;if(e[r(1090)](e.HlGUY,e.wIaQI)){let s=_0x1d0f3a[r(570)+"At"](_0x25580c);e.GQWkj(s,55296)&&e.fDziD(s,56319)&&e.yJBOV(e[r(1058)](_0x1fc0d4,1),_0x52518b)&&(s=e[r(1281)](e[r(787)](e[r(1814)](s,10),_0x482d67[r(570)+"At"](++_0x32ca9f)),56613888)),e[r(1412)](s,128)?_0x48eb8f[_0x2dc4a8++]=s:(e[r(409)](s,2048)?_0x122950[_0x1c20fc++]=e[r(393)](e[r(1373)](e[r(873)](s,6),31),192):(e.BnrmA(s,65536)?_0x58cf90[_0xe1912d++]=e.oVxUQ(e[r(1282)](e[r(649)](s,12),15),224):(_0xe695b[_0x11421a++]=e[r(569)](e.rVcVA(e[r(961)](s,18),7),240),_0x197d17[_0x8fafc++]=e[r(1354)](e.DOOuQ(e[r(961)](s,12),63),128)),_0x382f14[_0x3b9e9d++]=e[r(1476)](e[r(626)](e[r(1552)](s,6),63),128)),_0x470911[_0x499fef++]=e[r(731)](63&s,128))}else return!!(this[r(1905)+r(471)]>=this[r(1505)+"s"][r(1359)]||this[r(1905)+"ndex"]===e.qjTJG(this.endpoints[r(1359)],1)&&e[r(1150)](this["currentE"+r(1806)+"riesCount"],this[r(821)+"es"]))}[t(1293)+t(1314)+t(1129)+t(1081)+"tries"](){let r=t;return this.currentIndex==this[r(1505)+"s"][r(1359)]?!0:e.HJbVP(this[r(1341)+r(1806)+"riesCount"],this[r(821)+"es"])}[t(460)+t(464)+t(618)+t(1521)+t(1415)](){let r=t;return this[r(1341)+r(1806)+"riesCount"]=1,this[r(1905)+r(471)]++,this[r(1505)+"s"][this[r(1905)+r(471)]]}[t(887)+"ntEndpointAndUpdateCount"](){let r=t;return this[r(1341)+r(1806)+r(752)+"t"]++,this["getCurre"+r(370)+"nt"]()}}let gr=(e.vAIYQ!=typeof globalThis&&e[t(1445)](t(995),globalThis[t(1339)+t(1739)][t(1243)])||e[t(552)](e[t(699)],typeof window)&&e.mThWP(t(995),window["construc"+t(1739)][t(1243)]))&&e[t(1488)](e[t(699)],typeof document),zn=e[t(699)]!=typeof globalThis&&(e[t(1678)](t(1497),globalThis[t(1339)+t(1739)][t(1243)])||e[t(923)](e[t(492)],globalThis[t(1339)+t(1739)].name))&&e.Mwaxr(t(458)+"d",typeof tt),hi=(e.vAIYQ!=typeof globalThis&&e[t(1171)](e.OmDIs,globalThis[t(1339)+t(1739)][t(1243)])||e[t(699)]==typeof globalThis||e.Ldzbo(e.vAIYQ,typeof globalThis)&&!!globalThis.WeixinJSBridge)&&e.HeVGt(e[t(699)],typeof wx),xi=e[t(1488)](e[t(699)],typeof globalThis)&&(e[t(1469)](e[t(492)],globalThis[t(1339)+t(1739)][t(1243)])||e[t(1042)]("SharedWo"+t(1121)+t(927),globalThis["construc"+t(1739)][t(1243)])||e.bthBE(e.OQOkf,globalThis[t(1339)+t(1739)][t(1243)]))&&t(458)+"d"!=typeof self,Wg=e[t(1367)](e[t(699)],typeof globalThis)&&e[t(769)]===globalThis[t(1339)+t(1739)][t(1243)]&&e.HeVGt(e[t(699)],typeof global)&&e[t(654)](e[t(769)],global["construc"+t(1739)].name)&&e.hDQrs(e.vAIYQ,typeof process)&&!!process[t(1591)];class za{constructor(){let r=t;this[r(1673)+"rs"]={}}emit(r,...s){let l=t,x=this[l(1673)+"rs"][r];if(x)x.slice()[l(690)](w=>w.fn.apply(w[l(1571)],s));else if(r==="error"&&!this[l(1097)]){let w=s[l(1359)]&&s[0];if(e[l(406)](w,Error))throw w;let v=new Error(e[l(797)]+(w?e[l(910)](" (",w.message)+")":""));throw v.context=w,w}return this}[t(1909)](r,s){let l=t;if(e.AGUXh(void 0,r))this._listeners={};else if(e[l(781)](void 0,s))this[l(1673)+"rs"][r]=null;else{let x=this._listeners[r];if(x)for(let w=0;e[l(1514)](w,x[l(1359)]);)x[w].fn===s?x[l(1253)](w,1):++w}return this}on(r,s,l){let x=t;return(this._listeners[r]||(this[x(1673)+"rs"][r]=[]))[x(1426)]({fn:s,ctx:l||this}),this}}class jg extends za{[t(1046)+t(1032)+t(1215)](r){let s=t;return r[s(1864)]||r.errNo?("message: "+(r.errMsg||"")+s(1582)+(r[s(1029)]||""))[s(1435)]():JSON.stringify(r)}constructor(r,s,l){let x=t;super(),this[x(859)]=null,hi&&wx[x(1624)+x(462)]&&(this[x(859)]=wx.connectSocket({url:r,protocols:s,header:l,fail:this[x(429)+x(505)+x(532)][x(1248)](this),success:this[x(429)+x(1881)+"cessHandler"][x(1248)](this)})),zn&&tt[x(1624)+x(462)]&&(this[x(859)]=tt[x(1624)+x(462)]({url:r,protocols:s,header:l,fail:this["_createS"+x(505)+x(532)][x(1248)](this),success:this[x(429)+x(1881)+x(412)+x(423)][x(1248)](this)}))}[t(429)+"ocketSuc"+t(412)+t(423)](){let r=t,s={SXXgB:function(l,x){return e[j(1145)](l,x)},BcvgG:function(l,x){return e[j(1517)](l,x)},ObonM:function(l,x){return l&x},otaev:function(l,x){return l(x)},NhTvj:function(l,x){return e[j(1137)](l,x)},pTQAJ:function(l,x){return e[j(1194)](l,x)}};r(601)!==e.dJZZk?(_0x1cdc8a=KEbakM[r(799)](_0x3e7b81,_0x1a2bc4),_0x3c865f|=KEbakM.BcvgG(127&_0x9a76a2,21),KEbakM[r(1254)](128,_0x28f6d0)&&(_0x222ac4=KEbakM[r(799)](_0x5ab667,_0x591148),_0x3a516c=KEbakM.ObonM(127,_0x1d54d1),KEbakM[r(1254)](128,_0x18e870)&&(_0xdcff6=KEbakM[r(1358)](_0x41ef0a,_0x2ae825),_0x37fb10|=KEbakM[r(783)](KEbakM.pTQAJ(127,_0xbc4e26),7)))):Promise[r(848)]()[r(941)](()=>{let l=r;this[l(705)+l(1478)]()})}["_createS"+t(505)+t(532)](r){let s=t,l={LxVEv:function(x,w){return e[j(1770)](x,w)},NZaao:s(982),HvQAX:e[s(677)],XiIOi:e[s(1127)],jBStR:function(x,w,v){return e[s(514)](x,w,v)},yWPFO:e[s(379)]};Promise[s(848)]().then(()=>{let x=s;if(l[x(963)](l[x(1849)],l[x(721)]))this[x(1909)](_0x200d21,_0x4d9c55);else{let w=wt(l[x(1474)],{message:this[x(1046)+x(1032)+x(1215)](r)});this[x(1753)](l[x(1474)],w);let v=l[x(589)](kt,l[x(1721)],{reason:this[x(1046)+x(1032)+x(1215)](r)});this[x(1753)](l[x(1721)],v)}})}[t(705)+t(1478)](){let r=t;this[r(859)][r(1265)](s=>{let l=r;this.emit(e[l(960)],e.gfCXe(Ul,e[l(960)],{...s,data:s[l(1864)]||""}))}),this._socket[r(790)](s=>{let l=r;this.emit(l(1665),e[l(515)](kt,l(1665),{...s}))}),this._socket[r(822)+"e"](s=>{let l=r;this[l(1753)](e[l(637)],zl(e[l(637)],{...s}))}),this._socket[r(539)](s=>{let l=r;this[l(1753)](e[l(1127)],e[l(1353)](wt,l(902),{...s,message:s[l(1864)]||""}))})}[t(1204)](r){let s=t,l={ZNSOD:function(x,w,v){return x(w,v)},jFvXR:e[s(960)],PPSFi:function(x,w,v){return e[s(1353)](x,w,v)}};if(e[s(1823)](r,Uint8Array)){let x=r[s(1319)][s(1328)](r[s(1683)+"et"],r.byteLength+r[s(1683)+"et"]);this[s(859)]&&this[s(859)][s(1204)]({data:x,fail:w=>{let v=s;this[v(1753)](v(902),l[v(1516)](wt,"error",{message:this["_formatE"+v(1032)+v(1215)](w)}))}})}else this._socket&&this._socket[s(1204)]({data:r,fail:x=>{let w=s;e.eSMbF(e[w(1226)],"JXnnV")?this[w(1753)](ATRYUd[w(1141)],ATRYUd[w(1441)](_0x4be684,ATRYUd.jFvXR,{..._0x439688,data:_0x51c4eb[w(1864)]||""})):this[w(1753)](e[w(1127)],e[w(1411)](wt,e[w(1127)],{message:this["_formatE"+w(1032)+w(1215)](x)}))}})}[t(1665)](r,s){let l=t;if(e[l(463)](e[l(1512)],e[l(1048)]))this[l(859)]&&this[l(859)][l(1665)]({code:r,reason:s});else{let x=_0x4ae642[l(1257)+"g"](0,e[l(1281)](4,_0x229aea[_0x73f5ef].length)),w=x[l(955)](_0x3ebc85);_0x174fd5=_0x394547[l(955)](w)}}["addEvent"+t(744)](r,s){this.on(r,s)}["removeEv"+t(1188)+t(1139)](r,s){this[t(1909)](r,s)}get[t(1787)+"te"](){return this[t(859)].readyState}get[t(816)+"pe"](){let r=t;return this[r(859)][r(816)+"pe"]}set[t(816)+"pe"](r){}get[t(481)](){let r=t;return this[r(859)][r(481)]}get[t(1101)](){let r=t;return this[r(859)][r(1101)]}get extensions(){return this[t(859)].extensions}get["buffered"+t(602)](){return 0}}function Kg(c,r){let s=t;if(e[s(1873)](e[s(1529)],"Skhnr")){if(r)return new r(c[s(481)],c[s(1101)]);if(e[s(1069)](hi,zn))return new jg(c[s(481)],c.protocol,c.headers);if(e[s(1610)](gr,xi)&&e.vAIYQ!=typeof WebSocket&&WebSocket)return new WebSocket(c[s(481)],c[s(1101)+"s"])}else _0x4b08ba[_0x3c5682[_0x57abec][s(1296)+s(1130)]]=e[s(1568)](_0x55d0ee,_0x5038fd[_0x1b3359][s(1296)+s(1130)]),_0x58fd74+=e[s(1850)](14,_0x3052b3[_0x32ff1e[_0x1fb43c][s(1296)+s(1130)]])}function $g(c){let r=t;return!!(c||hi&&wx[r(1624)+"ocket"]||zn&&tt[r(1624)+r(462)]||(gr||xi)&&e[r(1105)](e[r(699)],typeof WebSocket)&&WebSocket)}function Gl(c,r,s){let l=-1;async function x(w){let v=j;return e[v(650)](w,l)?Promise[v(683)](new Error(e[v(1379)])):(l=w,w===s.length?Promise[v(848)]():s[w].bind(c)(r,x[v(1248)](null,w+1)))}e.csApD(x,0)}function ql(c){let r=t,s=0,l=0;for(let x=0;x<c[r(1359)];++x)l=c.charCodeAt(x),e.aiYBW(l,128)?s+=1:l<2048?s+=2:e[r(414)](e[r(1735)](64512,l),55296)&&e[r(1511)](e[r(1217)](64512,c[r(570)+"At"](e[r(1402)](x,1))),56320)?(++x,s+=4):s+=3;return s}function Wl(c,r,s){let l=t,x={kExTl:function(v,S,m){return e[j(697)](v,S,m)},tgjqe:function(v,S,m){return e.oeJpR(v,S,m)}};if(s-r<1)return"";let w="";for(let v=r;e.IGFdU(v,s);){let S=c[v++];if(e[l(849)](S,127))w+=String["fromChar"+l(1027)](S);else if(e[l(400)](S,192)&&e[l(1642)](S,224))w+=String.fromCharCode(e[l(704)]((31&S)<<6,e[l(396)](63,c[v++])));else if(e[l(1791)](S,224)&&e[l(646)](S,240))w+=String[l(1540)+"Code"](e.bTRhB(e[l(748)](e[l(640)](15,S),12),e.sTwIQ(e[l(1524)](63,c[v++]),6))|e[l(396)](63,c[v++]));else if(e[l(490)](S,240))if(e[l(915)](e[l(1835)],e.XHpDf))RprUfU.kExTl(_0x19de07,_0x1c924a,66),RprUfU[l(1798)](_0x413c5d,_0x2e781e,_0x35a9ab.length),RprUfU[l(1256)](_0x2034db,_0x2c5906,_0xeed05a);else{let m=e[l(1157)](e.MpBhI(7&S,18)|e[l(954)](e[l(1373)](63,c[v++]),12)|e[l(1177)](e[l(1503)](63,c[v++]),6)|e.TzNfg(63,c[v++]),65536);w+=String[l(1540)+l(1027)](e[l(910)](55296,e[l(1632)](m,10))),w+=String[l(1540)+l(1027)](e.vNOid(56320,e[l(1524)](1023,m)))}}return w}function Ua(c,r,s){let l=t,x={WzxcT:function(m,A){return e.ZBaFo(m,A)}},w=s,v,S;for(let m=0;e[l(499)](m,c[l(1359)]);++m)if(e.WEexM(e[l(1352)],e.VkWFS))if(v=c[l(570)+"At"](m),e[l(1725)](v,128))r[s++]=v;else if(e[l(1053)](v,2048))r[s++]=e.WDczd(e[l(1536)](v,6),192),r[s++]=63&v|128;else if(e[l(691)](e[l(1609)](64512,v),55296)&&e.vmVuF(e[l(1819)](64512,S=c[l(570)+"At"](e[l(922)](m,1))),56320)){let A=e.ulzWC.split("|"),P=0;for(;;){switch(A[P++]){case"0":r[s++]=e.KYjqE(63,v)|128;continue;case"1":r[s++]=e[l(938)](e.uBTdy(v,12),63)|128;continue;case"2":r[s++]=e[l(1719)](e[l(1691)](e[l(1552)](v,6),63),128);continue;case"3":++m;continue;case"4":v=e[l(812)](65536,e.eKKiI(e[l(1776)](1023,v),10))+e[l(1574)](1023,S);continue;case"5":r[s++]=e[l(1547)](e[l(1755)](v,18),240);continue}break}}else r[s++]=e[l(500)](e[l(415)](v,12),224),r[s++]=e[l(1061)](e[l(508)](v,6),63)|128,r[s++]=e[l(1743)](e[l(820)](63,v),128);else{let A=_0x2b9125[l(1257)+"g"](0,cUwJlr.WzxcT(4,_0x5cabf9[_0x12abab][l(1359)])),P=A[l(955)](_0xd5e7ef[_0x5d0eb0]);_0x24c387.push(P)}return e[l(1023)](s,w)}async function jl(c){let r=t;if(e[r(419)](e[r(1618)],typeof c)){let s=new Uint8Array(e.qSDWR(ql,c));return e.UfetQ(Ua,c,s,0),s}return c instanceof ArrayBuffer?new Uint8Array(c):new Uint8Array(c[r(1319)],c.byteOffset,c[r(1482)+"th"])}function Vg(c){let r=t;try{return e[r(1105)](e.DfBHn,typeof c)&&(e[r(1088)](c,ArrayBuffer)||c[r(1319)]&&e[r(656)](c[r(1319)],ArrayBuffer))||e[r(1105)]("string",typeof c)?"":(JSON.parse(c),e.ZEORF)}catch{if(e[r(385)](e.YWNpF,e[r(854)]))this[r(920)+"igatorOn"+r(1586)]=_0x33f5ac,_0x46cf9d?this["_handleO"+r(701)]():this[r(1672)+r(1751)]();else return r(1168)==typeof c?e.hpmxo:""}}let Jg=(c,r)=>{let s=t;switch(c){case e[s(1801)]:case e.udaUb:return{[s(1006)+c]:1,"x-tt-env":r};default:return{}}};class Zg{constructor(r){let s=t,l={TAGpq:function(x,w){return x(w)},NyYXk:function(x,w){return e[j(417)](x,w)},VLLab:function(x,w){return x<<w},zgqZn:function(x,w){return e[j(1558)](x,w)}};if(e.WsZIJ===e[s(1094)]){let x=0,w=0,v;do v=kngmJf[s(1291)](_0x2263c5,_0x10ddd8),kngmJf[s(1166)](x,32)&&(w|=kngmJf[s(548)](kngmJf[s(588)](127,v),x)),x+=7;while(128&v);return w}else this[s(1233)+"ount"]=r,this.count=0}addCount(){this.count++}[t(1729)+t(1882)+"nt"](){let r=t;return e[r(924)](this[r(1239)],this.maxLossCount)}[t(635)+t(1758)](r=0){let s=t;this[s(1233)+s(611)]=r,this[s(1239)]=0}}async function Yg(c){return new Promise(r=>{let s=j,l={XxOcJ:e[s(719)]};if(!gr)return e[s(1853)](r,e[s(719)]);try{let x=document[s(1452)+s(554)](e[s(1607)]);window[s(432)+s(1492)]=w=>{let v=s;document[v(425)]["removeCh"+v(540)](x),window["frontier"+v(1492)]=void 0,r(w&&w.msg||l[v(885)])},x[s(949)]=e[s(1199)],x[s(652)]=e[s(1208)](c[s(572)](/^ws/,e[s(395)]),e.cJWXw);try{document[s(425)][s(1848)+s(540)](x)}catch{document.body[s(750)+"ild"](x)}}catch{e[s(1150)](e[s(1903)],e[s(1903)])?(window[s(432)+s(1492)]=void 0,r(e.buPcA)):this[s(979)+"T"]?_0x23db89[s(891)+s(751)+"hange"](({isConnected:x})=>{let w=s;this["_miniNav"+w(1826)+w(1586)]=x,x?this[w(1672)+w(701)]():this[w(1672)+w(1751)]()}):this[s(1338)+"X"]&&_0x22a5a8[s(891)+"kStatusC"+s(1117)](({isConnected:x})=>{let w=s;this[w(920)+w(1826)+w(1586)]=x,x?this[w(1672)+"nLine"]():this[w(1672)+w(1751)]()})}})}function wn(c,r,s){let l=t;return!!c?.find(x=>x[l(1745)]===r&&x[l(1538)]===s)}function mr(c,r){let s=t;return c?.[s(1205)](l=>l.key===r)?.[s(1538)]}let Ha=null;async function Xg(){let c=t;if(e.VkOZx(e[c(629)],e[c(1209)]))return Ha||(Ha=Promise[c(848)]().then(Zt[c(1248)](Zt,e[c(1220)]))),Ha;this[c(598)+c(1120)]()}class Qg extends za{constructor(r,s){let l=t;super(),this._dbName=r,this[l(899)]=s,this[l(1333)]=void 0,this[l(1008)+l(441)]=null}async[t(1661)](){await this[t(1227)]()}async[t(1227)](){let r=t,s={vCMmR:function(l){return e.rJAqg(l)},AnZyH:function(l,x,w,v){return e.YzEuv(l,x,w,v)}};if(!this[r(1333)]){if(this[r(1008)+"mise"])return this[r(1008)+r(441)];try{let l=this[r(1834)],x=this[r(899)];this[r(1008)+"mise"]=(async()=>{let w=r,{openDB:v}=await s.vCMmR(Xg);this._qosDB=await s[w(440)](v,w(432)+"_"+l,1,{upgrade(S){let m=w;S[m(1486)+m(1071)+"e"](l,{keyPath:x})}})})(),await this[r(1008)+"mise"]}catch(l){console[r(1768)](l)}finally{if(e.ATSKj(e[r(1374)],"wAopj"))return new _0x30e6ec(l=>{let x=r;_0x47a9f3(l,this[x(928)+x(1070)+"e"](_0x29fc42))});this["_initPro"+r(441)]=null}}}async get(r){let s=t,l={BBlCK:function(x,w){return e[j(419)](x,w)},pNMTo:function(x,w){return x(w)},kCAVC:function(x,w){return e[j(1823)](x,w)}};if(e[s(407)](s(1273),e[s(595)]))try{return e[s(1843)](e.kqKUI,e[s(1016)])?(await this[s(1227)](),this[s(1333)]?.[s(892)](this._dbName,r)):this[s(1333)]?.isReady}catch(x){console[s(1768)](x)}else{if(ULqyWy[s(651)](s(1168),typeof _0x3a4d91)){let x=new _0x1f742c(ULqyWy[s(528)](_0x2ea6c9,_0x530690));return _0x32378c(_0x4efeda,x,0),x}return ULqyWy[s(622)](_0x524f86,_0x580f89)?new _0x15ae08(_0x152e8f):new _0x51d0a(_0x245d46[s(1319)],_0x3d702b[s(1683)+"et"],_0x2751b0[s(1482)+"th"])}}async[t(541)](r,s){let l=t;return e[l(1398)](e[l(841)],l(1762))?(await this._init(),this[l(1333)]?.[l(373)](this._dbName,r)):new _0x26c0aa(_0x46211c,{data:_0x312064})}async del(r){let s=t;try{if(e[s(414)](e.NOFLl,s(1797)))_0x296bb4[s(1768)](_0x16ef5f);else return await this._init(),this[s(1333)]?.[s(1055)](this[s(1834)],r)}catch(l){console[s(1768)](l)}}async clear(){let r=t;try{return await this[r(1227)](),this[r(1333)]?.[r(726)](this[r(1834)])}catch(s){console.log(s)}}async keys(){let r=t;return await this[r(1227)](),this[r(1333)]?.[r(1164)+"ys"](this[r(1834)])}async getAll(){let r=t;return await this[r(1227)](),this._qosDB?.[r(844)](this._dbName)}async[t(1462)](){let r=t,s={cjYyp:function(l,x){return e.OcAVB(l,x)},Kibsh:function(l,x){return e[j(984)](l,x)}};try{this._qosDB?.[r(1665)](),this[r(1333)]=void 0}catch(l){if(e[r(1445)](e.iCrmb,e.QjMgw))return _0x5ece75[r(685)+"t8"]?_0x4c2589[r(685)+"t8"](_0x388800,_0x189073):_0x4a914a[_0xf381c2]=s[r(967)](255,_0x199afa),s[r(1535)](_0x33bdac,1);console[r(1768)](l)}}get[t(1237)](){let r=t,s={BpMLK:e.mztig,UrxFR:function(l,x,w,v){return e[j(1260)](l,x,w,v)},RSzTM:e[r(1736)],pxtJB:e.RkEPq,andPi:e[r(561)],mvxgG:function(l,x,w,v){return e[r(1014)](l,x,w,v)},DJcbg:e[r(793)]};if(e[r(1652)](e.acGWq,e[r(1195)])){let l=s[r(993)][r(1277)]("|"),x=0;for(;;){switch(l[x++]){case"0":_0x2c1abc[r(1768)]("header",_0x408eba);continue;case"1":_0x3b8234=s.UrxFR(_0x412487,_0x5b6f31,_0x195c71,_0x56a9bf[r(1115)]||0);continue;case"2":_0x3da039[r(1768)](s.RSzTM,_0x582c50);continue;case"3":_0x5bc866[r(1768)](s.pxtJB,_0x1997d7);continue;case"4":_0x3ee765=_0x5b8e75(_0x4078e3[r(1296)+r(1130)],_0x491d0c,_0x5c47d4);continue;case"5":_0x1749ab=_0x4f3e5a(0,_0x41b6fc,_0x453e1b);continue;case"6":_0x1edce2=_0x4d28ab(_0x4e9c67[_0x3fd2a8[r(1296)+"ame"]],_0x769697,_0x2b21d9);continue;case"7":_0x17b1c3[r(1768)](r(1115),_0x3ee15d);continue;case"8":_0x57f387.log(s[r(1162)],_0x6f089a,_0x5438e5.service);continue;case"9":_0xf890e3=s[r(992)](_0x53cf35,_0x8566c6[r(1554)+"er"](_0x1a45cf[r(730)]||_0x11a75c),_0x3cce11,_0x1770e8);continue;case"10":_0xcb5efe[r(1768)](s[r(1449)],_0x6bb004);continue}break}}else try{return!!this._qosDB}catch(l){return console[r(1768)](l),!1}}}class em{constructor(r,s){let l=t,x={FSxfk:e.kWhbL};e[l(723)](e.WVklo,l(445))?(this[l(1165)]=r,this[l(1734)]=s,this[l(1333)]=localStorage):(this[l(1753)](x.FSxfk,_0x422482),this[l(996)]&&this.onclose(_0x19127f))}async[t(1661)](){}get[t(1167)](){let r=t;return r(432)+"_"+this[r(1165)]}async[t(892)](r){let s=t,l=this[s(1333)][s(1749)](this._prefix);return JSON[s(1434)](l||"{}")[r]}async[t(541)](r,s){let l=t,x=this[l(1333)][l(1749)](this[l(1167)]),w=JSON[l(1434)](e[l(1610)](x,"{}"));return w[s||r[this[l(1734)]]]=r,this._qosDB[l(1093)](this._prefix,JSON[l(1222)+"y"](w)),s||r[this[l(1734)]]}async[t(551)](r){let s=t,l=this[s(1333)][s(1749)](this._prefix),x=JSON.parse(l||"{}");return x[r]=void 0,this[s(1333)][s(1093)](this[s(1167)],JSON[s(1222)+"y"](x))}async clear(){let r=t;if(e[r(1843)](r(1639),e[r(1631)])){let s=e.EaXNE(_0x17038e,e[r(1127)],{message:_0x3f76ab[r(580)],code:_0xda9449[r(1612)+r(1011)],error:_0x277d5c});this["_dispatc"+r(644)+r(446)](s)}else return this[r(1333)][r(726)]()}async keys(){let r=t,s=this._qosDB[r(1749)](this._prefix),l=JSON.parse(e[r(1069)](s,"{}"));return Object[r(800)](l)}async getAll(){let r=t,s=this[r(1333)].getItem(this[r(1167)]),l=JSON[r(1434)](s||"{}");return Object.values(l)}[t(1462)](){return Promise[t(848)]()}get[t(1237)](){return!!this[t(1333)]}}class tm{constructor(r,s){let l=t;this._DBName=r,this._pathKey=s,this[l(1333)]=zn?tt:hi?wx:null}async[t(1661)](){}get _prefix(){let r=t;return r(432)+"_"+this[r(1165)]}async get(r){let s=t,l=this[s(1333)]["getStora"+s(918)](this[s(1167)]);return JSON[s(1434)](e.zBBrH(l,"{}"))[r]}async[t(541)](r,s){let l=t;if(e[l(1704)]===e[l(1704)]){let x=this._qosDB[l(473)+l(918)](this._prefix),w=JSON.parse(e[l(1610)](x,"{}"));return w[s||r[this[l(1734)]]]=r,this[l(1333)][l(1710)+l(918)](this[l(1167)],JSON[l(1222)+"y"](w)),s||r[this[l(1734)]]}else return _0x238682(_0x3aab0d[l(1590)](qgxJRp[l(1897)](_0x18e3c9,this),_0x1434b0))}async del(r){let s=t;if(e[s(587)]!==e.HGNNJ){let l=this[s(1333)][s(473)+s(918)](this._prefix),x=JSON[s(1434)](l||"{}");return x[r]=void 0,this[s(1333)][s(1710)+s(918)](this._prefix,JSON[s(1222)+"y"](x))}else{let l=e.aqUiy(this._options[s(1603)+s(636)],_0x35b0b5)?{force:!!this._options[s(1603)+s(636)][s(366)],encoding:this[s(1628)][s(1603)+s(636)][s(599)]?this._options[s(1603)+s(636)][s(599)][s(572)](/\s/g,"")[s(608)+s(813)]():""}:{force:!1,encoding:this[s(1628)][s(1603)+s(636)]?this[s(1628)]["payloadE"+s(636)].replace(/\s/g,"")[s(608)+s(813)]():""},x=_0xc56553["payloadE"+s(636)]?_0x46697d[s(1603)+"ncoding"].replace(/\s/g,"")["toLowerC"+s(813)]():"",w=this[s(1628)][s(957)+s(801)]instanceof _0x277382?{force:!!this[s(1628)][s(957)+s(801)][s(366)],type:this[s(1628)][s(957)+s(801)].type?this._options[s(957)+s(801)][s(949)][s(572)](/\s/g,"")[s(608)+"ase"]():""}:{force:!1,type:this[s(1628)]["payloadT"+s(801)]?this[s(1628)][s(957)+s(801)].replace(/\s/g,"").toLowerCase():""},v=_0x9de543[s(957)+"ype"]?_0x3dfa9f[s(957)+s(801)][s(572)](/\s/g,"")[s(608)+"ase"]():"",S=w[s(366)]?w[s(949)]:v||w[s(949)],m=l[s(366)]?l.encoding:x||l[s(599)],A=[s(1542)+s(1765)+"et=utf-8",e[s(702)],e[s(1870)],e[s(1618)]],P=[e.sQeqZ,e[s(1561)]];this[s(1628)][s(1851)+s(937)+s(1841)+"ad"]&&A.includes(S)&&(!m||P[s(796)](m))?_0x95e245["textPayl"+s(1324)]=_0x1ba86e(_0x43618c[s(1659)],0,_0x2d00fc[s(1659)][s(1482)+"th"]):_0x2044d5[s(1155)+s(1324)]=""}}async[t(726)](){let r=t;if(e[r(1525)](e[r(591)],e[r(879)]))e.nqvTs(_0x514a85,_0x4ea2f8,58),e[r(448)](_0x2cc213,_0x188263,_0x44993e);else return this[r(1333)]["clearSto"+r(1393)]()}async[t(800)](){let r=t,s=this[r(1333)]["getStora"+r(574)+"nc"](this[r(1167)]),l=JSON[r(1434)](e[r(1425)](s,"{}"));return Object[r(800)](l)}async[t(844)](){let r=t,s=this[r(1333)][r(473)+"geInfoSync"](this[r(1167)]),l=JSON[r(1434)](e[r(1610)](s,"{}"));return Object[r(609)](l)}closeDB(){return Promise[t(848)]()}get isReady(){return!!this[t(1333)]}}function Kl(c,r){let s=t;if(e[s(1744)](zn,zn))return new tm(c,r);if(e[s(1348)](gr,xi)&&e[s(1748)](e[s(699)],typeof indexedDB))return new Qg(c,r);if(e[s(1620)](gr,xi)&&e[s(1488)](e.vAIYQ,typeof localStorage))return new em(c,r);throw new Error(e[s(810)])}class nm{constructor(){let r=t;this[r(598)+r(951)+"Id"]=null,this[r(598)+"l"]=36e5,this[r(1333)]=Kl(e[r(909)],r(1481)+"id")}async["_interva"+t(1120)](){let r=t;e[r(742)](clearInterval,this[r(598)+r(951)+"Id"]),this[r(598)+r(951)+"Id"]=e[r(697)](setInterval,()=>{this[r(1588)+"ired"]()},this[r(598)+"l"])}async[t(1661)](){let r=t;await this[r(1333)][r(1661)]().then(()=>{let s=r;this[s(598)+s(1120)]()})}async["flushExp"+t(641)](){let r=t;(await this._qosDB?.[r(844)]()||[])[r(1062)](({timestamp:x})=>x<Date[r(1475)]())[r(690)](x=>{let w=r;this[w(1333)]?.[w(551)](x[w(1481)+"id"])})}async del(r){let s=t;return this[s(1333)]?.[s(551)](r)}async[t(541)](r,s){return this[t(1333)]?.set({message_id:r,timestamp:s})}async get(r){return this[t(1333)]?.get(r)}async[t(1462)](){let r=t;if(r(1060)==="gqLqI")e[r(578)](clearInterval,this[r(598)+r(951)+"Id"]),await this[r(1333)]?.closeDB();else{let s=this[r(1333)][r(473)+r(574)+"nc"](this._prefix),l=_0x12eeb2[r(1434)](s||"{}");return _0x3669f5.keys(l)}}get[t(1237)](){let r=t;if(e.UNgGh("XmBKk",r(1894))){let s=_0x15441b[_0x593b54];if(_0x4104ab[_0x2fe24c][r(1359)]!==4){let l=_0x559de9[r(1257)+"g"](0,e.DXUsY(4,_0x11de8b[_0x170a22][r(1359)])),x=l.concat(s);_0x2d5777=_0x307359.concat(x)}else _0x5aa697=_0x4f954d[r(955)](s)}else return this._qosDB?.[r(1237)]}}function Ga(c){let r=t,s=!!this._options.enableQoS;if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(1260)](wn,c.message[r(1173)],e[r(1418)],"2"),x=l&&e[r(1014)](wn,c.message.headers,r(638)+r(1268)+"ck","1"),w=l&&e[r(1754)](wn,c[r(580)].headers,e[r(546)],"1"),v=w?e[r(1455)](mr,c.message.headers,e[r(881)])?.[r(1277)](",")[r(1062)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:x,isAckCleanupMessage:w,ackMsgIds:v}}async function $l(){let c=t;return this["_QoSMana"+c(438)]||(this["_QoSMana"+c(438)]=new nm),this[c(452)+"ger"][c(1237)]||await this[c(452)+c(438)].openDB(),this[c(452)+c(438)]}async function rm(c,r){let s=t,{enableAutoAck:l}=this[s(1628)],x=wn(c[s(580)][s(1173)],e[s(1408)],"1"),w=e[s(1754)](wn,c[s(580)].headers,e[s(422)],"1"),v=Ga[s(876)](this,c);if(e[s(1442)](l,x)){let{SeqID:S,LogID:m,service:A,LogIDNew:P,method:N}=c[s(580)];this[s(1566)]({SeqID:S,LogID:m,LogIDNew:P,service:A,method:N,headers:[{key:e.ylUWD,value:"1"},{key:e[s(989)],value:e[s(1620)](P,"")},{key:s(1793),value:"0"}]})}w&&!v[s(1308)]&&this[s(858)+"hAckMess"+s(1789)](c),e[s(1064)](r)}async function im(c,r){let s=t;this[s(725)](s(1750),c.message),e[s(1185)](r)}async function sm(c,r){let s=t,l=Nt(await e[s(1645)](jl,c[s(806)]));try{if(e.NZWdY(e[s(1326)],e.APkrI))if(e[s(1487)](l[s(1659)],Uint8Array)){let x=this[s(1628)]["payloadE"+s(636)]instanceof Object?{force:!!this[s(1628)][s(1603)+s(636)][s(366)],encoding:this[s(1628)]["payloadE"+s(636)][s(599)]?this[s(1628)][s(1603)+s(636)][s(599)].replace(/\s/g,"")[s(608)+s(813)]():""}:{force:!1,encoding:this[s(1628)][s(1603)+s(636)]?this[s(1628)][s(1603)+s(636)][s(572)](/\s/g,"")[s(608)+s(813)]():""},w=l.payloadEncoding?l[s(1603)+"ncoding"].replace(/\s/g,"")["toLowerC"+s(813)]():"",v=e[s(633)](this[s(1628)][s(957)+s(801)],Object)?{force:!!this[s(1628)][s(957)+s(801)][s(366)],type:this._options[s(957)+"ype"][s(949)]?this[s(1628)][s(957)+s(801)][s(949)][s(572)](/\s/g,"")[s(608)+s(813)]():""}:{force:!1,type:this[s(1628)][s(957)+s(801)]?this[s(1628)]["payloadT"+s(801)][s(572)](/\s/g,"")[s(608)+s(813)]():""},S=l[s(957)+"ype"]?l["payloadT"+s(801)][s(572)](/\s/g,"")[s(608)+s(813)]():"",m=v[s(366)]?v.type:S||v.type,A=x[s(366)]?x[s(599)]:w||x.encoding,P=[s(1542)+"in;chars"+s(1592),e.ZEORF,s(1572)+s(1087)+";charset"+s(1323),e.DfBHn],N=[e[s(798)],"binary"];this[s(1628)]["enableTransformT"+s(1841)+"ad"]&&P.includes(m)&&(!A||N.includes(A))?l[s(1155)+s(1324)]=Wl(l[s(1659)],0,l[s(1659)][s(1482)+"th"]):l[s(1155)+"oad"]=""}else l["textPayl"+s(1324)]="";else this[s(1673)+"rs"]={}}catch(x){l[s(1155)+s(1324)]="",console[s(1768)](x)}c[s(580)]=l,e[s(1064)](r)}function om(c,r,s){let l=t,x={potLO:function(A,P){return e[j(417)](A,P)},ZFsEx:function(A,P){return e[j(399)](A,P)},wciqV:function(A,P){return e[j(906)](A,P)},MLIbt:function(A,P){return e.kAvAD(A,P)},CjJor:function(A,P){return e[j(585)](A,P)},DBGwD:e[l(1479)],pwATT:function(A,P){return e[l(842)](A,P)},Lekap:function(A,P){return e[l(396)](A,P)},leKoO:function(A,P){return A|P}},w=e[l(720)](s,8192),v=e.KsiNT(w,1),S=null,m=w;return function(A){let P=l;if(x[P(1266)](A,1)||x[P(486)](A,v))return x[P(900)](c,A);if(x.MLIbt(x.CjJor(m,A),w)){if(x[P(1438)]!==x[P(1438)])return _0x6bddc4;S=x[P(1230)](c,w),m=0}let N=r[P(876)](S,m,m+=A);return x[P(1600)](7,m)&&(m=x[P(1310)](x[P(535)](7,m),1)),N}}let am=4294967295;function cm(c,r,s){let l=t;return e.sAFOm(RangeError,e.bwcxG(e[l(1845)](e[l(1387)](e[l(878)](e[l(1349)],c),e[l(1804)]),r||1)+e[l(1400)],s))}function dm(c,r,s){let l=t;if(e[l(536)](s,am))throw new Error(e.RYxmg);let x=3;for(;e.ebqtN(x,0);){let w=e[l(994)](255,s);e.LsVHx(Wa,w,c,e[l(1701)](r,x)),s>>>=8,x--}return e.kZlOt(r,4)}function lm(c,r){let s=t,l=0,x=r,w=r+4;for(;x<w;){let{value:v,offset:S}=e[s(1703)](qa,c,x);x=S,l=e[s(1544)](l<<8,0),l+=v}return{value:l,offset:w}}function um(c,r,s){let l=t,x=e[l(426)].split("|"),w=0;for(;;){switch(x[w++]){case"0":if(r.utf8Write)return r[l(1747)+"e"](c,s)+s;continue;case"1":if(!c)return s;continue;case"2":if(e[l(775)](c[l(1359)],40))return Ua(c,r,s)+s;continue;case"3":if(r.write)return e[l(732)](r.write(c,s),s);continue;case"4":return e.QOvad(e[l(494)](Ua,c,r,s),s)}break}}function fm(c,r){let s=t,l=new ce(e[s(773)](e[s(1617)](e[s(393)](e[s(1780)](c[e[s(984)](r,4)],24),e[s(1831)](c[r+5],16)),e[s(1460)](c[e[s(1740)](r,6)],8)),c[r+7]),e[s(824)](e[s(1463)](e.cdUWk(e.ZWaKz(c[e.JErZS(r,0)],24),c[e[s(709)](r,1)]<<16),e[s(1814)](c[r+2],8)),c[e.ImRGu(r,3)]),!0);return r+=8,{value:l,offset:e[s(861)](r,8)}}function hm(c,r,s){let l=t,x=c[l(1142)],w=c.high;return r[s]=w>>>24,r[s+1]=e[l(1637)](e[l(1172)](w,16),255),r[e.UPcyM(s,2)]=e[l(1693)](e.hfrRm(w,8),255),r[e[l(713)](s,3)]=e[l(381)](255,w),r[e[l(1656)](s,4)]=x>>>24,r[e[l(678)](s,5)]=e[l(640)](x>>>16,255),r[e[l(812)](s,6)]=e.JLArU(x>>>8,255),r[e[l(1193)](s,7)]=e[l(1386)](255,x),s+=8,s}function qa(c,r){let s=t;return c[s(944)+"8"]?{value:c.readUInt8(r),offset:e[s(1274)](r,1)}:{value:e[s(1555)](255,c[r]),offset:r+1}}function Wa(c,r,s){let l=t;return r.writeUint8?r[l(685)+"t8"](c,s):r[s]=e[l(1282)](255,c),e[l(679)](s,1)}let xm=function(c){return new Uint8Array(c)},pm=e[t(1105)](t(458)+"d",typeof Buffer)?Buffer[t(1563)+t(1336)]:e[t(1457)](om,xm,Uint8Array[t(1619)+"e"][t(1783)]),gm=16,ja=32;function mm(c){let r=t,s=0,l={};for(let x=0;e[r(1412)](x,c[r(1359)]);x++)l[c[x]["cursor_n"+r(1130)]]=e[r(519)](ql,c[x][r(1296)+r(1130)]),s+=14+l[c[x]["cursor_n"+r(1130)]];return[s,l]}function Vl(c,r,s){let l=t,x={ArRun:function(w,v){return e[j(781)](w,v)},lFMTQ:l(1015),HTaNs:function(w,v,S,m){return e[l(1376)](w,v,S,m)},aIydD:e[l(1641)],swzIz:function(w,v,S,m){return e[l(1223)](w,v,S,m)},PqFJJ:"curvalue",KcIaZ:l(1243)};if(e[l(1447)](l(368),l(808))){let w=e[l(1353)](_0x48c7e2,_0x5e0472,_0x467f99);return _0xf53c8f[l(442)][l(1783)](w,e.TYOFO(w,_0x2dba97))}else{let[w,v]=e[l(671)](mm,c),S=e[l(906)](pm,w),m=0;return c[l(690)](A=>{let P=l;if(x.ArRun(x[P(482)],P(1778))){if(!this[P(1458)+"Lock"]){let N=(P(1378)+"1")[P(1277)]("|"),Y=0;for(;;){switch(N[Y++]){case"0":this[P(986)]=!0;continue;case"1":this[P(1458)]();continue;case"2":this[P(736)+P(908)]=!1;continue;case"3":this[P(1604)+P(1187)]?.["resetCou"+P(1758)]();continue;case"4":this[P(1342)+P(1675)]?.[P(577)+P(364)+P(1707)]();continue}break}}}else{let N=(P(1608)+P(976)+P(437))[P(1277)]("|"),Y=0;for(;;){switch(N[Y++]){case"0":m=x[P(584)](um,A[P(1296)+P(1130)],S,m);continue;case"1":console[P(1768)](P(1362),m);continue;case"2":console[P(1768)](x[P(1601)],m);continue;case"3":m=x[P(584)](Wa,v[A[P(1296)+P(1130)]],S,m);continue;case"4":m=x[P(1340)](hm,ce[P(1554)+"er"](A.cursor||r),S,m);continue;case"5":m=Wa(0,S,m);continue;case"6":console[P(1768)]("service",m);continue;case"7":console.log(x[P(1289)],m);continue;case"8":console.log(P(1858)+P(398),A,A[P(1115)]);continue;case"9":console.log(x[P(624)],m);continue;case"10":m=dm(S,m,A[P(1115)]||0);continue}break}}}),{frameType:ja,headers:[{key:e[l(1730)],value:s}],payload:S}}}function wm(c){let r=t,s=0,l=[];for(;e[r(1708)](s,c[r(1482)+"th"]);)if(r(1509)===e[r(771)])this[r(1833)]&&this[r(1833)].send(_0x1bba10),this[r(725)](e.hRmFE,_0x1e16d4);else{let{offset:x}=qa(c,s);s=x;let w={cursor_name:"",cursor:0,service:0},{value:v,offset:S}=e[r(488)](lm,c,s);w.service=v,s=S;let{value:m,offset:A}=e[r(1677)](qa,c,s);s=A,w["cursor_n"+r(1130)]=e[r(1260)](Wl,c,s,s+m),s+=m;let{value:P,offset:N}=e[r(959)](fm,c,s);w[r(730)]=P[r(1054)](),s=N,l[r(1426)](w)}return l}function _m(){return{frameType:ja,headers:[{key:e.FvoAQ,value:e.Bwcxw}],payload:void 0}}class ym{constructor(r,s,l){let x=t,w={qqnEM:e[x(1684)],oGwWk:x(1805),pWanW:e.npuov,sdock:e[x(1711)]};e.AMGvA(e[x(867)],e.mPkbh)?(this[x(729)+"er"]&&_0x4fea77[x(1738)+x(744)](w.qqnEM,this[x(1672)+x(701)]),this._isBrowser&&_0x1ed1b4[x(1738)+"Listener"](w.oGwWk,this[x(1672)+x(1751)]),this._isBrowser&&_0x5dbee9["addEvent"+x(744)](w[x(1206)],this[x(1125)+x(1231)]),this[x(729)+"er"]&&_0x120bc6[x(1738)+"Listener"](w[x(947)],this[x(1125)+x(1884)])):(this["_cursorN"+x(461)]=r,this[x(1911)+x(1429)]=s,this["_message"+x(1245)]=l,this[x(1333)]=e[x(765)](Kl,this[x(1304)+x(461)],x(1296)+x(1130)))}async[t(1661)](){await this[t(1333)].openDB()}async[t(475)+"rs"](){let r=t;if(!this[r(1333)][r(1237)])return;let s=this[r(1658)+"Strategy"],l=await this[r(1333)][r(844)]();switch(console[r(1768)](r(768)+r(1025),l),s){case e[r(1043)]:return l&&l.length?e[r(663)](Vl,l,0,this[r(1911)+r(1429)]):void 0;case e[r(1385)]:return;case e.Hwntq:return l&&l[r(1359)]?e[r(1585)](Vl,l,0,this[r(1911)+r(1429)]):_m()}}async[t(541)](r,s,l){let x=t;return console[x(1768)](e[x(1104)],r,s,l),this[x(1333)].set({cursor_name:r,cursor:s,service:l})}async setCursors(r){let s=t,l=e[s(1611)](wm,r);for(let x of l)console.log(e[s(1459)],l),await this._qosDB.set(x)}async[t(892)](r){let s=t;return(await this[s(1333)].get(r))?.[s(730)]}async[t(1462)](){let r=t;await this[r(1333)][r(1462)]()}[t(1200)+t(1066)+t(466)](r){let s=t;this[s(1911)+s(1429)]=r}get[t(1237)](){let r=t;return this._qosDB[r(1237)]}}let bm=t(1883)+t(1317);async function Jl(c){let r=t;if(!this[r(1628)][r(363)+"S"])return null;let{aID:s,fpID:l,messageStrategy:x}=this[r(1628)],w=e[r(720)](c,bm);try{return this["_cursorM"+r(470)]?c&&this[r(1232)+r(470)][r(1200)+"rsorFileName"](c):this[r(1232)+r(470)]=new ym(l+"_"+s+"_"+w,w,x),this._cursorManager[r(1237)]||await this[r(1232)+r(470)][r(1661)](),this[r(1232)+r(470)]}catch{return null}}async function Em(c,r){let s=t,l=wn(c.message[s(1173)],e[s(666)],"-1"),x=e[s(1752)](wn,c.message[s(1173)],e[s(422)],"1"),w=e[s(526)](mr,c[s(580)][s(1173)],e[s(1878)]),v=e[s(1267)](Number,e.HQqHU(mr,c[s(580)][s(1173)],e.mAVbW))||0,S=Ga[s(876)](this,c),m=wn(c.message[s(1173)],e[s(1021)],"2"),A=e[s(1703)](mr,c[s(580)].headers,s(1005)+s(516)+"e"),P=Number(mr(c[s(580)][s(1173)],s(1005)+s(1496)+"ue"));if(S.isQoSAck)return r();let N=S[s(1148)+"sage"]?await $l[s(876)](this):null;if(c[s(580)][s(1115)]>0&&x&&!l||e[s(645)](c.message.service,0)){if(w&&S[s(1148)+s(1847)]&&N)return!!!await N.get(w)&&(this[s(858)+s(1846)+s(1210)](c),await N.set(w,Date[s(1475)]()+v)),e[s(1064)](r);if(m){let Y=await Jl[s(876)](this);if(!Y)return this[s(858)+"hMessage"+s(1210)](c),r();let V=await Y[s(892)](A)??-1;if(e[s(1002)](V,P))this[s(858)+s(1846)+s(1210)](c),Y[s(541)](A,P,c[s(580)].service);else throw new Error(s(469)+s(1320)+s(1279)+P+(s(1153)+s(1421)+"al cursor ")+V);return e[s(998)](r)}return this[s(858)+"hMessageEvent"](c),e[s(1364)](r)}}async function vm(c,r){let s=t,l={kuUlB:function(x){return e[j(1185)](x)}};if(e[s(805)]!==e[s(1856)]){let x=Ga[s(876)](this,c);if(!x[s(1148)+s(1847)])return e[s(1064)](r);let w=await $l[s(876)](this);if(x[s(1668)+s(1306)+s(1215)]&&x[s(1837)+"s"][s(1359)])for(let v of x[s(1837)+"s"])await w[s(551)](v);r()}else cpQRwq.kuUlB(_0x280d25),cpQRwq[s(1213)](_0x4858c8)}async function Sm(c,r){let s=t;if(s(555)===e[s(456)]){let l=this[s(1146)],x=this[s(1142)];return[e[s(660)](l,24),e.yUBrp(e[s(1472)](l,16),255),e.JfKpk(e[s(1821)](l,8),255),e[s(1175)](255,l),e.wJNTb(x,24),e[s(1489)](x,16)&255,e[s(430)](e[s(367)](x,8),255),e[s(1539)](255,x)]}else{let l=e.RkGeQ(c[s(580)].frameType,gm),x=e[s(1447)](c[s(580)][s(477)+"e"],ja);if(e[s(804)](!l,!x))return e.KLThp(r);let w=mr(c.message[s(1173)],e[s(1730)]);if(!w)return e[s(905)](r);let v=await Jl[s(876)](this,w);if(!v)return e[s(1550)](r);if(l){let S=await v[s(475)+"rs"](),m={frameType:S?.["frameType"],SeqID:ce[s(1554)+"er"](this[s(1182)]++),LogID:ce[s(1554)+"er"](this[s(1628)]["logIDGen"+s(579)]()),service:9e3,method:5,headers:S?.[s(1173)],payload:S?.[s(1659)]},A=e.pgZyz(y,m);this[s(1833)]&&this[s(1833)][s(1787)+"te"]&&this[s(1833)][s(1204)](A)}if(x){let S=c[s(580)][s(1659)];S&&v.setCursors(S)}}}let Im=async function(c,r){let s=t;this[s(986)]=!1,e[s(1674)](clearTimeout,this["_connect"+s(619)+s(1246)]),e[s(998)](r)},Am=async function(c,r){let s=t;if(!this[s(1833)]||e[s(463)](this[s(1833)][s(1787)+"te"],this[s(1453)]))return r();let{pingInterval:l}=this[s(1628)];this[s(1342)+"tManager"]?.[s(577)+s(364)+s(1707)]();for(let w=0;e[s(499)](w,this["_message"+s(1417)][s(1359)]);w++){let v=this[s(1658)+s(1417)][w];if(e[s(487)](this[s(1833)][s(1787)+"te"],this[s(1453)])&&v!==null)this[s(1833)]&&this[s(1833)].send(v),this[s(1658)+s(1417)][w]=null;else break}this._messageQueue=this["_message"+s(1417)][s(1062)](w=>!!w),this[s(1461)+s(428)+"Id"]=e[s(1598)](setTimeout,()=>this[s(1301)](),l),this[s(858)+"hOpenEvent"](c),this[s(729)+"er"]&&this[s(1833)]&&(this[s(1833)][s(816)+"pe"]=this[s(782)+s(801)]);let x=this[s(1342)+s(1675)]?.[s(887)+s(370)+"nt"]();this[s(725)](s(1307)+x+s(1518)),e[s(688)](r)},km=async function(c,r){let s=t,l=this[s(1342)+s(1675)]?.[s(887)+s(370)+"nt"]();this[s(725)](s(1307)+l),r()};class Tm extends za{constructor(r){let s=t,l={lcBkZ:function(S,m){return e[j(1706)](S,m)},KhaPW:function(S,m,A,P){return e[j(1629)](S,m,A,P)},rbXQo:function(S,m){return e[j(1906)](S,m)},GIXJc:e[s(1664)],dHOwT:function(S,m,A){return e[s(700)](S,m,A)},VQghU:e[s(1127)],hcBbx:function(S,m){return e.mtNKG(S,m)},ThbCP:e[s(1039)],KRQlB:e[s(851)],QooEd:e[s(740)],KdZty:function(S,m){return e[s(385)](S,m)},WuRzT:function(S,m,A,P){return e[s(935)](S,m,A,P)},VpzTL:function(S,m,A){return e[s(1036)](S,m,A)},fBuJk:function(S,m,A){return e[s(1347)](S,m,A)}};super(),this[s(920)+s(1826)+s(1586)]=!0,this._isBrowser=gr,this[s(1663)]=Wg,this[s(979)+"T"]=zn,this[s(1338)+"X"]=hi,this._isWorker=xi,this[s(1658)+s(1417)]=[],this["_endpoin"+s(1675)]=null,this["_readyCl"+s(908)]=!1,this[s(782)+"ype"]=e[s(1041)],this[s(1458)+s(942)]=!1,this[s(1458)+s(619)+"utId"]=null,this[s(1772)+"ctTimeou"+s(1407)]=null,this[s(1461)+s(428)+"Id"]=null,this._seqId=0,this[s(986)]=!1,this[s(1490)]="",this["_QoSMana"+s(438)]=null,this["_cursorM"+s(470)]=null,this[s(1604)+s(1187)]=null,this._protocols=e[s(489)],this[s(1327)]=3,this[s(749)+"NG"]=0,this[s(1453)]=1,this[s(932)]=2,this[s(512)]=S=>{let m=s,A={ebvDg:function(P,N){return l[j(1132)](P,N)}};try{l[m(659)](Gl,this,S,[Im,Am,km])}catch(P){if(l[m(592)](l[m(759)],l.GIXJc))this[m(1160)]=!0,this[m(1142)]=SjVHJB[m(987)](0,_0x47fe40),this[m(1146)]=SjVHJB[m(987)](0,_0x3585a7),this[m(695)]=!!_0x131c5f;else{let N=l.dHOwT(wt,l.VQghU,{message:P[m(580)],code:mn[m(1191)+"OR"],error:P});this[m(858)+m(644)+m(446)](N)}}},this[s(1424)+"ge"]=async S=>{let m=s,{pingInterval:A,pingFrequency:P}=this[m(1628)];if((l[m(1901)]("hi",S[m(806)])&&m(600)===P||l[m(606)]===P)&&(this[m(1551)+"ngTimer"](),this[m(1753)](l[m(1056)],l[m(401)]),this[m(1461)+m(428)+"Id"]=l[m(1203)](setTimeout,this[m(1301)].bind(this),A)),!l[m(383)]("hi",S[m(806)]))try{l[m(1790)](Gl,this,S,[sm,rm,vm,Sm,Em,im])}catch(N){let Y=l[m(1203)](wt,l[m(397)],{message:N[m(580)],code:mn[m(1612)+"ERROR"],error:N});this[m(858)+m(644)+m(446)](Y)}},this._onError=S=>{let m=s,A=this[m(1342)+m(1675)]?.[m(1729)+m(1781)+"es"](),P=this[m(1342)+"tManager"]?.[m(887)+m(370)+"nt"]();if(A&&!S[m(580)]){let N=m(455)+P+(m(1784)+m(392)+m(1576)+"ed");this[m(858)+m(644)+m(446)](l[m(1300)](wt,l.VQghU,{message:N,code:mn[m(1272)+m(1258)+"R"],error:S}));return}this[m(1833)]&&this[m(1833)][m(1787)+"te"]===this.OPEN&&this[m(1810)+"ect"](),this[m(858)+m(644)+m(446)](l.fBuJk(wt,l[m(397)],{message:S[m(580)],code:mn["NATIVE_E"+m(1709)],error:S}))},this[s(612)]=async S=>{let m=s;this[m(966)+m(978)](),this["_clearPi"+m(1679)](),this["_removeW"+m(1695)+"rs"](),this[m(1833)]=null,this[m(1458)+m(942)]=!1;let A=this["_endpoin"+m(1675)]?.[m(1729)+m(1781)+"es"]();if(!A&&this[m(1731)+m(1863)]()&&!this._readyClosed)if(e[m(1331)](m(1156),e.ZXXTM))this[m(1333)]?.[m(1665)](),this[m(1333)]=void 0;else{let P=this[m(1342)+m(1675)]?.[m(887)+m(370)+"nt"](),N=this[m(1628)][m(794)+m(1131)+m(1788)](S[m(1802)],S.reason);this[m(858)+m(1545)+m(446)](e[m(1507)](kt,e[m(379)],{code:1006,reason:S[m(772)]||m(1860)+m(1112)+m(1344)+"wn reaso"+m(1244)+"ame: "+P,willReconnect:N})),N&&this[m(1458)]();return}if(S.code!==1e3&&this[m(736)+m(908)]){this[m(858)+m(1545)+m(446)](e[m(484)](kt,e[m(379)],{code:1e3,reason:e.iDfdS})),this[m(1342)+m(1675)]?.["resetEnd"+m(364)+"fig"](),this[m(1604)+"sCounter"]?.[m(635)+m(1758)]();return}if(S[m(1802)]!==1e3&&A){if(e.fyCYA(e.wpmIl,e[m(983)]))return 0;{let P=this[m(1342)+"tManager"]?.[m(887)+"ntEndpoint"](),N=S[m(772)];N||(N=await e[m(1816)](Yg,this[m(1490)])),N=m(1860)+m(1112)+m(1401)+N+(m(372)+m(434))+P+(m(1079)+"tries re"+m(1138)),this[m(858)+"hCloseEv"+m(446)](e[m(761)](kt,e[m(379)],{code:S.code,reason:N}));let Y=m(455)+P+(" fail, m"+m(392)+"es reached");this[m(858)+m(644)+"ent"](wt(e[m(1127)],{message:Y,code:mn[m(1272)+m(1258)+"R"]})),this[m(1342)+"tManager"]?.["resetEnd"+m(364)+m(1707)](),this["_pingLos"+m(1187)]?.[m(635)+m(1758)]();return}}if(e[m(1318)](1e3,S[m(1802)])&&!S.reason){let P=this[m(1342)+m(1675)]?.[m(887)+"ntEndpoint"]();this[m(858)+m(1545)+m(446)](kt(e.kWhbL,{code:S.code,reason:m(1860)+m(1112)+"d, unkno"+m(449)+m(1244)+m(621)+P})),this[m(1342)+"tManager"]?.[m(577)+m(364)+m(1707)](),this[m(1604)+"sCounter"]?.[m(635)+m(1758)]();return}this[m(858)+m(1545)+m(446)](S),this[m(1342)+m(1675)]?.[m(577)+"pointCon"+m(1707)](),this[m(1604)+m(1187)]?.["resetCou"+m(1758)]()},this[s(996)]=null,this.onerror=null,this[s(1313)+"e"]=null,this.onopen=null,this[s(522)+s(1375)]=null,this[s(556)+s(1889)]=null,this[s(1638)+s(563)+s(977)+"ct"]=null,this[s(1672)+s(701)]=this[s(1672)+s(701)][s(1248)](this),this._handleOffLine=this[s(1672)+"ffLine"][s(1248)](this),this[s(1125)+s(1231)]=this["_handleP"+s(1231)].bind(this),this["_handleP"+s(1884)]=this[s(1125)+s(1884)][s(1248)](this),this[s(1628)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(733)](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.EcOvf,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1495)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:x,ws:w}=r,v=Array[s(1207)](x)?x:e[s(1276)](e[s(1618)],typeof x)?[x]:[];if(!v||e[s(1010)](0,v[s(1359)]))throw new Error(e[s(853)]);if(!e[s(1726)]($g,w))throw new Error("please p"+s(1357)+"s params"+s(780)+s(378)+"tructor "+s(382)+s(1756));Object[s(657)](this._options,r),this[s(1342)+s(1675)]=new Hl(v,this[s(1628)][s(821)+"es"]),this[s(1604)+"sCounter"]=new Zg(this[s(1628)][s(496)+s(1278)]),this[s(1628)][s(745)+s(1416)]&&(this[s(986)]=!0,this[s(1458)]()),this[s(1628)][s(1839)+s(840)+s(1049)]&&(this[s(979)+"T"]||this[s(1338)+"X"]?this["_onPageN"+s(945)+"ange"]():this[s(729)+"er"]&&this[s(1092)+s(1767)+"Listener"]())}["_handleO"+t(701)](){let r=t;if(e[r(491)](e.AtaTm,e[r(809)])){let s=r(455)+_0x603242+(" timeout"+r(1079)+r(1548)+r(1138));this[r(725)](s),this[r(858)+r(644)+r(446)](e[r(1163)](_0x3dcff2,e.fbgbt,{message:s,code:_0x5a4c25[r(1272)+r(1258)+"R"]}));return}else{if(this[r(1628)]["disableA"+r(1519)+"nect"]||this[r(736)+r(908)])return;this[r(648)+r(1375)]()}}[t(1672)+t(1751)](){let r=t;this[r(1399)+r(1052)+"t"]();let s=e.Nbhxc(Fa,e.jqBlo,{message:e[r(839)]});this[r(1638)+r(563)+"yReconnect"]&&this[r(1638)+"mediatelyReconnect"](s)}[t(1092)+t(1767)+t(744)](){let r=t;this[r(729)+"er"]&&window[r(1738)+r(744)](e[r(1684)],this[r(1672)+r(701)]),this[r(729)+"er"]&&window[r(1738)+r(744)](e.BepTB,this[r(1672)+r(1751)]),this._isBrowser&&window.addEventListener(e.npuov,this[r(1125)+r(1231)]),this[r(729)+"er"]&&window[r(1738)+"Listener"](e[r(1711)],this[r(1125)+"ageShow"])}["_dropGlo"+t(1767)+"Listener"](){let r=t,s={OFaTI:function(l,x){return e[j(812)](l,x)},wPBCa:function(l,x){return l(x)}};if(e[r(1480)]==="aZtij")return SIjkHa[r(1515)](SIjkHa[r(784)](_0x3775b8,8)[r(1501)]("0"),_0x47a6e2(_0x26b964,10)[r(1116)](2))[r(1328)](-8);this[r(729)+"er"]&&window[r(1218)+"entListe"+r(1139)](e[r(1684)],this[r(1672)+"nLine"]),this[r(729)+"er"]&&window[r(1218)+r(1188)+r(1139)](e[r(1074)],this[r(1672)+r(1751)]),this[r(729)+"er"]&&window["removeEv"+r(1188)+r(1139)](e.npuov,this[r(1125)+r(1231)]),this[r(729)+"er"]&&window["removeEv"+r(1188)+r(1139)](e[r(1711)],this[r(1125)+r(1884)])}[t(1125)+t(1231)](r){let s=t,l={klOuh:function(x,w){return e[j(1706)](x,w)},DXOQN:function(x,w){return e[j(852)](x,w)},OMgou:function(x,w){return e.ATuja(x,w)},qCWjC:function(x,w){return e[j(773)](x,w)}};!r.persisted&&(e.XvGVo(s(1557),e.aohyS)?(_0x5d3ae4[_0x2a182f++]=AWfZIw.klOuh(AWfZIw.DXOQN(AWfZIw[s(1892)](_0x1b851f,18),7),240),_0x3d273a[_0x5b0830++]=AWfZIw[s(476)](AWfZIw.DXOQN(AWfZIw[s(1892)](_0x202d25,12),63),128)):(this[s(729)+"er"]&&window[s(1218)+"entListener"](e[s(1403)],this[s(1125)+"ageHide"]),this[s(729)+"er"]&&window[s(1218)+"entListener"](e[s(1711)],this[s(1125)+"ageShow"]),this[s(1665)]())),this._isBrowser&&window[s(1218)+s(1188)+s(1139)](e[s(1684)],this[s(1672)+"nLine"]),this[s(729)+"er"]&&window["removeEv"+s(1188)+s(1139)](e[s(1074)],this[s(1672)+s(1751)])}[t(1125)+t(1884)](r){let s=t;r[s(590)+"d"]&&(this[s(1731)+"orOnline"]()&&(!this[s(1833)]||e[s(1906)](this[s(1833)][s(1787)+"te"],this.OPEN)||e[s(1764)](this[s(1833)][s(1787)+"te"],this[s(749)+"NG"]))&&this["_handleO"+s(701)](),this[s(729)+"er"]&&window["addEvent"+s(744)](s(375),this[s(1672)+s(701)]),this[s(729)+"er"]&&window[s(1738)+s(744)](e[s(1074)],this[s(1672)+"ffLine"]))}async[t(413)+t(1431)](r){let s=t;if(e[s(1331)](e[s(684)],"yGcwj")){let{fpID:l,deviceID:x,bddID:w,ttwID:v,accessKey:S,aID:m,customParams:A={},enableAutoAck:P,enableQoS:N,QoSLevel:Y,env:V}=this[s(1628)],xe,ut,Je;this[s(729)+"er"]||this._isMiniWX||this[s(979)+"T"]?(xe=location&&e[s(956)](e.crjDB,location[s(1101)])?"wss://":"ws://",ut=r[s(572)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),Je=/^wss(.*:\/\/)/[s(664)](r)?r:""+xe+ut):(xe=e.nWUrw,ut=r[s(572)](/(^http)((?:[s]*:\/\/))/,""),Je=/(^ws)((?:[s]*:\/\/))/.test(ut)?ut:""+xe+ut);let Ze=w?s(1345):v?s(1717):"device_id",Zl=w||v||x;if(e[s(1465)](!Zl,!Ze))throw new Error(e[s(874)]);let Cm=e[s(419)](e[s(617)],typeof A)?await e[s(593)](A):A,Pm=V?e[s(1405)](Jg,V[s(1428)],V[s(1404)]):{},Ka=Object[s(657)]({device_platform:e[s(1100)],version_code:e[s(952)],access_key:S,fpid:l,aid:m,[Ze]:Zl,xsack:P?1:0,xaack:P?1:0,xsqos:N?1:0,qos_level:N?Y:void 0,qos_sdk_version:2,...Pm},Cm),Rm=Object[s(800)](Ka)[s(728)](($a,Va)=>Ka[Va]!==void 0?""+$a+($a?"&":"?")+Va+"="+Ka[Va]:$a,"");return Je+"/ws/v2"+Rm}else{let l=_0x33e31a.low,x=_0x246e47[s(1146)];return _0x25ec91[_0x1b29f9]=e[s(367)](x,24),_0x41f65c[e[s(1825)](_0x1c84d9,1)]=e[s(1777)](e[s(390)](x,16),255),_0x1b92c9[_0x2fe277+2]=e.OLxFy(e[s(1700)](x,8),255),_0x45a57c[e.QOvad(_0x3e46a3,3)]=e.jVErB(255,x),_0x291658[_0x4f96d7+4]=l>>>24,_0x41bb33[e[s(1030)](_0x1883b1,5)]=e[s(1593)](e[s(1489)](l,16),255),_0x1b9ffd[e[s(787)](_0x27e33d,6)]=e[s(661)](l,8)&255,_0x388127[e[s(530)](_0x2aed67,7)]=e.NLYNZ(255,l),_0x1268e3+=8,_0x2580c5}}async[t(1458)](){let r=t,s={peQyT:e[r(1403)],ORIKQ:"pageshow",SlDcf:function(l,x){return l>x}};if(!(this[r(1458)+r(942)]||this[r(736)+"osed"])){this[r(1458)+"Lock"]=!0;try{let l=this[r(1342)+r(1675)]?.["checkCur"+r(1314)+r(1129)+r(1081)+r(1329)](),{timeoutInterval:x}=this._options;if(l){let v=this["_endpoin"+r(1675)]?.["getCurre"+r(370)+"nt"](),S=this["_endpoin"+r(1675)]?.[r(460)+r(464)+r(618)+r(1521)+r(1415)](),m=this[r(1342)+r(1675)]?.[r(887)+r(370)+"ntTriesC"+r(611)]();if(S){let A="connect "+v+(r(1467)+r(1079)+"tries re"+r(1045)+r(1391)+r(1589)+r(1355))+S+" to retry",P=e[r(526)](wt,e[r(1127)],{message:A,code:mn[r(1272)+r(1258)+"R"]});this[r(725)](A),this["_dispatchErrorEv"+r(446)](P),this[r(1490)]=await this[r(413)+r(1431)](S),this._debug(r(455)+S+" "+m+r(408)),this[r(1083)+"sListeners"]()}else if(e[r(547)](e[r(1224)],e[r(737)])){let A=r(455)+v+(r(1467)+r(1079)+r(1548)+r(1138));this[r(725)](A),this[r(858)+r(644)+"ent"](e[r(1036)](wt,r(902),{message:A,code:mn[r(1272)+r(1258)+"R"]}));return}else return this._ws?this[r(1833)][r(1787)+"te"]:this[r(1628)][r(745)+r(1416)]?this.CONNECTING:this[r(1327)]}else if(e[r(1077)](e[r(1914)],e.AXwVC)){let v=this[r(1342)+r(1675)]?.[r(887)+"ntEndpointAndUpd"+r(1602)](),S=this[r(1342)+r(1675)]?.["getCurre"+r(370)+r(676)+"ount"]();this[r(1490)]=await this["_generat"+r(1431)](v||""),this[r(725)](r(455)+v+" "+S+r(408)),this[r(1083)+"sListeners"]()}else this[r(729)+"er"]&&_0x4d3ee1[r(1218)+"entListe"+r(1139)](r(375),this[r(1672)+r(701)]),this._isBrowser&&_0x50e33e[r(1218)+r(1188)+r(1139)](r(1805),this["_handleO"+r(1751)]),this[r(729)+"er"]&&_0x1daf28[r(1218)+r(1188)+r(1139)](pGdOFW.peQyT,this[r(1125)+r(1231)]),this._isBrowser&&_0xf0c7d0[r(1218)+r(1188)+r(1139)](pGdOFW[r(894)],this._handlePageShow);if(this[r(986)])this._isInit=!1;else if(e[r(1445)](r(1012),e[r(667)])){let v=e.qoSIG(Fa,r(794)+"t",{message:r(779)});this["onStartR"+r(1375)]&&this[r(522)+r(1375)](v)}else{if(pGdOFW[r(1746)](_0x1777ec[r(895)]+_0x1b42a9,_0x4285f2[r(1872)]))throw new _0x29d0c1(r(917)+"t limit");_0x73c80d[r(895)]+=_0x4b0651}let w=this[r(1342)+"tManager"]?.[r(887)+r(370)+"ntTriesC"+r(611)]()||0;e[r(1680)](w,1)&&await this._wait(e[r(1157)](w,1)),this._debug(r(1860)+r(1283)+this[r(1490)]+(r(743)+r(930))+this[r(1154)+"ls"]),this._ws=e[r(855)](Kg,{url:this[r(1490)],protocols:[this._protocols],headers:this[r(1628)][r(545)+r(803)+"s"][r(493)+r(758)]},this[r(1628)].ws),(this[r(729)+"er"]||this[r(1216)+"r"])&&this._ws&&(this._ws.binaryType=this[r(782)+"ype"]),this[r(705)+r(1478)](),this[r(1458)+r(619)+r(1246)]=e[r(1677)](setTimeout,this._onTimeout[r(1248)](this),x)}catch(l){throw this[r(1458)+r(942)]=!1,l}}}[t(966)+t(978)](){let r=t;e[r(843)](clearTimeout,this[r(1458)+r(619)+r(1246)]),this[r(1458)+r(619)+r(1246)]=null}["_clearPi"+t(1679)](){let r=t;if(e[r(1660)](r(985),r(1636)))e[r(971)](clearTimeout,this[r(1461)+r(428)+"Id"]),e.anTyb(clearTimeout,this[r(1772)+r(760)+"tId"]),this[r(1461)+"gTimeoutId"]=null,this[r(1772)+r(760)+r(1407)]=null;else return this.endpoints[this[r(1905)+r(471)]]}_debug(...r){let s=t;this._options[s(864)]&&console[s(1768)][s(1590)](console,[e.oUDbQ,...r])}["_getInte"+t(1070)+"e"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:x,reconnectIntervalGrowFactor:w}=this[s(1628)],v=e[s(1202)](l,Math[s(1817)](w,e[s(1281)](r,1)));return e[s(399)](v,x)?x:v}[t(1301)](){let r=t;if(this[r(1833)]&&e[r(1511)](this._ws.readyState,this[r(749)+"NG"])){this["_clearPi"+r(1679)](),this[r(1461)+r(428)+"Id"]=setTimeout(this[r(1301)][r(1248)](this),this._options.pingInterval);return}if(!this._ws||this[r(1833)][r(1787)+"te"]!==this[r(1453)])return void this[r(648)+r(1375)]();this[r(1833)]&&this[r(1833)].send("hi"),this[r(1772)+r(760)+"tId"]=e[r(1455)](setTimeout,this[r(648)+r(1375)+r(896)][r(1248)](this),this[r(1628)][r(1553)+r(550)+r(620)])}[t(648)+t(1375)+"Timeout"](){let r=t;this[r(1604)+r(1187)]?.addCount(),this.emit(r(1075)+"e_timeout","timeout"),this["_pingLos"+r(1187)]?.[r(1729)+r(1882)+"nt"]()?this["_handleR"+r(1375)]():this[r(1301)]()}_navigatorOnline(){let r=t,s={kpJTR:e[r(379)],jVuVz:function(l,x,w){return e[r(761)](l,x,w)}};if(e[r(1616)](e[r(642)],e[r(1779)]))return this._isMiniTT||this[r(1338)+"X"]?this["_miniNavigatorOn"+r(1586)]:(this[r(729)+"er"]||this[r(1216)+"r"])&&this._options[r(1839)+r(840)+"nged"]?navigator[r(402)]:!0;this.emit(cxpfNE[r(724)],cxpfNE.jVuVz(_0x33d2a5,cxpfNE[r(724)],{..._0x30a1b1}))}["_handleR"+t(1375)](){let r=t;!this[r(1731)+r(1863)]()||this["_readyCl"+r(908)]||(this[r(1342)+r(1675)]?.["resetEndpointCon"+r(1707)](),this[r(1604)+r(1187)]?.[r(635)+r(1758)](),this._ws?this["_disconn"+r(969)](1001,e[r(485)],!0):this[r(1458)]())}[t(478)+t(945)+t(1685)](){let r=t,s={QxVYJ:e.fbgbt,HUDMn:function(l,x){return e[j(457)](l,x)}};this._isMiniTT?tt["onNetwor"+r(751)+"hange"](({isConnected:l})=>{let x=r;this[x(920)+x(1826)+x(1586)]=l,l?this[x(1672)+"nLine"]():this._handleOffLine()}):this._isMiniWX&&wx[r(891)+r(751)+r(1117)](({isConnected:l})=>{let x=r;if(e[x(568)](e[x(1808)],e[x(904)])){let w={ZLAPQ:kWzCWw[x(1388)],JnBdR:function(S,m,A){return S(m,A)}},v=_0x30d8c3[x(1319)].slice(_0x359a7a[x(1683)+"et"],kWzCWw[x(1103)](_0x3bc63d[x(1482)+"th"],_0x242451[x(1683)+"et"]));this[x(859)]&&this[x(859)][x(1204)]({data:v,fail:S=>{let m=x;this[m(1753)](w[m(658)],w[m(845)](_0xfb4fa0,w[m(658)],{message:this[m(1046)+m(1032)+"age"](S)}))}})}else this[x(920)+x(1826)+"line"]=l,l?this[x(1672)+x(701)]():this[x(1672)+"ffLine"]()})}_wait(r){return new Promise(s=>{let l=j;e[l(1174)](setTimeout,s,this[l(928)+l(1070)+"e"](r))})}[t(1810)+t(969)](r=1e3,s="",l=!1){let x=t;this[x(1833)]&&this["_destroy"+x(1052)+"t"](r,s,l)}[t(607)+"ut"](){let r=t;if(e[r(1077)](e[r(1186)],e[r(655)]))return null;{let s=this[r(1342)+"tManager"]?.[r(887)+r(370)+"nt"]();this[r(725)](r(455)+s+r(1467)),this[r(1810)+r(969)](1001,e[r(1855)],!0)}}[t(1566)](r){let s=t;if(e[s(734)](s(1315),e[s(1019)])){let l=Xt(r);this[s(1833)]&&e[s(631)](this[s(1833)][s(1787)+"te"],this[s(1453)])&&(this._ws&&this[s(1833)][s(1204)](l),this._debug(e.hRmFE,r))}else this[s(986)]=!0,this[s(1458)]()}[t(1083)+"sListeners"](){let r=t;this[r(1833)]&&(this[r(1833)][r(1218)+r(1188)+r(1139)]("open",this[r(512)]),this[r(1833)][r(1218)+"entListe"+r(1139)](r(1665),this[r(612)]),this._ws["removeEv"+r(1188)+r(1139)](e[r(637)],this[r(1424)+"ge"]),this[r(1833)][r(1218)+r(1188)+"ner"](e[r(1127)],this._onError))}[t(705)+"steners"](){let r=t;this[r(1833)]&&(this._ws[r(1738)+"Listener"](r(1822),this._onOpen),this._ws["addEvent"+r(744)](e[r(379)],this._onClose),this[r(1833)]["addEvent"+r(744)](r(580),this._onMessage),this._ws["addEvent"+r(744)](e[r(1127)],this[r(940)]))}[t(846)+t(369)](r=1e3,s=""){let l=t;if(e.EwcIc("UoXGj",e.zskKW)){let{pingInterval:x,pingFrequency:w}=this[l(1628)];if((e[l(533)]("hi",_0x434702[l(806)])&&e[l(1873)](e.YWJcH,w)||e.yhpaF(e[l(1039)],w))&&(this[l(1551)+l(1679)](),this.emit(e.zcrFh,l(933)),this[l(1461)+l(428)+"Id"]=e.xwhRG(_0x561d67,this[l(1301)][l(1248)](this),x)),e[l(385)]("hi",_0x48090b[l(806)]))return;try{e[l(1754)](_0xade04,this,_0x8f74ed,[_0x4e52e3,_0x42bc95,_0x46ff48,_0x54a306,_0x4f71ae,_0x4e1fab])}catch(v){let S=_0x578af1(e.fbgbt,{message:v[l(580)],code:_0x131249[l(1612)+l(1011)],error:v});this["_dispatc"+l(644)+"ent"](S)}}else try{this[l(1833)]&&this[l(1833)][l(1665)](r,s)}catch{}}[t(1399)+"WebSocket"](r=1e3,s="",l=!1){let x=t;if(this[x(1551)+x(1679)](),this[x(966)+"mer"](),this[x(1083)+x(1695)+"rs"](),this[x(846)+x(369)](1e3,s),this[x(1458)+x(942)]=!1,l&&this["_navigat"+x(1863)]()&&!this[x(736)+x(908)]){if(this["_endpoin"+x(1675)]?.[x(1729)+"chMaxTries"]()){let v=this[x(1342)+x(1675)]?.[x(887)+x(370)+"nt"]();this[x(858)+x(1545)+x(446)](e[x(1879)](kt,e[x(379)],{code:1006,reason:x(455)+v+(x(1467)+x(1079)+"tries re"+x(1138)),wasClean:!0}))}else{let v=this[x(1628)][x(794)+"tInterceptor"](r,s);this[x(858)+x(1545)+x(446)](e[x(436)](kt,e[x(379)],{code:r,reason:s,wasClean:!0,willReconnect:v})),v&&this[x(1458)]()}return}this[x(1731)+"orOnline"]()||this[x(736)+x(908)]?this[x(858)+"hCloseEvent"](kt(e[x(379)],{code:r,reason:e.iDfdS})):this["_dispatc"+x(1545)+x(446)](e.afcPo(kt,"close",{code:1006,reason:e[x(564)]})),this._ws=null,this[x(1342)+x(1675)]?.[x(577)+x(364)+x(1707)](),this._pingLossCounter?.[x(635)+x(1758)]()}[t(858)+t(1437)+"nt"](r){let s=t;this[s(1753)](e[s(960)],r),this[s(1444)]&&this.onopen(r)}[t(858)+t(1846)+t(1210)](r){let s=t;this[s(1753)](e.eHoWc,r),this[s(1313)+"e"]&&this[s(1313)+"e"](r)}["_dispatc"+t(1587)+t(1789)](r){let s=t;this[s(1753)](e[s(479)],r),this["onReceiv"+s(1889)]&&this[s(556)+s(1889)](r)}[t(858)+t(644)+t(446)](r){let s=t;this[s(1753)](e[s(1127)],r),this.onerror&&this[s(1097)](r)}[t(858)+"hCloseEv"+t(446)](r){let s=t;e.IZehN(e[s(559)],s(1158))?(_0x540b76+=e[s(1183)](_0x32734e,_0x30d15e),_0x5d9849++):(this[s(1753)](e[s(379)],r),this[s(996)]&&this.onclose(r))}get[t(816)+"pe"](){let r=t;return this[r(1833)]?this[r(1833)].binaryType:this[r(782)+r(801)]}set[t(816)+"pe"](r){let s=t;this[s(782)+s(801)]=r,this[s(1833)]&&(this._ws[s(816)+"pe"]=r)}get[t(1312)+"nt"](){let r=t;return e[r(818)](e[r(472)],e[r(472)])?this[r(1342)+r(1675)]?.[r(887)+r(370)+r(676)+r(611)]()||0:this[r(1833)]?this[r(1833)][r(481)]:this._url}get["buffered"+t(602)](){let r=t,s={tWGWL:function(l,x){return e[j(1570)](l,x)}};if(e[r(1318)](e[r(836)],"wgWFR"))return this[r(1658)+"Queue"][r(728)]((x,w)=>(x+=w&&w.byteLength||0,x),0)+(this._ws?this._ws[r(1722)+r(602)]:0);{let l=this[r(1333)]["getStora"+r(918)](this[r(1167)]);return _0x17fa9e[r(1434)](ZZelUh[r(639)](l,"{}"))[_0x5543cc]}}get extensions(){let r=t;return this[r(1833)]?this._ws[r(1102)+"ns"]:""}get[t(1101)](){let r=t;return this._ws?this[r(1833)][r(1101)]:""}get[t(1787)+"te"](){let r=t;if(e[r(1678)](e[r(1067)],e[r(1067)]))return this[r(1833)]?this._ws[r(1787)+"te"]:this[r(1628)][r(745)+r(1416)]?this[r(749)+"NG"]:this[r(1327)];{let{value:s,offset:l}=_0x1821e7(_0x35c1e6,_0x1d77d6);_0x859506=l,_0x4d4028=e.gaLkV(e[r(1831)](_0x219623,8),0),_0x54e4e5+=s}}get url(){let r=t;if(e[r(643)](r(506),e.hbdje))this[r(979)+"T"]||this._isMiniWX?this[r(478)+r(945)+r(1685)]():this[r(729)+"er"]&&this[r(1092)+r(1767)+"Listener"]();else return this[r(1833)]?this._ws.url:this[r(1490)]}[t(1665)](r=1e3,s){let l=t,x=e[l(1907)][l(1277)]("|"),w=0;for(;;){switch(x[w++]){case"0":if(this._ws[l(1787)+"te"]===this[l(1327)]||e[l(1678)](this[l(1833)][l(1787)+"te"],this[l(932)]))return void this._debug(e.qMObA);continue;case"1":this[l(452)+l(438)]?.[l(1462)]();continue;case"2":if(!this[l(1833)])return void this._debug(e[l(1761)]);continue;case"3":this[l(1551)+l(1679)]();continue;case"4":this[l(736)+l(908)]=!0;continue;case"5":this[l(1399)+l(1052)+"t"](r,s);continue;case"6":this[l(966)+l(978)]();continue;case"7":this["_dropGlo"+l(1767)+"Listener"]();continue}break}}async[t(1204)](r,s){let l=t;if(r==null)throw new Error(e[l(1650)]);e[l(669)](e[l(1737)],typeof r)&&(r=JSON[l(1222)+"y"](r)),e[l(1370)](l(1168),typeof r)&&!e[l(1309)](r,ArrayBuffer)&&!(r[l(1319)]&&e[l(1487)](r.buffer,ArrayBuffer))&&(r=JSON.stringify(r));let x=await e[l(1816)](jl,r),w=e.tsMhO(Vg,r),{method:v=0,service:S=this[l(1628)][l(1115)],logID:m=this[l(1628)][l(504)+l(579)](),headers:A=this[l(1628)][l(1173)],payloadEncoding:P=this[l(1628)][l(1603)+l(636)],payloadType:N=this[l(1628)][l(957)+l(801)],logIDNew:Y=this[l(1628)][l(939)+"Config"][l(1031)+l(483)+l(1597)+"ew"]?e[l(774)](i,this[l(1628)][l(939)+l(1565)][l(1824)]):""}=e[l(1136)](s,{});if(!S)throw new Error(e[l(1297)]);let V={SeqID:ce[l(1554)+"er"](this[l(1182)]++),LogID:ce[l(1554)+"er"](m),service:S,method:v,headers:A,payloadEncoding:P instanceof Object?P[l(599)]?P.encoding:"":P,payloadType:e[l(1448)](N,Object)?N[l(949)]?N[l(949)]:w:N||w,payload:x,LogIDNew:Y},xe=e[l(671)](Xt,V);return this[l(1833)]&&this._ws[l(1787)+"te"]===this[l(1453)]?(this[l(1833)]&&this._ws[l(1204)](xe),this[l(725)](e.Cwgph,V)):e[l(628)](this[l(1658)+l(1417)][l(1359)],this._options[l(665)+l(1363)+l(365)])?(this[l(1658)+"Queue"][l(1426)](xe),this._debug(e[l(1108)],V)):(this["_message"+l(1417)].shift(),this[l(1658)+l(1417)].push(xe)),{seqID:this[l(1182)],logID:m,logIDNew:Y}}async[t(794)+"t"](r){let s=t,{url:l}=r||{},x=Array[s(1207)](l)?l:e[s(1618)]==typeof l?[l]:[];r&&Object[s(657)](this[s(1628)],r),x&&x.length?this[s(1342)+s(1675)]=new Hl(x,this[s(1628)].maxRetries):this[s(1342)+s(1675)]?.[s(577)+s(364)+s(1707)](),this[s(1604)+s(1187)]?.[s(635)+s(1758)](this[s(1628)][s(496)+s(1278)]),this["_readyCl"+s(908)]=!1,this._ws&&e[s(594)](this[s(1833)].readyState,this[s(1327)])?this[s(1810)+s(969)](1e3,e[s(1694)],!0):(this[s(986)]=!0,this[s(1458)]())}async connect(){let r=t;if(!this[r(1458)+r(942)]){let s=e[r(1871)][r(1277)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(986)]=!0;continue;case"1":this["_pingLos"+r(1187)]?.["resetCou"+r(1758)]();continue;case"2":this["_readyCl"+r(908)]=!1;continue;case"3":this["_endpoin"+r(1675)]?.[r(577)+r(364)+r(1707)]();continue;case"4":this[r(1458)]();continue}break}}}[t(1738)+"Listener"](r,s){this.on(r,s)}dispatchEvent(r){let s=t,{type:l}=r;this[s(1753)](l,r)}[t(1218)+t(1188)+"ner"](r,s){this[t(1909)](r,s)}[t(882)](){let r=t,s={QgJfe:function(l,x){return e[j(1645)](l,x)},psEOJ:e[r(740)],JLhRQ:e[r(851)],oFeLA:e[r(738)]};return new Promise((l,x)=>{let w=r,v={pJlFg:function(S,m){return e[j(1854)](S,m)},nPtvz:e[w(1286)],EAPZK:function(S,m){return S(m)},HsWbL:e[w(1299)],CYsRg:e[w(851)]};if(e[w(1184)]!=="LBhDe"){this[w(1551)+w(1679)](),this[w(1461)+w(428)+"Id"]=e[w(1365)](setTimeout,this._ping[w(1248)](this),this[w(1628)].pingInterval);let S=()=>{let A=w;s[A(1433)](l,s[A(1292)]),this[A(1909)](s[A(860)],S),this[A(1909)](s[A(557)],m)},m=()=>{let A=w;if(v[A(377)](v[A(1715)],A(391)))v[A(670)](x,v[A(1334)]),this[A(1909)](v[A(371)],S),this[A(1909)]("ping_onc"+A(480)+"t",m);else return this[A(859)][A(481)]};this.on(e[w(851)],S),this.on(e[w(738)],m),this._ping()}else{let S=_0x39071e[w(1302)]();return S?(S[w(895)]=S[w(1872)]=0,S):{bytes:new _0x33e336(64),offset:0,limit:0}}})}}})(),Fe[B(1500)+"oseEvent"]=De["CustomCl"+B(1196)],Fe[B(1389)+"rorEvent"]=De[B(1389)+B(877)],Fe[B(1261)+"e"]=De[B(1261)+"e"],Fe[B(1210)]=De[B(1210)],Fe[B(1696)]=De.FWS,Fe[B(1473)+B(495)+B(1073)]=De[B(1473)+"MessageE"+B(1073)],Fe[B(495)+"vent"]=De[B(495)+B(1073)],Fe.OpenEvent=De.OpenEvent,Fe[B(1916)+B(1035)]=De[B(1916)+"tEvent"],Fe[B(1252)+B(1196)]=De[B(1252)+"oseEvent"],Fe["createEr"+B(877)]=De[B(1596)+"rorEvent"],Fe[B(1534)+B(537)+"nt"]=De[B(1534)+"ssageEvent"],Fe[B(1662)+B(756)]=De[B(1662)+"enEvent"],Fe.createReconnectEvent=De[B(1494)+B(501)+"vent"],Fe[B(1786)+B(735)]=De[B(1786)+B(735)],Fe[B(1176)+"ame"]=De[B(1176)+B(1130)];for(pa in De)[B(1500)+B(1196),B(1389)+"rorEvent","ErrorCode",B(1210),B(1696),B(1473)+B(495)+"vent",B(495)+B(1073),B(1682)+"t","Reconnec"+B(1035),B(1252)+B(1196),"createEr"+B(877),B(1534)+B(537)+"nt",B(1662)+B(756),B(1494)+"connectEvent",B(1786)+B(735),"encodeFrame"].indexOf(pa)===-1&&(Fe[pa]=De[pa]);var pa;Object[B(1169)+"operty"](Fe,B(1842)+"le",{value:!0})});import{existsSync as OI,openSync as LI}from"node:fs";import{mkdir as MI}from"node:fs/promises";import{dirname as NI}from"node:path";import{fileURLToPath as BI}from"node:url";function zI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function yl(t=J()){return OI(t.libEntry)?t.libEntry:BI(new URL("../index.ts",import.meta.url))}async function tg(t={}){let e=t.paths??J(),n=t.entryOverride??yl(e),i=zI(e,process.env.COZE_BRIDGE_LOG_MODE);await MI(NI(i),{recursive:!0});let o=LI(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=ct(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[ys]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return FI.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var FI,ys,Aa=st(()=>{"use strict";Wt();ne();Te();FI=H("spawn-daemon"),ys="COZE_BRIDGE_DAEMON"});import{spawn as NA}from"node:child_process";import{mkdir as BA,unlink as FA,writeFile as zA}from"node:fs/promises";import{dirname as UA,join as HA}from"node:path";function ui(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function GA(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${ui(n)}</key>
|
|
20
|
+
`+n)}function fr(t,e,n,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,fr),t.emit("wsClientError",d,n,e)}else gs(n,i,o,a)}});var qp=ue(ze=>{"use strict";var L=F;(function(t,e){let n=F,i=t();for(;;)try{if(parseInt(n(1493))/1+parseInt(n(1216))/2+-parseInt(n(1429))/3*(parseInt(n(1388))/4)+-parseInt(n(1237))/5*(parseInt(n(1573))/6)+-parseInt(n(595))/7+parseInt(n(534))/8*(-parseInt(n(791))/9)+-parseInt(n(842))/10*(-parseInt(n(1181))/11)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(wa,897231);var Q1=Object[L(612)+"operty"],eI=Object[L(1680)+L(1274)+L(1717)],Bp=(t,e)=>function(){return t&&(e=(0,t[eI(t)[0]])(t=0)),e},tI=(t,e)=>{let n=L,i={txliw:function(a,d,u,f){return a(d,u,f)}};for(var o in e)i[n(1512)](Q1,t,o,{get:e[o],enumerable:!0})};function nI(){return Dp||(Dp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function rI(){let t=L;return Lp||(Lp=[IDBCursor[t(1640)+"e"][t(741)],IDBCursor[t(1640)+"e"][t(760)],IDBCursor[t(1640)+"e"][t(760)+"PrimaryKey"]])}function iI(t){let e=L,n={vHcJH:e(1471),uHhzV:e(1664),qQqfr:function(o,a){return o!==a},sCwks:e(1221),eucQo:function(o,a){return o(a)},CoezF:function(o){return o()},YOJkk:function(o,a){return o(a)},pzfDc:function(o,a){return o<=a},tejSn:e(985)+e(1096)+e(1259)+e(937)+e(522),cumYJ:function(o,a){return o===a},RVZCW:function(o,a){return o+a},lKFbc:function(o,a){return o instanceof a}},i=new Promise((o,a)=>{let d=e,u={qkGmi:function(m,y){return n[F(899)](m,y)},fEZbx:function(m){return m()},UOvDm:function(m,y){return n.pzfDc(m,y)},NwkAJ:n[d(413)],oRsdX:function(m,y){return n.cumYJ(m,y)},RwUPl:function(m,y){return n[d(1050)](m,y)}},f=()=>{let m=d;t[m(872)+m(1003)+"ner"](n[m(1371)],x),t[m(872)+m(1003)+"ner"](n[m(705)],p)},x=()=>{let m=d;o(u[m(1695)](Jt,t[m(1716)])),u[m(541)](f)},p=()=>{let m=d;if(n[m(558)](m(1221),n[m(1743)]))return u[m(1013)](_0x53350c,_0x4e7f78)?_0x5532fa[m(1366)](new _0xce7b83(u[m(1739)])):(_0x1ea8b4=_0x7a4c1b,u.oRsdX(_0x4af0ec,_0x6e45b6[m(1436)])?_0xb838c6[m(1241)]():_0x32716f[_0x424b87][m(1289)](_0x18353a)(_0x508bfb,_0x420d71[m(1289)](null,u[m(603)](_0x58a342,1))));n.eucQo(a,t.error),n[m(1404)](f)};t["addEvent"+d(459)](n.vHcJH,x),t[d(1347)+d(459)](d(1664),p)});return i.then(o=>{let a=e;n[a(371)](o,IDBCursor)&&pl[a(882)](o,t)})[e(1251)](()=>{}),ya.set(i,t),i}function F(t,e){t=t-315;let n=wa(),i=n[t];if(F.rLxrAf===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",m="";for(let y=0,_,E,I=0;E=f.charAt(I++);~E&&(_=y%4?_*64+E:E,y++%4)?p+=String.fromCharCode(255&_>>(-2*y&6)):0)E=x.indexOf(E);for(let y=0,_=p.length;y<_;y++)m+="%"+("00"+p.charCodeAt(y).toString(16)).slice(-2);return decodeURIComponent(m)};F.fdneVZ=o,F.JeWJHa={},F.rLxrAf=!0}let a=n[0],d=t+a,u=F.JeWJHa[d];return u?i=u:(i=F.fdneVZ(i),F.JeWJHa[d]=i),i}function sI(t){let e=L,n={QhOoI:function(o,a){return o(a)},vLvkL:"AbortError",ofwpK:function(o,a){return o===a},LaAxm:e(1701),VuiGW:e(1741),EmnSx:e(1664),qPkGx:e(868)};if(_a[e(679)](t))return;let i=new Promise((o,a)=>{let d=e,u={CNWpB:function(m,y){return n[F(1451)](m,y)},zjOVo:n.LaAxm,Eqjby:function(m){return m()}},f=()=>{let m=F;t[m(872)+m(1003)+m(1484)](m(1741),x),t[m(872)+m(1003)+m(1484)](m(1664),p),t[m(872)+m(1003)+m(1484)](m(868),p)},x=()=>{let m=F;u.CNWpB(u[m(1756)],u.zjOVo)?(u.Eqjby(o),u.Eqjby(f)):this[m(1480)+"T"]?_0x25a9b9[m(1734)+"kStatusC"+m(952)](({isConnected:y})=>{let _=m;this["_miniNav"+_(1372)+_(1112)]=y,y?this._handleOnLine():this[_(632)+_(623)]()}):this[m(1748)+"X"]&&_0x3bdb17[m(1734)+"kStatusC"+m(952)](({isConnected:y})=>{let _=m;this[_(1030)+_(1372)+_(1112)]=y,y?this[_(632)+_(1452)]():this._handleOffLine()})},p=()=>{let m=F;n[m(520)](a,t[m(1664)]||new DOMException(n[m(1352)],n[m(1352)])),f()};t[d(1347)+"Listener"](n.VuiGW,x),t[d(1347)+d(459)](n[d(907)],p),t[d(1347)+"Listener"](n[d(462)],p)});_a[e(882)](t,i)}function oI(t){ba={WfqRD:function(n,i){return n(i)}}.WfqRD(t,ba)}function wa(){let t=["uxzUC3O","ywTzC3e","Avvvque","nhWYFdn8mhW","zxjYtxnN","vu9cC24","quzvsKu","D3jPDgu","sgrtBwK","DhjPzxm","EMHhBvC","tKzJr0S","rNvqB2y","Ce9vq2S","CwThBwK","BM5Ly3q","AevYCM9Yrxy","CgLUz19VBMm","zfvsEeC","zfnsAxu","s1bzDKC","ufrnuKS","y3r4","AenYrwW","B25LCNjVCG","qNrhEei","s1Dytfy","CfroyLG","zwHhww8","D3P6qwe","Efrurw52","zuruvei","DgvmB2Djre4","x3jLy29UBMu","zw1LBNq","CMvZDwX0","BwvZ","tKPpy0u","x2LZtM9Kzq","qMrfD3i","vuDhDLK","C1v5wNm","x21LC3nHz2u","q1Lpsgu","CMzcDhy","yw1Lu3bHy2u","yM9L","CxL3rxi","z0zsB2i","Ee5sq0e","vunZCxu","wePAA3O","v1f2C0e","B25ozxr3B3i","t1bftG","Ewv0tNq","Dg9Y","C3bSAxq","tNDRquO","ve5PBKq","y29TCgXLDgu","CfftswK","C0n3A3m","x29UvgLTzw8","thPOA0y","C29YDa","BLPRCK8","x2LZtwLUAvC","y291BNq","x2LZsw5PDa","tLvHzvi","vwHbq2e","ihrYEsbYzwm","Dg9cExrLC0W","CeXwwu8","EMPpvM8","DenvDLC","vgLTzw91Da","q29UzMLN","y3vYCMvUDeK","EK1frKi","EK5dBNa","y0HtsgW","yNL0zxm","zenAugC","DgTRtuq","D3jPDgvvAw4","AM9Zrw8","zxjFBxnNAwq","Chv0","Dgv4Dc9WBge","vw1zvxC","wLfyueO","u3HIt20","qwnlDKm","B25szwnLAxy","C3rYAw5NAwy","zw50zwqGDhK","twvZC2fNzuu","zw1PDa","wwnhAg8","u05dvLa","ugzTr2u","ywnRx2LK","A3rbC1O","C3jJ","Cgf5Bg9Hzeu","ywDL","q3vZDg9Trxi","rujctKW","x25HDMLNyxq","BKr1zvK","u2Ppv0u","C0L2s0G","yMrFzgLK","C1HJy3a","zvvoyLa","Dwrizgm","DxbNCMfKzw4","r2Tpu3G","tgfbu0u","BxvnCK0","uwjjy1C","q0Xpu0LorW","AuTfrfe","CMHHALa","Dg9VigXHCMC","zMLUza","x2DLBMvYyxq","CxfiBue","vuLZqLO","u1DYtve","nNWZFdq","B1vOuw0","CMvHzg9UBhK","wgPhz1a","AKHPs2S","zvjZtwS","tKDFrvjst1i","ywDLu2HVDW","AgvHzgvYCW","AgvHzgvY","CxP3zeS","wu52wem","ENLSD1q","BMvOzMC","wNndD0G","q1jLDgy","u2D3tfm","vuXwwNu","Axnby2TdBgu","EuXQtue","B3ryA3G","A2nPwee","Ahr0Ca","rLDt","BNrbqNq","qvPYtvK","x2rPC3bHDgm","rxLYvem","zNjVBujPDhm","y3jLyxrLuMu","A1z2yMC","wKnYvM0","uKzUz1G","uvLdzgS","sxf6zxO","surOsgC","BxnN","uxDzueS","ihrVihjLDhi","qu5xCLG","BML0AwfSAxO","ywzL","vw5PBxbSzw0","BMXnAgC","ihzHBgLKigq","y2fSBa","BNvTyMvY","BMfsrwK","x2LUAxq","wKflAeO","qwPZEgS","BMrWB2LUDca","CgT5rvi","yKvNAfe","uKTnBei","t3L3Duy","uLjpuG","zMLSDgvY","BeTgyMm","B3zpzuW","CKnrwhC","EwLyyNK","Ef9MCM9UDgK","DNvNCw0","vgfN","zMLN","DNvZCKe","Ec11C2uT","ueX5EMm","uwLzENi","uw14tg4","vezJy2G","DKfbAw4","yNvMzMvY","CMvJB25Uzwm","AxnrB1nby2S","BxDluge","AK5fA2G","B25JBg9Zzq","B2foCg4","uNvhvxy","C2L6qLy","rNnPsMu","wKjmreW","u3rJCvC","yu5ftKe","vNzdDve","Aw5KzxHpzG","x0rctMfTzq","EwvArMG","Cgf5Bg9Hza","x2LZqNjVD3m","DgfIyxnL","y3vYDMfSDwu","CxzbwfK","z2v0qwXSs2u","CvrJvLu","vwjUuwW","rgjJCwG","Bhm6ia","DgvQu24","C2fNzq","rhfHvgy","ywvPzgW","DMvYC2LVBG","EK1Vufi","wezSuNa","v3DTBLq","BffAyvm","DgfYz2v0","x3jLywr5q2W","CNH3tfK","DxbKyxrLq3u","DMnVB2i","CgfYC2u","qw1VDw50","z2v0q3vYCMu","x3nLBMrby2S","vLnhCeO","y2XVC2veqG","DeLUDgvYy2u","y3zPDgS","DuPvuxq","AfvSyMm","vhLXzwS","uMfHC3O","B25Uzwn0Aw4","zgrjrcWGzgu","Ahb1EuC","zKvSrwG","BgPqBwy","rxjYB3jdB2q","qM1krhG","ugngqvi","wgr0qxq","AxnbCNjHEq","DMPmDxO","zxrxqKi","u2XIEfa","vKDdzfO","qw5yBhG","vxbKyxrLq28","CNjVCK1LC3m","Avn2tLm","CM92AwrLihC","uhr6AKK","tgLZDgvUzxi","swXJA0W","uun3r1C","CvbRr3G","zwHxzNa","qxnVuMW","Cw9Z","ueH5twO","D3DuBxG","lcbTyxGGCMu","ywXPzcb1CMW","suLQD1i","u2HHCMvKv28","DMXjzwO","AefUvLy","r0zfBLq","z2v0s2v5","x2rYB3bhBg8","A0jdBNa","B3bLCNr5","y29UC3rYDwm","vxrOBwG","u3PvDuy","x3bHDgHlzxK","B2XKvMvYC2K","BevzBLa","yxnL","zvvYBa","ru1Pwuy","z2v0qwXS","qNrYtgm","Cgf5Bg9Hzfq","B0HqwKC","sLrWtgu","wKPkwwW","y29Uy2f0","z3LYv00","y29UDgv4Da","u1nbuwy","t29cwMW","DgHLBG","z0vtEKS","BMnVzgLUzW","qMvrAuu","qwfjEgq","su1LrM8","wwjPCxK","BK5it1i","tM9xtum","D1nYqwS","zNfOuuC","Dw5Mshy","Dgv4DfbHEwW","yMfSrxzLBNq","seDLsfy","tg9Nsuq","re5ZyKq","u2TPCcbWyxm","y2XLyxi","tLz0zwG","ywXSq3vYC28","uwHpB0K","x0vysvnu","ChjVy2vZCW","yw9YtMq","shrKwee","AxnrB1nnzxm","ugrsy0y","rMTfBKK","vfbqzKm","twLVtLK","DfrjyNm","B3nLza","zcWGDw5RBM8","BgvVtLG","nJG5mdmYog5Nu05vwq","o2nOyxjZzxq","zxjHDg9Y","ExbL","CvnsDuK","rhbyq3G","B3jL","zKvAyNG","zwvmDKG","rg5XvK0","x2HHBMrSzvi","t0vmvgS","CMvJzxzPzwq","v2zJzuW","CM92AwrLigi","igXHCMDLCIa","CMvZzxruCMK","BwvY","rgv4BeO","wMfby1m","EuHQuvq","C2vUDa","t0HsyM8","B3bLBG","CvfXzNi","CgLUz1rPBwu","wNLYuKu","Dufhrhy","AMvJDfn0B3i","q29Kzq","q2PRBKu","CgfNzwHPzgu","CMfTugfYyw0","D0Dsrei","C1Pht28","wg1SwKK","C1DUDwG","AxnszwfKEq","wvvWqLa","rvLLwNC","zhrty28","BNrfBMrWB2K","x2TLEvbHDgG","ywnOzwq","zeLuCwG","Aw9Ul2PZB24","A0PNEuK","AgfmEuK","C2v0u3rVCMe","qvj6u1q","v3DAy0m","ugHRDem","zM9Yy2u","tuLIDxi","Cw9Zx18","t2v3txy","B2HxwNC","AxnmB25N","s3zJvMC","AxP0v3C","sMH1C3G","ntu5nJCZofLkuxjIEG","zxf1ywXZ","yvLxCwS","AwXLtMfTzq","ywDLrxzLBNq","ChPlugK","BKPQsgW","D2zPCfu","uNDvugW","DMfS","x2LUAxrqCM8","vNHjAuS","uMvJB25Uzwm","B0jKEMK","AxjLza","s3zIrLe","Du94Cfi","zgvMAw5Luhi","Ae9Wzw5fDMu","rwzzqxO","Aw5Lza","EhP2wLa","C2v0q3vYC28","x3bPBMC","BMPhBwK","Efrxs2C","Dgv4Dc9Qyxy","DMvYC2LVBMm","zMzmAw5L","zNjVBunOyxi","zfDVCMTLCKC","C2vYDMLJzq","BfrPBwvVDxq","z29PBMCGyxC","qxrOBMe","t0PVt2C","DhDVCMTdAge","x2HHBMrSzu8","CLrlDMi","De1HBMfNzxi","B05xs3y","yKfdtKG","zwnVBM5Ly3q","Dxrjza","ywrK","veDivKq","rMLxDLu","BxnNsuq","rhDVwwS","ze9WufC","z2v0sxrLBq","zcWG","AgTey2C","BMv3vMvYC2K","CNnVCKzPBgu","swjpBwm","CNzHBa","CMzKsNq","Bwf4tg9ZC0m","x2nVBM5Ly3q","q09oveLovuu","x2XPC3rLBMu","qwvQBxy","C2zUC20","vhL2sNi","y0rfrvK","EvD4sK0","yxKSihrYEsa","B1fdz3y","x1fVu01HBMe","r3fWuhK","A1L4BNG","Ben5sKy","zhniyuS","CMTLCKDSB2i","wfnevhm","CNLesvK","yMLUyxj5vhK","v1vSy0G","Bg9NsurozxC","CMT2ww4","t3bRr08","yNL0zu9MzNm","Bw1gC0u","AgfZ","u2nowvC","EwDhAhK","Bg93","CKzyreS","zKLQEM8","zLHMy2K","yu5VrhO","ug1ftgG","B210tvu","uwzYEfy","BM93","zxfjzfK","wK9fv0S","y2HHCKnVzgu","qw1VBe8","y29SBM8","DhjPzxmGCMu","z2vY","BNruCMLLC0m","z3fVvKe","t25gq3K","zMD1Eg0","CxzMExO","sNDICge","u1b2sKG","DuHOELy","Cg9W","swHquNC","zKL3qNK","s1bzCfO","wM9HseK","AKfeDgO","vKP1EgG","AgvKtwf4uMu","s0TOvK4","BhHIBg4","CKj6B00","y29UBMvJDgK","zMTYD2u","txLxwhy","zLPwzNG","q2Dtyvu","D2POBLy","D2ngvfe","Aw5KzxG","v1DqAwy","zfHQy0y","A3bkyMS","yxbWBgLJyxq","wMzvtNq","txHyvfC","t1Htrfe","veTZEgO","vgTpwwy","t2jQzwn0","BhzrteS","vwXLr1q","CNnVCL9Uyw0","y2rWswq","mxWZFdj8mhW","v2vIu29JA2u","ywr2yw5Jzq","v0rPD1e","Fdf8ohW0","x2rLyNvN","u2nztu8","wenqD2G","BxLeDNq","AxnFywnR","B25dBg9Zzq","ywnRpwzYB24","tKnSwK8","EfPrruC","q291BNq","CLzHBhvLCW","BwvZC2fNztO","BMnLq2XVC2u","DNDgq2i","y29UBMvJDca","vw5Oyw5KBgu","y29UDgLUDwu","Bwf4uMv0CMK","u0POBwq","tfvIAKO","x3nVy2TLDa","yKPVs3y","EvjVsNy","DhLWzq","CgLUz0XVC3m","B05TqwS","s1L6uei","uM1Lu0C","vg9su3O","uwjMtLe","qvn6DM0","rejHu3C","Dw50","Cg9PBNrbBMq","rxLtvvq","CgLUz0LUDgu","mdaWmdaWmda","CMfUzg9T","y2vWuxy","rKXfseG","x2jPBMfYEvq","rLv2AeW","C1vLqNe","vK1kCgm","B2nRzxrgywK","tK9fC0q","t3zLvfi","mtHoqMTOtue","Eg9qy1K","u09SEu4","sgHdz00","BMP6DxC","CgjICdi","ENfjseS","CMvWBgfJzq","rfv5Bg8","CMvZzxrdB3u","y3jLyxrLrxi","twLZC2LUzYa","sfvjuhm","rgvKAwnHDgu","ChrVCG","sePks0S","t2juBw0","qNnRBuG","zgvSzxrLrge","wfvdDxa","u3rYyxrLz3K","BuHdDuu","svzlDNa","B3jHyMS","svvpwK8","CgXLyxnLiha","t0rktMi","DgLTzw91Da","vNPPDLi","zgvIDwC","rKHoseG","uerXBfu","BNnoq00","tufyx1jfvfi","zerKBxi","zw5XDwv1zq","CMPKA1i","mNWZFdf8nhW","CM92AwrLige","Cur5ENy","vevMuee","s0Tttem","zNjVBuj5Dgu","BM9Uzv9UB24","BMLjvMC","Be12DM4","thHwCvC","x2nSzwfYvgK","z21KCwq","yvj5ww8","vNDevey","mJbTA3LlsKu","suvtx0vsuK8","AK5uB0S","x3bPBMDqB24","q0TNsvC","Dg9cExrLC0i","y2XVC2u","tLbPCg8","rKD3u1a","sxzPA1u","EsbJBg9Zzwq","BwvZC2fNzq","v1vMBwC","rw94u0i","DeLK","vgPqDhi","qKrPrLm","y2f6uMK","uunUA20","tvbLz20","D29vrKO","BIWGAg9ZDg4","D0HOt0q","qMvtzha","v1nVAgu","CK5utxi","ywjVCNq","Aw9U","q3vZDg9Tq2W","x2rPC2nVBM4","CMvTB3zLrxy","nNWXmhWZFdu","t1bftL9fuLi","Dwnbwvi","jMPZy2fSBgi","mhW0","C2rrzue","DgLUzYbZzxi","yxvvDwG","D29Lt1m","C2v0","s092qwy","CMvJzwL2zwq","CMvWBgfJzui","txfzu2S","zgf0yq","yxbWBhK","y3jLyxrLt2i","DKnLANC","m3WYFdz8nq","x3fVC0rc","r2L3wLi","yxKSig5LDhC","D2LSBfjLy28","x2n1CNnVCKy","BKHgD0O","s2nMwgG","wu9kA2S","AxnAzxjV","u0jZsNy","CgjswM0","mxW1Fdn8mNW","D3nZoI8V","uKPLChG","uvzAweC","rw1Uu3G","zxmGCMvHy2G","qKLkDhG","AxmGDw5Kzwy","Dev2zw50","svHkBMG","CMvZzxrfBMq","zsbHihn0CMK","C2v0y3vYC28","CMLXDLu","rNnVtKi","A1n0yxr1C0m","zLLxq3G","z1PNDu4","ALfVuxe","q1zPsuy","u1bIwg0","C3rVCMu","DKT6Dui","DfbqsMK","qwvkyvu","vNP1z20","sMLJEMG","tLjQteG","y0fzvgm","qM1ZBgi","x2LZv29YA2u","yMTLB00","AfnoAve","CMLLC0nVDw4","Aw1LCYbPBIa","D24GCMvHC28","txr3C0W","vKTpwuy","whrWD0C","DxrMofDYAxq","BLbPvKS","ywnR","tuHdq3G","zw5NDgG","x2nSzwfYugK","tMX2tva","s0PMseG","zxH0ugf5Bg8","tg9JAW","AgfUz2u","Bu5yBLC","C2v0zgi","x3DHAxq","Aw47y2HHCNm","A2v5","EMX0r04","rePOBMS","CgLUz09Uy2u","vMDYt2i","tgnNzuq","Aw9UvgLTzw8","BMvJDa","Dw9QAKG","x2rItMfTzq","r3vfsgS","y0jnuuG","vKHnA3a","rNjVBNrPzxi","yxv0B21HDgK","B3nhyxu","sfL4wM0","BezSDxnO","rMDNs0G","vgPLqxK","EMTiuKW","ywXSB2nvBNm","y3vYC29Yx2y","mNW0Fdn8mhW","x3DZsw5ZDge","yw5ZzM9YBvq","id4G","y3vYC29Yx24","BMv4DcGPigm","x29UrxjYB3i","Bg9Nsurhzw4","y0XrCwi","mNWX","y2HLy2TdDxi","B0HbtfC","qKfJqvm","uvfeuva","BMrLEa","BwvKAwf0zwW","ywnRtxnNswq","CM9uzhK","DgvZDa","B3jhEuG","AMjHEha","BNrLCG","ywrKt25L","zw50tgLZDgu","AfrKyNm","z1rTzuq","ignVzgu6ia","z0PNwM4","EvDLBNq","C0nVDw50zxi","Ec1TC2CTCw8","A1PoBuK","CMvXDwLYzwq","vu92rg0","y29UBMvJDeu","ihjLy29UBMu","C0DfCLa","q01kBLO","yMfSu2nVCgu","v094CNe","wgrOrMS","uevuBuq","mdaWma","B0jeBeW","t05MyNO","AwXLx25HBwu","CMfNzvn5BMm","zffrCLq","zMzMzG","Cxrwzwy","x21PBMLoyxy","DuXIEhm","x3nLCuLK","BMrWB2LUDfq","A2LMrfC","vfz0zLm","vNjSvwW","CMvHC29U","zxH0zw5ZAw8","v0n0s2C","vxnOs3K","ExzIr0G","ANnSv0y","thzcuMm","zhPJC2e","ExDlCeO","CM9YrxzLBNq","vu54v0W","qxDVvhe","sM9JzfG","uLzAq1C","Ehz1wuK","vffXCg0","zgvS","DfrQrMG","s21prKq","ywnOzwqSihC","zMzLCG","zwn0","sLnptLa","yxvmAuK","DenAseG","seP4vxG","C1nKB1q","s01SExa","DNvyB0q","CwPzA1O","x2zVCM1HDeu","y1jur1q","BMnOBeO","x29WDgLVBNm","Cuvfzhe","y3b3ruW","A0XUv3a","EwDKz0W","zvbczKS","DNvxv3O","BgLTAxq","B2zM","sLDsweK","CMvHzhLtDge","C3rYAw5N","r3zLvM4","Bvj6Dfy","DhbizwfKzxi","A0viD3m","x2n1CNnVCK4","r1vfs1K","BMCGDxjSoIa","CLbQtgW","C0XPC3rLBMu","y2uGBM90igK","wLrUuwi","D3zAyNO","wKndvNa","rwngwgi","ywXSzwqGBxu","Dg9hzw5LCMe","AM9PBG","ANvhAvG","DLLiAfC","CYbWyxjHBxm","ufHZyKi","B25TzxnZywC","DMDlA1q","yvfnELy","C2HPzNq","B3jpBMXPBMu","B3v0sw50zxi","ywrfq0O","tMjNv3q","yxrLq291BNq","BgLUzq","qMXmAMG","zxHWB3j0CW","vwXnz2C","u1PjuKi","z1rPBwvVDxq","x29UugfNzu4","zgvJB2rLzey","zLHLwNi","x29UtwvZC2e","vhDYuwS","thvAywS","yw5Nzq","CNHlExC","rKLmrv9ot1q","AeXLCeW","zxj2AwnL","tg9NsurozxC","v2vPEgLUsLm","yxjYyxLIDwy","yw5Hz2vY","r3byB1a","zw5JB2rPBMC","rNPZt2q","Dw5KzwzPBMu","DuTtqxa","tvHNqKy","D1rUALu","tMD0zfa","igzHAwWSig0","wNjKA2i","s2HQrK8","ywX3yxLZ","EfnbA28","aaaaaaaaaaa","svjHC04","x3vYBa","u2vXsuq","su5tvefova","x2HHBMrSzva","y2HnyxHuCMK","wLPYEMq","B0r0Efi","vwjureu","BwvZC2fNzv8","yxGGCMv0CMK","v2vQwwi","ELPwrxy","swfAyNO","B2zMC2v0","Dg9cExrLCW","vfvYwKO","yxbWzw5Kq2G","BgvxCeK","s1Luwwe","vMHUs28","zNDZxZeUmc4","C2vUza","wwrhsKG","vNHisKe","Cg1dEMC","ihrPBwvZ","A2TyzLC","C3vvBLq","zhz1AMS","uwLyExq","Aw5N","CMfTzq","yxLOq1q","mte4odCXmZL6ELzvreK","y3ruAw1LB3u","ru1sy0i","AhP2ywm","BMCGzMfPBgu","shrlsKi","Ec1TC2CTy3u","CxDYthK","ysbTDxn0igi","wNHrBha","C1Dmrhm","y2HnyxHdB3u","txboC0y","ywXty29Wzq","C3nHz2vfDMu","CMPPrLy","rNrvDw4","ihzHBgLKihm","AgjKseO","BuHuzui","zxjFDhrS","BwfW","zw5fDMvUDa","A0jmwvC","BMDLza","zxq9DxrMltG","A3fMv2O","y09Wzw4","s2Pzvg4","uvfyy2C","t2rythy","v05Muei","DKjWDgm","Dhj1y3rVCIa","v1zZz2G","mZa3odCZngT3EMDwzW","DMPbwKi","uwHHCxq","BenpqMm","B2PtDwq","zxP1vvG","zwrPyxrLBhK","y3vYC29YlNm","x29Ut3bLBG","AuLZvM4","nhWWFdv8m3W","EvjLy29UBMu","yvfsqum","pxv0zI04","Cg93","Ahr0Chm6","D0vXveC","s3fyEMC","sNPzqvK","uuHkq1O","rwfHzhu","mJuWsxP0y0rl","tg5hDLi","DvndDu4","ve9HBui","CMvZB2X2zq","AKr3z0W","BgLUzw5V","zcbLCNjVCI4","u3Pyzwy","BMPVA08","y29UBMvJDa","tKfusvzfx0u","B3nVBNG","BMCGB3iGyw4","y2f0y2G","rwjAvMS","uLnbwve","Bg9N","z2LWzKy","yMLUyxj5","r1DrqLK","yM9KEq","BhrPCgXLihq","s3LJwgi","z2u6ia","C3vIC3rYAw4","BNrbBMrvCgq","B255EM0","vKjHCNK","Dg9oDw1Izxi","yxnZAwDU","BwLZzq","B25SAw5L","EK1Lqwq","CgfNzxnOB3C","DMfSDwu","Bw5qqNi","B3bLCNr5tMe","yNLL","rxDhwKK","vxv1t3K","y1nWte0","wMjNExa","v3LbrgO","zgLZywjSzue","vNr4r2m","AMnzqLq","zwvKzwq","x3jLBw92zvC","z2vjBMzVu3K","uuDbEeO","ihrPBwvVDxq","yMLUza","zMLSzw5HBwu","zxjFCw9Z","CgPRC2u","yxrHlcbKyxq","tw9KDwXL","DLvKDva","y3jLyxrLrwW","zMD1zuy","zxjFCw9Zx2e","y3jLyxrLt3a","AgfZt3DUuhi","BKLJBwq","BvjPCNO","BwfUDwfSihi","C2vYDMvYvgK","z2vtEw5J","te5JrM8","B2nRzxq","y2nzrwi","y3jLyxrLtwu","ALPHs1u","uezfr1a","D2DgqMe","DgLTzw91DcW","D0fXDuC","BwLUzW","ENHMCee","uxnVsKi","zxztvfa","t0X0Chu","y3f5A2G","B2nRzxrtDwm","DMfSDwvZ","BMnLExa","zNjVBu51Bwi","EfnkB2q","DKzyrg8","ufHnCNm","rLjptLrjrvi","Aw5JBhvKzxm","t0DesxC","u2vYDMLJzvC","uLPyuMS","DKzxzfy","zxjYtM8","AMTtz1C","AMnJBxe","zgvSzxrL","CNzHBfzHBhu","BgzoCgy","BufrAvi","vvj0ze8","vxPhELa","B3jLtMfTzxm","rwTywwW","Cgu6ia","suLdy3a","ywrKrxzLBNq","DKvxtxK","uM1NBhO","sgP1ufy","yNL0zuXLBMC","DKX2A0W","rgzPAfO","CwnXAgO","tuzSyMS","x194x21Zz18","Dw1Rr20","DhjHBNnHy3q","vMLHCMC","C0Xf","CMvUDevUzha","DgX1q3q","BLHpzw4","C3H2sMS","BLrpB20","CMvQzwn0","q2j0t0m","BMzHu3i","rxzIz2W","AePtzge","DKHJsKG","AwDHDg9Yt24","rKDzsKG","CfPiCgW","yNvMzMvYzwq","r05MrvC","ALfdwgu","uNbcAe8","uwvMsfm","zxrxB3jRq2G","EeXkCK4","Ce95z2S","v3jmsfm","vgriz3q","DwPyDuS","y3vYCMvUDeu","EKjtqu0","nJmXnKvREur1ua","CvD4q0O","igfYCMf5yNu","B25pCgvU","Bwj5C1K","C0TAsey","v3HIAwi","y21srNG","x2DLDeLUDgu","mNWZFdb8nhW","EfvZzuvUDG","C0jf","qMzMEey","yMjJy2O","DcbSAw1PDa","ugnqww4","q29LEKy","AenSB3nLrxy","DevovNy","DfLAAhC","AKjhv1a","zv9ZDwnJzxm","zMT4z2q","y29Kzq","sxjnyxG","qw1yBwS","wKHpChe","tgnAsue","yxnJCMLWDa","mhWXFdn8mNW","C2DPza","BeHHBMrSzxi","Du1bEge","zfPOBKO","C3bSAwnL","x2rLC3rYB3K","x2n1CNnVCK0","r0Lcz04","yMXVy2TLza","vevZr2W","B2fK","nJi3vMTbt3LT","CMvHzfvjBNq","CeT3z2u","AgPPALu","EvPmzfa","BgvJv24","EMDwzNq","BgvUz3rO","q09otKvdveK","Aw5PDcbrB1m","ue9WCg0","Dw5ZAwDUzwq","x2LUAxrhBg8","BvvUwe4","zxDyDNu","x3DZ","x2fKzfDZtgK","yuDfveK","rejmEKu","yvDPr1q","uMvHzcbWyxm","uML4yNu","B2z3CeS","BKXPBMu","FdL8n3WWFdi","zw5HyMXLvhi","wMnnugC","wu1izxa","BLnfrfe","sMP5EeS","ywDLsgLKzq","B0fjCKC","DNj1uLu","v2LisgK","refqBwm","CMvTB3zLq2G","z2vrDwv1zuW","Dg9tDhjPBMC","AefJA01LC3m","vKT2q2i","zNjHBwvuExa","ELrJD0y","C3vJy2vZCW","Cgjjv24","z2v0","z1LbD0u","y29UBMvJDfm","C2XPy2u","rgDNt3K","B3bLBKrc","CNLpCK4","x2LZtwLUAvq","EgnjvvC","DMPMA1m","vgL2ENG","BMvY","BMDuAw1LCG","sujxDuC","B1HjvMq","tMTUDhK","y2vZC0HHBMq","CNnVCL92ywW","DMvUDa","EgHUBvy","mteXnZa5m2HvzKzPBG","B2jQzwn0u3q","tLnNvxK","y3vYC29Y","BvDpseu","sg9dv3a","y05Wr00","DfzNwMO","x3bPBMDmB3m","uxL5sM4","yNnxuKS","sMntB2e","CMv0CNLdB3u","tNnRC24","DeP0u2G","mxWWFdr8n3W","uhfNz0W","u3fwuKO","B1PPq1q","DhHSAxC","Ae1LC3nHz2u","ChjVDg9JB2W","ChL0DMW","u0jxv0q","x3bYzwzPEa","nxWWFdj8mxW","zw5HyMXLuw8","zwHjzfG","zM9YrwfJAa","BK5dDeW","zw5KCg9PBNq","v2LUzg93","wefhAvu","z2v0q3vYC28","uezVreG","D3bgrwe","vKriue0","Cg53Duq","s1v1Chq","DxjS","Cg9PBNrdB24","wKjZsvi","wKrYEue","wvzMrve","CvvJwKy","uxvLDwu","zNjVBNrPzxi","BfHxu08","vMn5D3C","A2v5CW","qKfwvfa","ywnRDxbfBMq","vwnqEhK","yw51Ce1LC3m","ywrKq291BNq","yxv0BW","yw1L","B25tDg9Wsw0","mNWXFdr8m3W","zw5HyMXLqxu","y2XLyxjtDg8","y2XVC2uSihC","zNvpreW","rgzbB00","CKPKsuu","CMvKDwnL","s1vxuey","t3bLBKv2zw4","zxjFAxnFywm","sg1PDwi","BLHAs0y","zvLut1G","qMrVr2e","vNv0AgO","rxzLBNq","D2vI","z2v0u3rVCMe","DLjNwvm","wKT1CfO","svf3sKC","mti4mJa4yLfht1zv","tvfcs2S","yNj6BeG","ywHbAgO","wvj2zgO","A3Pttxy","AvHoC2S","BwTiEwi","igzPzwXKoIa","Cg9ZD3i","D2zrufe","AfHbzNm","q0Xpu0ve","B2vJs2e","tgHQC0G","svz2q0C","wKXyEvO","DK1zC1i","B25oEeW","yw1LoIa","zMXVB3i","uuvnswC","CMXcA3y","C3vIyxjYyxK","B25nzxnZywC","CIb0DhDjra","B25fCNjVCG","zNnrD2e","wfvSCw8","ChvZAa","CNzovhq","Bwv0Ag9K","q25Ouvy","x3bYB3rVy28","EgnMsui","A3rPuNy","Dg15yLm","BvHVAKi","y2HLy2Tszwe","rxP2qwO","Bwu6ia","tefQB2K","BgvY","AwXSihvZzsa","y3jLyxrLq2W","BLHYzLG","B3bLBIa","D2fZq2XLyw4","zufJAW","AwHzwvK","BgPOtgK","vKzwrLi","Bff1rve","rwrrs1m","rMHivLm","y0vRze8","Aw1tAfe","zKDPvg0","x29Uq2XVC2u","zNvUy3rPB24","CgvYC2LZDgu","icSG","zgTPBuu","Ewr3Ehy","q0fJCLq","DNfvuxG","D3m6lY8","ChjVDg90Exa","y216uxG","AwXK","t2DYt0q","zg9Uzq","rNjRAMm","B3nLrxzLBNq","zuDVAxa","se91s0m","zw50","Dg9mB3DLCKm","BMfTzq","B25mAw5L","B3vUDa","x2vUzhbVAw4","uwXrwfu","B09Xz0e","AgLNAa","tuvtu0fhrv8","v3vXuwG","q3zXBKW","suDAs3a","EgjJBvO","C3rLBMvYCW","zxjYB3i","tvzrrxy","ufztAuy","Dw5RBM93BIa","swjZC2m","lcbxzwjtB2m","A1H2zK0","x2nYzwf0zvm","A05eAw8","BhHgrgu","x2LUDgvYDMe","tMfTzq","AxHuyxO","u0rcBuW","EKDozNC","Cezfvfq","z2v0t3DUuhi"];return wa=function(){return t},wa()}function aI(t){let e=L,n={wpFEa:function(i,o){return i(o)},qzwdK:function(i,o){return i===o},ohWZw:function(i,o){return i in o},Iwqmv:e(1494)+e(1343)};return n[e(323)](t,IDBDatabase.prototype["transact"+e(869)])&&!n[e(590)](n.Iwqmv,IDBTransaction[e(1640)+"e"])?function(i,...o){let a=e,d=t[a(358)](ms(this),i,...o);return xl.set(d,i[a(1746)]?i.sort():[i]),n[a(1528)](Jt,d)}:rI()[e(1329)](t)?function(...i){let o=e;return t[o(888)](n.wpFEa(ms,this),i),n[o(1528)](Jt,pl[o(1473)](this))}:function(...i){return Jt(t[e(888)](ms(this),i))}}function cI(t){let e=L,n={MyWXv:e(1632),rPjLl:function(i,o){return i(o)},vlIej:function(i,o){return i(o)},AFUJE:function(i){return i()}};return typeof t===n[e(719)]?n[e(1089)](aI,t):(t instanceof IDBTransaction&&n[e(472)](sI,t),zp(t,n[e(1687)](nI))?new Proxy(t,ba):t)}function Jt(t){let e=L,n={rfdJt:function(o,a){return o(a)},ARzST:function(o,a){return o!==a}};if(t instanceof IDBRequest)return n[e(652)](iI,t);if(ga[e(679)](t))return ga[e(1473)](t);let i=n[e(652)](cI,t);return n[e(583)](i,t)&&(ga[e(882)](t,i),ya[e(882)](i,t)),i}var zp,Dp,Lp,pl,_a,xl,ga,ya,ba,ms,Mp=Bp({"node_modules/idb/build/wrap-idb-value.js"(){let t=L,e={IVvCG:t(1471),UIsBZ:function(n,i){return n instanceof i},sKZHF:"done",IBWuG:function(n,i){return n===i},uJUQt:function(n,i){return n===i},aYspL:t(924),FPrZy:function(n,i){return n!==i},Bewup:t(1011),UGGvY:function(n,i){return n(i)},LUbjJ:function(n,i){return n===i},gJgZn:function(n,i){return n===i},vAAin:function(n,i){return n in i}};zp=(n,i)=>i.some(o=>n instanceof o),pl=new WeakMap,_a=new WeakMap,xl=new WeakMap,ga=new WeakMap,ya=new WeakMap,ba={get(n,i,o){let a=t,d={cRTGT:e[a(1588)]};if(e[a(1811)](n,IDBTransaction)){if(i===e.sKZHF)return _a[a(1473)](n);if(e[a(1486)](i,a(1494)+a(1343)))return n[a(1494)+a(1343)]||xl[a(1473)](n);if(e[a(435)](i,e.aYspL)){if(e.FPrZy(a(415),e.Bewup))return o[a(1494)+a(1343)][1]?void 0:o["objectSt"+a(540)](o["objectSt"+a(1343)][0]);_0x477097.removeEventListener(wWKuay[a(1068)],_0xb482d0),_0x3d8aa7[a(872)+a(1003)+a(1484)](a(1664),_0x18784)}}return e[a(1721)](Jt,n[i])},set(n,i,o){return n[i]=o,!0},has(n,i){let o=t;return e[o(1811)](n,IDBTransaction)&&(e[o(763)](i,e[o(1393)])||e[o(1007)](i,o(924)))?!0:e[o(385)](i,n)}},ms=n=>ya[t(1473)](n)}}),Up={};tI(Up,{deleteDB:()=>lI,openDB:()=>dI,unwrap:()=>ms,wrap:()=>Jt});function dI(t,e,{blocked:n,upgrade:i,blocking:o,terminated:a}={}){let d=L,u={qlpvc:function(p,m,y,_,E){return p(m,y,_,E)},QfrxV:function(p,m){return p(m)},cdpId:d(848),oQCgv:d(622)+d(952),yulrx:d(1426)},f=indexedDB[d(557)](t,e),x=u[d(689)](Jt,f);return i&&f["addEvent"+d(459)](d(1799)+d(1284),p=>{let m=d;u.qlpvc(i,u[m(689)](Jt,f[m(1716)]),p[m(483)+"on"],p[m(648)+"on"],Jt(f[m(1358)+m(869)]))}),n&&f[d(1347)+"Listener"](u.yulrx,()=>n()),x[d(499)](p=>{let m=d;a&&p[m(1347)+m(459)](u[m(738)],()=>a()),o&&p["addEvent"+m(459)](u[m(663)],()=>o())})[d(1251)](()=>{}),x}function lI(t,{blocked:e}={}){let n=L,i={VrlUl:n(1426),VKOYF:function(a,d){return a(d)}},o=indexedDB[n(809)+n(405)](t);return e&&o[n(1347)+"Listener"](i[n(1036)],()=>e()),i[n(940)](Jt,o)[n(499)](()=>{})}function Np(t,e){let n=L,i={bsgPV:"readwrite",kpJbk:n(315),jQCXe:function(f,x){return f instanceof x},LnGvR:function(f,x){return f in x},XmlZI:function(f,x){return f===x},ZsCwH:"string",ZCmvC:function(f,x){return f!==x}};if(!(i[n(1377)](t,IDBDatabase)&&!i[n(1238)](e,t)&&i[n(569)](typeof e,i[n(327)])))return;if(ma[n(1473)](e))return ma[n(1473)](e);let o=e.replace(/FromIndex$/,""),a=i.ZCmvC(e,o),d=Gp[n(1329)](o);if(!(o in(a?IDBIndex:IDBObjectStore)[n(1640)+"e"])||!(d||Hp[n(1329)](o)))return;let u=async function(f,...x){let p=n,m=this["transact"+p(869)](f,d?i.bsgPV:i[p(727)]),y=m[p(924)];return a&&(y=y[p(724)](x.shift())),(await Promise.all([y[o](...x),d&&m[p(1644)]]))[0]};return ma.set(e,u),u}var Hp,Gp,ma,uI=Bp({"node_modules/idb/build/index.js"(){let t=L,e={FggKH:t(1770),WUlcH:"add",pytvl:t(517),ojSud:function(o){return o()},sdQeA:t(1473),IQwJG:t(488),nXZKF:t(408)+"ys",SBWWD:function(o){return o()},naREi:function(o,a){return o(a)}},n=(t(739)+"5|4")[t(1738)]("|"),i=0;for(;;){switch(n[i++]){case"0":Gp=[e[t(975)],e[t(673)],t(1337),e[t(1515)]];continue;case"1":e[t(1220)](Mp);continue;case"2":Hp=[e[t(878)],t(475),e[t(1572)],e[t(1563)],"count"];continue;case"3":e[t(1516)](Mp);continue;case"4":e[t(360)](oI,o=>({...o,get:(a,d,u)=>Np(a,d)||o.get(a,d,u),has:(a,d)=>!!Np(a,d)||o.has(a,d)}));continue;case"5":ma=new Map;continue}break}}}),fI={idb:function(t){let e=L,n={IMeFo:function(i,o,a,d){return i(o,a,d)},yZLdP:function(i,o){return i===o},HtdXA:"CNLZa"};t[e(1114)]=Promise[e(1241)]().then(()=>(uI(),Up)).then(function(i){let o=e;if(n[o(1433)](n.HtdXA,n[o(524)]))return i;throw _0xe51918=_0x59b5d1[o(1436)],n[o(504)](_0x504f49,_0x264325,10,_0x498ac4[o(1436)])})}},Fp={};function Vt(t){let e=L,n={qwrLy:"1|4|2|3|0",TEfPA:function(u,f){return u!==f}},i=n[e(1188)][e(1738)]("|"),o=0;for(;;){switch(i[o++]){case"0":return d[e(1114)];case"1":var a=Fp[t];continue;case"2":var d=Fp[t]={exports:{}};continue;case"3":fI[t](d,d.exports,Vt);continue;case"4":if(n[e(831)](void 0,a))return a[e(1114)];continue}break}}Vt.d=(t,e)=>{let n=F;for(var i in e)Vt.o(e,i)&&!Vt.o(t,i)&&Object[n(612)+n(478)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=L;Vt.o=(e,n)=>Object[t(1640)+"e"][t(1300)+t(478)][t(358)](e,n)})(),(()=>{let t=L,e={RZXRk:function(n,i){return n!=i},dtSco:t(1136)+"d",muMrM:t(1294),xNRCA:"__esModule"};Vt.r=n=>{let i=t;e[i(1332)](e[i(574)],typeof Symbol)&&Symbol[i(1466)+i(377)]&&Object["definePr"+i(478)](n,Symbol["toString"+i(377)],{value:e[i(1802)]}),Object["definePr"+i(478)](n,e[i(1730)],{value:!0})}})();var De={};(()=>{let t=L,e={sXccp:function(c,r){return c+r},Jwbpa:function(c,r){return c*r},nPiVK:function(c,r){return c+r},cvitk:function(c,r){return c(r)},wgFBa:function(c,r,s){return c(r,s)},pLVYO:function(c,r){return c!==r},xvuYI:"Lbxuo",TKsxj:function(c,r,s){return c(r,s)},MIbur:function(c,r){return c(r)},hpuyG:function(c,r){return c+r},SSAQf:t(1022),BlLjh:t(1028),pOUCk:function(c,r){return c===r},ZxQlp:t(597),ZDryA:function(c,r){return c(r)},QbfNQ:t(780)+t(780)+t(780)+t(780),pbRZm:t(1397)+"1|5",uOxpR:function(c,r){return c>>r},nlMhg:function(c,r){return c|r},Dbcqh:function(c,r){return c>>r},TyvJr:function(c,r){return c&r},mNXnW:function(c,r){return c<r},tmybS:function(c,r){return c<<r},HJxUx:function(c,r){return c>r},pQSIi:function(c,r){return c<r},vxoqH:function(c,r){return c-r},qvAXY:function(c,r){return c!==r},xSJod:function(c,r){return c-r},lQZaS:function(c,r){return c<r},VvCuQ:function(c,r){return c!==r},lecWn:t(1385),ZOEWK:function(c,r){return c!==r},jslWF:"ENdLd",CikEX:"AAEMf",PDqlU:function(c,r){return c-r},KhjFO:t(410),aQMzV:function(c,r,s){return c(r,s)},vruRU:function(c,r,s){return c(r,s)},iKEDQ:function(c,r){return c(r)},VxIiK:function(c,r){return c>>>r},mUnXN:function(c,r,s){return c(r,s)},jqHjS:t(802)+t(1012)+t(1581)+"value",BabvQ:function(c){return c()},bEghQ:function(c,r){return c(r)},IaZbz:function(c,r,s){return c(r,s)},lxFDe:function(c,r,s){return c(r,s)},vUduP:"aOzEK",mkHyb:function(c,r,s){return c(r,s)},gESzK:function(c,r){return c(r)},zTcwF:function(c,r){return c!==r},CjknE:function(c,r){return c===r},sGErP:"QUguo",DAPmc:function(c,r,s){return c(r,s)},TUrZJ:function(c,r){return c(r)},WWPif:function(c,r,s){return c(r,s)},wwTmx:function(c,r,s){return c(r,s)},FGNLJ:t(1555),nchlJ:function(c,r,s){return c(r,s)},jDwgL:function(c,r){return c!==r},vMYsR:function(c,r){return c===r},uSCuN:t(1800),BeSdp:function(c,r){return c!==r},kVvbg:function(c,r,s){return c(r,s)},KWXLV:function(c,r,s){return c(r,s)},TkOYf:function(c,r){return c!==r},kEHws:function(c,r,s){return c(r,s)},VMJpc:function(c,r,s){return c(r,s)},MnHWG:function(c,r,s){return c(r,s)},ljPmf:function(c,r){return c+r},dzcsa:function(c,r){return c+r},nehfg:function(c,r){return c>>>r},eGoip:function(c,r){return c+r},oXIVd:function(c,r){return c===r},dsHaK:t(1728),qUcZF:function(c,r){return c(r)},rjiFV:function(c,r){return c>>>r},FkEnI:function(c,r,s){return c(r,s)},EBBNL:function(c,r){return c(r)},wTnjU:function(c,r,s){return c(r,s)},aGETI:function(c,r,s){return c(r,s)},VKvCb:function(c,r,s){return c(r,s)},mHTeB:function(c,r,s){return c(r,s)},nJjHl:function(c,r){return c&r},KozyW:t(802)+t(1012)+t(1581)+"SeqID",EfYAz:function(c,r){return c===r},RANZJ:t(802)+t(1012)+t(1581)+t(514),wfipU:function(c,r){return c===r},KtCZa:"Missing required field: "+t(1604),gGEEJ:function(c){return c()},FLEHH:t(1420),WfqOq:"SJeRY",CKgIW:t(565),WwZcC:t(1271),njokO:"offline",vRgYS:function(c,r){return c===r},viUPE:t(766),dmTea:function(c,r){return c(r)},PLyzc:function(c,r,s){return c(r,s)},KUWPF:function(c,r){return c(r)},TdHgt:function(c,r,s){return c(r,s)},sgQKM:t(355)+t(1778)+t(1345),ODJNb:function(c,r){return c>>r},zgVft:function(c,r){return c>=r},vugqm:function(c,r){return c+r},WVMdC:t(516)+"t limit",vusrA:function(c,r){return c*r},nTOom:t(1449)+t(1402),KYzPB:function(c,r){return c(r)},uLbxs:function(c,r){return c<<r},ydwxv:function(c,r){return c===r},xLJrN:"uRZhm",zBSAM:function(c,r,s){return c(r,s)},orabk:function(c,r,s){return c(r,s)},ccYEb:t(1785),TwrQk:t(769),NJOcE:function(c,r){return c<<r},WSohe:function(c,r){return c==r},Uthmh:function(c,r){return c&r},uAGDv:function(c,r){return c>=r},roTdy:function(c,r){return c+r},PcFAR:function(c,r){return c+r},cpwEL:function(c,r){return c+r},YNvXC:function(c,r){return c&r},vjAZB:function(c,r){return c<<r},Zbgyp:function(c,r){return c&r},fGiTm:function(c,r){return c<=r},NOEsD:function(c,r){return c(r)},IRasN:function(c,r){return c>=r},nZkrO:function(c,r){return c+r},vwFCb:function(c,r){return c+r},KMlyp:function(c,r){return c&r},HYxGf:function(c,r){return c|r},vgKkT:function(c,r){return c|r},Vuthj:function(c,r){return c<<r},xcfIB:function(c,r){return c<<r},cDEEY:function(c,r){return c|r},TQqpm:function(c,r){return c|r},oecKa:function(c,r){return c<<r},ZoaHI:function(c,r){return c&r},SPvJH:function(c,r){return c&r},Jiczh:function(c,r){return c<<r},BdEwr:function(c,r){return c&r},hSNiQ:function(c,r){return c<r},lQuEQ:function(c,r){return c+r},BIJtx:function(c,r){return c!==r},TOamB:function(c,r){return c|r},MxXTW:function(c,r){return c&r},ZaAcS:function(c,r){return c&r},mmFsE:function(c,r){return c(r)},fsQwa:"PtzjI",rCQXw:function(c,r){return c<=r},CgSaU:function(c,r){return c<r},mHCuE:function(c,r){return c+r},AaIxd:function(c,r){return c<r},xTWKg:function(c,r){return c+r},SSeiO:function(c,r){return c<<r},ObTmm:function(c,r){return c<r},UbTDE:function(c,r){return c|r},vcoob:function(c,r){return c<r},tVgZj:function(c,r){return c>>r},sWLDs:function(c,r){return c|r},TmKYp:function(c,r){return c&r},GylHx:function(c,r,s){return c(r,s)},NPipo:function(c,r,s){return c(r,s)},fIjzo:t(1408),rfBtv:function(c,r){return c(r)},wAquG:function(c,r){return c<r},KmOFD:function(c,r){return c<<r},WCtKg:t(848),WejYb:t(1407),Rmglz:t(665),qTcVU:function(c,r){return c(r)},MpNsF:function(c,r){return c<<r},sZGOo:function(c,r){return c&r},nHFwJ:t(1027),SzXef:function(c,r){return c(r)},wdqYo:function(c,r){return c<<r},PXMrs:function(c,r){return c(r)},IhPRw:function(c,r){return c&r},DwoYk:function(c,r){return c(r)},SxbOm:function(c,r){return c&r},tTIbs:function(c,r){return c(r)},jLeue:function(c,r){return c<<r},rBzoM:function(c,r){return c(r)},dITqh:"send_ack",JocdX:"ZRLFm",rJdIE:"BjztZ",vjfkS:function(c,r){return c>>>r},gyrWM:function(c,r){return c>>>r},MHCCx:function(c,r){return c===r},tluCt:function(c,r){return c&r},ZCCVp:function(c,r){return c>>>r},yWent:function(c,r){return c!==r},oBdzi:function(c,r){return c+r},DggOy:function(c,r){return c!==r},jNToK:function(c,r){return c|r},hkDcg:function(c,r){return c>>>r},VzivR:function(c,r){return c>>>r},XaLBw:function(c,r){return c>>>r},Hoyvl:function(c,r){return c+r},wSrAk:function(c,r){return c>>>r},gzCdv:function(c,r){return c&r},josEo:function(c,r){return c+r},ryDIY:function(c,r){return c|r},xoPcY:function(c,r){return c>>>r},KqXzg:function(c,r){return c|r},MQBKk:function(c,r){return c>>>r},IlckL:function(c,r){return c>>>r},aWiGT:function(c,r){return c!==r},ixTaz:t(818),QlQXU:"ping_once_timeout",ljhLi:function(c,r,s){return c(r,s)},vFXDo:"DkIjC",Frkjc:function(c,r){return c(r)},auLiI:function(c,r){return c<<r},rtCVT:t(1235),HKHyH:t(1207),zoehL:t(1218),tJtSh:function(c,r){return c|r},oaNpn:function(c,r){return c|r},TjeAy:function(c,r){return c|r},kYxnx:function(c,r){return c<<r},nNCtL:function(c,r){return c<<r},fkxgd:function(c,r){return c|r},nfaSr:function(c,r){return c<<r},vEWMy:function(c,r){return c|r},imShQ:function(c,r){return c|r},OveTR:function(c,r){return c<<r},mwKPa:function(c,r){return c<<r},lXWSO:function(c,r){return c===r},RuGUv:function(c,r){return c|r},qDyzv:function(c,r){return c<<r},ayhCT:function(c,r){return c<<r},aorNd:function(c,r){return c|r},lfNpf:function(c,r){return c<<r},UleGT:function(c,r){return c<<r},jZaKU:function(c,r){return c>>>r},HdSmi:function(c,r){return c|r},bkeoM:function(c,r){return c<r},lMvvn:function(c,r){return c===r},AFfUt:t(325),QefHS:t(731),vBptc:function(c,r){return c>=r},njGmi:function(c,r){return c>=r},UshKy:function(c,r){return c/r},eglse:function(c,r){return c<r},JjyxK:function(c,r){return c+r},WuqQh:function(c,r){return c<r},PhktC:"zNEHS",sUeBq:t(726),gZguN:function(c,r){return c+r},cEkdO:function(c,r){return c>>>r},pjkse:function(c,r){return c*r},wjhnV:function(c,r){return c-r},Aejmv:"WOgDq",wEqTG:"ejKjP",seZxj:function(c,r){return c>>>r},yeZFh:function(c,r){return c>>>r},MtXXm:function(c,r){return c>>>r},JzYAY:function(c,r){return c>>>r},QoFug:function(c,r){return c+r},TFcch:function(c,r){return c>>>r},AZrMY:function(c,r){return c<<r},PHyMj:function(c,r){return c<<r},zKamo:function(c,r){return c!==r},DBLzE:function(c,r){return c>>>r},XUlqo:function(c,r){return c===r},CIIWu:t(1741),OdXLv:t(1664),RThJZ:t(868),hAnVV:function(c,r){return c===r},ANWrX:"GaQih",Shiud:function(c,r){return c>>>r},IVKvp:function(c,r){return c>>>r},SLHOu:function(c,r){return c&r},kzSMv:function(c,r){return c>>>r},oBDlL:function(c,r){return c&r},pTNbX:function(c,r){return c>>>r},WZpJc:function(c,r){return c>>>r},IICcp:function(c,r){return c&r},hXAfs:function(c,r){return c>>>r},HGeHV:function(c,r){return c&r},tCZHH:t(874)+"OR",USObm:t(1248)+t(369),kciXA:t(824)+t(843)+"R",jHiKk:t(1437)+t(319),JWRXI:function(c,r){return c|r},cmRFx:function(c,r){return c|r},CAcrT:function(c,r){return c<<r},zgzFl:function(c,r){return c<<r},ZAKhJ:function(c,r){return c>>>r},AnXlx:function(c,r){return c<<r},pOygk:function(c,r){return c===r},vSiud:t(806),YRvdj:t(1518)+t(1813),GpXoP:function(c,r,s,l,h){return c(r,s,l,h)},BffxF:function(c,r){return c(r)},CRetf:t(1401),kqYPB:function(c,r){return c(r)},MPegm:"QUTjy",DpXCx:function(c,r,s){return c(r,s)},vCejw:function(c,r){return c!==r},TrXqu:t(1797),EoxSB:"aKwqs",NClZO:function(c,r){return c-r},nIcmd:t(1488),yJqWC:function(c,r){return c===r},eeLvH:t(759)+t(1244),xBSaO:function(c,r){return c+r},ahAhj:function(c,r){return c===r},EyrTC:function(c,r){return c!==r},XNutD:t(600),PqggL:function(c,r,s){return c(r,s)},DUylo:function(c,r,s){return c(r,s)},vEuPI:t(547),nosiK:t(658),ewXvu:t(853),XFlRp:function(c,r,s){return c(r,s)},hJSda:function(c,r,s){return c(r,s)},LxVqW:function(c,r,s){return c(r,s)},ntABt:function(c,r){return c instanceof r},GFEnT:function(c,r){return c<r},PFoDH:t(1562),aNENA:function(c,r){return c!==r},QbIcW:"LraqG",Bmslb:"HhKkB",pjxxe:t(893),EMiYF:function(c,r){return c&r},vuWWz:function(c,r){return c+r},NlvMP:t(1525),djjsJ:function(c,r){return c||r},QCwGW:t(1136)+"d",ULVZu:function(c,r){return c||r},CbtOC:function(c,r){return c!=r},bACNH:t(985)+t(1096)+t(1259)+t(937)+t(522),iIsVn:function(c,r){return c===r},eqIdY:function(c,r){return c(r)},HjuPV:function(c,r){return c(r)},WUfmg:function(c,r){return c&r},pbIWn:function(c,r){return c===r},EbZVk:function(c,r){return c+r},PXsbB:t(991),Jicqi:function(c,r){return c<r},VSGpJ:function(c,r){return c>=r},kXvfM:function(c,r){return c<r},QOzpz:function(c,r){return c<<r},BDiFS:function(c,r){return c&r},KvbFQ:function(c,r){return c-r},myDvt:function(c,r){return c|r},MioNY:function(c,r){return c<<r},nXrfX:function(c,r){return c+r},PFEGP:function(c,r){return c>>r},AwoTq:t(555),ehIdX:function(c,r){return c!==r},OoBZl:"MoMWk",OLzVx:function(c,r){return c<r},gYAwE:function(c,r){return c>>r},XryeK:function(c,r){return c===r},ehWfp:function(c,r){return c&r},vKjnd:function(c,r){return c+r},DBaSw:function(c,r){return c&r},wHhOD:function(c,r){return c|r},iLPZn:function(c,r){return c&r},KycXb:function(c,r){return c+r},Ybiqy:function(c,r){return c&r},WNfPB:function(c,r){return c>>r},xhnmV:function(c,r){return c>>r},zhGmW:function(c,r,s,l){return c(r,s,l)},rxwLY:function(c,r){return c instanceof r},QiXyt:t(1081),TVtfS:function(c,r){return c instanceof r},vjLuz:"ppe",oUhQm:function(c,r){return c(r)},GveVn:function(c,r){return c(r)},ZZrzd:function(c,r){return c===r},njzuw:t(1176),aQRAC:t(1667)+t(1037),XSDTs:"script",CeakO:t(621)+t(1416),LzhkF:"idb",omiGB:"boe",OewMv:t(967),YdGJH:t(999),sizBV:function(c,r){return c>r},KjYTn:function(c,r){return c*r},AmolO:function(c,r){return c>r},ZcMPg:function(c,r){return c!==r},YUpBP:t(1165),YcGho:t(1318),Ekmjz:t(1571),UlMgg:t(1099),Vzugm:t(515),rhajP:function(c,r){return c(r)},MXgBF:t(470),dOpPW:t(1140),ScNYW:function(c,r){return c+r},otXkx:function(c,r){return c===r},cLQqb:t(650),gUbCd:t(972),aRyYo:function(c,r){return c>>>r},xbcmZ:function(c,r){return c===r},HUIPs:"wrzee",UCsqu:function(c,r){return c||r},vOuuB:t(827),NUaeR:function(c,r){return c||r},Tivzx:function(c,r){return c||r},ObWdF:function(c,r){return c||r},PETmD:function(c,r){return c||r},wrCwI:t(1438)+"DB failed",UhACa:t(465),nSEDQ:function(c,r){return c(r)},bJoKv:function(c,r,s){return c(r,s)},TGHVD:function(c,r,s){return c(r,s)},SgwLS:function(c,r){return c===r},lvQLK:t(1595),Athna:t(593),BtrLc:function(c,r){return c(r)},tkkMD:t(375)+t(1291),YmnZJ:function(c,r,s,l){return c(r,s,l)},rxKyw:function(c,r,s,l){return c(r,s,l)},cazRi:"x_fronti"+t(1561)+"k",DjXHz:function(c,r,s,l){return c(r,s,l)},qcqhj:"need_ack",QwYPK:t(748),woUFJ:t(1784),kRGGX:function(c,r){return c||r},IGZKp:"ack_code",MFlbk:function(c,r,s){return c(r,s)},SPzkH:"sPgcQ",riqvU:t(884),WDiwQ:t(1771)+t(956)+"et=utf-8",SWrMQ:t(728)+t(579),sLXDa:t(728)+"ion/json"+t(535)+t(1229),nNHOR:t(834)+"e",ACgEt:t(1256),YMHep:function(c){return c()},QmxLn:function(c,r){return c>r},SJhmd:t(556),HoCWp:function(c,r){return c>>>r},SBsJv:function(c,r){return c+r},rrURs:"index out of ran"+t(1261),fElEh:t(1634),WOxrq:function(c,r){return c||r},auUuh:t(983),UZwTe:"integer "+t(1807)+"e",TjPtr:function(c,r){return c+r},kGFKc:function(c,r){return c<r},hUzsG:function(c,r){return c<<r},tXtIu:function(c,r){return c+r},cNpGM:function(c,r){return c|r},rTKvb:function(c,r){return c+r},yetNt:function(c,r){return c+r},jNEkh:function(c,r){return c|r},NRAyE:function(c,r){return c+r},ZBsIR:function(c,r){return c+r},UOBsn:function(c,r){return c+r},zMoPR:function(c,r){return c+r},vKzuB:function(c,r){return c+r},jccmq:function(c,r){return c>>>r},ctuYQ:function(c,r){return c+r},SqVRJ:function(c,r){return c&r},hLepL:function(c,r){return c+r},pFETT:function(c,r){return c>>>r},poswr:function(c,r){return c>>>r},RFngX:function(c,r){return c>>>r},ryOrN:function(c,r){return c&r},FGYJH:function(c,r){return c!==r},BqlqB:t(437),umkGm:function(c,r){return c&r},kNDio:function(c,r){return c&r},NSgUy:t(1110),PTMRK:function(c,r){return c>>>r},ZTnQb:function(c,r){return c<r},cmzQx:function(c,r){return c<<r},uqObK:function(c,r){return c&r},vYHhW:function(c,r){return c<r},Eaadu:function(c,r){return c>>>r},FhHVS:function(c,r){return c|r},dURxG:function(c,r){return c<r},VxHJA:function(c,r){return c|r},tikMR:function(c,r){return c>>>r},isRCd:function(c,r){return c|r},oHPZG:function(c,r){return c<<r},OGDIw:function(c,r){return c|r},fZVfx:function(c,r){return c<<r},RuZey:function(c,r){return c<r},TjYhs:t(635),xZQEG:function(c,r){return c===r},UzGzP:function(c,r){return c===r},akYsq:function(c,r){return c(r)},ygdgL:t(873)+t(1453)+t(743),bJxMq:"service-"+t(1651),kszxa:t(1651),FsiJe:t(322),vqUQx:function(c,r,s,l){return c(r,s,l)},UNxWL:t(1223)+t(1128),TNinD:function(c,r,s,l){return c(r,s,l)},IQVdV:function(c,r){return c(r)},LAjoi:t(979)+t(1025),oHjAO:function(c,r,s){return c(r,s)},EMRcB:function(c,r,s){return c(r,s)},zLRJX:function(c,r,s,l){return c(r,s,l)},BtGxB:function(c,r){return c===r},vFWdV:t(927),qvfyz:t(1126)+t(521),CVxLe:t(519)+t(754),yLjMA:function(c){return c()},bZqbf:t(954),gTmeD:function(c,r){return c||r},ZHOpq:function(c,r,s){return c(r,s)},qqHmA:function(c,r){return c===r},ZfRyt:function(c,r){return c+r},GNfEW:function(c,r){return c!==r},VBary:t(1782),CYOHe:function(c,r,s,l){return c(r,s,l)},URtdO:function(c,r,s,l){return c(r,s,l)},HhCgM:"x_fronti"+t(1769),RJepx:function(c,r){return c(r)},aeidl:function(c,r,s){return c(r,s)},WyADj:t(375)+t(1201),eXvbS:function(c,r,s,l){return c(r,s,l)},WQvsA:t(1010)+"s",Ibssc:"x-msg-cu"+t(1490)+"ue",MVQEv:function(c){return c()},iSvNS:t(1729),VDHPM:t(1340),cPCxz:t(839),ucAYR:function(c,r){return c+r},xmUGN:function(c,r){return c<r},adECJ:function(c,r){return c===r},HYxZm:t(718),mRirz:function(c){return c()},Vcyww:function(c){return c()},fXfci:function(c,r,s){return c(r,s)},Evbgl:function(c,r){return c(r)},HOuKC:function(c){return c()},rvNTt:function(c){return c()},mXojB:function(c,r,s,l){return c(r,s,l)},wfQPQ:function(c,r){return c===r},ZyrRE:t(835),EdQKS:function(c,r){return c===r},haLyI:t(1698)+t(1409)+"s",AcKvC:t(1471),Qvnsz:function(c,r,s){return c(r,s)},tPPJi:function(c,r){return c===r},dSRiu:function(c,r){return c!==r},eYTOX:t(686),SOlyN:function(c,r,s){return c(r,s)},OELTk:function(c,r,s){return c(r,s)},NoWMC:t(1275),SDBmL:function(c,r){return c(r)},rZCyU:function(c,r){return c&r},dZhnJ:function(c,r){return c&r},IvikU:t(796),ZUPMa:t(1548),GqLrT:t(655),XFfTa:function(c,r){return c===r},kBLYW:function(c,r){return c(r)},KPYpZ:"please p"+t(457)+t(1101)+t(1669)+"ket cons"+t(1214)+t(910)+t(615),TPPfC:function(c,r){return c===r},lCyJF:t(906),tTjFh:function(c,r,s){return c(r,s)},jsqYl:"reconnect",OpkGO:"stop imm"+t(1222)+t(1015)+"ct",lCOBc:t(1186),Ajsxk:t(1269),fguxm:t(318),StcqW:function(c,r){return c!==r},fIwBy:t(1231),cepQv:t(904),LaASE:t(1795),fYWCx:"ttwid",KKhVN:t(816)+t(548)+t(440)+"viceID o"+t(1598),XjGgP:function(c,r){return c==r},FmqWm:"function",PmELh:function(c){return c()},hTdbs:t(1568),iPfjo:t(1168)+"0",GiisY:function(c,r){return c>>>r},zqIHK:function(c,r){return c>>>r},vyodo:function(c,r){return c&r},ZCrVm:function(c,r){return c+r},OLtpu:function(c,r){return c+r},CQDYf:function(c,r){return c!==r},oAIrG:function(c,r){return c&r},oOqgA:function(c,r){return c|r},PdRcF:function(c,r){return c|r},RSAYQ:function(c,r){return c&r},tENVv:function(c,r){return c<r},leoNX:t(484),LNcFo:function(c,r,s){return c(r,s)},ejPAU:function(c,r){return c===r},cHSHl:t(464),lxbln:"ppnAt",pkyER:t(939),ASzvm:t(447),VhnKo:"start",JOlrI:function(c,r){return c>r},FiWvU:function(c,r){return c-r},AmXmk:function(c,r,s){return c(r,s)},KKSLC:function(c,r){return c!==r},dnNPr:t(554),GWQBY:t(1353),bOBTS:function(c,r){return c(r)},VJuxh:function(c,r){return c>>r},sWnuh:t(1536),VFVFR:t(968),EwGZI:t(1328)+">",dkimE:function(c,r){return c*r},mnPBr:function(c,r){return c-r},zMeAd:function(c,r){return c===r},mWOHE:function(c,r){return c!==r},SBAfh:function(c,r,s){return c(r,s)},JTpLe:t(382),SZIRB:function(c,r,s){return c(r,s)},sSdoT:function(c,r){return c(r)},BdoGa:t(372),quJWH:t(1313)+t(1753)+t(439)+"g",QGAxJ:function(c,r){return c(r)},qjYkZ:t(1087),kCnnT:t(675),HJIba:t(1417)+"4",hzvac:t(557),FsoNB:t(592),rFXDK:"jGsVp",ZLXyZ:t(980)+"1",lydbU:function(c,r,s,l){return c(r,s,l)},bMFea:t(962),mBcwf:function(c,r,s){return c(r,s)},cUMCA:t(628)+t(894)+"ork offline",Raasz:t(944),PcPYn:function(c,r){return c||r},XJZkz:t(1622),IDhHg:"please provide a"+t(357)+t(1293)+t(1189)+t(914)+t(1250)+t(1390)+t(1057),UBmVF:function(c,r){return c==r},ONfbz:t(359),xzvZP:function(c,r){return c!=r},VgrOb:function(c,r){return c(r)},TEsGl:t(816)+t(829)+t(1198)+t(1128),WiHHi:function(c,r){return c===r},SlbxP:t(922),fgueF:function(c,r){return c===r},Zrdkb:"fIWBw",suUnT:function(c,r){return c==r},vuXoD:t(518),QQXcg:t(1394),yvbGH:"3|2|4|0|1",Eqdld:function(c,r){return c!==r},RKMlB:"kicdo",BeQiE:function(c,r){return c||r},sxvJk:function(c,r){return c!==r},PfmGe:t(1071),Iqzez:t(745),DnqVM:function(c,r){return c(r)},tOenP:function(c,r){return c*r},RmeSG:function(c,r){return c===r},pmCzg:t(1524),DDmhk:function(c,r){return c!=r},JcSoa:function(c,r){return c!=r},ToRSz:function(c,r){return c===r},XtpwG:t(804)+t(625)+"lobalScope",ZrLKb:function(c,r){return c!=r},IUOZO:t(734),ygGhy:function(c,r){return c==r},nXOen:function(c,r){return c!=r},SRvZk:function(c,r){return c!=r},oDtxR:function(c,r){return c!=r},osonx:t(471)+t(669)+t(1194),BAVTP:t(1331)+"orkerGlo"+t(1018),BAcAS:function(c,r){return c===r},ZJJYl:function(c,r){return c!=r}};Vt.r(De),Vt.d(De,{FWS:()=>Cm,CustomErrorEvent:()=>Ll,createCloseEvent:()=>It,ReconnectEvent:()=>Dl,createErrorEvent:()=>gt,decodedFrame:()=>Lt,createOpenEvent:()=>Ul,CustomCloseEvent:()=>Ml,createReconnectEvent:()=>Ba,FrontierMessageEvent:()=>Fl,encodeFrame:()=>Zt,createMessageEvent:()=>zl,OpenEvent:()=>Bl,ErrorCode:()=>gn,Event:()=>pr,MessageEvent:()=>Nl});let n="";function i(c=""){let r=t,s="02",l=""+Date[r(690)](),h=n||(n=f(c)),g=Math[r(781)]()[r(1466)](16)[r(1476)](-6);return e[r(1796)](s,l)+h+g}function o(){let c=t;return e[c(1796)](1e4*Date[c(690)](),Math[c(1593)](e[c(703)](1e4,Math[c(781)]())))}function a(c){let r=t;return e.nPiVK(e[r(434)](Array,8)[r(1098)]("0"),e[r(1312)](parseInt,c,10)[r(1466)](2)).slice(-8)}function d(c){let r=t;if(e[r(1755)](e.xvuYI,e[r(1051)])){if(!this._ws)return;this._destroyWebSocket(_0x2fa4db,_0x37907b,_0x3974c5)}else return e[r(1796)](e[r(434)](Array,4)[r(1098)]("0"),e[r(732)](parseInt,c,2)[r(1466)](16))[r(1476)](-4)}function u(c){let r=t,s=c[r(1738)](/\./)[r(1202)](g=>a(g)),l=[];return l[0]=e[r(434)](d,e[r(943)](s[0],s[1])),l[1]=e.MIbur(d,e[r(441)](s[2],s[3])),[e[r(497)],e[r(497)],e[r(497)],e[r(497)],e[r(497)],e[r(1113)],l[0],l[1]][r(1098)]("")}function f(c){let r=t;if(e.pOUCk(e[r(1190)],e[r(1190)])){let s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(998)](c),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(998)](c);return s?e[r(1535)](u,c):l?e.MIbur(x,c):e[r(773)]}else return this[r(1444)]?this[r(1444)][r(1532)]:this[r(1148)]}function x(c){let r=t,s={kkXfW:function(O,N){return e[F(434)](O,N)},JwDVu:function(O,N){return e[F(953)](O,N)},xcIUW:function(O,N){return e.tmybS(O,N)}},l="",h=[],g=0,v=0,S=!0,w=r(1022);if(e[r(1062)](c[r(400)]("::"),-1)){let O=c[r(1738)]("::");for(let B=0;e[r(1742)](B,O[r(1436)]);B++){let K=O[B];if(e[r(1062)](K[r(400)](":"),0)){let j=K[r(1738)](":");S&&(g=j[r(1436)]),v+=j[r(1436)];for(let ce=0;e[r(953)](ce,j.length);ce++)if(e[r(1755)](4,j[ce][r(1436)])){let Re=w[r(1262)+"g"](0,e.vxoqH(4,j[ce][r(1436)])),Yt=Re[r(494)](j[ce]);h[r(1602)](Yt)}else h[r(1602)](j[ce]);S=!1}else{if(e[r(407)](4,K.length)){let j=w[r(1262)+"g"](0,e[r(1325)](4,K[r(1436)])),ce=j[r(494)](K);h.push(ce)}else h.push(K);S&&(g+=1),v+=1,S=!1}}let N="";for(let B=0;e[r(421)](B,e.vxoqH(8,v));B++)N=N[r(494)](w);for(let B=0;B<h[r(1436)];B++)B===g&&(l=l[r(494)](N)),l=l[r(494)](h[B]);return l}{let O=c.split(":");for(let N=0;N<O[r(1436)];N++)if(e[r(399)](e.lecWn,e[r(1434)])){let B=e[r(902)].split("|"),K=0;for(;;){switch(B[K++]){case"0":_0x40b844[_0x452a79++]=e[r(611)](_0x1039eb,18)|240;continue;case"1":_0x406d1f[_0x283719++]=e[r(356)](e[r(411)](_0xe6f761,6)&63,128);continue;case"2":_0x3cf9da=e.hpuyG(e[r(1796)](65536,e[r(659)](1023,_0x293615)<<10),e[r(659)](1023,_0x1fe82e));continue;case"3":++_0x1da5ab;continue;case"4":_0x4c7161[_0x3c96fe++]=e[r(659)](e[r(611)](_0x36976a,12),63)|128;continue;case"5":_0x5d42e3[_0x380826++]=e.nlMhg(e.TyvJr(63,_0x13f393),128);continue}break}}else{let B=O[N];if(e[r(692)](4,O[N].length))if(e[r(399)](e[r(1042)],e.CikEX)){let K=w.substring(0,e[r(822)](4,O[N][r(1436)])),j=K[r(494)](B);l=l[r(494)](j)}else _0x494a79=s[r(1174)](_0x4502f9,_0x4f6610),s.JwDVu(_0x3c8e58,32)&&(_0x33036b|=s[r(1481)](127&_0x4be519,_0x5f1922)),_0x4d09fb+=7;else l=l[r(494)](B)}return l}}function p(c,r){let s=t;if(e[s(407)](s(410),e[s(1143)]))_0x4ae00f[s(882)](_0x5d1f2a,_0x48d6c1),_0x375458.set(_0x5ed5b9,_0x2facc5);else{let l=c[s(957)];l!==void 0&&(ae(r,10),e[s(732)](Ue,r,l));let h=c[s(1272)];h!==void 0&&(e[s(1105)](ae,r,18),e[s(1461)](Ue,r,h))}}function m(c){let r=t,s={};e:for(;!e[r(1805)](J,c);){let l=ee(c);switch(e[r(606)](l,3)){case 0:break e;case 1:s[r(957)]=e.vruRU(ye,c,e[r(1805)](ee,c));break;case 2:s.value=e.TKsxj(ye,c,ee(c));break;default:e.mUnXN(C,c,e[r(659)](7,l))}}if(e[r(1694)](void 0,s[r(957)]))throw new Error(r(802)+r(1012)+r(1581)+"key");if(e[r(1694)](void 0,s.value))throw new Error(e.jqHjS);return s}function y(c){let r=t,s=e.BabvQ(R);return _(c,s),e[r(366)](M,s)}function _(c,r){let s=t,l={yiXby:s(565)},h=c.SeqID;if(e[s(692)](void 0,h))if(e.ZOEWK(s(867),s(1431)))e.IaZbz(ae,r,8),e[s(1160)](ct,r,h);else return this[s(1749)]>=this[s(653)+s(1653)];let g=c[s(514)];g!==void 0&&(e[s(1673)](ae,r,16),ct(r,g));let v=c[s(626)];if(e[s(399)](void 0,v)){if(e[s(1755)](e[s(1295)],e.vUduP))return _0x48454e?.find(Yt=>Yt[s(957)]===_0x302c61)?.value;e[s(1580)](ae,r,24),e[s(1442)](ct,r,e[s(500)](P,v))}let S=c[s(1604)];if(e[s(1470)](void 0,S))if(e[s(564)](e.sGErP,e[s(1016)]))e[s(1673)](ae,r,32),e[s(1463)](ct,r,e.TUrZJ(P,S));else return _0x56602d||(_0xfdf07=[_0x295cc1,_0x24053a,_0x3735b7,_0x150200,_0x5db820]);let w=c[s(321)];if(e[s(407)](void 0,w))for(let Yt of w){e[s(725)](ae,r,42);let zn=e.BabvQ(R);e[s(1442)](p,Yt,zn),ae(r,zn[s(1077)]),e[s(467)](T,r,zn),D(zn)}let O=c[s(1787)+"ncoding"];O!==void 0&&(e[s(1580)](ae,r,50),e.wgFBa(Ue,r,O));let N=c["payloadT"+s(537)];N!==void 0&&(e[s(1694)](e.FGNLJ,"fuODL")?(e[s(1461)](ae,r,58),e[s(1069)](Ue,r,N)):(this._isBrowser&&_0x2ed15a[s(872)+s(1003)+s(1484)](l[s(374)],this[s(1151)+"ageHide"]),this[s(404)+"er"]&&_0x7723b3[s(872)+s(1003)+s(1484)]("pageshow",this["_handleP"+s(320)]),this.close()));let B=c.payload;e[s(1242)](void 0,B)&&(e[s(1590)](e[s(1239)],e[s(1239)])?(ae(r,66),e[s(1069)](ae,r,B[s(1436)]),e[s(1105)](le,r,B)):_0x1a555a[s(1258)][s(1164)+s(1642)](_0x483c67));let K=c[s(1129)];e[s(865)](void 0,K)&&(e[s(343)](ae,r,74),e[s(1707)](Ue,r,K));let j=c[s(1304)+s(1315)];e[s(733)](void 0,j)&&(e[s(1085)](ae,r,82),e[s(343)](Ue,r,j));let ce=c[s(642)];e[s(733)](void 0,ce)&&(ae(r,90),Ue(r,ce));let Re=c[s(1469)+"e"];e.qvAXY(void 0,Re)&&(e[s(787)](ae,r,96),e.MnHWG(ct,r,P(Re)))}function E(c){let r=t,s={oLGje:function(l,h){return l>>>h},wGRDB:function(l,h){return e[F(443)](l,h)},zxfpA:function(l,h){return e[F(1044)](l,h)},bsWRK:function(l,h){return e[F(659)](l,h)},UcPxy:function(l,h){return e[F(326)](l,h)},VGCdZ:function(l,h){return e[F(1647)](l,h)},uojjH:function(l,h){return e[F(1796)](l,h)},CvqnL:function(l,h){return e[F(659)](l,h)},FzsOd:function(l,h){return e[F(326)](l,h)},wzzAa:function(l,h){return e[F(606)](l,h)}};if(e[r(1487)](e[r(668)],r(1728)))return e[r(1537)](I,e.bEghQ(U,c));{let l=_0x28953b[r(682)],h=_0x2e01a3[r(1657)];return _0x5f4c0a[_0x1897ac]=s.oLGje(h,24),_0x3666a0[s[r(567)](_0x47f6f5,1)]=h>>>16&255,_0x49f3da[s[r(1316)](_0x2863dd,2)]=s[r(1503)](s[r(1545)](h,8),255),_0x10ff19[s.VGCdZ(_0x30e2b9,3)]=s[r(1503)](255,h),_0x287ac4[s[r(1316)](_0x373df5,4)]=l>>>24,_0x11fb7a[s[r(965)](_0x2376f3,5)]=s[r(1660)](s[r(1135)](l,16),255),_0x183abb[s[r(452)](_0x3ff82a,6)]=s[r(1710)](l,8)&255,_0x19d21d[_0x9f9397+7]=s[r(1503)](255,l),_0x17b076+=8,_0x4c7187}}function I(c){let r=t,s={};e:for(;!e.TUrZJ(J,c);){let l=ee(c);switch(e[r(1196)](l,3)){case 0:break e;case 1:s[r(1149)]=e[r(527)](rt,c,!0);break;case 2:s.LogID=rt(c,!0);break;case 3:s[r(626)]=e[r(1537)](ee,c);break;case 4:s[r(1604)]=e[r(366)](ee,c);break;case 5:{let h=e[r(1790)](A,c);(s[r(321)]||(s[r(321)]=[]))[r(1602)](e.MIbur(m,c)),c.limit=h;break}case 6:s[r(1787)+"ncoding"]=e[r(1139)](ye,c,e[r(500)](ee,c));break;case 7:s[r(490)+r(537)]=e[r(1312)](ye,c,ee(c));break;case 8:s[r(403)]=oe(c,e[r(1163)](ee,c));break;case 9:s[r(1129)]=e[r(1446)](ye,c,e[r(1790)](ee,c));break;case 10:s[r(1304)+"ming"]=e.VKvCb(ye,c,e[r(587)](ee,c));break;case 11:s[r(642)]=e[r(1200)](ye,c,e[r(1537)](ee,c));break;case 12:s[r(1469)+"e"]=e[r(1535)](ee,c);break;default:e[r(1461)](C,c,e[r(601)](7,l))}}if(e[r(1590)](void 0,s[r(1149)]))throw new Error(e.KozyW);if(e[r(614)](void 0,s.LogID))throw new Error(e.RANZJ);if(e.EfYAz(void 0,s.service))throw new Error(r(802)+r(1012)+" field: "+r(626));if(e[r(602)](void 0,s[r(1604)]))throw new Error(e.KtCZa);return s}function A(c){let r=t;if(e[r(783)]===e.WfqOq)EXRVTG[r(366)](_0x204a83,_0x11f912[r(1664)]),EXRVTG.gGEEJ(_0x33ed44);else{let s=e[r(587)](ee,c),l=c[r(1077)];return c.limit=c[r(1161)]+s,l}}function C(c,r){let s=t;if(e[s(1570)](e.viUPE,s(766)))switch(r){case 0:for(;128&e.dmTea(H,c););break;case 2:e.PLyzc(V,c,e.KUWPF(ee,c));break;case 5:V(c,4);break;case 1:e[s(1384)](V,c,8);break;default:throw new Error(e[s(943)](e.sgQKM,r))}else!_0x1f562a[s(1633)+"d"]&&(this[s(404)+"er"]&&_0x3c61bc[s(872)+s(1003)+s(1484)](e.CKgIW,this[s(1151)+s(1459)]),this[s(404)+"er"]&&_0x372700["removeEv"+s(1003)+s(1484)](e[s(584)],this[s(1151)+s(320)]),this[s(848)]()),this._isBrowser&&_0xe862f2["removeEv"+s(1003)+s(1484)](s(1269),this["_handleO"+s(1452)]),this[s(404)+"er"]&&_0x385542[s(872)+s(1003)+s(1484)](e[s(1246)],this[s(632)+s(623)])}function P(c){let r=t;return c|=0,{low:c,high:e[r(817)](c,31),unsigned:e[r(1435)](c,0)}}let b=[];function R(){let c=t,r=b[c(706)]();return r?(r[c(1161)]=r[c(1077)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(c){b[t(1602)](c)}function U(c){return{bytes:c,offset:0,limit:c[t(1436)]}}function M(c){let r=t,s=c[r(1764)],l=c[r(1077)];return e.EfYAz(s[r(1436)],l)?s:s[r(1596)](0,l)}function V(c,r){let s=t;if(e.HJxUx(e[s(376)](c[s(1161)],r),c[s(1077)]))throw new Error(e.WVMdC);c[s(1161)]+=r}function J(c){let r=t;return e.zgVft(c[r(1161)],c[r(1077)])}function ie(c,r){let s=t,l=c.bytes,h=c[s(1161)],g=c[s(1077)],v=h+r;if(e.HJxUx(v,l[s(1436)])){let S=new Uint8Array(e[s(379)](2,v));S.set(l),c[s(1764)]=S}return c.offset=v,e[s(1062)](v,g)&&(c[s(1077)]=v),h}function X(c,r){let s=t,l=c[s(1161)];if(e.HJxUx(l+r,c[s(1077)]))throw new Error(e[s(1365)]);return c[s(1161)]+=r,l}function oe(c,r){let s=t,l=e.lxFDe(X,c,r);return c[s(1764)][s(1596)](l,e[s(441)](l,r))}function le(c,r){let s=t,l={fXeZr:function(h,g){return e[F(770)](h,g)},jIonG:function(h,g){return e[F(1031)](h,g)}};if(e[s(1636)](e[s(1381)],e[s(1381)])){let h=e.zBSAM(ie,c,r.length);c[s(1764)].set(r,h)}else{let h=0,g=0,v;do v=l[s(1120)](_0x1f2e37,_0x4fc99c),h<32&&(g|=l.jIonG(127&v,h)),h+=7;while(128&v);return g}}function ye(c,r){let s=t,l=e[s(814)](X,c,r),h=String[s(624)+"Code"],g=c[s(1764)],v="\uFFFD",S="";for(let w=0;w<r;w++)if(e[s(1308)]===e[s(1122)])_0x495245.log(_0x1b16e4);else{let O=g[w+l],N,B,K,j;e[s(602)](e[s(601)](128,O),0)?S+=e[s(1805)](h,O):(224&O)===192?w+1>=r?S+=v:(N=g[e[s(1796)](w,l)+1],e[s(733)](e[s(601)](192,N),128)?S+=v:(j=e[s(356)](e.NJOcE(e[s(601)](31,O),6),e[s(601)](63,N)),j<128?S+=v:(S+=e.ZDryA(h,j),w++))):e[s(866)](e[s(480)](240,O),224)?e[s(561)](e.roTdy(w,2),r)?S+=v:(N=g[e.nPiVK(e.PcFAR(w,l),1)],B=g[e[s(443)](e.cpwEL(w,l),2)],e[s(692)](e[s(324)](N|e[s(1609)](B,8),49344),32896)?S+=v:(j=e[s(356)](e[s(1217)](e[s(1279)](15,O),12),e[s(1718)](63&N,6))|e.YNvXC(63,B),j<2048||e[s(561)](j,55296)&&e[s(1630)](j,57343)?S+=v:(S+=e[s(789)](h,j),w+=2))):e[s(324)](248,O)==240?e[s(1147)](e[s(1747)](w,3),r)?S+=v:(N=g[e.vwFCb(w,l)+1],B=g[e[s(943)](e[s(943)](w,l),2)],K=g[e[s(1072)](e[s(446)](w,l),3)],e[s(733)](e[s(1064)](e.HYxGf(e[s(1104)](N,e.Vuthj(B,8)),e[s(1607)](K,16)),12632256),8421504)?S+=v:(j=e.cDEEY(e.TQqpm(e[s(1586)](e[s(710)](7,O),18),e[s(1718)](e[s(704)](63,N),12))|e[s(929)](63&B,6),e[s(1720)](63,K)),e[s(935)](j,65536)||e[s(1062)](j,1114111)?S+=v:(j-=65536,S+=e.FkEnI(h,e[s(817)](j,10)+55296,e[s(480)](1023,j)+56320),w+=3))):S+=v}return S}function Ue(c,r){let s=t;if(e[s(1600)]!==s(458))_0x57acc9=_0x38e59f[e.lQuEQ(e[s(757)](_0x26fb45,_0x5e56f6),1)],e[s(909)](e[s(659)](192,_0x225bbd),128)?_0x2c85d2+=_0x1d4e11:(_0x2b0828=e[s(1240)](e[s(1031)](e[s(730)](31,_0x58481e),6),e[s(553)](63,_0x40ed73)),e.lQZaS(_0x39236,128)?_0x40495e+=_0x3b077e:(_0x20bb83+=e[s(678)](_0x3904a3,_0x1f83ca),_0x59fde9++));else{let l=r[s(1436)],h=0;for(let S=0;S<l;S++){let w=r[s(693)+"At"](S);e[s(1435)](w,55296)&&e[s(373)](w,56319)&&e[s(721)](e[s(812)](S,1),l)&&(w=e[s(1044)](w<<10,r[s(693)+"At"](++S))-56613888),h+=w<128?1:e.pQSIi(w,2048)?2:e[s(503)](w,65536)?3:4}e[s(467)](ae,c,h);let g=e[s(1387)](ie,c,h),v=c.bytes;for(let S=0;S<l;S++){let w=r.charCodeAt(S);w>=55296&&e.fGiTm(w,56319)&&e[s(503)](e[s(620)](S,1),l)&&(w=e[s(1647)](e.SSeiO(w,10),r.charCodeAt(++S))-56613888),e[s(807)](w,128)?v[g++]=w:(e[s(721)](w,2048)?v[g++]=e[s(1155)](e[s(480)](e[s(817)](w,6),31),192):(e[s(426)](w,65536)?v[g++]=e[s(1240)](e[s(659)](e[s(817)](w,12),15),224):(v[g++]=e[s(660)](e[s(1279)](e[s(1500)](w,18),7),240),v[g++]=e.TOamB(e[s(1064)](e[s(817)](w,12),63),128)),v[g++]=e[s(1191)](e.TmKYp(e[s(1500)](w,6),63),128)),v[g++]=e[s(1240)](e[s(659)](63,w),128))}}}function T(c,r){let s=t,l=e.GylHx(ie,c,r[s(1077)]),h=c[s(1764)],g=r[s(1764)];for(let v=0,S=r[s(1077)];e.hSNiQ(v,S);v++)h[e.PcFAR(v,l)]=g[v]}function H(c){let r=t;return c[r(1764)][e[r(849)](X,c,1)]}function W(c,r){let s=e.mHTeB(ie,c,1);c.bytes[s]=r}function ee(c){let r=t;if(e[r(684)]==="pzGfz"){let s=_0x42f6d3(_0x21eb14),l=_0x3f53ad.limit;return _0x3834cc[r(1077)]=e.lQuEQ(_0x87d9e3[r(1161)],s),l}else{let s=0,l=0,h;do h=e[r(1725)](H,c),e[r(1314)](s,32)&&(l|=e[r(1055)](e[r(704)](127,h),s)),s+=7;while(e[r(704)](128,h));return l}}function ae(c,r){let s=t;for(r>>>=0;e[s(1435)](r,128);)e[s(725)](W,c,e.ZaAcS(127,r)|128),r>>>=7;W(c,r)}function rt(c,r){let s=t,l={YWbcD:e[s(1039)],sIvKH:function(w,O,N){return e[s(732)](w,O,N)}},h=0,g=0,v=0,S;return S=e.KUWPF(H,c),h=127&S,128&S&&(e[s(1158)]!==e[s(1349)]?(S=e[s(1559)](H,c),h|=e.NJOcE(127&S,7),128&S&&(S=e[s(409)](H,c),h|=e[s(1193)](127&S,14),128&S&&(S=e[s(587)](H,c),h|=e[s(1586)](e[s(553)](127,S),21),e.sZGOo(128,S)&&(e[s(897)]===e[s(897)]?(S=H(c),g=e[s(553)](127,S),e[s(1064)](128,S)&&(S=H(c),g|=e[s(1607)](e[s(480)](127,S),7),e[s(710)](128,S)&&(S=e[s(1245)](H,c),g|=e.wdqYo(127&S,14),e[s(480)](128,S)&&(S=e[s(1327)](H,c),g|=e[s(1607)](e[s(324)](127,S),21),e[s(707)](128,S)&&(S=e[s(643)](H,c),v=e[s(1720)](127,S),e.SxbOm(128,S)&&(S=e[s(530)](H,c),v|=(127&S)<<7)))))):(this[s(1780)](l.YWbcD,_0x3229de),this[s(391)]&&this.onclose(_0x37225b)))))):(this[s(1086)+"ameSpace"]=_0x260dc6,this["_cursorF"+s(598)]=_0xef8367,this._messageStrategy=_0x27f937,this._qosDB=l[s(1794)](_0x5b8404,this[s(1086)+"ameSpace"],s(984)+s(1549)))),{low:e.sWLDs(h,e.jLeue(g,28)),high:e[s(660)](e[s(606)](g,4),e.NJOcE(v,24)),unsigned:r}}function ct(c,r){let s=t;if(e.jDwgL(e[s(1049)],e[s(1557)])){let l=r[s(682)]>>>0,h=e[s(1482)](r[s(682)]>>>28|e.KmOFD(r[s(1657)],4),0),g=e[s(495)](r[s(1657)],24),v=e[s(945)](0,g)?e[s(1487)](0,h)?e.hSNiQ(l,16384)?e.pQSIi(l,128)?1:2:l<2097152?3:4:h<16384?h<128?5:6:h<2097152?7:8:g<128?9:10,S=e[s(1105)](ie,c,v),w=c.bytes;switch(v){case 10:w[e[s(443)](S,9)]=e[s(1362)](e.ZCCVp(g,7),1);case 9:w[S+8]=e[s(1008)](9,v)?e[s(1240)](128,g):e.TmKYp(127,g);case 8:w[e[s(608)](S,7)]=e.DggOy(8,v)?e[s(844)](e[s(1094)](h,21),128):e[s(647)](h,21)&127;case 7:w[e[s(997)](S,6)]=e[s(399)](7,v)?e[s(356)](e.VzivR(h,14),128):e[s(1064)](e.XaLBw(h,14),127);case 6:w[e.Hoyvl(S,5)]=e[s(1477)](6,v)?e.sWLDs(e[s(647)](h,7),128):e[s(508)](h,7)&127;case 5:w[S+4]=e[s(1242)](5,v)?128|h:e.gzCdv(127,h);case 4:w[e[s(1768)](S,3)]=v!==4?e[s(671)](e[s(792)](l,21),128):e[s(553)](l>>>21,127);case 3:w[e.hpuyG(S,2)]=v!==3?e[s(1094)](l,14)|128:e[s(324)](l>>>14,127);case 2:w[S+1]=e[s(399)](2,v)?e[s(1233)](e[s(1574)](l,7),128):e[s(460)](l,7)&127;case 1:w[S]=e[s(1448)](1,v)?e[s(1155)](128,l):127&l}}else{let l=e[s(716)](_0x2cade5,_0x12ef62);this[s(1444)]&&this[s(1444)][s(1080)+"te"]===this[s(1735)]&&(this[s(1444)]&&this[s(1444)][s(1169)](l),this[s(744)](e[s(578)],_0x564808))}}function Lt(c){let r=t,s={wNWBG:function(l,h){return e[F(1535)](l,h)},KOvAf:e.ixTaz,uKSAp:r(1698)+r(1409)+"s",zkHRL:e[r(1655)],ehGYo:r(1471),BmJDx:function(l,h,g){return e[r(1623)](l,h,g)}};if(e[r(1470)](e[r(1326)],e[r(1326)])){let l={OJoOg:function(v,S){return v(S)},qNroj:s[r(1709)],IXJnh:s[r(1137)],Rixbu:s.zkHRL};this["_clearPi"+r(1485)](),this[r(845)+r(1117)+"Id"]=s[r(445)](_0x36cf7e,this[r(618)][r(1289)](this),this._options[r(779)+r(651)]);let h=()=>{let v=r;l[v(630)](_0x3fb6b0,l.qNroj),this[v(1078)](l[v(912)],h),this[v(1078)](l[v(1450)],g)},g=()=>{let v=r;s.wNWBG(_0x3ce8ed,s[v(883)]),this[v(1078)](s.uKSAp,h),this[v(1078)](s[v(977)],g)};this.on(s.uKSAp,h),this.on(s[r(977)],g),this[r(618)]()}else return e.Frkjc(E,c)}function Zt(c){return y(c)}let pn=65536,Fn=t(1146),pt=e[t(1292)](pn,pn),xr=e.tOenP(pt,pt),Ne=e[t(1040)](xr,2),ge=String[t(1640)+"e"][t(693)+"At"];class de{constructor(r,s,l){let h=t;this[h(591)]=!0,this[h(682)]=0|r,this.high=0|s,this[h(1440)]=!!l}static[t(591)](r){let s=t,l={jkSgW:function(h,g){return e[F(508)](h,g)},loLOJ:function(h,g){return e[F(707)](h,g)},ZQXPJ:function(h,g){return h>>>g},PxUUI:function(h,g){return h&g},RpBhO:function(h,g){return e[F(441)](h,g)},fSgOQ:function(h,g){return e[F(647)](h,g)},NRjLH:function(h,g){return h+g},YNaFf:function(h,g){return h>>>g},lTmbh:function(h,g){return e[F(943)](h,g)},iAmBF:function(h,g){return e.auLiI(h,g)},BskmH:function(h,g){return e[F(1155)](h,g)}};if(e.rtCVT!==s(1235)){_0x124730.isLong(_0x52f0e6)||(_0x33f356=_0x31e322[s(1324)+"er"](_0x321b27));let h=l[s(1335)](this[s(1657)],16),g=l.loLOJ(65535,this[s(1657)]),v=l.jkSgW(this[s(682)],16),S=65535&this[s(682)],w=l[s(1773)](_0x1a2537.high,16),O=l.PxUUI(65535,_0x4a11b8[s(1657)]),N=_0x17b257[s(682)]>>>16,B=65535&_0x7127ea[s(682)],K=0,j=0,ce=0,Re=0;return Re+=l[s(1378)](S,B),ce+=l.fSgOQ(Re,16),Re&=65535,ce+=l[s(930)](v,N),j+=ce>>>16,ce&=65535,j+=g+O,K+=l.YNaFf(j,16),j&=65535,K+=l.lTmbh(h,w),K&=65535,_0x2dbf00[s(341)](l.iAmBF(ce,16)|Re,l[s(808)](K<<16,j),this[s(1440)])}else return r&&e[s(945)](!0,r.isLong)}static fromBits(r,s,l){return new de(r,s,l)}static[t(833)+"s"](r,s,l){let h=t,g={WVsgh:function(v,S){return e[F(1245)](v,S)},oZiCT:"ping_onc"+h(1409)+"s",mRztV:e[h(1655)],WrLHS:e[h(1676)],QEMIg:function(v,S,w){return e[h(1468)](v,S,w)}};return e.HKHyH!==e.zoehL?l?de[h(833)+h(1360)](r,s):de[h(833)+h(1399)](r,s):new _0x25dbd6((v,S)=>{let w=h,O={hCrEl:function(K,j){return g[F(1215)](K,j)},PVSiF:g[w(1511)],gqoVA:g[w(1083)],EzvAj:g[w(1383)]};this[w(947)+w(1485)](),this[w(845)+w(1117)+"Id"]=g[w(1594)](_0x39a526,this[w(618)][w(1289)](this),this[w(1070)]["pingInte"+w(651)]);let N=()=>{let K=w;O.hCrEl(v,"success"),this[K(1078)](O[K(1666)],N),this[K(1078)](O.gqoVA,B)},B=()=>{let K=w;O[K(1704)](S,O[K(1612)]),this[K(1078)](O[K(1666)],N),this[K(1078)](O[K(699)],B)};this.on(g[w(1511)],N),this.on(g[w(1083)],B),this[w(618)]()})}static[t(833)+t(1360)](r,s){let l=t;return new de(e[l(1507)](e[l(1155)](r[0],r[1]<<8)|e[l(1060)](r[2],16),e[l(1566)](r[3],24)),e[l(392)](e.TjeAy(r[4],e.kYxnx(r[5],8)),e[l(1060)](r[6],16))|e[l(1522)](r[7],24),s)}static[t(833)+"sBE"](r,s){let l=t;return new de(e[l(1155)](e[l(1410)](r[4]<<24|e[l(1368)](r[5],16),e[l(1060)](r[6],8)),r[7]),e[l(1348)](e.imShQ(e[l(790)](r[0],24),r[1]<<16),e[l(389)](r[2],8))|r[3],s)}static fromHash(r){let s=t;return e[s(1540)](r,Fn)?dt:new de(e.hkDcg(e[s(393)](e[s(1629)](ge[s(358)](r,0),e[s(830)](ge[s(358)](r,1),8)),ge[s(358)](r,2)<<16)|e[s(1180)](ge[s(358)](r,3),24),0),e[s(495)](e[s(523)](e[s(1052)](ge[s(358)](r,4),e[s(1217)](ge.call(r,5),8))|e[s(1339)](ge[s(358)](r,6),16),e[s(736)](ge[s(358)](r,7),24)),0),!0)}toHash(){let r=t;return String[r(624)+r(563)](e[r(1774)](255,this[r(682)]),e[r(495)](this.low,8)&255,e[r(707)](e.VxIiK(this.low,16),255),this[r(682)]>>>24,255&this[r(1657)],this[r(1657)]>>>8&255,e[r(707)](e[r(1310)](this[r(1657)],16),255),e[r(1482)](this[r(1657)],24))}static[t(1324)+"er"](r,s=!0){let l=t;if(e[l(836)](e.AFfUt,e[l(1379)]))_0x3a79d2=e[l(1689)](e[l(1368)](31&_0x3f0962,6),e[l(480)](63,_0x480c36)),e[l(934)](_0x532aa1,128)?_0x278749+=_0x24c0c7:(_0x2cd531+=e.PXMrs(_0x38b605,_0x1bc248),_0x2b7e11++);else{if(e[l(770)](isNaN,r))return s?Ug:dt;if(s){if(e[l(1213)](r,xr))return Gg}else{if(r<=-Ne)return qg;if(e[l(619)](e[l(997)](r,1),Ne))return Hg}return de[l(341)](e[l(1104)](r%pt,0),e[l(1629)](e[l(1040)](r,pt),0),s)}}toNumber(){let r=t,s={QsoJB:function(l,h){return e[F(1213)](l,h)},kifDW:function(l,h){return e.eglse(l,h)},dhOje:function(l,h){return e.lQuEQ(l,h)},FQACZ:function(l,h){return e[F(1458)](l,h)},unfHv:function(l,h){return e[F(1659)](l,h)}};if(e[r(585)]===e[r(786)]){let l=_0x151dd2.charCodeAt(_0x3a310d);KADiOP[r(1317)](l,55296)&&l<=56319&&KADiOP[r(1034)](KADiOP.dhOje(_0x2e8161,1),_0x31266d)&&(l=KADiOP.FQACZ(l<<10,_0x5bb654[r(693)+"At"](++_0x30ed70))-56613888),_0x29e8c8+=l<128?1:l<2048?2:KADiOP[r(510)](l,65536)?3:4}else return this[r(1440)]?e[r(920)](e.vusrA(e[r(1628)](this.high,0),pt),e[r(1094)](this[r(682)],0)):e[r(1625)](e[r(1292)](this[r(1657)],pt),this.low>>>0)}[t(900)](){let r=t,s={kJgyI:function(l,h){return l!==h},GIBgN:function(l,h){return e[F(722)](l,h)}};if(e[r(865)](e[r(657)],e[r(1232)]))return e.ydwxv(0,this[r(1657)])&&e.ydwxv(0,this[r(682)]);if(kpaMNm[r(580)](4,_0x15b248[r(1436)])){let l=_0x3ff311[r(1262)+"g"](0,kpaMNm[r(1425)](4,_0xb5bbc1[r(1436)])),h=l[r(494)](_0x2956fd);_0x1ce119[r(1602)](h)}else _0x5b1fc3.push(_0x5043a4);_0x238250&&(_0x1f6f2e+=1),_0x2c56cb+=1,_0xdfa1d2=!1}[t(639)](r){let s=t;de[s(591)](r)||(r=de.fromNumber(r));let l=e.seZxj(this.high,16),h=e[s(659)](65535,this[s(1657)]),g=e[s(402)](this[s(682)],16),v=e[s(707)](65535,this[s(682)]),S=e.MtXXm(r[s(1657)],16),w=e[s(659)](65535,r.high),O=r.low>>>16,N=e[s(1279)](65535,r.low),B=0,K=0,j=0,ce=0;return ce+=e[s(1647)](v,N),j+=e.seZxj(ce,16),ce&=65535,j+=g+O,K+=e[s(1234)](j,16),j&=65535,K+=e.QoFug(h,w),B+=e[s(384)](K,16),K&=65535,B+=l+S,B&=65535,de.fromBits(e[s(1233)](e[s(338)](j,16),ce),e.sWLDs(e[s(466)](B,16),K),this[s(1440)])}[t(596)](r){let s=t;return de.isLong(r)||(r=de[s(1324)+"er"](r)),e.zKamo(this.unsigned,r[s(1440)])&&e[s(1447)](this.high,31)===1&&e[s(1636)](r[s(1657)]>>>31,1)?!1:e[s(1601)](this[s(1657)],r.high)&&this[s(682)]===r.low}[t(1002)](){let r=t;return this[r(682)]===-1&&this[r(1657)]===-1?de[r(341)](0,0,this[r(1440)]):e[r(945)](-1,this[r(682)])?de[r(341)](0,e[r(997)](this[r(1657)],1),this[r(1440)]):de[r(341)](e[r(376)](this.low,1),this[r(1657)],this[r(1440)])}[t(1162)](r){return r?this.toBytesLE():this[t(847)+"E"]()}[t(1754)+"E"](){let r=t;if(e[r(473)](e[r(352)],e.ANWrX)){let s=this[r(1657)],l=this[r(682)];return[e[r(1064)](255,l),e.sZGOo(e[r(1628)](l,8),255),e[r(819)](l,16)&255,e.Shiud(l,24),255&s,e[r(704)](e[r(813)](s,8),255),e.SLHOu(e[r(1447)](s,16),255),e[r(1310)](s,24)]}else _0x5489e[r(872)+r(1003)+r(1484)](EXRVTG.CIIWu,_0x228ace),_0x54ea26[r(872)+r(1003)+"ner"](EXRVTG.OdXLv,_0x3dcd9e),_0x10e9f0["removeEv"+r(1003)+r(1484)](EXRVTG.RThJZ,_0x389c90)}[t(847)+"E"](){let r=t,s=this[r(1657)],l=this[r(682)];return[e[r(1578)](s,24),e[r(659)](e[r(1196)](s,16),255),e[r(1023)](e[r(1708)](s,8),255),255&s,e.WZpJc(l,24),e[r(707)](e[r(508)](l,16),255),e[r(1346)](e[r(1584)](l,8),255),e[r(513)](255,l)]}}let dt=new de(0,0,!1),Ug=new de(0,0,!0),Hg=de[t(341)](-1,2147483647,!1),Gg=de[t(341)](-1,-1,!0),qg=de[t(341)](0,-2147483648,!1);var gn=(function(c){let r=t,s=(r(903)+r(877))[r(1738)]("|"),l=0;for(;;){switch(s[l++]){case"0":c[c[e[r(1061)]]=5005]=e[r(1061)];continue;case"1":c[c[e.USObm]=5001]=r(1248)+r(369);continue;case"2":c[c[r(1658)+"ERROR"]=5004]=r(1658)+"ERROR";continue;case"3":c[c[e[r(334)]]=5003]=e[r(334)];continue;case"4":return c;case"5":c[c[r(1437)+r(319)]=5002]=e[r(317)];continue}break}})({});class pr{constructor(r){let s=t;if(e[s(1382)](e.vSiud,s(1123)))return _0x2b3004===_0x4f3534?_0x3ebdd5:new _0x33544e(e[s(1482)](e[s(1079)](e[s(1395)](e.TOamB(_0x3d2c12[s(358)](_0x4f09d0,0),e[s(1637)](_0x5ffebc[s(358)](_0x5cee9c,1),8)),e.zgzFl(_0x34088b[s(358)](_0x39a6bc,2),16)),e[s(666)](_0x3eeb0f[s(358)](_0xa8dbd9,3),24)),0),e[s(362)](e[s(1629)](_0x7a5a4c.call(_0x226688,4)|e.nfaSr(_0x4b6c34[s(358)](_0x409aa8,5),8),e[s(453)](_0x516ae1.call(_0x9a36d2,6),16))|e[s(1607)](_0x30c7e3[s(358)](_0x338639,7),24),0),!0);this[s(767)]=r,this[s(422)]=null}}class Dl extends pr{constructor(r,s){let l=t;super(r),this.message=s&&s[l(853)]||null}}class Ll extends pr{constructor(r,s){let l=t,h=e[l(1577)].split("|"),g=0;for(;;){switch(h[g++]){case"0":this[l(1664)]=s&&s[l(1664)]||null;continue;case"1":this[l(1290)]=s&&s[l(1290)]||"";continue;case"2":this.colno=s&&s[l(695)]||0;continue;case"3":this[l(853)]=s&&s[l(853)]||"";continue;case"4":this[l(1411)]=s&&s[l(1411)]||5001;continue;case"5":super(r);continue;case"6":this.lineno=s&&s[l(1243)]||0;continue}break}}}class Ml extends pr{constructor(r,s){let l=t,h=(l(1684)+"1").split("|"),g=0;for(;;){switch(h[g++]){case"0":this[l(1620)]=s&&s[l(1620)]||!1;continue;case"1":this[l(895)+l(1696)]=s&&s[l(895)+l(1696)]||!1;continue;case"2":this[l(1411)]=s&&s[l(1411)]||0;continue;case"3":this[l(1037)]=s&&s.reason||"";continue;case"4":super(r);continue}break}}}class Nl extends pr{constructor(r,s){let l=t;super(r),this.data=s&&s[l(887)]||null}}class Fl extends Nl{constructor(r,s){let l=t;super(r),this[l(887)]=s&&s[l(887)]||null,this.message=s&&s[l(853)]||null}}class Bl extends pr{constructor(r,s){let l=t;super(r),this[l(887)]=s&&s[l(887)]||null}}function gt(c,{message:r,code:s,error:l}){return new Ll(c,{message:r,code:s,error:l})}function It(c,{code:r,reason:s,wasClean:l,willReconnect:h}){return new Ml(c,{code:r,reason:s,wasClean:l,willReconnect:h})}function zl(c,{data:r,message:s}){let l=t;if(e[l(1477)](e[l(328)],l(420)))return new Fl(c,{data:r,message:s});EXRVTG[l(1133)](_0x8f7d29,EXRVTG[l(409)](_0x2ad354,_0x5d3d9e.result),_0xdea6d4.oldVersion,_0x3780f9[l(648)+"on"],EXRVTG[l(1400)](_0x21fab5,_0x489939[l(1358)+l(869)]))}function Ul(c,{data:r}){let s=t;return e.zKamo(s(1531),e[s(861)])?new Bl(c,{data:r}):e.kqYPB(_0x31d984,_0x184dda)}function Ba(c,{message:r}){return new Dl(c,{message:r})}class Hl{constructor(r,s){let l=t;this[l(1523)+"s"]=r,this[l(761)+"es"]=s,this[l(1760)+l(994)]=0,this["currentE"+l(1033)+l(936)+"t"]=0}[t(913)+t(1533)+t(378)](){let r=t;this[r(1760)+r(994)]=0,this[r(1386)+"ndpointT"+r(936)+"t"]=0}[t(550)+"es"](){let r=t;this[r(1386)+r(1033)+r(936)+"t"]=0}[t(429)+"ntEndpoint"](){let r=t;return this[r(1523)+"s"][this["currentI"+r(994)]]}[t(429)+t(575)+t(698)+"ount"](){let r=t,s={dCZPg:function(l,h,g){return e[F(539)](l,h,g)},roOUj:function(l,h){return e[F(890)](l,h)}};if(e[r(733)](e.TrXqu,e[r(855)]))return this["currentE"+r(1033)+r(936)+"t"];{let l=_0x417e98.key;l!==void 0&&(ZwjbMq[r(1765)](_0x361246,_0x6c6bdf,10),_0x1998ab(_0xc48768,l));let h=_0x2e132a[r(1272)];ZwjbMq.roOUj(void 0,h)&&(ZwjbMq.dCZPg(_0x3520e0,_0x29847b,18),ZwjbMq[r(1765)](_0x60e1c8,_0x2a3316,h))}}[t(1611)+t(1152)+"es"](){let r=t;return!!(this[r(1760)+r(994)]>=this[r(1523)+"s"][r(1436)]||e[r(1601)](this[r(1760)+"ndex"],e[r(751)](this[r(1523)+"s"][r(1436)],1))&&e[r(602)](this[r(1386)+r(1033)+r(936)+"t"],this[r(761)+"es"]))}[t(990)+t(1361)+"ointReac"+t(713)+t(1690)](){let r=t;return this[r(1760)+r(994)]==this[r(1523)+"s"].length?!0:this["currentE"+r(1033)+r(936)+"t"]>this[r(761)+"es"]}["replaceB"+t(1544)+"pointAndUpdateCo"+t(776)](){let r=t;return this[r(1386)+r(1033)+"riesCount"]=1,this[r(1760)+r(994)]++,this.endpoints[this[r(1760)+"ndex"]]}[t(429)+t(575)+t(1263)+t(1111)](){let r=t;if(e[r(407)](r(1488),e[r(1301)])){let s=_0x274640[r(853)][r(403)];s&&_0x3745c4[r(617)+"rs"](s)}else return this[r(1386)+"ndpointTriesCount"]++,this[r(429)+r(575)+"nt"]()}}let gr=(e[t(616)](e[t(461)],typeof globalThis)&&e[t(771)](e[t(1172)],globalThis[t(479)+t(1737)].name)||e[t(1367)](e[t(461)],typeof window)&&e[t(945)](e[t(1172)],window[t(479)+t(1737)][t(1651)]))&&e.DDmhk(e[t(461)],typeof document),Bn=e[t(1504)](e[t(461)],typeof globalThis)&&(e[t(772)](t(734),globalThis.constructor.name)||e[t(1270)](e[t(941)],globalThis["construc"+t(1737)][t(1651)]))&&e.ZrLKb(e[t(461)],typeof tt),hi=(e.QCwGW!=typeof globalThis&&e.RmeSG(e[t(815)],globalThis[t(479)+t(1737)].name)||e[t(681)](t(1136)+"d",typeof globalThis)||e[t(1363)](e[t(461)],typeof globalThis)&&!!globalThis[t(1130)+"Bridge"])&&e.SRvZk(e[t(461)],typeof wx),xi=e[t(1154)](e[t(461)],typeof globalThis)&&(e[t(941)]===globalThis[t(479)+t(1737)][t(1651)]||e[t(1706)](e[t(1249)],globalThis["construc"+t(1737)].name)||e[t(1543)]===globalThis[t(479)+t(1737)][t(1651)])&&e[t(1363)](e[t(461)],typeof self),jg=e[t(461)]!=typeof globalThis&&t(734)===globalThis[t(479)+t(1737)][t(1651)]&&t(1136)+"d"!=typeof global&&e[t(992)](e.IUOZO,global[t(479)+"tor"].name)&&e[t(493)](t(1136)+"d",typeof process)&&!!process[t(417)];class za{constructor(){let r=t;this[r(656)+"rs"]={}}[t(1780)](r,...s){let l=t,h=this[l(656)+"rs"][r];if(h)h.slice().forEach(g=>g.fn[l(888)](g[l(1703)],s));else if(e.yJqWC(e[l(1211)],r)&&!this[l(1705)]){let g=s[l(1436)]&&s[0];if(g instanceof Error)throw g;let v=new Error(e[l(542)]+(g?e.xBSaO(e.hpuyG(" (",g.message),")"):""));throw v[l(496)]=g,g}return this}[t(1078)](r,s){let l=t;if(e[l(1601)](void 0,r))this[l(656)+"rs"]={};else if(e[l(1382)](void 0,s))this._listeners[r]=null;else{let h=this[l(656)+"rs"][r];if(h)for(let g=0;e[l(503)](g,h[l(1436)]);)e[l(1576)](h[g].fn,s)?h[l(1422)](g,1):++g}return this}on(r,s,l){let h=t;return(this[h(656)+"rs"][r]||(this[h(656)+"rs"][r]=[]))[h(1602)]({fn:s,ctx:l||this}),this}}class Wg extends za{[t(1067)+t(455)+"age"](r){let s=t;return r.errMsg||r[s(1334)]?(s(755)+" "+(r[s(1685)]||"")+s(1006)+(r[s(1334)]||"")).trim():JSON[s(1777)+"y"](r)}constructor(r,s,l){let h=t;super(),this[h(764)]=null,hi&&wx[h(1475)+h(1307)]&&(this[h(764)]=wx[h(1475)+h(1307)]({url:r,protocols:s,header:l,fail:this[h(1671)+h(788)+"lHandler"].bind(this),success:this["_createS"+h(1321)+h(1489)+h(1615)][h(1289)](this)})),Bn&&tt[h(1475)+h(1307)]&&(this[h(764)]=tt[h(1475)+h(1307)]({url:r,protocols:s,header:l,fail:this[h(1671)+"ocketFai"+h(1419)][h(1289)](this),success:this[h(1671)+h(1321)+h(1489)+h(1615)][h(1289)](this)}))}[t(1671)+t(1321)+t(1489)+t(1615)](){let r=t;e.EyrTC(e.XNutD,e.XNutD)?(++_0x18abb5,_0x42e09f+=4):Promise[r(1241)]()[r(499)](()=>{let s=r;this[s(1445)+s(1663)]()})}[t(1671)+t(788)+t(1419)](r){let s=t;Promise[s(1241)]()[s(499)](()=>{let l=s,h=e[l(1139)](gt,"error",{message:this[l(1067)+l(455)+l(1788)](r)});this[l(1780)](e.OdXLv,h);let g=e[l(1509)](It,e[l(1039)],{reason:this[l(1067)+l(455)+l(1788)](r)});this[l(1780)](e[l(1039)],g)})}[t(1445)+t(1663)](){let r=t,s={qtVef:r(557),QYCdk:function(l,h,g){return e[r(1370)](l,h,g)},ZfUNt:r(1269),qSRuI:e[r(1246)],MqYSk:e[r(846)],etWBB:e[r(1211)],pZHpl:function(l,h,g){return e[r(1139)](l,h,g)}};this[r(764)][r(1391)](l=>{let h=r;this[h(1780)](s[h(1029)],s[h(346)](Ul,h(557),{...l,data:l.errMsg||""}))}),this[r(764)][r(749)](l=>{let h=r;this[h(1780)](h(848),e[h(799)](It,e[h(1039)],{...l}))}),this[r(764)][r(1597)+"e"](l=>{let h=r;e[h(1601)](e.vEuPI,e.nosiK)?(this[h(404)+"er"]&&_0x526b51["removeEventListe"+h(1484)](s[h(729)],this[h(632)+h(1452)]),this[h(404)+"er"]&&_0x18974e[h(872)+h(1003)+h(1484)](s[h(538)],this[h(632)+h(623)]),this[h(404)+"er"]&&_0x5e420e[h(872)+h(1003)+h(1484)](s[h(886)],this._handlePageHide),this[h(404)+"er"]&&_0x3d480e[h(872)+h(1003)+h(1484)](h(1271),this[h(1151)+h(320)])):this[h(1780)](e[h(1443)],e[h(419)](zl,h(853),{...l}))}),this[r(764)][r(1599)](l=>{let h=r;this[h(1780)](s[h(450)],s[h(1374)](gt,s[h(450)],{...l,message:l[h(1685)]||""}))})}[t(1169)](r){let s=t,l={woeOS:function(h,g,v){return e[F(1707)](h,g,v)},XCPwh:s(1664),FUvhL:function(h,g,v){return e[s(837)](h,g,v)}};if(e.ntABt(r,Uint8Array)){let h=r[s(386)][s(1476)](r.byteOffset,r[s(1351)+"th"]+r[s(677)+"et"]);this[s(764)]&&this[s(764)][s(1169)]({data:h,fail:g=>{let v=s;this[v(1780)](v(1664),l[v(881)](gt,l[v(746)],{message:this["_formatE"+v(455)+v(1788)](g)}))}})}else this[s(764)]&&this._socket[s(1169)]({data:r,fail:h=>{let g=s;this[g(1780)](l[g(746)],l[g(785)](gt,l[g(746)],{message:this[g(1067)+g(455)+g(1788)](h)}))}})}[t(848)](r,s){let l=t;this._socket&&this[l(764)][l(848)]({code:r,reason:s})}[t(1347)+t(459)](r,s){this.on(r,s)}[t(872)+t(1003)+t(1484)](r,s){this[t(1078)](r,s)}get[t(1080)+"te"](){let r=t,s={NFcGK:function(l,h){return e[F(474)](l,h)},UuuOy:function(l,h){return l===h},yWxJM:function(l,h){return e[F(513)](l,h)}};if(e[r(1242)](e[r(1527)],e[r(1527)])){let l=0,h=0;for(let g=0;g<_0x3a9385.length;++g)h=_0x1619e5.charCodeAt(g),s[r(1692)](h,128)?l+=1:h<2048?l+=2:s[r(1277)](s[r(661)](64512,h),55296)&&s[r(1277)](s[r(661)](64512,_0x33eb37[r(693)+"At"](g+1)),56320)?(++g,l+=4):l+=3;return l}else return this._socket[r(1080)+"te"]}get binaryType(){let r=t;if(e[r(473)]("LraqG",e[r(1803)]))return this[r(764)].binaryType;{let h=(r(1551)+"0")[r(1738)]("|"),g=0;for(;;){switch(h[g++]){case"0":return l.exports;case"1":if(EXRVTG[r(398)](void 0,s))return s[r(1114)];continue;case"2":var s=_0x2db7a6[_0x1396e1];continue;case"3":_0x9852ea[_0x3cf193](l,l.exports,_0xce7fef);continue;case"4":var l=_0x35edb3[_0x3b9b17]={exports:{}};continue}break}}}set[t(672)+"pe"](r){}get[t(1532)](){return this[t(764)].url}get[t(1514)](){let r=t;return this._socket[r(1514)]}get[t(1038)+"ns"](){let r=t;if(e[r(1540)]("nDnoU",e[r(932)])){let s=_0x469538(_0x177890,_0x23bcce);return _0x49e020[r(1764)][r(1596)](s,s+_0xa1cf4)}else return this[r(764)].extensions}get[t(1375)+t(428)](){let r=t,s={mbysY:function(l,h){return e.pOUCk(l,h)},sUyZs:function(l,h,g){return e[F(381)](l,h,g)}};if(e[r(1570)](r(1166),e.pjxxe)){if(this[r(1444)]&&s[r(1392)](this._ws[r(1080)+"te"],this[r(1437)+"NG"])){this[r(947)+r(1485)](),this._pingPongTimeoutId=s[r(1722)](_0x5c0d56,this[r(618)].bind(this),this._options[r(779)+r(651)]);return}if(!this[r(1444)]||this[r(1444)].readyState!==this[r(1735)])return void this["_handleR"+r(637)]();this[r(1444)]&&this._ws[r(1169)]("hi"),this[r(1714)+r(1182)+r(856)]=s[r(1722)](_0x3ae34e,this[r(544)+r(637)+r(1758)][r(1289)](this),this[r(1070)][r(559)+r(1108)+r(604)])}else return 0}}function Kg(c,r){let s=t,l={tCUvW:function(h,g){return e[F(487)](h,g)},VHMkp:function(h,g,v,S){return h(g,v,S)},hbdHJ:function(h,g){return e[F(1076)](h,g)}};if(e[s(1008)]("XAGiU",e[s(948)])){let h=l[s(1757)](255,_0x5ce0bb);l[s(969)](_0x114cb4,h,_0x2cc177,l[s(1199)](_0x5eea89,_0x54ca56)),_0x33f05e>>>=8,_0x1a1350--}else{if(r)return new r(c.url,c.protocol);if(hi||Bn)return new Wg(c.url,c[s(1514)],c[s(321)]);if(e.djjsJ(gr,xi)&&e[s(461)]!=typeof WebSocket&&WebSocket)return new WebSocket(c[s(1532)],c[s(1514)+"s"])}}function $g(c){let r=t,s=(r(828)+"0").split("|"),l=0;for(;;){switch(s[l++]){case"0":return!1;case"1":if(Bn&&tt[r(1475)+r(1307)])return!0;continue;case"2":if(c)return!0;continue;case"3":if(hi&&wx[r(1475)+r(1307)])return!0;continue;case"4":if(e[r(330)](gr,xi)&&e[r(1367)](e[r(461)],typeof WebSocket)&&WebSocket)return!0;continue}break}}function Gl(c,r,s){let l=t,h={EkXYl:e[l(636)],EcFXb:function(S,w){return e[l(1225)](S,w)}},g=-1;async function v(S){let w=l;return S<=g?Promise[w(1366)](new Error(h[w(1344)])):(g=S,h[w(1095)](S,s[w(1436)])?Promise[w(1241)]():s[S].bind(c)(r,v[w(1289)](null,S+1)))}e[l(691)](v,0)}function ql(c){let r=t,s={ktiRv:function(g,v){return e[F(1350)](g,v)},CMJnZ:function(g,v){return e[F(1645)](g,v)}},l=0,h=0;for(let g=0;g<c[r(1436)];++g)h=c.charCodeAt(g),e[r(935)](h,128)?l+=1:e[r(721)](h,2048)?l+=2:e.WUfmg(64512,h)===55296&&e[r(1472)](64512&c[r(693)+"At"](e.EbZVk(g,1)),56320)?e[r(1636)](r(931),e[r(1102)])?(s[r(1608)](_0x128a21,this["_pingPon"+r(1117)+"Id"]),s[r(1017)](_0x3a37d0,this[r(1714)+r(1182)+r(856)]),this[r(845)+r(1117)+"Id"]=null,this["_reconne"+r(1182)+r(856)]=null):(++g,l+=4):l+=3;return l}function jl(c,r,s){let l=t;if(e.Jicqi(e[l(751)](s,r),1))return"";let h="";for(let g=r;e[l(421)](g,s);){let v=c[g++];if(v<=127)h+=String["fromChar"+l(563)](v);else if(e[l(431)](v,192)&&e[l(1670)](v,224))h+=String[l(624)+l(563)](e[l(976)](e[l(1279)](31,v)<<6,e[l(707)](63,c[g++])));else if(e[l(1435)](v,224)&&v<240)h+=String[l(624)+l(563)](e[l(1629)](e.QOzpz(15&v,12)|e[l(858)](63,c[g++])<<6,63&c[g++]));else if(e[l(561)](v,240)){let S=e[l(610)](e[l(1507)](e[l(747)](e[l(529)](e[l(1346)](7,v),18)|(63&c[g++])<<12,e[l(704)](63,c[g++])<<6),e[l(1023)](63,c[g++])),65536);h+=String["fromChar"+l(563)](e[l(1618)](55296,e[l(1311)](S,10))),h+=String[l(624)+l(563)](56320+e[l(1064)](1023,S))}}return h}function Ua(c,r,s){let l=t,h={iUUAA:e[l(1048)]},g=s,v,S;for(let w=0;e.ObTmm(w,c.length);++w)if(e[l(1520)](e[l(498)],l(841)))if(v=c[l(693)+"At"](w),e.OLzVx(v,128))r[s++]=v;else if(v<2048)r[s++]=e[l(1474)](v,6)|192,r[s++]=e[l(660)](63&v,128);else if(e.XryeK(e[l(1720)](64512,v),55296)&&e[l(463)](64512,S=c.charCodeAt(e.vKjnd(w,1)))===56320){let O=(l(1226)+l(989)).split("|"),N=0;for(;;){switch(O[N++]){case"0":++w;continue;case"1":r[s++]=e[l(707)](63,v)|128;continue;case"2":r[s++]=e[l(775)](e[l(611)](v,6),63)|128;continue;case"3":r[s++]=e[l(864)](e.iLPZn(v>>12,63),128);continue;case"4":v=e[l(1260)](65536,e[l(1055)](e[l(505)](1023,v),10))+(1023&S);continue;case"5":r[s++]=e[l(976)](e[l(1212)](v,18),240);continue}break}}else r[s++]=e[l(1492)](v,12)|224,r[s++]=e[l(1240)](e.EMiYF(v>>6,63),128),r[s++]=e.BDiFS(63,v)|128;else this[l(1444)]&&this._ws[l(1169)](_0x4825c0),this[l(744)](h[l(1683)],_0x1e152a);return s-g}async function Wl(c){let r=t;if(r(1081)==typeof c){let s=new Uint8Array(ql(c));return e[r(1691)](Ua,c,s,0),s}return e[r(424)](c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c[r(386)],c[r(677)+"et"],c.byteLength)}function Vg(c){let r=t;try{return e[r(1367)](e[r(1177)],typeof c)&&(e[r(1035)](c,ArrayBuffer)||c[r(386)]&&e[r(424)](c[r(386)],ArrayBuffer))||e[r(1177)]!=typeof c?"":(JSON[r(427)](c),r(728)+"ion/json")}catch{return e[r(866)](e.QiXyt,typeof c)?"text/pla"+r(956)+r(1206):""}}let Jg=(c,r)=>{let s=t;switch(c){case s(1727):case e[s(449)]:return{[s(380)+c]:1,"x-tt-env":r};default:return{}}};class Zg{constructor(r){let s=t,l={Jhusx:function(h,g){return e[F(1814)](h,g)},jQoQq:function(h,g){return e[F(1082)](h,g)},dDdmr:s(780)+s(780)+s(780)+s(780)};if(e.ZZrzd(s(1772),e[s(795)])){let h=/(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(_0x42d5d1),g=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[s(998)](_0x4cb99e);return h?vJUVOT[s(594)](_0x1bb76e,_0x2b1ed5):g?vJUVOT[s(921)](_0x3ba8a4,_0x5dd0d5):vJUVOT[s(825)]}else this[s(653)+s(1653)]=r,this.count=0}[t(1547)](){let r=t;this[r(1749)]++}[t(1611)+"chMaxCount"](){return this[t(1749)]>=this.maxLossCount}[t(800)+t(1001)](r=0){let s=t;this["maxLossC"+s(1653)]=r,this[s(1749)]=0}}async function Yg(c){let r=t,s={DexlJ:function(l,h){return e[F(366)](l,h)},jcYBT:e[r(1228)],Viarg:e[r(670)],iXNsk:e.CeakO,hjijU:function(l,h){return e[r(1805)](l,h)}};return new Promise(l=>{let h=r;if(!gr)return s.DexlJ(l,s.jcYBT);try{let g=document[h(1296)+h(1715)](s[h(1359)]);window.frontierJSONP=v=>{let S=h;document[S(1258)]["removeCh"+S(1642)](g),window[S(1539)+S(1059)]=void 0,s[S(552)](l,v&&v[S(349)]||s[S(1283)])},g[h(767)]=s[h(1579)],g[h(1786)]=c[h(798)](/^ws/,h(335))+(h(876)+h(750)+"tierJSONP");try{document[h(1258)][h(1164)+"ild"](g)}catch{document.body[h(1464)+h(1642)](g)}}catch{window["frontier"+h(1059)]=void 0,s[h(1432)](l,h(1667)+"reason")}})}function mn(c,r,s){let l=t;return!!c?.find(h=>h[l(957)]===r&&h[l(1272)]===s)}function mr(c,r){let s=t;return c?.[s(1808)](l=>l[s(957)]===r)?.[s(1272)]}let Ha=null;async function Xg(){let c=t;return Ha||(Ha=Promise.resolve()[c(499)](Vt.bind(Vt,e[c(1745)]))),Ha}class Qg extends za{constructor(r,s){let l=t;super(),this._dbName=r,this[l(576)]=s,this[l(892)]=void 0,this[l(605)+l(1268)]=null}async[t(1478)](){await this[t(361)]()}async[t(361)](){let r=t,s={WqhHC:function(l,h){return e[F(1477)](l,h)},zZVEv:e[r(589)]};if(!this._qosDB){if(this[r(605)+r(1268)])return this[r(605)+r(1268)];try{let l=this[r(966)],h=this[r(576)];this["_initPro"+r(1268)]=(async()=>{let g=r,v={QCnkm:e.omiGB,ePBfK:e.vjLuz},{openDB:S}=await e.gGEEJ(Xg);this[g(892)]=await S("frontier_"+l,1,{upgrade(w){let O=g;if(s.WqhHC(O(967),s[O(1159)]))switch(_0x1849fe){case OYVOZU[O(860)]:case OYVOZU[O(1075)]:return{[O(380)+_0x134966]:1,"x-tt-env":_0x4480c5};default:return{}}else w[O(889)+O(562)+"e"](l,{keyPath:h})}})})(),await this["_initPro"+r(1268)]}catch(l){if(e[r(473)](e[r(1170)],e.YdGJH))console.log(l);else return!!this._qosDB}finally{this[r(605)+r(1268)]=null}}}async[t(1473)](r){let s=t;try{return await this[s(361)](),this[s(892)]?.[s(1473)](this[s(966)],r)}catch(l){if(e[s(1455)](e[s(572)],e[s(572)])){let h=_0x585415[s(1764)],g=_0x3a05c1[s(1161)],v=_0x3c148e[s(1077)],S=g+_0x55116f;if(e[s(394)](S,h[s(1436)])){let w=new _0x1c8030(e[s(1209)](2,S));w.set(h),_0x403c3a[s(1764)]=w}return _0x220bb5[s(1161)]=S,e[s(694)](S,v)&&(_0x425e13[s(1077)]=S),g}else console[s(1254)](l)}}async[t(882)](r,s){let l=t;return await this[l(361)](),this._qosDB?.[l(1770)](this[l(966)],r)}async[t(1053)](r){let s=t;try{return await this._init(),this._qosDB?.[s(1337)](this[s(966)],r)}catch(l){console[s(1254)](l)}}async[t(517)](){let r=t,s={pnwuD:function(l,h){return e[F(1500)](l,h)},jbaxp:function(l,h){return l>=h}};try{return e.aWiGT(e[r(1781)],e.Ekmjz)?(await this._init(),this._qosDB?.[r(517)](this._dbName)):(_0x353a51|=0,{low:_0x44c6f4,high:AsZeSx[r(1530)](_0x4a0639,31),unsigned:AsZeSx[r(1e3)](_0x1014f3,0)})}catch(l){console[r(1254)](l)}}async keys(){let r=t;return await this._init(),this[r(892)]?.[r(408)+"ys"](this._dbName)}async getAll(){let r=t;return await this._init(),this._qosDB?.[r(488)](this[r(966)])}async closeDB(){let r=t;try{this[r(892)]?.[r(848)](),this[r(892)]=void 0}catch(s){console.log(s)}}get[t(571)](){let r=t;try{if(e[r(1115)]===e[r(928)])this[r(784)+r(537)]=_0xa7637c,this[r(1444)]&&(this._ws.binaryType=_0x3b0514);else return!!this._qosDB}catch(s){return console[r(1254)](s),!1}}}class em{constructor(r,s){let l=t;if(e[l(1008)](e[l(1138)],e[l(644)]))this[l(401)]=r,this._pathKey=s,this[l(892)]=localStorage;else return e[l(1806)](_0x3f1761,e[l(1559)](_0x862434,_0x45779e))}async[t(1478)](){}get _prefix(){return"frontier_"+this[t(401)]}async get(r){let s=t,l=this[s(892)][s(645)](this[s(1517)]);return JSON[s(427)](e[s(330)](l,"{}"))[r]}async set(r,s){let l=t;if(e[l(333)](e[l(988)],e.gUbCd)){let h="0|3|1|4|2"[l(1738)]("|"),g=0;for(;;){switch(h[g++]){case"0":if(!_0x66b929)return _0x2d83a3;continue;case"1":if(_0x3fb663[l(942)+"e"])return _0x291374[l(942)+"e"](_0x42176e,_0x341444)+_0x3ea9d9;continue;case"2":return e[l(680)](e[l(1691)](_0x2b9083,_0x45bea5,_0x94e2ae,_0x14bd81),_0xcb37c);case"3":if(_0x2082e2[l(1436)]<40)return e.ScNYW(_0x48c2a4(_0x5f3c41,_0x521b30,_0x3c2bc1),_0x47d44d);continue;case"4":if(_0x2e13bc[l(1688)])return _0x1894a9.write(_0x1f8ed0,_0x30e316)+_0x4ea1e5;continue}break}}else{let h=this[l(892)][l(645)](this[l(1517)]),g=JSON[l(427)](h||"{}");return g[s||r[this._pathKey]]=r,this[l(892)].setItem(this[l(1517)],JSON.stringify(g)),s||r[this[l(482)]]}}async[t(1053)](r){let s=t,l={zMEFB:function(h,g){return e[F(854)](h,g)},onNxL:function(h,g){return e.EMiYF(h,g)},xSAko:function(h,g){return h>>>g},bnuZF:function(h,g){return e[F(840)](h,g)}};if(e[s(1662)](e.HUIPs,e[s(803)])){let h=this[s(892)][s(645)](this[s(1517)]),g=JSON[s(427)](e[s(330)](h,"{}"));return g[r]=void 0,this[s(892)].setItem(this[s(1517)],JSON[s(1777)+"y"](g))}else{let h=this[s(1657)],g=this[s(682)];return[ZntqLP[s(1761)](255,g),ZntqLP.onNxL(ZntqLP[s(1145)](g,8),255),ZntqLP[s(1761)](ZntqLP[s(1145)](g,16),255),ZntqLP.xSAko(g,24),ZntqLP.zMEFB(255,h),ZntqLP[s(1591)](h>>>8,255),ZntqLP[s(1591)](h>>>16,255),ZntqLP.bnuZF(h,24)]}}async[t(517)](){return this[t(892)].clear()}async keys(){let r=t,s=this[r(892)][r(645)](this[r(1517)]),l=JSON[r(427)](s||"{}");return Object[r(1542)](l)}async[t(488)](){let r=t,s=this[r(892)][r(645)](this[r(1517)]),l=JSON[r(427)](e[r(1731)](s,"{}"));return Object[r(1322)](l)}[t(432)](){return Promise[t(1241)]()}get[t(571)](){return!!this[t(892)]}}class tm{constructor(r,s){let l=t;this[l(401)]=r,this[l(482)]=s,this._qosDB=Bn?tt:hi?wx:null}async[t(1478)](){}get _prefix(){let r=t;return r(827)!==e.vOuuB?this[r(764)][r(1514)]:r(1539)+"_"+this[r(401)]}async[t(1473)](r){let s=t,l=this[s(892)]["getStora"+s(1305)](this[s(1517)]);return JSON.parse(e[s(1751)](l,"{}"))[r]}async[t(882)](r,s){let l=t;if(l(1264)===l(1264)){let h=this[l(892)][l(1569)+l(1305)](this._prefix),g=JSON[l(427)](h||"{}");return g[s||r[this[l(482)]]]=r,this[l(892)][l(582)+l(1305)](this[l(1517)],JSON[l(1777)+"y"](g)),s||r[this[l(482)]]}else return _0x1f777b?_0x1afe49[l(833)+l(1360)](_0x494429,_0x3dc5ec):_0x59270a[l(833)+l(1399)](_0x500729,_0x1e4dca)}async[t(1053)](r){let s=t,l=this[s(892)][s(1569)+s(1305)](this[s(1517)]),h=JSON[s(427)](e[s(1483)](l,"{}"));return h[r]=void 0,this[s(892)][s(582)+"geSync"](this[s(1517)],JSON[s(1777)+"y"](h))}async[t(517)](){return this[t(892)].clearStorageSync()}async[t(1542)](){let r=t,s=this[r(892)][r(1569)+r(1286)+"nc"](this[r(1517)]),l=JSON[r(427)](e.ObWdF(s,"{}"));return Object[r(1542)](l)}async[t(488)](){let r=t,s=this[r(892)][r(1569)+"geInfoSync"](this[r(1517)]),l=JSON[r(427)](e[r(1021)](s,"{}"));return Object[r(1322)](l)}[t(432)](){return Promise[t(1241)]()}get[t(571)](){return!!this[t(892)]}}function Kl(c,r){let s=t;if(e[s(330)](Bn,Bn))return new tm(c,r);if(e.djjsJ(gr,xi)&&e.CbtOC("undefined",typeof indexedDB))return new Qg(c,r);if((gr||xi)&&e[s(1367)](e[s(461)],typeof localStorage))return new em(c,r);throw new Error(e.wrCwI)}class nm{constructor(){let r=t;this[r(1674)+r(627)+"Id"]=null,this[r(1674)+"l"]=36e5,this._qosDB=Kl(e[r(1752)],r(1156)+"id")}async[t(1674)+"lFlush"](){let r=t,s={IrMax:function(l,h,g){return e[F(1461)](l,h,g)},UdiMR:function(l,h){return e[F(1400)](l,h)},CnhQV:r(1678),Nsksn:r(1439)};e[r(1457)](clearInterval,this[r(1674)+r(627)+"Id"]),this._intervalTimeoutId=e[r(765)](setInterval,()=>{let l=r;s[l(1605)]===s[l(1506)]?(eobDFe[l(1412)](_0x24810a,_0x42c4db,24),eobDFe[l(1412)](_0x367718,_0x27d3e8,eobDFe.UdiMR(_0x150d5a,_0x34f2e1))):this["flushExp"+l(609)]()},this[r(1674)+"l"])}async[t(1478)](){let r=t;await this[r(892)].openDB()[r(499)](()=>{let s=r;this[s(1674)+s(974)]()})}async["flushExp"+t(609)](){let r=t;(await this[r(892)]?.[r(488)]()||[])[r(370)](({timestamp:h})=>h<Date[r(690)]()).forEach(h=>{let g=r;this[g(892)]?.del(h[g(1156)+"id"])})}async del(r){let s=t;return this[s(892)]?.[s(1053)](r)}async[t(882)](r,s){let l=t;return this[l(892)]?.[l(882)]({message_id:r,timestamp:s})}async[t(1473)](r){let s=t,l={VtxGc:e[s(1443)],jADtj:function(h,g,v){return e[s(640)](h,g,v)}};if(e[s(329)](e[s(735)],e[s(629)]))this[s(1780)](moqKeT.VtxGc,moqKeT[s(711)](_0x2feda9,moqKeT[s(1282)],{..._0x446209}));else return this[s(892)]?.[s(1473)](r)}async closeDB(){let r=t;e[r(489)](clearInterval,this[r(1674)+r(627)+"Id"]),await this._qosDB?.[r(432)]()}get isReady(){let r=t;return this[r(892)]?.[r(571)]}}function Ga(c){let r=t,s=!!this[r(1070)][r(1519)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=mn(c[r(853)][r(321)],e[r(1766)],"2"),h=l&&e.YmnZJ(mn,c[r(853)][r(321)],r(375)+r(1298)+"ck","1"),g=l&&e[r(1125)](mn,c.message[r(321)],e[r(859)],"1"),v=g?e[r(527)](mr,c[r(853)][r(321)],r(375)+"er_ack_m"+r(1418))?.split(",")[r(370)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:g,ackMsgIds:v}}async function $l(){let c=t;return this[c(664)+"ger"]||(this[c(664)+c(697)]=new nm),this[c(664)+c(697)][c(571)]||await this[c(664)+c(697)][c(1478)](),this[c(664)+c(697)]}async function rm(c,r){let s=t,{enableAutoAck:l}=this._options,h=e.DjXHz(mn,c[s(853)][s(321)],e[s(1354)],"1"),g=e.rxKyw(mn,c[s(853)][s(321)],e[s(350)],"1"),v=Ga.call(this,c);if(l&&h){let{SeqID:S,LogID:w,service:O,LogIDNew:N,method:B}=c.message;this[s(430)]({SeqID:S,LogID:w,LogIDNew:N,service:O,method:B,headers:[{key:e[s(350)],value:"1"},{key:e[s(862)],value:e.kRGGX(N,"")},{key:e[s(1661)],value:"0"}]})}g&&!v[s(388)]&&this[s(339)+s(1467)+s(599)](c),r()}async function im(c,r){let s=t;s(850)!==e.SPzkH?(this._debug(e[s(916)],c[s(853)]),r()):this[s(1780)](s(848),e[s(1355)](_0x15fed6,s(848),{..._0xb02c8}))}async function sm(c,r){let s=t,l=Lt(await Wl(c.data));try{if(e[s(424)](l[s(403)],Uint8Array)){let h=e.TVtfS(this._options[s(1787)+"ncoding"],Object)?{force:!!this[s(1070)][s(1787)+s(501)][s(586)],encoding:this[s(1070)][s(1787)+s(501)][s(1134)]?this[s(1070)][s(1787)+s(501)][s(1134)][s(798)](/\s/g,"")[s(1650)+s(485)]():""}:{force:!1,encoding:this[s(1070)][s(1787)+s(501)]?this[s(1070)][s(1787)+s(501)][s(798)](/\s/g,"")[s(1650)+s(485)]():""},g=l[s(1787)+s(501)]?l[s(1787)+s(501)].replace(/\s/g,"")[s(1650)+s(485)]():"",v=e[s(424)](this[s(1070)].payloadType,Object)?{force:!!this[s(1070)][s(490)+s(537)].force,type:this[s(1070)][s(490)+s(537)].type?this[s(1070)][s(490)+s(537)][s(767)][s(798)](/\s/g,"")[s(1650)+"ase"]():""}:{force:!1,type:this[s(1070)][s(490)+"ype"]?this[s(1070)][s(490)+s(537)][s(798)](/\s/g,"")["toLowerC"+s(485)]():""},S=l[s(490)+s(537)]?l["payloadT"+s(537)].replace(/\s/g,"")[s(1650)+s(485)]():"",w=v[s(586)]?v.type:S||v[s(767)],O=h[s(586)]?h.encoding:g||h[s(1134)],N=[e[s(742)],e[s(1812)],e.sLXDa,e[s(1177)]],B=[e[s(506)],e.ACgEt];this[s(1070)][s(1454)+s(982)+s(950)+"ad"]&&N.includes(w)&&(!O||B[s(1329)](O))?l[s(511)+s(1428)]=e[s(1125)](jl,l[s(403)],0,l.payload.byteLength):l[s(511)+"oad"]=""}else l[s(511)+s(1428)]=""}catch(h){l[s(511)+"oad"]="",console.log(h)}c[s(853)]=l,e[s(1456)](r)}function om(c,r,s){let l=t,h={brzlH:function(g,v){return g<v},XdhFk:function(g,v){return e.QmxLn(g,v)},FtUun:function(g,v){return e.kqYPB(g,v)},LvBRc:function(g,v){return e[F(1252)](g,v)},QyyJn:function(g,v){return e[F(568)](g,v)}};if(l(556)!==e[l(762)])return!!this[l(892)];{let g=e.djjsJ(s,8192),v=e[l(1498)](g,1),S=null,w=g;return function(O){let N=l;if(h[N(1575)](O,1)||h[N(1020)](O,v))return h[N(1197)](c,O);h[N(1043)](w,O)>g&&(S=c(g),w=0);let B=r[N(358)](S,w,w+=O);return h[N(1502)](7,w)&&(w=h[N(1043)](7|w,1)),B}}}let am=4294967295;function cm(c,r,s){let l=t;return RangeError(e.sXccp(e[l(901)](e[l(1647)](e[l(443)](e[l(1647)](e.rrURs,c),e[l(442)]),e[l(1019)](r,1)),e[l(880)]),s))}function dm(c,r,s){let l=t;if(s>am)throw new Error(e.UZwTe);let h=3;for(;e[l(619)](h,0);){let g=255&s;e[l(1125)](ja,g,c,e[l(1044)](r,h)),s>>>=8,h--}return e[l(446)](r,4)}function lm(c,r){let s=t,l=0,h=r,g=e[s(857)](r,4);for(;e.kGFKc(h,g);){let{value:v,offset:S}=qa(c,h);h=S,l=e[s(647)](e.hUzsG(l,8),0),l+=v}return{value:l,offset:g}}function um(c,r,s){let l=t;return c?c[l(1436)]<40?e[l(443)](e.YmnZJ(Ua,c,r,s),s):r[l(942)+"e"]?r.utf8Write(c,s)+s:r.write?e.tXtIu(r[l(1688)](c,s),s):e[l(1647)](Ua(c,r,s),s):s}function fm(c,r){let s=t,l=new de(e[s(1499)](e[s(1689)](c[e.xBSaO(r,4)]<<24,c[r+5]<<16),c[e[s(633)](r,6)]<<8)|c[e[s(1736)](r,7)],e[s(1507)](e[s(390)](e[s(356)](c[e.NRAyE(r,0)]<<24,e[s(1031)](c[e[s(1534)](r,1)],16)),c[e[s(1686)](r,2)]<<8),c[e[s(418)](r,3)]),!0);return r+=8,{value:l,offset:e[s(925)](r,8)}}function hm(c,r,s){let l=t,h=c[l(682)],g=c.high;return r[s]=e[l(1336)](g,24),r[s+1]=g>>>16&255,r[e.ctuYQ(s,2)]=e[l(1510)](e[l(792)](g,8),255),r[e[l(1127)](s,3)]=e.SqVRJ(255,g),r[s+4]=e[l(1679)](h,24),r[e[l(1534)](s,5)]=e[l(1582)](h,16)&255,r[s+6]=e[l(345)](h,8)&255,r[s+7]=e[l(1479)](255,h),s+=8,s}function qa(c,r){let s=t;if(e[s(1373)](s(1792),e.BqlqB))return c[s(1430)+"8"]?{value:c[s(1430)+"8"](r),offset:e[s(1686)](r,1)}:{value:e[s(1357)](255,c[r]),offset:e.nXrfX(r,1)};_0x173556[s(1539)+s(1059)]=void 0,_0x575538(e.aQRAC)}function ja(c,r,s){let l=t;return r[l(1767)+"t8"]?r[l(1767)+"t8"](c,s):r[s]=e[l(1672)](255,c),e[l(1736)](s,1)}let xm=function(c){let r=t;if(e.yWent(r(1110),e[r(1495)]))_0x5336f6=_0x23a1e9[r(494)](_0x4e412d),_0x978def=_0x565991.concat(_0x1ca7b4[_0x512f78]);else return new Uint8Array(c)},pm=t(1136)+"d"!=typeof Buffer?Buffer[t(978)+t(354)]:e.fXfci(om,xm,Uint8Array[t(1640)+"e"][t(1596)]),gm=16,Wa=32;function mm(c){let r=t,s=0,l={};for(let h=0;h<c[r(1436)];h++)l[c[h][r(984)+"ame"]]=e[r(1682)](ql,c[h][r(984)+"ame"]),s+=e.dzcsa(14,l[c[h][r(984)+r(1549)]]);return[s,l]}function Vl(c,r,s){let l=t,[h,g]=e.IQVdV(mm,c),v=e[l(1814)](pm,h),S=0;return c[l(1521)](w=>{let O=l,N=e[O(1074)][O(1738)]("|"),B=0;for(;;){switch(N[B++]){case"0":console[O(1254)](e.bJxMq,S);continue;case"1":console[O(1254)](e.kszxa,S);continue;case"2":S=um(w[O(984)+O(1549)],v,S);continue;case"3":console.log(e[O(395)],S);continue;case"4":console.log(O(406),S);continue;case"5":S=e[O(1638)](dm,v,S,w[O(626)]||0);continue;case"6":console.log(e[O(1047)],w,w[O(626)]);continue;case"7":S=e[O(1740)](ja,g[w[O(984)+O(1549)]],v,S);continue;case"8":S=hm(de[O(1324)+"er"](w[O(1496)]||r),v,S);continue;case"9":console.log(O(626),S);continue;case"10":S=e[O(1638)](ja,0,v,S);continue}break}}),{frameType:Wa,headers:[{key:e[l(1614)],value:s}],payload:v}}function wm(c){let r=t,s=0,l=[];for(;s<c[r(1351)+"th"];){let{offset:h}=e.oHjAO(qa,c,s);s=h;let g={cursor_name:"",cursor:0,service:0},{value:v,offset:S}=e[r(1183)](lm,c,s);g[r(626)]=v,s=S;let{value:w,offset:O}=e[r(467)](qa,c,s);s=O,g[r(984)+r(1549)]=e.zLRJX(jl,c,s,e[r(1127)](s,w)),s+=w;let{value:N,offset:B}=fm(c,s);g[r(1496)]=N[r(1266)](),s=B,l.push(g)}return l}function _m(){let c=t;return e[c(1706)](e[c(1333)],e[c(1333)])?{frameType:Wa,headers:[{key:e.LAjoi,value:e[c(702)]}],payload:void 0}:this[c(892)][c(1553)+c(1026)]()}class ym{constructor(r,s,l){let h=t;this[h(1086)+h(1726)]=r,this["_cursorF"+h(598)]=s,this[h(1723)+h(811)]=l,this[h(892)]=Kl(this[h(1086)+h(1726)],h(984)+"ame")}async[t(1478)](){let r=t;await this[r(892)][r(1478)]()}async[t(1526)+"rs"](){let r=t;if(!this[r(892)][r(571)])return;let s=this["_message"+r(811)],l=await this[r(892)][r(488)]();switch(console.log(e.CVxLe,l),s){case"ALL":return l&&l[r(1436)]?e.rxKyw(Vl,l,0,this[r(896)+r(598)]):void 0;case r(1150):return;case r(655):return l&&l[r(1436)]?e[r(1638)](Vl,l,0,this._cursorFileName):e[r(332)](_m)}}async[t(882)](r,s,l){return console[t(1254)](e.bZqbf,r,s,l),this._qosDB.set({cursor_name:r,cursor:s,service:l})}async setCursors(r){let s=t,l=e.HjuPV(wm,r);for(let h of l)console.log(s(915)+"r",l),await this[s(892)][s(882)](h)}async get(r){let s=t;return(await this._qosDB[s(1473)](r))?.[s(1496)]}async[t(432)](){await this[t(892)].closeDB()}[t(425)+t(649)+t(1675)](r){let s=t;this["_cursorF"+s(598)]=r}get[t(571)](){let r=t;return this[r(892)][r(571)]}}let bm=t(1356)+t(588);async function Jl(c){let r=t;if(!this[r(1070)][r(1519)+"S"])return null;let{aID:s,fpID:l,messageStrategy:h}=this._options,g=e[r(1005)](c,bm);try{return this[r(1424)+"anager"]?c&&this[r(1424)+r(1132)][r(425)+r(649)+r(1675)](c):this[r(1424)+"anager"]=new ym(l+"_"+s+"_"+g,g,h),this["_cursorM"+r(1132)][r(571)]||await this._cursorManager[r(1478)](),this[r(1424)+r(1132)]}catch{return null}}async function Em(c,r){let s=t;if(e[s(1376)](s(923),e[s(1265)])){let l=e[s(1724)](mn,c.message[s(321)],"code","-1"),h=e[s(1341)](mn,c[s(853)][s(321)],e[s(350)],"1"),g=mr(c[s(853)].headers,e[s(794)]),v=e[s(905)](Number,e[s(416)](mr,c.message[s(321)],e[s(1280)]))||0,S=Ga[s(358)](this,c),w=e.eXvbS(mn,c.message[s(321)],e[s(1733)],"2"),O=mr(c[s(853)][s(321)],s(1187)+s(737)+"e"),N=e[s(1790)](Number,mr(c[s(853)][s(321)],e[s(1668)]));if(S[s(388)])return e.MVQEv(r);let B=S[s(525)+s(414)]?await $l.call(this):null;if(c.message[s(626)]>0&&h&&!l||e[s(383)](c[s(853)][s(626)],0)){if(g&&S[s(525)+s(414)]&&B)if(e[s(909)](e[s(456)],e[s(1529)])){if(!!!await B.get(g))if(e[s(865)](e.cPCxz,s(839))){_0x1e6979(_0x407550,42);let j=e[s(332)](_0x1a0097);e[s(1468)](_0x11096f,_0x44ac90,j),_0x201d45(_0x4108c2,j[s(1077)]),e[s(1414)](_0x494d57,_0x2a3eb1,j),_0x5effc7(j)}else this[s(339)+s(1513)+"Event"](c),await B[s(882)](g,e[s(875)](Date[s(690)](),v));return r()}else return e.otXkx(-1,this.low)&&e[s(1810)](-1,this[s(1657)])?_0x4ff951[s(341)](0,0,this[s(1440)]):this.low===-1?_0x1e8640[s(341)](0,e.EbZVk(this[s(1657)],1),this.unsigned):_0x15ce09[s(341)](e.ZfRyt(this[s(682)],1),this[s(1657)],this[s(1440)]);if(w){let K=await Jl[s(358)](this);if(!K)return this[s(339)+s(1513)+"Event"](c),r();let j=await K[s(1473)](O)??-1;if(e.xmUGN(j,N))this[s(339)+s(1513)+s(1567)](c),K.set(O,N,c[s(853)][s(626)]);else throw new Error(s(546)+" message cursor "+N+(s(549)+"than local cursor ")+j);return e.YMHep(r)}return this[s(339)+s(1513)+s(1567)](c),r()}}else return this["currentE"+s(1033)+s(936)+"t"]++,this["getCurre"+s(575)+"nt"]()}async function vm(c,r){let s=t;if(e[s(1109)](e[s(973)],"fkrwe")){let l=Ga[s(358)](this,c);if(!l[s(525)+"sage"])return e[s(1302)](r);let h=await $l[s(358)](this);if(l[s(331)+s(1546)+s(1788)]&&l[s(996)+"s"][s(1436)])for(let g of l[s(996)+"s"])await h.del(g);r()}else return _0x445c9e[s(888)](_0x2ef6ec(this),_0x4293c6),_0x3b6b4f(_0x108f9b.get(this))}async function Sm(c,r){let s=t,l=e.SgwLS(c[s(853)][s(1469)+"e"],gm),h=e[s(836)](c[s(853)][s(1469)+"e"],Wa);if(!l&&!h)return e[s(1541)](r);let g=e[s(685)](mr,c[s(853)].headers,s(979)+s(1025));if(!g)return e.yLjMA(r);let v=await Jl.call(this,g);if(!v)return e[s(1665)](r);if(l){let S=await v.getCursors(),w={frameType:S?.[s(1469)+"e"],SeqID:de[s(1324)+"er"](this[s(1032)]++),LogID:de[s(1324)+"er"](this[s(1070)].logIDGenerator()),service:9e3,method:5,headers:S?.[s(321)],payload:S?.[s(403)]},O=y(w);this[s(1444)]&&this._ws[s(1080)+"te"]&&this[s(1444)][s(1169)](O)}if(h){let S=c.message[s(403)];S&&v[s(617)+"rs"](S)}}let Im=async function(c,r){let s=t;this._isInit=!1,e[s(1369)](clearTimeout,this["_connect"+s(963)+s(638)]),e[s(1648)](r)},Am=async function(c,r){let s=t;if(!this._ws||this[s(1444)][s(1080)+"te"]!==this[s(1735)])return r();let{pingInterval:l}=this[s(1070)];this["_endpoin"+s(634)]?.[s(913)+s(1533)+s(378)]();for(let g=0;e.dURxG(g,this[s(1723)+s(1538)][s(1436)]);g++){let v=this["_message"+s(1538)][g];if(e[s(1810)](this[s(1444)][s(1080)+"te"],this[s(1735)])&&e[s(340)](null,v))this[s(1444)]&&this[s(1444)][s(1169)](v),this[s(1723)+s(1538)][g]=null;else break}this["_message"+s(1538)]=this._messageQueue[s(370)](g=>!!g),this[s(845)+s(1117)+"Id"]=setTimeout(()=>this[s(618)](),l),this[s(339)+s(613)+"nt"](c),this[s(404)+"er"]&&this[s(1444)]&&(this[s(1444)][s(672)+"pe"]=this["_binaryT"+s(537)]);let h=this["_endpoin"+s(634)]?.[s(429)+s(575)+"nt"]();this[s(744)](s(1619)+h+" success"),e[s(1603)](r)},km=async function(c,r){let s=t,l=this[s(1654)+s(634)]?.[s(429)+s(575)+"nt"]();this._debug(s(1619)+l),r()};class Cm extends za{constructor(r){let s=t,l={prmml:function(S,w){return e[F(1470)](S,w)},nsNCM:function(S,w,O){return S(w,O)},KJfHH:e.WCtKg,cSpLM:function(S,w,O){return e[F(545)](S,w,O)},zNCnp:e[s(507)],OnFCy:function(S,w){return S!==w},XUCup:function(S,w){return e[s(1725)](S,w)},fsoaG:function(S,w){return S!==w},wvZbz:function(S,w){return e[s(1677)](S,w)},qWxCJ:function(S,w){return e.rZCyU(S,w)},FHNHH:function(S,w){return e[s(1421)](S,w)},SzUuF:function(S,w){return e.zgzFl(S,w)}};super(),this._miniNavigatorOnline=!0,this[s(404)+"er"]=gr,this[s(1719)]=jg,this[s(1480)+"T"]=Bn,this[s(1748)+"X"]=hi,this._isWorker=xi,this[s(1723)+s(1538)]=[],this[s(1654)+s(634)]=null,this[s(423)+s(531)]=!1,this[s(784)+"ype"]=s(1131)+"fer",this[s(654)+s(951)]=!1,this[s(654)+"ionTimeo"+s(638)]=null,this[s(1714)+s(1182)+s(856)]=null,this[s(845)+s(1117)+"Id"]=null,this[s(1032)]=0,this[s(1750)]=!1,this[s(1148)]="",this[s(664)+s(697)]=null,this["_cursorM"+s(1132)]=null,this["_pingLos"+s(1009)]=null,this[s(1606)+"ls"]=e[s(851)],this[s(1585)]=3,this.CONNECTING=0,this.OPEN=1,this[s(1804)]=2,this._onOpen=S=>{let w=s,O={ywKpJ:e[w(1655)],kLnWp:w(818)};try{e[w(1610)](Gl,this,S,[Im,Am,km])}catch(N){if(e[w(1583)](w(835),e[w(560)])){let B=e[w(1160)](gt,e[w(1211)],{message:N[w(853)],code:gn[w(874)+"OR"],error:N});this["_dispatc"+w(1697)+w(1649)](B)}else this[w(1501)+w(1009)]?.[w(1547)](),this[w(1780)](O[w(1045)],O[w(1073)]),this[w(1501)+w(1009)]?.[w(1611)+"chMaxCount"]()?this[w(544)+w(637)]():this[w(618)]()}},this[s(1121)+"ge"]=async S=>{let w=s,O={OgrOD:function(K,j){return e.Tivzx(K,j)}},{pingInterval:N,pingFrequency:B}=this[w(1070)];if((e[w(1153)]("hi",S.data)&&w(1144)===B||e[w(1626)](w(1548),B))&&(this[w(947)+w(1485)](),this.emit(e[w(581)],e[w(1775)]),this[w(845)+w(1117)+"Id"]=e[w(1681)](setTimeout,this[w(618)][w(1289)](this),N)),!e[w(926)]("hi",S[w(887)]))try{if(e[w(1700)]("DhDUn",e[w(1564)]))e.rxKyw(Gl,this,S,[sm,rm,vm,Sm,Em,im]);else{let K=this._qosDB[w(645)](this._prefix),j=_0x2e5959[w(427)](JDMPsc[w(1643)](K,"{}"));return _0x54ff7b[w(1542)](j)}}catch(K){let j=e[w(793)](gt,e[w(1211)],{message:K[w(853)],code:gn[w(1658)+"ERROR"],error:K});this[w(339)+w(1697)+w(1649)](j)}},this[s(986)]=S=>{let w=s,O=this["_endpoin"+w(634)]?.["checkRea"+w(1152)+"es"](),N=this["_endpoin"+w(634)]?.[w(429)+w(575)+"nt"]();if(O&&!S[w(853)]){let B=w(758)+N+(w(1141)+"ax retri"+w(908)+"ed");this[w(339)+"hErrorEv"+w(1649)](e.WWPif(gt,e[w(1211)],{message:B,code:gn[w(824)+"IES_ERROR"],error:S}));return}this._ws&&e[w(1225)](this[w(1444)][w(1080)+"te"],this[w(1735)])&&this["_disconn"+w(1058)](),this["_dispatc"+w(1697)+w(1649)](gt(e.OdXLv,{message:S[w(853)],code:gn.NATIVE_ERROR,error:S}))},this[s(1631)]=async S=>{let w=s;this[w(838)+"mer"](),this[w(947)+"ngTimer"](),this[w(1285)+w(1090)+"rs"](),this[w(1444)]=null,this["_connect"+w(951)]=!1;let O=this["_endpoin"+w(634)]?.[w(1611)+w(1152)+"es"]();if(!O&&this[w(1791)+w(1107)]()&&!this._readyClosed)if(l.prmml(w(509),"BPIsT")){let N=this["_endpoin"+w(634)]?.[w(429)+w(575)+"nt"](),B=this[w(1070)][w(387)+w(433)+"ptor"](S.code,S[w(1037)]);this["_dispatc"+w(1405)+"ent"](l[w(823)](It,l[w(949)],{code:1006,reason:S[w(1037)]||"connecti"+w(1185)+w(532)+w(938)+w(863)+w(1592)+N,willReconnect:B})),B&&this._connect();return}else return this[w(764)].url;if(l.prmml(1e3,S[w(1411)])&&this[w(423)+"osed"]){this["_dispatc"+w(1405)+"ent"](l[w(1278)](It,l[w(949)],{code:1e3,reason:l[w(1762)]})),this[w(1654)+w(634)]?.["resetEnd"+w(1533)+w(378)](),this[w(1501)+w(1009)]?.[w(800)+"nter"]();return}if(l[w(700)](1e3,S.code)&&O){let N=this[w(1654)+w(634)]?.["getCurre"+w(575)+"nt"](),B=S.reason;B||(B=await l[w(810)](Yg,this[w(1148)])),B="connecti"+w(1185)+w(646)+B+(", hostna"+w(1613))+N+(w(468)+w(696)+"ached"),this["_dispatc"+w(1405)+w(1649)](l[w(1278)](It,l[w(949)],{code:S[w(1411)],reason:B}));let K=w(758)+N+(" fail, m"+w(1157)+w(908)+"ed");this[w(339)+w(1697)+"ent"](gt("error",{message:K,code:gn[w(824)+w(843)+"R"]})),this[w(1654)+w(634)]?.["resetEnd"+w(1533)+w(378)](),this[w(1501)+w(1009)]?.[w(800)+w(1001)]();return}if(l.fsoaG(1e3,S[w(1411)])&&!S[w(1037)]){let N=this["_endpoin"+w(634)]?.[w(429)+w(575)+"nt"]();this[w(339)+w(1405)+w(1649)](l.cSpLM(It,l[w(949)],{code:S.code,reason:w(717)+w(1185)+w(532)+w(938)+w(863)+w(1592)+N})),this[w(1654)+w(634)]?.[w(913)+w(1533)+"fig"](),this["_pingLos"+w(1009)]?.[w(800)+w(1001)]();return}this[w(339)+"hCloseEv"+w(1649)](S),this["_endpoin"+w(634)]?.[w(913)+w(1533)+"fig"](),this[w(1501)+w(1009)]?.[w(800)+w(1001)]()},this[s(391)]=null,this[s(1705)]=null,this.onmessage=null,this.onopen=null,this.onStartReconnect=null,this[s(1776)+s(1621)]=null,this[s(1550)+s(995)+s(1227)+"ct"]=null,this["_handleO"+s(1452)]=this[s(632)+s(1452)][s(1289)](this),this[s(632)+"ffLine"]=this[s(632)+"ffLine"][s(1289)](this),this[s(1151)+"ageHide"]=this[s(1151)+s(1459)][s(1289)](this),this[s(1151)+"ageShow"]=this[s(1151)+"ageShow"][s(1289)](this),this[s(1070)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1040)](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.ZUPMa,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e.GqLrT,env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:g}=r,v=Array[s(448)](h)?h:e[s(866)](e[s(1177)],typeof h)?[h]:[];if(!v||e.XFfTa(0,v[s(1436)]))throw new Error(s(816)+"rovide v"+s(469));if(!e[s(1204)]($g,g))throw new Error(e[s(709)]);Object[s(1267)](this[s(1070)],r),this["_endpoin"+s(634)]=new Hl(v,this[s(1070)].maxRetries),this["_pingLos"+s(1009)]=new Zg(this[s(1070)][s(768)+"Count"]),this._options[s(971)+s(1208)]&&(e[s(528)]("QVZXG",e[s(667)])?(this[s(1750)]=!0,this[s(654)]()):(_0x4a9dec=dsYJZr[s(1093)](_0x204e25,_0x4deb3c),_0x14a406=dsYJZr[s(1389)](127,_0x52217b),dsYJZr[s(821)](128,_0x446d08)&&(_0x221984=dsYJZr[s(1093)](_0x3d9ca6,_0x35cd0a),_0x1da189|=dsYJZr[s(481)](dsYJZr.FHNHH(127,_0x2c8dca),7)))),this[s(1070)].listenNetworkChanged&&(this[s(1480)+"T"]||this[s(1748)+"X"]?this[s(1118)+s(1380)+s(1124)]():this._isBrowser&&this[s(1441)+s(512)+"Listener"]())}[t(632)+t(1452)](){let r=t;this[r(1070)][r(1281)+"utoRecon"+r(964)]||this["_readyCl"+r(531)]||this[r(544)+r(637)]()}[t(632)+"ffLine"](){let r=t;this[r(1423)+r(740)+"t"]();let s=e[r(1054)](Ba,e.jsqYl,{message:e[r(676)]});this[r(1550)+r(995)+r(1227)+"ct"]&&this[r(1550)+r(995)+"yReconnect"](s)}[t(1441)+t(512)+"Listener"](){let r=t;e[r(1219)]!==r(1255)?(this._isBrowser&&window[r(1347)+"Listener"](r(1269),this[r(632)+r(1452)]),this[r(404)+"er"]&&window[r(1347)+"Listener"](e.njokO,this[r(632)+r(623)]),this[r(404)+"er"]&&window[r(1347)+r(459)](r(565),this[r(1151)+r(1459)]),this[r(404)+"er"]&&window[r(1347)+r(459)](e.WwZcC,this[r(1151)+r(320)])):this[r(1386)+r(1033)+r(936)+"t"]=0}["_dropGlo"+t(512)+t(459)](){let r=t;this[r(404)+"er"]&&window[r(872)+r(1003)+r(1484)](e[r(363)],this["_handleO"+r(1452)]),this[r(404)+"er"]&&window[r(872)+r(1003)+r(1484)](e[r(1246)],this[r(632)+r(623)]),this[r(404)+"er"]&&window[r(872)+r(1003)+r(1484)](e.CKgIW,this[r(1151)+"ageHide"]),this._isBrowser&&window[r(872)+r(1003)+r(1484)](r(1271),this["_handleP"+r(320)])}[t(1151)+t(1459)](r){let s=t,l={FuPof:function(h,g){return h!==g},JpaAy:e[s(1246)]};r.persisted||(e[s(333)](e.fguxm,e[s(701)])?(this._isBrowser&&window[s(872)+s(1003)+s(1484)](e[s(846)],this._handlePageHide),this[s(404)+"er"]&&window["removeEv"+s(1003)+s(1484)](e[s(584)],this[s(1151)+s(320)]),this[s(848)]()):_0x1434c2.persisted&&(this["_navigat"+s(1107)]()&&(!this[s(1444)]||l[s(1693)](this[s(1444)][s(1080)+"te"],this[s(1735)])||l[s(1693)](this[s(1444)][s(1080)+"te"],this[s(1437)+"NG"]))&&this["_handleO"+s(1452)](),this[s(404)+"er"]&&_0x22c2a5[s(1347)+s(459)](s(1269),this[s(632)+s(1452)]),this[s(404)+"er"]&&_0x4379b7[s(1347)+s(459)](l.JpaAy,this[s(632)+s(623)]))),this._isBrowser&&window[s(872)+s(1003)+s(1484)](e[s(363)],this["_handleO"+s(1452)]),this[s(404)+"er"]&&window[s(872)+s(1003)+s(1484)](e.njokO,this[s(632)+s(623)])}[t(1151)+t(320)](r){let s=t;r[s(1633)+"d"]&&(this[s(1791)+"orOnline"]()&&(!this[s(1444)]||e.zTcwF(this[s(1444)][s(1080)+"te"],this[s(1735)])||e[s(397)](this[s(1444)][s(1080)+"te"],this[s(1437)+"NG"]))&&this["_handleO"+s(1452)](),this._isBrowser&&window.addEventListener(e.Ajsxk,this["_handleO"+s(1452)]),this[s(404)+"er"]&&window[s(1347)+"Listener"](e[s(1246)],this[s(632)+"ffLine"]))}async[t(1809)+t(486)](r){let s=t,{fpID:l,deviceID:h,bddID:g,ttwID:v,accessKey:S,aID:w,customParams:O={},enableAutoAck:N,enableQoS:B,QoSLevel:K,env:j}=this._options,ce,Re,Yt;this[s(404)+"er"]||this[s(1748)+"X"]||this._isMiniTT?(ce=location&&e[s(708)]==location[s(1514)]?e[s(782)]:s(1639),Re=r[s(798)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),Yt=/^wss(.*:\/\/)/[s(998)](r)?r:""+ce+Re):(ce=s(904),Re=r[s(798)](/(^http)((?:[s]*:\/\/))/,""),Yt=/(^ws)((?:[s]*:\/\/))/[s(998)](Re)?Re:""+ce+Re);let zn=g?e[s(1801)]:v?e[s(919)]:"device_id",Zl=g||v||h;if(e.kRGGX(!Zl,!zn))throw new Error(e[s(714)]);let Tm=e[s(316)](e.FmqWm,typeof O)?await e[s(687)](O):O,Pm=j?e.mUnXN(Jg,j[s(1398)],j[s(1711)]):{},Ka=Object[s(1267)]({device_platform:e[s(1004)],version_code:e.iPfjo,access_key:S,fpid:l,aid:w,[zn]:Zl,xsack:N?1:0,xaack:N?1:0,xsqos:B?1:0,qos_level:B?K:void 0,qos_sdk_version:2,...Pm},Tm),Rm=Object.keys(Ka)[s(1558)](($a,Va)=>Ka[Va]!==void 0?""+$a+($a?"&":"?")+Va+"="+Ka[Va]:$a,"");return Yt+"/ws/v2"+Rm}async[t(654)](){let r=t,s={bdDDv:function(l,h){return e[F(344)](l,h)},OywuF:function(l,h){return e[F(1319)](l,h)},cqykh:function(l,h){return e.CQDYf(l,h)},nceyp:function(l,h){return e[F(1460)](l,h)},hUlbc:function(l,h){return e[F(1656)](l,h)},eDTTB:function(l,h){return e[F(790)](l,h)},LhjsH:function(l,h){return e[F(526)](l,h)},fkLWK:function(l,h){return e[F(1253)](l,h)},oepHk:function(l,h){return e[F(1406)](l,h)},QQDQP:function(l,h){return e[F(373)](l,h)}};if(!(this["_connect"+r(951)]||this["_readyCl"+r(531)])){this[r(654)+r(951)]=!0;try{if(e[r(333)](e[r(533)],r(1798)))_0x193918[r(889)+r(562)+"e"](_0x1acbf5,{keyPath:_0x3c9138});else{let l=this[r(1654)+r(634)]?.[r(990)+r(1361)+"ointReac"+r(713)+"tries"](),{timeoutInterval:h}=this[r(1070)];if(l){let v=this[r(1654)+r(634)]?.[r(429)+r(575)+"nt"](),S=this[r(1654)+r(634)]?.[r(885)+r(1544)+r(777)+r(454)+"unt"](),w=this["_endpoin"+r(634)]?.[r(429)+r(575)+r(698)+r(1653)]();if(S){let O="connect "+v+(r(1288)+r(468)+r(696)+r(1056)+r(1616)+"backup e"+r(364))+S+(r(351)+"y"),N=e[r(1306)](gt,e[r(1211)],{message:O,code:gn["MAX_RETR"+r(843)+"R"]});this._debug(O),this[r(339)+r(1697)+r(1649)](N),this[r(1148)]=await this["_generat"+r(486)](S),this[r(744)](r(758)+S+" "+w+" times"),this[r(1285)+"sListeners"]()}else if(e.ejPAU(e[r(1763)],e[r(715)])){let O=this[r(1657)],N=this[r(682)];return[e[r(362)](O,24),e.aRyYo(O,16)&255,e[r(1584)](O,8)&255,e.ehWfp(255,O),e.GiisY(N,24),e[r(1482)](N,16)&255,e[r(797)](N,8)&255,e.vyodo(255,N)]}else{let O=r(758)+v+(r(1288)+", max re"+r(696)+r(577));this._debug(O),this[r(339)+"hErrorEv"+r(1649)](gt(e.OdXLv,{message:O,code:gn["MAX_RETR"+r(843)+"R"]}));return}}else if(e[r(1153)](e[r(365)],e[r(774)]))_0x4585c2=_0x4cca65[UurjrH.bdDDv(_0x26d3c8+_0x54ca9e,1)],_0x33915a=_0x31dbaa[UurjrH[r(368)](_0x14c012+_0x291a3e,2)],UurjrH[r(1320)](UurjrH[r(1323)](UurjrH[r(436)](_0x4b14c9,UurjrH[r(1712)](_0x1bde97,8)),49344),32896)?_0x35695d+=_0x1616ef:(_0x5aadb0=UurjrH[r(1587)](UurjrH.hUlbc((15&_0x2efa2f)<<12,UurjrH[r(1712)](UurjrH.fkLWK(63,_0x247b24),6)),63&_0x13bf94),UurjrH.oepHk(_0x19c240,2048)||_0x27a380>=55296&&UurjrH[r(993)](_0x1dd4ad,57343)?_0x381a79+=_0x1fdf81:(_0x445717+=_0x1bd465(_0x22ca6e),_0x17e156+=2));else{let v=this[r(1654)+r(634)]?.["getCurre"+r(575)+r(1263)+r(1111)](),S=this[r(1654)+r(634)]?.[r(429)+r(575)+r(698)+"ount"]();this[r(1148)]=await this._generateUrl(v||""),this._debug("connect "+v+" "+S+r(1173)),this[r(1285)+r(1090)+"rs"]()}if(this._isInit)this[r(1750)]=!1;else{let v=Ba(e.jsqYl,{message:e[r(1167)]});this["onStartR"+r(637)]&&this["onStartR"+r(637)](v)}let g=this[r(1654)+r(634)]?.[r(429)+"ntEndpoi"+r(698)+"ount"]()||0;e.JOlrI(g,1)&&await this[r(955)](e[r(641)](g,1)),this[r(744)](r(717)+r(1088)+this._url+(" protoco"+r(412))+this._protocols),this[r(1444)]=e[r(381)](Kg,{url:this[r(1148)],protocols:[this[r(1606)+"ls"]],headers:this[r(1070)]["miniProg"+r(566)+"s"]["customHt"+r(1084)]},this._options.ws),(this[r(404)+"er"]||this._isWorker)&&this[r(1444)]&&(this[r(1444)][r(672)+"pe"]=this[r(784)+"ype"]),this["_addWsLi"+r(1663)](),this[r(654)+r(963)+r(638)]=e[r(1413)](setTimeout,this[r(1744)+"ut"][r(1289)](this),h)}}catch(l){throw this[r(654)+r(951)]=!1,l}}}["_clearTi"+t(551)](){let r=t;e[r(1790)](clearTimeout,this[r(654)+r(963)+r(638)]),this[r(654)+"ionTimeo"+r(638)]=null}["_clearPi"+t(1485)](){let r=t;e.KKSLC(e.dnNPr,e[r(1257)])?(e.akYsq(clearTimeout,this[r(845)+r(1117)+"Id"]),e.bOBTS(clearTimeout,this[r(1714)+r(1182)+"tId"]),this[r(845)+r(1117)+"Id"]=null,this[r(1714)+r(1182)+r(856)]=null):_0x4336d3.d=(s,l)=>{let h=r;for(var g in l)_0x239109.o(l,g)&&!_0x57e2f4.o(s,g)&&_0x24dc6b[h(612)+h(478)](s,g,{enumerable:!0,get:l[g]})}}_debug(...r){let s=t,l={omtMU:function(h,g){return h|g},ZBLDL:function(h,g){return e[F(712)](h,g)},EySUT:function(h,g){return e[F(707)](h,g)}};e[s(570)]===e[s(1624)]?(_0x3ca814[_0x486224++]=fqtqpi[s(688)](_0x2f486e>>12,224),_0x32a604[_0x20e37c++]=fqtqpi[s(688)](fqtqpi[s(396)](_0x3757b7,6)&63,128),_0x1701cc[_0x2b39ed++]=fqtqpi[s(778)](63,_0x5f042f)|128):this._options[s(820)]&&console[s(1254)][s(888)](console,[e[s(1276)],...r])}["_getInte"+t(1338)+"e"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:g}=this._options,v=e[s(1635)](l,Math[s(1230)](g,e[s(1273)](r,1)));return v>h?h:v}[t(618)](){let r=t;if(this[r(1444)]&&e.zMeAd(this._ws[r(1080)+"te"],this[r(1437)+"NG"])){this[r(947)+r(1485)](),this[r(845)+r(1117)+"Id"]=e.GylHx(setTimeout,this[r(618)].bind(this),this[r(1070)][r(779)+r(651)]);return}if(!this[r(1444)]||e[r(1497)](this._ws.readyState,this[r(1735)]))return void this["_handleR"+r(637)]();this._ws&&this[r(1444)][r(1169)]("hi"),this[r(1714)+r(1182)+r(856)]=e.SBAfh(setTimeout,this[r(544)+"econnect"+r(1758)].bind(this),this[r(1070)][r(559)+r(1108)+r(604)])}[t(544)+"econnect"+t(1758)](){let r=t;this[r(1501)+r(1009)]?.[r(1547)](),this.emit(e.QlQXU,e[r(1676)]),this["_pingLos"+r(1009)]?.[r(1611)+r(1192)+"nt"]()?this[r(544)+r(637)]():this._ping()}[t(1791)+t(1107)](){let r=t,s={DfAoM:function(l,h){return l(h)}};if(e[r(564)](e[r(492)],"vZHeg"))_0xb50e8b+=tphKQb[r(1556)](_0x2eb891,_0x3d8f94),_0x4b45e4++;else return this[r(1480)+"T"]||this[r(1748)+"X"]?this[r(1030)+r(1372)+"line"]:(this._isBrowser||this[r(933)+"r"])&&this[r(1070)]["listenNe"+r(631)+r(1205)]?navigator[r(1652)]:!0}[t(544)+t(637)](){let r=t;!this[r(1791)+r(1107)]()||this._readyClosed||(this["_endpoin"+r(634)]?.[r(913)+"pointCon"+r(378)](),this[r(1501)+"sCounter"]?.[r(800)+r(1001)](),this[r(1444)]?this._disconnect(1001,r(628)+r(662)+r(387)+r(879)+"ver",!0):this[r(654)]())}[t(1118)+"etWorkCh"+t(1124)](){let r=t;this[r(1480)+"T"]?tt[r(1734)+r(918)+r(952)](({isConnected:s})=>{let l=r;this[l(1030)+l(1372)+l(1112)]=s,s?this["_handleO"+l(1452)]():this["_handleO"+l(623)]()}):this[r(1748)+"X"]&&wx[r(1734)+"kStatusC"+r(952)](({isConnected:s})=>{let l=r;this["_miniNavigatorOn"+l(1112)]=s,s?this[l(632)+l(1452)]():this[l(632)+l(623)]()})}[t(955)](r){return new Promise(s=>{let l=F;e[l(1116)](setTimeout,s,this[l(1396)+"rvalValue"](r))})}[t(871)+"ect"](r=1e3,s="",l=!1){let h=t,g={cuHep:function(v,S){return e[F(1063)](v,S)},wcFTQ:function(v,S){return e[F(905)](v,S)}};if(e.ZOEWK(e[h(1565)],e[h(1565)]))return function(...v){let S=h;return _0x2ee851[S(888)](ZDTLrW.cuHep(_0xb44f8e,this),v),ZDTLrW[S(723)](_0x3073af,_0x126a1b[S(1473)](this))};if(!this[h(1444)])return;this[h(1423)+"WebSocket"](r,s,l)}_onTimeout(){let r=t,s=this["_endpoin"+r(634)]?.getCurrentEndpoint();this[r(744)](r(758)+s+r(1288)),this[r(871)+r(1058)](1001,e.quJWH,!0)}[t(430)](r){let s=t,l=e[s(1287)](Zt,r);this[s(1444)]&&e[s(1626)](this._ws[s(1080)+"te"],this[s(1735)])&&(this[s(1444)]&&this[s(1444)][s(1169)](l),this._debug(e[s(578)],r))}[t(1285)+"sListeners"](){let r=t;if(e[r(926)](e[r(1066)],e.kCnnT))this[r(1780)](r(853),_0x203f5c),this[r(1103)+"e"]&&this[r(1103)+"e"](_0x564cd9);else{let s=e.HJIba.split("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[r(1444)])return;continue;case"1":this[r(1444)]["removeEv"+r(1003)+r(1484)](e[r(1184)],this[r(1224)]);continue;case"2":this._ws[r(872)+r(1003)+"ner"](e[r(1443)],this._onMessage);continue;case"3":this._ws["removeEv"+r(1003)+"ner"](e.WCtKg,this[r(1631)]);continue;case"4":this[r(1444)]["removeEv"+r(1003)+r(1484)](e.OdXLv,this[r(986)]);continue}break}}}[t(1445)+t(1663)](){let r=t;if(e[r(1636)](e[r(917)],e[r(683)]))return r(1539)+"_"+this[r(401)];{let s=e[r(1589)][r(1738)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1444)][r(1347)+r(459)]("message",this._onMessage);continue;case"1":this._ws.addEventListener(e[r(1211)],this[r(986)]);continue;case"2":if(!this[r(1444)])return;continue;case"3":this._ws[r(1347)+r(459)](e[r(1039)],this[r(1631)]);continue;case"4":this[r(1444)][r(1347)+r(459)](r(557),this[r(1224)]);continue}break}}}[t(981)+t(756)](r=1e3,s=""){let l=t,h={DJhnk:function(g,v,S,w){return e.lydbU(g,v,S,w)}};try{l(962)!==e.bMFea?JsHXln[l(959)](_0x1932fe,this,_0x21d0f8,[_0x515b01,_0x5f0893,_0x63f9f4,_0x4c15ce,_0x1da44a,_0x46ba2e]):this[l(1444)]&&this[l(1444)][l(848)](r,s)}catch{}}[t(1423)+t(740)+"t"](r=1e3,s="",l=!1){let h=t;if(this[h(947)+"ngTimer"](),this[h(838)+h(551)](),this[h(1285)+h(1090)+"rs"](),this[h(981)+h(756)](1e3,s),this["_connect"+h(951)]=!1,l&&this[h(1791)+h(1107)]()&&!this[h(423)+h(531)]){if(this[h(1654)+h(634)]?.checkReachMaxTries()){let v=this[h(1654)+h(634)]?.["getCurre"+h(575)+"nt"]();this["_dispatc"+h(1405)+"ent"](It(e[h(1039)],{code:1006,reason:h(758)+v+(h(1288)+h(468)+h(696)+h(577)),wasClean:!0}))}else{let v=this[h(1070)][h(387)+h(433)+h(805)](r,s);this[h(339)+"hCloseEvent"](It("close",{code:r,reason:s,wasClean:!0,willReconnect:v})),v&&this[h(654)]()}return}this[h(1791)+h(1107)]()||this["_readyCl"+h(531)]?this[h(339)+h(1405)+h(1649)](It(e[h(1039)],{code:r,reason:h(1275)})):this[h(339)+h(1405)+h(1649)](e.mBcwf(It,"close",{code:1006,reason:e.cUMCA})),this[h(1444)]=null,this[h(1654)+"tManager"]?.[h(913)+h(1533)+h(378)](),this[h(1501)+h(1009)]?.[h(800)+h(1001)]()}[t(339)+t(613)+"nt"](r){this[t(1780)](e.hzvac,r),this.onopen&&this.onopen(r)}[t(339)+t(1513)+t(1567)](r){let s=t;this.emit(e[s(1443)],r),this.onmessage&&this[s(1103)+"e"](r)}[t(339)+"hAckMess"+t(599)](r){let s=t;this.emit(e[s(438)],r),this[s(1776)+"eAck"]&&this["onReceiv"+s(1621)](r)}[t(339)+t(1697)+t(1649)](r){let s=t;this.emit(e[s(1211)],r),this[s(1705)]&&this[s(1705)](r)}["_dispatc"+t(1405)+t(1649)](r){let s=t;this[s(1780)](e[s(1039)],r),this[s(391)]&&this[s(391)](r)}get[t(672)+"pe"](){let r=t;return this[r(1444)]?this[r(1444)][r(672)+"pe"]:this[r(784)+r(537)]}set[t(672)+"pe"](r){let s=t;this[s(784)+s(537)]=r,this[s(1444)]&&(this[s(1444)][s(672)+"pe"]=r)}get[t(1505)+"nt"](){let r=t;return this["_endpoin"+r(634)]?.[r(429)+r(575)+"ntTriesC"+r(1653)]()||0}get[t(1375)+t(428)](){let r=t;return this["_message"+r(1538)][r(1558)]((l,h)=>(l+=h&&h[r(1351)+"th"]||0,l),0)+(this[r(1444)]?this._ws["buffered"+r(428)]:0)}get extensions(){let r=t;return this[r(1444)]?this[r(1444)][r(1038)+"ns"]:""}get[t(1514)](){let r=t;return this[r(1444)]?this._ws[r(1514)]:""}get[t(1080)+"te"](){let r=t;return this._ws?this[r(1444)][r(1080)+"te"]:this._options[r(971)+r(1208)]?this[r(1437)+"NG"]:this[r(1585)]}get[t(1532)](){let r=t;return this[r(1444)]?this[r(1444)][r(1532)]:this[r(1148)]}close(r=1e3,s){let l=t,h=(l(1508)+l(891)).split("|"),g=0;for(;;){switch(h[g++]){case"0":this["_clearTi"+l(551)]();continue;case"1":this[l(423)+l(531)]=!0;continue;case"2":if(!this[l(1444)])return void this[l(744)](l(1554)+"s instan"+l(1091)+l(353)+"ed");continue;case"3":this[l(664)+l(697)]?.[l(432)]();continue;case"4":this["_clearPi"+l(1485)]();continue;case"5":this[l(1423)+l(740)+"t"](r,s);continue;case"6":if(this[l(1444)].readyState===this[l(1585)]||e.pOygk(this[l(1444)][l(1080)+"te"],this[l(1804)]))return void this[l(744)](l(1554)+"s alread"+l(852));continue;case"7":this[l(476)+l(512)+"Listener"]();continue}break}}async[t(1169)](r,s){let l=t,h={nWjww:function(g,v){return e[F(611)](g,v)},EYeZw:function(g,v){return g&v}};if(e.dSRiu(e[l(1732)],l(898))){if(e[l(866)](null,r))throw new Error(e[l(348)]);e.UBmVF(e[l(1024)],typeof r)&&(r=JSON[l(1777)+"y"](r)),e[l(616)](e[l(1177)],typeof r)&&!e.rxwLY(r,ArrayBuffer)&&!(r[l(386)]&&r[l(386)]instanceof ArrayBuffer)&&(r=JSON[l(1777)+"y"](r));let g=await e.mmFsE(Wl,r),v=e[l(961)](Vg,r),{method:S=0,service:w=this[l(1070)][l(626)],logID:O=this[l(1070)][l(987)+l(536)](),headers:N=this._options[l(321)],payloadEncoding:B=this[l(1070)][l(1787)+l(501)],payloadType:K=this._options[l(490)+"ype"],logIDNew:j=this[l(1070)][l(674)+l(1759)][l(1552)+l(1097)+l(1713)+"ew"]?i(this[l(1070)]["logIDNew"+l(1759)].userIp):""}=s||{};if(!w)throw new Error(e[l(1427)]);let ce={SeqID:de.fromNumber(this[l(1032)]++),LogID:de[l(1324)+"er"](O),service:w,method:S,headers:N,payloadEncoding:e[l(424)](B,Object)?B[l(1134)]?B[l(1134)]:"":B,payloadType:e[l(337)](K,Object)?K[l(767)]?K[l(767)]:v:K||v,payload:g,LogIDNew:j},Re=Zt(ce);return this[l(1444)]&&e[l(1462)](this[l(1444)][l(1080)+"te"],this[l(1735)])?(this[l(1444)]&&this[l(1444)][l(1169)](Re),this[l(744)](e[l(1048)],ce)):this[l(1723)+"Queue"][l(1436)]<this[l(1070)]["maxMessa"+l(1465)+l(946)]?l(922)!==e[l(451)]?(_0x4b745f[_0x33a71d++]=EuwxdL.nWjww(_0x427b7b,6)|192,_0x36090a[_0x3b59da++]=EuwxdL[l(573)](63,_0xe11810)|128):(this[l(1723)+"Queue"][l(1602)](Re),this[l(744)](l(826),ce)):e[l(1297)](e[l(1142)],e[l(1142)])?(this["_message"+l(1538)][l(1106)](),this[l(1723)+l(1538)][l(1602)](Re)):this[l(605)+l(1268)]=null,{seqID:this[l(1032)],logID:O,logIDNew:j}}else{let g=this[l(892)][l(1569)+l(1305)](this._prefix),v=_0x2b8e4e.parse(e[l(1403)](g,"{}"));return v[_0x374d6d||_0x2b5d7c[this._pathKey]]=_0x4fe348,this._qosDB[l(582)+l(1305)](this[l(1517)],_0x2c7425.stringify(v)),_0x18fb39||_0x1b14f2[this._pathKey]}}async[t(387)+"t"](r){let s=t,{url:l}=e[s(1403)](r,{}),h=Array.isArray(l)?l:e[s(1175)](s(1081),typeof l)?[l]:[];if(r&&Object[s(1267)](this[s(1070)],r),h&&h[s(1436)]?this["_endpoin"+s(634)]=new Hl(h,this[s(1070)][s(761)+"es"]):this[s(1654)+s(634)]?.[s(913)+s(1533)+s(378)](),this[s(1501)+s(1009)]?.[s(800)+"nter"](this[s(1070)][s(768)+s(753)]),this[s(423)+s(531)]=!1,this._ws&&e[s(832)](this[s(1444)][s(1080)+"te"],this[s(1585)]))this[s(871)+s(1058)](1e3,s(1303)+s(637)+s(1178),!0);else if(e[s(1008)](e[s(1065)],e[s(1210)]))this[s(1750)]=!0,this[s(654)]();else return this[s(892)]?.get(_0x2acac9)}async[t(1247)](){let r=t;if(!this._connectLock){let s=e[r(1041)][r(1738)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1750)]=!0;continue;case"1":this[r(654)]();continue;case"2":this[r(1501)+"sCounter"]?.[r(800)+r(1001)]();continue;case"3":this[r(1654)+r(634)]?.["resetEnd"+r(1533)+r(378)]();continue;case"4":this["_readyCl"+r(531)]=!1;continue}break}}}["addEvent"+t(459)](r,s){let l=t,h={uGDvJ:function(g,v){return g(v)}};e.Eqdld(e[l(367)],e.RKMlB)?(_0x4265e1[_0x293332[_0x23ba2f].cursor_name]=iabjMD.uGDvJ(_0x36aac5,_0x1958ca[_0xb47661].cursor_name),_0x13ab39+=14+_0x266f2e[_0x4f0eae[_0x2268c6][l(984)+l(1549)]]):this.on(r,s)}["dispatch"+t(1567)](r){let s=t;if(e[s(1364)](e[s(1783)],e[s(347)])){let{type:l}=r;this[s(1780)](l,r)}else{let l=this[s(892)][s(1569)+s(1286)+"nc"](this._prefix),h=_0x48a7af[s(427)](e[s(502)](l,"{}"));return _0x51d7db[s(1542)](h)}}[t(872)+t(1003)+t(1484)](r,s){this.off(r,s)}[t(960)](){let r=t,s={zltGN:function(l,h){return e[F(543)](l,h)},LcZIA:e[r(1655)]};return new Promise((l,h)=>{let g=r,v={kBCnp:e[g(1775)],ElfFz:e[g(581)],AUlLf:e[g(1655)]};this[g(947)+g(1485)](),this[g(845)+"gTimeoutId"]=e[g(1681)](setTimeout,this[g(618)][g(1289)](this),this[g(1070)][g(779)+"rval"]);let S=()=>{let O=g;l(v[O(477)]),this[O(1078)](v.ElfFz,S),this[O(1078)](v.AUlLf,w)},w=()=>{let O=g;s[O(958)](h,O(818)),this[O(1078)](O(1698)+O(1409)+"s",S),this[O(1078)](s[O(1415)],w)};this.on(e[g(581)],S),this.on(g(1698)+"e_timeout",w),this._ping()})}}})(),ze[L(870)+L(1646)]=De[L(870)+"oseEvent"],ze[L(1789)+"rorEvent"]=De["CustomEr"+L(1046)],ze[L(444)+"e"]=De[L(444)+"e"],ze[L(1567)]=De[L(1567)],ze.FWS=De[L(336)],ze[L(970)+L(1779)+L(1491)]=De[L(970)+"MessageE"+L(1491)],ze["MessageE"+L(1491)]=De[L(1779)+L(1491)],ze[L(1560)+"t"]=De[L(1560)+"t"],ze["Reconnec"+L(911)]=De[L(607)+"tEvent"],ze["createCl"+L(1646)]=De[L(1617)+L(1646)],ze[L(801)+L(1046)]=De[L(801)+L(1046)],ze["createMe"+L(1195)+"nt"]=De[L(1309)+L(1195)+"nt"],ze[L(1299)+L(1203)]=De[L(1299)+L(1203)],ze[L(342)+L(1014)+"vent"]=De[L(342)+L(1014)+L(1491)],ze[L(1119)+"rame"]=De[L(1119)+"rame"],ze["encodeFr"+L(1549)]=De["encodeFr"+L(1549)];for(pa in De)[L(870)+"oseEvent",L(1789)+L(1046),L(444)+"e","Event",L(336),L(970)+L(1779)+L(1491),L(1779)+L(1491),L(1560)+"t",L(607)+L(911),L(1617)+L(1646),L(801)+L(1046),L(1309)+L(1195)+"nt","createOp"+L(1203),L(342)+L(1014)+"vent","decodedF"+L(1179),"encodeFr"+L(1549)][L(400)](pa)===-1&&(ze[pa]=De[pa]);var pa;Object[L(612)+L(478)](ze,"__esModule",{value:!0})});import{existsSync as DI,openSync as LI}from"node:fs";import{mkdir as MI}from"node:fs/promises";import{dirname as NI}from"node:path";import{fileURLToPath as FI}from"node:url";function zI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function yl(t=Z()){return DI(t.libEntry)?t.libEntry:FI(new URL("../index.ts",import.meta.url))}async function tg(t={}){let e=t.paths??Z(),n=t.entryOverride??yl(e),i=zI(e,process.env.COZE_BRIDGE_LOG_MODE);await MI(NI(i),{recursive:!0});let o=LI(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=at(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[ys]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return BI.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var BI,ys,Aa=it(()=>{"use strict";Gt();ne();Ce();BI=G("spawn-daemon"),ys="COZE_BRIDGE_DAEMON"});import{spawn as NA}from"node:child_process";import{mkdir as FA,unlink as BA,writeFile as zA}from"node:fs/promises";import{dirname as UA,join as HA}from"node:path";function ui(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function GA(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${ui(n)}</key>
|
|
21
21
|
<string>${ui(i)}</string>`).join(`
|
|
22
22
|
`);return e?`
|
|
23
23
|
<key>EnvironmentVariables</key>
|
|
24
24
|
<dict>
|
|
25
25
|
${e}
|
|
26
|
-
</dict>`:""}function qA(t,e){return new Promise((n,i)=>{let o=NA(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 li,vs,
|
|
26
|
+
</dict>`:""}function qA(t,e){return new Promise((n,i)=>{let o=NA(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 li,vs,Oa,Tl,Sg=it(()=>{"use strict";ne();li=G("supervisor.launchd"),vs="ai.coze.bridge",Oa=qA,Tl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
27
27
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
28
28
|
<plist version="1.0">
|
|
29
29
|
<dict>
|
|
@@ -47,8 +47,8 @@ ${e}
|
|
|
47
47
|
<string>${ui(t.logFile)}</string>${GA(t.env)}
|
|
48
48
|
</dict>
|
|
49
49
|
</plist>
|
|
50
|
-
`},configPath(t){return HA(t.homeDir,"Library","LaunchAgents",`${vs}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await
|
|
51
|
-
`):""}function Ma(t,e){return new Promise((n,i)=>{let o=
|
|
50
|
+
`},configPath(t){return HA(t.homeDir,"Library","LaunchAgents",`${vs}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await FA(UA(i),{recursive:!0}),await zA(i,this.renderConfig(t),"utf8"),li.info("plist written",{plistPath:i,activate:n}),!n)return;await Oa("launchctl",["unload","-w",i]).catch(a=>li.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await Oa("launchctl",["load","-w",i]),li.info("launchd job loaded",{label:vs});let o=process.getuid?.()??0;await Oa("launchctl",["kickstart","-k",`gui/${o}/${vs}`]),li.info("launchd job kickstarted",{label:vs,uid:o})},async uninstall(t){let e=this.configPath(t);await Oa("launchctl",["unload","-w",e]).catch(n=>li.warn("launchctl unload failed (ignored)",{err:String(n)})),await BA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),li.info("launchd job removed",{plistPath:e})}}});import{spawn as jA}from"node:child_process";import{mkdir as WA,unlink as KA,writeFile as $A}from"node:fs/promises";import{dirname as VA,join as Ig}from"node:path";function La(t,e){return t.isRoot?e:["--user",...e]}function ZA(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
|
|
51
|
+
`):""}function Ma(t,e){return new Promise((n,i)=>{let o=jA(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 Da,fi,JA,Pl,Ag=it(()=>{"use strict";ne();Da=G("supervisor.systemd"),fi="coze-bridge.service",JA="/etc/systemd/system";Pl={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
|
${ZA(t.env)}
|
|
63
63
|
[Install]
|
|
64
64
|
WantedBy=${e}
|
|
65
|
-
`},configPath(t){return t.isRoot?Ig(JA,fi):Ig(t.homeDir,".config","systemd","user",fi)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await
|
|
65
|
+
`},configPath(t){return t.isRoot?Ig(JA,fi):Ig(t.homeDir,".config","systemd","user",fi)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await WA(VA(i),{recursive:!0}),await $A(i,this.renderConfig(t),"utf8"),Da.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await Ma("systemctl",La(t,["daemon-reload"])),await Ma("systemctl",La(t,n?["enable","--now",fi]:["enable",fi])),Da.info("systemd unit enabled",{unitName:fi,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await Ma("systemctl",La(t,["disable","--now",fi])).catch(n=>Da.warn("systemctl disable failed (ignored)",{err:String(n)})),await KA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Ma("systemctl",La(t,["daemon-reload"])).catch(()=>{}),Da.info("systemd unit removed",{unitPath:e})}}});import{spawn as YA}from"node:child_process";import{join as XA}from"node:path";function kg(t,e){return new Promise((n,i)=>{let o=YA(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 Rl,Na,Ol,Cg=it(()=>{"use strict";ne();Rl=G("supervisor.taskscheduler"),Na="CozeBridge",Ol={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 XA(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 kg("schtasks",["/Create","/SC","ONLOGON","/TN",Na,"/TR",n,"/RU",t.userName,"/F"]),Rl.info("task scheduler entry created",{task:Na,logFile:t.logFile})},async uninstall(t){await kg("schtasks",["/Delete","/TN",Na,"/F"]).catch(e=>Rl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Rl.info("task scheduler entry removed",{task:Na})}}});var Cg={};Za(Cg,{buildContext:()=>ik,getSupervisor:()=>tk,launchdSupervisor:()=>Cl,systemdSupervisor:()=>Pl,taskSchedulerSupervisor:()=>Dl});import{homedir as QA,userInfo as ek}from"node:os";function tk(t=process.platform){switch(t){case"darwin":return Cl;case"linux":return Pl;case"win32":return Dl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function rk(){let t={};for(let e of nk){let n=process.env[e];n&&(t[e]=n)}return t}function ik(){let t=J();return{nodeBin:process.execPath,entry:yl(t),logFile:t.logFile,homeDir:QA(),userName:ek().username,isRoot:process.getuid?.()===0,env:rk()}}var nk,Pg=st(()=>{"use strict";Te();Aa();Sg();Ag();Tg();nk=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();_n();var cu=H("acp-installer-warmup"),iw=["claude-code","codex"];async function du(t={}){let e=t.ensure??Er,i=(await Promise.allSettled(iw.map(async o=>{let a=await e(o);cu.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&cu.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))})}en();ne();import{readdir as yw}from"node:fs/promises";import{mkdir as hu,readFile as ww,writeFile as xu}from"node:fs/promises";import{join as rc}from"node:path";var _w={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function vr(t,e,n){await hu(t,{recursive:!0});let i=_w[e],o=rc(t,i);return await xu(o,n??"","utf8"),o}async function ic(t,e,n){let i=rc(t,".claude");await hu(i,{recursive:!0});let o=rc(i,"settings.local.json"),a={};try{let u=await ww(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 xu(o,JSON.stringify(a,null,2),"utf8"),o}var Qe=H("agent-detail-sync"),bw=6e4,Ew=5*6e4,Ms=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await yw(n)}catch(o){Qe.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}Qe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let a=await me(o,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){Qe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,a)}catch(d){Qe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Qe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&n.push(i);if(n.length!==0){Qe.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){Qe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await me(e,this.opts.paths);if(!i){Qe.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){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let h=this.retryQueue.get(e),p=h?Math.min(h.currentDelay*2,Ew):bw;this.retryQueue.set(e,{dueAt:Date.now()+p,currentDelay:p});return}if(o.agentId&&o.agentId!==e){Qe.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"?(Qe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):o.deployType&&Qe.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){Qe.debug("detail sync: no diff",{agentId:e});return}await Ce(i,this.opts.paths),Qe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Qe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await vr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Ld=Qt($u(),1);import{createHash as Eb}from"node:crypto";import{lstat as Ad,mkdir as kd,readFile as Do,readdir as Q0,rm as Td,stat as Dd,writeFile as Cd}from"node:fs/promises";import{homedir as vb}from"node:os";import{basename as Z0,dirname as Sb,join as he,normalize as Ib,relative as Od,resolve as Pd,sep as eh}from"node:path";import{Readable as th}from"node:stream";import{pipeline as nh}from"node:stream/promises";import Ww from"events";import at from"fs";import{EventEmitter as id}from"node:events";import Pf from"node:stream";import{StringDecoder as jw}from"node:string_decoder";import Of from"node:path";import Mr from"node:fs";import{dirname as i_,parse as s_}from"path";import{EventEmitter as h_}from"events";import zc from"assert";import{Buffer as Yn}from"buffer";import*as Xu from"zlib";import x_ from"zlib";import{posix as Tr}from"node:path";import{basename as G_}from"node:path";import xo from"fs";import Ht from"fs";import af from"path";import{win32 as ty}from"node:path";import xf from"path";import Vf from"node:fs";import wy from"node:assert";import{randomBytes as Jf}from"node:crypto";import se from"node:fs";import Be from"node:path";import Zf from"fs";import vo from"node:fs";import zi from"node:path";import pt from"node:fs";import Iy from"node:fs/promises";import mo from"node:path";import{join as a0}from"node:path";import xt from"node:fs";import l0 from"node:path";var Gw=Object.defineProperty,qw=(t,e)=>{for(var n in e)Gw(t,n,{get:e[n],enumerable:!0})},Vu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Kw=t=>!!t&&typeof t=="object"&&(t instanceof er||t instanceof Pf||$w(t)||Vw(t)),$w=t=>!!t&&typeof t=="object"&&t instanceof id&&typeof t.pipe=="function"&&t.pipe!==Pf.Writable.prototype.pipe,Vw=t=>!!t&&typeof t=="object"&&t instanceof id&&typeof t.write=="function"&&typeof t.end=="function",tn=Symbol("EOF"),nn=Symbol("maybeEmitEnd"),bn=Symbol("emittedEnd"),Us=Symbol("emittingEnd"),bi=Symbol("emittedError"),Hs=Symbol("closed"),Ju=Symbol("read"),Gs=Symbol("flush"),Zu=Symbol("flushChunk"),Ct=Symbol("encoding"),kr=Symbol("decoder"),Ue=Symbol("flowing"),Ei=Symbol("paused"),Dr=Symbol("resume"),He=Symbol("buffer"),et=Symbol("pipes"),Ge=Symbol("bufferLength"),lc=Symbol("bufferPush"),qs=Symbol("bufferShift"),Xe=Symbol("objectMode"),Pe=Symbol("destroyed"),uc=Symbol("error"),fc=Symbol("emitData"),Yu=Symbol("emitEnd"),hc=Symbol("emitEnd2"),Bt=Symbol("async"),xc=Symbol("abort"),Ws=Symbol("aborted"),vi=Symbol("signal"),Gn=Symbol("dataListeners"),ht=Symbol("discarded"),Si=t=>Promise.resolve().then(t),Jw=t=>t(),Zw=t=>t==="end"||t==="finish"||t==="prefinish",Yw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Xw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Rf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Dr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Qw=class extends Rf{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)}},e_=t=>!!t.objectMode,t_=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",er=class extends id{[Ue]=!1;[Ei]=!1;[et]=[];[He]=[];[Xe];[Ct];[Bt];[kr];[tn]=!1;[bn]=!1;[Us]=!1;[Hs]=!1;[bi]=null;[Ge]=0;[Pe]=!1;[vi];[Ws]=!1;[Gn]=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");e_(e)?(this[Xe]=!0,this[Ct]=null):t_(e)?(this[Ct]=e.encoding,this[Xe]=!1):(this[Xe]=!1,this[Ct]=null),this[Bt]=!!e.async,this[kr]=this[Ct]?new jw(this[Ct]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:n}=e;n&&(this[vi]=n,n.aborted?this[xc]():n.addEventListener("abort",()=>this[xc]()))}get bufferLength(){return this[Ge]}get encoding(){return this[Ct]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Xe]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Bt]}set async(t){this[Bt]=this[Bt]||!!t}[xc](){this[Ws]=!0,this.emit("abort",this[vi]?.reason),this.destroy(this[vi]?.reason)}get aborted(){return this[Ws]}set aborted(t){}write(t,e,n){if(this[Ws])return!1;if(this[tn])throw new Error("write after end");if(this[Pe])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]?Si:Jw;if(!this[Xe]&&!Buffer.isBuffer(t)){if(Xw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Yw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Xe]?(this[Ue]&&this[Ge]!==0&&this[Gs](!0),this[Ue]?this.emit("data",t):this[lc](t),this[Ge]!==0&&this.emit("readable"),n&&i(n),this[Ue]):t.length?(typeof t=="string"&&!(e===this[Ct]&&!this[kr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Ct]&&(t=this[kr].write(t)),this[Ue]&&this[Ge]!==0&&this[Gs](!0),this[Ue]?this.emit("data",t):this[lc](t),this[Ge]!==0&&this.emit("readable"),n&&i(n),this[Ue]):(this[Ge]!==0&&this.emit("readable"),n&&i(n),this[Ue])}read(t){if(this[Pe])return null;if(this[ht]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[nn](),null;this[Xe]&&(t=null),this[He].length>1&&!this[Xe]&&(this[He]=[this[Ct]?this[He].join(""):Buffer.concat(this[He],this[Ge])]);let e=this[Ju](t||null,this[He][0]);return this[nn](),e}[Ju](t,e){if(this[Xe])this[qs]();else{let n=e;t===n.length||t===null?this[qs]():typeof n=="string"?(this[He][0]=n.slice(t),e=n.slice(0,t),this[Ge]-=t):(this[He][0]=n.subarray(t),e=n.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[He].length&&!this[tn]&&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[tn]=!0,this.writable=!1,(this[Ue]||!this[Ei])&&this[nn](),this}[Dr](){this[Pe]||(!this[Gn]&&!this[et].length&&(this[ht]=!0),this[Ei]=!1,this[Ue]=!0,this.emit("resume"),this[He].length?this[Gs]():this[tn]?this[nn]():this.emit("drain"))}resume(){return this[Dr]()}pause(){this[Ue]=!1,this[Ei]=!0,this[ht]=!1}get destroyed(){return this[Pe]}get flowing(){return this[Ue]}get paused(){return this[Ei]}[lc](t){this[Xe]?this[Ge]+=1:this[Ge]+=t.length,this[He].push(t)}[qs](){return this[Xe]?this[Ge]-=1:this[Ge]-=this[He][0].length,this[He].shift()}[Gs](t=!1){do;while(this[Zu](this[qs]())&&this[He].length);!t&&!this[He].length&&!this[tn]&&this.emit("drain")}[Zu](t){return this.emit("data",t),this[Ue]}pipe(t,e){if(this[Pe])return t;this[ht]=!1;let n=this[bn];return e=e||{},t===Vu.stdout||t===Vu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[et].push(e.proxyErrors?new Qw(this,t,e):new Rf(this,t,e)),this[Bt]?Si(()=>this[Dr]()):this[Dr]()),t}unpipe(t){let e=this[et].find(n=>n.dest===t);e&&(this[et].length===1?(this[Ue]&&this[Gn]===0&&(this[Ue]=!1),this[et]=[]):this[et].splice(this[et].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[ht]=!1,this[Gn]++,!this[et].length&&!this[Ue]&&this[Dr]();else if(t==="readable"&&this[Ge]!==0)super.emit("readable");else if(Zw(t)&&this[bn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[bi]){let i=e;this[Bt]?Si(()=>i.call(this,this[bi])):i.call(this,this[bi])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Gn]=this.listeners("data").length,this[Gn]===0&&!this[ht]&&!this[et].length&&(this[Ue]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Gn]=0,!this[ht]&&!this[et].length&&(this[Ue]=!1)),e}get emittedEnd(){return this[bn]}[nn](){!this[Us]&&!this[bn]&&!this[Pe]&&this[He].length===0&&this[tn]&&(this[Us]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Hs]&&this.emit("close"),this[Us]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Pe&&this[Pe])return!1;if(t==="data")return!this[Xe]&&!n?!1:this[Bt]?(Si(()=>this[fc](n)),!0):this[fc](n);if(t==="end")return this[Yu]();if(t==="close"){if(this[Hs]=!0,!this[bn]&&!this[Pe])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[bi]=n,super.emit(uc,n);let o=!this[vi]||this.listeners("error").length?super.emit("error",n):!1;return this[nn](),o}else if(t==="resume"){let o=super.emit("resume");return this[nn](),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[nn](),i}[fc](t){for(let n of this[et])n.dest.write(t)===!1&&this.pause();let e=this[ht]?!1:super.emit("data",t);return this[nn](),e}[Yu](){return this[bn]?!1:(this[bn]=!0,this.readable=!1,this[Bt]?(Si(()=>this[hc]()),!0):this[hc]())}[hc](){if(this[kr]){let e=this[kr].end();if(e){for(let n of this[et])n.dest.write(e);this[ht]||super.emit("data",e)}}for(let e of this[et])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Xe]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Xe]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Xe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Ct]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Pe,()=>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[tn])return e();let i,o,a=h=>{this.off("data",d),this.off("end",u),this.off(Pe,f),e(),o(h)},d=h=>{this.off("error",a),this.off("end",u),this.off(Pe,f),this.pause(),i({value:h,done:!!this[tn]})},u=()=>{this.off("error",a),this.off("data",d),this.off(Pe,f),e(),i({done:!0,value:void 0})},f=()=>a(new Error("stream destroyed"));return new Promise((h,p)=>{o=p,i=h,this.once(Pe,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[ht]=!1;let t=!1,e=()=>(this.pause(),this.off(uc,e),this.off(Pe,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(uc,e),this.once(Pe,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Pe])return t?this.emit("error",t):this.emit(Pe),this;this[Pe]=!0,this[ht]=!0,this[He].length=0,this[Ge]=0;let e=this;return typeof e.close=="function"&&!this[Hs]&&e.close(),t?this.emit("error",t):this.emit(Pe),this}static get isStream(){return Kw}},n_=at.writev,Pn=Symbol("_autoClose"),Ot=Symbol("_close"),Ii=Symbol("_ended"),fe=Symbol("_fd"),pc=Symbol("_finished"),an=Symbol("_flags"),gc=Symbol("_flush"),Bc=Symbol("_handleChunk"),Fc=Symbol("_makeBuf"),Bi=Symbol("_mode"),js=Symbol("_needDrain"),Br=Symbol("_onerror"),Fr=Symbol("_onopen"),mc=Symbol("_onread"),Or=Symbol("_onwrite"),Rn=Symbol("_open"),Dt=Symbol("_path"),In=Symbol("_pos"),Ft=Symbol("_queue"),Lr=Symbol("_read"),wc=Symbol("_readSize"),on=Symbol("_reading"),Ai=Symbol("_remain"),_c=Symbol("_size"),to=Symbol("_write"),qn=Symbol("_writing"),no=Symbol("_defaultFlag"),Zn=Symbol("_errored"),sd=class extends er{[Zn]=!1;[fe];[Dt];[wc];[on]=!1;[_c];[Ai];[Pn];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[Zn]=!1,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[Dt]=t,this[wc]=e.readSize||16*1024*1024,this[on]=!1,this[_c]=typeof e.size=="number"?e.size:1/0,this[Ai]=this[_c],this[Pn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[fe]=="number"?this[Lr]():this[Rn]()}get fd(){return this[fe]}get path(){return this[Dt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Rn](){at.open(this[Dt],"r",(t,e)=>this[Fr](t,e))}[Fr](t,e){t?this[Br](t):(this[fe]=e,this.emit("open",e),this[Lr]())}[Fc](){return Buffer.allocUnsafe(Math.min(this[wc],this[Ai]))}[Lr](){if(!this[on]){this[on]=!0;let t=this[Fc]();if(t.length===0)return process.nextTick(()=>this[mc](null,0,t));at.read(this[fe],t,0,t.length,null,(e,n,i)=>this[mc](e,n,i))}}[mc](t,e,n){this[on]=!1,t?this[Br](t):this[Bc](e,n)&&this[Lr]()}[Ot](){if(this[Pn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,at.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Br](t){this[on]=!0,this[Ot](),this.emit("error",t)}[Bc](t,e){let n=!1;return this[Ai]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[Ai]<=0)&&(n=!1,this[Ot](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[fe]=="number"&&this[Lr](),!1;case"error":return this[Zn]?!1:(this[Zn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},r_=class extends sd{[Rn](){let t=!0;try{this[Fr](null,at.openSync(this[Dt],"r")),t=!1}finally{t&&this[Ot]()}}[Lr](){let t=!0;try{if(!this[on]){this[on]=!0;do{let e=this[Fc](),n=e.length===0?0:at.readSync(this[fe],e,0,e.length,null);if(!this[Bc](n,e))break}while(!0);this[on]=!1}t=!1}finally{t&&this[Ot]()}}[Ot](){if(this[Pn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,at.closeSync(t),this.emit("close")}}},wo=class extends Ww{readable=!1;writable=!0;[Zn]=!1;[qn]=!1;[Ii]=!1;[Ft]=[];[js]=!1;[Dt];[Bi];[Pn];[fe];[no];[an];[pc]=!1;[In];constructor(t,e){e=e||{},super(e),this[Dt]=t,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[Bi]=e.mode===void 0?438:e.mode,this[In]=typeof e.start=="number"?e.start:void 0,this[Pn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[In]!==void 0?"r+":"w";this[no]=e.flags===void 0,this[an]=e.flags===void 0?n:e.flags,this[fe]===void 0&&this[Rn]()}emit(t,...e){if(t==="error"){if(this[Zn])return!1;this[Zn]=!0}return super.emit(t,...e)}get fd(){return this[fe]}get path(){return this[Dt]}[Br](t){this[Ot](),this[qn]=!0,this.emit("error",t)}[Rn](){at.open(this[Dt],this[an],this[Bi],(t,e)=>this[Fr](t,e))}[Fr](t,e){this[no]&&this[an]==="r+"&&t&&t.code==="ENOENT"?(this[an]="w",this[Rn]()):t?this[Br](t):(this[fe]=e,this.emit("open",e),this[qn]||this[gc]())}end(t,e){return t&&this.write(t,e),this[Ii]=!0,!this[qn]&&!this[Ft].length&&typeof this[fe]=="number"&&this[Or](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Ii]?(this.emit("error",new Error("write() after end()")),!1):this[fe]===void 0||this[qn]||this[Ft].length?(this[Ft].push(t),this[js]=!0,!1):(this[qn]=!0,this[to](t),!0)}[to](t){at.write(this[fe],t,0,t.length,this[In],(e,n)=>this[Or](e,n))}[Or](t,e){t?this[Br](t):(this[In]!==void 0&&typeof e=="number"&&(this[In]+=e),this[Ft].length?this[gc]():(this[qn]=!1,this[Ii]&&!this[pc]?(this[pc]=!0,this[Ot](),this.emit("finish")):this[js]&&(this[js]=!1,this.emit("drain"))))}[gc](){if(this[Ft].length===0)this[Ii]&&this[Or](null,0);else if(this[Ft].length===1)this[to](this[Ft].pop());else{let t=this[Ft];this[Ft]=[],n_(this[fe],t,this[In],(e,n)=>this[Or](e,n))}}[Ot](){if(this[Pn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,at.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Df=class extends wo{[Rn](){let t;if(this[no]&&this[an]==="r+")try{t=at.openSync(this[Dt],this[an],this[Bi])}catch(e){if(e?.code==="ENOENT")return this[an]="w",this[Rn]();throw e}else t=at.openSync(this[Dt],this[an],this[Bi]);this[Fr](null,t)}[Ot](){if(this[Pn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,at.closeSync(t),this.emit("close")}}[to](t){let e=!0;try{this[Or](null,at.writeSync(this[fe],t,0,t.length,this[In])),e=!1}finally{if(e)try{this[Ot]()}catch{}}}},o_=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"]]),a_=t=>!!t.sync&&!!t.file,c_=t=>!t.sync&&!!t.file,d_=t=>!!t.sync&&!t.file,l_=t=>!t.sync&&!t.file,u_=t=>!!t.file,f_=t=>o_.get(t)||t,od=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=f_(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Ki=(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=od(a);if(o?.(f,d),a_(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(c_(f)){let h=e(f,d);return u?h.then(()=>u(),u):h}else if(d_(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(f,d)}else if(l_(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}),p_=x_.constants||{ZLIB_VERNUM:4736},qt=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},p_)),g_=Yn.concat,Qu=Object.getOwnPropertyDescriptor(Yn,"concat"),m_=t=>t,yc=Qu?.writable===!0||Qu?.set!==void 0?t=>{Yn.concat=t?m_:g_}:t=>{},Xn=Symbol("_superWrite"),Ks=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"}},bc=Symbol("flushFlag"),ad=class extends er{#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 Xu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Xu[e](t)}catch(n){throw new Ks(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 Ks(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return zc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Yn.alloc(0),{[bc]: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}[Xn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Yn.from(t,e)),this.#e)return;zc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},yc(!0);let d;try{let f=typeof t[bc]=="number"?t[bc]:this.#r;d=this.#t._processChunk(t,f),yc(!1)}catch(f){yc(!1),this.#o(new Ks(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 Ks(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[Xn](Yn.from(f));for(let h=1;h<d.length;h++)u=this[Xn](d[h])}else u=this[Xn](Yn.from(d));return n&&n(),u}},Lf=class extends ad{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||qt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||qt.Z_FINISH,t.fullFlushFlag=qt.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(qt.Z_SYNC_FLUSH),zc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},w_=class extends Lf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Xn](t){return this.#e?(this.#e=!1,t[9]=255,super[Xn](t)):super[Xn](t)}},__=class extends Lf{constructor(t){super(t,"Unzip")}},Mf=class extends ad{constructor(t,e){t=t||{},t.flush=t.flush||qt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||qt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=qt.BROTLI_OPERATION_FLUSH,super(t,e)}},y_=class extends Mf{constructor(t){super(t,"BrotliCompress")}},b_=class extends Mf{constructor(t){super(t,"BrotliDecompress")}},Nf=class extends ad{constructor(t,e){t=t||{},t.flush=t.flush||qt.ZSTD_e_continue,t.finishFlush=t.finishFlush||qt.ZSTD_e_end,t.fullFlushFlag=qt.ZSTD_e_flush,super(t,e)}},E_=class extends Nf{constructor(t){super(t,"ZstdCompress")}},v_=class extends Nf{constructor(t){super(t,"ZstdDecompress")}},S_=(t,e)=>{if(Number.isSafeInteger(t))t<0?A_(t,e):I_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},I_=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},A_=(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]=Bf(o):o===0?e[i-1]=0:(n=!0,e[i-1]=Ff(o))}},k_=t=>{let e=t[0],n=e===128?C_(t.subarray(1,t.length)):e===255?T_(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},T_=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var a=Number(t[o]),d;i?d=Bf(a):a===0?d=a:(i=!0,d=Ff(a)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},C_=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},Bf=t=>(255^t)&255,Ff=t=>(255^t)+1&255,P_={};qw(P_,{code:()=>cd,isCode:()=>ro,isName:()=>R_,name:()=>_o,normalFsTypes:()=>zf});var ro=t=>_o.has(t),R_=t=>cd.has(t),zf=new Set(["0","","1","2","3","4","5","6","7","D"]),_o=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"]]),cd=new Map(Array.from(_o).map(t=>[t[1],t[0]])),D_=t=>t===void 0||t<0?void 0:t,Qn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,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=Wn(t,e+156,1),a=zf.has(o),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??Wn(t,e,100),this.mode=d?.mode??u?.mode??An(t,e+100,8),this.uid=d?.uid??u?.uid??An(t,e+108,8),this.gid=d?.gid??u?.gid??An(t,e+116,8),this.size=D_(d?.size??u?.size??An(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??Ec(t,e+136,12),this.cksum=An(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),ro(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Wn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Wn(t,e+265,32),this.gname=d?.gname??u?.gname??Wn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??An(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??An(t,e+337,8)??0,t[e+475]!==0){let h=Wn(t,e+345,155);this.path=h+"/"+this.path}else{let h=Wn(t,e+345,130);h&&(this.path=h+"/"+this.path),this.atime=n?.atime??i?.atime??Ec(t,e+476,12),this.ctime=n?.ctime??i?.ctime??Ec(t,e+488,12)}let f=256;for(let h=e;h<e+148;h++)f+=t[h];for(let h=e+156;h<e+512;h++)f+=t[h];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=O_(this.path||"",n),o=i[0],a=i[1];this.needPax=!!i[2],this.needPax=jn(t,e,100,o)||this.needPax,this.needPax=kn(t,e+100,8,this.mode)||this.needPax,this.needPax=kn(t,e+108,8,this.uid)||this.needPax,this.needPax=kn(t,e+116,8,this.gid)||this.needPax,this.needPax=kn(t,e+124,12,this.size)||this.needPax,this.needPax=vc(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=kn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=kn(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=vc(t,e+476,12,this.atime)||this.needPax,this.needPax=vc(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,kn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:_o.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(cd.get(t));if(ro(e)||e==="Unsupported")this.#e=e;else if(ro(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},O_=(t,e)=>{let n=t,i="",o,a=Tr.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=Tr.dirname(n),n=Tr.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=Tr.join(Tr.basename(i),n),i=Tr.dirname(i));while(i!==a&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Wn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),Ec=(t,e,n)=>L_(An(t,e,n)),L_=t=>t===void 0?void 0:new Date(t*1e3),An=(t,e,n)=>Number(t[e])&128?k_(t.subarray(e,e+n)):N_(t,e,n),M_=t=>isNaN(t)?void 0:t,N_=(t,e,n)=>M_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),B_={12:8589934591,8:2097151},kn=(t,e,n,i)=>i===void 0?!1:i>B_[n]||i<0?(S_(i,t.subarray(e,e+n)),!0):(F_(t,e,n,i),!1),F_=(t,e,n,i)=>t.write(z_(i,n),e,n,"ascii"),z_=(t,e)=>U_(Math.floor(t).toString(8),e),U_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",vc=(t,e,n,i)=>i===void 0?!1:kn(t,e,n,i.getTime()/1e3),H_=new Array(156).join("\0"),jn=(t,e,n,i)=>i===void 0?!1:(t.write(i+H_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),ho=class Uf{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 Qn({path:("PaxHeader/"+G_(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 Uf(q_(
|
|
91
|
-
`).reduce(j_,Object.create(null)),j_=(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},K_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,te=K_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),$_=class extends er{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))))}},yo=(t,e,n,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=n instanceof Error&&n.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(n instanceof Error&&(i=Object.assign(n,i),n=n.message),t.emit("warn",e,n,i)):n instanceof Error?t.emit("error",Object.assign(n,i)):t.emit("error",Object.assign(new Error(`${e}: ${n}`),i))},V_=1024*1024,Uc=Buffer.from([31,139]),Hc=Buffer.from([40,181,47,253]),J_=Math.max(Uc.length,Hc.length),yt=Symbol("state"),Kn=Symbol("writeEntry"),rn=Symbol("readEntry"),Sc=Symbol("nextEntry"),ef=Symbol("processEntry"),zt=Symbol("extendedHeader"),ki=Symbol("globalExtendedHeader"),En=Symbol("meta"),tf=Symbol("emitMeta"),we=Symbol("buffer"),sn=Symbol("queue"),vn=Symbol("ended"),Ic=Symbol("emittedEnd"),$n=Symbol("emit"),Ae=Symbol("unzip"),$s=Symbol("consumeChunk"),Vs=Symbol("consumeChunkSub"),Ac=Symbol("consumeBody"),nf=Symbol("consumeMeta"),rf=Symbol("consumeHeader"),Ti=Symbol("consuming"),kc=Symbol("bufferConcat"),Js=Symbol("maybeEnd"),Cr=Symbol("writing"),Ut=Symbol("aborted"),Zs=Symbol("onDone"),Vn=Symbol("sawValidEntry"),Ys=Symbol("sawNullBlock"),Xs=Symbol("sawEOF"),sf=Symbol("closeStream"),Z_=1e3,Ci=Symbol("compressedBytesRead"),Tc=Symbol("decompressedBytesRead"),of=Symbol("checkDecompressionRatio"),Y_=()=>!0,ji=class extends h_{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[sn]=[];[we];[rn];[Kn];[yt]="begin";[En]="";[zt];[ki];[vn]=!1;[Ae];[Ut]=!1;[Vn];[Ys]=!1;[Xs]=!1;[Cr]=!1;[Ti]=!1;[Ic]=!1;[Ci]=0;[Tc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Zs,()=>{(this[yt]==="begin"||this[Vn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Zs,t.ondone):this.on(Zs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:Z_,this.maxMetaEntrySize=t.maxMetaEntrySize||V_,this.filter=typeof t.filter=="function"?t.filter:Y_;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[sf]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){yo(this,t,e,n)}[rf](t,e){this[Vn]===void 0&&(this[Vn]=!1);let n;try{n=new Qn(t,e,this[zt],this[ki])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Ys]?(this[Xs]=!0,this[yt]==="begin"&&(this[yt]="header"),this[$n]("eof")):(this[Ys]=!0,this[$n]("nullBlock"));else if(this[Ys]=!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[Kn]=new $_(n,this[zt],this[ki]);if(!this[Vn])if(o.remain){let a=()=>{o.invalid||(this[Vn]=!0)};o.on("end",a)}else this[Vn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[$n]("ignoredEntry",o),this[yt]="ignore",o.resume()):o.size>0&&(this[En]="",o.on("data",a=>this[En]+=a),this[yt]="meta"):(this[zt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[$n]("ignoredEntry",o),this[yt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[yt]="body":(this[yt]="header",o.end()),this[rn]?this[sn].push(o):(this[sn].push(o),this[Sc]())))}}}[sf](){queueMicrotask(()=>this.emit("close"))}[ef](t){let e=!0;if(!t)this[rn]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[rn]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Sc]()),e=!1);return e}[Sc](){do;while(this[ef](this[sn].shift()));if(this[sn].length===0){let t=this[rn];!t||t.flowing||t.size===t.remain?this[Cr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Ac](t,e){let n=this[Kn];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[Kn]=void 0,n.end()),o.length}[nf](t,e){let n=this[Kn],i=this[Ac](t,e);return!this[Kn]&&n&&this[tf](n),i}[$n](t,e,n){this[sn].length===0&&!this[rn]?this.emit(t,e,n):this[sn].push([t,e,n])}[tf](t){switch(this[$n]("meta",this[En]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[zt]=ho.parse(this[En],this[zt],!1);break;case"GlobalExtendedHeader":this[ki]=ho.parse(this[En],this[ki],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[zt]??Object.create(null);this[zt]=e,e.path=this[En].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[zt]||Object.create(null);this[zt]=e,e.linkpath=this[En].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Ut]){if(this[Ae]){let e=this[Ae];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Ut]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[of](t){this[Tc]+=t.length;let e=this[Tc]/this[Ci];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[Ut])return n?.(),!1;if((this[Ae]===void 0||this.brotli===void 0&&this[Ae]===!1)&&t){if(this[we]&&(t=Buffer.concat([this[we],t]),this[we]=void 0),t.length<J_)return this[we]=t,n?.(),!0;for(let d=0;this[Ae]===void 0&&d<Uc.length;d++)t[d]!==Uc[d]&&(this[Ae]=!1);let o=!1;if(this[Ae]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Hc.length;d++)if(t[d]!==Hc[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[Ae]===!1&&a)if(t.length<512)if(this[vn])this.brotli=!0;else return this[we]=t,n?.(),!0;else try{new Qn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ae]===void 0||this[Ae]===!1&&(this.brotli||o)){let d=this[vn];this[vn]=!1,this[Ae]=this[Ae]===void 0?new __({}):o?new v_({}):new b_({}),this[Ae].on("data",f=>{this[of](f)&&this[$s](f)}),this[Ae].on("error",f=>{this[Ut]||this.abort(f)}),this[Ae].on("end",()=>{this[vn]=!0,this[$s]()}),this[Cr]=!0,this[Ci]+=t.length;let u=!!this[Ae][d?"end":"write"](t);return this[Cr]=!1,n?.(),u}}this[Cr]=!0,this[Ae]?(this[Ci]+=t.length,this[Ae].write(t)):this[$s](t),this[Cr]=!1;let i=this[sn].length>0?!1:this[rn]?this[rn].flowing:!0;return!i&&this[sn].length===0&&this[rn]?.once("drain",()=>this.emit("drain")),n?.(),i}[kc](t){t&&!this[Ut]&&(this[we]=this[we]?Buffer.concat([this[we],t]):t)}[Js](){if(this[vn]&&!this[Ic]&&!this[Ut]&&!this[Ti]){this[Ic]=!0;let t=this[Kn];if(t?.blockRemain){let e=this[we]?this[we].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[we]&&t.write(this[we]),t.end()}this[$n](Zs)}}[$s](t){if(this[Ti]&&t)this[kc](t);else if(!t&&!this[we])this[Js]();else if(t){if(this[Ti]=!0,this[we]){this[kc](t);let e=this[we];this[we]=void 0,this[Vs](e)}else this[Vs](t);for(;this[we]&&this[we]?.length>=512&&!this[Ut]&&!this[Xs];){let e=this[we];this[we]=void 0,this[Vs](e)}this[Ti]=!1}(!this[we]||this[vn])&&this[Js]()}[Vs](t){let e=0,n=t.length;for(;e+512<=n&&!this[Ut]&&!this[Xs];)switch(this[yt]){case"begin":case"header":this[rf](t,e),e+=512;break;case"ignore":case"body":e+=this[Ac](t,e);break;case"meta":e+=this[nf](t,e);break;default:throw new Error("invalid state: "+this[yt])}e<n&&(this[we]=this[we]?Buffer.concat([t.subarray(e),this[we]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[Ut]||(this[Ae]?(t&&(this[Ci]+=t.length,this[Ae].write(t)),this[Ae].end()):(this[vn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Js]())),this}},Fi=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)},X_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Hf=(t,e)=>{let n=new Map(e.map(a=>[Fi(a),!0])),i=t.filter,o=(a,d="")=>{let u=d||s_(a).root||".",f;if(a===u)f=!1;else{let h=n.get(a);f=h!==void 0?h:o(i_(a),u)}return n.set(a,f),f};t.filter=i?(a,d)=>i(a,d)&&o(Fi(a)):a=>o(Fi(a))},Q_=t=>{let e=new ji(t),n=t.file,i;try{i=Mr.openSync(n,"r");let o=Mr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),u=Mr.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=Mr.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{Mr.closeSync(i)}catch{}}},ey=(t,e)=>{let n=new ji(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Mr.stat(o,(u,f)=>{if(u)d(u);else{let h=new sd(o,{readSize:i,size:f.size});h.on("error",d),h.pipe(n)}})})},zr=Ki(Q_,ey,t=>new ji(t),t=>new ji(t),(t,e)=>{e?.length&&Hf(t,e),t.noResume||X_(t)}),Gf=(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:ny,parse:cf}=ty,dd=t=>{let e="",n=cf(t);for(;ny(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=cf(t)}return[e,t]},bo=["|","<",">","?",":"],ld=bo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),ry=new Map(bo.map((t,e)=>[t,ld[e]])),iy=new Map(ld.map((t,e)=>[t,bo[e]])),df=t=>bo.reduce((e,n)=>e.split(n).join(ry.get(n)),t),sy=t=>ld.reduce((e,n)=>e.split(n).join(iy.get(n)),t),qf=(t,e)=>e?(t=te(t).replace(/^\.(\/|$)/,""),Fi(e)+"/"+t):te(t),oy=16*1024*1024,lf=Symbol("process"),uf=Symbol("file"),ff=Symbol("directory"),Gc=Symbol("symlink"),hf=Symbol("hardlink"),Pi=Symbol("header"),io=Symbol("read"),qc=Symbol("lstat"),so=Symbol("onlstat"),Wc=Symbol("onread"),jc=Symbol("onreadlink"),Kc=Symbol("openfile"),$c=Symbol("onopenfile"),Tn=Symbol("close"),po=Symbol("mode"),Vc=Symbol("awaitDrain"),Cc=Symbol("ondrain"),Gt=Symbol("prefix"),Wf=class extends er{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=od(e);super(),this.path=te(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||oy,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]=dd(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=sy(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=te(n.absolute||af.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[so](o):this[qc]()}warn(t,e,n={}){return yo(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[qc](){Ht.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[so](e)})}[so](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=dy(t),this.emit("stat",t),this[lf]()}[lf](){switch(this.type){case"File":return this[uf]();case"Directory":return this[ff]();case"SymbolicLink":return this[Gc]();default:return this.end()}}[po](t){return Gf(t,this.type==="Directory",this.portable)}[Gt](t){return qf(t,this.prefix)}[Pi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Qn({path:this[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](this.linkpath):this.linkpath,mode:this[po](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 ho({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)}[ff](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Pi](),this.end()}[Gc](){Ht.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[jc](e)})}[jc](t){this.linkpath=te(t),this[Pi](),this.end()}[hf](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=te(af.relative(this.cwd,t)),this.stat.size=0,this[Pi](),this.end()}[uf](){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[hf](e);this.linkCache.set(t,this.absolute)}if(this[Pi](),this.stat.size===0)return this.end();this[Kc]()}[Kc](){Ht.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[$c](e)})}[$c](t){if(this.fd=t,this.#e)return this[Tn]();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[io]()}[io](){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");Ht.read(t,e,n,i,o,(a,d)=>{if(a)return this[Tn](()=>this.emit("error",a));this[Wc](d)})}[Tn](t=()=>{}){this.fd!==void 0&&Ht.close(this.fd,t)}[Wc](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[Tn](()=>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[Tn](()=>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[Cc]():this[Vc](()=>this[Cc]())}[Vc](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,n)}[Cc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Tn](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[io]()}},ay=class extends Wf{sync=!0;[qc](){this[so](Ht.lstatSync(this.absolute))}[Gc](){this[jc](Ht.readlinkSync(this.absolute))}[Kc](){this[$c](Ht.openSync(this.absolute,"r"))}[io](){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=Ht.readSync(e,n,i,o,a);this[Wc](d),t=!1}finally{if(t)try{this[Tn](()=>{})}catch{}}}[Vc](t){t()}[Tn](t=()=>{}){this.fd!==void 0&&Ht.closeSync(this.fd),t()}},cy=class extends er{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 yo(this,t,e,n)}constructor(t,e={}){let n=od(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[po](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,u]=dd(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 Qn({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 ho({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 qf(t,this.prefix)}[po](t){return Gf(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}},dy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",ly=class Nr{tail;head;length=0;static create(e=[]){return new Nr(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++)fy(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)hy(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 Nr;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 Nr;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 Nr;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 Nr;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=uy(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 uy(t,e,n){let i=e,o=e?e.next:t.head,a=new ud(n,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function fy(t,e){t.tail=new ud(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function hy(t,e){t.head=new ud(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var ud=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}},pf=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},gf=Buffer.alloc(1024),oo=Symbol("onStat"),Ri=Symbol("ended"),Pt=Symbol("queue"),Di=Symbol("pendingLinks"),Sn=Symbol("current"),Jn=Symbol("process"),Oi=Symbol("processing"),Qs=Symbol("processJob"),Rt=Symbol("jobs"),Pc=Symbol("jobDone"),ao=Symbol("addFSEntry"),mf=Symbol("addTarEntry"),Jc=Symbol("stat"),Zc=Symbol("readdir"),co=Symbol("onreaddir"),lo=Symbol("pipe"),wf=Symbol("entry"),Rc=Symbol("entryOpt"),uo=Symbol("writeEntryClass"),jf=Symbol("write"),Dc=Symbol("ondrain"),Eo=class extends er{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[uo];onWriteEntry;[Pt];[Di]=new Map;[Rt]=0;[Oi]=!1;[Ri]=!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[uo]=Wf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new w_(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new y_(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new E_(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[Dc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Dc]);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 ly,this[Rt]=0,this.jobs=Number(t.jobs)||4,this[Oi]=!1,this[Ri]=!1}[jf](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[Ri]=!0,this[Jn](),n&&n(),this}write(t){if(this[Ri])throw new Error("write after end");return typeof t=="string"?this[ao](t):this[mf](t),this.flowing}[mf](t){let e=te(xf.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new pf(t.path,e);n.entry=new cy(t,this[Rc](n)),n.entry.on("end",()=>this[Pc](n)),this[Rt]+=1,this[Pt].push(n)}this[Jn]()}[ao](t){let e=te(xf.resolve(this.cwd,t));this[Pt].push(new pf(t,e)),this[Jn]()}[Jc](t){t.pending=!0,this[Rt]+=1;let e=this.follow?"stat":"lstat";xo[e](t.absolute,(n,i)=>{t.pending=!1,this[Rt]-=1,n?this.emit("error",n):this[oo](t,i)})}[oo](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[Sn])this[Qs](t);else{let n=`${e.dev}:${e.ino}`,i=this[Di].get(n);i?i.push(t):this[Di].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Jn]()}[Zc](t){t.pending=!0,this[Rt]+=1,xo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[Rt]-=1,e)return this.emit("error",e);this[co](t,n)})}[co](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Jn]()}[Jn](){if(!this[Oi]){this[Oi]=!0;for(let t=this[Pt].head;t&&this[Rt]<this.jobs;t=t.next)if(this[Qs](t.value),t.value.ignore){let e=t.next;this[Pt].removeNode(t),t.next=e}this[Oi]=!1,this[Ri]&&this[Pt].length===0&&this[Rt]===0&&(this.zip?this.zip.end(gf):(super.write(gf),super.end()))}}get[Sn](){return this[Pt]&&this[Pt].head&&this[Pt].head.value}[Pc](t){this[Pt].shift(),this[Rt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Di].get(n);if(i){this[Di].delete(n);for(let o of i)o.pending=!1,this[Qs](o)}}this[Jn]()}[Qs](t){if(t.pending&&t.pendingLink&&t===this[Sn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Sn]&&!t.piped&&this[lo](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[oo](t,e):this[Jc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[co](t,e):this[Zc](t),!t.readdir)return}if(t.entry=this[wf](t),!t.entry){t.ignore=!0;return}t===this[Sn]&&!t.piped&&this[lo](t)}}}[Rc](t){return{onwarn:(e,n,i)=>this.warn(e,n,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[wf](t){this[Rt]+=1;try{return new this[uo](t.path,this[Rc](t)).on("end",()=>this[Pc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Dc](){this[Sn]&&this[Sn].entry&&this[Sn].entry.resume()}[lo](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[ao](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={}){yo(this,t,e,n)}},fd=class extends Eo{sync=!0;constructor(t){super(t),this[uo]=ay}pause(){}resume(){}[Jc](t){let e=this.follow?"statSync":"lstatSync";this[oo](t,xo[e](t.absolute))}[Zc](t){this[co](t,xo.readdirSync(t.absolute))}[lo](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[ao](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[jf](i)})}},xy=(t,e)=>{let n=new fd(t),i=new Df(t.file,{mode:t.mode||438});n.pipe(i),Kf(n,e)},py=(t,e)=>{let n=new Eo(t),i=new wo(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 $f(n,e).catch(a=>n.emit("error",a)),o},Kf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?zr({file:Of.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},$f=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await zr({file:Of.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},gy=(t,e)=>{let n=new fd(t);return Kf(n,e),n},my=(t,e)=>{let n=new Eo(t);return $f(n,e).catch(i=>n.emit("error",i)),n},U2=Ki(xy,py,gy,my,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),_y=process.env.__FAKE_PLATFORM__||process.platform,Yf=_y==="win32",{O_CREAT:Xf,O_NOFOLLOW:_f,O_TRUNC:Qf,O_WRONLY:e0}=Zf.constants,t0=Number(process.env.__FAKE_FS_O_FILENAME__)||Zf.constants.UV_FS_O_FILEMAP||0,yy=Yf&&!!t0,by=512*1024,Ey=t0|Qf|Xf|e0,yf=!Yf&&typeof _f=="number"?_f|Qf|Xf|e0:null,n0=yf!==null?()=>yf:yy?t=>t<by?Ey:"w":()=>"w",Yc=(t,e,n)=>{try{return vo.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},go=(t,e,n,i)=>{vo.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},vy=(t,e,n,i,o)=>{if(e.isDirectory())r0(zi.resolve(t,e.name),n,i,a=>{if(a)return o(a);let d=zi.resolve(t,e.name);go(d,n,i,o)});else{let a=zi.resolve(t,e.name);go(a,n,i,o)}},r0=(t,e,n,i)=>{vo.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 go(t,e,n,i);let d=a.length,u=null,f=h=>{if(!u){if(h)return i(u=h);if(--d===0)return go(t,e,n,i)}};for(let h of a)vy(t,h,e,n,f)})},Sy=(t,e,n,i)=>{e.isDirectory()&&i0(zi.resolve(t,e.name),n,i),Yc(zi.resolve(t,e.name),n,i)},i0=(t,e,n)=>{let i;try{i=vo.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Yc(t,e,n);throw a}for(let o of i)Sy(t,o,e,n);return Yc(t,e,n)},s0=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},So=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},Ay=(t,e)=>{pt.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new s0(t,n?.code||"ENOTDIR")),e(n)})},ky=(t,e,n)=>{t=te(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),h=e.preserve,p=e.unlink,g=te(e.cwd),y=(b,I)=>{b?n(b):I&&f?r0(I,d,u,k=>y(k)):a?pt.chmod(t,o,n):n()};if(t===g)return Ay(t,y);if(h)return Iy.mkdir(t,{mode:o,recursive:!0}).then(b=>y(null,b??void 0),y);let _=te(mo.relative(g,t)).split("/");Xc(g,_,o,p,g,void 0,y)},Xc=(t,e,n,i,o,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),f=te(mo.resolve(t+"/"+u));pt.mkdir(f,n,o0(f,e,n,i,o,a,d))},o0=(t,e,n,i,o,a,d)=>u=>{u?pt.lstat(t,(f,h)=>{if(f)f.path=f.path&&te(f.path),d(f);else if(h.isDirectory())Xc(t,e,n,i,o,a,d);else if(i)pt.unlink(t,p=>{if(p)return d(p);pt.mkdir(t,n,o0(t,e,n,i,o,a,d))});else{if(h.isSymbolicLink())return d(new So(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,Xc(t,e,n,i,o,a,d))},Ty=t=>{let e=!1,n;try{e=pt.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new s0(t,n??"ENOTDIR")}},Cy=(t,e)=>{t=te(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,h=e.unlink,p=te(e.cwd),g=b=>{b&&u&&i0(b,a,d),o&&pt.chmodSync(t,i)};if(t===p)return Ty(p),g();if(f)return g(pt.mkdirSync(t,{mode:i,recursive:!0})??void 0);let y=te(mo.relative(p,t)).split("/"),_;for(let b=y.shift(),I=p;b&&(I+="/"+b);b=y.shift()){I=te(mo.resolve(I));try{pt.mkdirSync(I,i),_=_||I}catch{let k=pt.lstatSync(I);if(k.isDirectory())continue;if(h){pt.unlinkSync(I),pt.mkdirSync(I,i),_=_||I;continue}else if(k.isSymbolicLink())return new So(I,I+"/"+y.join("/"))}}return g(_)},Oc=Object.create(null),bf=1e4,Pr=new Set,Py=t=>{Pr.has(t)?Pr.delete(t):Oc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Pr.add(t);let e=Oc[t],n=Pr.size-bf;if(n>bf/10){for(let i of Pr)if(Pr.delete(i),delete Oc[i],--n<=0)break}return e},Ry=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Dy=Ry==="win32",Oy=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=a0(i,n)),e.push(n||"/"),e},[]),Ly=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=Dy?["win32 parallelization disabled"]:t.map(i=>Fi(a0(Py(i))));let n=new Set(t.map(i=>Oy(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}},My=()=>process.umask(),Ef=Symbol("onEntry"),Qc=Symbol("checkFs"),vf=Symbol("checkFs2"),ed=Symbol("isReusable"),bt=Symbol("makeFs"),td=Symbol("file"),nd=Symbol("directory"),fo=Symbol("link"),Sf=Symbol("symlink"),If=Symbol("hardlink"),Ni=Symbol("ensureNoSymlink"),Af=Symbol("unsupported"),kf=Symbol("checkPath"),Lc=Symbol("stripAbsolutePath"),Cn=Symbol("mkdir"),qe=Symbol("onError"),eo=Symbol("pending"),Tf=Symbol("pend"),Rr=Symbol("unpend"),Mc=Symbol("ended"),Nc=Symbol("maybeClose"),rd=Symbol("skip"),Ui=Symbol("doChown"),Hi=Symbol("uid"),Gi=Symbol("gid"),qi=Symbol("checkedCwd"),Ny=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Wi=Ny==="win32",By=1024,Fy=(t,e)=>{if(!Wi)return se.unlink(t,e);let n=t+".DELETE."+Jf(16).toString("hex");se.rename(t,n,i=>{if(i)return e(i);se.unlink(n,e)})},zy=t=>{if(!Wi)return se.unlinkSync(t);let e=t+".DELETE."+Jf(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},Cf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,hd=class extends ji{[Mc]=!1;[qi]=!1;[eo]=0;reservations=new Ly;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[Mc]=!0,this[Nc]()},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:By,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Wi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=te(Be.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:My():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Ef](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Nc](){this[Mc]&&this[eo]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Lc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,a]=dd(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Wi&&/^[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=Be.posix.dirname(t.path),f=Be.posix.normalize(Be.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}[kf](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[Lc](t,"path")||!this[Lc](t,"linkpath"))return!1;if(t.absolute=Be.isAbsolute(t.path)?te(Be.resolve(t.path)):te(Be.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path: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}=Be.win32.parse(String(t.absolute));t.absolute=i+df(String(t.absolute).slice(i.length));let{root:o}=Be.win32.parse(t.path);t.path=o+df(t.path.slice(o.length))}return!0}[Ef](t){if(!this[kf](t))return t.resume();switch(wy.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[Qc](t);default:return this[Af](t)}}[qe](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Rr](),e.resume())}[Cn](t,e,n){ky(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)}[Ui](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}[Hi](t){return Cf(this.uid,t.uid,this.processUid)}[Gi](t){return Cf(this.gid,t.gid,this.processGid)}[td](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new wo(String(t.absolute),{flags:n0(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[qe](u,t),e()});let o=1,a=u=>{if(u){i.fd&&se.close(i.fd,()=>{}),this[qe](u,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,f=>{f?this[qe](f,t):this[Rr](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let h=t.atime||new Date,p=t.mtime;se.futimes(f,h,p,g=>g?se.utimes(u,h,p,y=>a(y&&g)):a())}if(typeof f=="number"&&this[Ui](t)){o++;let h=this[Hi](t),p=this[Gi](t);typeof h=="number"&&typeof p=="number"&&se.fchown(f,h,p,g=>g?se.chown(u,h,p,y=>a(y&&g)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[qe](u,t),e()}),t.pipe(d)),d.pipe(i)}[nd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Cn](String(t.absolute),n,i=>{if(i){this[qe](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[Rr](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Ui](t)&&(o++,se.chown(String(t.absolute),Number(this[Hi](t)),Number(this[Gi](t)),a)),a()})}[Af](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Sf](t,e){let n=te(Be.relative(this.cwd,Be.resolve(Be.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ni](t,this.cwd,n,()=>this[fo](t,String(t.linkpath),"symlink",e),i=>{this[qe](i,t),e()})}[If](t,e){let n=te(Be.resolve(this.cwd,String(t.linkpath))),i=te(String(t.linkpath)).split("/");this[Ni](t,this.cwd,i,()=>this[fo](t,n,"link",e),o=>{this[qe](o,t),e()})}[Ni](t,e,n,i,o){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Be.resolve(e,a);se.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new So(d,Be.resolve(d,n.join("/"))));this[Ni](t,d,n,i,o)})}[Tf](){this[eo]++}[Rr](){this[eo]--,this[Nc]()}[rd](t){this[Rr](),t.resume()}[ed](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Wi}[Qc](t){this[Tf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[vf](t,n))}[vf](t,e){let n=d=>{e(d)},i=()=>{this[Cn](this.cwd,this.dmode,d=>{if(d){this[qe](d,t),n();return}this[qi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=te(Be.dirname(String(t.absolute)));if(d!==this.cwd)return this[Cn](d,this.dmode,u=>{if(u){this[qe](u,t),n();return}a()})}a()},a=()=>{se.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[rd](t),n();return}if(d||this[ed](t,u))return this[bt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,h=p=>this[bt](p??null,t,n);return f?se.chmod(String(t.absolute),Number(t.mode),h):h()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),f=>this[bt](f??null,t,n))}if(t.absolute===this.cwd)return this[bt](null,t,n);Fy(String(t.absolute),f=>this[bt](f??null,t,n))})};this[qi]?o():i()}[bt](t,e,n){if(t){this[qe](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[td](e,n);case"Link":return this[If](e,n);case"SymbolicLink":return this[Sf](e,n);case"Directory":case"GNUDumpDir":return this[nd](e,n)}}[fo](t,e,n,i){se[n](e,String(t.absolute),o=>{o?this[qe](o,t):(this[Rr](),t.resume()),i()})}},Li=t=>{try{return[null,t()]}catch(e){return[e,null]}},c0=class extends hd{sync=!0;[bt](t,e){return super[bt](t,e,()=>{})}[Qc](t){if(!this[qi]){let o=this[Cn](this.cwd,this.dmode);if(o)return this[qe](o,t);this[qi]=!0}if(t.absolute!==this.cwd){let o=te(Be.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[Cn](o,this.dmode);if(a)return this[qe](a,t)}}let[e,n]=Li(()=>se.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[rd](t);if(e||this[ed](t,n))return this[bt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Li(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[bt](d,t)}let[o]=Li(()=>se.rmdirSync(String(t.absolute)));this[bt](o,t)}let[i]=t.absolute===this.cwd?[]:Li(()=>zy(String(t.absolute)));this[bt](i,t)}[td](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{se.closeSync(o)}catch(f){u=f}(d||u)&&this[qe](d||u,t),e()},o;try{o=se.openSync(String(t.absolute),n0(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[qe](d,t)),t.pipe(a)),a.on("data",d=>{try{se.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{se.futimesSync(o,u,f)}catch(h){try{se.utimesSync(String(t.absolute),u,f)}catch{d=h}}}if(this[Ui](t)){let u=this[Hi](t),f=this[Gi](t);try{se.fchownSync(o,Number(u),Number(f))}catch(h){try{se.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||h}}}i(d)})}[nd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Cn](String(t.absolute),n);if(i){this[qe](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ui](t))try{se.chownSync(String(t.absolute),Number(this[Hi](t)),Number(this[Gi](t)))}catch{}e(),t.resume()}[Cn](t,e){try{return Cy(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}}[Ni](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=Be.resolve(a,d);let[u,f]=Li(()=>se.lstatSync(a));if(u)return i();if(f.isSymbolicLink())return o(new So(a,Be.resolve(e,n.join("/"))))}i()}[fo](t,e,n,i){let o=`${n}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[qe](a,t)}}},Uy=t=>{let e=new c0(t),n=t.file,i=Vf.statSync(n),o=t.maxReadSize||16*1024*1024;new r_(n,{readSize:o,size:i.size}).pipe(e)},Hy=(t,e)=>{let n=new hd(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Vf.stat(o,(u,f)=>{if(u)d(u);else{let h=new sd(o,{readSize:i,size:f.size});h.on("error",d),h.pipe(n)}})})},d0=Ki(Uy,Hy,t=>new c0(t),t=>new hd(t),(t,e)=>{e?.length&&Hf(t,e)}),Gy=(t,e)=>{let n=new fd(t),i=!0,o,a;try{try{o=xt.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=xt.openSync(t.file,"w+");else throw f}let d=xt.fstatSync(o),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let p=0,g=0;p<512;p+=g){if(g=xt.readSync(o,u,p,u.length-p,a+p),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!g)break e}let f=new Qn(u);if(!f.cksumValid)break;let h=512*Math.ceil((f.size||0)/512);if(a+h+512>d.size)break;a+=h,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,qy(t,n,a,o,e)}finally{if(i)try{xt.closeSync(o)}catch{}}},qy=(t,e,n,i,o)=>{let a=new Df(t.file,{fd:i,start:n});e.pipe(a),jy(e,o)},Wy=(t,e)=>{e=Array.from(e);let n=new Eo(t),i=(o,a,d)=>{let u=(y,_)=>{y?xt.close(o,b=>d(y)):d(null,_)},f=0;if(a===0)return u(null,0);let h=0,p=Buffer.alloc(512),g=(y,_)=>{if(y||_===void 0)return u(y);if(h+=_,h<512&&_)return xt.read(o,p,h,p.length-h,f+h,g);if(f===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(h<512)return u(null,f);let b=new Qn(p);if(!b.cksumValid)return u(null,f);let I=512*Math.ceil((b.size??0)/512);if(f+I+512>a||(f+=I+512,f>=a))return u(null,f);t.mtimeCache&&b.mtime&&t.mtimeCache.set(String(b.path),b.mtime),h=0,xt.read(o,p,0,512,f,g)};xt.read(o,p,0,512,f,g)};return new Promise((o,a)=>{n.on("error",a);let d="r+",u=(f,h)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",xt.open(t.file,d,u);if(f||!h)return a(f);xt.fstat(h,(p,g)=>{if(p)return xt.close(h,()=>a(p));i(h,g.size,(y,_)=>{if(y)return a(y);let b=new wo(t.file,{fd:h,start:_});n.pipe(b),b.on("error",a),b.on("close",o),Ky(n,e)})})};xt.open(t.file,d,u)})},jy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?zr({file:l0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Ky=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await zr({file:l0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Mi=Ki(Gy,Wy,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!u_(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")}),tT=Ki(Mi.syncFile,Mi.asyncFile,Mi.syncNoFile,Mi.asyncNoFile,(t,e=[])=>{Mi.validate?.(t,e),$y(t)}),$y=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))};en();var nt={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 tr(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function u0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function Io(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function f0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function h0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function x0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function nr(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Tt();import{homedir as Jy}from"node:os";import p0 from"node:path";var g0=".claude",m0="settings.json",Ao=new Map;function w0(t){return p0.join(t,g0,m0)}async function _0(t,e){let n=w0(t),o=(Ao.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>{let a=await Ye(n)??{};a.effortLevel=e,await ft(n,a)});Ao.set(n,o);try{await o}finally{Ao.get(n)===o&&Ao.delete(n)}}async function y0(t){let n=(await Ye(w0(t)))?.effortLevel;return typeof n=="string"?n:void 0}async function b0(){let t=p0.join(Jy(),g0,m0),n=(await Ye(t))?.effortLevel;return typeof n=="string"?n:void 0}Wt();$e();ne();Te();$e();function $i(t,e){if(tr(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function xd(t,e){if(tr(t)==="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_CLOUD",`${e} is not allowed for cloud agent`)}function Vi(t){return t.startsWith("http://")||t.startsWith("https://")}function Ur(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as ZT}from"node:fs";import{dirname as XT,join as QT}from"node:path";import{fileURLToPath as tC}from"node:url";var jt="0.3.2-beta.1";var pd={"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 S0(t,e){return pd[t][e]}import{mkdir as ub,rm as z0}from"node:fs/promises";import{join as Xi}from"node:path";Tt();import{readFileSync as nb}from"node:fs";var rb=384;async function gd(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await ft(t.agentEnvFile,n,{mode:rb})}function rr(t){try{let e=JSON.parse(nb(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function To(t,e,n={},i=o=>o){return{...i({...t,...rr(e)}),...n}}Tt();function Ji(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(ib(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
|
|
89
|
+
`},configPath(t){return XA(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 kg("schtasks",["/Create","/SC","ONLOGON","/TN",Na,"/TR",n,"/RU",t.userName,"/F"]),Rl.info("task scheduler entry created",{task:Na,logFile:t.logFile})},async uninstall(t){await kg("schtasks",["/Delete","/TN",Na,"/F"]).catch(e=>Rl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Rl.info("task scheduler entry removed",{task:Na})}}});var Tg={};Za(Tg,{buildContext:()=>ik,getSupervisor:()=>tk,launchdSupervisor:()=>Tl,systemdSupervisor:()=>Pl,taskSchedulerSupervisor:()=>Ol});import{homedir as QA,userInfo as ek}from"node:os";function tk(t=process.platform){switch(t){case"darwin":return Tl;case"linux":return Pl;case"win32":return Ol;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function rk(){let t={};for(let e of nk){let n=process.env[e];n&&(t[e]=n)}return t}function ik(){let t=Z();return{nodeBin:process.execPath,entry:yl(t),logFile:t.logFile,homeDir:QA(),userName:ek().username,isRoot:process.getuid?.()===0,env:rk()}}var nk,Pg=it(()=>{"use strict";Ce();Aa();Sg();Ag();Cg();nk=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();wn();var cu=G("acp-installer-warmup"),iw=["claude-code","codex"];async function du(t={}){let e=t.ensure??Er,i=(await Promise.allSettled(iw.map(async o=>{let a=await e(o);cu.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&cu.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}Qt();ne();import{readdir as yw}from"node:fs/promises";import{mkdir as hu,readFile as ww,writeFile as xu}from"node:fs/promises";import{join as rc}from"node:path";var _w={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function vr(t,e,n){await hu(t,{recursive:!0});let i=_w[e],o=rc(t,i);return await xu(o,n??"","utf8"),o}async function ic(t,e,n){let i=rc(t,".claude");await hu(i,{recursive:!0});let o=rc(i,"settings.local.json"),a={};try{let u=await ww(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 xu(o,JSON.stringify(a,null,2),"utf8"),o}var Xe=G("agent-detail-sync"),bw=6e4,Ew=5*6e4,Ms=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await yw(n)}catch(o){Xe.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}Xe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let a=await me(o,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){Xe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,a)}catch(d){Xe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Xe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&n.push(i);if(n.length!==0){Xe.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){Xe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await me(e,this.opts.paths);if(!i){Xe.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,Ew):bw;this.retryQueue.set(e,{dueAt:Date.now()+p,currentDelay:p});return}if(o.agentId&&o.agentId!==e){Xe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let a=!1,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,a=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,a=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,a=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Xe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):o.deployType&&Xe.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){Xe.debug("detail sync: no diff",{agentId:e});return}await Te(i,this.opts.paths),Xe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Xe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await vr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Ld=Xt($u(),1);import{createHash as Eb}from"node:crypto";import{lstat as Ad,mkdir as kd,readFile as Oo,readdir as Q0,rm as Cd,stat as Od,writeFile as Td}from"node:fs/promises";import{homedir as vb}from"node:os";import{basename as Z0,dirname as Sb,join as xe,normalize as Ib,relative as Dd,resolve as Pd,sep as eh}from"node:path";import{Readable as th}from"node:stream";import{pipeline as nh}from"node:stream/promises";import jw from"events";import ot from"fs";import{EventEmitter as id}from"node:events";import Pf from"node:stream";import{StringDecoder as Ww}from"node:string_decoder";import Df from"node:path";import Mr from"node:fs";import{dirname as i_,parse as s_}from"path";import{EventEmitter as h_}from"events";import zc from"assert";import{Buffer as Yn}from"buffer";import*as Xu from"zlib";import x_ from"zlib";import{posix as Cr}from"node:path";import{basename as G_}from"node:path";import xo from"fs";import zt from"fs";import af from"path";import{win32 as ty}from"node:path";import xf from"path";import Vf from"node:fs";import wy from"node:assert";import{randomBytes as Jf}from"node:crypto";import se from"node:fs";import Be from"node:path";import Zf from"fs";import vo from"node:fs";import zi from"node:path";import ht from"node:fs";import Iy from"node:fs/promises";import mo from"node:path";import{join as a0}from"node:path";import ft from"node:fs";import l0 from"node:path";var Gw=Object.defineProperty,qw=(t,e)=>{for(var n in e)Gw(t,n,{get:e[n],enumerable:!0})},Vu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Kw=t=>!!t&&typeof t=="object"&&(t instanceof er||t instanceof Pf||$w(t)||Vw(t)),$w=t=>!!t&&typeof t=="object"&&t instanceof id&&typeof t.pipe=="function"&&t.pipe!==Pf.Writable.prototype.pipe,Vw=t=>!!t&&typeof t=="object"&&t instanceof id&&typeof t.write=="function"&&typeof t.end=="function",en=Symbol("EOF"),tn=Symbol("maybeEmitEnd"),yn=Symbol("emittedEnd"),Us=Symbol("emittingEnd"),bi=Symbol("emittedError"),Hs=Symbol("closed"),Ju=Symbol("read"),Gs=Symbol("flush"),Zu=Symbol("flushChunk"),kt=Symbol("encoding"),kr=Symbol("decoder"),He=Symbol("flowing"),Ei=Symbol("paused"),Or=Symbol("resume"),Ge=Symbol("buffer"),Qe=Symbol("pipes"),qe=Symbol("bufferLength"),lc=Symbol("bufferPush"),qs=Symbol("bufferShift"),Ye=Symbol("objectMode"),Pe=Symbol("destroyed"),uc=Symbol("error"),fc=Symbol("emitData"),Yu=Symbol("emitEnd"),hc=Symbol("emitEnd2"),Mt=Symbol("async"),xc=Symbol("abort"),js=Symbol("aborted"),vi=Symbol("signal"),Gn=Symbol("dataListeners"),ut=Symbol("discarded"),Si=t=>Promise.resolve().then(t),Jw=t=>t(),Zw=t=>t==="end"||t==="finish"||t==="prefinish",Yw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Xw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Rf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Or](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Qw=class extends Rf{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)}},e_=t=>!!t.objectMode,t_=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",er=class extends id{[He]=!1;[Ei]=!1;[Qe]=[];[Ge]=[];[Ye];[kt];[Mt];[kr];[en]=!1;[yn]=!1;[Us]=!1;[Hs]=!1;[bi]=null;[qe]=0;[Pe]=!1;[vi];[js]=!1;[Gn]=0;[ut]=!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");e_(e)?(this[Ye]=!0,this[kt]=null):t_(e)?(this[kt]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[kt]=null),this[Mt]=!!e.async,this[kr]=this[kt]?new Ww(this[kt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ge]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:n}=e;n&&(this[vi]=n,n.aborted?this[xc]():n.addEventListener("abort",()=>this[xc]()))}get bufferLength(){return this[qe]}get encoding(){return this[kt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Mt]}set async(t){this[Mt]=this[Mt]||!!t}[xc](){this[js]=!0,this.emit("abort",this[vi]?.reason),this.destroy(this[vi]?.reason)}get aborted(){return this[js]}set aborted(t){}write(t,e,n){if(this[js])return!1;if(this[en])throw new Error("write after end");if(this[Pe])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[Mt]?Si:Jw;if(!this[Ye]&&!Buffer.isBuffer(t)){if(Xw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Yw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ye]?(this[He]&&this[qe]!==0&&this[Gs](!0),this[He]?this.emit("data",t):this[lc](t),this[qe]!==0&&this.emit("readable"),n&&i(n),this[He]):t.length?(typeof t=="string"&&!(e===this[kt]&&!this[kr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[kt]&&(t=this[kr].write(t)),this[He]&&this[qe]!==0&&this[Gs](!0),this[He]?this.emit("data",t):this[lc](t),this[qe]!==0&&this.emit("readable"),n&&i(n),this[He]):(this[qe]!==0&&this.emit("readable"),n&&i(n),this[He])}read(t){if(this[Pe])return null;if(this[ut]=!1,this[qe]===0||t===0||t&&t>this[qe])return this[tn](),null;this[Ye]&&(t=null),this[Ge].length>1&&!this[Ye]&&(this[Ge]=[this[kt]?this[Ge].join(""):Buffer.concat(this[Ge],this[qe])]);let e=this[Ju](t||null,this[Ge][0]);return this[tn](),e}[Ju](t,e){if(this[Ye])this[qs]();else{let n=e;t===n.length||t===null?this[qs]():typeof n=="string"?(this[Ge][0]=n.slice(t),e=n.slice(0,t),this[qe]-=t):(this[Ge][0]=n.subarray(t),e=n.subarray(0,t),this[qe]-=t)}return this.emit("data",e),!this[Ge].length&&!this[en]&&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[en]=!0,this.writable=!1,(this[He]||!this[Ei])&&this[tn](),this}[Or](){this[Pe]||(!this[Gn]&&!this[Qe].length&&(this[ut]=!0),this[Ei]=!1,this[He]=!0,this.emit("resume"),this[Ge].length?this[Gs]():this[en]?this[tn]():this.emit("drain"))}resume(){return this[Or]()}pause(){this[He]=!1,this[Ei]=!0,this[ut]=!1}get destroyed(){return this[Pe]}get flowing(){return this[He]}get paused(){return this[Ei]}[lc](t){this[Ye]?this[qe]+=1:this[qe]+=t.length,this[Ge].push(t)}[qs](){return this[Ye]?this[qe]-=1:this[qe]-=this[Ge][0].length,this[Ge].shift()}[Gs](t=!1){do;while(this[Zu](this[qs]())&&this[Ge].length);!t&&!this[Ge].length&&!this[en]&&this.emit("drain")}[Zu](t){return this.emit("data",t),this[He]}pipe(t,e){if(this[Pe])return t;this[ut]=!1;let n=this[yn];return e=e||{},t===Vu.stdout||t===Vu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[Qe].push(e.proxyErrors?new Qw(this,t,e):new Rf(this,t,e)),this[Mt]?Si(()=>this[Or]()):this[Or]()),t}unpipe(t){let e=this[Qe].find(n=>n.dest===t);e&&(this[Qe].length===1?(this[He]&&this[Gn]===0&&(this[He]=!1),this[Qe]=[]):this[Qe].splice(this[Qe].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[ut]=!1,this[Gn]++,!this[Qe].length&&!this[He]&&this[Or]();else if(t==="readable"&&this[qe]!==0)super.emit("readable");else if(Zw(t)&&this[yn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[bi]){let i=e;this[Mt]?Si(()=>i.call(this,this[bi])):i.call(this,this[bi])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Gn]=this.listeners("data").length,this[Gn]===0&&!this[ut]&&!this[Qe].length&&(this[He]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Gn]=0,!this[ut]&&!this[Qe].length&&(this[He]=!1)),e}get emittedEnd(){return this[yn]}[tn](){!this[Us]&&!this[yn]&&!this[Pe]&&this[Ge].length===0&&this[en]&&(this[Us]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Hs]&&this.emit("close"),this[Us]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Pe&&this[Pe])return!1;if(t==="data")return!this[Ye]&&!n?!1:this[Mt]?(Si(()=>this[fc](n)),!0):this[fc](n);if(t==="end")return this[Yu]();if(t==="close"){if(this[Hs]=!0,!this[yn]&&!this[Pe])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[bi]=n,super.emit(uc,n);let o=!this[vi]||this.listeners("error").length?super.emit("error",n):!1;return this[tn](),o}else if(t==="resume"){let o=super.emit("resume");return this[tn](),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[tn](),i}[fc](t){for(let n of this[Qe])n.dest.write(t)===!1&&this.pause();let e=this[ut]?!1:super.emit("data",t);return this[tn](),e}[Yu](){return this[yn]?!1:(this[yn]=!0,this.readable=!1,this[Mt]?(Si(()=>this[hc]()),!0):this[hc]())}[hc](){if(this[kr]){let e=this[kr].end();if(e){for(let n of this[Qe])n.dest.write(e);this[ut]||super.emit("data",e)}}for(let e of this[Qe])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ye]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Ye]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Ye])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[kt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Pe,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ut]=!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[en])return e();let i,o,a=x=>{this.off("data",d),this.off("end",u),this.off(Pe,f),e(),o(x)},d=x=>{this.off("error",a),this.off("end",u),this.off(Pe,f),this.pause(),i({value:x,done:!!this[en]})},u=()=>{this.off("error",a),this.off("data",d),this.off(Pe,f),e(),i({done:!0,value:void 0})},f=()=>a(new Error("stream destroyed"));return new Promise((x,p)=>{o=p,i=x,this.once(Pe,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[ut]=!1;let t=!1,e=()=>(this.pause(),this.off(uc,e),this.off(Pe,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(uc,e),this.once(Pe,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Pe])return t?this.emit("error",t):this.emit(Pe),this;this[Pe]=!0,this[ut]=!0,this[Ge].length=0,this[qe]=0;let e=this;return typeof e.close=="function"&&!this[Hs]&&e.close(),t?this.emit("error",t):this.emit(Pe),this}static get isStream(){return Kw}},n_=ot.writev,Tn=Symbol("_autoClose"),Rt=Symbol("_close"),Ii=Symbol("_ended"),he=Symbol("_fd"),pc=Symbol("_finished"),on=Symbol("_flags"),gc=Symbol("_flush"),Fc=Symbol("_handleChunk"),Bc=Symbol("_makeBuf"),Fi=Symbol("_mode"),Ws=Symbol("_needDrain"),Fr=Symbol("_onerror"),Br=Symbol("_onopen"),mc=Symbol("_onread"),Dr=Symbol("_onwrite"),Pn=Symbol("_open"),Pt=Symbol("_path"),Sn=Symbol("_pos"),Nt=Symbol("_queue"),Lr=Symbol("_read"),wc=Symbol("_readSize"),sn=Symbol("_reading"),Ai=Symbol("_remain"),_c=Symbol("_size"),to=Symbol("_write"),qn=Symbol("_writing"),no=Symbol("_defaultFlag"),Zn=Symbol("_errored"),sd=class extends er{[Zn]=!1;[he];[Pt];[wc];[sn]=!1;[_c];[Ai];[Tn];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[Zn]=!1,this[he]=typeof e.fd=="number"?e.fd:void 0,this[Pt]=t,this[wc]=e.readSize||16*1024*1024,this[sn]=!1,this[_c]=typeof e.size=="number"?e.size:1/0,this[Ai]=this[_c],this[Tn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[he]=="number"?this[Lr]():this[Pn]()}get fd(){return this[he]}get path(){return this[Pt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Pn](){ot.open(this[Pt],"r",(t,e)=>this[Br](t,e))}[Br](t,e){t?this[Fr](t):(this[he]=e,this.emit("open",e),this[Lr]())}[Bc](){return Buffer.allocUnsafe(Math.min(this[wc],this[Ai]))}[Lr](){if(!this[sn]){this[sn]=!0;let t=this[Bc]();if(t.length===0)return process.nextTick(()=>this[mc](null,0,t));ot.read(this[he],t,0,t.length,null,(e,n,i)=>this[mc](e,n,i))}}[mc](t,e,n){this[sn]=!1,t?this[Fr](t):this[Fc](e,n)&&this[Lr]()}[Rt](){if(this[Tn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Fr](t){this[sn]=!0,this[Rt](),this.emit("error",t)}[Fc](t,e){let n=!1;return this[Ai]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[Ai]<=0)&&(n=!1,this[Rt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[he]=="number"&&this[Lr](),!1;case"error":return this[Zn]?!1:(this[Zn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},r_=class extends sd{[Pn](){let t=!0;try{this[Br](null,ot.openSync(this[Pt],"r")),t=!1}finally{t&&this[Rt]()}}[Lr](){let t=!0;try{if(!this[sn]){this[sn]=!0;do{let e=this[Bc](),n=e.length===0?0:ot.readSync(this[he],e,0,e.length,null);if(!this[Fc](n,e))break}while(!0);this[sn]=!1}t=!1}finally{t&&this[Rt]()}}[Rt](){if(this[Tn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ot.closeSync(t),this.emit("close")}}},wo=class extends jw{readable=!1;writable=!0;[Zn]=!1;[qn]=!1;[Ii]=!1;[Nt]=[];[Ws]=!1;[Pt];[Fi];[Tn];[he];[no];[on];[pc]=!1;[Sn];constructor(t,e){e=e||{},super(e),this[Pt]=t,this[he]=typeof e.fd=="number"?e.fd:void 0,this[Fi]=e.mode===void 0?438:e.mode,this[Sn]=typeof e.start=="number"?e.start:void 0,this[Tn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[Sn]!==void 0?"r+":"w";this[no]=e.flags===void 0,this[on]=e.flags===void 0?n:e.flags,this[he]===void 0&&this[Pn]()}emit(t,...e){if(t==="error"){if(this[Zn])return!1;this[Zn]=!0}return super.emit(t,...e)}get fd(){return this[he]}get path(){return this[Pt]}[Fr](t){this[Rt](),this[qn]=!0,this.emit("error",t)}[Pn](){ot.open(this[Pt],this[on],this[Fi],(t,e)=>this[Br](t,e))}[Br](t,e){this[no]&&this[on]==="r+"&&t&&t.code==="ENOENT"?(this[on]="w",this[Pn]()):t?this[Fr](t):(this[he]=e,this.emit("open",e),this[qn]||this[gc]())}end(t,e){return t&&this.write(t,e),this[Ii]=!0,!this[qn]&&!this[Nt].length&&typeof this[he]=="number"&&this[Dr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Ii]?(this.emit("error",new Error("write() after end()")),!1):this[he]===void 0||this[qn]||this[Nt].length?(this[Nt].push(t),this[Ws]=!0,!1):(this[qn]=!0,this[to](t),!0)}[to](t){ot.write(this[he],t,0,t.length,this[Sn],(e,n)=>this[Dr](e,n))}[Dr](t,e){t?this[Fr](t):(this[Sn]!==void 0&&typeof e=="number"&&(this[Sn]+=e),this[Nt].length?this[gc]():(this[qn]=!1,this[Ii]&&!this[pc]?(this[pc]=!0,this[Rt](),this.emit("finish")):this[Ws]&&(this[Ws]=!1,this.emit("drain"))))}[gc](){if(this[Nt].length===0)this[Ii]&&this[Dr](null,0);else if(this[Nt].length===1)this[to](this[Nt].pop());else{let t=this[Nt];this[Nt]=[],n_(this[he],t,this[Sn],(e,n)=>this[Dr](e,n))}}[Rt](){if(this[Tn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Of=class extends wo{[Pn](){let t;if(this[no]&&this[on]==="r+")try{t=ot.openSync(this[Pt],this[on],this[Fi])}catch(e){if(e?.code==="ENOENT")return this[on]="w",this[Pn]();throw e}else t=ot.openSync(this[Pt],this[on],this[Fi]);this[Br](null,t)}[Rt](){if(this[Tn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ot.closeSync(t),this.emit("close")}}[to](t){let e=!0;try{this[Dr](null,ot.writeSync(this[he],t,0,t.length,this[Sn])),e=!1}finally{if(e)try{this[Rt]()}catch{}}}},o_=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"]]),a_=t=>!!t.sync&&!!t.file,c_=t=>!t.sync&&!!t.file,d_=t=>!!t.sync&&!t.file,l_=t=>!t.sync&&!t.file,u_=t=>!!t.file,f_=t=>o_.get(t)||t,od=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=f_(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Ki=(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=od(a);if(o?.(f,d),a_(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(c_(f)){let x=e(f,d);return u?x.then(()=>u(),u):x}else if(d_(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(f,d)}else if(l_(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}),p_=x_.constants||{ZLIB_VERNUM:4736},Ht=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},p_)),g_=Yn.concat,Qu=Object.getOwnPropertyDescriptor(Yn,"concat"),m_=t=>t,yc=Qu?.writable===!0||Qu?.set!==void 0?t=>{Yn.concat=t?m_:g_}:t=>{},Xn=Symbol("_superWrite"),Ks=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"}},bc=Symbol("flushFlag"),ad=class extends er{#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 Xu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Xu[e](t)}catch(n){throw new Ks(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 Ks(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return zc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Yn.alloc(0),{[bc]: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}[Xn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Yn.from(t,e)),this.#e)return;zc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},yc(!0);let d;try{let f=typeof t[bc]=="number"?t[bc]:this.#r;d=this.#t._processChunk(t,f),yc(!1)}catch(f){yc(!1),this.#o(new Ks(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 Ks(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[Xn](Yn.from(f));for(let x=1;x<d.length;x++)u=this[Xn](d[x])}else u=this[Xn](Yn.from(d));return n&&n(),u}},Lf=class extends ad{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ht.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ht.Z_FINISH,t.fullFlushFlag=Ht.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(Ht.Z_SYNC_FLUSH),zc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},w_=class extends Lf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Xn](t){return this.#e?(this.#e=!1,t[9]=255,super[Xn](t)):super[Xn](t)}},__=class extends Lf{constructor(t){super(t,"Unzip")}},Mf=class extends ad{constructor(t,e){t=t||{},t.flush=t.flush||Ht.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ht.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ht.BROTLI_OPERATION_FLUSH,super(t,e)}},y_=class extends Mf{constructor(t){super(t,"BrotliCompress")}},b_=class extends Mf{constructor(t){super(t,"BrotliDecompress")}},Nf=class extends ad{constructor(t,e){t=t||{},t.flush=t.flush||Ht.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ht.ZSTD_e_end,t.fullFlushFlag=Ht.ZSTD_e_flush,super(t,e)}},E_=class extends Nf{constructor(t){super(t,"ZstdCompress")}},v_=class extends Nf{constructor(t){super(t,"ZstdDecompress")}},S_=(t,e)=>{if(Number.isSafeInteger(t))t<0?A_(t,e):I_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},I_=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},A_=(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]=Ff(o):o===0?e[i-1]=0:(n=!0,e[i-1]=Bf(o))}},k_=t=>{let e=t[0],n=e===128?T_(t.subarray(1,t.length)):e===255?C_(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},C_=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var a=Number(t[o]),d;i?d=Ff(a):a===0?d=a:(i=!0,d=Bf(a)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},T_=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},Ff=t=>(255^t)&255,Bf=t=>(255^t)+1&255,P_={};qw(P_,{code:()=>cd,isCode:()=>ro,isName:()=>R_,name:()=>_o,normalFsTypes:()=>zf});var ro=t=>_o.has(t),R_=t=>cd.has(t),zf=new Set(["0","","1","2","3","4","5","6","7","D"]),_o=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"]]),cd=new Map(Array.from(_o).map(t=>[t[1],t[0]])),O_=t=>t===void 0||t<0?void 0:t,Qn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,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=jn(t,e+156,1),a=zf.has(o),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??jn(t,e,100),this.mode=d?.mode??u?.mode??In(t,e+100,8),this.uid=d?.uid??u?.uid??In(t,e+108,8),this.gid=d?.gid??u?.gid??In(t,e+116,8),this.size=O_(d?.size??u?.size??In(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??Ec(t,e+136,12),this.cksum=In(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),ro(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=jn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??jn(t,e+265,32),this.gname=d?.gname??u?.gname??jn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??In(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??In(t,e+337,8)??0,t[e+475]!==0){let x=jn(t,e+345,155);this.path=x+"/"+this.path}else{let x=jn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??Ec(t,e+476,12),this.ctime=n?.ctime??i?.ctime??Ec(t,e+488,12)}let f=256;for(let x=e;x<e+148;x++)f+=t[x];for(let x=e+156;x<e+512;x++)f+=t[x];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="size"&&Number(i)<0||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,i=D_(this.path||"",n),o=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Wn(t,e,100,o)||this.needPax,this.needPax=An(t,e+100,8,this.mode)||this.needPax,this.needPax=An(t,e+108,8,this.uid)||this.needPax,this.needPax=An(t,e+116,8,this.gid)||this.needPax,this.needPax=An(t,e+124,12,this.size)||this.needPax,this.needPax=vc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Wn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Wn(t,e+265,32,this.uname)||this.needPax,this.needPax=Wn(t,e+297,32,this.gname)||this.needPax,this.needPax=An(t,e+329,8,this.devmaj)||this.needPax,this.needPax=An(t,e+337,8,this.devmin)||this.needPax,this.needPax=Wn(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=Wn(t,e+345,155,a)||this.needPax:(this.needPax=Wn(t,e+345,130,a)||this.needPax,this.needPax=vc(t,e+476,12,this.atime)||this.needPax,this.needPax=vc(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,An(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:_o.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(cd.get(t));if(ro(e)||e==="Unsupported")this.#e=e;else if(ro(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},D_=(t,e)=>{let n=t,i="",o,a=Cr.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=Cr.dirname(n),n=Cr.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=Cr.join(Cr.basename(i),n),i=Cr.dirname(i));while(i!==a&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},jn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),Ec=(t,e,n)=>L_(In(t,e,n)),L_=t=>t===void 0?void 0:new Date(t*1e3),In=(t,e,n)=>Number(t[e])&128?k_(t.subarray(e,e+n)):N_(t,e,n),M_=t=>isNaN(t)?void 0:t,N_=(t,e,n)=>M_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),F_={12:8589934591,8:2097151},An=(t,e,n,i)=>i===void 0?!1:i>F_[n]||i<0?(S_(i,t.subarray(e,e+n)),!0):(B_(t,e,n,i),!1),B_=(t,e,n,i)=>t.write(z_(i,n),e,n,"ascii"),z_=(t,e)=>U_(Math.floor(t).toString(8),e),U_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",vc=(t,e,n,i)=>i===void 0?!1:An(t,e,n,i.getTime()/1e3),H_=new Array(156).join("\0"),Wn=(t,e,n,i)=>i===void 0?!1:(t.write(i+H_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),ho=class Uf{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 Qn({path:("PaxHeader/"+G_(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 Uf(q_(j_(e),n),i)}},q_=(t,e)=>e?Object.assign({},e,t):t,j_=t=>t.replace(/\n$/,"").split(`
|
|
91
|
+
`).reduce(W_,Object.create(null)),W_=(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},K_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,te=K_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),$_=class extends er{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))))}},yo=(t,e,n,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=n instanceof Error&&n.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(n instanceof Error&&(i=Object.assign(n,i),n=n.message),t.emit("warn",e,n,i)):n instanceof Error?t.emit("error",Object.assign(n,i)):t.emit("error",Object.assign(new Error(`${e}: ${n}`),i))},V_=1024*1024,Uc=Buffer.from([31,139]),Hc=Buffer.from([40,181,47,253]),J_=Math.max(Uc.length,Hc.length),wt=Symbol("state"),Kn=Symbol("writeEntry"),nn=Symbol("readEntry"),Sc=Symbol("nextEntry"),ef=Symbol("processEntry"),Ft=Symbol("extendedHeader"),ki=Symbol("globalExtendedHeader"),bn=Symbol("meta"),tf=Symbol("emitMeta"),we=Symbol("buffer"),rn=Symbol("queue"),En=Symbol("ended"),Ic=Symbol("emittedEnd"),$n=Symbol("emit"),Ae=Symbol("unzip"),$s=Symbol("consumeChunk"),Vs=Symbol("consumeChunkSub"),Ac=Symbol("consumeBody"),nf=Symbol("consumeMeta"),rf=Symbol("consumeHeader"),Ci=Symbol("consuming"),kc=Symbol("bufferConcat"),Js=Symbol("maybeEnd"),Tr=Symbol("writing"),Bt=Symbol("aborted"),Zs=Symbol("onDone"),Vn=Symbol("sawValidEntry"),Ys=Symbol("sawNullBlock"),Xs=Symbol("sawEOF"),sf=Symbol("closeStream"),Z_=1e3,Ti=Symbol("compressedBytesRead"),Cc=Symbol("decompressedBytesRead"),of=Symbol("checkDecompressionRatio"),Y_=()=>!0,Wi=class extends h_{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[rn]=[];[we];[nn];[Kn];[wt]="begin";[bn]="";[Ft];[ki];[En]=!1;[Ae];[Bt]=!1;[Vn];[Ys]=!1;[Xs]=!1;[Tr]=!1;[Ci]=!1;[Ic]=!1;[Ti]=0;[Cc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Zs,()=>{(this[wt]==="begin"||this[Vn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Zs,t.ondone):this.on(Zs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:Z_,this.maxMetaEntrySize=t.maxMetaEntrySize||V_,this.filter=typeof t.filter=="function"?t.filter:Y_;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[sf]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){yo(this,t,e,n)}[rf](t,e){this[Vn]===void 0&&(this[Vn]=!1);let n;try{n=new Qn(t,e,this[Ft],this[ki])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Ys]?(this[Xs]=!0,this[wt]==="begin"&&(this[wt]="header"),this[$n]("eof")):(this[Ys]=!0,this[$n]("nullBlock"));else if(this[Ys]=!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[Kn]=new $_(n,this[Ft],this[ki]);if(!this[Vn])if(o.remain){let a=()=>{o.invalid||(this[Vn]=!0)};o.on("end",a)}else this[Vn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[$n]("ignoredEntry",o),this[wt]="ignore",o.resume()):o.size>0&&(this[bn]="",o.on("data",a=>this[bn]+=a),this[wt]="meta"):(this[Ft]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[$n]("ignoredEntry",o),this[wt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[wt]="body":(this[wt]="header",o.end()),this[nn]?this[rn].push(o):(this[rn].push(o),this[Sc]())))}}}[sf](){queueMicrotask(()=>this.emit("close"))}[ef](t){let e=!0;if(!t)this[nn]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[nn]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Sc]()),e=!1);return e}[Sc](){do;while(this[ef](this[rn].shift()));if(this[rn].length===0){let t=this[nn];!t||t.flowing||t.size===t.remain?this[Tr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Ac](t,e){let n=this[Kn];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[wt]="header",this[Kn]=void 0,n.end()),o.length}[nf](t,e){let n=this[Kn],i=this[Ac](t,e);return!this[Kn]&&n&&this[tf](n),i}[$n](t,e,n){this[rn].length===0&&!this[nn]?this.emit(t,e,n):this[rn].push([t,e,n])}[tf](t){switch(this[$n]("meta",this[bn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ft]=ho.parse(this[bn],this[Ft],!1);break;case"GlobalExtendedHeader":this[ki]=ho.parse(this[bn],this[ki],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ft]??Object.create(null);this[Ft]=e,e.path=this[bn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ft]||Object.create(null);this[Ft]=e,e.linkpath=this[bn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Bt]){if(this[Ae]){let e=this[Ae];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Bt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[of](t){this[Cc]+=t.length;let e=this[Cc]/this[Ti];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[Bt])return n?.(),!1;if((this[Ae]===void 0||this.brotli===void 0&&this[Ae]===!1)&&t){if(this[we]&&(t=Buffer.concat([this[we],t]),this[we]=void 0),t.length<J_)return this[we]=t,n?.(),!0;for(let d=0;this[Ae]===void 0&&d<Uc.length;d++)t[d]!==Uc[d]&&(this[Ae]=!1);let o=!1;if(this[Ae]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Hc.length;d++)if(t[d]!==Hc[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[Ae]===!1&&a)if(t.length<512)if(this[En])this.brotli=!0;else return this[we]=t,n?.(),!0;else try{new Qn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ae]===void 0||this[Ae]===!1&&(this.brotli||o)){let d=this[En];this[En]=!1,this[Ae]=this[Ae]===void 0?new __({}):o?new v_({}):new b_({}),this[Ae].on("data",f=>{this[of](f)&&this[$s](f)}),this[Ae].on("error",f=>{this[Bt]||this.abort(f)}),this[Ae].on("end",()=>{this[En]=!0,this[$s]()}),this[Tr]=!0,this[Ti]+=t.length;let u=!!this[Ae][d?"end":"write"](t);return this[Tr]=!1,n?.(),u}}this[Tr]=!0,this[Ae]?(this[Ti]+=t.length,this[Ae].write(t)):this[$s](t),this[Tr]=!1;let i=this[rn].length>0?!1:this[nn]?this[nn].flowing:!0;return!i&&this[rn].length===0&&this[nn]?.once("drain",()=>this.emit("drain")),n?.(),i}[kc](t){t&&!this[Bt]&&(this[we]=this[we]?Buffer.concat([this[we],t]):t)}[Js](){if(this[En]&&!this[Ic]&&!this[Bt]&&!this[Ci]){this[Ic]=!0;let t=this[Kn];if(t?.blockRemain){let e=this[we]?this[we].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[we]&&t.write(this[we]),t.end()}this[$n](Zs)}}[$s](t){if(this[Ci]&&t)this[kc](t);else if(!t&&!this[we])this[Js]();else if(t){if(this[Ci]=!0,this[we]){this[kc](t);let e=this[we];this[we]=void 0,this[Vs](e)}else this[Vs](t);for(;this[we]&&this[we]?.length>=512&&!this[Bt]&&!this[Xs];){let e=this[we];this[we]=void 0,this[Vs](e)}this[Ci]=!1}(!this[we]||this[En])&&this[Js]()}[Vs](t){let e=0,n=t.length;for(;e+512<=n&&!this[Bt]&&!this[Xs];)switch(this[wt]){case"begin":case"header":this[rf](t,e),e+=512;break;case"ignore":case"body":e+=this[Ac](t,e);break;case"meta":e+=this[nf](t,e);break;default:throw new Error("invalid state: "+this[wt])}e<n&&(this[we]=this[we]?Buffer.concat([t.subarray(e),this[we]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[Bt]||(this[Ae]?(t&&(this[Ti]+=t.length,this[Ae].write(t)),this[Ae].end()):(this[En]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Js]())),this}},Bi=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)},X_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Hf=(t,e)=>{let n=new Map(e.map(a=>[Bi(a),!0])),i=t.filter,o=(a,d="")=>{let u=d||s_(a).root||".",f;if(a===u)f=!1;else{let x=n.get(a);f=x!==void 0?x:o(i_(a),u)}return n.set(a,f),f};t.filter=i?(a,d)=>i(a,d)&&o(Bi(a)):a=>o(Bi(a))},Q_=t=>{let e=new Wi(t),n=t.file,i;try{i=Mr.openSync(n,"r");let o=Mr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),u=Mr.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=Mr.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{Mr.closeSync(i)}catch{}}},ey=(t,e)=>{let n=new Wi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Mr.stat(o,(u,f)=>{if(u)d(u);else{let x=new sd(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},zr=Ki(Q_,ey,t=>new Wi(t),t=>new Wi(t),(t,e)=>{e?.length&&Hf(t,e),t.noResume||X_(t)}),Gf=(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:ny,parse:cf}=ty,dd=t=>{let e="",n=cf(t);for(;ny(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=cf(t)}return[e,t]},bo=["|","<",">","?",":"],ld=bo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),ry=new Map(bo.map((t,e)=>[t,ld[e]])),iy=new Map(ld.map((t,e)=>[t,bo[e]])),df=t=>bo.reduce((e,n)=>e.split(n).join(ry.get(n)),t),sy=t=>ld.reduce((e,n)=>e.split(n).join(iy.get(n)),t),qf=(t,e)=>e?(t=te(t).replace(/^\.(\/|$)/,""),Bi(e)+"/"+t):te(t),oy=16*1024*1024,lf=Symbol("process"),uf=Symbol("file"),ff=Symbol("directory"),Gc=Symbol("symlink"),hf=Symbol("hardlink"),Pi=Symbol("header"),io=Symbol("read"),qc=Symbol("lstat"),so=Symbol("onlstat"),jc=Symbol("onread"),Wc=Symbol("onreadlink"),Kc=Symbol("openfile"),$c=Symbol("onopenfile"),kn=Symbol("close"),po=Symbol("mode"),Vc=Symbol("awaitDrain"),Tc=Symbol("ondrain"),Ut=Symbol("prefix"),jf=class extends er{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=od(e);super(),this.path=te(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||oy,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]=dd(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=sy(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=te(n.absolute||af.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[so](o):this[qc]()}warn(t,e,n={}){return yo(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[qc](){zt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[so](e)})}[so](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=dy(t),this.emit("stat",t),this[lf]()}[lf](){switch(this.type){case"File":return this[uf]();case"Directory":return this[ff]();case"SymbolicLink":return this[Gc]();default:return this.end()}}[po](t){return Gf(t,this.type==="Directory",this.portable)}[Ut](t){return qf(t,this.prefix)}[Pi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Qn({path:this[Ut](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ut](this.linkpath):this.linkpath,mode:this[po](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 ho({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[Ut](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ut](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)}[ff](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Pi](),this.end()}[Gc](){zt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Wc](e)})}[Wc](t){this.linkpath=te(t),this[Pi](),this.end()}[hf](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=te(af.relative(this.cwd,t)),this.stat.size=0,this[Pi](),this.end()}[uf](){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[hf](e);this.linkCache.set(t,this.absolute)}if(this[Pi](),this.stat.size===0)return this.end();this[Kc]()}[Kc](){zt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[$c](e)})}[$c](t){if(this.fd=t,this.#e)return this[kn]();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[io]()}[io](){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");zt.read(t,e,n,i,o,(a,d)=>{if(a)return this[kn](()=>this.emit("error",a));this[jc](d)})}[kn](t=()=>{}){this.fd!==void 0&&zt.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[kn](()=>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[kn](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let n=t;n<this.length&&t<this.blockRemain;n++)this.buf[n+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[Tc]():this[Vc](()=>this[Tc]())}[Vc](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,n)}[Tc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[kn](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[io]()}},ay=class extends jf{sync=!0;[qc](){this[so](zt.lstatSync(this.absolute))}[Gc](){this[Wc](zt.readlinkSync(this.absolute))}[Kc](){this[$c](zt.openSync(this.absolute,"r"))}[io](){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=zt.readSync(e,n,i,o,a);this[jc](d),t=!1}finally{if(t)try{this[kn](()=>{})}catch{}}}[Vc](t){t()}[kn](t=()=>{}){this.fd!==void 0&&zt.closeSync(this.fd),t()}},cy=class extends er{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 yo(this,t,e,n)}constructor(t,e={}){let n=od(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[po](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,u]=dd(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 Qn({path:this[Ut](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ut](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 ho({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[Ut](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ut](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)}[Ut](t){return qf(t,this.prefix)}[po](t){return Gf(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}},dy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",ly=class Nr{tail;head;length=0;static create(e=[]){return new Nr(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++)fy(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)hy(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 Nr;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 Nr;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 Nr;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 Nr;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=uy(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 uy(t,e,n){let i=e,o=e?e.next:t.head,a=new ud(n,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function fy(t,e){t.tail=new ud(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function hy(t,e){t.head=new ud(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var ud=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}},pf=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},gf=Buffer.alloc(1024),oo=Symbol("onStat"),Ri=Symbol("ended"),Ct=Symbol("queue"),Oi=Symbol("pendingLinks"),vn=Symbol("current"),Jn=Symbol("process"),Di=Symbol("processing"),Qs=Symbol("processJob"),Tt=Symbol("jobs"),Pc=Symbol("jobDone"),ao=Symbol("addFSEntry"),mf=Symbol("addTarEntry"),Jc=Symbol("stat"),Zc=Symbol("readdir"),co=Symbol("onreaddir"),lo=Symbol("pipe"),wf=Symbol("entry"),Rc=Symbol("entryOpt"),uo=Symbol("writeEntryClass"),Wf=Symbol("write"),Oc=Symbol("ondrain"),Eo=class extends er{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[uo];onWriteEntry;[Ct];[Oi]=new Map;[Tt]=0;[Di]=!1;[Ri]=!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[uo]=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 w_(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new y_(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new E_(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[Oc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Oc]);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[Ct]=new ly,this[Tt]=0,this.jobs=Number(t.jobs)||4,this[Di]=!1,this[Ri]=!1}[Wf](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[Ri]=!0,this[Jn](),n&&n(),this}write(t){if(this[Ri])throw new Error("write after end");return typeof t=="string"?this[ao](t):this[mf](t),this.flowing}[mf](t){let e=te(xf.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new pf(t.path,e);n.entry=new cy(t,this[Rc](n)),n.entry.on("end",()=>this[Pc](n)),this[Tt]+=1,this[Ct].push(n)}this[Jn]()}[ao](t){let e=te(xf.resolve(this.cwd,t));this[Ct].push(new pf(t,e)),this[Jn]()}[Jc](t){t.pending=!0,this[Tt]+=1;let e=this.follow?"stat":"lstat";xo[e](t.absolute,(n,i)=>{t.pending=!1,this[Tt]-=1,n?this.emit("error",n):this[oo](t,i)})}[oo](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[vn])this[Qs](t);else{let n=`${e.dev}:${e.ino}`,i=this[Oi].get(n);i?i.push(t):this[Oi].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Jn]()}[Zc](t){t.pending=!0,this[Tt]+=1,xo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[Tt]-=1,e)return this.emit("error",e);this[co](t,n)})}[co](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Jn]()}[Jn](){if(!this[Di]){this[Di]=!0;for(let t=this[Ct].head;t&&this[Tt]<this.jobs;t=t.next)if(this[Qs](t.value),t.value.ignore){let e=t.next;this[Ct].removeNode(t),t.next=e}this[Di]=!1,this[Ri]&&this[Ct].length===0&&this[Tt]===0&&(this.zip?this.zip.end(gf):(super.write(gf),super.end()))}}get[vn](){return this[Ct]&&this[Ct].head&&this[Ct].head.value}[Pc](t){this[Ct].shift(),this[Tt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Oi].get(n);if(i){this[Oi].delete(n);for(let o of i)o.pending=!1,this[Qs](o)}}this[Jn]()}[Qs](t){if(t.pending&&t.pendingLink&&t===this[vn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[vn]&&!t.piped&&this[lo](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[oo](t,e):this[Jc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[co](t,e):this[Zc](t),!t.readdir)return}if(t.entry=this[wf](t),!t.entry){t.ignore=!0;return}t===this[vn]&&!t.piped&&this[lo](t)}}}[Rc](t){return{onwarn:(e,n,i)=>this.warn(e,n,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[wf](t){this[Tt]+=1;try{return new this[uo](t.path,this[Rc](t)).on("end",()=>this[Pc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Oc](){this[vn]&&this[vn].entry&&this[vn].entry.resume()}[lo](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[ao](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={}){yo(this,t,e,n)}},fd=class extends Eo{sync=!0;constructor(t){super(t),this[uo]=ay}pause(){}resume(){}[Jc](t){let e=this.follow?"statSync":"lstatSync";this[oo](t,xo[e](t.absolute))}[Zc](t){this[co](t,xo.readdirSync(t.absolute))}[lo](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[ao](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Wf](i)})}},xy=(t,e)=>{let n=new fd(t),i=new Of(t.file,{mode:t.mode||438});n.pipe(i),Kf(n,e)},py=(t,e)=>{let n=new Eo(t),i=new wo(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 $f(n,e).catch(a=>n.emit("error",a)),o},Kf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?zr({file:Df.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},$f=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await zr({file:Df.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},gy=(t,e)=>{let n=new fd(t);return Kf(n,e),n},my=(t,e)=>{let n=new Eo(t);return $f(n,e).catch(i=>n.emit("error",i)),n},U2=Ki(xy,py,gy,my,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),_y=process.env.__FAKE_PLATFORM__||process.platform,Yf=_y==="win32",{O_CREAT:Xf,O_NOFOLLOW:_f,O_TRUNC:Qf,O_WRONLY:e0}=Zf.constants,t0=Number(process.env.__FAKE_FS_O_FILENAME__)||Zf.constants.UV_FS_O_FILEMAP||0,yy=Yf&&!!t0,by=512*1024,Ey=t0|Qf|Xf|e0,yf=!Yf&&typeof _f=="number"?_f|Qf|Xf|e0:null,n0=yf!==null?()=>yf:yy?t=>t<by?Ey:"w":()=>"w",Yc=(t,e,n)=>{try{return vo.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},go=(t,e,n,i)=>{vo.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},vy=(t,e,n,i,o)=>{if(e.isDirectory())r0(zi.resolve(t,e.name),n,i,a=>{if(a)return o(a);let d=zi.resolve(t,e.name);go(d,n,i,o)});else{let a=zi.resolve(t,e.name);go(a,n,i,o)}},r0=(t,e,n,i)=>{vo.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 go(t,e,n,i);let d=a.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--d===0)return go(t,e,n,i)}};for(let x of a)vy(t,x,e,n,f)})},Sy=(t,e,n,i)=>{e.isDirectory()&&i0(zi.resolve(t,e.name),n,i),Yc(zi.resolve(t,e.name),n,i)},i0=(t,e,n)=>{let i;try{i=vo.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Yc(t,e,n);throw a}for(let o of i)Sy(t,o,e,n);return Yc(t,e,n)},s0=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},So=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},Ay=(t,e)=>{ht.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new s0(t,n?.code||"ENOTDIR")),e(n)})},ky=(t,e,n)=>{t=te(t);let i=e.umask??18,o=e.mode|448,a=(o&i)!==0,d=e.uid,u=e.gid,f=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,p=e.unlink,m=te(e.cwd),y=(E,I)=>{E?n(E):I&&f?r0(I,d,u,A=>y(A)):a?ht.chmod(t,o,n):n()};if(t===m)return Ay(t,y);if(x)return Iy.mkdir(t,{mode:o,recursive:!0}).then(E=>y(null,E??void 0),y);let _=te(mo.relative(m,t)).split("/");Xc(m,_,o,p,m,void 0,y)},Xc=(t,e,n,i,o,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),f=te(mo.resolve(t+"/"+u));ht.mkdir(f,n,o0(f,e,n,i,o,a,d))},o0=(t,e,n,i,o,a,d)=>u=>{u?ht.lstat(t,(f,x)=>{if(f)f.path=f.path&&te(f.path),d(f);else if(x.isDirectory())Xc(t,e,n,i,o,a,d);else if(i)ht.unlink(t,p=>{if(p)return d(p);ht.mkdir(t,n,o0(t,e,n,i,o,a,d))});else{if(x.isSymbolicLink())return d(new So(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,Xc(t,e,n,i,o,a,d))},Cy=t=>{let e=!1,n;try{e=ht.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new s0(t,n??"ENOTDIR")}},Ty=(t,e)=>{t=te(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==0,a=e.uid,d=e.gid,u=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),f=e.preserve,x=e.unlink,p=te(e.cwd),m=E=>{E&&u&&i0(E,a,d),o&&ht.chmodSync(t,i)};if(t===p)return Cy(p),m();if(f)return m(ht.mkdirSync(t,{mode:i,recursive:!0})??void 0);let y=te(mo.relative(p,t)).split("/"),_;for(let E=y.shift(),I=p;E&&(I+="/"+E);E=y.shift()){I=te(mo.resolve(I));try{ht.mkdirSync(I,i),_=_||I}catch{let A=ht.lstatSync(I);if(A.isDirectory())continue;if(x){ht.unlinkSync(I),ht.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new So(I,I+"/"+y.join("/"))}}return m(_)},Dc=Object.create(null),bf=1e4,Pr=new Set,Py=t=>{Pr.has(t)?Pr.delete(t):Dc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Pr.add(t);let e=Dc[t],n=Pr.size-bf;if(n>bf/10){for(let i of Pr)if(Pr.delete(i),delete Dc[i],--n<=0)break}return e},Ry=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Oy=Ry==="win32",Dy=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=a0(i,n)),e.push(n||"/"),e},[]),Ly=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=Oy?["win32 parallelization disabled"]:t.map(i=>Bi(a0(Py(i))));let n=new Set(t.map(i=>Dy(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}},My=()=>process.umask(),Ef=Symbol("onEntry"),Qc=Symbol("checkFs"),vf=Symbol("checkFs2"),ed=Symbol("isReusable"),_t=Symbol("makeFs"),td=Symbol("file"),nd=Symbol("directory"),fo=Symbol("link"),Sf=Symbol("symlink"),If=Symbol("hardlink"),Ni=Symbol("ensureNoSymlink"),Af=Symbol("unsupported"),kf=Symbol("checkPath"),Lc=Symbol("stripAbsolutePath"),Cn=Symbol("mkdir"),je=Symbol("onError"),eo=Symbol("pending"),Cf=Symbol("pend"),Rr=Symbol("unpend"),Mc=Symbol("ended"),Nc=Symbol("maybeClose"),rd=Symbol("skip"),Ui=Symbol("doChown"),Hi=Symbol("uid"),Gi=Symbol("gid"),qi=Symbol("checkedCwd"),Ny=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ji=Ny==="win32",Fy=1024,By=(t,e)=>{if(!ji)return se.unlink(t,e);let n=t+".DELETE."+Jf(16).toString("hex");se.rename(t,n,i=>{if(i)return e(i);se.unlink(n,e)})},zy=t=>{if(!ji)return se.unlinkSync(t);let e=t+".DELETE."+Jf(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},Tf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,hd=class extends Wi{[Mc]=!1;[qi]=!1;[eo]=0;reservations=new Ly;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[Mc]=!0,this[Nc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:Fy,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||ji,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=te(Be.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:My():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Ef](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Nc](){this[Mc]&&this[eo]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Lc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,a]=dd(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||ji&&/^[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=Be.posix.dirname(t.path),f=Be.posix.normalize(Be.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}[kf](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[Lc](t,"path")||!this[Lc](t,"linkpath"))return!1;if(t.absolute=Be.isAbsolute(t.path)?te(Be.resolve(t.path)):te(Be.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path: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}=Be.win32.parse(String(t.absolute));t.absolute=i+df(String(t.absolute).slice(i.length));let{root:o}=Be.win32.parse(t.path);t.path=o+df(t.path.slice(o.length))}return!0}[Ef](t){if(!this[kf](t))return t.resume();switch(wy.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[Qc](t);default:return this[Af](t)}}[je](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Rr](),e.resume())}[Cn](t,e,n){ky(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)}[Ui](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}[Hi](t){return Tf(this.uid,t.uid,this.processUid)}[Gi](t){return Tf(this.gid,t.gid,this.processGid)}[td](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new wo(String(t.absolute),{flags:n0(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[je](u,t),e()});let o=1,a=u=>{if(u){i.fd&&se.close(i.fd,()=>{}),this[je](u,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,f=>{f?this[je](f,t):this[Rr](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,p=t.mtime;se.futimes(f,x,p,m=>m?se.utimes(u,x,p,y=>a(y&&m)):a())}if(typeof f=="number"&&this[Ui](t)){o++;let x=this[Hi](t),p=this[Gi](t);typeof x=="number"&&typeof p=="number"&&se.fchown(f,x,p,m=>m?se.chown(u,x,p,y=>a(y&&m)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[je](u,t),e()}),t.pipe(d)),d.pipe(i)}[nd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Cn](String(t.absolute),n,i=>{if(i){this[je](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[Rr](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Ui](t)&&(o++,se.chown(String(t.absolute),Number(this[Hi](t)),Number(this[Gi](t)),a)),a()})}[Af](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Sf](t,e){let n=te(Be.relative(this.cwd,Be.resolve(Be.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ni](t,this.cwd,n,()=>this[fo](t,String(t.linkpath),"symlink",e),i=>{this[je](i,t),e()})}[If](t,e){let n=te(Be.resolve(this.cwd,String(t.linkpath))),i=te(String(t.linkpath)).split("/");this[Ni](t,this.cwd,i,()=>this[fo](t,n,"link",e),o=>{this[je](o,t),e()})}[Ni](t,e,n,i,o){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Be.resolve(e,a);se.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new So(d,Be.resolve(d,n.join("/"))));this[Ni](t,d,n,i,o)})}[Cf](){this[eo]++}[Rr](){this[eo]--,this[Nc]()}[rd](t){this[Rr](),t.resume()}[ed](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!ji}[Qc](t){this[Cf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[vf](t,n))}[vf](t,e){let n=d=>{e(d)},i=()=>{this[Cn](this.cwd,this.dmode,d=>{if(d){this[je](d,t),n();return}this[qi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=te(Be.dirname(String(t.absolute)));if(d!==this.cwd)return this[Cn](d,this.dmode,u=>{if(u){this[je](u,t),n();return}a()})}a()},a=()=>{se.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[rd](t),n();return}if(d||this[ed](t,u))return this[_t](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=p=>this[_t](p??null,t,n);return f?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),f=>this[_t](f??null,t,n))}if(t.absolute===this.cwd)return this[_t](null,t,n);By(String(t.absolute),f=>this[_t](f??null,t,n))})};this[qi]?o():i()}[_t](t,e,n){if(t){this[je](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[td](e,n);case"Link":return this[If](e,n);case"SymbolicLink":return this[Sf](e,n);case"Directory":case"GNUDumpDir":return this[nd](e,n)}}[fo](t,e,n,i){se[n](e,String(t.absolute),o=>{o?this[je](o,t):(this[Rr](),t.resume()),i()})}},Li=t=>{try{return[null,t()]}catch(e){return[e,null]}},c0=class extends hd{sync=!0;[_t](t,e){return super[_t](t,e,()=>{})}[Qc](t){if(!this[qi]){let o=this[Cn](this.cwd,this.dmode);if(o)return this[je](o,t);this[qi]=!0}if(t.absolute!==this.cwd){let o=te(Be.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[Cn](o,this.dmode);if(a)return this[je](a,t)}}let[e,n]=Li(()=>se.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[rd](t);if(e||this[ed](t,n))return this[_t](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Li(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[_t](d,t)}let[o]=Li(()=>se.rmdirSync(String(t.absolute)));this[_t](o,t)}let[i]=t.absolute===this.cwd?[]:Li(()=>zy(String(t.absolute)));this[_t](i,t)}[td](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{se.closeSync(o)}catch(f){u=f}(d||u)&&this[je](d||u,t),e()},o;try{o=se.openSync(String(t.absolute),n0(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[je](d,t)),t.pipe(a)),a.on("data",d=>{try{se.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{se.futimesSync(o,u,f)}catch(x){try{se.utimesSync(String(t.absolute),u,f)}catch{d=x}}}if(this[Ui](t)){let u=this[Hi](t),f=this[Gi](t);try{se.fchownSync(o,Number(u),Number(f))}catch(x){try{se.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||x}}}i(d)})}[nd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Cn](String(t.absolute),n);if(i){this[je](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ui](t))try{se.chownSync(String(t.absolute),Number(this[Hi](t)),Number(this[Gi](t)))}catch{}e(),t.resume()}[Cn](t,e){try{return Ty(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}}[Ni](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=Be.resolve(a,d);let[u,f]=Li(()=>se.lstatSync(a));if(u)return i();if(f.isSymbolicLink())return o(new So(a,Be.resolve(e,n.join("/"))))}i()}[fo](t,e,n,i){let o=`${n}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[je](a,t)}}},Uy=t=>{let e=new c0(t),n=t.file,i=Vf.statSync(n),o=t.maxReadSize||16*1024*1024;new r_(n,{readSize:o,size:i.size}).pipe(e)},Hy=(t,e)=>{let n=new hd(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Vf.stat(o,(u,f)=>{if(u)d(u);else{let x=new sd(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},d0=Ki(Uy,Hy,t=>new c0(t),t=>new hd(t),(t,e)=>{e?.length&&Hf(t,e)}),Gy=(t,e)=>{let n=new fd(t),i=!0,o,a;try{try{o=ft.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=ft.openSync(t.file,"w+");else throw f}let d=ft.fstatSync(o),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let p=0,m=0;p<512;p+=m){if(m=ft.readSync(o,u,p,u.length-p,a+p),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!m)break e}let f=new Qn(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,qy(t,n,a,o,e)}finally{if(i)try{ft.closeSync(o)}catch{}}},qy=(t,e,n,i,o)=>{let a=new Of(t.file,{fd:i,start:n});e.pipe(a),Wy(e,o)},jy=(t,e)=>{e=Array.from(e);let n=new Eo(t),i=(o,a,d)=>{let u=(y,_)=>{y?ft.close(o,E=>d(y)):d(null,_)},f=0;if(a===0)return u(null,0);let x=0,p=Buffer.alloc(512),m=(y,_)=>{if(y||_===void 0)return u(y);if(x+=_,x<512&&_)return ft.read(o,p,x,p.length-x,f+x,m);if(f===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let E=new Qn(p);if(!E.cksumValid)return u(null,f);let I=512*Math.ceil((E.size??0)/512);if(f+I+512>a||(f+=I+512,f>=a))return u(null,f);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),x=0,ft.read(o,p,0,512,f,m)};ft.read(o,p,0,512,f,m)};return new Promise((o,a)=>{n.on("error",a);let d="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",ft.open(t.file,d,u);if(f||!x)return a(f);ft.fstat(x,(p,m)=>{if(p)return ft.close(x,()=>a(p));i(x,m.size,(y,_)=>{if(y)return a(y);let E=new wo(t.file,{fd:x,start:_});n.pipe(E),E.on("error",a),E.on("close",o),Ky(n,e)})})};ft.open(t.file,d,u)})},Wy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?zr({file:l0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Ky=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await zr({file:l0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Mi=Ki(Gy,jy,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!u_(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")}),tC=Ki(Mi.syncFile,Mi.asyncFile,Mi.syncNoFile,Mi.asyncNoFile,(t,e=[])=>{Mi.validate?.(t,e),$y(t)}),$y=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))};Qt();var et={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 tr(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function u0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function Io(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function f0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function h0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function x0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function nr(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}At();import{homedir as Jy}from"node:os";import p0 from"node:path";var g0=".claude",m0="settings.json",Ao=new Map;function w0(t){return p0.join(t,g0,m0)}async function _0(t,e){let n=w0(t),o=(Ao.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>{let a=await Ze(n)??{};a.effortLevel=e,await lt(n,a)});Ao.set(n,o);try{await o}finally{Ao.get(n)===o&&Ao.delete(n)}}async function y0(t){let n=(await Ze(w0(t)))?.effortLevel;return typeof n=="string"?n:void 0}async function b0(){let t=p0.join(Jy(),g0,m0),n=(await Ze(t))?.effortLevel;return typeof n=="string"?n:void 0}Gt();Ve();ne();Ce();Ve();function $i(t,e){if(tr(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function xd(t,e){if(tr(t)==="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_CLOUD",`${e} is not allowed for cloud agent`)}function Vi(t){return t.startsWith("http://")||t.startsWith("https://")}function Ur(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as ZC}from"node:fs";import{dirname as XC,join as QC}from"node:path";import{fileURLToPath as tT}from"node:url";var qt="0.3.3";var pd={"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 S0(t,e){return pd[t][e]}import{mkdir as ub,rm as z0}from"node:fs/promises";import{join as Xi}from"node:path";At();import{readFileSync as nb}from"node:fs";var rb=384;async function gd(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await lt(t.agentEnvFile,n,{mode:rb})}function rr(t){try{let e=JSON.parse(nb(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Co(t,e,n={},i=o=>o){return{...i({...t,...rr(e)}),...n}}At();function Ji(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(ib(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
|
|
92
92
|
`)}
|
|
93
93
|
`}function ib(t){if(t.includes(`
|
|
94
|
-
`)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}ne();
|
|
95
|
-
`)}}function bd(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Ed(t){return t.model||
|
|
94
|
+
`)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}ne();Ce();import{homedir as ab}from"node:os";import{join as cb}from"node:path";Ve();ne();var To="1008033",I0="1289";var A0="pbbp2",k0="https://www.coze.cn",C0="/api/coze_claw/resource/get_frontier_key",sb="https://www.coze.cn",ob="wss://frontier.coze.cn";function Hr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??sb}function T0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??ob}function Rn(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 Yi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Zi=G("handshake");async function md(t){let e=Hr(t.endpoint),n=t.timeoutMs??1e4,i=`${Ur(e)}${C0}?aid=${encodeURIComponent(To)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Rn(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),n);Zi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:a.signal}),f=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let E=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${E.slice(0,200)}`)}let p=await u.json();if(p.code!==void 0&&p.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${p.code} msg=${p.msg??"-"} logid=${f}`);let m=p.data??{},y=typeof m.access_key=="string"&&m.access_key||typeof m.accessKey=="string"&&m.accessKey||void 0,_=typeof m.device_id=="string"&&m.device_id||typeof m.deviceId=="string"&&m.deviceId||void 0;if(!y||!_){let E=JSON.stringify(p).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${E}`)}return Zi.info("handshake ok",{remoteDeviceId:_,logid:f,traceId:x}),{accessKey:y,deviceId:_}}catch(u){if(u instanceof k)throw Zi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Zi.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let f=u.cause;throw Zi.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 Po=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Ot="auto",_d="default",wd=19e4,P0=32e3;function O0(t){if(!(yt(t.model)&&!t.effort&&!t.fastMode))return{model:t.model,...t.effort?{effort:t.effort}:{},...t.fastMode?{fastMode:t.fastMode}:{}}}function D0(t){return{model:yd(t.model)??Ot,...t.modelToken?{modelToken:t.modelToken}:{}}}function yt(t){return!t||t===Ot}var db=new Set(["auto","\u81EA\u52A8"]);function yd(t){let e=t?.trim();if(e)return db.has(e.toLowerCase())?Ot:e}function L0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Po,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Ot;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=n,e.ANTHROPIC_DEFAULT_OPUS_MODEL=n,e.ANTHROPIC_DEFAULT_SONNET_MODEL=n,e.CLAUDE_CODE_SUBAGENT_MODEL=n,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else!yt(t.model)&&t.model!==_d&&(e.ANTHROPIC_MODEL=t.model);return e}function M0(t,e,n,i){let o={};if(t.modelToken?o.model=t.model||Ot:yt(t.model)||(o.model=t.model),t.effort&&(o.model_reasoning_effort=t.effort),t.modelToken){let a={name:"coze",base_url:`${Po}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=Ro(e,n,i);Object.keys(d).length>0&&(a.http_headers=d),o.model_providers={coze:a},o.model_context_window=t.modelInfo?.contextWindow??wd}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function N0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Ro(t,e,n){let{ttEnv:i,usePpe:o}=Yi(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 F0(t,e,n,i){if(!t.modelToken)return{};let o=Ro(e,n,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,u])=>`${d}:${u}`).join(`
|
|
95
|
+
`)}}function bd(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Ed(t){return t.model||Ot}function R0(t,e,n,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:i,api:"openai-completions"}}function B0(t,e,n,i,o){if(!t.modelToken)return null;let a=Ed(t),d=Ro(e,n,o),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let f=[R0(a,u,t.modelInfo?.contextWindow??wd,t.modelInfo?.maxOutput??P0)],x=new Set([a]);for(let m of i??[])!m||x.has(m)||(x.add(m),f.push(R0(m,["text"],wd,P0)));let p={baseUrl:`${Po}/v1`,api:"openai-completions",apiKey:t.modelToken,models:f};return Object.keys(d).length>0&&(p.headers=d),p}function lb(t){if(t!==void 0)return t?"auto":"text"}function vd(t,e,n){let i=Ro(e,n),o=t.model||Ot,a=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${Po}/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=lb(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(` - ${cb(ab(),".hermes","skills")}`),`${a.join(`
|
|
96
96
|
`)}
|
|
97
|
-
`}var ir=
|
|
98
|
-
`).slice(1,6).join(" | ")}),await z0(n,{force:!0}).catch(a=>ir.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let o=vd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await
|
|
99
|
-
`).slice(1,6).join(" | ")}),await z0(n,{recursive:!0,force:!0}).catch(i=>ir.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var Sd=new Map;function q0(t){let e=Sd.get(t.agentId);if(e)return e;let n=fb(t).finally(()=>Sd.delete(t.agentId));return Sd.set(t.agentId,n),n}Wt();import{createHash as W0}from"node:crypto";import{readFile as hb}from"node:fs/promises";import{homedir as xb}from"node:os";import pb from"node:path";var gb=3e4;function cn(t){return typeof t=="object"&&t!==null?t:null}function Gr(t){return Array.isArray(t)?t:[]}function vt(t){return typeof t=="string"?t:void 0}function j0(t,e){return t.map(n=>cn(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 mb(t){let e=Gr(t.configOptions);if(e.length===0)return null;let n=null,i,o,a,d,u;for(let h of e){let p=cn(h);if(!p)continue;let g=vt(p.id);if(!g)continue;let y=Gr(p.options);g==="model"?(n=j0(y,"value"),i=vt(p.currentValue)):g==="effort"||g==="reasoning_effort"?(o=vt(p.currentValue),d=y.map(_=>vt(cn(_)?.value)).filter(_=>_!==void 0)):g==="fast-mode"&&(a=vt(p.currentValue),u=y.map(_=>vt(cn(_)?.value)).filter(_=>_!==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 wb(t){let e=cn(t.models);if(!e)return null;let n=Gr(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 K0(t,e){let n=cn(e);if(!n)return null;let i=cn(n.result)??n;return t==="hermes"?wb(i):mb(i)}function _b(t){let e=[],n=t.split(/\r?\n/),i=!1,o=-1,a=null,d=-1,u=!1,f=-1,h=p=>p.length-p.trimStart().length;for(let p of n){let g=p.replace(/#.*$/,"").trimEnd();if(g.trim()==="")continue;let y=h(g),_=g.trim();if(!i){_==="providers:"&&(i=!0,o=y);continue}if(y<=o&&!_.startsWith("-"))break;if((a===null||y<=d)&&_.endsWith(":")&&!_.startsWith("-")){a=_.slice(0,-1).trim(),d=y,u=!1;continue}if(a!==null){if(!u){_==="models:"&&(u=!0,f=y);continue}if(_.startsWith("-")&&y>f){let b=_.slice(1).trim(),I,k=b.match(/^(?:model|id)\s*:\s*(.+)$/);if(k?.[1]?I=k[1].trim():b&&!b.includes(":")&&(I=b),I){let C=I.replace(/^["']|["']$/g,"");e.push({id:`${a}:${C}`,providerId:a})}continue}y<=f&&(u=!1,y<=d&&_.endsWith(":")&&(a=_.slice(0,-1).trim(),d=y))}}return e}async function $0(t){let e=t??xb(),n=pb.join(e,".hermes","config.yaml"),i;try{i=await hb(n,"utf8")}catch{return null}let o=_b(i);return o.length===0?null:{models:o}}async function V0(t){let e;try{({stdout:e}=await ko(t,["models","list","--json","--log-level","silent"],{timeout:gb,maxBuffer:4*1024*1024}))}catch{return null}return yb(e)}function yb(t){let e;try{e=JSON.parse(t)}catch{return null}let n=Gr(cn(e)?.models);if(n.length===0)return null;let i=n.map(f=>cn(f)).filter(f=>f!==null&&f.available!==!1),o=i.filter(f=>Gr(f.tags).some(h=>h==="configured")),a=o.length>0?o:i,d=[],u;for(let f of a){let h=vt(f.key);if(!h)continue;let p={id:h},g=vt(f.name);g&&(p.name=g);let y=h.indexOf("/");y>0&&(p.providerId=h.slice(0,y)),d.push(p),!u&&Gr(f.tags).some(_=>_==="default")&&(u=h)}return d.length===0?null:{models:d,...u?{defaultModelId:u}:{}}}function bb(t){let e=[...t].sort((n,i)=>n.id.localeCompare(i.id));return W0("sha1").update(JSON.stringify(e)).digest("hex")}function J0(t){return W0("sha1").update(bb(t.models)).update(JSON.stringify(t.effortLevels??null)).update(JSON.stringify(t.fastModes??null)).digest("hex")}var Z=H("agent-handlers"),Y0=5*1024*1024,Ab=1,kb=6,Tb=new Set(["node_modules",".git",".coze","dist","build",".next"]),Cb=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Pb=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Rb=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Db(t){let e=t?.trim();return e?Rb.test(e)||Pb.test(e)?e:(Z.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Ob(t){return new Promise((e,n)=>{let i=ct("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 Lb(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var Oo=class t{constructor(e){this.opts=e}opts;static OPENCLAW_MODEL_CACHE_TTL_MS=18e4;openclawRefreshInFlight=!1;get paths(){return this.opts.paths??J()}async listSkills(e){e._meta;let n=nr(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Re(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Wr(a,n,o,this.paths),f=[],h=new Set;for(let g of d){let y=he(u,g.relPath,"SKILL.md");await Dd(y).then(b=>b.isFile()).catch(()=>!1)&&(f.push(zb(g)),h.add(g.relPath))}if(e.scanLocal){let g=await ch(n,o,a,this.paths),y=await dh(n,a);for(let _ of[...g,...y])h.has(_.relPath)||(h.add(_.relPath),f.push(_.skill))}return{skills:a==="hermes"?f.filter(g=>g.skillName!=="yuanbao"):f}}async addSkills(e){e._meta;let n=nr(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((f,h)=>[f.skillId,h])),u=[];for(let f of o){let h=await Lo({agentId:n,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});Mo(a,d,h),u.push(f)}return await _i(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=nr(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:u}=Wr(i.framework,n,i.workspace,this.paths);for(let f of a){if(!o.has(f.skillId)){d.push(f);continue}let h=he(u,f.relPath);Z.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:f.skillId,relPath:f.relPath,skillBase:u,absDir:h}),await Td(h,{recursive:!0,force:!0}),Z.info("skill removed",{agentId:n,skillId:f.skillId,relPath:f.relPath})}return await _i(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=nr(e._meta);if(!e.skillName)throw new T("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");Z.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),o=i?.workspace??Re(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,u=await Nb(n,o,a,e.skillName,d,this.paths);if(!u){let D=d?"global":"workspace";throw new T("SKILL_NOT_FOUND",`skill not found in ${D}: ${e.skillName}`)}let{absDir:f,relPath:h,dirName:p}=u,g=he(f,"SKILL.md"),y=new Ld.default;y.addLocalFolder(f,p);let _=y.toBuffer();if(_.length>X0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${X0}`);let b=await Do(g,{encoding:"utf8"}).then(D=>oh(D).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...b?{description:b}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):Z.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let k=I.version??"v1.0",C=I.skillId??e.skillId??sh(n,h);if(i&&!d){let D=i.skills??[],E=D.find(O=>O.relPath===h);E?(E.version=k,E.skillId=C):D.push({skillId:C,skillName:e.skillName,relPath:h,version:k,installedAt:Date.now(),...b?{description:b}:{}}),await _i(n,D)}return Z.info("skill published",{agentId:n,skillName:e.skillName,relPath:h,zipBytes:_.length,skillId:C,version:k}),{ok:!0,skillId:C,version:k}}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,Z.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,Z.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(n).catch(h=>Z.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:o,err:String(h)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return Z.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await me(n);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return Z.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await vr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw Z.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(o)}),new T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Ce(i),Z.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:i.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async upgradeBridge(e){let n=e.agentId||e._meta?.cozeAgentId;if(!n)throw new T("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await me(n))throw new T("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&Vi(e.registry)&&o.push(`--registry=${e.registry}`);let a=Db(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&Cb.test(d)&&o.push("--env",d);let u=await Ob(o);return Z.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 T("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await me(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ce(i),Z.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}):(Z.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new T("IPC_BAD_REQUEST",`${nt.DELETE}: missing agentId`);Z.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 me(n),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,a=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let d=Re(n);return a==="cloud"?(Z.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 Td(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ce(i)),Z.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=yd(e.model)??Lt;if(tr(e._meta)!=="cloud")return this.switchModelLocal(e,n);let i=await me(e.agentId);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ce(i),Z.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return Z.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(h=>Z.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(h)}));let u=o.framework==="hermes"&&Lb(d,o.modelInfo);if(o.framework==="hermes"&&!u){let h=[];for(let[p,g]of o.allSessionQueues())h.push(g.enqueue(async()=>{let y=o.sessions.get(p);if(!(!y?.downstream||!y.acpSessionId))try{await y.downstream.setSessionModel?.({sessionId:y.acpSessionId,modelId:n})}catch(_){Z.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:p,acpId:y.acpSessionId,err:String(_)})}}));return await Promise.all(h),Z.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:h.length}),{ok:!0}}let f=[];for(let[h,p]of o.allSessionQueues())f.push(p.enqueue(async()=>{let g=o.sessions.get(h);g?.downstream&&(await g.downstream.stop(`switchModel: ${n}`).catch(()=>{}),g.downstream=void 0)}));return await Promise.all(f),Z.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 me(e.agentId);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,await Ce(i),Z.info("_agent/switchModel(local): model persisted",{agentId:e.agentId,model:n});let o=this.opts.agents.get(e.agentId);if(!o)return Z.info("_agent/switchModel(local): agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};if(o.model=n,Et(n))return Z.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 Z.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 h=e.sessions.get(u);!h?.downstream||!h.acpSessionId||await h.downstream.setConfigOption(h.acpSessionId,i,o).catch(p=>Z.warn(`${a}: set_config_option failed (ignored)`,{agentId:n,cloudId:u,err:String(p)}))}));return await Promise.all(d),d.length}async setConfigOption(e){if(xd(e._meta,nt.SET_CONFIG_OPTION),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/setConfigOption: missing agentId");let n=await me(e.agentId);if(!n)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=S0(n.framework,e.configType);if(!i)throw new T("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 T("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 Ce(n),Z.info("_agent/setConfigOption: persisted",{agentId:e.agentId,configType:e.configType,value:d}),n.framework==="claude-code"&&e.configType==="effort"&&await _0(n.workspace,d).catch(h=>Z.warn("_agent/setConfigOption: writeCcWorkspaceEffort failed (ignored)",{agentId:e.agentId,err:String(h)}));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 y0(e).catch(()=>{});if(n)return n;let i=await b0().catch(()=>{});return i||"default"}async listAvailableModels(e){if(xd(e._meta,nt.LIST_AVAILABLE_MODELS),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/listAvailableModels: missing agentId");let n=await me(e.agentId);if(!n)throw new T("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 $0().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 h=o?.getRuntimeCurrent(e.agentId),p;n.model&&!Et(n.model)?p=n.model:(p=h?.model??n.resolvedModelId??d,p&&p!==n.resolvedModelId&&(n.resolvedModelId=p,await Ce(n).catch(C=>Z.warn("listAvailableModels: persist resolvedModelId failed (ignored)",{agentId:e.agentId,err:String(C)}))));let g=n.effort??h?.effort,y=n.fastMode??h?.fastMode,_=pd[i],b=f?.effortLevels??_.effort,I=f?.fastModes??_.fastMode,k={switchModel:!0,switchEffort:_.effort!==null,switchFastMode:_.fastMode!==null,...b?{supportedEffortLevels:[...b]}:{},...I?{supportedFastModes:[...I]}:{}};return{framework:i,models:a,...d?{defaultModelId:d}:{},...p?{currentModelId:p}:{},...k.switchEffort&&g?{currentEffort:g}:{},...k.switchFastMode&&y?{currentFastMode:y}:{},source:u,capabilities:k}}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 T("IPC_BAD_REQUEST",`${nt.DETAIL}: missing cozeAgentId`);let i=await me(n);if(!i)throw new T("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($i(e._meta,nt.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${nt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,nt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>Z.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,nt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),Z.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 wi(e,o)}async clearPersistedAcpSessionIds(e){let n=await me(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 Ce(n)}async repairAgent(e){if($i(e._meta,nt.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${nt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${nt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){Z.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,nt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){Z.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){Z.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){$i(e._meta,"_agent/getFileTree");let n=e._meta,i=nr(n),o=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(o,a),u=await Ad(d).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${a}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${a}`);if(!await mi(d,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let f=Yb(e.depth);return u.isDirectory()?{tree:await Zb(o,d,a,f)}:{tree:[{name:Xb(a),path:fh(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){$i(e._meta,"_agent/getFileContent");let n=nr(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new T("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),a=await Ad(o).catch(()=>null);if(!a||!a.isFile())throw new T("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(a.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await mi(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>Y0)throw new T("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${Y0})`);let d=await Do(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 me(e).catch(()=>null))?.workspace??Re(e).workspace}safeJoin(e,n){let i=Pd(e,n||"."),o=Od(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${eh}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return me(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new T("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function rh(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new T("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new T("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function Wr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:he(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:he(".agents","skills")};case"hermes":return{base:sr(e,i??J()),subdir:"skills"}}}function ih(t){let e=vb();if(t==="claude-code")return[he(e,".claude","skills")];if(t==="codex")return[he(e,".agents","skills"),he(e,".codex","skills")];if(t==="openclaw")return[he(e,".agents","skills"),he(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||he(e,"AppData","Local");return[he(n,"hermes","skills"),he(e,".hermes","skills")]}return[he(e,".hermes","skills")]}return[]}async function Mb(t,e,n,i,o,a){let d=async u=>Dd(he(u,"SKILL.md")).then(f=>f.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:f}=Wr(n,t,e,a),h=he(f,i),p=he(u,h);return await d(p)?{absDir:p,relPath:h}:null}for(let u of ih(n)){let f=he(u,i);if(await d(f))return{absDir:f,relPath:f}}return null}async function Nb(t,e,n,i,o,a){let d=rh(i),u=await Mb(t,e,n,d,o,a);if(u)return{...u,dirName:d};let h=(o?await dh(t,n):await ch(t,e,n,a)).filter(y=>y.skill.skillName===i);if(h.length>1)throw new T("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${h.map(y=>Z0(y.relPath)).join(", ")} \u2014 rename or remove duplicates`);let p=h[0];return p?{absDir:o?p.relPath:he(e,p.relPath),relPath:p.relPath,dirName:Z0(p.relPath)}:null}function sh(t,e){return(Eb("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function oh(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
|
|
97
|
+
`}var ir=G("hermes-config"),U0="dont_ask",H0="default";function sr(t,e){return Xi(Oe(t,e).root,"hermes-home")}async function fb(t){let e=sr(t.agentId,t.paths);await ub(e,{recursive:!0,mode:448});let n=Ji({...process.env,...rr(t.paths.agentEnvFile)});await mt(Xi(e,".env"),n,{mode:384});let i=vd(t.modelConfig,t.cozeEnv,t.mockScenario);await mt(Xi(e,"config.yaml"),i,{mode:384}),ir.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function G0(t){let e=sr(t.agentId,t.paths),n=Xi(e,"state.db"),i=Xi(e,"config.yaml");ir.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 z0(n,{force:!0}).catch(a=>ir.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let o=vd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await mt(i,o,{mode:384}).catch(a=>ir.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(a)})),ir.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function Id(t,e){let n=sr(t,e);ir.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 z0(n,{recursive:!0,force:!0}).catch(i=>ir.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var Sd=new Map;function q0(t){let e=Sd.get(t.agentId);if(e)return e;let n=fb(t).finally(()=>Sd.delete(t.agentId));return Sd.set(t.agentId,n),n}Gt();import{createHash as j0}from"node:crypto";import{readFile as hb}from"node:fs/promises";import{homedir as xb}from"node:os";import pb from"node:path";var gb=3e4;function an(t){return typeof t=="object"&&t!==null?t:null}function Gr(t){return Array.isArray(t)?t:[]}function bt(t){return typeof t=="string"?t:void 0}function W0(t,e){return t.map(n=>an(n)).filter(n=>n!==null).map(n=>{let i={id:bt(n[e])??""},o=bt(n.name),a=bt(n.description);return o&&(i.name=o),a&&(i.description=a),i}).filter(n=>n.id!=="")}function mb(t){let e=Gr(t.configOptions);if(e.length===0)return null;let n=null,i,o,a,d,u;for(let x of e){let p=an(x);if(!p)continue;let m=bt(p.id);if(!m)continue;let y=Gr(p.options);m==="model"?(n=W0(y,"value"),i=bt(p.currentValue)):m==="effort"||m==="reasoning_effort"?(o=bt(p.currentValue),d=y.map(_=>bt(an(_)?.value)).filter(_=>_!==void 0)):m==="fast-mode"&&(a=bt(p.currentValue),u=y.map(_=>bt(an(_)?.value)).filter(_=>_!==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 wb(t){let e=an(t.models);if(!e)return null;let n=Gr(e.availableModels);if(n.length===0)return null;let i=W0(n,"modelId");if(i.length===0)return null;let o=bt(e.currentModelId);return{models:i,...o?{currentModelId:o}:{}}}function K0(t,e){let n=an(e);if(!n)return null;let i=an(n.result)??n;return t==="hermes"?wb(i):mb(i)}function _b(t){let e=[],n=t.split(/\r?\n/),i=!1,o=-1,a=null,d=-1,u=!1,f=-1,x=p=>p.length-p.trimStart().length;for(let p of n){let m=p.replace(/#.*$/,"").trimEnd();if(m.trim()==="")continue;let y=x(m),_=m.trim();if(!i){_==="providers:"&&(i=!0,o=y);continue}if(y<=o&&!_.startsWith("-"))break;if((a===null||y<=d)&&_.endsWith(":")&&!_.startsWith("-")){a=_.slice(0,-1).trim(),d=y,u=!1;continue}if(a!==null){if(!u){_==="models:"&&(u=!0,f=y);continue}if(_.startsWith("-")&&y>f){let E=_.slice(1).trim(),I,A=E.match(/^(?:model|id)\s*:\s*(.+)$/);if(A?.[1]?I=A[1].trim():E&&!E.includes(":")&&(I=E),I){let C=I.replace(/^["']|["']$/g,"");e.push({id:`${a}:${C}`,providerId:a})}continue}y<=f&&(u=!1,y<=d&&_.endsWith(":")&&(a=_.slice(0,-1).trim(),d=y))}}return e}async function $0(t){let e=t??xb(),n=pb.join(e,".hermes","config.yaml"),i;try{i=await hb(n,"utf8")}catch{return null}let o=_b(i);return o.length===0?null:{models:o}}async function V0(t){let e;try{({stdout:e}=await ko(t,["models","list","--json","--log-level","silent"],{timeout:gb,maxBuffer:4*1024*1024}))}catch{return null}return yb(e)}function yb(t){let e;try{e=JSON.parse(t)}catch{return null}let n=Gr(an(e)?.models);if(n.length===0)return null;let i=n.map(f=>an(f)).filter(f=>f!==null&&f.available!==!1),o=i.filter(f=>Gr(f.tags).some(x=>x==="configured")),a=o.length>0?o:i,d=[],u;for(let f of a){let x=bt(f.key);if(!x)continue;let p={id:x},m=bt(f.name);m&&(p.name=m);let y=x.indexOf("/");y>0&&(p.providerId=x.slice(0,y)),d.push(p),!u&&Gr(f.tags).some(_=>_==="default")&&(u=x)}return d.length===0?null:{models:d,...u?{defaultModelId:u}:{}}}function bb(t){let e=[...t].sort((n,i)=>n.id.localeCompare(i.id));return j0("sha1").update(JSON.stringify(e)).digest("hex")}function J0(t){return j0("sha1").update(bb(t.models)).update(JSON.stringify(t.effortLevels??null)).update(JSON.stringify(t.fastModes??null)).digest("hex")}var Y=G("agent-handlers"),Y0=5*1024*1024,Ab=1,kb=6,Cb=new Set(["node_modules",".git",".coze","dist","build",".next"]),Tb=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Pb=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Rb=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Ob(t){let e=t?.trim();return e?Rb.test(e)||Pb.test(e)?e:(Y.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Db(t){return new Promise((e,n)=>{let i=at("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,a=d=>{o||(o=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),a()}),i.once("error",d=>a(d))})}function Lb(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var Do=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=nr(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Oe(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:u}=jr(a,n,o,this.paths),f=[],x=new Set;for(let m of d){let y=xe(u,m.relPath,"SKILL.md");await Od(y).then(E=>E.isFile()).catch(()=>!1)&&(f.push(zb(m)),x.add(m.relPath))}if(e.scanLocal){let m=await ch(n,o,a,this.paths),y=await dh(n,a);for(let _ of[...m,...y])x.has(_.relPath)||(x.add(_.relPath),f.push(_.skill))}return{skills:a==="hermes"?f.filter(m=>m.skillName!=="yuanbao"):f}}async addSkills(e){e._meta;let n=nr(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await Lo({agentId:n,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});Mo(a,d,x),u.push(f)}return await _i(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=nr(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:u}=jr(i.framework,n,i.workspace,this.paths);for(let f of a){if(!o.has(f.skillId)){d.push(f);continue}let x=xe(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:x}),await Cd(x,{recursive:!0,force:!0}),Y.info("skill removed",{agentId:n,skillId:f.skillId,relPath:f.relPath})}return await _i(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=nr(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??Oe(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,u=await Nb(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:x,dirName:p}=u,m=xe(f,"SKILL.md"),y=new Ld.default;y.addLocalFolder(f,p);let _=y.toBuffer();if(_.length>X0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${X0}`);let E=await Oo(m,{encoding:"utf8"}).then(P=>oh(P).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...E?{description:E}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):Y.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",C=I.skillId??e.skillId??sh(n,x);if(i&&!d){let P=i.skills??[],b=P.find(R=>R.relPath===x);b?(b.version=A,b.skillId=C):P.push({skillId:C,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...E?{description:E}:{}}),await _i(n,P)}return Y.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:_.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(x=>Y.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 Y.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await me(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 vr(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 Te(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 me(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&Vi(e.registry)&&o.push(`--registry=${e.registry}`);let a=Ob(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&Tb.test(d)&&o.push("--env",d);let u=await Db(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 me(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Te(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",`${et.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 me(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"?(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 Cd(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Te(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=yd(e.model)??Ot;if(tr(e._meta)!=="cloud")return this.switchModelLocal(e,n);let i=await me(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 Te(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(x=>Y.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=o.framework==="hermes"&&Lb(d,o.modelInfo);if(o.framework==="hermes"&&!u){let x=[];for(let[p,m]of o.allSessionQueues())x.push(m.enqueue(async()=>{let y=o.sessions.get(p);if(!(!y?.downstream||!y.acpSessionId))try{await y.downstream.setSessionModel?.({sessionId:y.acpSessionId,modelId:n})}catch(_){Y.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:p,acpId:y.acpSessionId,err:String(_)})}}));return await Promise.all(x),Y.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:x.length}),{ok:!0}}let f=[];for(let[x,p]of o.allSessionQueues())f.push(p.enqueue(async()=>{let m=o.sessions.get(x);m?.downstream&&(await m.downstream.stop(`switchModel: ${n}`).catch(()=>{}),m.downstream=void 0)}));return await Promise.all(f),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 me(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,await Te(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,yt(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 x=e.sessions.get(u);!x?.downstream||!x.acpSessionId||await x.downstream.setConfigOption(x.acpSessionId,i,o).catch(p=>Y.warn(`${a}: set_config_option failed (ignored)`,{agentId:n,cloudId:u,err:String(p)}))}));return await Promise.all(d),d.length}async setConfigOption(e){if(xd(e._meta,et.SET_CONFIG_OPTION),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/setConfigOption: missing agentId");let n=await me(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=S0(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 Te(n),Y.info("_agent/setConfigOption: persisted",{agentId:e.agentId,configType:e.configType,value:d}),n.framework==="claude-code"&&e.configType==="effort"&&await _0(n.workspace,d).catch(x=>Y.warn("_agent/setConfigOption: writeCcWorkspaceEffort failed (ignored)",{agentId:e.agentId,err:String(x)}));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 y0(e).catch(()=>{});if(n)return n;let i=await b0().catch(()=>{});return i||"default"}async listAvailableModels(e){if(xd(e._meta,et.LIST_AVAILABLE_MODELS),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/listAvailableModels: missing agentId");let n=await me(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 $0().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 x=o?.getRuntimeCurrent(e.agentId),p;n.model&&!yt(n.model)?p=n.model:(p=x?.model??n.resolvedModelId??d,p&&p!==n.resolvedModelId&&(n.resolvedModelId=p,await Te(n).catch(C=>Y.warn("listAvailableModels: persist resolvedModelId failed (ignored)",{agentId:e.agentId,err:String(C)}))));let m=n.effort??x?.effort,y=n.fastMode??x?.fastMode,_=pd[i],E=f?.effortLevels??_.effort,I=f?.fastModes??_.fastMode,A={switchModel:!0,switchEffort:_.effort!==null,switchFastMode:_.fastMode!==null,...E?{supportedEffortLevels:[...E]}:{},...I?{supportedFastModes:[...I]}:{}};return{framework:i,models:a,...d?{defaultModelId:d}:{},...p?{currentModelId:p}:{},...A.switchEffort&&m?{currentEffort:m}:{},...A.switchFastMode&&y?{currentFastMode:y}:{},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",`${et.DETAIL}: missing cozeAgentId`);let i=await me(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($i(e._meta,et.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${et.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,et.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,et.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 wi(e,o)}async clearPersistedAcpSessionIds(e){let n=await me(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 Te(n)}async repairAgent(e){if($i(e._meta,et.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${et.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${et.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,et.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){$i(e._meta,"_agent/getFileTree");let n=e._meta,i=nr(n),o=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(o,a),u=await Ad(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 mi(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let f=Yb(e.depth);return u.isDirectory()?{tree:await Zb(o,d,a,f)}:{tree:[{name:Xb(a),path:fh(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){$i(e._meta,"_agent/getFileContent");let n=nr(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 Ad(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 mi(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>Y0)throw new k("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${Y0})`);let d=await Oo(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 me(e).catch(()=>null))?.workspace??Oe(e).workspace}safeJoin(e,n){let i=Pd(e,n||"."),o=Dd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${eh}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return me(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 rh(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:sr(e,i??Z()),subdir:"skills"}}}function ih(t){let e=vb();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 Mb(t,e,n,i,o,a){let d=async u=>Od(xe(u,"SKILL.md")).then(f=>f.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:f}=jr(n,t,e,a),x=xe(f,i),p=xe(u,x);return await d(p)?{absDir:p,relPath:x}:null}for(let u of ih(n)){let f=xe(u,i);if(await d(f))return{absDir:f,relPath:f}}return null}async function Nb(t,e,n,i,o,a){let d=rh(i),u=await Mb(t,e,n,d,o,a);if(u)return{...u,dirName:d};let x=(o?await dh(t,n):await ch(t,e,n,a)).filter(y=>y.skill.skillName===i);if(x.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${x.map(y=>Z0(y.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:Z0(p.relPath)}:null}function sh(t,e){return(Eb("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function oh(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
|
|
101
101
|
---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let o of n.split(`
|
|
102
|
-
`)){let a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!a||!a[2])continue;let d=a[1],u=a[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function ah(t,e,n,i){let o=await Q0(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 Dd(he(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,h=he(n,f),p=he(e,f,"SKILL.md"),g=await Do(p,{encoding:"utf8"}).catch(()=>null);if(g===null)continue;let y=oh(g);a.push({relPath:h,skill:{skillId:sh(t,h),skillName:y.name||f,...y.description?{description:y.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function ch(t,e,n,i){let{base:o,subdir:a}=Wr(n,t,e,i);return ah(t,he(o,a),a,!1)}async function dh(t,e){let n=[],i=new Set;for(let o of ih(e)){let a=await ah(t,o,o,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var Bb=3e4,Fb=50*1024*1024,X0=10*1024*1024,qr=3e4;async function Lo(t){let{agentId:e,workspace:n,framework:i,skill:o,paths:a}=t;if(!o.skillName)throw new T("IPC_BAD_REQUEST","skill missing skillName");let d=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!d&&!u)throw new T("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let f=rh(o.skillName),{base:h,subdir:p}=Wr(i,e,n,a),g=he(p,f),y=he(h,g);if(await kd(y,{recursive:!0}),d){let b=Buffer.from(o.content,"utf8");Qi(b.length),await Cd(he(y,"SKILL.md"),b,"utf8")}else{let b=await Hb(o.downloadUrl);qb(b)?await $b(b,y):Wb(b)?await jb(b,y):await Cd(he(y,"SKILL.md"),b.toString("utf8"),"utf8")}let _={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 Z.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:g,source:d?"content":"downloadUrl"}),_}function Mo(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 zb(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 Ub(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 lh(t,e){let n=await me(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 Ce(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((g,y)=>[g.skillId,y])),u=a.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Ce(n,e),{status:"noop",count:0};let f=0,h=0,{base:p}=Wr(n.framework,t,n.workspace,e);Z.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:p,builtinCount:u.length,builtinRelPaths:u.map(g=>g.relPath)});for(let g of u)try{let y=he(p,g.relPath);Z.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:g.skillId,relPath:g.relPath,rmTarget:y}),await Td(y,{recursive:!0,force:!0});let _=await Lo({agentId:t,workspace:n.workspace,framework:n.framework,skill:Ub(g),...e?{paths:e}:{}});Mo(a,d,_),f+=1}catch(y){h+=1,Z.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(y)})}return n.skills=a,h===0&&(n.skillsRefreshedForVersion=i),await Ce(n,e),Z.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:h}),{status:"refreshed",count:f}}async function Hb(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Qi(e);let n=Gb(t);return Qi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Do(e);return Qi(n.length),n}if(Vi(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),Bb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new T("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Qi(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new T("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Qi(t){if(t>Fb)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Gb(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new T("IPC_BAD_REQUEST","bad data URL");let n=!!e[2],i=e[3]??"";return n?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function qb(t){return t.length>=2&&t[0]===31&&t[1]===139}function Wb(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 Rd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function jb(t,e){let n,i;try{n=new Ld.default(t),i=n.getEntries()}catch(d){throw new T("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||Rd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new T("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(h=>h===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=Kb(i),a=Pd(e);for(let d of i){if(Rd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=Pd(e,u),h=Od(a,f);if(h.startsWith("..")||h==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await kd(f,{recursive:!0});continue}await kd(Sb(f),{recursive:!0});let p;try{p=d.getData()}catch(g){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${g.message}`,{cause:g})}await Cd(f,p)}}function Kb(t){let e;for(let n of t){let i=n.entryName;if(!i||Rd(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 $b(t,e){await Vb(t);let n=d0({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${qr}ms)`))},qr);try{await nh(th.from(t),n)}catch(a){throw a instanceof T?a:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${qr}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function Vb(t){let e=[],n=zr({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(h=>h==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${qr}ms)`))},qr);try{await nh(th.from(t),n)}catch(a){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${qr}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Jb=5e3;async function Zb(t,e,n,i){return uh(t,e,n,i,{count:0})}async function uh(t,e,n,i,o){if(i<=0)return[];let a;try{a=await Q0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if(Tb.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Jb){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=he(e,u.name),h=Ib(he(n,u.name)),p=null;try{p=await Ad(f)}catch{continue}if(p.isSymbolicLink())continue;o.count++;let g={name:u.name,path:fh(Od(t,f)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(g.children=await uh(t,f,h,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 Yb(t){return!t||t<=0?Ab:Math.min(t,kb)}function Xb(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function fh(t){return t.split(eh).join("/")}ne();var On=H("agent-health-reporter"),Qb=1e4,eE=3,es=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Qb,this.livenessFailureThreshold=e.livenessFailureThreshold??eE}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()}),On.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),On.info("heartbeat stopped"))}async tick(){if(this.inFlight){On.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,On.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=tE(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,On.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=o?.authFailures;if(a&&a.length>0&&(On.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){On.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){On.warn("onTickEnd hook failed",{err:String(n)})}}};function tE(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}en();import{copyFile as wv,cp as _v,mkdir as $o,readFile as yv,rm as bv,stat as Gd,writeFile as Ev}from"node:fs/promises";import{homedir as Yh}from"node:os";import{basename as vv,join as ln}from"node:path";_n();import{existsSync as fE}from"node:fs";import{release as hE}from"node:os";import{basename as xE,isAbsolute as pE}from"node:path";function ts(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function jr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Kr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Ln(t,e){return{jsonrpc:"2.0",id:t,error:e}}$e();var No=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 hh(t){return"method"in t&&"id"in t&&t.id!==void 0}function xh(t){return"method"in t&&!("id"in t)}function Bo(t){return!("method"in t)&&"id"in t}var nE={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 rE(t){if(t!=null)return t instanceof Error?{name:t.name,message:ns(t.message)}:typeof t=="string"?ns(t):typeof t=="object"?sE(t):t}var iE=[[/\/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 ns(t){let e=t;for(let[n,i]of iE)e=e.replace(n,i);return e}function sE(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=ns(i):e[n]=i;return e}function rs(t){if(t instanceof T){let e=rE(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:nE[t.code]??Q.INTERNAL_ERROR,message:ns(t.message),data:n}}return{code:Q.INTERNAL_ERROR,message:ns(t instanceof Error?t.message:String(t))}}function ph(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 T(n,o,{retriable:e?.retriable??!1,cause:a})}function mh(t){return`${JSON.stringify(t)}
|
|
103
|
-
`}var gh=10*1024*1024,
|
|
104
|
-
`);this.buffer=n.pop()??"";let i=[];for(let o of n){let a=o.replace(/\r$/,"").trim();if(a)try{i.push(JSON.parse(a))}catch(d){this.onError?.({line:a,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(n){return this.onError?.({line:e,error:n}),[]}}};var _h={"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"},fP=Object.fromEntries(Object.entries(_h).map(([t,e])=>[e,t])),oE={"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:[]},$r=class{seq=0;next(e,n){this.seq+=1;let i=_h[e]??aE(e),o=oE[i]??[],a=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>wh(n?.[f]??"")),u=cE(d).join(":");u&&a.push(u)}else n&&Object.values(n).some(d=>d)&&a.push(Object.values(n).filter(Boolean).map(d=>wh(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function aE(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function wh(t){return t.replace(/[:_\s]+/g,"-")}function cE(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}
|
|
105
|
-
`).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function Sh(t,e){if(t.length===0)return;let n=e?.killFn??ss,i=e?.isAliveFn??is,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 uE=[{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 Ih(t,e){if(!e)return null;for(let n of uE)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function Ah(t,e){return Ih(t,e)}function kh(t,e){return Ih(t,e)}function Jr(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 Th(t,e,n){let o=n-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let h=t.suspendedMs+o,p=n-t.startedAt-h;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Jr(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:Jr(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Jr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Jr(a,!1,e)}}var Ch=Ke("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",6e4),gE=200,mE=40,wE=Ke("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),_E=Ke("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),yE=Ke("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),bE=Ke("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),EE=Ke("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),vE=Ke("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Ph=500,SE=process.env.COZE_BRIDGE_TRACE_RPC==="1",Rh=Ke("COZE_BRIDGE_TRACE_RPC_MAX",2e3);function IE(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Ph?t:`${e.slice(0,Ph)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function AE(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 Dh(t){try{return fE(t)}catch{return}}function kE(t,e){return{platform:process.platform,osRelease:hE(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:pE(e.command)?Dh(e.command):void 0,cwd:e.cwd,cwdExists:Dh(e.cwd),envKeys:e.envKeys}}function TE(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${xE(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var St=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Fo({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new $r;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new T("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=To(process.env,this.opts.agentEnvFile??J().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=ct(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,yh(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>gE&&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,bh(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=kE(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 T("AGENT_SPAWN_FAILED",TE(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()));ss(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||ss(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:EE,phase2GateMs:wE,livenessWindowMs:_E,absoluteMaxMs:yE,approvalMaxMs:vE,suspendThresholdMs:bE,...n};return this.call("session/prompt",e,Ch,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(jr("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 T("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(Kr(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(Ln(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=Ch,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=ts(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,h)=>{let p={resolve:f,reject:h,timer:null,method:e,promptTimeout:null};if(o){let g=this.now(),y={cfg:o,startedAt:g,lastActivityAt:g,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:g,expectedIntervalMs:Jr(0,!1,o),sessionId:u};p.promptTimeout=y;let _=()=>{let b={startedAt:y.startedAt,lastActivityAt:y.lastActivityAt,firstFrameSeen:y.firstFrameSeen,hasActiveTool:y.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:y.suspendedMs,armedAt:y.armedAt,expectedIntervalMs:y.expectedIntervalMs},I=this.now(),k=Th(b,y.cfg,I),C=D=>{y.armedAt=I,y.expectedIntervalMs=D,p.timer=setTimeout(_,D)};if(k.action==="suspend"){y.suspendedMs+=k.suspendedDeltaMs,y.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:k.suspendedDeltaMs,suspendedMs:y.suspendedMs,...y.sessionId?{sessionId:y.sessionId}:{}}),C(k.rearmMs);return}if(k.action==="continue"){C(k.rearmMs);return}this.pending.delete(a),k.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:k.awaitingApproval,...y.sessionId?{sessionId:y.sessionId}:{}}),h(k.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${y.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${y.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...y.sessionId?{sessionId:y.sessionId}:{}}),h(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${y.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(_,y.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}),h(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,p);try{this.writeFrame(d)}catch(g){p.timer&&clearTimeout(p.timer),this.pending.delete(a),h(g)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.traceFrame("->",e),this.child.stdin.write(mh(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}traceFrame(e,n){if(!SE)return;let i=n,o;try{let a=JSON.stringify(n);o=a===void 0||a.length<=Rh?n:`${a.slice(0,Rh)}...<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),Bo(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new T("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:IE(e.result)}),n.resolve(e.result));return}if(xh(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(hh(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(Ln(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(Ln(e.id,rs(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=ph(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=kh(this.framework,AE(e));return i?new T(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):n}buildExitError(e,n){if(this.stopReason!==void 0)return new T("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(mE).join(`
|
|
106
|
-
`),o=Ah(this.framework,i);return o?new
|
|
107
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function YE(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]=ZE(o.slice(a+1)))}return e}function XE(t){let e=Zr(t,"cozeloop.env");return
|
|
108
|
-
`)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{BE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function ev(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=Nh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}ne();var tv=H("hermes-downstream"),Go=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){tv.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)}};$e();var Uh=3e4,Yr=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}`}]},Uh))}get acpSessionName(){return this.sessionName}async setConfigOption(e,n,i){if(n!=="model")throw new T("CAPABILITY_UNSUPPORTED",`openclaw does not support axis '${n}'`);await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${i}`}]},Uh)}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Tt();$e();ne();Te();function Ud(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}_n();var $t=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 qo=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 $t,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)Xr(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 Xr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function dn(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Wt();ne();import{constants as Hh}from"node:fs";import{access as nv,readFile as rv}from"node:fs/promises";import{delimiter as iv,dirname as sv,join as Gh}from"node:path";var rt=H("framework-detector"),qh={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},ov=[".exe",".cmd",".bat",".ps1"],or=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??ct,access:e.access??nv,readFile:e.readFile??rv}}async detect(e){let n=qh[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return rt.debug("framework binary not found",{framework:e,bin:n}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[a,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:a};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(qh).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(iv).filter(Boolean),i=this.env.platform==="win32"?["",...ov]:[""];for(let o of n)for(let a of i){let d=Gh(o,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?Hh.F_OK:Hh.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let n;try{n=await this.env.readFile(e,"utf8")}catch(d){return rt.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let o=n.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return rt.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=Gh(sv(o),"hermes-acp");return await this.isExecutable(a)?(rt.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(rt.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:a}),null)}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return rt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return rt.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return rt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return rt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let a=o.find(d=>d?.isDefault===!0);return a?!a.id||!a.workspace?(rt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!a.id,hasWorkspace:!!a.workspace}),null):{id:a.id,workspace:a.workspace}:(rt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return rt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return rt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||rt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let o={reachable:i},a=n.stdout.match(/\{[\s\S]*\}/);if(a)try{let d=JSON.parse(a[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){rt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(cv(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",h=>{o+=h.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",h=>u({code:h,stdout:o}))}catch{u(null)}})}},av=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function cv(t){return t.replace(av,"")}import{homedir as jh}from"node:os";import{join as jo}from"node:path";Tt();Wt();wr();$e();ne();async function Kh(){let t=jo(jh(),".openclaw/openclaw.json");return Ye(t)}async function $h(){return(await Kh())?.gateway?.auth?.token??""}var ar=H("openclaw.config"),dv=[0,5e3,5e3],lv=Ke("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),Wh="models.providers.",Wo="agents.defaults.models",uv=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function Qr(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 Ko=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new $t;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??dv,this.cliTimeoutMs=e.cliTimeoutMs??lv,this.openclawDir=e.openclawDir??jo(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,ar.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new T("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=ct(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=h=>{d||(d=!0,clearTimeout(f),h())};o.stderr?.on("data",h=>{a+=h.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",h=>u(()=>i(h))),o.on("close",h=>u(()=>{h===0?n():i(new Error(`exit ${h}: ${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){ar.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",`${Wh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Wh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Wo}[${e}]`,()=>this.runCli(["config","set",Wo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Wo}[${e}]`,`${Wo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await Kh())?.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=jo(this.openclawDir,"identity","device.json"),i=(await Ye(e))?.deviceId?.trim();if(!i)return ar.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=jo(this.openclawDir,"devices","paired.json"),a=await Ye(o),d=a?.[i];if(!a||!d)return ar.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,f=Qr(Qr(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(b=>b.startsWith("operator.")),h=Qr([...uv],f),p=Qr(d.scopes,h),g=Qr(d.approvedScopes,h),y=u?Qr(u.scopes,h):void 0;return p.length!==(d.scopes?.length??0)||g.length!==(d.approvedScopes?.length??0)||u!==void 0&&y?.length!==(u.scopes?.length??0)?(d.scopes=p,d.approvedScopes=g,u&&y&&(u.scopes=y),await ft(o,a,{mode:384}),ar.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:h}),!0):(ar.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return ar.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 fv,writeFile as hv}from"node:fs/promises";import{join as xv}from"node:path";var pv=["```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 ah(t,e,n,i){let o=await Q0(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 Od(xe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,x=xe(n,f),p=xe(e,f,"SKILL.md"),m=await Oo(p,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let y=oh(m);a.push({relPath:x,skill:{skillId:sh(t,x),skillName:y.name||f,...y.description?{description:y.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function ch(t,e,n,i){let{base:o,subdir:a}=jr(n,t,e,i);return ah(t,xe(o,a),a,!1)}async function dh(t,e){let n=[],i=new Set;for(let o of ih(e)){let a=await ah(t,o,o,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var Fb=3e4,Bb=50*1024*1024,X0=10*1024*1024,qr=3e4;async function Lo(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=rh(o.skillName),{base:x,subdir:p}=jr(i,e,n,a),m=xe(p,f),y=xe(x,m);if(await kd(y,{recursive:!0}),d){let E=Buffer.from(o.content,"utf8");Qi(E.length),await Td(xe(y,"SKILL.md"),E,"utf8")}else{let E=await Hb(o.downloadUrl);qb(E)?await $b(E,y):jb(E)?await Wb(E,y):await Td(xe(y,"SKILL.md"),E.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:m,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return Y.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:m,source:d?"content":"downloadUrl"}),_}function Mo(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 zb(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 Ub(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 lh(t,e){let n=await me(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=qt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await Te(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((m,y)=>[m.skillId,y])),u=a.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Te(n,e),{status:"noop",count:0};let f=0,x=0,{base:p}=jr(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:p,builtinCount:u.length,builtinRelPaths:u.map(m=>m.relPath)});for(let m of u)try{let y=xe(p,m.relPath);Y.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:m.skillId,relPath:m.relPath,rmTarget:y}),await Cd(y,{recursive:!0,force:!0});let _=await Lo({agentId:t,workspace:n.workspace,framework:n.framework,skill:Ub(m),...e?{paths:e}:{}});Mo(a,d,_),f+=1}catch(y){x+=1,Y.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(y)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await Te(n,e),Y.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function Hb(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Qi(e);let n=Gb(t);return Qi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Oo(e);return Qi(n.length),n}if(Vi(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),Fb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Qi(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Qi(t){if(t>Bb)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Gb(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 qb(t){return t.length>=2&&t[0]===31&&t[1]===139}function jb(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 Rd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Wb(t,e){let n,i;try{n=new Ld.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||Rd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=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=Kb(i),a=Pd(e);for(let d of i){if(Rd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=Pd(e,u),x=Dd(a,f);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await kd(f,{recursive:!0});continue}await kd(Sb(f),{recursive:!0});let p;try{p=d.getData()}catch(m){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${m.message}`,{cause:m})}await Td(f,p)}}function Kb(t){let e;for(let n of t){let i=n.entryName;if(!i||Rd(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 $b(t,e){await Vb(t);let n=d0({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${qr}ms)`))},qr);try{await nh(th.from(t),n)}catch(a){throw a instanceof k?a:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${qr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function Vb(t){let e=[],n=zr({onReadEntry:a=>{let d=a.path,u=a.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${qr}ms)`))},qr);try{await nh(th.from(t),n)}catch(a){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${qr}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 Jb=5e3;async function Zb(t,e,n,i){return uh(t,e,n,i,{count:0})}async function uh(t,e,n,i,o){if(i<=0)return[];let a;try{a=await Q0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if(Cb.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Jb){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=xe(e,u.name),x=Ib(xe(n,u.name)),p=null;try{p=await Ad(f)}catch{continue}if(p.isSymbolicLink())continue;o.count++;let m={name:u.name,path:fh(Dd(t,f)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(m.children=await uh(t,f,x,i-1,o)),d.push(m)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function Yb(t){return!t||t<=0?Ab:Math.min(t,kb)}function Xb(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function fh(t){return t.split(eh).join("/")}ne();var On=G("agent-health-reporter"),Qb=1e4,eE=3,es=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Qb,this.livenessFailureThreshold=e.livenessFailureThreshold??eE}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()}),On.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),On.info("heartbeat stopped"))}async tick(){if(this.inFlight){On.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,On.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=tE(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:qt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,On.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=o?.authFailures;if(a&&a.length>0&&(On.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){On.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){On.warn("onTickEnd hook failed",{err:String(n)})}}};function tE(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Qt();import{copyFile as wv,cp as _v,mkdir as $o,readFile as yv,rm as bv,stat as Gd,writeFile as Ev}from"node:fs/promises";import{homedir as Yh}from"node:os";import{basename as vv,join as dn}from"node:path";wn();import{existsSync as fE}from"node:fs";import{release as hE}from"node:os";import{basename as xE,isAbsolute as pE}from"node:path";function ts(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Wr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Kr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Dn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ve();var No=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 hh(t){return"method"in t&&"id"in t&&t.id!==void 0}function xh(t){return"method"in t&&!("id"in t)}function Fo(t){return!("method"in t)&&"id"in t}var nE={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 rE(t){if(t!=null)return t instanceof Error?{name:t.name,message:ns(t.message)}:typeof t=="string"?ns(t):typeof t=="object"?sE(t):t}var iE=[[/\/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 ns(t){let e=t;for(let[n,i]of iE)e=e.replace(n,i);return e}function sE(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=ns(i):e[n]=i;return e}function rs(t){if(t instanceof k){let e=rE(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:nE[t.code]??Q.INTERNAL_ERROR,message:ns(t.message),data:n}}return{code:Q.INTERNAL_ERROR,message:ns(t instanceof Error?t.message:String(t))}}function ph(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 mh(t){return`${JSON.stringify(t)}
|
|
103
|
+
`}var gh=10*1024*1024,Bo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>gh){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${gh} 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 _h={"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"},fP=Object.fromEntries(Object.entries(_h).map(([t,e])=>[e,t])),oE={"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:[]},$r=class{seq=0;next(e,n){this.seq+=1;let i=_h[e]??aE(e),o=oE[i]??[],a=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>wh(n?.[f]??"")),u=cE(d).join(":");u&&a.push(u)}else n&&Object.values(n).some(d=>d)&&a.push(Object.values(n).filter(Boolean).map(d=>wh(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function aE(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function wh(t){return t.replace(/[:_\s]+/g,"-")}function cE(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Gt();wr();Ve();ne();Ce();import{execFileSync as dE,spawnSync as lE}from"node:child_process";function is(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function ss(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),lE("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var Md=new Set;function yh(t){typeof t=="number"&&t>0&&Md.add(t)}function bh(t){typeof t=="number"&&Md.delete(t)}function Eh(){for(let t of Md)ss(t,"SIGKILL")}var Vr="coze-bridge-daemon";function vh(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return dE("pgrep",["-U",String(o),"-f",Vr],{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 Sh(t,e){if(t.length===0)return;let n=e?.killFn??ss,i=e?.isAliveFn??is,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 uE=[{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 Ih(t,e){if(!e)return null;for(let n of uE)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function Ah(t,e){return Ih(t,e)}function kh(t,e){return Ih(t,e)}function Jr(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 Ch(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:Jr(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:Jr(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Jr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Jr(a,!1,e)}}var Th=$e("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",6e4),gE=200,mE=40,wE=$e("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),_E=$e("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),yE=$e("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),bE=$e("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),EE=$e("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),vE=$e("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Ph=500,SE=process.env.COZE_BRIDGE_TRACE_RPC==="1",Rh=$e("COZE_BRIDGE_TRACE_RPC_MAX",2e3);function IE(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Ph?t:`${e.slice(0,Ph)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function AE(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 Oh(t){try{return fE(t)}catch{return}}function kE(t,e){return{platform:process.platform,osRelease:hE(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:pE(e.command)?Oh(e.command):void 0,cwd:e.cwd,cwdExists:Oh(e.cwd),envKeys:e.envKeys}}function CE(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${xE(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Et=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Bo({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new $r;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=Co(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=at(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,yh(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>gE&&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,bh(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=kE(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",CE(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()));ss(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||ss(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:EE,phase2GateMs:wE,livenessWindowMs:_E,absoluteMaxMs:yE,approvalMaxMs:vE,suspendThresholdMs:bE,...n};return this.call("session/prompt",e,Th,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Wr("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(Kr(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(Dn(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=Th,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=ts(a,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let f=n.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,x)=>{let p={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let m=this.now(),y={cfg:o,startedAt:m,lastActivityAt:m,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:m,expectedIntervalMs:Jr(0,!1,o),sessionId:u};p.promptTimeout=y;let _=()=>{let E={startedAt:y.startedAt,lastActivityAt:y.lastActivityAt,firstFrameSeen:y.firstFrameSeen,hasActiveTool:y.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:y.suspendedMs,armedAt:y.armedAt,expectedIntervalMs:y.expectedIntervalMs},I=this.now(),A=Ch(E,y.cfg,I),C=P=>{y.armedAt=I,y.expectedIntervalMs=P,p.timer=setTimeout(_,P)};if(A.action==="suspend"){y.suspendedMs+=A.suspendedDeltaMs,y.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:y.suspendedMs,...y.sessionId?{sessionId:y.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,...y.sessionId?{sessionId:y.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${y.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${y.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...y.sessionId?{sessionId:y.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${y.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(_,y.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(m){p.timer&&clearTimeout(p.timer),this.pending.delete(a),x(m)}})}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(mh(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}traceFrame(e,n){if(!SE)return;let i=n,o;try{let a=JSON.stringify(n);o=a===void 0||a.length<=Rh?n:`${a.slice(0,Rh)}...<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),Fo(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:IE(e.result)}),n.resolve(e.result));return}if(xh(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(hh(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(Dn(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(Dn(e.id,rs(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=ph(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=kh(this.framework,AE(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(mE).join(`
|
|
106
|
+
`),o=Ah(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 TE(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&(n.startsWith("CLAUDE")||n==="AI_AGENT"||n==="BAGGAGE"||(e[n]=i));return e}var zo=class extends Et{framework="claude-code";constructor(e){let{command:n,args:i}=gi("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 TE(e)}configIdFor(e){return e==="model"?"model":e==="effort"?"effort":null}};wn();import{spawn as PE}from"node:child_process";import{closeSync as RE,existsSync as Bd,mkdirSync as OE,mkdtempSync as DE,openSync as LE,readFileSync as zh,readSync as ME,readdirSync as NE,rmSync as FE,statSync as BE}from"node:fs";import{homedir as zE,tmpdir as UE}from"node:os";import{join as Zr}from"node:path";var Dh=["default","acceptEdits","plan","auto","bypassPermissions"],Lh=["read-only","auto","full-access"];var Mh=["default","accept_edits","dont_ask"];function jt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return Dh.includes(e);case"codex":return Lh.includes(e);case"hermes":return Mh.includes(e);case"openclaw":return!1}}function Uo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Nh(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function Nd(t){switch(t){case"claude-code":return Dh.join("/");case"codex":return Lh.join("/");case"hermes":return Mh.join("/");case"openclaw":return""}}Ce();var zd=9e4,HE=64*1024,GE=100;function qE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?zd:Math.max(1,Math.floor(e*1e3))}function jE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?zd:Math.max(1,Math.floor(e))}function WE(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 Fh(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:zd};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=WE(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?qE(e.timeout):jE(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function Fd(t){if(Array.isArray(t))return t.flatMap(i=>Fd(i));if(!t||typeof t!="object"){let i=Fh(t);return i?[i]:[]}let e=t;if(e.hooks)return Fd(e.hooks);let n=Fh(e);return n?[n]:[]}function KE(t){let e=Zr(t,"hooks.json");if(!Bd(e))return[];let n=JSON.parse(zh(e,"utf8")),o=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return Fd(o.Stop??o.stop)}function $E(t,e){let n=Zr(t,"sessions");if(!Bd(n))return;let i=[],o=a=>{let d;try{d=NE(a,{withFileTypes:!0})}catch{return}for(let u of d){let f=Zr(a,u.name);if(u.isDirectory())o(f);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:f,mtimeMs:BE(f).mtimeMs})}catch{}}};o(n),i.sort((a,d)=>d.mtimeMs-a.mtimeMs);for(let a of i.slice(0,GE))if(VE(a.path,e))return a.path}function VE(t,e){let n;try{n=LE(t,"r");let i=Buffer.alloc(HE),o=ME(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{RE(n)}catch{}}}function JE(t){return rr(t??Z().agentEnvFile)}function ZE(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 YE(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]=ZE(o.slice(a+1)))}return e}function XE(t){let e=Zr(t,"cozeloop.env");return Bd(e)?YE(zh(e,"utf8")):{}}function Bh(t){let e=t?.trim();return e||void 0}function QE(t){let e=JE(t.agentEnvFile),n=Bh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=Bh(t.env?.HOME??e.HOME??process.env.HOME)??zE();return Zr(i,".codex")}var Ho=class extends Et{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;fastMode;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:a}=gi("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??DE(Zr(UE(),"coze-bridge-codex-home-")):QE(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&OE(d,{recursive:!0});let f=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:o,args:a,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...f?{env:f}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=d,this.cleanupCodexHomeDir=u,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=jt("codex",e.modeId)?Uo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(ev(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=KE(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let o=$E(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?XE(a):{},u=Co(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=PE(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",p=setTimeout(()=>{f.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);f.stderr?.setEncoding("utf8"),f.stderr?.on("data",m=>{x+=m,x.length>4e3&&(x=x.slice(-4e3))}),f.on("error",m=>{clearTimeout(p),o(m)}),f.on("close",(m,y)=>{if(clearTimeout(p),m===0){i();return}o(new Error(`hook exited code=${m} signal=${y} stderr=${x.slice(-1e3)}`))}),f.stdin.end(`${n}
|
|
108
|
+
`)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{FE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function ev(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=Nh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}ne();var tv=G("hermes-downstream"),Go=class extends Et{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){tv.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)}};Ve();var Uh=3e4,Yr=class extends Et{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}`}]},Uh))}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}`}]},Uh)}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};At();Ve();ne();Ce();function Ud(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}wn();var Wt=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 qo=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 Wt,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)Xr(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 Xr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function cn(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Gt();ne();import{constants as Hh}from"node:fs";import{access as nv,readFile as rv}from"node:fs/promises";import{delimiter as iv,dirname as sv,join as Gh}from"node:path";var nt=G("framework-detector"),qh={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},ov=[".exe",".cmd",".bat",".ps1"],or=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??at,access:e.access??nv,readFile:e.readFile??rv}}async detect(e){let n=qh[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return nt.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(qh).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(iv).filter(Boolean),i=this.env.platform==="win32"?["",...ov]:[""];for(let o of n)for(let a of i){let d=Gh(o,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?Hh.F_OK:Hh.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 nt.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 nt.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=Gh(sv(o),"hermes-acp");return await this.isExecutable(a)?(nt.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(nt.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 nt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return nt.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 nt.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 nt.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?(nt.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}:(nt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return nt.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 nt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||nt.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){nt.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&&(cv(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let o="",a=!1,d,u=f=>{a||(a=!0,d&&clearTimeout(d),i(f))};try{let f=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{o+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},av=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function cv(t){return t.replace(av,"")}import{homedir as Wh}from"node:os";import{join as Wo}from"node:path";At();Gt();wr();Ve();ne();async function Kh(){let t=Wo(Wh(),".openclaw/openclaw.json");return Ze(t)}async function $h(){return(await Kh())?.gateway?.auth?.token??""}var ar=G("openclaw.config"),dv=[0,5e3,5e3],lv=$e("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),jh="models.providers.",jo="agents.defaults.models",uv=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function Qr(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 Ko=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Wt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??dv,this.cliTimeoutMs=e.cliTimeoutMs??lv,this.openclawDir=e.openclawDir??Wo(Wh(),".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,ar.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=at(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=x=>{d||(d=!0,clearTimeout(f),x())};o.stderr?.on("data",x=>{a+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${a.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let o=String(i);if(n.some(a=>o.includes(a)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",n],["Config path not found","Nothing was changed"])))}catch(i){ar.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 ${jo}[${e}]`,()=>this.runCli(["config","set",jo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${jo}[${e}]`,`${jo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await Kh())?.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=Wo(this.openclawDir,"identity","device.json"),i=(await Ze(e))?.deviceId?.trim();if(!i)return ar.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Wo(this.openclawDir,"devices","paired.json"),a=await Ze(o),d=a?.[i];if(!a||!d)return ar.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,f=Qr(Qr(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(E=>E.startsWith("operator.")),x=Qr([...uv],f),p=Qr(d.scopes,x),m=Qr(d.approvedScopes,x),y=u?Qr(u.scopes,x):void 0;return p.length!==(d.scopes?.length??0)||m.length!==(d.approvedScopes?.length??0)||u!==void 0&&y?.length!==(u.scopes?.length??0)?(d.scopes=p,d.approvedScopes=m,u&&y&&(u.scopes=y),await lt(o,a,{mode:384}),ar.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(ar.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return ar.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 fv,writeFile as hv}from"node:fs/promises";import{join as xv}from"node:path";var pv=["```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
|
`),gv=["# 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 mv(t){return t.length===0?t:`${(t.endsWith(`
|
|
111
111
|
`)?t.slice(0,-1):t).split(`
|
|
112
112
|
`).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
|
|
113
113
|
`)}
|
|
114
|
-
`}async function Vh(t){let e=xv(t,"HEARTBEAT.md"),n=await fv(e,"utf8");return mv(n)!==pv?!1:(await hv(e,gv),!0)}var re=
|
|
115
|
-
`);await Ev(d,f,{mode:384})}else await wv(a,d);re.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var qd="acceptEdits",Xh="full-access",Qh="read-only";function kv(t){return{INITIAL_AGENT_MODE:Uo(t)}}var Tv=(t,e,n,i,o,a,d,u,f,h,p,g)=>{switch(t){case"claude-code":{let y={...o?{...L0(o),...B0(o,d,u,g)}:{},...f??{},IS_SANDBOX:"1"};return new zo({cwd:n,env:y,agentId:i})}case"codex":{let y=Xh;h!==void 0&&(Kt("codex",h)?y=h:re.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:h}));let _=!!o?.modelToken,b={...o?{...N0(o),...M0(o,d,u,g)}:{},...kv(y),..._?{NO_BROWSER:"1"}:{},...f??{},..._?{COZELAB_ONBOARD_CLOUD:"true"}:{}};return new Ho({cwd:n,agentId:i,...Object.keys(b).length>0?{env:b}:{},...o?.fastMode?{fastMode:o.fastMode}:{},..._?{authMethodId:"api-key",isolateCodexHome:!0,...p?{codexHomeDir:p}:{}}:{}})}case"openclaw":return new Yr({command:e,cwd:n,agentId:i,...a?{sessionName:Ud(a)}:{}});case"hermes":return new Go({command:e,cwd:n,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{},...o?.model&&!Et(o.model)?{modelId:o.model}:{}})}};function Hd(t){return t==="claude-code"||t==="codex"}var Cv={path:"",version:"cloud-deployed"},Jh="openclaw_gateway_unavailable",Pv="openclaw_default_agent_missing";function Zh(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 Rv={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Dv=6e4,Vo=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??Tv,this.createTimeoutMs=e.createTimeoutMs??Dv,this.detectorFactory=e.detectorFactory??(()=>new or),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Ko({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??ln(Yh(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new T("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{re.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=ln(e,".env");if(await Gd(n).then(a=>a.isFile()).catch(()=>!1)){re.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=Ji({...process.env,...rr(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 T("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new T("IPC_BAD_REQUEST","framework required");let i=await me(e.agentId,this.paths).catch(()=>null),o=tr(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 T("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(C=>re.warn("dispose stale agent failed (ignored)",{err:String(C)})),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(C=>re.warn("dispose drifted agent failed (ignored)",{err:String(C)})),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 C=await me(e.agentId,this.paths).catch(()=>null);C&&(C.patToken=e.patToken,await Ce(C,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){re.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let C=await me(e.agentId,this.paths).catch(()=>null);C&&(C.modelInfo=e.modelInfo,await Ce(C,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 D=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${D}`)}let u=Re(e.agentId,this.paths),f=o?"cloud":"local",h=e.framework==="openclaw"&&f==="local",p;h&&!n?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let g=p??(h?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),y=e.workspace??g??u.workspace,_=new AbortController,b=setTimeout(()=>_.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,k=!1;try{o&&Hd(e.framework)&&await Er(e.framework,_.signal);let C=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await $o(u.root,{recursive:!0}),await $o(y,{recursive:!0}),await $o(u.logs,{recursive:!0}),C(),h||await vr(y,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await ic(y,"cloud"):await ic(y,"local",qd)),C();let D=i,E=O0({model:e.model??D?.model}),O=u0(e._meta)??D?.accountId,L=e.patToken??D?.patToken,z=f==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new qo({agentId:e.agentId,framework:e.framework,workspace:y,model:E.model??Lt,deployType:f,...O?{accountId:O}:{},...L?{patToken:L}:{},...z?{modelInfo:z}:{}}),I.status="ok",D?.sessions){let $=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,oe]of Object.entries(D.sessions)){let de={acpSessionId:oe.acpSessionId,modelToken:oe.modelToken,tokenGeneratedAt:oe.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};$?oe.permissionMode===void 0?(de.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:X,framework:e.framework,fallback:de.permissionMode})):Kt(e.framework,oe.permissionMode)?de.permissionMode=oe.permissionMode:re.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&re.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:f}),oe.cozeGroupId&&(de.cozeGroupId=oe.cozeGroupId),oe.tokenGroupId&&(de.tokenGroupId=oe.tokenGroupId),oe.requestScene&&(de.requestScene=oe.requestScene),I.sessions.set(X,de)}let ie=Object.keys(D.sessions).length;ie>0&&re.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ie})}this.registry.register(I),k=!0,n?.revive||this.registry.warmupModelList?.(I);let M={agentId:e.agentId,framework:e.framework,workspace:y,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:E.model};if(f==="cloud"&&(M.deployType="cloud"),O&&(M.accountId=O),L&&(M.patToken=L),z&&(M.modelInfo=z),D?.skills&&(M.skills=D.skills),D?.agentName&&(M.agentName=D.agentName),D?.description&&(M.description=D.description),M.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??jt,e.framework==="openclaw"&&f==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,y)):re.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await Vh(y)&&re.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:y})}catch($){re.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:y,err:String($)})}}let K=e.initialSkills??[];if(K.length>0){let $=[...M.skills??[]],ie=new Map($.map((de,ye)=>[de.skillId,ye])),X=await Promise.allSettled(K.map(de=>Lo({agentId:e.agentId,workspace:y,framework:e.framework,skill:de,paths:this.paths}))),oe=0;for(let[de,ye]of X.entries()){let ze=K[de];ze&&(ye.status==="fulfilled"?(Mo($,ie,ye.value),oe++):re.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:ze.skillId,skillName:ze.skillName,err:String(ye.reason)}))}oe>0&&(M.skills=$,re.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:K.length}))}return await Ce(M,this.paths),re.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:y,framework:e.framework}}catch(C){throw re.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),k&&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:u.root,revive:n?.revive===!0,framework:e.framework,errStack:C instanceof Error?C.stack:String(C)}),await bv(u.root,{recursive:!0,force:!0}).catch(D=>re.warn("rm agent dir failed (ignored)",{err:String(D)})),C instanceof T?C:new T("AGENT_SPAWN_FAILED",String(C),{cause:C})}finally{clearTimeout(b)}}async spawnSessionDownstream(e,n,i,o,a,d){let f=this.config.frameworksCache?.[e.framework];if(!f)if(e.deployType==="cloud"&&Hd(e.framework))f=Cv;else throw e.framework==="hermes"?new T("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Hd(e.framework)&&!Rs(e.framework)&&(re.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await Er(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:D0({model:e.model,effort:e.effort,fastMode:e.fastMode}),p;if(e.framework==="openclaw")p=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:i,cozeEnv:o,mockScenario:a,requestScene:d,command:f.path});else if(e.framework==="hermes"){let g={...this.buildBinShimPathEnv()};h?.modelToken&&(await q0({paths:this.paths,agentId:e.agentId,modelConfig:h,cozeEnv:o,mockScenario:a}),g.HERMES_HOME=sr(e.agentId,this.paths)),p=this.factory(e.framework,f.path,e.workspace,e.agentId,h,i,o,a,g)}else{let g=e.sessions.get(i),y=dn(e)?g?.permissionMode??Xh:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await Av(e.agentId,this.paths),p=this.factory(e.framework,f.path,e.workspace,e.agentId,h,i,o,a,this.buildBinShimPathEnv(),y,e.framework==="codex"&&e.deployType==="cloud"?ln(Re(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await p.start(),await p.initialize(Rv),p}catch(g){let y=p instanceof St?p.getStderrTail():[];throw y.length>0&&re.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof T?g.code:"unknown",recentStderr:y}),await p.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 T("AGENT_ENV_NOT_READY",Zh(o),{cause:{reason:Jh}})}catch(o){re.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof T?i:new T("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};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 T("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:Pv}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new T("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new T("AGENT_ENV_NOT_READY",Zh(n),{cause:{reason:Jh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,requestScene:u,command:f}=e,h=Ud(o);if(n.deployType==="local"){let y=await this.ensureOpenclawDefaultAgent(),_=i&&!Et(i.model)?i.model:void 0;return new Yr({command:f,cwd:y.workspace,agentId:y.id,sessionName:h,..._?{slashModelOnStart:_}:{}})}let p=await $h();try{let y=this.getOpenclawConfig();await y.ensureAcpDeviceScopes()&&await y.restartGateway()}catch(y){re.warn("acp device scope ensure failed (ignored)",{err:String(y)})}let g;if(i?.modelToken){let y=bd(o),_=Ed(i),b=`${y}/${_}`,I=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(b)!==I){let k=this.getOpenclawConfig(),C=await k.getAllowlistModelsForProvider(y),D=F0(i,a,d,C,u);D&&(await k.ensureProvider(y,D),await k.addModelToAllowlist(b),this.ensuredProviders.set(b,I))}g=b}else i&&!Et(i.model)&&(g=i.model);return new Yr({command:f,cwd:n.workspace,agentId:n.agentId,sessionName:h,...p?{gatewayToken:p}:{},...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=bd(a),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(h){f=!1,re.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(h)})}try{await i.removeModelFromAllowlist(u)}catch(h){f=!1,re.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(h)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as ix}from"node:crypto";import{promises as zv}from"node:fs";import{basename as sx}from"node:path";$e();ne();import{promises as Ov}from"node:fs";import{basename as Lv}from"node:path";var ex=H("file-upload"),Mv="/api/coze_claw/file/agent_upload",Nv=6e4;async function tx(t,e={}){let i=`${Ur(Hr(e.handshakeBase))}${Mv}`,o=e.timeoutMs??Nv,a=await Ov.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",...Dn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,h=setTimeout(()=>f.abort(),o);ex.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let p=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),g=p.headers.get("x-tt-logid")??"";if(!p.ok){let b=await p.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${g}: ${b.slice(0,200)}`)}let y=await p.json();if(y.code!==void 0&&y.code!==0)throw new T("UPLOAD_FAILED",`upload code=${y.code} msg=${y.msg??"-"} logid=${g}`);let _=y.data?.file?.file_url;if(!_)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${g}: ${JSON.stringify(y).slice(0,200)}`);return ex.info("file upload ok",{uri:_,logid:g}),{uri:_}}catch(p){throw p instanceof T?p:p.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Lv(t.path)}`):new T("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(h)}}$e();ne();import{extname as Bv}from"node:path";var Fv={".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 nx(t){let e=Bv(t).toLowerCase();return Fv[e]??"application/octet-stream"}Te();var Jo=H("agent-send"),rx=50*1024*1024;function ox(t,e,n){let i=t.get(e);if(!i)throw new T("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new T("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(n);if(!o)throw new T("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function ax(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(h){u=h,f<2&&(Jo.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(h)}),await new Promise(p=>setTimeout(p,5e3)))}throw new T("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function cx(t,e){let{session:n,runtime:i}=ox(e.core,t.agentId,t.sessionId);if(!await mi(t.path,n.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await zv.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new T("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>rx)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${rx}`);let a=await nx(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new T("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??sx(t.path),u;try{u=await tx({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(h){throw Jo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:a,code:h instanceof T?h.code:"UNKNOWN",message:h instanceof Error?h.message:String(h)}),h}let f={sessionUpdate:"agent_file",messageId:ix(),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 ax(e,n,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Jo.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 dx(t,e){let{session:n,runtime:i}=ox(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new T("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??sx(t.path),a={sessionUpdate:"group_file",messageId:ix(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ax(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),Jo.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 lx(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}Wt();ne();_n();var Vt=H("coze-cli-installer"),ux="@coze/cli@latest",Uv="coze",fx="0.1.8",Hv=5e3,Gv=5e3,qv=9e4,hx=1e4,os=null,Zo=!1;async function jd(t,e={}){if(Zo)return;if(os)return os;let n=e.exec??ko;return os=(async()=>{try{let i=await Wv(Uv,n),o=!1;if(i){let d=await jv(n);if(d===void 0)Vt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(lx(d,fx))Vt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:fx}),o=!0;else{Vt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Zo=!0;return}}let a=o?"upgrade-only":"full";Vt.info("coze-cli install start",{package:ux,mode:a});try{await n("npm",["i","-g","--prefer-online",ux],{timeout:qv,maxBuffer:10*1024*1024}),Vt.info("coze-cli install ok")}catch(d){Vt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Zo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:hx}),Vt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Vt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:hx}),Vt.info("coze auth login ok")}catch(d){Vt.warn("coze auth login failed",{err:String(d)});return}Zo=!0}finally{os=null}})(),os}async function Wv(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:Hv});return nc(i)}catch{return}}async function jv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:Gv});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Tt();var Yo=class{cacheFilePath;memory=new Map;runtimeCurrent=new Map;writeQueue=new $t;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=J0(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 Ye(this.cacheFilePath)??{};u[e]=o,await ft(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 Ye(this.cacheFilePath)??{};return d[e]=a,await ft(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)}};en();Tt();Te();var Kv=10*6e4;function xx(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Kv:e}function Xo(t){return Ye(t??J().configFile)}function as(t,e){return ft(e??J().configFile,t)}import{randomBytes as fS}from"node:crypto";wr();$e();ne();import{createReadStream as $v}from"node:fs";import{mkdir as Vv,readFile as Jv,realpath as Zv,stat as Yv,writeFile as Xv}from"node:fs/promises";import{basename as Qv,dirname as Kd,isAbsolute as eS,join as tS,relative as nS,resolve as px,sep as rS}from"node:path";import{createInterface as iS}from"node:readline";var mx=H("fs-rpc"),cs=Ke("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function _x(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>cs)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${cs} bytes`);let i=await bx(t.path,e);return await Vv(Kd(i),{recursive:!0}),await Xv(i,t.content,"utf8"),mx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function yx(t,e){let n=await bx(t.path,e),i=await Yv(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>cs&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${cs} bytes`);let a;if(o&&i.size>cs)a=await sS(n,t.line??1,t.limit);else{let d=await Jv(n,"utf8");if(o){let u=d.split(`
|
|
116
|
-
`),f=Math.max(0,(t.line??1)-1),
|
|
114
|
+
`}async function Vh(t){let e=xv(t,"HEARTBEAT.md"),n=await fv(e,"utf8");return mv(n)!==pv?!1:(await hv(e,gv),!0)}var re=G("agent-manager"),Sv=["hooks.json","cozeloop.env"],Iv=["hooks"];async function Av(t,e){let n=dn(Oe(t,e).root,"codex-home"),i=dn(Yh(),".codex");if(n!==i){await $o(n,{recursive:!0});for(let o of Iv){let a=dn(i,o),d=dn(n,o);try{await Gd(d);continue}catch{}try{await _v(a,d,{recursive:!0,errorOnExist:!0,filter:u=>{let f=vv(u);return!f.endsWith(".log")&&!f.includes(".bak")}}),re.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}for(let o of Sv){let a=dn(i,o),d=dn(n,o);try{await Gd(d);continue}catch{}try{if(o==="cozeloop.env"){let f=(await yv(a,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
|
|
115
|
+
`);await Ev(d,f,{mode:384})}else await wv(a,d);re.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var qd="acceptEdits",Xh="full-access",Qh="read-only";function kv(t){return{INITIAL_AGENT_MODE:Uo(t)}}var Cv=(t,e,n,i,o,a,d,u,f,x,p,m)=>{switch(t){case"claude-code":{let y={...o?{...L0(o),...F0(o,d,u,m)}:{},...f??{},IS_SANDBOX:"1"};return new zo({cwd:n,env:y,agentId:i})}case"codex":{let y=Xh;x!==void 0&&(jt("codex",x)?y=x:re.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _=!!o?.modelToken,E={...o?{...N0(o),...M0(o,d,u,m)}:{},...kv(y),..._?{NO_BROWSER:"1"}:{},...f??{},..._?{COZELAB_ONBOARD_CLOUD:"true"}:{}};return new Ho({cwd:n,agentId:i,...Object.keys(E).length>0?{env:E}:{},...o?.fastMode?{fastMode:o.fastMode}:{},..._?{authMethodId:"api-key",isolateCodexHome:!0,...p?{codexHomeDir:p}:{}}:{}})}case"openclaw":return new Yr({command:e,cwd:n,agentId:i,...a?{sessionName:Ud(a)}:{}});case"hermes":return new Go({command:e,cwd:n,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{},...o?.model&&!yt(o.model)?{modelId:o.model}:{}})}};function Hd(t){return t==="claude-code"||t==="codex"}var Tv={path:"",version:"cloud-deployed"},Jh="openclaw_gateway_unavailable",Pv="openclaw_default_agent_missing";function Zh(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 Rv={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Ov=6e4,Vo=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??Cv,this.createTimeoutMs=e.createTimeoutMs??Ov,this.detectorFactory=e.detectorFactory??(()=>new or),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Ko({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??dn(Yh(),".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=dn(e,".env");if(await Gd(n).then(a=>a.isFile()).catch(()=>!1)){re.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=Ji({...process.env,...rr(this.paths.agentEnvFile)});await mt(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 me(e.agentId,this.paths).catch(()=>null),o=tr(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(C=>re.warn("dispose stale agent failed (ignored)",{err:String(C)})),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(C=>re.warn("dispose drifted agent failed (ignored)",{err:String(C)})),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 C=await me(e.agentId,this.paths).catch(()=>null);C&&(C.patToken=e.patToken,await Te(C,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){re.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let C=await me(e.agentId,this.paths).catch(()=>null);C&&(C.modelInfo=e.modelInfo,await Te(C,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 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=Oe(e.agentId,this.paths),f=o?"cloud":"local",x=e.framework==="openclaw"&&f==="local",p;x&&!n?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let m=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),y=e.workspace??m??u.workspace,_=new AbortController,E=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&Hd(e.framework)&&await Er(e.framework,_.signal);let C=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await $o(u.root,{recursive:!0}),await $o(y,{recursive:!0}),await $o(u.logs,{recursive:!0}),C(),x||await vr(y,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await ic(y,"cloud"):await ic(y,"local",qd)),C();let P=i,b=D0({model:e.model??P?.model}),R=u0(e._meta)??P?.accountId,D=e.patToken??P?.patToken,U=f==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new qo({agentId:e.agentId,framework:e.framework,workspace:y,model:b.model??Ot,deployType:f,...R?{accountId:R}:{},...D?{patToken:D}:{},...U?{modelInfo:U}:{}}),I.status="ok",P?.sessions){let J=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,oe]of Object.entries(P.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:X,framework:e.framework,fallback:le.permissionMode})):jt(e.framework,oe.permissionMode)?le.permissionMode=oe.permissionMode:re.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&re.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:f}),oe.cozeGroupId&&(le.cozeGroupId=oe.cozeGroupId),oe.tokenGroupId&&(le.tokenGroupId=oe.tokenGroupId),oe.requestScene&&(le.requestScene=oe.requestScene),I.sessions.set(X,le)}let ie=Object.keys(P.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 M={agentId:e.agentId,framework:e.framework,workspace:y,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:b.model};if(f==="cloud"&&(M.deployType="cloud"),R&&(M.accountId=R),D&&(M.patToken=D),U&&(M.modelInfo=U),P?.skills&&(M.skills=P.skills),P?.agentName&&(M.agentName=P.agentName),P?.description&&(M.description=P.description),M.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??qt,e.framework==="openclaw"&&f==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,y)):re.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await Vh(y)&&re.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:y})}catch(J){re.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:y,err:String(J)})}}let V=e.initialSkills??[];if(V.length>0){let J=[...M.skills??[]],ie=new Map(J.map((le,ye)=>[le.skillId,ye])),X=await Promise.allSettled(V.map(le=>Lo({agentId:e.agentId,workspace:y,framework:e.framework,skill:le,paths:this.paths}))),oe=0;for(let[le,ye]of X.entries()){let Ue=V[le];Ue&&(ye.status==="fulfilled"?(Mo(J,ie,ye.value),oe++):re.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:Ue.skillId,skillName:Ue.skillName,err:String(ye.reason)}))}oe>0&&(M.skills=J,re.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:V.length}))}return await Te(M,this.paths),re.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:y,framework:e.framework}}catch(C){throw re.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),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:u.root,revive:n?.revive===!0,framework:e.framework,errStack:C instanceof Error?C.stack:String(C)}),await bv(u.root,{recursive:!0,force:!0}).catch(P=>re.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"&&Hd(e.framework))f=Tv;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`);Hd(e.framework)&&!Rs(e.framework)&&(re.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await Er(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:O0({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:f.path});else if(e.framework==="hermes"){let m={...this.buildBinShimPathEnv()};x?.modelToken&&(await q0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:o,mockScenario:a}),m.HERMES_HOME=sr(e.agentId,this.paths)),p=this.factory(e.framework,f.path,e.workspace,e.agentId,x,i,o,a,m)}else{let m=e.sessions.get(i),y=cn(e)?m?.permissionMode??Xh:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await Av(e.agentId,this.paths),p=this.factory(e.framework,f.path,e.workspace,e.agentId,x,i,o,a,this.buildBinShimPathEnv(),y,e.framework==="codex"&&e.deployType==="cloud"?dn(Oe(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await p.start(),await p.initialize(Rv),p}catch(m){let y=p instanceof Et?p.getStderrTail():[];throw y.length>0&&re.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof k?m.code:"unknown",recentStderr:y}),await p.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,f.path,m)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let o=await this.detectorFactory().probeOpenclawGateway(n);if(!o.reachable)return new k("AGENT_ENV_NOT_READY",Zh(o),{cause:{reason:Jh}})}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:Pv}})}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",Zh(n),{cause:{reason:Jh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,requestScene:u,command:f}=e,x=Ud(o);if(n.deployType==="local"){let y=await this.ensureOpenclawDefaultAgent(),_=i&&!yt(i.model)?i.model:void 0;return new Yr({command:f,cwd:y.workspace,agentId:y.id,sessionName:x,..._?{slashModelOnStart:_}:{}})}let p=await $h();try{let y=this.getOpenclawConfig();await y.ensureAcpDeviceScopes()&&await y.restartGateway()}catch(y){re.warn("acp device scope ensure failed (ignored)",{err:String(y)})}let m;if(i?.modelToken){let y=bd(o),_=Ed(i),E=`${y}/${_}`,I=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(E)!==I){let A=this.getOpenclawConfig(),C=await A.getAllowlistModelsForProvider(y),P=B0(i,a,d,C,u);P&&(await A.ensureProvider(y,P),await A.addModelToAllowlist(E),this.ensuredProviders.set(E,I))}m=E}else i&&!yt(i.model)&&(m=i.model);return new Yr({command:f,cwd:n.workspace,agentId:n.agentId,sessionName:x,...p?{gatewayToken:p}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=n??e.model;for(let a of e.sessions.keys()){let d=bd(a),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(x){f=!1,re.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){f=!1,re.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as ix}from"node:crypto";import{promises as zv}from"node:fs";import{basename as sx}from"node:path";Ve();ne();import{promises as Dv}from"node:fs";import{basename as Lv}from"node:path";var ex=G("file-upload"),Mv="/api/coze_claw/file/agent_upload",Nv=6e4;async function tx(t,e={}){let i=`${Ur(Hr(e.handshakeBase))}${Mv}`,o=e.timeoutMs??Nv,a=await Dv.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",...Rn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);ex.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let p=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),m=p.headers.get("x-tt-logid")??"";if(!p.ok){let E=await p.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${m}: ${E.slice(0,200)}`)}let y=await p.json();if(y.code!==void 0&&y.code!==0)throw new k("UPLOAD_FAILED",`upload code=${y.code} msg=${y.msg??"-"} logid=${m}`);let _=y.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${m}: ${JSON.stringify(y).slice(0,200)}`);return ex.info("file upload ok",{uri:_,logid:m}),{uri:_}}catch(p){throw p instanceof k?p:p.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Lv(t.path)}`):new k("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}Ve();ne();import{extname as Fv}from"node:path";var Bv={".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 nx(t){let e=Fv(t).toLowerCase();return Bv[e]??"application/octet-stream"}Ce();var Jo=G("agent-send"),rx=50*1024*1024;function ox(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 ax(t,e,n,i,o,a){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,n,i,o);return}catch(x){u=x,f<2&&(Jo.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new k("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function cx(t,e){let{session:n,runtime:i}=ox(e.core,t.agentId,t.sessionId);if(!await mi(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await zv.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>rx)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${rx}`);let a=await nx(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??sx(t.path),u;try{u=await tx({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 Jo.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 f={sessionUpdate:"agent_file",messageId:ix(),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 ax(e,n,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Jo.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 dx(t,e){let{session:n,runtime:i}=ox(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??sx(t.path),a={sessionUpdate:"group_file",messageId:ix(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ax(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),Jo.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 lx(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}Gt();ne();wn();var Kt=G("coze-cli-installer"),ux="@coze/cli@latest",Uv="coze",fx="0.1.8",Hv=5e3,Gv=5e3,qv=9e4,hx=1e4,os=null,Zo=!1;async function Wd(t,e={}){if(Zo)return;if(os)return os;let n=e.exec??ko;return os=(async()=>{try{let i=await jv(Uv,n),o=!1;if(i){let d=await Wv(n);if(d===void 0)Kt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(lx(d,fx))Kt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:fx}),o=!0;else{Kt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Zo=!0;return}}let a=o?"upgrade-only":"full";Kt.info("coze-cli install start",{package:ux,mode:a});try{await n("npm",["i","-g","--prefer-online",ux],{timeout:qv,maxBuffer:10*1024*1024}),Kt.info("coze-cli install ok")}catch(d){Kt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Zo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:hx}),Kt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Kt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:hx}),Kt.info("coze auth login ok")}catch(d){Kt.warn("coze auth login failed",{err:String(d)});return}Zo=!0}finally{os=null}})(),os}async function jv(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:Hv});return nc(i)}catch{return}}async function Wv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:Gv});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}At();var Yo=class{cacheFilePath;memory=new Map;runtimeCurrent=new Map;writeQueue=new Wt;constructor(e){this.cacheFilePath=e}async loadFromDisk(){if(!this.cacheFilePath)return;let e=await Ze(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=J0(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 Ze(this.cacheFilePath)??{};u[e]=o,await lt(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 Ze(this.cacheFilePath)??{};return d[e]=a,await lt(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)}};Qt();At();Ce();var Kv=10*6e4;function xx(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Kv:e}function Xo(t){return Ze(t??Z().configFile)}function as(t,e){return lt(e??Z().configFile,t)}import{randomBytes as fS}from"node:crypto";wr();Ve();ne();import{createReadStream as $v}from"node:fs";import{mkdir as Vv,readFile as Jv,realpath as Zv,stat as Yv,writeFile as Xv}from"node:fs/promises";import{basename as Qv,dirname as Kd,isAbsolute as eS,join as tS,relative as nS,resolve as px,sep as rS}from"node:path";import{createInterface as iS}from"node:readline";var mx=G("fs-rpc"),cs=$e("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function _x(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>cs)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${cs} bytes`);let i=await bx(t.path,e);return await Vv(Kd(i),{recursive:!0}),await Xv(i,t.content,"utf8"),mx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function yx(t,e){let n=await bx(t.path,e),i=await Yv(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>cs&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${cs} bytes`);let a;if(o&&i.size>cs)a=await sS(n,t.line??1,t.limit);else{let d=await Jv(n,"utf8");if(o){let u=d.split(`
|
|
116
|
+
`),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;a=u.slice(f,x).join(`
|
|
117
117
|
`)}else a=d}return mx.info("fs/read_text_file ok",{path:n,size:a.length}),{content:a}}async function sS(t,e,n){let i=iS({input:$v(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 bx(t,e){if(typeof t!="string"||t.length===0)throw new T("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([gx(px(e)),gx(px(t))]),o=nS(n,i);if(oS(o,rS,eS(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function oS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function gx(t){let e=[],n=t;for(;n!==Kd(n);)try{let i=await Zv(n);return e.length?tS(i,...e.reverse()):i}catch{e.push(Qv(n)),n=Kd(n)}return t}ne();var Ex=H("prompt-multimodal"),vx=10*1024*1024,aS=15e3,cS=6;async function Sx(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 dS(d))}}let o=Array.from({length:Math.min(cS,t.length)},()=>i());return await Promise.all(o),e}function Ix(t){return t.some(e=>e.type==="image")}async function dS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Vi(e.uri))return t;try{let{buf:n,contentType:i}=await uS(e.uri),o=e.mimeType||lS(i)||"application/octet-stream";return Ex.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 Ex.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function lS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function uS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),aS);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>vx)throw new Error(`image too large: ${o.byteLength} bytes (max ${vx})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}en();$e();ne();var W=H("core"),hS=3e4,xS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,pS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",gS="\u5BA1\u6279\u5DF2\u8D85\u65F6",mS=3e4,wS="__model_warmup__",Qo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new $r;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=xx(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}),Xr(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(Ln(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 T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Bo(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&&xS.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,a=f0(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);a&&u!==a?(this.requestSceneBySession.set(d,a),W.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),W.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){n!==null?await this.sendError(n,Q.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let f=await u(e,this);n!==null&&await this.upstream.send(Kr(n,f));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Kr(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Kr(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(u){W.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Ln(n,rs(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new T("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new T("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new T("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new T("AGENT_NOT_FOUND",`agent not found: ${i}`);let 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 h=n._meta?.cozeTriggerMsgId,p=Io(n._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,f,a,pS,h,p)}}let d=Date.now(),u=!1;try{let f=await o.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return u=!0,f}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=x0(i);switch(n){case"session/new":{let a=_S();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 T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=dn(e)?h0(i._meta):void 0;if(u!==void 0&&!Kt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Nd(e.framework)}`);let f=Io(i._meta),h=this.requestSceneBySession.get(d),p=await this.ensureRuntime(e,d,f,h);if(u!==void 0&&p.permissionMode===void 0&&(p.permissionMode=u,await this.persistSessionMapping(e)),p.replySeq=0,await this.ensureDownstream(e,d,p),!p.downstream||!p.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&p.permissionMode!==void 0&&p.permissionMode!==u){let _=p.permissionMode;p.permissionMode=u,await this.persistSessionMapping(e);try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(b){throw p.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),b}}let g=i._meta?.cozeTriggerMsgId;if(g?e.activeTriggers.set(p.acpSessionId,g):e.activeTriggers.delete(p.acpSessionId),f?e.activeGroupIds.set(p.acpSessionId,f):e.activeGroupIds.delete(p.acpSessionId),f&&p.cozeGroupId!==f&&(p.cozeGroupId=f,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Ix(a.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let y=await Sx(a.prompt);try{let _=await p.downstream.sessionPrompt({...a,sessionId:p.acpSessionId,prompt:y});return p.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof T&&_.code==="AGENT_APPROVAL_TIMEOUT"){let b=p.pendingPermission;b&&(b.downstream.respondAgentRequest(b.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(b.upstreamId),p.pendingPermission=void 0);let I=p.acpSessionId,k=I?e.activeTriggers.get(I):void 0,C=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,gS,k,C)}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(b=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(b)})))}else p.downstream?.isAlive()&&this.armIdleTimer(e,d,p)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new T("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&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:f.size}),f.dispose(new T("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=o,d=a.sessionId,u=a.modeId,f=Io(i._meta);if(!d)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!dn(e))throw e.framework==="openclaw"?new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new T("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Kt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Nd(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let h=e.sessions.get(d)??await this.ensureRuntime(e,d);if(h.permissionMode===u)return{};let p=h.permissionMode;if(h.permissionMode=u,await this.persistSessionMapping(e),h.downstream?.isAlive()&&h.acpSessionId)try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(g){throw h.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),g}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new T("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let d of o){let u=d.runtime.downstream,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,h=e.deployType==="cloud"&&a.tokenGroupId!==i,p=a.requestScene!==o;if(h&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),h||p){Xr(a);let g=a.downstream;a.downstream=void 0,g&&await g.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=o,(f||h||p)&&await this.persistSessionMapping(e),a}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...o?{requestScene:o}:{}};return dn(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?U0:H0:u.permissionMode=e.framework==="claude-code"?qd:Qh),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(nt.GEN_MODEL_TOKEN,o,mS);if(!a?.modelToken)throw new T("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return a.modelToken}catch(a){throw a instanceof T&&a.code==="MODEL_TOKEN_GEN_FAILED"?a:new T("MODEL_TOKEN_GEN_FAILED",a instanceof Error?a.message:String(a),{cause:a})}}async ensureDownstream(e,n,i){if(Xr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new T("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<a)throw new T("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((a-(Date.now()-u))/1e3)}s`);let f;try{let h=this.requestSceneBySession.get(n);h&&W.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:h}),f=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,h)}catch(h){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),h}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{let h=await f.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,h)}catch(h){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(h)}),i.acpSessionId=void 0;let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,this.piggybackModelList(e,p),await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let h=await f.sessionNew({cwd:e.workspace});i.acpSessionId=h.sessionId,this.piggybackModelList(e,h),await this.persistSessionMapping(e)}}catch(h){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(h)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,h}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),dn(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(h){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(h)})}}armIdleTimer(e,n,i){if(Xr(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(a=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(a)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,o){let a={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(a.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(a.cozeGroupId=u)}await this.upstream.send(jr("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(jr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,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(ES(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"&&dn(e)){let p=d.currentModeId;Kt(e.framework,p)&&a.permissionMode!==p?(a.permissionMode=p,this.persistSessionMapping(e).catch(g=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(g)}))):typeof p=="string"&&!Kt(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 u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let h=e.activeGroupIds.get(i);h&&(u.cozeGroupId=h),this.upstream.send(jr("session/update",{...n,sessionId:o,_meta:u})).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=K0(e.framework,n);if(!o)return;(Et(e.model)||e.model===_d)&&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)?.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),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,"",wS,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 _x(a,o);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await yx(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,rs(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,h={cozeAgentId:e.agentId};f&&(h.cozeTriggerMsgId=f);let p=u?e.activeGroupIds.get(u):void 0;p&&(h.cozeGroupId=p);let g=u?this.reverseSessionId(e,u):void 0,y=g?e.sessions.get(g):void 0;y&&(y.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...a,...g?{sessionId:g}:{},_meta:h};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:g}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:g,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(b=>({optionId:b.optionId,kind:b.kind,name:b.name}))}),this.upstream.send(ts(o,"session/request_permission",_)).catch(b=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(b)}),n.respondAgentRequestError(i.id,{code:Q.INTERNAL_ERROR,message:`upstream send failed: ${String(b)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let o=n.value;this.clearPendingPermissionFor(o),e.error?(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"&&yS(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 No(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=hS){let o=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(ts(o,e,n)).catch(f=>{let h=this.pendingBridge.get(o);h&&(clearTimeout(h.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&&dn(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 wi(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(Ln(e,{code:n,message:i,data:{bridgeVersion:jt}}))}};function _S(){return fS(16).toString("hex")}function yS(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 bS=["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."],Ax="Warning: ";function ES(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(Ax)?i.text.slice(Ax.length):i.text;return bS.some(a=>o.startsWith(a))}Tt();ne();Te();import{randomBytes as vS}from"node:crypto";import{createServer as SS}from"node:http";var IS=1e6,kx=H("ipc"),ea=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??J()}async start(){this.token=vS(32).toString("hex");let e=SS((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(),kx.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}`){ds(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){ds(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await AS(e)}catch(u){ds(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);ds(n,200,u??{ok:!0})}catch(u){kx.error("IPC handler failed",{key:o,err:String(u)}),ds(n,500,{error:u instanceof Error?u.message:String(u)})}}};function ds(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function AS(t){let e=[],n=0;for await(let o of t){let a=o;if(n+=a.length,n>IS)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 K1=Qt(Ep(),1),$1=Qt(da(),1),V1=Qt(ni(),1),J1=Qt(rl(),1),Z1=Qt(ol(),1),Y1=Qt(fl(),1),Rp=Qt(ha(),1),X1=Qt(Pp(),1);var Dp=Rp.default;$e();ne();var{FWS:xI}=qp(),Oe=H("upstream.frontier"),jp="application/json",Kp="none",pI=15e3;function gI(t){class e extends Dp{constructor(i){super(i,A0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Oe.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(tu("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");Oe.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Oe.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...o)}}return e}var ws=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Oe.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:k0,...Dn(this.opts.ppeOverride)},n=gI(e),i=C0(this.opts.urlOverride),o={url:i,ws:n,fpID:I0,aID:Co,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:jp,force:!0},payloadEncoding:{encoding:Kp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new xI(o),d=!1,u=null,f,h,p=new Promise((_,b)=>{f=_,h=b}),g=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?h(_):f())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Oe.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&g();for(let b of this.connectHandlers)Promise.resolve(b({initial:_})).catch(I=>Oe.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=_=>{this.opened=!1,Oe.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},a.onerror=_=>{Oe.warn("frontier error",{code:_.code,msg:_.message}),g(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},a.onmessage=_=>this.handleMessage(_),this.fws=a;let y=this.opts.openTimeoutMs??pI;u=setTimeout(()=>{g(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${y}ms (handshake or upgrade slow)`))},y),await a.connect();try{await p}catch(_){try{a.close(1e3,"open failed")}catch(b){Oe.warn("fws close during start failure threw (ignored)",{err:String(b)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Oe.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Oe.warn("frontier send refused: upstream not started",{method:i}),new T("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Oe.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new T("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;$p(a)||Oe.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:Kp})}catch(u){throw Oe.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(u)}),new T("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=n(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Oe.debug("drop non-adapter frontier frame",{service:n});return}let i=_I(e);if(!i){Oe.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Oe.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Oe.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=o;$p(a)||Oe.info("frontier frame in",{logid:wI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:mI(i)}),Promise.resolve(this.handler(o)).catch(d=>Oe.warn("frontier frame handler threw",{err:String(d)}))}};function $p(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Vp=2e3;function mI(t){return t.length<=Vp?t:`${t.slice(0,Vp)}...<truncated, total ${t.length} chars>`}function wI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function _I(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}$e();ne();var gl=H("skill-publish"),yI="/api/marketplace/product/skill/publish_with_assets",bI=15e4;async function Jp(t,e={}){let i=`${Ur(Hr(e.handshakeBase))}${yI}`,o=e.timeoutMs??bI,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",...Dn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);gl.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let h=await fetch(i,{method:"POST",headers:d,body:a,signal:u.signal}),p=h.headers.get("x-tt-logid")??"";if(!h.ok){let _=await h.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${h.status} logid=${p}: ${_.slice(0,200)}`)}let g=await h.json();if(gl.info("skill publish response",{logid:p,httpStatus:h.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 T("UPLOAD_FAILED",`skill publish code=${g.code} msg=${g.msg??"-"} logid=${p}`);let y={};return g.data?.skill_id!==void 0&&g.data.skill_id!==""&&(y.skillId=String(g.data.skill_id)),g.data?.version&&(y.version=g.data.version),gl.info("skill publish ok",{logid:p,skillId:y.skillId??"",version:y.version??""}),y}catch(h){throw h instanceof T?h:h.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(h),{cause:h})}finally{clearTimeout(f)}}ne();var ml=H("upstream.switchable"),Ea=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;ml.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 ml.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>ml.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 wl=H("upstream"),ci=class{handler=null;async start(){wl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){wl.info("NoopUpstream stopped",{reason:e})}async send(e){wl.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};$e();ne();Tt();ne();Te();import{promises as EI}from"node:fs";var Zp=H("pat-token-store");async function va(t=J()){try{let n=(await EI.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Zp.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"&&Zp.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function _s(t,e=J()){if(!t)throw new Error("writePatToken: empty patToken");await _t(e.patTokenFile,t,{mode:384})}Te();Te();import{promises as Sa}from"node:fs";import{join as vI}from"node:path";function SI(t,e){return`#!/bin/sh
|
|
118
|
+
`)}async function bx(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([gx(px(e)),gx(px(t))]),o=nS(n,i);if(oS(o,rS,eS(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function oS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function gx(t){let e=[],n=t;for(;n!==Kd(n);)try{let i=await Zv(n);return e.length?tS(i,...e.reverse()):i}catch{e.push(Qv(n)),n=Kd(n)}return t}ne();var Ex=G("prompt-multimodal"),vx=10*1024*1024,aS=15e3,cS=6;async function Sx(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 dS(d))}}let o=Array.from({length:Math.min(cS,t.length)},()=>i());return await Promise.all(o),e}function Ix(t){return t.some(e=>e.type==="image")}async function dS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Vi(e.uri))return t;try{let{buf:n,contentType:i}=await uS(e.uri),o=e.mimeType||lS(i)||"application/octet-stream";return Ex.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 Ex.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function lS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function uS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),aS);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>vx)throw new Error(`image too large: ${o.byteLength} bytes (max ${vx})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}Qt();Ve();ne();var $=G("core"),hS=3e4,xS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,pS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",gS="\u5BA1\u6279\u5DF2\u8D85\u65F6",mS=3e4,wS="__model_warmup__",Qo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new $r;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=xx(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(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(n=>n.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of n)await this.agents.get(i)?.killAllRuntimes("reload");return n}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){$.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&$.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,i){let o=i.downstream;o&&(o.onUpdate(a=>{i.loadingSession||this.forwardUpdate(e,a)}),o.onAgentRequest(a=>{this.handleAgentRequest(e,o,a)}),o.onExit((a,d)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),Xr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[o,a]of this.pendingUpstream)a.downstream===e&&i.push(o);if(i.length!==0){$.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let o of i){let a=this.pendingUpstream.get(o);if(a){this.pendingUpstream.delete(o),this.upstream.send(Dn(o,{code:Q.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>$.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:Q.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){$.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code: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(Fo(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&&xS.test(i)?this.currentCozeEnv=i:i&&$.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,a=f0(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);a&&u!==a?(this.requestSceneBySession.set(d,a),$.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),$.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){n!==null?await this.sendError(n,Q.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let f=await u(e,this);n!==null&&await this.upstream.send(Kr(n,f));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Kr(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Kr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,Q.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(u){$.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Dn(n,rs(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 x=n._meta?.cozeTriggerMsgId,p=Io(n._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,f,a,pS,x,p)}}let d=Date.now(),u=!1;try{let f=await o.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return u=!0,f}finally{$.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=x0(i);switch(n){case"session/new":{let a=_S();return $.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=o;return $.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:a.sessionId}),{}}case"session/prompt":{let a=o,d=a.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=cn(e)?h0(i._meta):void 0;if(u!==void 0&&!jt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Nd(e.framework)}`);let f=Io(i._meta),x=this.requestSceneBySession.get(d),p=await this.ensureRuntime(e,d,f,x);if(u!==void 0&&p.permissionMode===void 0&&(p.permissionMode=u,await this.persistSessionMapping(e)),p.replySeq=0,await this.ensureDownstream(e,d,p),!p.downstream||!p.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&p.permissionMode!==void 0&&p.permissionMode!==u){let _=p.permissionMode;p.permissionMode=u,await this.persistSessionMapping(e);try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(E){throw p.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),E}}let m=i._meta?.cozeTriggerMsgId;if(m?e.activeTriggers.set(p.acpSessionId,m):e.activeTriggers.delete(p.acpSessionId),f?e.activeGroupIds.set(p.acpSessionId,f):e.activeGroupIds.delete(p.acpSessionId),f&&p.cozeGroupId!==f&&(p.cozeGroupId=f,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Ix(a.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let y=await Sx(a.prompt);try{let _=await p.downstream.sessionPrompt({...a,sessionId:p.acpSessionId,prompt:y});return p.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof k&&_.code==="AGENT_APPROVAL_TIMEOUT"){let E=p.pendingPermission;E&&(E.downstream.respondAgentRequest(E.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(E.upstreamId),p.pendingPermission=void 0);let I=p.acpSessionId,A=I?e.activeTriggers.get(I):void 0,C=I?e.activeGroupIds.get(I):void 0;return $.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,p,d,gS,A,C)}throw _}finally{if(e.activeTriggers.delete(p.acpSessionId),e.activeGroupIds.delete(p.acpSessionId),p.pendingPermission=void 0,p.reloadAfterTurn){p.reloadAfterTurn=!1;let _=p.downstream;_&&(p.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:p.acpSessionId}),_.stop("reload-after-turn").catch(E=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(E)})))}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 u=e.sessions.get(d);if(e.hasSessionQueue(d)){let f=e.getSessionQueue(d);f.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:f.size}),f.dispose(new 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=Io(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!cn(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(!jt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Nd(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let p=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(m){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),m}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new 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 $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};$.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let d of o){let u=d.runtime.downstream,f=d.runtime.acpSessionId;u?.isAlive()&&f&&a.push({downstream:u,acpSessionId:f,oldMode:d.oldMode,runtime:d.runtime})}for(let d of a)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let f of o)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n,i,o){let a=e.sessions.get(n);if(a){let f=a.cozeGroupId!==i,x=e.deployType==="cloud"&&a.tokenGroupId!==i,p=a.requestScene!==o;if(x&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),x||p){Xr(a);let m=a.downstream;a.downstream=void 0,m&&await m.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=o,(f||x||p)&&await this.persistSessionMapping(e),a}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...o?{requestScene:o}:{}};return cn(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?U0:H0:u.permissionMode=e.framework==="claude-code"?qd:Qh),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(et.GEN_MODEL_TOKEN,o,mS);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(Xr(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 x=this.requestSceneBySession.get(n);x&&$.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),f=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&($.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{let x=await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace});$.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId}),this.piggybackModelList(e,x)}catch(x){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,this.piggybackModelList(e,p),await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,this.piggybackModelList(e,x),await this.persistSessionMapping(e)}}catch(x){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),cn(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){$.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(Xr(i),this.isRuntimeBusy(e,i)){$.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}$.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(a=>$.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(a)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,o){let a={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(a.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(a.cozeGroupId=u)}await this.upstream.send(Wr("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(Wr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>$.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,o=this.reverseSessionId(e,i);if(!o){$.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(o);if(!a){$.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(ES(n)){$.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&cn(e)){let p=d.currentModeId;jt(e.framework,p)&&a.permissionMode!==p?(a.permissionMode=p,this.persistSessionMapping(e).catch(m=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(m)}))):typeof p=="string"&&!jt(e.framework,p)&&$.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 u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Wr("session/update",{...n,sessionId:o,_meta:u})).catch(p=>$.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}piggybackModelList(e,n){let i=this.modelListCache;if(i)try{let o=K0(e.framework,n);if(!o)return;(yt(e.model)||e.model===_d)&&o.currentModelId&&!o.defaultModelId&&(o.defaultModelId=o.currentModelId),o.models.length>0&&i.update(e.framework,o).catch(d=>$.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){$.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),$.info("openclaw model-list warm-up done",{framework:e,count:n.models.length})):$.warn("openclaw model-list warm-up: empty CLI result (ignored)",{framework:e})}catch(n){$.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,"",wS,this.currentCozeEnv,this.currentMockScenario,void 0);let o=await i.sessionNew({cwd:e.workspace});this.piggybackModelList(e,o),$.info("model-list warm-up done",{agentId:e.agentId,framework:n})}catch(o){$.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}$.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 _x(a,o);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await yx(a,o);n.respondAgentRequest(i.id,d)}}catch(o){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,rs(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let o=this.upstreamIds.next("session/request_permission"),a=i.params??{},u=a.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let p=u?e.activeGroupIds.get(u):void 0;p&&(x.cozeGroupId=p);let m=u?this.reverseSessionId(e,u):void 0,y=m?e.sessions.get(m):void 0;y&&(y.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...a,...m?{sessionId:m}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:m}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:m,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(ts(o,"session/request_permission",_)).catch(E=>{this.pendingUpstream.delete(o),$.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),n.respondAgentRequestError(i.id,{code:Q.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?($.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"&&yS(e.result,o),$.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new No(e.error)):i.value.resolve(e.result);return}$.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let o=e.get(n);if(o)return{value:o,key:n};if(typeof n=="number"){let a=String(n),d=e.get(a);if(d)return $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=hS){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(ts(o,e,n)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(f)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,o]of e.sessions){let a={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(a.acpSessionId=o.acpSessionId),o.permissionMode&&cn(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 wi(e.agentId,n,this.paths)}catch(n){$.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Dn(e,{code:n,message:i,data:{bridgeVersion:qt}}))}};function _S(){return fS(16).toString("hex")}function yS(t,e){if(!t||typeof t!="object"){$.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){$.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=n.outcome;if(!i||typeof i!="object"){$.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let a=i.outcome;(typeof a!="string"||a!=="selected"&&a!=="cancelled")&&$.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var bS=["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."],Ax="Warning: ";function ES(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(Ax)?i.text.slice(Ax.length):i.text;return bS.some(a=>o.startsWith(a))}At();ne();Ce();import{randomBytes as vS}from"node:crypto";import{createServer as SS}from"node:http";var IS=1e6,kx=G("ipc"),ea=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=vS(32).toString("hex");let e=SS((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(),kx.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 mt(this.paths.portFile,String(this.port)),await mt(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){ds(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){ds(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await AS(e)}catch(u){ds(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);ds(n,200,u??{ok:!0})}catch(u){kx.error("IPC handler failed",{key:o,err:String(u)}),ds(n,500,{error:u instanceof Error?u.message:String(u)})}}};function ds(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function AS(t){let e=[],n=0;for await(let o of t){let a=o;if(n+=a.length,n>IS)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 K1=Xt(Ep(),1),$1=Xt(da(),1),V1=Xt(ni(),1),J1=Xt(rl(),1),Z1=Xt(ol(),1),Y1=Xt(fl(),1),Rp=Xt(ha(),1),X1=Xt(Pp(),1);var Op=Rp.default;Ve();ne();var{FWS:xI}=qp(),Le=G("upstream.frontier"),Wp="application/json",Kp="none",pI=15e3;function gI(t){class e extends Op{constructor(i){super(i,A0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Le.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(tu("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");Le.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Le.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...o)}}return e}var ws=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Le.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:k0,...Rn(this.opts.ppeOverride)},n=gI(e),i=T0(this.opts.urlOverride),o={url:i,ws:n,fpID:I0,aID:To,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Wp,force:!0},payloadEncoding:{encoding:Kp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new xI(o),d=!1,u=null,f,x,p=new Promise((_,E)=>{f=_,x=E}),m=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?x(_):f())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Le.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&m();for(let E of this.connectHandlers)Promise.resolve(E({initial:_})).catch(I=>Le.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=_=>{this.opened=!1,Le.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},a.onerror=_=>{Le.warn("frontier error",{code:_.code,msg:_.message}),m(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},a.onmessage=_=>this.handleMessage(_),this.fws=a;let y=this.opts.openTimeoutMs??pI;u=setTimeout(()=>{m(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${y}ms (handshake or upgrade slow)`))},y),await a.connect();try{await p}catch(_){try{a.close(1e3,"open failed")}catch(E){Le.warn("fws close during start failure threw (ignored)",{err:String(E)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Le.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Le.warn("frontier send refused: upstream not started",{method:i}),new k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Le.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState: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;$p(a)||Le.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:Wp,payloadEncoding:Kp})}catch(u){throw Le.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){Le.debug("drop non-adapter frontier frame",{service:n});return}let i=_I(e);if(!i){Le.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Le.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Le.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=o;$p(a)||Le.info("frontier frame in",{logid:wI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:mI(i)}),Promise.resolve(this.handler(o)).catch(d=>Le.warn("frontier frame handler threw",{err:String(d)}))}};function $p(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Vp=2e3;function mI(t){return t.length<=Vp?t:`${t.slice(0,Vp)}...<truncated, total ${t.length} chars>`}function wI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function _I(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}Ve();ne();var gl=G("skill-publish"),yI="/api/marketplace/product/skill/publish_with_assets",bI=15e4;async function Jp(t,e={}){let i=`${Ur(Hr(e.handshakeBase))}${yI}`,o=e.timeoutMs??bI,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",...Rn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);gl.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:a,signal:u.signal}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${_.slice(0,200)}`)}let m=await x.json();if(gl.info("skill publish response",{logid:p,httpStatus:x.status,code:m.code,msg:m.msg,dataSkillId:m.data?.skill_id??"",dataVersion:m.data?.version??""}),m.code!==void 0&&m.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${m.code} msg=${m.msg??"-"} logid=${p}`);let y={};return m.data?.skill_id!==void 0&&m.data.skill_id!==""&&(y.skillId=String(m.data.skill_id)),m.data?.version&&(y.version=m.data.version),gl.info("skill publish ok",{logid:p,skillId:y.skillId??"",version:y.version??""}),y}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(f)}}ne();var ml=G("upstream.switchable"),Ea=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;ml.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 ml.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>ml.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 wl=G("upstream"),ci=class{handler=null;async start(){wl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){wl.info("NoopUpstream stopped",{reason:e})}async send(e){wl.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Ve();ne();At();ne();Ce();import{promises as EI}from"node:fs";var Zp=G("pat-token-store");async function va(t=Z()){try{let n=(await EI.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Zp.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"&&Zp.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function _s(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await mt(e.patTokenFile,t,{mode:384})}Ce();Ce();import{promises as Sa}from"node:fs";import{join as vI}from"node:path";function SI(t,e){return`#!/bin/sh
|
|
119
119
|
exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
|
|
120
120
|
`}function II(t,e){return`@echo off\r
|
|
121
121
|
"${e}" "${t}" %*\r
|
|
122
|
-
`}async function Yp(t,e=
|
|
122
|
+
`}async function Yp(t,e=Z()){let n=e.binDir;await Sa.mkdir(n,{recursive:!0});let i=vI(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,a=process.platform==="win32"?II(t,o):SI(t,o);return await Sa.readFile(i,"utf8").catch(()=>null)===a||(await Sa.writeFile(i,a,"utf8"),process.platform!=="win32"&&await Sa.chmod(i,493)),n}ne();Ce();import{execSync as Xp}from"node:child_process";import{readFileSync as Qp,unlinkSync as AI}from"node:fs";import{mkdir as kI,open as CI,readFile as eg,unlink as _l,writeFile as TI}from"node:fs/promises";import{dirname as PI}from"node:path";var RI=G("single-instance"),OI=t=>new Promise(e=>setTimeout(e,t)),Ia=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=>is(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&&RI.warn("removing stale pid file",{stalePid:i}),await TI(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 eg(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await _l(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 eg(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 kI(PI(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await CI(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 OI(this.claimLockIntervalMs);continue}await _l(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await _l(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=Qp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Vr)||n.includes("lib/index.js"))}catch{}try{let n=Xp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Vr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Xp(`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{Qp(this.pidFile,"utf8").trim()===String(this.selfPid)&&AI(this.pidFile)}catch{}})}};Aa();ne();var hr=G("daemon.upstream-watchdog"),UI=12e4,HI=9e5,GI=3e4;function bl(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ka=class{constructor(e){this.opts=e;this.softMs=e.softMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",UI),this.hardMs=e.hardMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",HI),this.intervalMs=e.intervalMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",GI),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?.(),hr.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&&hr.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&&hr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,hr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){hr.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,hr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>hr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var q=G("daemon");async function rg(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Ql({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:T=>Oe(T,t).logs,listAgentIds:()=>Os(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 Ia({processTitle:Vr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Xo(),o=i??{};Ts({pid:process.pid}),G.info(i?"loaded bridge config":"initialized bridge config");let a=new Ea(new ci),d=new Yo(t.modelCacheFile);await d.loadFromDisk().catch(R=>G.warn("modelListCache.loadFromDisk failed (ignored)",{err:String(R)}));let u=null,f=async()=>{let R=o.frameworksCache?.openclaw?.path;return R?V0(R):null},h=new Qo({upstream:a,paths:t,bridgeConfig:o,modelListCache:d,openclawModelLister:f,sessionSpawner:async(R,U,q,ee,ae,it)=>{if(!u)throw new Error("agentManager not ready");return u.spawnSessionDownstream(R,U,q,ee,ae,it)}}),p=new Vo({paths:t,config:o,registry:h});u=p;let g,y,_=null,b={},I,k=null,C=null,D=null,E=new $t;function O(R,U){return E.enqueue(()=>z(R,U))}function L(){C||(C=new ka({isConnected:()=>a.isConnected()&&!(k?.isLivenessLost()??!1),forceReconnect:()=>D?O(D,{force:!0}):void 0,onFatal:R=>{if(process.env[ys]==="1"){G.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:R});return}G.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:R}),process.exit(1)}})),C.start()}async function z(R,U){let q=R,ee=q?.privatecode;if(!ee)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let ae=Yi(q.env),it=q.handshake_url,dt=q.frontier_url,Nt=ng(q.env,it,dt);if(D=q,!U?.force&&g===ee&&y===Nt){let Me=await qI(t);return h.agents.size===0&&Me?(G.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ca(t,p).catch(ge=>G.warn("connect-noop auto-revive error (ignored)",{err:String(ge)}))):G.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let Xt=!!g&&g!==ee,gn=y!==void 0&&y!==Nt,Fn=Xt||gn,mt=await md({privatecode:ee,...it?{endpoint:it}:{},ppeOverride:ae});if(Fn){G.warn("connect config switched, resetting agents",{pcChanged:Xt,envChanged:gn,previousPc:g?Ta(g):"",nextPc:Ta(ee)});for(let Me of[...h.agents.values()])await Me.dispose("connect config switch").catch(()=>{}),h.agents.delete(Me.agentId);h.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on connect config switch",{count:h.disconnectedAgents.size}),h.disconnectedAgents.clear()),await a.swap(new ci,"connect switch").catch(()=>{})}_=mt.deviceId,Ts({deviceId:_,pid:process.pid}),jd({patToken:ee,env:q.env}).catch(Me=>G.warn("coze-cli setup error (ignored)",{err:String(Me)}));let xr=new ws({handshake:mt,privatecode:ee,...dt?{urlOverride:dt}:{},ppeOverride:ae,getPatTokenForAgent:Me=>h.agents.get(Me)?.patToken});return await a.swap(xr,"connect"),g=ee,y=Nt,b=ae,I=it,q.mock_scenario!==void 0&&(h.setMockScenario(q.mock_scenario),G.info("mock scenario set",{scenario:q.mock_scenario})),k||(k=new es({core:h,getDeviceId:()=>_??"",onTickEnd:()=>$.retryPending().catch(Me=>G.warn("detailSync.retryPending failed (ignored)",{err:String(Me)})),onAuthFailures:ie})),k.start(),L(),Fn&&Ca(t,p).catch(Me=>G.warn("post-connect-switch auto-revive error (ignored)",{err:String(Me)})),_s(ee,t).catch(Me=>G.warn("writePatToken after /connect failed (ignored)",{err:String(Me)})),G.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}h.registerExtension("_agent/create",async R=>p.createAgent(R.params)),h.registerExtension("_agent/health",async()=>({ok:!0}));let M={},K=new Oo({agents:h.agents,modelListCache:d,openclawModelLister:f,paths:t,publishSkillToMarketplace:async R=>{let U=h.agents.get(R.agentId)?.patToken??g;if(!U)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Jp({patToken:U,zip:R.zip,...R.skillId?{skillId:R.skillId}:{},skillName:R.skillName,...R.description?{description:R.description}:{},agentId:R.agentId,...R.accountId?{accountId:R.accountId}:{}},{handshakeBase:I,ppeOverride:b})},disposeAndMarkDisconnected:async(R,U)=>{let q=h.agents.get(R);if(q){await p.cleanupOpenclawSessionProviders(q).catch(ae=>G.warn("cleanup openclaw providers failed (ignored)",{agentId:R,err:String(ae)})),q.framework==="hermes"&&q.deployType==="cloud"&&await Id(R,t).catch(ae=>G.warn("cleanup hermes-home failed (ignored)",{agentId:R,err:String(ae)}));let ee=!0;try{await q.dispose(`disconnect: ${U}`)}catch(ae){ee=!1,G.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:R,err:String(ae)}),q.status="error"}ee&&(q.status="disconnected",h.unregister(R),h.disconnectedAgents.add(R))}else h.disconnectedAgents.add(R)},disposeForDelete:async(R,U)=>{let q=h.agents.get(R);q&&(await p.cleanupOpenclawSessionProviders(q).catch(ee=>G.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:R,err:String(ee)})),q.framework==="hermes"&&q.deployType==="cloud"&&await Id(R,t).catch(ee=>G.warn("cleanup hermes-home during delete failed (ignored)",{agentId:R,err:String(ee)})),await q.dispose(`delete: ${U}`).catch(ee=>G.warn("dispose during delete failed (ignored)",{agentId:R,err:String(ee)})),h.unregister(R)),h.disconnectedAgents.delete(R)},detailSyncer:async R=>{if(!M.ref)throw new Error("agent-detail-sync not initialized yet");await M.ref.syncOne(R)},cleanupOpenclawProviders:async(R,U)=>{await p.cleanupOpenclawSessionProviders(R,U)},openclawRepair:async(R,U)=>{await p.openclawRepair(R,U)},hermesReset:async(R,U)=>{let q=await me(R).catch(()=>null);!q||q.framework!=="hermes"||q.deployType!=="cloud"||await G0({paths:t,agentId:R,model:q.model,modelInfo:q.modelInfo,cozeEnv:U,mockScenario:h.getMockScenario()})},isRuntimePendingPermission:R=>h.hasPendingPermissionFor(R)});h.registerExtension("_agent/listSkills",R=>K.listSkills(R.params)),h.registerExtension("_agent/addSkills",R=>K.addSkills(R.params)),h.registerExtension("_agent/removeSkills",R=>K.removeSkills(R.params)),h.registerExtension("_agent/publishSkill",R=>K.publishSkill(R.params)),h.registerExtension("_agent/getFileTree",R=>K.getFileTree(R.params)),h.registerExtension("_agent/getFileContent",R=>K.getFileContent(R.params)),h.registerExtension("_agent/update",R=>K.updateAgent(R.params)),h.registerExtension("_agent/disconnect",R=>K.disconnectAgent(R.params)),h.registerExtension("_agent/switchModel",R=>K.switchModel(R.params)),h.registerExtension("_agent/setConfigOption",R=>K.setConfigOption(R.params)),h.registerExtension("_agent/listAvailableModels",R=>K.listAvailableModels(R.params)),h.registerExtension("_agent/detail",R=>K.detail(R.params)),h.registerExtension("_agent/reset",R=>K.resetAgent(R.params)),h.registerExtension("_agent/repair",R=>K.repairAgent(R.params)),h.registerExtension("_agent/delete",R=>K.deleteAgent(R.params)),h.registerExtension("_agent/upgrade",R=>K.upgradeBridge(R.params));let $=new Ms({paths:t,handlers:K,agentManager:p,sendDetail:R=>h.sendRequest("_agent/detail",R)});M.ref=$;let ie=async R=>{await Promise.allSettled(R.map(async U=>{try{await K.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:R})=>{G.info("frontier upstream connected, triggering detail sync",{initial:R}),$.syncAll(R?"initial-connect":"reconnect").catch(U=>G.warn("detail sync top-level error (ignored)",{err:String(U)}))});let X=new ea({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let R=h.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[ys]==="1"?"manual":"supervisor",agents:[...h.agents.keys()],deviceId:_??"",frameworksCache:o.frameworksCache??{},...R?{mockScenario:R}:{}}}},{method:"POST",path:"/pair",handler:async R=>{let U=R,q=U?.privatecode,ee=U?.pairing_code;if(!q||!ee)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ae=Yi(U.env),it=U.handshake_url,dt=U.frontier_url,Nt=ng(U.env,it,dt),Xt=!!g&&g!==q,gn=y!==void 0&&y!==Nt,Fn=Xt||gn,mt=await md({privatecode:q,...it?{endpoint:it}:{},ppeOverride:ae});if(Fn){G.warn("pair config switched, resetting agents",{pcChanged:Xt,envChanged:gn,previousPc:g?Ta(g):"",nextPc:Ta(q),previousEnvKey:y??"",nextEnvKey:Nt});for(let ge of[...h.agents.values()])await ge.dispose("pair config switch").catch(()=>{}),h.agents.delete(ge.agentId);h.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on pair config switch",{count:h.disconnectedAgents.size}),h.disconnectedAgents.clear()),await a.swap(new ci,"pair switch").catch(()=>{})}_=mt.deviceId,Ts({deviceId:_,pid:process.pid}),jd({patToken:q,env:U.env}).catch(ge=>G.warn("coze-cli setup error (ignored)",{err:String(ge)}));let xr=new ws({handshake:mt,privatecode:q,...dt?{urlOverride:dt}:{},ppeOverride:ae,getPatTokenForAgent:ge=>h.agents.get(ge)?.patToken});await a.swap(xr,"pair");try{let ge=new or;o.frameworksCache=await ge.detectAll(),await as(o),G.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(ge){G.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(ge)})}let Me=Object.keys(o.frameworksCache??{});try{let ge=await h.sendRequest("_agent/pair",{pairCode:ee,patToken:q,frameworks:Me,_meta:{cozeDeviceId:_}});G.info("_agent/pair ok",{pairResult:ge}),g=q,y=Nt,b=ae,I=it,U.mock_scenario!==void 0&&(h.setMockScenario(U.mock_scenario),G.info("mock scenario set",{scenario:U.mock_scenario})),_s(q,t).catch(lt=>G.warn("writePatToken after /pair failed (ignored)",{err:String(lt)})),k||(k=new es({core:h,getDeviceId:()=>_??"",onTickEnd:()=>$.retryPending().catch(lt=>G.warn("detailSync.retryPending failed (ignored)",{err:String(lt)})),onAuthFailures:ie})),k.start(),L(),Fn&&Ca(t,p).catch(lt=>G.warn("post-pair-switch auto-revive error (ignored)",{err:String(lt)}));let ce;return U.agent_id&&(ce=await jI(U.agent_id,t,p,lt=>h.sendRequest("_agent/detail",lt),q).catch(lt=>(G.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(lt)}),{ok:!1,agentId:U.agent_id??"",note:String(lt)}))),{ok:!0,note:"paired with cloud",...ce?{agent:ce}:{}}}catch(ge){return G.error("_agent/pair failed",{err:String(ge)}),{ok:!1,note:`pair failed: ${String(ge)}`}}}},{method:"POST",path:"/connect",handler:R=>O(R)},{method:"POST",path:"/_agent/create",handler:async R=>{let U=R;return{ok:!0,result:await p.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async R=>{let U=R;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new T("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!g)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let q=U;return await(q.groupFile?dx:cx)(q,{core:h,patToken:g,handshakeBase:I,ppeOverride:b})}catch(q){if(q instanceof T)return{ok:!1,code:q.code,message:q.message};throw q}}},{method:"POST",path:"/reload",handler:async R=>{let U=R?.agent_id,q=await h.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(()=>{ze.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:oe,token:de}=await X.start();try{await Yp(t.libEntry,t)}catch(R){G.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(R)})}await h.start(),KI({paths:t,core:h,agentManager:p,detectAll:async()=>(o.frameworksCache=await new or().detectAll(),await as(o),o.frameworksCache)}).catch(R=>G.warn("startup warmup error (ignored)",{err:String(R)})),du().then(async()=>{let{probeAcpVersion:R}=await Promise.resolve().then(()=>(_n(),au));for(let U of["claude-code","codex"]){let q=await R(U);q&&G.info("acp wrapper version",{framework:U,version:q})}}).catch(R=>G.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(R)}));let ye=null,ze={port:oe,token:de,core:h,ipc:X,shutdown(R){return ye||(G.info("daemon shutdown",{reason:R}),ye=(async()=>{k?.stop(),C?.stop(),await h.stop(R),await X.stop(),await e.release()})(),ye)}};for(let R of["SIGTERM","SIGINT"])process.on(R,()=>{ze.shutdown(R).then(()=>process.exit(0))});return process.on("exit",()=>Eh()),process.on("unhandledRejection",R=>{G.error("unhandledRejection",{reason:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0})}),process.on("uncaughtException",R=>{G.error("uncaughtException (will exit, supervisor will restart)",{message:R.message,stack:R.stack,name:R.name});try{process.stderr.write(`FATAL uncaughtException: ${R.stack??R.message}
|
|
126
|
-
`)}catch{}process.exit(1)}),
|
|
127
|
-
`)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function tA(){let t=(process.env.SHELL??"").trim()||(ag().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return XI.has(e)?t:null}function nA(t){return new Promise(e=>{let n=`printf '%s' '${El}'; env; printf '%s' '${El}'`,i;try{i=YI(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??ag().homedir}})}catch{e(null);return}let o="",a=!1,d=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},u=p=>{a||(a=!0,clearTimeout(f),clearTimeout(
|
|
128
|
-
`;await Es(
|
|
125
|
+
`)}catch{}}let e=new Ia({processTitle:Vr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Xo(),o=i??{};Cs({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let a=new Ea(new ci),d=new Yo(t.modelCacheFile);await d.loadFromDisk().catch(T=>q.warn("modelListCache.loadFromDisk failed (ignored)",{err:String(T)}));let u=null,f=async()=>{let T=o.frameworksCache?.openclaw?.path;return T?V0(T):null},x=new Qo({upstream:a,paths:t,bridgeConfig:o,modelListCache:d,openclawModelLister:f,sessionSpawner:async(T,H,W,ee,ae,rt)=>{if(!u)throw new Error("agentManager not ready");return u.spawnSessionDownstream(T,H,W,ee,ae,rt)}}),p=new Vo({paths:t,config:o,registry:x});u=p;let m,y,_=null,E={},I,A=null,C=null,P=null,b=new Wt;function R(T,H){return b.enqueue(()=>U(T,H))}function D(){C||(C=new ka({isConnected:()=>a.isConnected()&&!(A?.isLivenessLost()??!1),forceReconnect:()=>P?R(P,{force:!0}):void 0,onFatal:T=>{if(process.env[ys]==="1"){q.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:T});return}q.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:T}),process.exit(1)}})),C.start()}async function U(T,H){let W=T,ee=W?.privatecode;if(!ee)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let ae=Yi(W.env),rt=W.handshake_url,ct=W.frontier_url,Lt=ng(W.env,rt,ct);if(P=W,!H?.force&&m===ee&&y===Lt){let Ne=await qI(t);return x.agents.size===0&&Ne?(q.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ta(t,p).catch(ge=>q.warn("connect-noop auto-revive error (ignored)",{err:String(ge)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let Zt=!!m&&m!==ee,pn=y!==void 0&&y!==Lt,Fn=Zt||pn,pt=await md({privatecode:ee,...rt?{endpoint:rt}:{},ppeOverride:ae});if(Fn){q.warn("connect config switched, resetting agents",{pcChanged:Zt,envChanged:pn,previousPc:m?Ca(m):"",nextPc:Ca(ee)});for(let Ne of[...x.agents.values()])await Ne.dispose("connect config switch").catch(()=>{}),x.agents.delete(Ne.agentId);x.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on connect config switch",{count:x.disconnectedAgents.size}),x.disconnectedAgents.clear()),await a.swap(new ci,"connect switch").catch(()=>{})}_=pt.deviceId,Cs({deviceId:_,pid:process.pid}),Wd({patToken:ee,env:W.env}).catch(Ne=>q.warn("coze-cli setup error (ignored)",{err:String(Ne)}));let xr=new ws({handshake:pt,privatecode:ee,...ct?{urlOverride:ct}:{},ppeOverride:ae,getPatTokenForAgent:Ne=>x.agents.get(Ne)?.patToken});return await a.swap(xr,"connect"),m=ee,y=Lt,E=ae,I=rt,W.mock_scenario!==void 0&&(x.setMockScenario(W.mock_scenario),q.info("mock scenario set",{scenario:W.mock_scenario})),A||(A=new es({core:x,getDeviceId:()=>_??"",onTickEnd:()=>J.retryPending().catch(Ne=>q.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:ie})),A.start(),D(),Fn&&Ta(t,p).catch(Ne=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(Ne)})),_s(ee,t).catch(Ne=>q.warn("writePatToken after /connect failed (ignored)",{err:String(Ne)})),q.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}x.registerExtension("_agent/create",async T=>p.createAgent(T.params)),x.registerExtension("_agent/health",async()=>({ok:!0}));let M={},V=new Do({agents:x.agents,modelListCache:d,openclawModelLister:f,paths:t,publishSkillToMarketplace:async T=>{let H=x.agents.get(T.agentId)?.patToken??m;if(!H)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Jp({patToken:H,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:I,ppeOverride:E})},disposeAndMarkDisconnected:async(T,H)=>{let W=x.agents.get(T);if(W){await p.cleanupOpenclawSessionProviders(W).catch(ae=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:T,err:String(ae)})),W.framework==="hermes"&&W.deployType==="cloud"&&await Id(T,t).catch(ae=>q.warn("cleanup hermes-home failed (ignored)",{agentId:T,err:String(ae)}));let ee=!0;try{await W.dispose(`disconnect: ${H}`)}catch(ae){ee=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:T,err:String(ae)}),W.status="error"}ee&&(W.status="disconnected",x.unregister(T),x.disconnectedAgents.add(T))}else x.disconnectedAgents.add(T)},disposeForDelete:async(T,H)=>{let W=x.agents.get(T);W&&(await p.cleanupOpenclawSessionProviders(W).catch(ee=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:T,err:String(ee)})),W.framework==="hermes"&&W.deployType==="cloud"&&await Id(T,t).catch(ee=>q.warn("cleanup hermes-home during delete failed (ignored)",{agentId:T,err:String(ee)})),await W.dispose(`delete: ${H}`).catch(ee=>q.warn("dispose during delete failed (ignored)",{agentId:T,err:String(ee)})),x.unregister(T)),x.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,H)=>{await p.cleanupOpenclawSessionProviders(T,H)},openclawRepair:async(T,H)=>{await p.openclawRepair(T,H)},hermesReset:async(T,H)=>{let W=await me(T).catch(()=>null);!W||W.framework!=="hermes"||W.deployType!=="cloud"||await G0({paths:t,agentId:T,model:W.model,modelInfo:W.modelInfo,cozeEnv:H,mockScenario:x.getMockScenario()})},isRuntimePendingPermission:T=>x.hasPendingPermissionFor(T)});x.registerExtension("_agent/listSkills",T=>V.listSkills(T.params)),x.registerExtension("_agent/addSkills",T=>V.addSkills(T.params)),x.registerExtension("_agent/removeSkills",T=>V.removeSkills(T.params)),x.registerExtension("_agent/publishSkill",T=>V.publishSkill(T.params)),x.registerExtension("_agent/getFileTree",T=>V.getFileTree(T.params)),x.registerExtension("_agent/getFileContent",T=>V.getFileContent(T.params)),x.registerExtension("_agent/update",T=>V.updateAgent(T.params)),x.registerExtension("_agent/disconnect",T=>V.disconnectAgent(T.params)),x.registerExtension("_agent/switchModel",T=>V.switchModel(T.params)),x.registerExtension("_agent/setConfigOption",T=>V.setConfigOption(T.params)),x.registerExtension("_agent/listAvailableModels",T=>V.listAvailableModels(T.params)),x.registerExtension("_agent/detail",T=>V.detail(T.params)),x.registerExtension("_agent/reset",T=>V.resetAgent(T.params)),x.registerExtension("_agent/repair",T=>V.repairAgent(T.params)),x.registerExtension("_agent/delete",T=>V.deleteAgent(T.params)),x.registerExtension("_agent/upgrade",T=>V.upgradeBridge(T.params));let J=new Ms({paths:t,handlers:V,agentManager:p,sendDetail:T=>x.sendRequest("_agent/detail",T)});M.ref=J;let ie=async T=>{await Promise.allSettled(T.map(async H=>{try{await V.disconnectAgent({agentId:H.agentId,reason:`auth_failure: code=${H.code} ${H.message}`}),q.info("agent disconnected due to auth failure from heartbeat response",{agentId:H.agentId,code:H.code,message:H.message})}catch(W){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:H.agentId,err:String(W)})}}))};a.onConnect(({initial:T})=>{q.info("frontier upstream connected, triggering detail sync",{initial:T}),J.syncAll(T?"initial-connect":"reconnect").catch(H=>q.warn("detail sync top-level error (ignored)",{err:String(H)}))});let X=new ea({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let T=x.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[ys]==="1"?"manual":"supervisor",agents:[...x.agents.keys()],deviceId:_??"",frameworksCache:o.frameworksCache??{},...T?{mockScenario:T}:{}}}},{method:"POST",path:"/pair",handler:async T=>{let H=T,W=H?.privatecode,ee=H?.pairing_code;if(!W||!ee)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ae=Yi(H.env),rt=H.handshake_url,ct=H.frontier_url,Lt=ng(H.env,rt,ct),Zt=!!m&&m!==W,pn=y!==void 0&&y!==Lt,Fn=Zt||pn,pt=await md({privatecode:W,...rt?{endpoint:rt}:{},ppeOverride:ae});if(Fn){q.warn("pair config switched, resetting agents",{pcChanged:Zt,envChanged:pn,previousPc:m?Ca(m):"",nextPc:Ca(W),previousEnvKey:y??"",nextEnvKey:Lt});for(let ge of[...x.agents.values()])await ge.dispose("pair config switch").catch(()=>{}),x.agents.delete(ge.agentId);x.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on pair config switch",{count:x.disconnectedAgents.size}),x.disconnectedAgents.clear()),await a.swap(new ci,"pair switch").catch(()=>{})}_=pt.deviceId,Cs({deviceId:_,pid:process.pid}),Wd({patToken:W,env:H.env}).catch(ge=>q.warn("coze-cli setup error (ignored)",{err:String(ge)}));let xr=new ws({handshake:pt,privatecode:W,...ct?{urlOverride:ct}:{},ppeOverride:ae,getPatTokenForAgent:ge=>x.agents.get(ge)?.patToken});await a.swap(xr,"pair");try{let ge=new or;o.frameworksCache=await ge.detectAll(),await as(o),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(ge){q.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(ge)})}let Ne=Object.keys(o.frameworksCache??{});try{let ge=await x.sendRequest("_agent/pair",{pairCode:ee,patToken:W,frameworks:Ne,_meta:{cozeDeviceId:_}});q.info("_agent/pair ok",{pairResult:ge}),m=W,y=Lt,E=ae,I=rt,H.mock_scenario!==void 0&&(x.setMockScenario(H.mock_scenario),q.info("mock scenario set",{scenario:H.mock_scenario})),_s(W,t).catch(dt=>q.warn("writePatToken after /pair failed (ignored)",{err:String(dt)})),A||(A=new es({core:x,getDeviceId:()=>_??"",onTickEnd:()=>J.retryPending().catch(dt=>q.warn("detailSync.retryPending failed (ignored)",{err:String(dt)})),onAuthFailures:ie})),A.start(),D(),Fn&&Ta(t,p).catch(dt=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(dt)}));let de;return H.agent_id&&(de=await WI(H.agent_id,t,p,dt=>x.sendRequest("_agent/detail",dt),W).catch(dt=>(q.error("--agent-id ensureAgent failed",{agentId:H.agent_id,err:String(dt)}),{ok:!1,agentId:H.agent_id??"",note:String(dt)}))),{ok:!0,note:"paired with cloud",...de?{agent:de}:{}}}catch(ge){return q.error("_agent/pair failed",{err:String(ge)}),{ok:!1,note:`pair failed: ${String(ge)}`}}}},{method:"POST",path:"/connect",handler:T=>R(T)},{method:"POST",path:"/_agent/create",handler:async T=>{let H=T;return{ok:!0,result:await p.createAgent(H)}}},{method:"POST",path:"/agent/send",handler:async T=>{let H=T;if(!H?.agentId||!H?.sessionId||!H?.kind||!H?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!m)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let W=H;return await(W.groupFile?dx:cx)(W,{core:x,patToken:m,handshakeBase:I,ppeOverride:E})}catch(W){if(W instanceof k)return{ok:!1,code:W.code,message:W.message};throw W}}},{method:"POST",path:"/reload",handler:async T=>{let H=T?.agent_id,W=await x.reloadAgents(H);return q.info("IPC /reload: recycled agent subprocesses",{agentId:H??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{Ue.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:oe,token:le}=await X.start();try{await Yp(t.libEntry,t)}catch(T){q.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(T)})}await x.start(),KI({paths:t,core:x,agentManager:p,detectAll:async()=>(o.frameworksCache=await new or().detectAll(),await as(o),o.frameworksCache)}).catch(T=>q.warn("startup warmup error (ignored)",{err:String(T)})),du().then(async()=>{let{probeAcpVersion:T}=await Promise.resolve().then(()=>(wn(),au));for(let H of["claude-code","codex"]){let W=await T(H);W&&q.info("acp wrapper version",{framework:H,version:W})}}).catch(T=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(T)}));let ye=null,Ue={port:oe,token:le,core:x,ipc:X,shutdown(T){return ye||(q.info("daemon shutdown",{reason:T}),ye=(async()=>{A?.stop(),C?.stop(),await x.stop(T),await X.stop(),await e.release()})(),ye)}};for(let T of["SIGTERM","SIGINT"])process.on(T,()=>{Ue.shutdown(T).then(()=>process.exit(0))});return process.on("exit",()=>Eh()),process.on("unhandledRejection",T=>{q.error("unhandledRejection",{reason:T instanceof Error?T.message:String(T),stack:T instanceof Error?T.stack:void 0})}),process.on("uncaughtException",T=>{q.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)}),q.info("daemon ready",{port:oe,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),VI({cliSpawned:process.env[ys]==="1",readPatToken:()=>va(t),connect:R}).catch(T=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(T)})),Ue}async function qI(t){return Os(t).length>0}function Ca(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function ng(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function jI(t,e){let n=Os(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(Qt(),Ls));for(let a of n){await o(a,t).catch(d=>q.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),q.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),q.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){q.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(d)})}}}async function WI(t,e,n,i,o){let{loadAgentConfig:a}=await Promise.resolve().then(()=>(Qt(),Ls)),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`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let p=ig(d),m={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...p?{_meta:p}:{}};return await n.createAgent(m),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}q.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new 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 x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function KI(t){let e=t.logger??q;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 jI(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await Ta(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await $I(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function Ta(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(()=>(Qt(),Ls));q.info("auto-revive: scanning local agents on startup",{count:i.length});let a=0,d=0;for(let u of i){let f;try{f=await o(u,t)}catch(x){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){q.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){q.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{q.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=ig(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...x?{_meta:x}:{}},{revive:!0}),a+=1}catch(x){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),d+=1}}return q.info("auto-revive: done",{revived:a,skipped:d,total:i.length}),{revived:a,skipped:d,total:i.length}}async function $I(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 lh(o,t)).status==="refreshed"&&(i+=1)}catch(a){q.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(a)})}return i>0&&q.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function VI(t){let e=t.logger??q;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 ig(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Aa();Ce();import{readFile as sg}from"node:fs/promises";var xn=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let n=await Pa(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:ZI(i)}}}async request(e){let n=await Pa(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:JI(f)}}finally{clearTimeout(d)}}};async function Pa(t){try{let[e,n]=await Promise.all([sg(t.portFile,"utf8"),sg(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 JI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function ZI(t){return t instanceof Error?t.message:String(t)}Gt();ne();wr();import{spawn as YI}from"node:child_process";import{userInfo as ag}from"node:os";var El="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",XI=new Set(["bash","zsh","sh","dash","ksh"]),og=$e("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),QI=2e3;function eA(t,e=El){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 tA(){let t=(process.env.SHELL??"").trim()||(ag().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return XI.has(e)?t:null}function nA(t){return new Promise(e=>{let n=`printf '%s' '${El}'; env; printf '%s' '${El}'`,i;try{i=YI(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??ag().homedir}})}catch{e(null);return}let o="",a=!1,d=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},u=p=>{a||(a=!0,clearTimeout(f),clearTimeout(x),e(p))};i.stdout?.on("data",p=>{o+=p.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>d("SIGTERM"),og),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},og+QI)})}async function vl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=tA();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??nA)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=eA(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Ce();function Nn(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}}wn();import{chmod as rA,copyFile as cg,mkdir as lg,readFile as Es,rename as dg,rm as Al,stat as ug,writeFile as iA}from"node:fs/promises";import{homedir as u3}from"node:os";import{dirname as sA,join as Me,resolve as kl,sep as bs}from"node:path";import{fileURLToPath as oA}from"node:url";Gt();ne();Ce();function di(t,e,n,i){st(t.bridgeLogsDir,e,"dist-install",n,i)}function fg(){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 aA(){return{darwin:{arm64:Me("vendor","aarch64-apple-darwin","bin","codex"),x64:Me("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Me("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Me("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Me("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Me("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function cA(t){let e=oA(t),n=sA(e),i=`${bs}src${bs}`;if(n.includes(i)||n.endsWith(`${bs}src${bs}cli`))return null;let o=kl(n,"index.js"),a=kl(n,"..","package.json");return{dist:o,pkgJson:a}}async function Cl(t={}){let e=t.paths??Z(),n=cA(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 Es(o,"utf8"));a=E.version??"unknown",d=E.dependencies??{}}catch(E){throw di(e,"error","cannot read source package.json",{err:String(E)}),new Error(`cannot read source package.json: ${String(E)}`,{cause:E})}let u=Ps.map(E=>({name:E,spec:d[E]??"latest"})),f=u.map(({name:E,spec:I})=>`${E}@${I}`),x=await Xo(e.configFile)??{},p=x.libVersion,m=await Es(e.libEntry).then(()=>!0).catch(()=>!1),y=p===a,_=await hg(e,u);if(y&&m&&_)return{kind:"already-current",libVersion:a};if(!y||!m){await lg(e.libDir,{recursive:!0}),await cg(i,e.libEntry),await cg(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=kl(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
|
|
128
|
+
`;await Es(E,"utf8").catch(()=>null)!==I&&await iA(E,I)}return _||(t.installWrappers?await t.installWrappers(e,f):await uA(e,f,u)),x.libVersion=a,await as(x,e.configFile),di(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:p,toVersion:a}),y&&m?{kind:"already-current",libVersion:a}:p?{kind:"version-changed",fromVersion:p,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function hg(t,e){for(let n of e){let i=Me(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await Es(i,"utf8"))}catch(d){return di(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 di(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!dA(a,n.spec))return di(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!!await xg(Me(t.libDir,"node_modules"))}function dA(t,e){let n=Sl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=Sl(i.slice(1));if(!a)return!0;if(Il(n,a)<0)return!1;let d=lA(a);return Il(n,d)<0}let o=Sl(i);return o?Il(n,o)===0:!0}function lA(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function Sl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Il(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 uA(t,e,n){await xA(t.installLock,async()=>{if(await hg(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${bs}.staging-${process.pid}-${i}`,a=Me(o,"node_modules"),d=Me(t.libDir,"node_modules");try{await lg(o,{recursive:!0}),await fA(e,o),await hA(a);let u=`${d}.trash-${i}`;await dg(d,u).catch(()=>{}),await dg(a,d),await Al(u,{recursive:!0,force:!0}).catch(()=>{}),di(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await Al(o,{recursive:!0,force:!0}).catch(()=>{})}})}function fA(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let a=at("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";a.stderr?.on("data",f=>{d.length<8192&&(d+=f.toString("utf8"))});let u=setTimeout(()=>a.kill("SIGKILL"),18e4);a.once("error",f=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(f)}`))}),a.once("close",f=>{clearTimeout(u),f===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${d.trim().slice(0,2e3)}`))})})}async function hA(t){for(let e of Ps){let n=Me(t,...e.split("/")),i=JSON.parse(await Es(Me(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=Me(t,".bin",o),d=await ug(a);process.platform!=="win32"&&!(d.mode&73)&&await rA(a,d.mode|73).catch(()=>{})}if(!await xg(t)){let e=fg()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function xg(t){let e=fg(),n=aA();if(!e||!n)return!0;let i=Me(t,"@openai","codex"),o=Me(t,...e.split("/")),a=[Me(i,"package.json"),Me(i,"bin","codex.js"),Me(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Me(o,"package.json"),Me(o,n)];return(await Promise.all(a.map(u=>ug(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function xA(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 Al(t,{force:!0}).catch(()=>{})}}Xa();ne();Ce();import{closeSync as gg,fstatSync as mg,openSync as wg,readFileSync as pA,readSync as gA,readdirSync as mA,statSync as wA}from"node:fs";import{join as Ra}from"node:path";var _A=new Set(["debug","info","warn","error"]);function _g(t){let e=t,n=Nn(e,"--agent-id");e=n.rest;let i=Nn(e,"--date");e=i.rest;let o=Nn(e,"-n","--lines");e=o.rest;let a=Nn(e,"--level");e=a.rest;let d=Nn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,x=a.value&&_A.has(a.value)?a.value:void 0,p={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(p.agentId=n.value),i.value&&(p.date=i.value),x&&(p.level=x),d.value&&(p.grep=d.value),p}function yA(t,e){return t.agentId?Ra(Oe(t.agentId,e).logs,_r("agent",t.date)):Ra(e.bridgeLogsDir,_r("bridge",t.date))}function bA(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function EA(t,e){let n;try{n=mA(t)}catch{return[]}let i=[];for(let o of n){let a=Ya(o,e);if(!a)continue;let d=0;try{d=wA(Ra(t,o)).size}catch{}i.push({file:Ra(t,o),date:a,size:d})}return i.sort((o,a)=>a.date.localeCompare(o.date)),i}function yg(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"&&!nu(n,e.level))return!1}return!0}var pg={debug:"90",info:"36",warn:"33",error:"31"},vA=new Set(["ts","level","module","msg"]);function SA(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function bg(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=SA(n.ts),o=typeof n.level=="string"?n.level:"",a=o.toUpperCase().padEnd(5);e.color&&pg[o]&&(a=`\x1B[${pg[o]}m${a}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",f=Object.entries(n).filter(([x])=>!vA.has(x)).map(([x,p])=>` ${x}=${typeof p=="string"?p:JSON.stringify(p)}`).join("");return`${i} ${a} ${d} ${u}${f}`}function IA(t,e,n){let a=pA(t,"utf8").split(`
|
|
129
129
|
`).filter(d=>d.length>0).filter(d=>yg(d,{level:e.level,grep:e.grep}));for(let d of bA(a,e.lines))process.stdout.write(`${bg(d,{raw:e.raw,color:n})}
|
|
130
|
-
`)}async function Eg(t,e){let n=e.paths??
|
|
131
|
-
`),1;for(let
|
|
130
|
+
`)}async function Eg(t,e){let n=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Oe(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=EA(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
|
|
131
|
+
`),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
|
|
132
132
|
`);return 0}let o=t.date??Un(new Date),a=yA({agentId:t.agentId,date:o},n);try{IA(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=f.pop()??"";for(let
|
|
137
|
-
`)}await new Promise(f=>setTimeout(f,AA))}}finally{process.off("SIGINT",d)}}import{basename as
|
|
135
|
+
`),1}return t.follow&&await CA(a,t,i),0}var AA=500;function kA(t){try{let e=wg(t,"r");try{return mg(e).size}finally{gg(e)}}catch{return 0}}async function CA(t,e,n){let i=kA(t),o="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let u="";try{let f=wg(t,"r");try{let x=mg(f).size;if(x>i){let p=Buffer.allocUnsafe(x-i),m=gA(f,p,0,p.length,i);u=p.subarray(0,m).toString("utf8"),i+=m}}finally{gg(f)}}catch{}if(u){let f=(o+u).split(`
|
|
136
|
+
`);o=f.pop()??"";for(let x of f)x.length>0&&yg(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${bg(x,{raw:e.raw,color:n})}
|
|
137
|
+
`)}await new Promise(f=>setTimeout(f,AA))}}finally{process.off("SIGINT",d)}}import{basename as TA,resolve as PA}from"node:path";Ce();var RA=9e4,OA={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 DA(t){return OA[t]??1}async function vg(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
139
|
`),3;let i=await Pa(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:PA(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 LA(i,"/agent/send",o,RA)}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
|
-
`),
|
|
143
|
-
`);else{let d=t.name??
|
|
142
|
+
`),DA(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
|
|
143
|
+
`);else{let d=t.name??TA(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} (${MA(a.bytes)})
|
|
145
|
-
`)}return 0}async function LA(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 MA(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var
|
|
146
|
-
`)}function sk(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 LA(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 MA(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Dg=G("cli");function Ke(t,e){let{value:n,rest:i}=Nn(t,e);return{value:n,rest:i}}function Fa(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
|
|
146
|
+
`)}function sk(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:P}=Ke(e.slice(1),"--agent-id");return P?{mode:"reload",agentId:P}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return ok(e.slice(1));if(e[0]==="log")return{mode:"log",..._g(e.slice(1))};if(e[0]==="connect")return ak(e.slice(1));if(e.includes("--status"))return Fa("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Fa("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Fa("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Fa("--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}=Ke(n,"--pat-token");n=o;let{value:a,rest:d}=Ke(n,"--pair-code");n=d;let{value:u,rest:f}=Ke(n,"--env");n=f;let{value:x,rest:p}=Ke(n,"--handshake-url");n=p;let{value:m,rest:y}=Ke(n,"--frontier-url");n=y;let{value:_,rest:E}=Ke(n,"--mock-scenario");n=E;let{value:I}=Ke(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),x&&(C.handshakeUrl=x),m&&(C.frontierUrl=m),_&&(C.mockScenario=_),I&&(C.agentId=I),A&&(C.skipRebuildEnv=!0),C}function ok(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}=Ke(i,"--caption");i=a;let{value:d,rest:u}=Ke(i,"--name");i=u;let{value:f,rest:x}=Ke(i,"--agent-id");i=x;let{value:p,rest:m}=Ke(i,"--session-id");i=m;let{value:y,rest:_}=Ke(i,"--mime");i=_;let E=i.includes("--group-file");i=i.filter(C=>C!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return o&&(A.caption=o),d&&(A.name=d),f&&(A.agentId=f),p&&(A.sessionId=p),E&&(A.groupFile=!0),y&&(A.mimeType=y),A}function ak(t){let e=t,{value:n,rest:i}=Ke(e,"--pat-token");e=i;let{value:o,rest:a}=Ke(e,"--env");e=a;let{value:d,rest:u}=Ke(e,"--handshake-url");e=u;let{value:f,rest:x}=Ke(e,"--frontier-url");e=x;let{value:p,rest:m}=Ke(e,"--mock-scenario");e=m;let y=e.includes("--skip-rebuild-env"),_={mode:"connect"};return n&&(_.privatecode=n),o&&(_.env=o),d&&(_.handshakeUrl=d),f&&(_.frontierUrl=f),p&&(_.mockScenario=p),y&&(_.skipRebuildEnv=!0),_}var ck=`
|
|
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,31 +224,31 @@ 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 Lg(t=process.argv,e={}){let n=sk(t);switch(n.mode){case"help":return process.stdout.write(ck),0;case"version":return process.stdout.write(`${
|
|
228
|
-
`),0;case"daemon":{try{await rg()}catch(i){return
|
|
227
|
+
`.trimStart();async function Lg(t=process.argv,e={}){let n=sk(t);switch(n.mode){case"help":return process.stdout.write(ck),0;case"version":return process.stdout.write(`${qt}
|
|
228
|
+
`),0;case"daemon":{try{await rg()}catch(i){return Dg.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return dk(e);case"stop":return Ng(e);case"reload":return fk(n.agentId,e);case"log":return Eg(n,e);case"update":return lk(e);case"purge":return xk(e);case"service-install":return pk(e);case"service-uninstall":return gk(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),mk(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),wk(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return vg({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 Mg(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 dk(t){let e=t.paths??Z(),n=new xn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
229
229
|
`),1;if(i.kind==="stale")return await Mg(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 Ng(t){let e=t.paths??
|
|
232
|
+
`),0}async function Ng(t){let e=t.paths??Z(),n=new xn(e),i=t.daemonSweep??(async()=>{let f=vh();return await Sh(f),f}),o=async()=>{t.skipProcessKill||await i(e)},a=await Ss(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
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
235
|
`),0;if(u.kind==="stale")return await Mg(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
237
|
`),0}catch(f){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
|
|
238
238
|
`),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
|
|
239
|
-
`),1)}}async function lk(t){return await Ng(t),(t.spawnNpx??uk)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function uk(t){return new Promise(e=>{let n=
|
|
240
|
-
`),e(1)})})}async function fk(t,e){let n=new
|
|
239
|
+
`),1)}}async function lk(t){return await Ng(t),(t.spawnNpx??uk)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function uk(t){return new Promise(e=>{let n=at("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
|
|
240
|
+
`),e(1)})})}async function fk(t,e){let n=new xn(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 Ss(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(()=>(Pg(),
|
|
245
|
+
`),1}}async function Ss(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(()=>(Pg(),Tg)),i=e(),o=n();return{platform:i.platform,install:a=>i.install(o,a),uninstall:()=>i.uninstall(o)}}async function Fg(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??_k,a=t.paths??Z();if(n.kind==="connected"){if(!hk(n.body))return n;st(a.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:n.body}),await e.request({method:"POST",path:"/shutdown"}).catch(f=>st(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await Og(a.pidFile,o)}let d=t.spawnDaemon??tg,u=await Ss(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await Rg(e,i,o);if(f.kind==="connected")return f;st(a.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(f){st(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}st(a.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await Og(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}),Rg(e,i,o)}function hk(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 xk(t){let e=new
|
|
247
|
+
`),await d({paths:t.paths}),Rg(e,i,o)}function hk(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 xk(t){let e=new xn(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
249
|
`)}await new Promise(d=>setTimeout(d,500))}let i=await Ss(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
|
-
`)}let o=t.paths??
|
|
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
254
|
`),0}async function pk(t){let e=await Ss(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
|
|
@@ -256,20 +256,20 @@ ${JSON.stringify(o.body,null,2)}
|
|
|
256
256
|
`),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
|
|
257
257
|
`),1}}async function gk(t){let e=await Ss(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
|
|
260
|
-
`),
|
|
261
|
-
`),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):
|
|
262
|
-
`)}let
|
|
263
|
-
`),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),o&&(p.agent_id=o);try{let
|
|
259
|
+
`),1}}async function Bg(t,e,n){if(e)return st(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(st(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(st(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
|
|
260
|
+
`),st(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function mk(t,e,n,i={},o,a){let d=new xn(n.paths),u=n.paths??Z(),f=await Bg(u,a,n.reconstructEnv??vl);if(await gd(u,f).catch(m=>st(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!n.skipDistInstall){let m=await Cl({paths:n.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
|
|
261
|
+
`),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
|
|
262
|
+
`)}let x=await Fg(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
|
|
263
|
+
`),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),o&&(p.agent_id=o);try{let m=await d.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});if(m.status===200&&m.body?.ok){let y=m.body.agent;return y&&!y.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${y.agentId}): ${y.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 wk(t,e,n={},i){let o=e.paths??
|
|
265
|
+
`),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(m.body)}
|
|
266
|
+
`),1}catch(m){return process.stderr.write(`coze-bridge: pair failed: ${String(m)}
|
|
267
|
+
`),1}}async function wk(t,e,n={},i){let o=e.paths??Z(),a=t??await va(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 xn(e.paths),u=await Bg(o,i,e.reconstructEnv??vl);if(await gd(o,u).catch(p=>st(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(p)})),!e.skipDistInstall){let p=await Cl({paths:e.paths});p.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${p.fromVersion} \u2192 ${p.toVersion}
|
|
268
268
|
`),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):p.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${p.libVersion}
|
|
269
|
-
`)}let f=await
|
|
270
|
-
`),1;let
|
|
271
|
-
`),t!==void 0&&await _s(a,o).catch(
|
|
269
|
+
`)}let f=await Fg(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
|
|
270
|
+
`),1;let x={privatecode:a};n.env&&(x.env=n.env),n.handshakeUrl&&(x.handshake_url=n.handshakeUrl),n.frontierUrl&&(x.frontier_url=n.frontierUrl),n.mockScenario&&(x.mock_scenario=n.mockScenario);try{let p=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return p.status===200&&p.body?.ok?(process.stdout.write(`coze-bridge: connected (${p.body.note??"ok"})
|
|
271
|
+
`),t!==void 0&&await _s(a,o).catch(m=>Dg.warn("writePatToken after connect failed (ignored)",{err:String(m)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(p.body)}
|
|
272
272
|
`),1)}catch(p){return process.stderr.write(`coze-bridge: connect failed: ${String(p)}
|
|
273
|
-
`),1}}async function Rg(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
|
|
273
|
+
`),1}}async function Rg(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 Og(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||!is(u))return;await e(i)}}function _k(t){return new Promise(e=>setTimeout(e,t))}ne();function yk(t){let e=/^v?(\d+)/.exec(t.trim());return e&&Number(e[1])<22?"fatal":"ok"}function zg(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){if(yk(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
274
|
`),n(1)}zg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&eu("warn");Lg(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)});
|